summaryrefslogtreecommitdiffstats
path: root/luni/src
diff options
context:
space:
mode:
Diffstat (limited to 'luni/src')
-rw-r--r--luni/src/main/files/cacerts/03f2b8cf.0120
-rw-r--r--luni/src/main/files/cacerts/1dbdda5b.074
-rw-r--r--luni/src/main/files/cacerts/1f58a078.0120
-rw-r--r--luni/src/main/files/cacerts/2e8714cb.0103
-rw-r--r--luni/src/main/files/cacerts/48478734.076
-rw-r--r--luni/src/main/files/cacerts/52b525c7.0120
-rw-r--r--luni/src/main/files/cacerts/5a5372fc.074
-rw-r--r--luni/src/main/files/cacerts/635ccfd5.074
-rw-r--r--luni/src/main/files/cacerts/6adf0799.080
-rw-r--r--luni/src/main/files/cacerts/8d6437c3.080
-rw-r--r--luni/src/main/files/cacerts/961f5451.0121
-rw-r--r--luni/src/main/files/cacerts/a2c66da8.0121
-rw-r--r--luni/src/main/files/cacerts/bcdd5959.052
-rw-r--r--luni/src/main/files/cacerts/c491639e.053
-rw-r--r--luni/src/main/files/cacerts/c8763593.0132
-rw-r--r--luni/src/main/files/cacerts/c90bc37d.080
-rw-r--r--luni/src/main/files/cacerts/d06393bb.080
-rw-r--r--luni/src/main/files/cacerts/d537fba6.096
-rw-r--r--luni/src/main/files/cacerts/e442e424.0120
-rw-r--r--luni/src/main/files/cacerts/ed39abd0.053
-rw-r--r--luni/src/main/files/cacerts/f4996e82.052
-rw-r--r--luni/src/main/java/android/system/ErrnoException.java82
-rw-r--r--luni/src/main/java/android/system/GaiException.java83
-rw-r--r--luni/src/main/java/android/system/Os.java539
-rw-r--r--luni/src/main/java/android/system/OsConstants.java (renamed from luni/src/main/java/libcore/io/OsConstants.java)92
-rw-r--r--luni/src/main/java/android/system/StructAddrinfo.java (renamed from luni/src/main/java/libcore/io/StructAddrinfo.java)41
-rw-r--r--luni/src/main/java/android/system/StructFlock.java (renamed from luni/src/main/java/libcore/io/StructFlock.java)30
-rw-r--r--luni/src/main/java/android/system/StructGroupReq.java (renamed from luni/src/main/java/libcore/io/StructGroupReq.java)23
-rw-r--r--luni/src/main/java/android/system/StructGroupSourceReq.java41
-rw-r--r--luni/src/main/java/android/system/StructLinger.java (renamed from luni/src/main/java/libcore/io/StructLinger.java)34
-rw-r--r--luni/src/main/java/android/system/StructPasswd.java48
-rw-r--r--luni/src/main/java/android/system/StructPollfd.java49
-rw-r--r--luni/src/main/java/android/system/StructStat.java98
-rw-r--r--luni/src/main/java/android/system/StructStatVfs.java (renamed from luni/src/main/java/libcore/io/StructStatVfs.java)15
-rw-r--r--luni/src/main/java/android/system/StructTimeval.java (renamed from luni/src/main/java/libcore/io/StructTimeval.java)54
-rw-r--r--luni/src/main/java/android/system/StructUcred.java (renamed from luni/src/main/java/libcore/io/StructUcred.java)10
-rw-r--r--luni/src/main/java/android/system/StructUtsname.java55
-rw-r--r--luni/src/main/java/android/util/MutableBoolean.java (renamed from luni/src/main/java/libcore/util/MutableBoolean.java)12
-rw-r--r--luni/src/main/java/android/util/MutableByte.java (renamed from luni/src/main/java/libcore/util/MutableByte.java)12
-rw-r--r--luni/src/main/java/android/util/MutableChar.java (renamed from luni/src/main/java/libcore/util/MutableChar.java)12
-rw-r--r--luni/src/main/java/android/util/MutableDouble.java (renamed from luni/src/main/java/libcore/util/MutableDouble.java)12
-rw-r--r--luni/src/main/java/android/util/MutableFloat.java (renamed from luni/src/main/java/libcore/util/MutableFloat.java)12
-rw-r--r--luni/src/main/java/android/util/MutableInt.java (renamed from luni/src/main/java/libcore/util/MutableInt.java)12
-rw-r--r--luni/src/main/java/android/util/MutableLong.java (renamed from luni/src/main/java/libcore/util/MutableLong.java)12
-rw-r--r--luni/src/main/java/android/util/MutableShort.java (renamed from luni/src/main/java/libcore/util/MutableShort.java)12
-rw-r--r--luni/src/main/java/java/io/BufferedInputStream.java11
-rw-r--r--luni/src/main/java/java/io/Console.java47
-rw-r--r--luni/src/main/java/java/io/File.java19
-rw-r--r--luni/src/main/java/java/io/FileDescriptor.java13
-rw-r--r--luni/src/main/java/java/io/FileInputStream.java12
-rw-r--r--luni/src/main/java/java/io/FileOutputStream.java9
-rw-r--r--luni/src/main/java/java/io/InputStream.java20
-rw-r--r--luni/src/main/java/java/io/InputStreamReader.java6
-rw-r--r--luni/src/main/java/java/io/ObjectInputStream.java4
-rw-r--r--luni/src/main/java/java/io/ObjectOutput.java2
-rw-r--r--luni/src/main/java/java/io/ObjectOutputStream.java48
-rw-r--r--luni/src/main/java/java/io/OutputStreamWriter.java4
-rw-r--r--luni/src/main/java/java/io/PipedInputStream.java5
-rw-r--r--luni/src/main/java/java/io/PipedOutputStream.java2
-rw-r--r--luni/src/main/java/java/io/PipedReader.java2
-rw-r--r--luni/src/main/java/java/io/PipedWriter.java5
-rw-r--r--luni/src/main/java/java/io/RandomAccessFile.java11
-rw-r--r--luni/src/main/java/java/lang/AbstractStringBuilder.java79
-rw-r--r--luni/src/main/java/java/lang/CaseMapper.java19
-rw-r--r--luni/src/main/java/java/lang/CharSequence.java11
-rw-r--r--luni/src/main/java/java/lang/Character.java38
-rw-r--r--luni/src/main/java/java/lang/Double.java8
-rw-r--r--luni/src/main/java/java/lang/Float.java8
-rw-r--r--luni/src/main/java/java/lang/Integer.java70
-rw-r--r--luni/src/main/java/java/lang/Long.java65
-rw-r--r--luni/src/main/java/java/lang/ProcessManager.java8
-rw-r--r--luni/src/main/java/java/lang/Runtime.java65
-rw-r--r--luni/src/main/java/java/lang/StringToReal.java37
-rw-r--r--luni/src/main/java/java/lang/System.java627
-rw-r--r--luni/src/main/java/java/lang/ref/FinalizerReference.java30
-rw-r--r--luni/src/main/java/java/lang/ref/Reference.java200
-rw-r--r--luni/src/main/java/java/lang/ref/ReferenceQueue.java36
-rw-r--r--luni/src/main/java/java/lang/reflect/Array.java12
-rw-r--r--luni/src/main/java/java/lang/reflect/Modifier.java2
-rw-r--r--luni/src/main/java/java/math/BigDecimal.java8
-rw-r--r--luni/src/main/java/java/math/Multiplication.java78
-rw-r--r--luni/src/main/java/java/net/AddressCache.java50
-rw-r--r--luni/src/main/java/java/net/DatagramSocket.java70
-rw-r--r--luni/src/main/java/java/net/DatagramSocketImpl.java36
-rw-r--r--luni/src/main/java/java/net/HttpCookie.java62
-rw-r--r--luni/src/main/java/java/net/HttpURLConnection.java12
-rw-r--r--luni/src/main/java/java/net/Inet4Address.java2
-rw-r--r--luni/src/main/java/java/net/Inet6Address.java2
-rw-r--r--luni/src/main/java/java/net/InetAddress.java77
-rw-r--r--luni/src/main/java/java/net/InetUnixAddress.java2
-rw-r--r--luni/src/main/java/java/net/JarURLConnection.java20
-rw-r--r--luni/src/main/java/java/net/MulticastSocket.java6
-rw-r--r--luni/src/main/java/java/net/NetworkInterface.java4
-rw-r--r--luni/src/main/java/java/net/PlainDatagramSocketImpl.java43
-rw-r--r--luni/src/main/java/java/net/PlainSocketImpl.java47
-rw-r--r--luni/src/main/java/java/net/ServerSocket.java43
-rw-r--r--luni/src/main/java/java/net/Socket.java74
-rw-r--r--luni/src/main/java/java/net/SocketImpl.java27
-rw-r--r--luni/src/main/java/java/net/SocketOptions.java81
-rw-r--r--luni/src/main/java/java/net/URI.java55
-rw-r--r--luni/src/main/java/java/net/URLConnection.java7
-rw-r--r--luni/src/main/java/java/net/URLStreamHandler.java8
-rw-r--r--luni/src/main/java/java/nio/Buffer.java23
-rw-r--r--luni/src/main/java/java/nio/ByteArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/ByteBuffer.java160
-rw-r--r--luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java3
-rw-r--r--luni/src/main/java/java/nio/ByteBufferAsDoubleBuffer.java3
-rw-r--r--luni/src/main/java/java/nio/ByteBufferAsFloatBuffer.java3
-rw-r--r--luni/src/main/java/java/nio/ByteBufferAsIntBuffer.java3
-rw-r--r--luni/src/main/java/java/nio/ByteBufferAsLongBuffer.java3
-rw-r--r--luni/src/main/java/java/nio/ByteBufferAsShortBuffer.java3
-rw-r--r--luni/src/main/java/java/nio/CharArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/CharBuffer.java85
-rw-r--r--luni/src/main/java/java/nio/CharSequenceAdapter.java2
-rw-r--r--luni/src/main/java/java/nio/DatagramChannelImpl.java248
-rw-r--r--luni/src/main/java/java/nio/DirectByteBuffer.java87
-rw-r--r--luni/src/main/java/java/nio/DoubleArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/DoubleBuffer.java44
-rw-r--r--luni/src/main/java/java/nio/FileChannelImpl.java29
-rw-r--r--luni/src/main/java/java/nio/FloatArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/FloatBuffer.java46
-rw-r--r--luni/src/main/java/java/nio/IntArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/IntBuffer.java44
-rw-r--r--luni/src/main/java/java/nio/IoVec.java2
-rw-r--r--luni/src/main/java/java/nio/LongArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/LongBuffer.java44
-rw-r--r--luni/src/main/java/java/nio/MappedByteBuffer.java12
-rw-r--r--luni/src/main/java/java/nio/MemoryBlock.java30
-rw-r--r--luni/src/main/java/java/nio/NIOAccess.java17
-rw-r--r--luni/src/main/java/java/nio/NioUtils.java8
-rw-r--r--luni/src/main/java/java/nio/PipeImpl.java4
-rw-r--r--luni/src/main/java/java/nio/SelectorImpl.java24
-rw-r--r--luni/src/main/java/java/nio/ServerSocketChannelImpl.java63
-rw-r--r--luni/src/main/java/java/nio/ShortArrayBuffer.java2
-rw-r--r--luni/src/main/java/java/nio/ShortBuffer.java44
-rw-r--r--luni/src/main/java/java/nio/SocketChannelImpl.java304
-rw-r--r--luni/src/main/java/java/nio/channels/DatagramChannel.java3
-rw-r--r--luni/src/main/java/java/nio/channels/FileChannel.java23
-rw-r--r--luni/src/main/java/java/nio/channels/FileLock.java2
-rw-r--r--luni/src/main/java/java/nio/channels/ServerSocketChannel.java3
-rw-r--r--luni/src/main/java/java/nio/channels/SocketChannel.java48
-rw-r--r--luni/src/main/java/java/nio/charset/CharsetDecoderICU.java18
-rw-r--r--luni/src/main/java/java/nio/charset/CharsetEncoderICU.java30
-rw-r--r--luni/src/main/java/java/security/AlgorithmParameterGenerator.java3
-rw-r--r--luni/src/main/java/java/security/AlgorithmParameters.java3
-rw-r--r--luni/src/main/java/java/security/GuardedObject.java2
-rw-r--r--luni/src/main/java/java/security/KeyFactory.java3
-rw-r--r--luni/src/main/java/java/security/KeyPairGenerator.java3
-rw-r--r--luni/src/main/java/java/security/KeyStore.java3
-rw-r--r--luni/src/main/java/java/security/MessageDigest.java27
-rw-r--r--luni/src/main/java/java/security/Provider.java246
-rw-r--r--luni/src/main/java/java/security/SecureRandom.java7
-rw-r--r--luni/src/main/java/java/security/Security.java46
-rw-r--r--luni/src/main/java/java/security/Signature.java217
-rw-r--r--luni/src/main/java/java/security/SignatureSpi.java5
-rw-r--r--luni/src/main/java/java/security/cert/CRLReason.java40
-rw-r--r--luni/src/main/java/java/security/cert/CertPathValidator.java3
-rw-r--r--luni/src/main/java/java/security/cert/CertStore.java4
-rw-r--r--luni/src/main/java/java/security/cert/Certificate.java10
-rw-r--r--luni/src/main/java/java/security/cert/CertificateFactory.java7
-rw-r--r--luni/src/main/java/java/security/cert/CertificateFactorySpi.java8
-rw-r--r--luni/src/main/java/java/security/cert/CertificateRevokedException.java155
-rw-r--r--luni/src/main/java/java/security/cert/Extension.java65
-rw-r--r--luni/src/main/java/java/security/cert/X509CRLEntry.java25
-rw-r--r--luni/src/main/java/java/security/interfaces/DSAParams.java4
-rw-r--r--luni/src/main/java/java/security/security.properties8
-rw-r--r--luni/src/main/java/java/security/spec/ECParameterSpec.java24
-rw-r--r--luni/src/main/java/java/sql/Date.java26
-rw-r--r--luni/src/main/java/java/sql/Timestamp.java70
-rw-r--r--luni/src/main/java/java/text/Bidi.java49
-rw-r--r--luni/src/main/java/java/text/BreakIterator.java35
-rw-r--r--luni/src/main/java/java/text/CollationElementIterator.java36
-rw-r--r--luni/src/main/java/java/text/DateFormat.java16
-rw-r--r--luni/src/main/java/java/text/DateFormatSymbols.java46
-rw-r--r--luni/src/main/java/java/text/DecimalFormat.java136
-rw-r--r--luni/src/main/java/java/text/DecimalFormatSymbols.java23
-rw-r--r--luni/src/main/java/java/text/FieldPosition.java244
-rw-r--r--luni/src/main/java/java/text/MessageFormat.java4
-rw-r--r--luni/src/main/java/java/text/NumberFormat.java45
-rw-r--r--luni/src/main/java/java/text/RuleBasedCollator.java304
-rw-r--r--luni/src/main/java/java/text/SimpleDateFormat.java106
-rw-r--r--luni/src/main/java/java/text/spi/BreakIteratorProvider.java90
-rw-r--r--luni/src/main/java/java/text/spi/CollatorProvider.java50
-rw-r--r--luni/src/main/java/java/text/spi/DateFormatProvider.java81
-rw-r--r--luni/src/main/java/java/text/spi/DateFormatSymbolsProvider.java50
-rw-r--r--luni/src/main/java/java/text/spi/DecimalFormatSymbolsProvider.java51
-rw-r--r--luni/src/main/java/java/text/spi/NumberFormatProvider.java93
-rw-r--r--luni/src/main/java/java/util/Arrays.java53
-rw-r--r--luni/src/main/java/java/util/Calendar.java16
-rw-r--r--luni/src/main/java/java/util/Collections.java2
-rw-r--r--luni/src/main/java/java/util/Currency.java14
-rw-r--r--luni/src/main/java/java/util/EnumMap.java4
-rw-r--r--luni/src/main/java/java/util/Formatter.java21
-rw-r--r--luni/src/main/java/java/util/GregorianCalendar.java60
-rw-r--r--luni/src/main/java/java/util/HashMap.java33
-rw-r--r--luni/src/main/java/java/util/IllformedLocaleException.java57
-rw-r--r--luni/src/main/java/java/util/LinkedHashMap.java5
-rw-r--r--luni/src/main/java/java/util/Locale.java1702
-rw-r--r--luni/src/main/java/java/util/Properties.java2
-rw-r--r--luni/src/main/java/java/util/Random.java17
-rw-r--r--luni/src/main/java/java/util/Scanner.java105
-rw-r--r--luni/src/main/java/java/util/TimeZone.java46
-rw-r--r--luni/src/main/java/java/util/Timer.java7
-rw-r--r--luni/src/main/java/java/util/TreeSet.java16
-rw-r--r--luni/src/main/java/java/util/UUID.java25
-rw-r--r--luni/src/main/java/java/util/concurrent/ConcurrentHashMap.java3892
-rw-r--r--luni/src/main/java/java/util/concurrent/ConcurrentLinkedDeque.java2
-rw-r--r--luni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java2
-rw-r--r--luni/src/main/java/java/util/concurrent/CountedCompleter.java113
-rw-r--r--luni/src/main/java/java/util/concurrent/ForkJoinPool.java1659
-rw-r--r--luni/src/main/java/java/util/concurrent/ForkJoinTask.java142
-rw-r--r--luni/src/main/java/java/util/concurrent/ForkJoinWorkerThread.java18
-rw-r--r--luni/src/main/java/java/util/concurrent/LinkedTransferQueue.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/Phaser.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/RecursiveAction.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/RecursiveTask.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/ScheduledThreadPoolExecutor.java2
-rw-r--r--luni/src/main/java/java/util/concurrent/ThreadLocalRandom.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/TransferQueue.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/atomic/Fences.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java1
-rw-r--r--luni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java1
-rw-r--r--luni/src/main/java/java/util/jar/Attributes.java9
-rw-r--r--luni/src/main/java/java/util/jar/JarEntry.java143
-rw-r--r--luni/src/main/java/java/util/jar/JarFile.java226
-rw-r--r--luni/src/main/java/java/util/jar/JarInputStream.java163
-rw-r--r--luni/src/main/java/java/util/jar/JarVerifier.java177
-rw-r--r--luni/src/main/java/java/util/jar/Manifest.java80
-rw-r--r--luni/src/main/java/java/util/jar/StrictJarFile.java232
-rw-r--r--luni/src/main/java/java/util/logging/SocketHandler.java7
-rw-r--r--luni/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java7
-rw-r--r--luni/src/main/java/java/util/prefs/FilePreferencesImpl.java25
-rw-r--r--luni/src/main/java/java/util/prefs/Preferences.java41
-rw-r--r--luni/src/main/java/java/util/regex/MatchResult.java58
-rw-r--r--luni/src/main/java/java/util/regex/MatchResultImpl.java2
-rw-r--r--luni/src/main/java/java/util/regex/Matcher.java199
-rw-r--r--luni/src/main/java/java/util/regex/Pattern.java2
-rw-r--r--luni/src/main/java/java/util/spi/CurrencyNameProvider.java49
-rw-r--r--luni/src/main/java/java/util/spi/LocaleNameProvider.java75
-rw-r--r--luni/src/main/java/java/util/spi/LocaleServiceProvider.java40
-rw-r--r--luni/src/main/java/java/util/spi/TimeZoneNameProvider.java51
-rw-r--r--luni/src/main/java/java/util/zip/Deflater.java8
-rw-r--r--luni/src/main/java/java/util/zip/DeflaterInputStream.java7
-rw-r--r--luni/src/main/java/java/util/zip/DeflaterOutputStream.java5
-rw-r--r--luni/src/main/java/java/util/zip/GZIPInputStream.java176
-rw-r--r--luni/src/main/java/java/util/zip/GZIPOutputStream.java7
-rw-r--r--luni/src/main/java/java/util/zip/Inflater.java9
-rw-r--r--luni/src/main/java/java/util/zip/InflaterInputStream.java7
-rw-r--r--luni/src/main/java/java/util/zip/ZipEntry.java72
-rw-r--r--luni/src/main/java/java/util/zip/ZipFile.java48
-rw-r--r--luni/src/main/java/java/util/zip/ZipInputStream.java41
-rw-r--r--luni/src/main/java/java/util/zip/ZipOutputStream.java61
-rw-r--r--luni/src/main/java/javax/crypto/Cipher.java358
-rw-r--r--luni/src/main/java/javax/crypto/CipherInputStream.java73
-rw-r--r--luni/src/main/java/javax/crypto/ExemptionMechanism.java1
-rw-r--r--luni/src/main/java/javax/crypto/KeyAgreement.java156
-rw-r--r--luni/src/main/java/javax/crypto/KeyGenerator.java3
-rw-r--r--luni/src/main/java/javax/crypto/Mac.java162
-rw-r--r--luni/src/main/java/javax/crypto/SealedObject.java72
-rw-r--r--luni/src/main/java/javax/crypto/SecretKeyFactory.java3
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLContext.java142
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLEngine.java623
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLEngineResult.java8
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLParameters.java1
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java9
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLSocket.java719
-rw-r--r--luni/src/main/java/javax/net/ssl/SSLSocketFactory.java47
-rw-r--r--luni/src/main/java/javax/security/cert/Certificate.java11
-rw-r--r--luni/src/main/java/javax/xml/transform/overview.html12
-rw-r--r--luni/src/main/java/libcore/icu/CollationElementIteratorICU.java9
-rw-r--r--luni/src/main/java/libcore/icu/DateIntervalFormat.java8
-rw-r--r--luni/src/main/java/libcore/icu/ICU.java277
-rw-r--r--luni/src/main/java/libcore/icu/LocaleData.java35
-rw-r--r--luni/src/main/java/libcore/icu/NativeBreakIterator.java18
-rw-r--r--luni/src/main/java/libcore/icu/NativeCollation.java9
-rw-r--r--luni/src/main/java/libcore/icu/NativeDecimalFormat.java195
-rw-r--r--luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java2
-rw-r--r--luni/src/main/java/libcore/icu/TimeZoneNames.java15
-rw-r--r--luni/src/main/java/libcore/io/BlockGuardOs.java140
-rw-r--r--luni/src/main/java/libcore/io/DeleteOnExit.java (renamed from luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java)18
-rw-r--r--luni/src/main/java/libcore/io/ErrnoException.java65
-rw-r--r--luni/src/main/java/libcore/io/ForwardingOs.java47
-rw-r--r--luni/src/main/java/libcore/io/GaiException.java66
-rw-r--r--luni/src/main/java/libcore/io/IoBridge.java105
-rw-r--r--luni/src/main/java/libcore/io/IoUtils.java4
-rw-r--r--luni/src/main/java/libcore/io/Memory.java57
-rw-r--r--luni/src/main/java/libcore/io/MemoryMappedFile.java6
-rw-r--r--luni/src/main/java/libcore/io/Os.java47
-rw-r--r--luni/src/main/java/libcore/io/Posix.java55
-rw-r--r--luni/src/main/java/libcore/io/Streams.java5
-rw-r--r--luni/src/main/java/libcore/io/StructPasswd.java38
-rw-r--r--luni/src/main/java/libcore/io/StructPollfd.java48
-rw-r--r--luni/src/main/java/libcore/io/StructStat.java90
-rw-r--r--luni/src/main/java/libcore/io/StructUtsname.java47
-rw-r--r--luni/src/main/java/libcore/net/MimeUtils.java48
-rw-r--r--luni/src/main/java/libcore/net/RawSocket.java142
-rw-r--r--luni/src/main/java/libcore/net/event/NetworkEventDispatcher.java79
-rw-r--r--luni/src/main/java/libcore/net/event/NetworkEventListener.java27
-rw-r--r--luni/src/main/java/libcore/net/url/FileURLConnection.java165
-rw-r--r--luni/src/main/java/libcore/net/url/JarURLConnectionImpl.java10
-rw-r--r--luni/src/main/java/libcore/reflect/AnnotationAccess.java83
-rw-r--r--luni/src/main/java/libcore/reflect/GenericArrayTypeImpl.java15
-rw-r--r--luni/src/main/java/libcore/reflect/ParameterizedTypeImpl.java29
-rw-r--r--luni/src/main/java/libcore/util/EmptyArray.java2
-rw-r--r--luni/src/main/java/libcore/util/ZoneInfo.java693
-rw-r--r--luni/src/main/java/libcore/util/ZoneInfoDB.java71
-rw-r--r--luni/src/main/java/org/apache/harmony/security/fortress/Engine.java71
-rw-r--r--luni/src/main/java/org/apache/harmony/security/fortress/Services.java48
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java324
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java44
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java179
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java504
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java858
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java430
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java451
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java49
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java217
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java159
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java171
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java306
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java423
-rw-r--r--luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.java73
-rw-r--r--luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java105
-rw-r--r--luni/src/main/java/org/apache/harmony/security/utils/WrappedX509Certificate.java175
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java2
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java13
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java84
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x509/Extension.java19
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x509/Extensions.java8
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java7
-rw-r--r--luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java9
-rw-r--r--luni/src/main/java/org/apache/harmony/xml/ExpatParser.java6
-rw-r--r--luni/src/main/native/AsynchronousCloseMonitor.cpp (renamed from luni/src/main/native/AsynchronousSocketCloseMonitor.cpp)33
-rw-r--r--luni/src/main/native/AsynchronousCloseMonitor.h (renamed from luni/src/main/native/AsynchronousSocketCloseMonitor.h)36
-rw-r--r--luni/src/main/native/IcuUtilities.cpp6
-rw-r--r--luni/src/main/native/IcuUtilities.h3
-rw-r--r--luni/src/main/native/NetworkUtilities.h2
-rw-r--r--luni/src/main/native/Portability.h14
-rw-r--r--luni/src/main/native/Register.cpp9
-rw-r--r--luni/src/main/native/android_system_OsConstants.cpp (renamed from luni/src/main/native/libcore_io_OsConstants.cpp)85
-rw-r--r--luni/src/main/native/canonicalize_path.cpp (renamed from luni/src/main/native/realpath.cpp)2
-rw-r--r--luni/src/main/native/java_io_Console.cpp51
-rw-r--r--luni/src/main/native/java_io_File.cpp188
-rw-r--r--luni/src/main/native/java_io_FileDescriptor.cpp35
-rw-r--r--luni/src/main/native/java_lang_Character.cpp34
-rw-r--r--luni/src/main/native/java_lang_Double.cpp14
-rw-r--r--luni/src/main/native/java_lang_Float.cpp15
-rw-r--r--luni/src/main/native/java_lang_Math.cpp1
-rw-r--r--luni/src/main/native/java_lang_ProcessManager.cpp2
-rw-r--r--luni/src/main/native/java_lang_System.cpp26
-rw-r--r--luni/src/main/native/java_math_NativeBN.cpp130
-rw-r--r--luni/src/main/native/java_util_jar_StrictJarFile.cpp173
-rw-r--r--luni/src/main/native/libcore_icu_AlphabeticIndex.cpp17
-rw-r--r--luni/src/main/native/libcore_icu_DateIntervalFormat.cpp8
-rw-r--r--luni/src/main/native/libcore_icu_ICU.cpp307
-rw-r--r--luni/src/main/native/libcore_icu_NativeBreakIterator.cpp20
-rw-r--r--luni/src/main/native/libcore_icu_NativeCollation.cpp112
-rw-r--r--luni/src/main/native/libcore_icu_NativeConverter.cpp8
-rw-r--r--luni/src/main/native/libcore_icu_NativeDecimalFormat.cpp94
-rw-r--r--luni/src/main/native/libcore_icu_TimeZoneNames.cpp58
-rw-r--r--luni/src/main/native/libcore_io_AsynchronousCloseMonitor.cpp6
-rw-r--r--luni/src/main/native/libcore_io_Memory.cpp52
-rw-r--r--luni/src/main/native/libcore_io_Posix.cpp300
-rw-r--r--luni/src/main/native/libcore_net_RawSocket.cpp219
-rw-r--r--luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp5
-rw-r--r--luni/src/main/native/sub.mk123
-rw-r--r--luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java2
-rw-r--r--luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java32
-rw-r--r--luni/src/test/java/dalvik/system/DexClassLoaderTest.java427
-rw-r--r--luni/src/test/java/dalvik/system/JniTest.java368
-rw-r--r--luni/src/test/java/dalvik/system/VMRuntimeTest.java135
-rw-r--r--luni/src/test/java/libcore/android/system/OsConstantsTest.java31
-rw-r--r--luni/src/test/java/libcore/icu/AlphabeticIndexTest.java23
-rw-r--r--luni/src/test/java/libcore/icu/DateIntervalFormatTest.java126
-rw-r--r--luni/src/test/java/libcore/icu/ICUTest.java162
-rw-r--r--luni/src/test/java/libcore/icu/LocaleDataTest.java210
-rw-r--r--luni/src/test/java/libcore/icu/NativePluralRulesTest.java6
-rw-r--r--luni/src/test/java/libcore/icu/TimeZoneNamesTest.java7
-rw-r--r--luni/src/test/java/libcore/io/MemoryTest.java18
-rw-r--r--luni/src/test/java/libcore/io/OsTest.java4
-rw-r--r--luni/src/test/java/libcore/java/io/FileTest.java35
-rwxr-xr-xluni/src/test/java/libcore/java/io/InterruptedStreamTest.java7
-rw-r--r--luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java228
-rw-r--r--luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java209
-rw-r--r--luni/src/test/java/libcore/java/io/OldFileTest.java116
-rw-r--r--luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java45
-rw-r--r--luni/src/test/java/libcore/java/io/SerializationTest.java104
-rw-r--r--luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java81
-rw-r--r--luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java154
-rw-r--r--luni/src/test/java/libcore/java/lang/CharacterTest.java30
-rw-r--r--luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java78
-rw-r--r--luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java49
-rw-r--r--luni/src/test/java/libcore/java/lang/ClassTest.java53
-rw-r--r--luni/src/test/java/libcore/java/lang/DoubleTest.java15
-rw-r--r--luni/src/test/java/libcore/java/lang/IntegerTest.java125
-rw-r--r--luni/src/test/java/libcore/java/lang/LongTest.java101
-rw-r--r--luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java108
-rw-r--r--luni/src/test/java/libcore/java/lang/OldClassTest.java20
-rw-r--r--luni/src/test/java/libcore/java/lang/OldIntegerTest.java69
-rw-r--r--luni/src/test/java/libcore/java/lang/OldLongTest.java83
-rw-r--r--luni/src/test/java/libcore/java/lang/OldObjectTest.java10
-rw-r--r--luni/src/test/java/libcore/java/lang/OldRuntimeTest.java26
-rw-r--r--luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java14
-rw-r--r--luni/src/test/java/libcore/java/lang/StringBuilderTest.java132
-rw-r--r--luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java47
-rw-r--r--luni/src/test/java/libcore/java/lang/StringTest.java128
-rw-r--r--luni/src/test/java/libcore/java/lang/SystemTest.java136
-rw-r--r--luni/src/test/java/libcore/java/lang/ThreadTest.java99
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java277
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java22
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java18
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/FieldTest.java23
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/MethodTest.java56
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java2
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java2
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java334
-rw-r--r--luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java55
-rw-r--r--luni/src/test/java/libcore/java/math/BigIntegerTest.java28
-rw-r--r--luni/src/test/java/libcore/java/math/CSVTest.java88
-rw-r--r--luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java4
-rw-r--r--luni/src/test/java/libcore/java/math/RunCSVTests.java109
-rw-r--r--luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java62
-rw-r--r--luni/src/test/java/libcore/java/net/DatagramSocketTest.java58
-rw-r--r--luni/src/test/java/libcore/java/net/InetAddressTest.java15
-rw-r--r--luni/src/test/java/libcore/java/net/InetSocketAddressTest.java3
-rw-r--r--luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java73
-rw-r--r--luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java2183
-rw-r--r--luni/src/test/java/libcore/java/net/OldFileNameMapTest.java22
-rw-r--r--luni/src/test/java/libcore/java/net/OldSocketTest.java22
-rw-r--r--luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java41
-rw-r--r--luni/src/test/java/libcore/java/net/ServerSocketTest.java32
-rw-r--r--luni/src/test/java/libcore/java/net/SocketTest.java69
-rw-r--r--luni/src/test/java/libcore/java/net/URITest.java46
-rw-r--r--luni/src/test/java/libcore/java/net/URLConnectionTest.java125
-rw-r--r--luni/src/test/java/libcore/java/net/URLTest.java18
-rw-r--r--luni/src/test/java/libcore/java/nio/BufferTest.java448
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java116
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java119
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java709
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java19
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/SelectorTest.java10
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java114
-rw-r--r--luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java201
-rw-r--r--luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java172
-rw-r--r--luni/src/test/java/libcore/java/security/KeyStoreTest.java75
-rw-r--r--luni/src/test/java/libcore/java/security/MessageDigestTest.java46
-rw-r--r--luni/src/test/java/libcore/java/security/MockPrivateKey.java40
-rw-r--r--luni/src/test/java/libcore/java/security/MockPrivateKey2.java40
-rw-r--r--luni/src/test/java/libcore/java/security/MockPublicKey.java40
-rw-r--r--luni/src/test/java/libcore/java/security/MockSignatureSpi.java118
-rw-r--r--luni/src/test/java/libcore/java/security/OldDHTest.java3
-rw-r--r--luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java3
-rw-r--r--luni/src/test/java/libcore/java/security/ProviderTest.java433
-rw-r--r--luni/src/test/java/libcore/java/security/SignatureTest.java375
-rw-r--r--luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java67
-rw-r--r--luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java3
-rw-r--r--luni/src/test/java/libcore/java/security/cert/X509CRLTest.java38
-rw-r--r--luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java3
-rw-r--r--luni/src/test/java/libcore/java/sql/ConnectionTest.java69
-rw-r--r--luni/src/test/java/libcore/java/sql/DriverTest.java76
-rw-r--r--luni/src/test/java/libcore/java/sql/OldResultSetTest.java2
-rw-r--r--luni/src/test/java/libcore/java/sql/OldTimestampTest.java41
-rw-r--r--luni/src/test/java/libcore/java/sql/TimestampTest.java147
-rw-r--r--luni/src/test/java/libcore/java/text/CollatorTest.java8
-rw-r--r--luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java11
-rw-r--r--luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java19
-rw-r--r--luni/src/test/java/libcore/java/text/DecimalFormatTest.java141
-rw-r--r--luni/src/test/java/libcore/java/text/NumberFormatTest.java42
-rw-r--r--luni/src/test/java/libcore/java/text/OldBidiTest.java22
-rw-r--r--luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.java52
-rw-r--r--luni/src/test/java/libcore/java/text/OldCollationKeyTest.java9
-rw-r--r--luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java1007
-rw-r--r--luni/src/test/java/libcore/java/text/OldFieldPositionTest.java79
-rw-r--r--luni/src/test/java/libcore/java/text/OldMessageFormatTest.java463
-rw-r--r--luni/src/test/java/libcore/java/text/OldNumberFormatTest.java15
-rw-r--r--luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java539
-rw-r--r--luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java107
-rw-r--r--luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java44
-rw-r--r--luni/src/test/java/libcore/java/util/CalendarTest.java29
-rw-r--r--luni/src/test/java/libcore/java/util/CurrencyTest.java8
-rw-r--r--luni/src/test/java/libcore/java/util/DateTest.java32
-rw-r--r--luni/src/test/java/libcore/java/util/GregorianCalendarTest.java56
-rw-r--r--luni/src/test/java/libcore/java/util/LocaleInternalsTest.java129
-rw-r--r--luni/src/test/java/libcore/java/util/LocaleTest.java1018
-rw-r--r--luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java17
-rw-r--r--luni/src/test/java/libcore/java/util/OldTimeZoneTest.java49
-rw-r--r--luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java90
-rw-r--r--luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java73
-rw-r--r--luni/src/test/java/libcore/java/util/TimeZoneTest.java9
-rw-r--r--luni/src/test/java/libcore/java/util/UUIDTest.java53
-rw-r--r--luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java258
-rw-r--r--luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java181
-rw-r--r--luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java22
-rw-r--r--luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java21
-rw-r--r--luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java21
-rw-r--r--luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java21
-rw-r--r--luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java16
-rw-r--r--luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java43
-rw-r--r--luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java122
-rw-r--r--luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java16
-rw-r--r--luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java39
-rw-r--r--luni/src/test/java/libcore/java/util/zip/ZipFileTest.java64
-rw-r--r--luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java25
-rw-r--r--luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java35
-rw-r--r--luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java154
-rw-r--r--luni/src/test/java/libcore/javax/crypto/CipherTest.java486
-rw-r--r--luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java2
-rw-r--r--luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java136
-rw-r--r--luni/src/test/java/libcore/javax/crypto/MockKey.java (renamed from luni/src/test/java/libcore/sqlite/OldExceptionTest.java)35
-rw-r--r--luni/src/test/java/libcore/javax/crypto/MockKey2.java40
-rw-r--r--luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java2
-rw-r--r--luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java3
-rw-r--r--luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java3
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java3
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java4
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java104
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java376
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java355
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java28
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java66
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java2
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java193
-rw-r--r--luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java445
-rw-r--r--luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java19
-rw-r--r--luni/src/test/java/libcore/net/MimeUtilsTest.java45
-rw-r--r--luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java78
-rw-r--r--luni/src/test/java/libcore/reflect/InternalNamesTest.java82
-rw-r--r--luni/src/test/java/libcore/sqlite/AbstractSqlTest.java213
-rw-r--r--luni/src/test/java/libcore/sqlite/OldBlobTest.java135
-rw-r--r--luni/src/test/java/libcore/sqlite/OldDatabaseTest.java1224
-rw-r--r--luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java314
-rw-r--r--luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java64
-rw-r--r--luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java113
-rw-r--r--luni/src/test/java/libcore/sqlite/OldSQLiteTest.java62
-rw-r--r--luni/src/test/java/libcore/sqlite/OldStmtTest.java823
-rw-r--r--luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java165
-rw-r--r--luni/src/test/java/libcore/util/ZoneInfoDBTest.java55
-rw-r--r--luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java374
-rw-r--r--luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java1001
-rw-r--r--luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java505
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java4
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java134
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java206
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java89
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java82
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java28
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java5
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java5
-rw-r--r--luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java3
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java4
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java1043
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java851
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java147
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java89
-rw-r--r--luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java3
-rw-r--r--luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java7
-rw-r--r--luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java10
-rw-r--r--luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java145
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java687
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationTestClass.java335
-rw-r--r--luni/src/test/java/tests/api/java/lang/Process2Test.java87
-rw-r--r--luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java223
-rw-r--r--luni/src/test/java/tests/api/java/lang/ProcessTest.java135
-rw-r--r--luni/src/test/java/tests/api/java/lang/StringTest.java49
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java141
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java253
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java340
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java143
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java80
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java215
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java1001
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java128
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java443
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java1868
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java64
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java121
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java74
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java101
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java305
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java21
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java881
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java77
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java319
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java150
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java53
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java151
-rw-r--r--luni/src/test/java/tests/api/java/math/MathContextTest.java79
-rw-r--r--luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java372
-rw-r--r--luni/src/test/java/tests/api/java/math/RoundingModeTest.java49
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractListTest.java293
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractMapTest.java327
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractQueueTest.java323
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java603
-rw-r--r--luni/src/test/java/tests/api/java/util/ArrayListTest.java699
-rw-r--r--luni/src/test/java/tests/api/java/util/ArraysTest.java2403
-rw-r--r--luni/src/test/java/tests/api/java/util/BitSetTest.java1279
-rw-r--r--luni/src/test/java/tests/api/java/util/CalendarTest.java1099
-rw-r--r--luni/src/test/java/tests/api/java/util/CollectionsTest.java2226
-rw-r--r--luni/src/test/java/tests/api/java/util/ConcurrentModTest.java667
-rw-r--r--luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java107
-rw-r--r--luni/src/test/java/tests/api/java/util/CurrencyTest.java428
-rw-r--r--luni/src/test/java/tests/api/java/util/DateTest.java514
-rw-r--r--luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java65
-rw-r--r--luni/src/test/java/tests/api/java/util/EnumMapTest.java1175
-rw-r--r--luni/src/test/java/tests/api/java/util/EnumSetTest.java2003
-rw-r--r--luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java31
-rw-r--r--luni/src/test/java/tests/api/java/util/HashMapTest.java558
-rw-r--r--luni/src/test/java/tests/api/java/util/HashSetTest.java253
-rw-r--r--luni/src/test/java/tests/api/java/util/HashtableTest.java838
-rw-r--r--luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java494
-rw-r--r--luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java39
-rw-r--r--luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java736
-rw-r--r--luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java351
-rw-r--r--luni/src/test/java/tests/api/java/util/LinkedListTest.java658
-rw-r--r--luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java78
-rw-r--r--luni/src/test/java/tests/api/java/util/LocaleTest.java416
-rw-r--r--luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java85
-rw-r--r--luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java73
-rw-r--r--luni/src/test/java/tests/api/java/util/ObservableTest.java246
-rw-r--r--luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java98
-rw-r--r--luni/src/test/java/tests/api/java/util/RandomTest.java298
-rw-r--r--luni/src/test/java/tests/api/java/util/ResourceBundleTest.java398
-rw-r--r--luni/src/test/java/tests/api/java/util/SampleBundleClass.java43
-rw-r--r--luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java838
-rw-r--r--luni/src/test/java/tests/api/java/util/StackTest.java188
-rw-r--r--luni/src/test/java/tests/api/java/util/StringTokenizerTest.java225
-rw-r--r--luni/src/test/java/tests/api/java/util/TimerTaskTest.java248
-rw-r--r--luni/src/test/java/tests/api/java/util/TimerTest.java986
-rw-r--r--luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java64
-rw-r--r--luni/src/test/java/tests/api/java/util/VectorTest.java1198
-rw-r--r--luni/src/test/java/tests/api/java/util/WeakHashMapTest.java383
-rw-r--r--luni/src/test/java/tests/api/java/util/support/A.java13
-rw-r--r--luni/src/test/java/tests/api/java/util/support/B.java4
-rw-r--r--luni/src/test/java/tests/api/java/util/support/I.java5
-rw-r--r--luni/src/test/java/tests/api/java/util/support/P.java28
-rw-r--r--luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java129
-rw-r--r--luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java267
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java78
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java478
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java613
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java290
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java341
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java532
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java263
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java151
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java101
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java599
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java293
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java229
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java83
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java90
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java217
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java1482
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java158
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java55
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java55
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java55
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java55
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java106
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java431
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java236
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java85
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java95
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java641
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java139
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java631
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java519
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java255
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java139
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java176
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java753
-rw-r--r--luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java149
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.java47
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.java69
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java64
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.java69
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java107
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java250
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.java117
-rw-r--r--luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java270
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.java78
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java79
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java79
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java81
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.java80
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java159
-rw-r--r--luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java788
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java975
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java637
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java99
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java39
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java415
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java922
-rw-r--r--luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java492
-rw-r--r--luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java285
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java151
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java168
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java101
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java40
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java40
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java216
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java392
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java153
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java113
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java205
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java481
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java187
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java108
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java318
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java335
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java145
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java484
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java314
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java146
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java54
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java55
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java79
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java95
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java89
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java147
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java68
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java128
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java47
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java55
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java79
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java58
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java82
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java54
-rw-r--r--luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java79
-rw-r--r--luni/src/test/java/tests/java/sql/SqlDateTest.java50
-rw-r--r--luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java167
-rw-r--r--luni/src/test/native/dalvik_system_JniTest.cpp274
-rw-r--r--luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider2
-rw-r--r--luni/src/test/resources/math_important_numbers.csv738
-rw-r--r--luni/src/test/resources/math_java_only.csv4132
-rw-r--r--luni/src/test/resources/math_tests.csv5199
-rw-r--r--luni/src/test/resources/org/apache/harmony/tests/java/lang/test#.properties1
-rw-r--r--luni/src/test/resources/org/apache/harmony/tests/java/lang/test.properties1
-rw-r--r--luni/src/test/resources/serialization/java/text/DecimalFormat.serbin1384 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/java/text/DecimalFormatSymbols.serbin495 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.0.serbin113 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.1.serbin443 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.2.serbin329 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.3.serbin288 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.serbin329 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/util/UUIDTest.golden.serbin80 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.golden.serbin1283 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.golden.serbin1369 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.golden.serbin1403 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.golden.serbin1420 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.golden.serbin1427 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.golden.serbin1441 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.golden.serbin1424 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.golden.serbin1500 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.golden.serbin1374 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.golden.serbin1430 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.golden.serbin1439 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.golden.serbin1395 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.golden.serbin1743 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.golden.serbin1734 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.golden.serbin1445 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.golden.serbin1442 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.golden.serbin1442 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.golden.serbin1719 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.golden.serbin1731 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.golden.serbin1743 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.golden.serbin1740 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.golden.serbin1755 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.golden.serbin1822 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.golden.serbin1771 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.golden.serbin1924 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.golden.serbin1893 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.golden.serbin1908 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.golden.serbin1924 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDClass.serbin798 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDConstructors.serbin890 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDFields.serbin1856 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDInterfaces.serbin1306 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDMethods.serbin1136 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/util/EnumMapTest.golden.serbin270 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/util/EnumSetTest.golden.serbin897 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/util/HashSetTest.golden.serbin69 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/api/java/util/IdentityHashMapTest.golden.serbin88 -> 0 bytes
-rw-r--r--luni/src/test/resources/serialization/tests/security/cert/CertificateRevocationExceptionTest.golden.serbin0 -> 2137 bytes
-rw-r--r--luni/src/test/resources/tests/api/java/lang/reflect/dex1.bytesbin888 -> 0 bytes
-rw-r--r--luni/src/test/resources/tests/resources/java/util/zip/EmptyArchive.zipbin0 -> 22 bytes
786 files changed, 42409 insertions, 82072 deletions
diff --git a/luni/src/main/files/cacerts/03f2b8cf.0 b/luni/src/main/files/cacerts/03f2b8cf.0
new file mode 100644
index 0000000..82813fb
--- /dev/null
+++ b/luni/src/main/files/cacerts/03f2b8cf.0
@@ -0,0 +1,120 @@
+-----BEGIN CERTIFICATE-----
+MIIFWDCCA0CgAwIBAgIQUHBrzdgT/BtOOzNy0hFIjTANBgkqhkiG9w0BAQsFADBG
+MQswCQYDVQQGEwJDTjEaMBgGA1UEChMRV29TaWduIENBIExpbWl0ZWQxGzAZBgNV
+BAMMEkNBIOayg+mAmuagueivgeS5pjAeFw0wOTA4MDgwMTAwMDFaFw0zOTA4MDgw
+MTAwMDFaMEYxCzAJBgNVBAYTAkNOMRowGAYDVQQKExFXb1NpZ24gQ0EgTGltaXRl
+ZDEbMBkGA1UEAwwSQ0Eg5rKD6YCa5qC56K+B5LmmMIICIjANBgkqhkiG9w0BAQEF
+AAOCAg8AMIICCgKCAgEA0EkhHiX8h8EqwqzbdoYGTufQdDTc7WU1/FDWiD+k8H/r
+D195L4mx/bxjWDeTmzj4t1up+thxx7S8gJeNbEvxUNUqKaqoGXqW5pWOdO2XCld1
+9AXbbQs5uQF/qvbW2mzmBeCkTVL829B0txGMe41P/4eDrv8FAxNXUDf+jJZSEExf
+v5RxadmWPgxDT74wwJ85dE8GRV2j1lY5aAfMh09Qd5Nx2UQIsYo06Yms25tO4dnk
+UkWMLhQfkWsZHWgpLFbE4h4TV2TwYeO5Ed+w4VegG63XX9Gv2ystP9Bojg/qnw+L
+NVgbExz03jWhCl3W6t8Sb8D7aQdGctyB9gQjF+BNdeFyb7Ao65vh4YOhn0pdr8yb
++gIgthhid5E7o9Vlrdx8kHccREGkSovrlXLp9glk3Kgtn3R46MGiCWOc76DbT52V
+qyBPt7D3h1ymoOQ3OMdc4zUPLK2jgKLsLl3Az+2LBcLmc272idX10kaO6m1jGx6K
+yX2m+Jzr5dVjhU1zZmkR/sgO9MHHZklTfuQZa/HpelmjbX7FF+Ynxu8b22/8DU0G
+AbQOXDBGVWCvOGU6yke6rCzMRh+yRpY/8+0mBe53oWprfi1tWFxK1I5nuPHa1UaK
+J/kR8slC/k7e3x9cxKSGhxYzoacXGKUN5AXlK8IrC6KVkLn9YDxOiT7nnO4fuwEC
+AwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O
+BBYEFOBNv9ybQV0T6GTwp+kVpOGBwboxMA0GCSqGSIb3DQEBCwUAA4ICAQBqinA4
+WbbaixjIvirTthnVZil6Xc1bL3McJk6jfW+rtylNpumlEYOnOXOvEESS5iVdT2H6
+yAa+Tkvv/vMx/sZ8cApBWNromUuWyXi8mHwCKe0JgOYKOoICKuLJL8hWGSbueBwj
+/feTZU7n85iYr83d2Z5AiDEoOqsuC7CsDCT6eiaY8xJhEPRdF/d+4niXVOKM6Cm6
+jBAyvd0zaziGfjk9DgNyp115j0WKWa5bIW4xRtVZjc8VX90xJc/bYNaBRHIpAlf2
+ltTW/+op2znFuCyKGo3Oy+dCMYYFaA6eFN0AkLppRQjbbpCBhqcqBT/mhDn4t/lX
+X0ykeVoQDF7Va/81XwVRHmyjdanPUIPTfPRm94KNPQx96N97qA4bLJyuQHCH2u2n
+FoJavjVsIE4iYdm8UXrNemHcSxH5/mc0zy4EZmFcV5cjjPOGG0jfKq+nwf/Yjj4D
+u9gqsPoUJbJRa4ZDhS4HIxaAjUz7tGM7zMN07RujHv41D198HRaG9Q7DlfEvr10l
+O1Hm13ZBONFLAzkopR6RctR9q5czxNM+4Gm2KHmgCY0c0f9BckgG/Jou5yD5m6Le
+ie2uPAmvylezkolwQOQvT8Jwg0DXJCxr5wkf09XHwQj02w47HAcLQxGEIYbpgNR1
+2KvxAmLBsX5VYc8T1yaw15zLKYs4SgsOkI26oQ==
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 50:70:6b:cd:d8:13:fc:1b:4e:3b:33:72:d2:11:48:8d
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=CN, O=WoSign CA Limited, CN=CA \xE6\xB2\x83\xE9\x80\x9A\xE6\xA0\xB9\xE8\xAF\x81\xE4\xB9\xA6
+ Validity
+ Not Before: Aug 8 01:00:01 2009 GMT
+ Not After : Aug 8 01:00:01 2039 GMT
+ Subject: C=CN, O=WoSign CA Limited, CN=CA \xE6\xB2\x83\xE9\x80\x9A\xE6\xA0\xB9\xE8\xAF\x81\xE4\xB9\xA6
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:d0:49:21:1e:25:fc:87:c1:2a:c2:ac:db:76:86:
+ 06:4e:e7:d0:74:34:dc:ed:65:35:fc:50:d6:88:3f:
+ a4:f0:7f:eb:0f:5f:79:2f:89:b1:fd:bc:63:58:37:
+ 93:9b:38:f8:b7:5b:a9:fa:d8:71:c7:b4:bc:80:97:
+ 8d:6c:4b:f1:50:d5:2a:29:aa:a8:19:7a:96:e6:95:
+ 8e:74:ed:97:0a:57:75:f4:05:db:6d:0b:39:b9:01:
+ 7f:aa:f6:d6:da:6c:e6:05:e0:a4:4d:52:fc:db:d0:
+ 74:b7:11:8c:7b:8d:4f:ff:87:83:ae:ff:05:03:13:
+ 57:50:37:fe:8c:96:52:10:4c:5f:bf:94:71:69:d9:
+ 96:3e:0c:43:4f:be:30:c0:9f:39:74:4f:06:45:5d:
+ a3:d6:56:39:68:07:cc:87:4f:50:77:93:71:d9:44:
+ 08:b1:8a:34:e9:89:ac:db:9b:4e:e1:d9:e4:52:45:
+ 8c:2e:14:1f:91:6b:19:1d:68:29:2c:56:c4:e2:1e:
+ 13:57:64:f0:61:e3:b9:11:df:b0:e1:57:a0:1b:ad:
+ d7:5f:d1:af:db:2b:2d:3f:d0:68:8e:0f:ea:9f:0f:
+ 8b:35:58:1b:13:1c:f4:de:35:a1:0a:5d:d6:ea:df:
+ 12:6f:c0:fb:69:07:46:72:dc:81:f6:04:23:17:e0:
+ 4d:75:e1:72:6f:b0:28:eb:9b:e1:e1:83:a1:9f:4a:
+ 5d:af:cc:9b:fa:02:20:b6:18:62:77:91:3b:a3:d5:
+ 65:ad:dc:7c:90:77:1c:44:41:a4:4a:8b:eb:95:72:
+ e9:f6:09:64:dc:a8:2d:9f:74:78:e8:c1:a2:09:63:
+ 9c:ef:a0:db:4f:9d:95:ab:20:4f:b7:b0:f7:87:5c:
+ a6:a0:e4:37:38:c7:5c:e3:35:0f:2c:ad:a3:80:a2:
+ ec:2e:5d:c0:cf:ed:8b:05:c2:e6:73:6e:f6:89:d5:
+ f5:d2:46:8e:ea:6d:63:1b:1e:8a:c9:7d:a6:f8:9c:
+ eb:e5:d5:63:85:4d:73:66:69:11:fe:c8:0e:f4:c1:
+ c7:66:49:53:7e:e4:19:6b:f1:e9:7a:59:a3:6d:7e:
+ c5:17:e6:27:c6:ef:1b:db:6f:fc:0d:4d:06:01:b4:
+ 0e:5c:30:46:55:60:af:38:65:3a:ca:47:ba:ac:2c:
+ cc:46:1f:b2:46:96:3f:f3:ed:26:05:ee:77:a1:6a:
+ 6b:7e:2d:6d:58:5c:4a:d4:8e:67:b8:f1:da:d5:46:
+ 8a:27:f9:11:f2:c9:42:fe:4e:de:df:1f:5c:c4:a4:
+ 86:87:16:33:a1:a7:17:18:a5:0d:e4:05:e5:2b:c2:
+ 2b:0b:a2:95:90:b9:fd:60:3c:4e:89:3e:e7:9c:ee:
+ 1f:bb:01
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Subject Key Identifier:
+ E0:4D:BF:DC:9B:41:5D:13:E8:64:F0:A7:E9:15:A4:E1:81:C1:BA:31
+ Signature Algorithm: sha256WithRSAEncryption
+ 6a:8a:70:38:59:b6:da:8b:18:c8:be:2a:d3:b6:19:d5:66:29:
+ 7a:5d:cd:5b:2f:73:1c:26:4e:a3:7d:6f:ab:b7:29:4d:a6:e9:
+ a5:11:83:a7:39:73:af:10:44:92:e6:25:5d:4f:61:fa:c8:06:
+ be:4e:4b:ef:fe:f3:31:fe:c6:7c:70:0a:41:58:da:e8:99:4b:
+ 96:c9:78:bc:98:7c:02:29:ed:09:80:e6:0a:3a:82:02:2a:e2:
+ c9:2f:c8:56:19:26:ee:78:1c:23:fd:f7:93:65:4e:e7:f3:98:
+ 98:af:cd:dd:d9:9e:40:88:31:28:3a:ab:2e:0b:b0:ac:0c:24:
+ fa:7a:26:98:f3:12:61:10:f4:5d:17:f7:7e:e2:78:97:54:e2:
+ 8c:e8:29:ba:8c:10:32:bd:dd:33:6b:38:86:7e:39:3d:0e:03:
+ 72:a7:5d:79:8f:45:8a:59:ae:5b:21:6e:31:46:d5:59:8d:cf:
+ 15:5f:dd:31:25:cf:db:60:d6:81:44:72:29:02:57:f6:96:d4:
+ d6:ff:ea:29:db:39:c5:b8:2c:8a:1a:8d:ce:cb:e7:42:31:86:
+ 05:68:0e:9e:14:dd:00:90:ba:69:45:08:db:6e:90:81:86:a7:
+ 2a:05:3f:e6:84:39:f8:b7:f9:57:5f:4c:a4:79:5a:10:0c:5e:
+ d5:6b:ff:35:5f:05:51:1e:6c:a3:75:a9:cf:50:83:d3:7c:f4:
+ 66:f7:82:8d:3d:0c:7d:e8:df:7b:a8:0e:1b:2c:9c:ae:40:70:
+ 87:da:ed:a7:16:82:5a:be:35:6c:20:4e:22:61:d9:bc:51:7a:
+ cd:7a:61:dc:4b:11:f9:fe:67:34:cf:2e:04:66:61:5c:57:97:
+ 23:8c:f3:86:1b:48:df:2a:af:a7:c1:ff:d8:8e:3e:03:bb:d8:
+ 2a:b0:fa:14:25:b2:51:6b:86:43:85:2e:07:23:16:80:8d:4c:
+ fb:b4:63:3b:cc:c3:74:ed:1b:a3:1e:fe:35:0f:5f:7c:1d:16:
+ 86:f5:0e:c3:95:f1:2f:af:5d:25:3b:51:e6:d7:76:41:38:d1:
+ 4b:03:39:28:a5:1e:91:72:d4:7d:ab:97:33:c4:d3:3e:e0:69:
+ b6:28:79:a0:09:8d:1c:d1:ff:41:72:48:06:fc:9a:2e:e7:20:
+ f9:9b:a2:de:89:ed:ae:3c:09:af:ca:57:b3:92:89:70:40:e4:
+ 2f:4f:c2:70:83:40:d7:24:2c:6b:e7:09:1f:d3:d5:c7:c1:08:
+ f4:db:0e:3b:1c:07:0b:43:11:84:21:86:e9:80:d4:75:d8:ab:
+ f1:02:62:c1:b1:7e:55:61:cf:13:d7:26:b0:d7:9c:cb:29:8b:
+ 38:4a:0b:0e:90:8d:ba:a1
+SHA1 Fingerprint=16:32:47:8D:89:F9:21:3A:92:00:85:63:F5:A4:A7:D3:12:40:8A:D6
diff --git a/luni/src/main/files/cacerts/1dbdda5b.0 b/luni/src/main/files/cacerts/1dbdda5b.0
deleted file mode 100644
index b9e52f6..0000000
--- a/luni/src/main/files/cacerts/1dbdda5b.0
+++ /dev/null
@@ -1,74 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIC+TCCAmKgAwIBAgIENvEbGTANBgkqhkiG9w0BAQUFADA2MQswCQYDVQQGEwJF
-UzENMAsGA1UEChMERk5NVDEYMBYGA1UECxMPRk5NVCBDbGFzZSAyIENBMB4XDTk5
-MDMxODE0NTYxOVoXDTE5MDMxODE1MjYxOVowNjELMAkGA1UEBhMCRVMxDTALBgNV
-BAoTBEZOTVQxGDAWBgNVBAsTD0ZOTVQgQ2xhc2UgMiBDQTCBnTANBgkqhkiG9w0B
-AQEFAAOBiwAwgYcCgYEAmD+tGTaTPT7+dkIU/TVv8fqtInpY40bQXcZa+WItjzFe
-/rQw/lB0rNadHeBixkndFBJ9cQusBsE/1waH4JCJ1uXjA7LyJ7GfM8iqazZKo8Q/
-eUGdiUYvKz5j1DhWkaodsQ1CdU3zh07jD03MtGy/YhOH6tCbjrbi/xn0lAnVlmEC
-AQOjggEUMIIBEDARBglghkgBhvhCAQEEBAMCAAcwWAYDVR0fBFEwTzBNoEugSaRH
-MEUxCzAJBgNVBAYTAkVTMQ0wCwYDVQQKEwRGTk1UMRgwFgYDVQQLEw9GTk1UIENs
-YXNlIDIgQ0ExDTALBgNVBAMTBENSTDEwKwYDVR0QBCQwIoAPMTk5OTAzMTgxNDU2
-MTlagQ8yMDE5MDMxODE0NTYxOVowCwYDVR0PBAQDAgEGMB8GA1UdIwQYMBaAFECa
-dkSXdAfErBTLHo1POkV8MNdhMB0GA1UdDgQWBBRAmnZEl3QHxKwUyx6NTzpFfDDX
-YTAMBgNVHRMEBTADAQH/MBkGCSqGSIb2fQdBAAQMMAobBFY0LjADAgSQMA0GCSqG
-SIb3DQEBBQUAA4GBAGFMoHxZY1tm+O5lE85DgEe5sjXJyITHa3NgReSdN531jiW5
-+aqqyuP4Q5wvoIkFsUUylCoeA41dpt7PV5Xa3yZgX8vflR64zgjY+IrJT6lodZPj
-LwVMZGACokIeb4ZoZVUO2ENv8pExPqNHPCgFr0W2nSJMJntLfVsV+RlG3whd
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 921770777 (0x36f11b19)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=ES, O=FNMT, OU=FNMT Clase 2 CA
- Validity
- Not Before: Mar 18 14:56:19 1999 GMT
- Not After : Mar 18 15:26:19 2019 GMT
- Subject: C=ES, O=FNMT, OU=FNMT Clase 2 CA
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:98:3f:ad:19:36:93:3d:3e:fe:76:42:14:fd:35:
- 6f:f1:fa:ad:22:7a:58:e3:46:d0:5d:c6:5a:f9:62:
- 2d:8f:31:5e:fe:b4:30:fe:50:74:ac:d6:9d:1d:e0:
- 62:c6:49:dd:14:12:7d:71:0b:ac:06:c1:3f:d7:06:
- 87:e0:90:89:d6:e5:e3:03:b2:f2:27:b1:9f:33:c8:
- aa:6b:36:4a:a3:c4:3f:79:41:9d:89:46:2f:2b:3e:
- 63:d4:38:56:91:aa:1d:b1:0d:42:75:4d:f3:87:4e:
- e3:0f:4d:cc:b4:6c:bf:62:13:87:ea:d0:9b:8e:b6:
- e2:ff:19:f4:94:09:d5:96:61
- Exponent: 3 (0x3)
- X509v3 extensions:
- Netscape Cert Type:
- SSL CA, S/MIME CA, Object Signing CA
- X509v3 CRL Distribution Points:
-
- Full Name:
- DirName: C = ES, O = FNMT, OU = FNMT Clase 2 CA, CN = CRL1
-
- X509v3 Private Key Usage Period:
- Not Before: Mar 18 14:56:19 1999 GMT, Not After: Mar 18 14:56:19 2019 GMT
- X509v3 Key Usage:
- Certificate Sign, CRL Sign
- X509v3 Authority Key Identifier:
- keyid:40:9A:76:44:97:74:07:C4:AC:14:CB:1E:8D:4F:3A:45:7C:30:D7:61
-
- X509v3 Subject Key Identifier:
- 40:9A:76:44:97:74:07:C4:AC:14:CB:1E:8D:4F:3A:45:7C:30:D7:61
- X509v3 Basic Constraints:
- CA:TRUE
- 1.2.840.113533.7.65.0:
- 0
-..V4.0....
- Signature Algorithm: sha1WithRSAEncryption
- 61:4c:a0:7c:59:63:5b:66:f8:ee:65:13:ce:43:80:47:b9:b2:
- 35:c9:c8:84:c7:6b:73:60:45:e4:9d:37:9d:f5:8e:25:b9:f9:
- aa:aa:ca:e3:f8:43:9c:2f:a0:89:05:b1:45:32:94:2a:1e:03:
- 8d:5d:a6:de:cf:57:95:da:df:26:60:5f:cb:df:95:1e:b8:ce:
- 08:d8:f8:8a:c9:4f:a9:68:75:93:e3:2f:05:4c:64:60:02:a2:
- 42:1e:6f:86:68:65:55:0e:d8:43:6f:f2:91:31:3e:a3:47:3c:
- 28:05:af:45:b6:9d:22:4c:26:7b:4b:7d:5b:15:f9:19:46:df:
- 08:5d
-SHA1 Fingerprint=43:F9:B1:10:D5:BA:FD:48:22:52:31:B0:D0:08:2B:37:2F:EF:9A:54
diff --git a/luni/src/main/files/cacerts/1f58a078.0 b/luni/src/main/files/cacerts/1f58a078.0
new file mode 100644
index 0000000..ac07485
--- /dev/null
+++ b/luni/src/main/files/cacerts/1f58a078.0
@@ -0,0 +1,120 @@
+-----BEGIN CERTIFICATE-----
+MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL
+BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc
+BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00
+MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
+aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG
+SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf
+qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW
+n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym
+c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+
+O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1
+o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j
+IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq
+IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz
+8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh
+vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l
+7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG
+cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
+BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD
+ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66
+AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC
+roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga
+W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n
+lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE
++V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV
+csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd
+dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg
+KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM
+HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4
+WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 44:57:34:24:5b:81:89:9b:35:f2:ce:b8:2b:3b:5b:a7:26:f0:75:28
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2 G3
+ Validity
+ Not Before: Jan 12 18:59:32 2012 GMT
+ Not After : Jan 12 18:59:32 2042 GMT
+ Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2 G3
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:a1:ae:25:b2:01:18:dc:57:88:3f:46:eb:f9:af:
+ e2:eb:23:71:e2:9a:d1:61:66:21:5f:aa:af:27:51:
+ e5:6e:1b:16:d4:2d:7d:50:b0:53:77:bd:78:3a:60:
+ e2:64:02:9b:7c:86:9b:d6:1a:8e:ad:ff:1f:15:7f:
+ d5:95:1e:12:cb:e6:14:84:04:c1:df:36:b3:16:9f:
+ 8a:e3:c9:db:98:34:ce:d8:33:17:28:46:fc:a7:c9:
+ f0:d2:b4:d5:4d:09:72:49:f9:f2:87:e3:a9:da:7d:
+ a1:7d:6b:b2:3a:25:a9:6d:52:44:ac:f8:be:6e:fb:
+ dc:a6:73:91:90:61:a6:03:14:20:f2:e7:87:a3:88:
+ ad:ad:a0:8c:ff:a6:0b:25:52:25:e7:16:01:d5:cb:
+ b8:35:81:0c:a3:3b:f0:e1:e1:fc:5a:5d:ce:80:71:
+ 6d:f8:49:ab:3e:3b:ba:b8:d7:80:01:fb:a5:eb:5b:
+ b3:c5:5e:60:2a:31:a0:af:37:e8:20:3a:9f:a8:32:
+ 2c:0c:cc:09:1d:d3:9e:8e:5d:bc:4c:98:ee:c5:1a:
+ 68:7b:ec:53:a6:e9:14:35:a3:df:cd:80:9f:0c:48:
+ fb:1c:f4:f1:bf:4a:b8:fa:d5:8c:71:4a:c7:1f:ad:
+ fe:41:9a:b3:83:5d:f2:84:56:ef:a5:57:43:ce:29:
+ ad:8c:ab:55:bf:c4:fb:5b:01:dd:23:21:a1:58:00:
+ 8e:c3:d0:6a:13:ed:13:e3:12:2b:80:dc:67:e6:95:
+ b2:cd:1e:22:6e:2a:f8:41:d4:f2:ca:14:07:8d:8a:
+ 55:12:c6:69:f5:b8:86:68:2f:53:5e:b0:d2:aa:21:
+ c1:98:e6:30:e3:67:55:c7:9b:6e:ac:19:a8:55:a6:
+ 45:06:d0:23:3a:db:eb:65:5d:2a:11:11:f0:3b:4f:
+ ca:6d:f4:34:c4:71:e4:ff:00:5a:f6:5c:ae:23:60:
+ 85:73:f1:e4:10:b1:25:ae:d5:92:bb:13:c1:0c:e0:
+ 39:da:b4:39:57:b5:ab:35:aa:72:21:3b:83:35:e7:
+ 31:df:7a:21:6e:b8:32:08:7d:1d:32:91:15:4a:62:
+ 72:cf:e3:77:a1:bc:d5:11:1b:76:01:67:08:e0:41:
+ 0b:c3:eb:15:6e:f8:a4:19:d9:a2:ab:af:e2:27:52:
+ 56:2b:02:8a:2c:14:24:f9:bf:42:02:bf:26:c8:c6:
+ 8f:e0:6e:38:7d:53:2d:e5:ed:98:b3:95:63:68:7f:
+ f9:35:f4:df:88:c5:60:35:92:c0:7c:69:1c:61:95:
+ 16:d0:eb:de:0b:af:3e:04:10:45:65:58:50:38:af:
+ 48:f2:59:b6:16:f2:3c:0d:90:02:c6:70:2e:01:ad:
+ 3c:15:d7
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ ED:E7:6F:76:5A:BF:60:EC:49:5B:C6:A5:77:BB:72:16:71:9B:C4:3D
+ Signature Algorithm: sha256WithRSAEncryption
+ 91:df:80:3f:43:09:7e:71:c2:f7:eb:b3:88:8f:e1:51:b2:bc:
+ 3d:75:f9:28:5d:c8:bc:99:9b:7b:5d:aa:e5:ca:e1:0a:f7:e8:
+ b2:d3:9f:dd:67:31:7e:ba:01:aa:c7:6a:41:3b:90:d4:08:5c:
+ b2:60:6a:90:f0:c8:ce:03:62:f9:8b:ed:fb:6e:2a:dc:06:4d:
+ 3c:29:0f:89:16:8a:58:4c:48:0f:e8:84:61:ea:3c:72:a6:77:
+ e4:42:ae:88:a3:43:58:79:7e:ae:ca:a5:53:0d:a9:3d:70:bd:
+ 20:19:61:a4:6c:38:fc:43:32:e1:c1:47:ff:f8:ec:f1:11:22:
+ 32:96:9c:c2:f6:5b:69:96:7b:20:0c:43:41:9a:5b:f6:59:19:
+ 88:de:55:88:37:51:0b:78:5c:0a:1e:a3:42:fd:c7:9d:88:0f:
+ c0:f2:78:02:24:54:93:af:89:87:88:c9:4a:80:1d:ea:d0:6e:
+ 3e:61:2e:36:bb:35:0e:27:96:fd:66:34:3b:61:72:73:f1:16:
+ 5c:47:06:54:49:00:7a:58:12:b0:0a:ef:85:fd:b1:b8:33:75:
+ 6a:93:1c:12:e6:60:5e:6f:1d:7f:c9:1f:23:cb:84:61:9f:1e:
+ 82:44:f9:5f:ad:62:55:24:9a:52:98:ed:51:e7:a1:7e:97:3a:
+ e6:2f:1f:11:da:53:80:2c:85:9e:ab:35:10:db:22:5f:6a:c5:
+ 5e:97:53:f2:32:02:09:30:a3:58:f0:0d:01:d5:72:c6:b1:7c:
+ 69:7b:c3:f5:36:45:cc:61:6e:5e:4c:94:c5:5e:ae:e8:0e:5e:
+ 8b:bf:f7:cd:e0:ed:a1:0e:1b:33:ee:54:18:fe:0f:be:ef:7e:
+ 84:6b:43:e3:70:98:db:5d:75:b2:0d:59:07:85:15:23:39:d6:
+ f1:df:a9:26:0f:d6:48:c7:b3:a6:22:f5:33:37:5a:95:47:9f:
+ 7b:ba:18:15:6f:ff:d6:14:64:83:49:d2:0a:67:21:db:0f:35:
+ 63:60:28:22:e3:b1:95:83:cd:85:a6:dd:2f:0f:e7:67:52:6e:
+ bb:2f:85:7c:f5:4a:73:e7:c5:3e:c0:bd:21:12:05:3f:fc:b7:
+ 03:49:02:5b:c8:25:e6:e2:54:38:f5:79:87:8c:1d:53:b2:4e:
+ 85:7b:06:38:c7:2c:f8:f8:b0:72:8d:25:e5:77:52:f4:03:1c:
+ 48:a6:50:5f:88:20:30:6e:f2:82:43:ab:3d:97:84:e7:53:fb:
+ 21:c1:4f:0f:22:9a:86:b8:59:2a:f6:47:3d:19:88:2d:e8:85:
+ e1:9e:ec:85:08:6a:b1:6c:34:c9:1d:ec:48:2b:3b:78:ed:66:
+ c4:8e:79:69:83:de:7f:8c
+SHA1 Fingerprint=09:3C:61:F3:8B:8B:DC:7D:55:DF:75:38:02:05:00:E1:25:F5:C8:36
diff --git a/luni/src/main/files/cacerts/2e8714cb.0 b/luni/src/main/files/cacerts/2e8714cb.0
deleted file mode 100644
index c67d949..0000000
--- a/luni/src/main/files/cacerts/2e8714cb.0
+++ /dev/null
@@ -1,103 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFUjCCBDqgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJLUjEN
-MAsGA1UEChMES0lTQTEuMCwGA1UECxMlS29yZWEgQ2VydGlmaWNhdGlvbiBBdXRo
-b3JpdHkgQ2VudHJhbDEWMBQGA1UEAxMNS0lTQSBSb290Q0EgMzAeFw0wNDExMTkw
-NjM5NTFaFw0xNDExMTkwNjM5NTFaMGQxCzAJBgNVBAYTAktSMQ0wCwYDVQQKEwRL
-SVNBMS4wLAYDVQQLEyVLb3JlYSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBDZW50
-cmFsMRYwFAYDVQQDEw1LSVNBIFJvb3RDQSAzMIIBIDANBgkqhkiG9w0BAQEFAAOC
-AQ0AMIIBCAKCAQEA3rrtF2Wu0b1KPazbgHLMWOHn4ZPazDB6z+8Lri2nQ6u/p0LP
-CFYIpEcdffqG79gwlyY0YTyADvjU65/8IjAboW0+40zSVU4WQDfC9gdu2we1pYyW
-geKbXH6UYcjOhDyx+gDmctMJhXfp3F4hT7TkTvTiF6tQrxz/oTlYdVsSspa5jfBw
-YkhbVigqpYeRNrkeJPW5unu2UlFbF1pgBWycwubGjD756t08jP+J3kNwrB248XXN
-OMpTDUdoasY8GMq94bS+DvTQ49IT+rBRERHUQavo9DmO4TSETwuTqmo4/OXGeEeu
-dhf6oYA3BgAVCP1rI476cg2V1ktisWjC3TSbXQIBA6OCAg8wggILMB8GA1UdIwQY
-MBaAFI+B8NqmzXQ8vmb0FWtGpP4GKMyqMB0GA1UdDgQWBBSPgfDaps10PL5m9BVr
-RqT+BijMqjAOBgNVHQ8BAf8EBAMCAQYwggEuBgNVHSAEggElMIIBITCCAR0GBFUd
-IAAwggETMDAGCCsGAQUFBwIBFiRodHRwOi8vd3d3LnJvb3RjYS5vci5rci9yY2Ev
-Y3BzLmh0bWwwgd4GCCsGAQUFBwICMIHRHoHOx3QAIMd4yZ3BHLKUACCs9cd4x3jJ
-ncEcx4WyyLLkACgAVABoAGkAcwAgAGMAZQByAHQAaQBmAGkAYwBhAHQAZQAgAGkA
-cwAgAGEAYwBjAHIAZQBkAGkAdABlAGQAIAB1AG4AZABlAHIAIABFAGwAZQBjAHQA
-cgBvAG4AaQBjACAAUwBpAGcAbgBhAHQAdQByAGUAIABBAGMAdAAgAG8AZgAgAHQA
-aABlACAAUgBlAHAAdQBiAGwAaQBjACAAbwBmACAASwBvAHIAZQBhACkwMwYDVR0R
-BCwwKqQoMCYxJDAiBgNVBAMMG+2VnOq1reygleuztOuztO2YuOynhO2dpeybkDAz
-BgNVHRIELDAqpCgwJjEkMCIGA1UEAwwb7ZWc6rWt7KCV67O067O07Zi47KeE7Z2l
-7JuQMA8GA1UdEwEB/wQFMAMBAf8wDAYDVR0kBAUwA4ABADANBgkqhkiG9w0BAQUF
-AAOCAQEAz9b3Dv2wjG4FFY6oXCuyWtEeV6ZeGKqCEQj8mbdbp+PI0qLT+SQ09+Pk
-rolUR9NpScmAwRHr4inH9gaLX7riXs+rw87P7pIl3J85Hg4D9N6QW6FwmVzHc07J
-pHVJeyWhn4KSjU3sYcUMMqfHODiAVToqgx2cZHm5Dac1Smjvj/8F2LpOVmHY+Epw
-mAiWk9hgxzrsX58dKzVPSBShmrtv7tIDhlPxEMcHVGJeNo7iHCsdF03m9VrvirqC
-6HfZKBF+N4dKlArJQOk1pTr7ZD7yXxZ683bXzu4/RB1Fql8RqlMcOh9SUWJUD6OQ
-Nc9Nb7rHviwJ8TX4Absk3TC8SA/u2Q==
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 2 (0x2)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=KR, O=KISA, OU=Korea Certification Authority Central, CN=KISA RootCA 3
- Validity
- Not Before: Nov 19 06:39:51 2004 GMT
- Not After : Nov 19 06:39:51 2014 GMT
- Subject: C=KR, O=KISA, OU=Korea Certification Authority Central, CN=KISA RootCA 3
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (2048 bit)
- Modulus:
- 00:de:ba:ed:17:65:ae:d1:bd:4a:3d:ac:db:80:72:
- cc:58:e1:e7:e1:93:da:cc:30:7a:cf:ef:0b:ae:2d:
- a7:43:ab:bf:a7:42:cf:08:56:08:a4:47:1d:7d:fa:
- 86:ef:d8:30:97:26:34:61:3c:80:0e:f8:d4:eb:9f:
- fc:22:30:1b:a1:6d:3e:e3:4c:d2:55:4e:16:40:37:
- c2:f6:07:6e:db:07:b5:a5:8c:96:81:e2:9b:5c:7e:
- 94:61:c8:ce:84:3c:b1:fa:00:e6:72:d3:09:85:77:
- e9:dc:5e:21:4f:b4:e4:4e:f4:e2:17:ab:50:af:1c:
- ff:a1:39:58:75:5b:12:b2:96:b9:8d:f0:70:62:48:
- 5b:56:28:2a:a5:87:91:36:b9:1e:24:f5:b9:ba:7b:
- b6:52:51:5b:17:5a:60:05:6c:9c:c2:e6:c6:8c:3e:
- f9:ea:dd:3c:8c:ff:89:de:43:70:ac:1d:b8:f1:75:
- cd:38:ca:53:0d:47:68:6a:c6:3c:18:ca:bd:e1:b4:
- be:0e:f4:d0:e3:d2:13:fa:b0:51:11:11:d4:41:ab:
- e8:f4:39:8e:e1:34:84:4f:0b:93:aa:6a:38:fc:e5:
- c6:78:47:ae:76:17:fa:a1:80:37:06:00:15:08:fd:
- 6b:23:8e:fa:72:0d:95:d6:4b:62:b1:68:c2:dd:34:
- 9b:5d
- Exponent: 3 (0x3)
- X509v3 extensions:
- X509v3 Authority Key Identifier:
- keyid:8F:81:F0:DA:A6:CD:74:3C:BE:66:F4:15:6B:46:A4:FE:06:28:CC:AA
-
- X509v3 Subject Key Identifier:
- 8F:81:F0:DA:A6:CD:74:3C:BE:66:F4:15:6B:46:A4:FE:06:28:CC:AA
- X509v3 Key Usage: critical
- Certificate Sign, CRL Sign
- X509v3 Certificate Policies:
- Policy: X509v3 Any Policy
- CPS: http://www.rootca.or.kr/rca/cps.html
- User Notice:
- Explicit Text: Çt
-
- X509v3 Subject Alternative Name:
- DirName:/CN=\xED\x95\x9C\xEA\xB5\xAD\xEC\xA0\x95\xEB\xB3\xB4\xEB\xB3\xB4\xED\x98\xB8\xEC\xA7\x84\xED\x9D\xA5\xEC\x9B\x90
- X509v3 Issuer Alternative Name:
- DirName:/CN=\xED\x95\x9C\xEA\xB5\xAD\xEC\xA0\x95\xEB\xB3\xB4\xEB\xB3\xB4\xED\x98\xB8\xEC\xA7\x84\xED\x9D\xA5\xEC\x9B\x90
- X509v3 Basic Constraints: critical
- CA:TRUE
- X509v3 Policy Constraints:
- Require Explicit Policy:0
- Signature Algorithm: sha1WithRSAEncryption
- cf:d6:f7:0e:fd:b0:8c:6e:05:15:8e:a8:5c:2b:b2:5a:d1:1e:
- 57:a6:5e:18:aa:82:11:08:fc:99:b7:5b:a7:e3:c8:d2:a2:d3:
- f9:24:34:f7:e3:e4:ae:89:54:47:d3:69:49:c9:80:c1:11:eb:
- e2:29:c7:f6:06:8b:5f:ba:e2:5e:cf:ab:c3:ce:cf:ee:92:25:
- dc:9f:39:1e:0e:03:f4:de:90:5b:a1:70:99:5c:c7:73:4e:c9:
- a4:75:49:7b:25:a1:9f:82:92:8d:4d:ec:61:c5:0c:32:a7:c7:
- 38:38:80:55:3a:2a:83:1d:9c:64:79:b9:0d:a7:35:4a:68:ef:
- 8f:ff:05:d8:ba:4e:56:61:d8:f8:4a:70:98:08:96:93:d8:60:
- c7:3a:ec:5f:9f:1d:2b:35:4f:48:14:a1:9a:bb:6f:ee:d2:03:
- 86:53:f1:10:c7:07:54:62:5e:36:8e:e2:1c:2b:1d:17:4d:e6:
- f5:5a:ef:8a:ba:82:e8:77:d9:28:11:7e:37:87:4a:94:0a:c9:
- 40:e9:35:a5:3a:fb:64:3e:f2:5f:16:7a:f3:76:d7:ce:ee:3f:
- 44:1d:45:aa:5f:11:aa:53:1c:3a:1f:52:51:62:54:0f:a3:90:
- 35:cf:4d:6f:ba:c7:be:2c:09:f1:35:f8:01:bb:24:dd:30:bc:
- 48:0f:ee:d9
-SHA1 Fingerprint=5F:4E:1F:CF:31:B7:91:3B:85:0B:54:F6:E5:FF:50:1A:2B:6F:C6:CF
diff --git a/luni/src/main/files/cacerts/48478734.0 b/luni/src/main/files/cacerts/48478734.0
deleted file mode 100644
index e317faf..0000000
--- a/luni/src/main/files/cacerts/48478734.0
+++ /dev/null
@@ -1,76 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDczCCAlugAwIBAgIBBDANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJLUjEN
-MAsGA1UECgwES0lTQTEuMCwGA1UECwwlS29yZWEgQ2VydGlmaWNhdGlvbiBBdXRo
-b3JpdHkgQ2VudHJhbDEWMBQGA1UEAwwNS0lTQSBSb290Q0EgMTAeFw0wNTA4MjQw
-ODA1NDZaFw0yNTA4MjQwODA1NDZaMGQxCzAJBgNVBAYTAktSMQ0wCwYDVQQKDARL
-SVNBMS4wLAYDVQQLDCVLb3JlYSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBDZW50
-cmFsMRYwFAYDVQQDDA1LSVNBIFJvb3RDQSAxMIIBIDANBgkqhkiG9w0BAQEFAAOC
-AQ0AMIIBCAKCAQEAvATk+hM58DSWIGtsaLv623f/J/es7C/n/fB/bW+MKs0lCVsk
-9KFo/CjsySXirO3eyDOE9bClCTqnsUdIxcxPjHmc+QZXfd3uOPbPFLKc6tPAXXdi
-8EcNuRpAU1xkcK8IWsD3z3X5bI1kKB4g/rcbGdNaZoNy4rCbvdMlFQ0yb2Q3lIVG
-yHK+d9VuHygvx2nt54OJM1jT3qC/QOhDUO7cTWu8peqmyGGO9cNkrwYV3CmLP3WM
-vHFE2/yttRcdbYmDz8Yzvb9Fov4Kn6MRXw+5H5wawkbMnChmn3AmPC7fqoD+jMUE
-CSVPzZNHPDfqAmeS/vwiJFys0izgXAEzisEZ2wIBA6MyMDAwHQYDVR0OBBYEFL+2
-J9gDWnZlTGEBQVYx5Yt7OtnMMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEF
-BQADggEBABOvUQveimpb5poKyLGQSk6hAp3MiNKrZr097LuxQpVqslxa/6FjZJap
-aBV/JV6K+KRzwYCKhQoOUugy50X4TmWAkZl0Q+VFnUkq8JSV3enhMNITbslOsXfl
-BM+tWh6UCVrXPAgcrnrpFDLBRa3SJkhyrKhB2vAhhzle3/xk/2F0KpzZm4tfwjeT
-2KM3LzuTa7IbB6d/CVDv0zq+IWuKkDsnSlFOa56ch534eJAx7REnxqhZvvwYC/uO
-fi5C4e3nCSG9uRPFVmf0JqZCQ5BEVLRxm3bkGhKsGigA35vB1fjbXKP4krG9tNT5
-UNkAAk/bg9ART6RCVmE6fhMy04Qfybo=
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 4 (0x4)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=KR, O=KISA, OU=Korea Certification Authority Central, CN=KISA RootCA 1
- Validity
- Not Before: Aug 24 08:05:46 2005 GMT
- Not After : Aug 24 08:05:46 2025 GMT
- Subject: C=KR, O=KISA, OU=Korea Certification Authority Central, CN=KISA RootCA 1
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (2048 bit)
- Modulus:
- 00:bc:04:e4:fa:13:39:f0:34:96:20:6b:6c:68:bb:
- fa:db:77:ff:27:f7:ac:ec:2f:e7:fd:f0:7f:6d:6f:
- 8c:2a:cd:25:09:5b:24:f4:a1:68:fc:28:ec:c9:25:
- e2:ac:ed:de:c8:33:84:f5:b0:a5:09:3a:a7:b1:47:
- 48:c5:cc:4f:8c:79:9c:f9:06:57:7d:dd:ee:38:f6:
- cf:14:b2:9c:ea:d3:c0:5d:77:62:f0:47:0d:b9:1a:
- 40:53:5c:64:70:af:08:5a:c0:f7:cf:75:f9:6c:8d:
- 64:28:1e:20:fe:b7:1b:19:d3:5a:66:83:72:e2:b0:
- 9b:bd:d3:25:15:0d:32:6f:64:37:94:85:46:c8:72:
- be:77:d5:6e:1f:28:2f:c7:69:ed:e7:83:89:33:58:
- d3:de:a0:bf:40:e8:43:50:ee:dc:4d:6b:bc:a5:ea:
- a6:c8:61:8e:f5:c3:64:af:06:15:dc:29:8b:3f:75:
- 8c:bc:71:44:db:fc:ad:b5:17:1d:6d:89:83:cf:c6:
- 33:bd:bf:45:a2:fe:0a:9f:a3:11:5f:0f:b9:1f:9c:
- 1a:c2:46:cc:9c:28:66:9f:70:26:3c:2e:df:aa:80:
- fe:8c:c5:04:09:25:4f:cd:93:47:3c:37:ea:02:67:
- 92:fe:fc:22:24:5c:ac:d2:2c:e0:5c:01:33:8a:c1:
- 19:db
- Exponent: 3 (0x3)
- X509v3 extensions:
- X509v3 Subject Key Identifier:
- BF:B6:27:D8:03:5A:76:65:4C:61:01:41:56:31:E5:8B:7B:3A:D9:CC
- X509v3 Basic Constraints: critical
- CA:TRUE
- Signature Algorithm: sha1WithRSAEncryption
- 13:af:51:0b:de:8a:6a:5b:e6:9a:0a:c8:b1:90:4a:4e:a1:02:
- 9d:cc:88:d2:ab:66:bd:3d:ec:bb:b1:42:95:6a:b2:5c:5a:ff:
- a1:63:64:96:a9:68:15:7f:25:5e:8a:f8:a4:73:c1:80:8a:85:
- 0a:0e:52:e8:32:e7:45:f8:4e:65:80:91:99:74:43:e5:45:9d:
- 49:2a:f0:94:95:dd:e9:e1:30:d2:13:6e:c9:4e:b1:77:e5:04:
- cf:ad:5a:1e:94:09:5a:d7:3c:08:1c:ae:7a:e9:14:32:c1:45:
- ad:d2:26:48:72:ac:a8:41:da:f0:21:87:39:5e:df:fc:64:ff:
- 61:74:2a:9c:d9:9b:8b:5f:c2:37:93:d8:a3:37:2f:3b:93:6b:
- b2:1b:07:a7:7f:09:50:ef:d3:3a:be:21:6b:8a:90:3b:27:4a:
- 51:4e:6b:9e:9c:87:9d:f8:78:90:31:ed:11:27:c6:a8:59:be:
- fc:18:0b:fb:8e:7e:2e:42:e1:ed:e7:09:21:bd:b9:13:c5:56:
- 67:f4:26:a6:42:43:90:44:54:b4:71:9b:76:e4:1a:12:ac:1a:
- 28:00:df:9b:c1:d5:f8:db:5c:a3:f8:92:b1:bd:b4:d4:f9:50:
- d9:00:02:4f:db:83:d0:11:4f:a4:42:56:61:3a:7e:13:32:d3:
- 84:1f:c9:ba
-SHA1 Fingerprint=02:72:68:29:3E:5F:5D:17:AA:A4:B3:C3:E6:36:1E:1F:92:57:5E:AA
diff --git a/luni/src/main/files/cacerts/52b525c7.0 b/luni/src/main/files/cacerts/52b525c7.0
new file mode 100644
index 0000000..98adef0
--- /dev/null
+++ b/luni/src/main/files/cacerts/52b525c7.0
@@ -0,0 +1,120 @@
+-----BEGIN CERTIFICATE-----
+MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL
+BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc
+BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00
+MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
+aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG
+SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV
+wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe
+rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341
+68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh
+4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp
+UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o
+abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc
+3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G
+KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt
+hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO
+Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt
+zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
+BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD
+ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC
+MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2
+cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN
+qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5
+YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv
+b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2
+8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k
+NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj
+ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp
+q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt
+nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 78:58:5f:2e:ad:2c:19:4b:e3:37:07:35:34:13:28:b5:96:d4:65:93
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 1 G3
+ Validity
+ Not Before: Jan 12 17:27:44 2012 GMT
+ Not After : Jan 12 17:27:44 2042 GMT
+ Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 1 G3
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:a0:be:50:10:8e:e9:f2:6c:40:b4:04:9c:85:b9:
+ 31:ca:dc:2d:e4:11:a9:04:3c:1b:55:c1:e7:58:30:
+ 1d:24:b4:c3:ef:85:de:8c:2c:e1:c1:3d:df:82:e6:
+ 4f:ad:47:87:6c:ec:5b:49:c1:4a:d5:bb:8f:ec:87:
+ ac:7f:82:9a:86:ec:3d:03:99:52:01:d2:35:9e:ac:
+ da:f0:53:c9:66:3c:d4:ac:02:01:da:24:d3:3b:a8:
+ 02:46:af:a4:1c:e3:f8:73:58:76:b7:f6:0e:90:0d:
+ b5:f0:cf:cc:fa:f9:c6:4c:e5:c3:86:30:0a:8d:17:
+ 7e:35:eb:c5:df:bb:0e:9c:c0:8d:87:e3:88:38:85:
+ 67:fa:3e:c7:ab:e0:13:9c:05:18:98:cf:93:f5:b1:
+ 92:b4:fc:23:d3:cf:d5:c4:27:49:e0:9e:3c:9b:08:
+ a3:8b:5d:2a:21:e0:fc:39:aa:53:da:7d:7e:cf:1a:
+ 09:53:bc:5d:05:04:cf:a1:4a:8f:8b:76:82:0d:a1:
+ f8:d2:c7:14:77:5b:90:36:07:81:9b:3e:06:fa:52:
+ 5e:63:c5:a6:00:fe:a5:e9:52:1b:52:b5:92:39:72:
+ 03:09:62:bd:b0:60:16:6e:a6:dd:25:c2:03:66:dd:
+ f3:04:d1:40:e2:4e:8b:86:f4:6f:e5:83:a0:27:84:
+ 5e:04:c1:f5:90:bd:30:3d:c4:ef:a8:69:bc:38:9b:
+ a4:a4:96:d1:62:da:69:c0:01:96:ae:cb:c4:51:34:
+ ea:0c:aa:ff:21:8e:59:8f:4a:5c:e4:61:9a:a7:d2:
+ e9:2a:78:8d:51:3d:3a:15:ee:a2:59:8e:a9:5c:de:
+ c5:f9:90:22:e5:88:45:71:dd:91:99:6c:7a:9f:3d:
+ 3d:98:7c:5e:f6:be:16:68:a0:5e:ae:0b:23:fc:5a:
+ 0f:aa:22:76:2d:c9:a1:10:1d:e4:d3:44:23:90:88:
+ 9f:c6:2a:e6:d7:f5:9a:b3:58:1e:2f:30:89:08:1b:
+ 54:a2:b5:98:23:ec:08:77:1c:95:5d:61:d1:cb:89:
+ 9c:5f:a2:4a:91:9a:ef:21:aa:49:16:08:a8:bd:61:
+ 28:31:c9:74:ad:85:f6:d9:c5:b1:8b:d1:e5:10:32:
+ 4d:5f:8b:20:3a:3c:49:1f:33:85:59:0d:db:cb:09:
+ 75:43:69:73:fb:6b:71:7d:f0:df:c4:4c:7d:c6:a3:
+ 2e:c8:95:79:cb:73:a2:8e:4e:4d:24:fb:5e:e4:04:
+ be:72:1b:a6:27:2d:49:5a:99:7a:d7:5c:09:20:b7:
+ 7f:94:b9:4f:f1:0d:1c:5e:88:42:1b:11:b7:e7:91:
+ db:9e:6c:f4:6a:df:8c:06:98:03:ad:cc:28:ef:a5:
+ 47:f3:53
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ A3:97:D6:F3:5E:A2:10:E1:AB:45:9F:3C:17:64:3C:EE:01:70:9C:CC
+ Signature Algorithm: sha256WithRSAEncryption
+ 18:fa:5b:75:fc:3e:7a:c7:5f:77:c7:ca:df:cf:5f:c3:12:c4:
+ 40:5d:d4:32:aa:b8:6a:d7:d5:15:15:46:98:23:a5:e6:90:5b:
+ 18:99:4c:e3:ad:42:a3:82:31:36:88:cd:e9:fb:c4:04:96:48:
+ 8b:01:c7:8d:01:cf:5b:33:06:96:46:66:74:1d:4f:ed:c1:b6:
+ b9:b4:0d:61:cc:63:7e:d7:2e:77:8c:96:1c:2a:23:68:6b:85:
+ 57:76:70:33:13:fe:e1:4f:a6:23:77:18:fa:1a:8c:e8:bd:65:
+ c9:cf:3f:f4:c9:17:dc:eb:c7:bc:c0:04:2e:2d:46:2f:69:66:
+ c3:1b:8f:fe:ec:3e:d3:ca:94:bf:76:0a:25:0d:a9:7b:02:1c:
+ a9:d0:3b:5f:0b:c0:81:3a:3d:64:e1:bf:a7:2d:4e:bd:4d:c4:
+ d8:29:c6:22:18:d0:c5:ac:72:02:82:3f:aa:3a:a2:3a:22:97:
+ 31:dd:08:63:c3:75:14:b9:60:28:2d:5b:68:e0:16:a9:66:82:
+ 23:51:f5:eb:53:d8:31:9b:7b:e9:b7:9d:4b:eb:88:16:cf:f9:
+ 5d:38:8a:49:30:8f:ed:f1:eb:19:f4:77:1a:31:18:4d:67:54:
+ 6c:2f:6f:65:f9:db:3d:ec:21:ec:5e:f4:f4:8b:ca:60:65:54:
+ d1:71:64:f4:f9:a6:a3:81:33:36:33:71:f0:a4:78:5f:4e:ad:
+ 83:21:de:34:49:8d:e8:59:ac:9d:f2:76:5a:36:f2:13:f4:af:
+ e0:09:c7:61:2a:6c:f7:e0:9d:ae:bb:86:4a:28:6f:2e:ee:b4:
+ 79:cd:90:33:c3:b3:76:fa:f5:f0:6c:9d:01:90:fa:9e:90:f6:
+ 9c:72:cf:47:da:c3:1f:e4:35:20:53:f2:54:d1:df:61:83:a6:
+ 02:e2:25:38:de:85:32:2d:5e:73:90:52:5d:42:c4:ce:3d:4b:
+ e1:f9:19:84:1d:d5:a2:50:cc:41:fb:41:14:c3:bd:d6:c9:5a:
+ a3:63:66:02:80:bd:05:3a:3b:47:9c:ec:00:26:4c:f5:88:51:
+ bf:a8:23:7f:18:07:b0:0b:ed:8b:26:a1:64:d3:61:4a:eb:5c:
+ 9f:de:b3:af:67:03:b3:1f:dd:6d:5d:69:68:69:ab:5e:3a:ec:
+ 7c:69:bc:c7:3b:85:4e:9e:15:b9:b4:15:4f:c3:95:7a:58:d7:
+ c9:6c:e9:6c:b9:f3:29:63:5e:b4:2c:f0:2d:3d:ed:5a:65:e0:
+ a9:5b:40:c2:48:99:81:6d:9e:1f:06:2a:3c:12:b4:8b:0f:9b:
+ a2:24:f0:a6:8d:d6:7a:e0:4b:b6:64:96:63:95:84:c2:4a:cd:
+ 1c:2e:24:87:33:60:e5:c3
+SHA1 Fingerprint=1B:8E:EA:57:96:29:1A:C9:39:EA:B8:0A:81:1A:73:73:C0:93:79:67
diff --git a/luni/src/main/files/cacerts/5a5372fc.0 b/luni/src/main/files/cacerts/5a5372fc.0
deleted file mode 100644
index b69d119..0000000
--- a/luni/src/main/files/cacerts/5a5372fc.0
+++ /dev/null
@@ -1,74 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFSzCCBLSgAwIBAgIBaTANBgkqhkiG9w0BAQQFADCBmTELMAkGA1UEBhMCSFUx
-ETAPBgNVBAcTCEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0
-b25zYWdpIEtmdC4xGjAYBgNVBAsTEVRhbnVzaXR2YW55a2lhZG9rMTIwMAYDVQQD
-EylOZXRMb2NrIFV6bGV0aSAoQ2xhc3MgQikgVGFudXNpdHZhbnlraWFkbzAeFw05
-OTAyMjUxNDEwMjJaFw0xOTAyMjAxNDEwMjJaMIGZMQswCQYDVQQGEwJIVTERMA8G
-A1UEBxMIQnVkYXBlc3QxJzAlBgNVBAoTHk5ldExvY2sgSGFsb3phdGJpenRvbnNh
-Z2kgS2Z0LjEaMBgGA1UECxMRVGFudXNpdHZhbnlraWFkb2sxMjAwBgNVBAMTKU5l
-dExvY2sgVXpsZXRpIChDbGFzcyBCKSBUYW51c2l0dmFueWtpYWRvMIGfMA0GCSqG
-SIb3DQEBAQUAA4GNADCBiQKBgQCx6gTsIKAjwo84YM/HRrPVG/77uZmeBNwcf4xK
-gZjupNTKihe5In+DCnVMm8Bp2GQ5o+2So/1bXHQawEfKOml2mrriRBf8TKPV/riX
-iK+IA4kfpPIEPsgHC+b5sy96YhQJRhTKZPWLgLViqNhr1nGTLbO/CVRY7QbrqHvc
-Q7GhaQIDAQABo4ICnzCCApswEgYDVR0TAQH/BAgwBgEB/wIBBDAOBgNVHQ8BAf8E
-BAMCAAYwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaCAk1G
-SUdZRUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFu
-b3MgU3pvbGdhbHRhdGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBh
-bGFwamFuIGtlc3p1bHQuIEEgaGl0ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExv
-Y2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2VnLWJpenRvc2l0YXNhIHZlZGkuIEEgZGln
-aXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0ZXRlbGUgYXogZWxvaXJ0
-IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFzIGxlaXJh
-c2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGph
-biBhIGh0dHBzOi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJo
-ZXRvIGF6IGVsbGVub3J6ZXNAbmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBP
-UlRBTlQhIFRoZSBpc3N1YW5jZSBhbmQgdGhlIHVzZSBvZiB0aGlzIGNlcnRpZmlj
-YXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sgQ1BTIGF2YWlsYWJsZSBhdCBo
-dHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFpbCBhdCBjcHNA
-bmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4GBAATbrowXr/gOkDFOzT4JwG06
-sPgzTEdM43WIEJessDgVkcYplswhwG08pXTP2IKlOcNl40JwuyKQ433bNXbhoLXa
-n3BukxowOR0w2y7jfLKRstE3Kfq51hdcR0/jHTjrn9V7lagonhVK0dHQKwCXoOKS
-NitjrFgBazMpUIaD8QFI
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 105 (0x69)
- Signature Algorithm: md5WithRSAEncryption
- Issuer: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Uzleti (Class B) Tanusitvanykiado
- Validity
- Not Before: Feb 25 14:10:22 1999 GMT
- Not After : Feb 20 14:10:22 2019 GMT
- Subject: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Uzleti (Class B) Tanusitvanykiado
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:b1:ea:04:ec:20:a0:23:c2:8f:38:60:cf:c7:46:
- b3:d5:1b:fe:fb:b9:99:9e:04:dc:1c:7f:8c:4a:81:
- 98:ee:a4:d4:ca:8a:17:b9:22:7f:83:0a:75:4c:9b:
- c0:69:d8:64:39:a3:ed:92:a3:fd:5b:5c:74:1a:c0:
- 47:ca:3a:69:76:9a:ba:e2:44:17:fc:4c:a3:d5:fe:
- b8:97:88:af:88:03:89:1f:a4:f2:04:3e:c8:07:0b:
- e6:f9:b3:2f:7a:62:14:09:46:14:ca:64:f5:8b:80:
- b5:62:a8:d8:6b:d6:71:93:2d:b3:bf:09:54:58:ed:
- 06:eb:a8:7b:dc:43:b1:a1:69
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints: critical
- CA:TRUE, pathlen:4
- X509v3 Key Usage: critical
- Certificate Sign, CRL Sign
- Netscape Cert Type:
- SSL CA, S/MIME CA, Object Signing CA
- Netscape Comment:
- FIGYELEM! Ezen tanusitvany a NetLock Kft. Altalanos Szolgaltatasi Felteteleiben leirt eljarasok alapjan keszult. A hitelesites folyamatat a NetLock Kft. termekfelelosseg-biztositasa vedi. A digitalis alairas elfogadasanak feltetele az eloirt ellenorzesi eljaras megtetele. Az eljaras leirasa megtalalhato a NetLock Kft. Internet honlapjan a https://www.netlock.net/docs cimen vagy kerheto az ellenorzes@netlock.net e-mail cimen. IMPORTANT! The issuance and the use of this certificate is subject to the NetLock CPS available at https://www.netlock.net/docs or by e-mail at cps@netlock.net.
- Signature Algorithm: md5WithRSAEncryption
- 04:db:ae:8c:17:af:f8:0e:90:31:4e:cd:3e:09:c0:6d:3a:b0:
- f8:33:4c:47:4c:e3:75:88:10:97:ac:b0:38:15:91:c6:29:96:
- cc:21:c0:6d:3c:a5:74:cf:d8:82:a5:39:c3:65:e3:42:70:bb:
- 22:90:e3:7d:db:35:76:e1:a0:b5:da:9f:70:6e:93:1a:30:39:
- 1d:30:db:2e:e3:7c:b2:91:b2:d1:37:29:fa:b9:d6:17:5c:47:
- 4f:e3:1d:38:eb:9f:d5:7b:95:a8:28:9e:15:4a:d1:d1:d0:2b:
- 00:97:a0:e2:92:36:2b:63:ac:58:01:6b:33:29:50:86:83:f1:
- 01:48
-SHA1 Fingerprint=87:9F:4B:EE:05:DF:98:58:3B:E3:60:D6:33:E7:0D:3F:FE:98:71:AF
diff --git a/luni/src/main/files/cacerts/635ccfd5.0 b/luni/src/main/files/cacerts/635ccfd5.0
deleted file mode 100644
index 79753cd..0000000
--- a/luni/src/main/files/cacerts/635ccfd5.0
+++ /dev/null
@@ -1,74 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFTzCCBLigAwIBAgIBaDANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCSFUx
-ETAPBgNVBAcTCEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0
-b25zYWdpIEtmdC4xGjAYBgNVBAsTEVRhbnVzaXR2YW55a2lhZG9rMTQwMgYDVQQD
-EytOZXRMb2NrIEV4cHJlc3N6IChDbGFzcyBDKSBUYW51c2l0dmFueWtpYWRvMB4X
-DTk5MDIyNTE0MDgxMVoXDTE5MDIyMDE0MDgxMVowgZsxCzAJBgNVBAYTAkhVMREw
-DwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6dG9u
-c2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE0MDIGA1UEAxMr
-TmV0TG9jayBFeHByZXNzeiAoQ2xhc3MgQykgVGFudXNpdHZhbnlraWFkbzCBnzAN
-BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA6+ywbGGKIyWvYCDj2Z/8kwvbXY2wobNA
-OoLO/XXgeDIDhlqGlZHtU/qdQPzm6N3ZW3oDvV3zOwzDUXmbrVWg6dADEK8KuhRC
-2VImESLH0iDMgqSaqf64gXadarfSNnU+sYYJ9m5tfk63euyucYT2BDMIJTLrdKwW
-RMbkQJMdf60CAwEAAaOCAp8wggKbMBIGA1UdEwEB/wQIMAYBAf8CAQQwDgYDVR0P
-AQH/BAQDAgAGMBEGCWCGSAGG+EIBAQQEAwIABzCCAmAGCWCGSAGG+EIBDQSCAlEW
-ggJNRklHWUVMRU0hIEV6ZW4gdGFudXNpdHZhbnkgYSBOZXRMb2NrIEtmdC4gQWx0
-YWxhbm9zIFN6b2xnYWx0YXRhc2kgRmVsdGV0ZWxlaWJlbiBsZWlydCBlbGphcmFz
-b2sgYWxhcGphbiBrZXN6dWx0LiBBIGhpdGVsZXNpdGVzIGZvbHlhbWF0YXQgYSBO
-ZXRMb2NrIEtmdC4gdGVybWVrZmVsZWxvc3NlZy1iaXp0b3NpdGFzYSB2ZWRpLiBB
-IGRpZ2l0YWxpcyBhbGFpcmFzIGVsZm9nYWRhc2FuYWsgZmVsdGV0ZWxlIGF6IGVs
-b2lydCBlbGxlbm9yemVzaSBlbGphcmFzIG1lZ3RldGVsZS4gQXogZWxqYXJhcyBs
-ZWlyYXNhIG1lZ3RhbGFsaGF0byBhIE5ldExvY2sgS2Z0LiBJbnRlcm5ldCBob25s
-YXBqYW4gYSBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIGNpbWVuIHZhZ3kg
-a2VyaGV0byBheiBlbGxlbm9yemVzQG5ldGxvY2submV0IGUtbWFpbCBjaW1lbi4g
-SU1QT1JUQU5UISBUaGUgaXNzdWFuY2UgYW5kIHRoZSB1c2Ugb2YgdGhpcyBjZXJ0
-aWZpY2F0ZSBpcyBzdWJqZWN0IHRvIHRoZSBOZXRMb2NrIENQUyBhdmFpbGFibGUg
-YXQgaHR0cHM6Ly93d3cubmV0bG9jay5uZXQvZG9jcyBvciBieSBlLW1haWwgYXQg
-Y3BzQG5ldGxvY2submV0LjANBgkqhkiG9w0BAQQFAAOBgQAQrX/XDDKACtiG8XmY
-ta3UzbM2xJZIwVzNmtkFLp++UOv0JhQQLdRmF/iewSf98e3ke0ugbLWrmldwpu2g
-pO0u9f38vf5NNwgMvOOWgyL1SRt/Syu0VMGAfJlOHdCM7tCs5ZL6dVb+ZKATj7i4
-Fp1hBWeAyNDYpQcCNJgEjTME1A==
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 104 (0x68)
- Signature Algorithm: md5WithRSAEncryption
- Issuer: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Expressz (Class C) Tanusitvanykiado
- Validity
- Not Before: Feb 25 14:08:11 1999 GMT
- Not After : Feb 20 14:08:11 2019 GMT
- Subject: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Expressz (Class C) Tanusitvanykiado
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:eb:ec:b0:6c:61:8a:23:25:af:60:20:e3:d9:9f:
- fc:93:0b:db:5d:8d:b0:a1:b3:40:3a:82:ce:fd:75:
- e0:78:32:03:86:5a:86:95:91:ed:53:fa:9d:40:fc:
- e6:e8:dd:d9:5b:7a:03:bd:5d:f3:3b:0c:c3:51:79:
- 9b:ad:55:a0:e9:d0:03:10:af:0a:ba:14:42:d9:52:
- 26:11:22:c7:d2:20:cc:82:a4:9a:a9:fe:b8:81:76:
- 9d:6a:b7:d2:36:75:3e:b1:86:09:f6:6e:6d:7e:4e:
- b7:7a:ec:ae:71:84:f6:04:33:08:25:32:eb:74:ac:
- 16:44:c6:e4:40:93:1d:7f:ad
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints: critical
- CA:TRUE, pathlen:4
- X509v3 Key Usage: critical
- Certificate Sign, CRL Sign
- Netscape Cert Type:
- SSL CA, S/MIME CA, Object Signing CA
- Netscape Comment:
- FIGYELEM! Ezen tanusitvany a NetLock Kft. Altalanos Szolgaltatasi Felteteleiben leirt eljarasok alapjan keszult. A hitelesites folyamatat a NetLock Kft. termekfelelosseg-biztositasa vedi. A digitalis alairas elfogadasanak feltetele az eloirt ellenorzesi eljaras megtetele. Az eljaras leirasa megtalalhato a NetLock Kft. Internet honlapjan a https://www.netlock.net/docs cimen vagy kerheto az ellenorzes@netlock.net e-mail cimen. IMPORTANT! The issuance and the use of this certificate is subject to the NetLock CPS available at https://www.netlock.net/docs or by e-mail at cps@netlock.net.
- Signature Algorithm: md5WithRSAEncryption
- 10:ad:7f:d7:0c:32:80:0a:d8:86:f1:79:98:b5:ad:d4:cd:b3:
- 36:c4:96:48:c1:5c:cd:9a:d9:05:2e:9f:be:50:eb:f4:26:14:
- 10:2d:d4:66:17:f8:9e:c1:27:fd:f1:ed:e4:7b:4b:a0:6c:b5:
- ab:9a:57:70:a6:ed:a0:a4:ed:2e:f5:fd:fc:bd:fe:4d:37:08:
- 0c:bc:e3:96:83:22:f5:49:1b:7f:4b:2b:b4:54:c1:80:7c:99:
- 4e:1d:d0:8c:ee:d0:ac:e5:92:fa:75:56:fe:64:a0:13:8f:b8:
- b8:16:9d:61:05:67:80:c8:d0:d8:a5:07:02:34:98:04:8d:33:
- 04:d4
-SHA1 Fingerprint=E3:92:51:2F:0A:CF:F5:05:DF:F6:DE:06:7F:75:37:E1:65:EA:57:4B
diff --git a/luni/src/main/files/cacerts/6adf0799.0 b/luni/src/main/files/cacerts/6adf0799.0
deleted file mode 100644
index 74b4813..0000000
--- a/luni/src/main/files/cacerts/6adf0799.0
+++ /dev/null
@@ -1,80 +0,0 @@
------BEGIN CERTIFICATE-----
-MIID5TCCAs2gAwIBAgIEOeSXnjANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UEBhMC
-VVMxFDASBgNVBAoTC1dlbGxzIEZhcmdvMSwwKgYDVQQLEyNXZWxscyBGYXJnbyBD
-ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEvMC0GA1UEAxMmV2VsbHMgRmFyZ28gUm9v
-dCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDAxMDExMTY0MTI4WhcNMjEwMTE0
-MTY0MTI4WjCBgjELMAkGA1UEBhMCVVMxFDASBgNVBAoTC1dlbGxzIEZhcmdvMSww
-KgYDVQQLEyNXZWxscyBGYXJnbyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEvMC0G
-A1UEAxMmV2VsbHMgRmFyZ28gUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEi
-MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDVqDM7Jvk0/82bfuUER84A4n13
-5zHCLielTWi5MbqNQ1mXx3Oqfz1cQJ4F5aHiidlMuD+b+Qy0yGIZLEWukR5zcUHE
-SxP9cMIlrCL1dQu3U+SlK93OvRw6esP3E48mVJwWa2uv+9iWsWCaSOAlIiR5NM4O
-JgALTqv9i86C1y8IcGjBqAr5dE8Hq6T54oN+J3N0Prj5OEL8pahbSCOz6+MlsoCu
-ltQKnMJ4msZoGK43YjdeUXWoWGPAUe5AeH6orxqg4bB4nVCMe+ez/I4jsNtlAHCE
-AQgAFG5Uhpq6zPk3EPbg3oQtnaSFN9OH4xXQwReQfhkhahKpdv0SAulPIV4XAgMB
-AAGjYTBfMA8GA1UdEwEB/wQFMAMBAf8wTAYDVR0gBEUwQzBBBgtghkgBhvt7hwcB
-CzAyMDAGCCsGAQUFBwIBFiRodHRwOi8vd3d3LndlbGxzZmFyZ28uY29tL2NlcnRw
-b2xpY3kwDQYJKoZIhvcNAQEFBQADggEBANIn3ZwKdyu7IvICtUpKkfnRLb7kuxpo
-7w6kAOnu5+/u9vnldKTC2FJYxHT7zmu1Oyl5GFrvm+0fazbuSCUlFLZWohDo7qd/
-0D+j0MNdJu4HzMPBJCGHHt8qElNvQRbn7a6U+oxy+hNH8Dx+rn0ROhPs7fpvcmR7
-nX1/Jv16+yWt6j4pf0zjAFcysLPp7VMX2YuyFA4w6OXVE8Zkr8QA1dhYJPz1j+zx
-x32l2w8n0cbyQIjmH/ZhqPRCyLk306m+LFZ4wnKbWV01QIroTmMatukgalHizqSQ
-33ZwmVxwQ023tqcZZE6St8WRPH9IFmV7Fv3L/PvZ1dZPIWU7Sn9Ho/s=
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 971282334 (0x39e4979e)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=US, O=Wells Fargo, OU=Wells Fargo Certification Authority, CN=Wells Fargo Root Certificate Authority
- Validity
- Not Before: Oct 11 16:41:28 2000 GMT
- Not After : Jan 14 16:41:28 2021 GMT
- Subject: C=US, O=Wells Fargo, OU=Wells Fargo Certification Authority, CN=Wells Fargo Root Certificate Authority
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (2048 bit)
- Modulus:
- 00:d5:a8:33:3b:26:f9:34:ff:cd:9b:7e:e5:04:47:
- ce:00:e2:7d:77:e7:31:c2:2e:27:a5:4d:68:b9:31:
- ba:8d:43:59:97:c7:73:aa:7f:3d:5c:40:9e:05:e5:
- a1:e2:89:d9:4c:b8:3f:9b:f9:0c:b4:c8:62:19:2c:
- 45:ae:91:1e:73:71:41:c4:4b:13:fd:70:c2:25:ac:
- 22:f5:75:0b:b7:53:e4:a5:2b:dd:ce:bd:1c:3a:7a:
- c3:f7:13:8f:26:54:9c:16:6b:6b:af:fb:d8:96:b1:
- 60:9a:48:e0:25:22:24:79:34:ce:0e:26:00:0b:4e:
- ab:fd:8b:ce:82:d7:2f:08:70:68:c1:a8:0a:f9:74:
- 4f:07:ab:a4:f9:e2:83:7e:27:73:74:3e:b8:f9:38:
- 42:fc:a5:a8:5b:48:23:b3:eb:e3:25:b2:80:ae:96:
- d4:0a:9c:c2:78:9a:c6:68:18:ae:37:62:37:5e:51:
- 75:a8:58:63:c0:51:ee:40:78:7e:a8:af:1a:a0:e1:
- b0:78:9d:50:8c:7b:e7:b3:fc:8e:23:b0:db:65:00:
- 70:84:01:08:00:14:6e:54:86:9a:ba:cc:f9:37:10:
- f6:e0:de:84:2d:9d:a4:85:37:d3:87:e3:15:d0:c1:
- 17:90:7e:19:21:6a:12:a9:76:fd:12:02:e9:4f:21:
- 5e:17
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints: critical
- CA:TRUE
- X509v3 Certificate Policies:
- Policy: 2.16.840.1.114171.903.1.11
- CPS: http://www.wellsfargo.com/certpolicy
-
- Signature Algorithm: sha1WithRSAEncryption
- d2:27:dd:9c:0a:77:2b:bb:22:f2:02:b5:4a:4a:91:f9:d1:2d:
- be:e4:bb:1a:68:ef:0e:a4:00:e9:ee:e7:ef:ee:f6:f9:e5:74:
- a4:c2:d8:52:58:c4:74:fb:ce:6b:b5:3b:29:79:18:5a:ef:9b:
- ed:1f:6b:36:ee:48:25:25:14:b6:56:a2:10:e8:ee:a7:7f:d0:
- 3f:a3:d0:c3:5d:26:ee:07:cc:c3:c1:24:21:87:1e:df:2a:12:
- 53:6f:41:16:e7:ed:ae:94:fa:8c:72:fa:13:47:f0:3c:7e:ae:
- 7d:11:3a:13:ec:ed:fa:6f:72:64:7b:9d:7d:7f:26:fd:7a:fb:
- 25:ad:ea:3e:29:7f:4c:e3:00:57:32:b0:b3:e9:ed:53:17:d9:
- 8b:b2:14:0e:30:e8:e5:d5:13:c6:64:af:c4:00:d5:d8:58:24:
- fc:f5:8f:ec:f1:c7:7d:a5:db:0f:27:d1:c6:f2:40:88:e6:1f:
- f6:61:a8:f4:42:c8:b9:37:d3:a9:be:2c:56:78:c2:72:9b:59:
- 5d:35:40:8a:e8:4e:63:1a:b6:e9:20:6a:51:e2:ce:a4:90:df:
- 76:70:99:5c:70:43:4d:b7:b6:a7:19:64:4e:92:b7:c5:91:3c:
- 7f:48:16:65:7b:16:fd:cb:fc:fb:d9:d5:d6:4f:21:65:3b:4a:
- 7f:47:a3:fb
-SHA1 Fingerprint=93:E6:AB:22:03:03:B5:23:28:DC:DA:56:9E:BA:E4:D1:D1:CC:FB:65
diff --git a/luni/src/main/files/cacerts/8d6437c3.0 b/luni/src/main/files/cacerts/8d6437c3.0
new file mode 100644
index 0000000..2097b64
--- /dev/null
+++ b/luni/src/main/files/cacerts/8d6437c3.0
@@ -0,0 +1,80 @@
+-----BEGIN CERTIFICATE-----
+MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv
+b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG
+EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl
+cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi
+MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA
+n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc
+biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp
+EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA
+bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu
+YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB
+AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW
+BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI
+QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I
+0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni
+lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9
+B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv
+ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo
+IhNzbM8m9Yop5w==
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 0b:93:1c:3a:d6:39:67:ea:67:23:bf:c3:af:9a:f4:4b
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G2
+ Validity
+ Not Before: Aug 1 12:00:00 2013 GMT
+ Not After : Jan 15 12:00:00 2038 GMT
+ Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G2
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (2048 bit)
+ Modulus:
+ 00:d9:e7:28:2f:52:3f:36:72:49:88:93:34:f3:f8:
+ 6a:1e:31:54:80:9f:ad:54:41:b5:47:df:96:a8:d4:
+ af:80:2d:b9:0a:cf:75:fd:89:a5:7d:24:fa:e3:22:
+ 0c:2b:bc:95:17:0b:33:bf:19:4d:41:06:90:00:bd:
+ 0c:4d:10:fe:07:b5:e7:1c:6e:22:55:31:65:97:bd:
+ d3:17:d2:1e:62:f3:db:ea:6c:50:8c:3f:84:0c:96:
+ cf:b7:cb:03:e0:ca:6d:a1:14:4c:1b:89:dd:ed:00:
+ b0:52:7c:af:91:6c:b1:38:13:d1:e9:12:08:c0:00:
+ b0:1c:2b:11:da:77:70:36:9b:ae:ce:79:87:dc:82:
+ 70:e6:09:74:70:55:69:af:a3:68:9f:bf:dd:b6:79:
+ b3:f2:9d:70:29:55:f4:ab:ff:95:61:f3:c9:40:6f:
+ 1d:d1:be:93:bb:d3:88:2a:bb:9d:bf:72:5a:56:71:
+ 3b:3f:d4:f3:d1:0a:fe:28:ef:a3:ee:d9:99:af:03:
+ d3:8f:60:b7:f2:92:a1:b1:bd:89:89:1f:30:cd:c3:
+ a6:2e:62:33:ae:16:02:77:44:5a:e7:81:0a:3c:a7:
+ 44:2e:79:b8:3f:04:bc:5c:a0:87:e1:1b:af:51:8e:
+ cd:ec:2c:fa:f8:fe:6d:f0:3a:7c:aa:8b:e4:67:95:
+ 31:8d
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Digital Signature, Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ CE:C3:4A:B9:99:55:F2:B8:DB:60:BF:A9:7E:BD:56:B5:97:36:A7:D6
+ Signature Algorithm: sha256WithRSAEncryption
+ ca:a5:55:8c:e3:c8:41:6e:69:27:a7:75:11:ef:3c:86:36:6f:
+ d2:9d:c6:78:38:1d:69:96:a2:92:69:2e:38:6c:9b:7d:04:d4:
+ 89:a5:b1:31:37:8a:c9:21:cc:ab:6c:cd:8b:1c:9a:d6:bf:48:
+ d2:32:66:c1:8a:c0:f3:2f:3a:ef:c0:e3:d4:91:86:d1:50:e3:
+ 03:db:73:77:6f:4a:39:53:ed:de:26:c7:b5:7d:af:2b:42:d1:
+ 75:62:e3:4a:2b:02:c7:50:4b:e0:69:e2:96:6c:0e:44:66:10:
+ 44:8f:ad:05:eb:f8:79:ac:a6:1b:e8:37:34:9d:53:c9:61:aa:
+ a2:52:af:4a:70:16:86:c2:3a:c8:b1:13:70:36:d8:cf:ee:f4:
+ 0a:34:d5:5b:4c:fd:07:9c:a2:ba:d9:01:72:5c:f3:4d:c1:dd:
+ 0e:b1:1c:0d:c4:63:be:ad:f4:14:fb:89:ec:a2:41:0e:4c:cc:
+ c8:57:40:d0:6e:03:aa:cd:0c:8e:89:99:99:6c:f0:3c:30:af:
+ 38:df:6f:bc:a3:be:29:20:27:ab:74:ff:13:22:78:de:97:52:
+ 55:1e:83:b5:54:20:03:ee:ae:c0:4f:56:de:37:cc:c3:7f:aa:
+ 04:27:bb:d3:77:b8:62:db:17:7c:9c:28:22:13:73:6c:cf:26:
+ f5:8a:29:e7
+SHA1 Fingerprint=A1:4B:48:D9:43:EE:0A:0E:40:90:4F:3C:E0:A4:C0:91:93:51:5D:3F
diff --git a/luni/src/main/files/cacerts/961f5451.0 b/luni/src/main/files/cacerts/961f5451.0
new file mode 100644
index 0000000..2a61cb0
--- /dev/null
+++ b/luni/src/main/files/cacerts/961f5451.0
@@ -0,0 +1,121 @@
+-----BEGIN CERTIFICATE-----
+MIIFdjCCA16gAwIBAgIQXmjWEXGUY1BWAGjzPsnFkTANBgkqhkiG9w0BAQUFADBV
+MQswCQYDVQQGEwJDTjEaMBgGA1UEChMRV29TaWduIENBIExpbWl0ZWQxKjAoBgNV
+BAMTIUNlcnRpZmljYXRpb24gQXV0aG9yaXR5IG9mIFdvU2lnbjAeFw0wOTA4MDgw
+MTAwMDFaFw0zOTA4MDgwMTAwMDFaMFUxCzAJBgNVBAYTAkNOMRowGAYDVQQKExFX
+b1NpZ24gQ0EgTGltaXRlZDEqMCgGA1UEAxMhQ2VydGlmaWNhdGlvbiBBdXRob3Jp
+dHkgb2YgV29TaWduMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvcqN
+rLiRFVaXe2tcesLea9mhsMMQI/qnobLMMfo+2aYpbxY94Gv4uEBf2zmoAHqLoE1U
+fcIiePyOCbiohdfMlZdLdNiefvAA5A6JrkkoRBoQmTIPJYhTpA2zDxIIFgsDcScc
+f+Hb0v1naMQFXQoOXXDX2JegvFNBmpGN9J42Znp+VsGQX+axaCA2pIwkLCxHC1l2
+ZjC1vt7tj/id07sBMOby8w7gLJKA84X5KIq0VC6a7fd2/BVoFutKbOsuEo/Uz/4M
+x1wdC34FMr5esAkqQtXJTpCzWQ27en7N1QhatH/YHGkR+ScPewavVIMYe+HdVHpR
+aG53/Ma/UkpmRqGyZxq7o093oL5d//xWC0Nyd5DKnvnyOfUNqfTq1+ezEC8wQjch
+zDBwyYaYD8xYTYO7feUapTeNtqwylwA6Y3EkHp43xP901DfA4v6IRmAR3Qg/UDar
+uHqklWJqbrDKaiFaafPz+x1wOZXzp26mgYmhiMU7ccqjUu6Du/2gd/Tkb+dC221K
+mYo0SLwX3OSACCK28jHAPwQ+658geda4BmRkAjHXqc1S+4RFaQkAKtxVi8QGRkvA
+Sh0JWzko/amrzgD5LkhLJuYwTKVYyrREgk/nkR4zw7CT/xH8gdLKH3Ep3XZPkiWv
+HYG3Dy+MwwbMLyejSuQOmbp8HkUff6oZRZb9/D0CAwEAAaNCMEAwDgYDVR0PAQH/
+BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFOFmzw7R8bNLtwYgFP6H
+EtX2/vs+MA0GCSqGSIb3DQEBBQUAA4ICAQCoy3JAsnbBfnv8rWTjMnvMPLZdRtP1
+LOJwXcgu2AZ9mNELIaCJWSQBnfmvCX0KI4I01fx8cpm5o9dU9OpScA7F9dY74ToJ
+MuYhOZO9sxXqT2r09Ys/L3yNWC7F4TmgPsc9SnOeQHrAK2GpZ8nzJLmzbVUsWh2e
+JXLOC62qx1ViC777Y7NhRCOjy+EaDveaBk3e1CNOIZZbOVtXHS9dCF4Jef98l7VN
+g64N1uajeeAz0JmWAjCnPv/So0M/BVoG6kQC2nz4SNAzqfkHx5Xh9T71XXG68pWp
+dIhhWeO/yloTunK0jF02h+mmxTwTv97QRCbut+wucPrXnbes5cVAWubXbHssw1ab
+R80LzvobtCHXt2a49CUwi1wNuepnsvRtrtWhnk/Yn+knArAdBtaP4/tIEp9/EaEQ
+PkxROpaw0RPxx9gmrjrKkcRpnd8BKWRRb2jaFOwIQZeQjdCygPLPwj2/kWjFgGce
+xGATVdVhmVd8upUPYUk6ynW8yQqTP2cOEvIo4jEbwFcW3wh8GcF+Dx+FHgo2fFt+
+J7x6v+Db9NpSvd4MVHAxkUOVyLzwPt0JfjBkUO1/AaQzZ01oT74V77D2AhGiGxMl
+OtzCWfHjXEa7ZywCRuoeSKbmW9m1vFGikpbbqsY3Iqb+zCB0oy2pLmvLwIIRIbWT
+ee5Ehr7XHuQe+w==
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 5e:68:d6:11:71:94:63:50:56:00:68:f3:3e:c9:c5:91
+ Signature Algorithm: sha1WithRSAEncryption
+ Issuer: C=CN, O=WoSign CA Limited, CN=Certification Authority of WoSign
+ Validity
+ Not Before: Aug 8 01:00:01 2009 GMT
+ Not After : Aug 8 01:00:01 2039 GMT
+ Subject: C=CN, O=WoSign CA Limited, CN=Certification Authority of WoSign
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:bd:ca:8d:ac:b8:91:15:56:97:7b:6b:5c:7a:c2:
+ de:6b:d9:a1:b0:c3:10:23:fa:a7:a1:b2:cc:31:fa:
+ 3e:d9:a6:29:6f:16:3d:e0:6b:f8:b8:40:5f:db:39:
+ a8:00:7a:8b:a0:4d:54:7d:c2:22:78:fc:8e:09:b8:
+ a8:85:d7:cc:95:97:4b:74:d8:9e:7e:f0:00:e4:0e:
+ 89:ae:49:28:44:1a:10:99:32:0f:25:88:53:a4:0d:
+ b3:0f:12:08:16:0b:03:71:27:1c:7f:e1:db:d2:fd:
+ 67:68:c4:05:5d:0a:0e:5d:70:d7:d8:97:a0:bc:53:
+ 41:9a:91:8d:f4:9e:36:66:7a:7e:56:c1:90:5f:e6:
+ b1:68:20:36:a4:8c:24:2c:2c:47:0b:59:76:66:30:
+ b5:be:de:ed:8f:f8:9d:d3:bb:01:30:e6:f2:f3:0e:
+ e0:2c:92:80:f3:85:f9:28:8a:b4:54:2e:9a:ed:f7:
+ 76:fc:15:68:16:eb:4a:6c:eb:2e:12:8f:d4:cf:fe:
+ 0c:c7:5c:1d:0b:7e:05:32:be:5e:b0:09:2a:42:d5:
+ c9:4e:90:b3:59:0d:bb:7a:7e:cd:d5:08:5a:b4:7f:
+ d8:1c:69:11:f9:27:0f:7b:06:af:54:83:18:7b:e1:
+ dd:54:7a:51:68:6e:77:fc:c6:bf:52:4a:66:46:a1:
+ b2:67:1a:bb:a3:4f:77:a0:be:5d:ff:fc:56:0b:43:
+ 72:77:90:ca:9e:f9:f2:39:f5:0d:a9:f4:ea:d7:e7:
+ b3:10:2f:30:42:37:21:cc:30:70:c9:86:98:0f:cc:
+ 58:4d:83:bb:7d:e5:1a:a5:37:8d:b6:ac:32:97:00:
+ 3a:63:71:24:1e:9e:37:c4:ff:74:d4:37:c0:e2:fe:
+ 88:46:60:11:dd:08:3f:50:36:ab:b8:7a:a4:95:62:
+ 6a:6e:b0:ca:6a:21:5a:69:f3:f3:fb:1d:70:39:95:
+ f3:a7:6e:a6:81:89:a1:88:c5:3b:71:ca:a3:52:ee:
+ 83:bb:fd:a0:77:f4:e4:6f:e7:42:db:6d:4a:99:8a:
+ 34:48:bc:17:dc:e4:80:08:22:b6:f2:31:c0:3f:04:
+ 3e:eb:9f:20:79:d6:b8:06:64:64:02:31:d7:a9:cd:
+ 52:fb:84:45:69:09:00:2a:dc:55:8b:c4:06:46:4b:
+ c0:4a:1d:09:5b:39:28:fd:a9:ab:ce:00:f9:2e:48:
+ 4b:26:e6:30:4c:a5:58:ca:b4:44:82:4f:e7:91:1e:
+ 33:c3:b0:93:ff:11:fc:81:d2:ca:1f:71:29:dd:76:
+ 4f:92:25:af:1d:81:b7:0f:2f:8c:c3:06:cc:2f:27:
+ a3:4a:e4:0e:99:ba:7c:1e:45:1f:7f:aa:19:45:96:
+ fd:fc:3d
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Subject Key Identifier:
+ E1:66:CF:0E:D1:F1:B3:4B:B7:06:20:14:FE:87:12:D5:F6:FE:FB:3E
+ Signature Algorithm: sha1WithRSAEncryption
+ a8:cb:72:40:b2:76:c1:7e:7b:fc:ad:64:e3:32:7b:cc:3c:b6:
+ 5d:46:d3:f5:2c:e2:70:5d:c8:2e:d8:06:7d:98:d1:0b:21:a0:
+ 89:59:24:01:9d:f9:af:09:7d:0a:23:82:34:d5:fc:7c:72:99:
+ b9:a3:d7:54:f4:ea:52:70:0e:c5:f5:d6:3b:e1:3a:09:32:e6:
+ 21:39:93:bd:b3:15:ea:4f:6a:f4:f5:8b:3f:2f:7c:8d:58:2e:
+ c5:e1:39:a0:3e:c7:3d:4a:73:9e:40:7a:c0:2b:61:a9:67:c9:
+ f3:24:b9:b3:6d:55:2c:5a:1d:9e:25:72:ce:0b:ad:aa:c7:55:
+ 62:0b:be:fb:63:b3:61:44:23:a3:cb:e1:1a:0e:f7:9a:06:4d:
+ de:d4:23:4e:21:96:5b:39:5b:57:1d:2f:5d:08:5e:09:79:ff:
+ 7c:97:b5:4d:83:ae:0d:d6:e6:a3:79:e0:33:d0:99:96:02:30:
+ a7:3e:ff:d2:a3:43:3f:05:5a:06:ea:44:02:da:7c:f8:48:d0:
+ 33:a9:f9:07:c7:95:e1:f5:3e:f5:5d:71:ba:f2:95:a9:74:88:
+ 61:59:e3:bf:ca:5a:13:ba:72:b4:8c:5d:36:87:e9:a6:c5:3c:
+ 13:bf:de:d0:44:26:ee:b7:ec:2e:70:fa:d7:9d:b7:ac:e5:c5:
+ 40:5a:e6:d7:6c:7b:2c:c3:56:9b:47:cd:0b:ce:fa:1b:b4:21:
+ d7:b7:66:b8:f4:25:30:8b:5c:0d:b9:ea:67:b2:f4:6d:ae:d5:
+ a1:9e:4f:d8:9f:e9:27:02:b0:1d:06:d6:8f:e3:fb:48:12:9f:
+ 7f:11:a1:10:3e:4c:51:3a:96:b0:d1:13:f1:c7:d8:26:ae:3a:
+ ca:91:c4:69:9d:df:01:29:64:51:6f:68:da:14:ec:08:41:97:
+ 90:8d:d0:b2:80:f2:cf:c2:3d:bf:91:68:c5:80:67:1e:c4:60:
+ 13:55:d5:61:99:57:7c:ba:95:0f:61:49:3a:ca:75:bc:c9:0a:
+ 93:3f:67:0e:12:f2:28:e2:31:1b:c0:57:16:df:08:7c:19:c1:
+ 7e:0f:1f:85:1e:0a:36:7c:5b:7e:27:bc:7a:bf:e0:db:f4:da:
+ 52:bd:de:0c:54:70:31:91:43:95:c8:bc:f0:3e:dd:09:7e:30:
+ 64:50:ed:7f:01:a4:33:67:4d:68:4f:be:15:ef:b0:f6:02:11:
+ a2:1b:13:25:3a:dc:c2:59:f1:e3:5c:46:bb:67:2c:02:46:ea:
+ 1e:48:a6:e6:5b:d9:b5:bc:51:a2:92:96:db:aa:c6:37:22:a6:
+ fe:cc:20:74:a3:2d:a9:2e:6b:cb:c0:82:11:21:b5:93:79:ee:
+ 44:86:be:d7:1e:e4:1e:fb
+SHA1 Fingerprint=B9:42:94:BF:91:EA:8F:B6:4B:E6:10:97:C7:FB:00:13:59:B6:76:CB
diff --git a/luni/src/main/files/cacerts/a2c66da8.0 b/luni/src/main/files/cacerts/a2c66da8.0
new file mode 100644
index 0000000..f922408
--- /dev/null
+++ b/luni/src/main/files/cacerts/a2c66da8.0
@@ -0,0 +1,121 @@
+-----BEGIN CERTIFICATE-----
+MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg
+RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV
+UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu
+Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG
+SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y
+ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If
+xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV
+ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO
+DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ
+jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/
+CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi
+EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM
+fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY
+uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK
+chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t
+9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
+hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD
+ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2
+SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd
++SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc
+fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa
+sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N
+cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N
+0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie
+4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI
+r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1
+/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm
+gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 05:9b:1b:57:9e:8e:21:32:e2:39:07:bd:a7:77:75:5c
+ Signature Algorithm: sha384WithRSAEncryption
+ Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Trusted Root G4
+ Validity
+ Not Before: Aug 1 12:00:00 2013 GMT
+ Not After : Jan 15 12:00:00 2038 GMT
+ Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Trusted Root G4
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:bf:e6:90:73:68:de:bb:e4:5d:4a:3c:30:22:30:
+ 69:33:ec:c2:a7:25:2e:c9:21:3d:f2:8a:d8:59:c2:
+ e1:29:a7:3d:58:ab:76:9a:cd:ae:7b:1b:84:0d:c4:
+ 30:1f:f3:1b:a4:38:16:eb:56:c6:97:6d:1d:ab:b2:
+ 79:f2:ca:11:d2:e4:5f:d6:05:3c:52:0f:52:1f:c6:
+ 9e:15:a5:7e:be:9f:a9:57:16:59:55:72:af:68:93:
+ 70:c2:b2:ba:75:99:6a:73:32:94:d1:10:44:10:2e:
+ df:82:f3:07:84:e6:74:3b:6d:71:e2:2d:0c:1b:ee:
+ 20:d5:c9:20:1d:63:29:2d:ce:ec:5e:4e:c8:93:f8:
+ 21:61:9b:34:eb:05:c6:5e:ec:5b:1a:bc:eb:c9:cf:
+ cd:ac:34:40:5f:b1:7a:66:ee:77:c8:48:a8:66:57:
+ 57:9f:54:58:8e:0c:2b:b7:4f:a7:30:d9:56:ee:ca:
+ 7b:5d:e3:ad:c9:4f:5e:e5:35:e7:31:cb:da:93:5e:
+ dc:8e:8f:80:da:b6:91:98:40:90:79:c3:78:c7:b6:
+ b1:c4:b5:6a:18:38:03:10:8d:d8:d4:37:a4:2e:05:
+ 7d:88:f5:82:3e:10:91:70:ab:55:82:41:32:d7:db:
+ 04:73:2a:6e:91:01:7c:21:4c:d4:bc:ae:1b:03:75:
+ 5d:78:66:d9:3a:31:44:9a:33:40:bf:08:d7:5a:49:
+ a4:c2:e6:a9:a0:67:dd:a4:27:bc:a1:4f:39:b5:11:
+ 58:17:f7:24:5c:46:8f:64:f7:c1:69:88:76:98:76:
+ 3d:59:5d:42:76:87:89:97:69:7a:48:f0:e0:a2:12:
+ 1b:66:9a:74:ca:de:4b:1e:e7:0e:63:ae:e6:d4:ef:
+ 92:92:3a:9e:3d:dc:00:e4:45:25:89:b6:9a:44:19:
+ 2b:7e:c0:94:b4:d2:61:6d:eb:33:d9:c5:df:4b:04:
+ 00:cc:7d:1c:95:c3:8f:f7:21:b2:b2:11:b7:bb:7f:
+ f2:d5:8c:70:2c:41:60:aa:b1:63:18:44:95:1a:76:
+ 62:7e:f6:80:b0:fb:e8:64:a6:33:d1:89:07:e1:bd:
+ b7:e6:43:a4:18:b8:a6:77:01:e1:0f:94:0c:21:1d:
+ b2:54:29:25:89:6c:e5:0e:52:51:47:74:be:26:ac:
+ b6:41:75:de:7a:ac:5f:8d:3f:c9:bc:d3:41:11:12:
+ 5b:e5:10:50:eb:31:c5:ca:72:16:22:09:df:7c:4c:
+ 75:3f:63:ec:21:5f:c4:20:51:6b:6f:b1:ab:86:8b:
+ 4f:c2:d6:45:5f:9d:20:fc:a1:1e:c5:c0:8f:a2:b1:
+ 7e:0a:26:99:f5:e4:69:2f:98:1d:2d:f5:d9:a9:b2:
+ 1d:e5:1b
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Digital Signature, Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ EC:D7:E3:82:D2:71:5D:64:4C:DF:2E:67:3F:E7:BA:98:AE:1C:0F:4F
+ Signature Algorithm: sha384WithRSAEncryption
+ bb:61:d9:7d:a9:6c:be:17:c4:91:1b:c3:a1:a2:00:8d:e3:64:
+ 68:0f:56:cf:77:ae:70:f9:fd:9a:4a:99:b9:c9:78:5c:0c:0c:
+ 5f:e4:e6:14:29:56:0b:36:49:5d:44:63:e0:ad:9c:96:18:66:
+ 1b:23:0d:3d:79:e9:6d:6b:d6:54:f8:d2:3c:c1:43:40:ae:1d:
+ 50:f5:52:fc:90:3b:bb:98:99:69:6b:c7:c1:a7:a8:68:a4:27:
+ dc:9d:f9:27:ae:30:85:b9:f6:67:4d:3a:3e:8f:59:39:22:53:
+ 44:eb:c8:5d:03:ca:ed:50:7a:7d:62:21:0a:80:c8:73:66:d1:
+ a0:05:60:5f:e8:a5:b4:a7:af:a8:f7:6d:35:9c:7c:5a:8a:d6:
+ a2:38:99:f3:78:8b:f4:4d:d2:20:0b:de:04:ee:8c:9b:47:81:
+ 72:0d:c0:14:32:ef:30:59:2e:ae:e0:71:f2:56:e4:6a:97:6f:
+ 92:50:6d:96:8d:68:7a:9a:b2:36:14:7a:06:f2:24:b9:09:11:
+ 50:d7:08:b1:b8:89:7a:84:23:61:42:29:e5:a3:cd:a2:20:41:
+ d7:d1:9c:64:d9:ea:26:a1:8b:14:d7:4c:19:b2:50:41:71:3d:
+ 3f:4d:70:23:86:0c:4a:dc:81:d2:cc:32:94:84:0d:08:09:97:
+ 1c:4f:c0:ee:6b:20:74:30:d2:e0:39:34:10:85:21:15:01:08:
+ e8:55:32:de:71:49:d9:28:17:50:4d:e6:be:4d:d1:75:ac:d0:
+ ca:fb:41:b8:43:a5:aa:d3:c3:05:44:4f:2c:36:9b:e2:fa:e2:
+ 45:b8:23:53:6c:06:6f:67:55:7f:46:b5:4c:3f:6e:28:5a:79:
+ 26:d2:a4:a8:62:97:d2:1e:e2:ed:4a:8b:bc:1b:fd:47:4a:0d:
+ df:67:66:7e:b2:5b:41:d0:3b:e4:f4:3b:f4:04:63:e9:ef:c2:
+ 54:00:51:a0:8a:2a:c9:ce:78:cc:d5:ea:87:04:18:b3:ce:af:
+ 49:88:af:f3:92:99:b6:b3:e6:61:0f:d2:85:00:e7:50:1a:e4:
+ 1b:95:9d:19:a1:b9:9c:b1:9b:b1:00:1e:ef:d0:0f:4f:42:6c:
+ c9:0a:bc:ee:43:fa:3a:71:a5:c8:4d:26:a5:35:fd:89:5d:bc:
+ 85:62:1d:32:d2:a0:2b:54:ed:9a:57:c1:db:fa:10:cf:19:b7:
+ 8b:4a:1b:8f:01:b6:27:95:53:e8:b6:89:6d:5b:bc:68:d4:23:
+ e8:8b:51:a2:56:f9:f0:a6:80:a0:d6:1e:b3:bc:0f:0f:53:75:
+ 29:aa:ea:13:77:e4:de:8c:81:21:ad:07:10:47:11:ad:87:3d:
+ 07:d1:75:bc:cf:f3:66:7e
+SHA1 Fingerprint=DD:FB:16:CD:49:31:C9:73:A2:03:7D:3F:C8:3A:4D:7D:77:5D:05:E4
diff --git a/luni/src/main/files/cacerts/bcdd5959.0 b/luni/src/main/files/cacerts/bcdd5959.0
deleted file mode 100644
index 39e952b..0000000
--- a/luni/src/main/files/cacerts/bcdd5959.0
+++ /dev/null
@@ -1,52 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0
-IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz
-BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y
-aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG
-9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMTk1NFoXDTE5MDYy
-NjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y
-azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
-YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw
-Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl
-cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOOnHK5avIWZJV16vY
-dA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVCCSRrCl6zfN1SLUzm1NZ9
-WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7RfZHM047QS
-v4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9v
-UJSZSWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTu
-IYEZoDJJKPTEjlbVUjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwC
-W/POuZ6lcg5Ktz885hZo+L7tdEy8W9ViH0Pd
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 1 (0x0)
- Serial Number: 1 (0x1)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 2 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com
- Validity
- Not Before: Jun 26 00:19:54 1999 GMT
- Not After : Jun 26 00:19:54 2019 GMT
- Subject: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 2 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:ce:3a:71:ca:e5:ab:c8:59:92:55:d7:ab:d8:74:
- 0e:f9:ee:d9:f6:55:47:59:65:47:0e:05:55:dc:eb:
- 98:36:3c:5c:53:5d:d3:30:cf:38:ec:bd:41:89:ed:
- 25:42:09:24:6b:0a:5e:b3:7c:dd:52:2d:4c:e6:d4:
- d6:7d:5a:59:a9:65:d4:49:13:2d:24:4d:1c:50:6f:
- b5:c1:85:54:3b:fe:71:e4:d3:5c:42:f9:80:e0:91:
- 1a:0a:5b:39:36:67:f3:3f:55:7c:1b:3f:b4:5f:64:
- 73:34:e3:b4:12:bf:87:64:f8:da:12:ff:37:27:c1:
- b3:43:bb:ef:7b:6e:2e:69:f7
- Exponent: 65537 (0x10001)
- Signature Algorithm: sha1WithRSAEncryption
- 3b:7f:50:6f:6f:50:94:99:49:62:38:38:1f:4b:f8:a5:c8:3e:
- a7:82:81:f6:2b:c7:e8:c5:ce:e8:3a:10:82:cb:18:00:8e:4d:
- bd:a8:58:7f:a1:79:00:b5:bb:e9:8d:af:41:d9:0f:34:ee:21:
- 81:19:a0:32:49:28:f4:c4:8e:56:d5:52:33:fd:50:d5:7e:99:
- 6c:03:e4:c9:4c:fc:cb:6c:ab:66:b3:4a:21:8c:e5:b5:0c:32:
- 3e:10:b2:cc:6c:a1:dc:9a:98:4c:02:5b:f3:ce:b9:9e:a5:72:
- 0e:4a:b7:3f:3c:e6:16:68:f8:be:ed:74:4c:bc:5b:d5:62:1f:
- 43:dd
-SHA1 Fingerprint=31:7A:2A:D0:7F:2B:33:5E:F5:A1:C3:4E:4B:57:E8:B7:D8:F1:FC:A6
diff --git a/luni/src/main/files/cacerts/c491639e.0 b/luni/src/main/files/cacerts/c491639e.0
new file mode 100644
index 0000000..ec9e422
--- /dev/null
+++ b/luni/src/main/files/cacerts/c491639e.0
@@ -0,0 +1,53 @@
+-----BEGIN CERTIFICATE-----
+MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw
+CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu
+ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg
+RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV
+UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu
+Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq
+hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf
+Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q
+RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/
+BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD
+AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY
+JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv
+6pZjamVFkpUBtA==
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 0b:a1:5a:fa:1d:df:a0:b5:49:44:af:cd:24:a0:6c:ec
+ Signature Algorithm: ecdsa-with-SHA384
+ Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G3
+ Validity
+ Not Before: Aug 1 12:00:00 2013 GMT
+ Not After : Jan 15 12:00:00 2038 GMT
+ Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G3
+ Subject Public Key Info:
+ Public Key Algorithm: id-ecPublicKey
+ Public-Key: (384 bit)
+ pub:
+ 04:19:e7:bc:ac:44:65:ed:cd:b8:3f:58:fb:8d:b1:
+ 57:a9:44:2d:05:15:f2:ef:0b:ff:10:74:9f:b5:62:
+ 52:5f:66:7e:1f:e5:dc:1b:45:79:0b:cc:c6:53:0a:
+ 9d:8d:5d:02:d9:a9:59:de:02:5a:f6:95:2a:0e:8d:
+ 38:4a:8a:49:c6:bc:c6:03:38:07:5f:55:da:7e:09:
+ 6e:e2:7f:5e:d0:45:20:0f:59:76:10:d6:a0:24:f0:
+ 2d:de:36:f2:6c:29:39
+ ASN1 OID: secp384r1
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Digital Signature, Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ CB:D0:BD:A9:E1:98:05:51:A1:4D:37:A2:83:79:CE:8D:1D:2A:E4:84
+ Signature Algorithm: ecdsa-with-SHA384
+ 30:64:02:30:25:a4:81:45:02:6b:12:4b:75:74:4f:c8:23:e3:
+ 70:f2:75:72:de:7c:89:f0:cf:91:72:61:9e:5e:10:92:59:56:
+ b9:83:c7:10:e7:38:e9:58:26:36:7d:d5:e4:34:86:39:02:30:
+ 7c:36:53:f0:30:e5:62:63:3a:99:e2:b6:a3:3b:9b:34:fa:1e:
+ da:10:92:71:5e:91:13:a7:dd:a4:6e:92:cc:32:d6:f5:21:66:
+ c7:2f:ea:96:63:6a:65:45:92:95:01:b4
+SHA1 Fingerprint=F5:17:A2:4F:9A:48:C6:C9:F8:A2:00:26:9F:DC:0F:48:2C:AB:30:89
diff --git a/luni/src/main/files/cacerts/c8763593.0 b/luni/src/main/files/cacerts/c8763593.0
deleted file mode 100644
index 70675c7..0000000
--- a/luni/src/main/files/cacerts/c8763593.0
+++ /dev/null
@@ -1,132 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIGZjCCBE6gAwIBAgIPB35Sk3vgFeNX8GmMy+wMMA0GCSqGSIb3DQEBBQUAMHsx
-CzAJBgNVBAYTAkNPMUcwRQYDVQQKDD5Tb2NpZWRhZCBDYW1lcmFsIGRlIENlcnRp
-ZmljYWNpw7NuIERpZ2l0YWwgLSBDZXJ0aWPDoW1hcmEgUy5BLjEjMCEGA1UEAwwa
-QUMgUmHDrXogQ2VydGljw6FtYXJhIFMuQS4wHhcNMDYxMTI3MjA0NjI5WhcNMzAw
-NDAyMjE0MjAyWjB7MQswCQYDVQQGEwJDTzFHMEUGA1UECgw+U29jaWVkYWQgQ2Ft
-ZXJhbCBkZSBDZXJ0aWZpY2FjacOzbiBEaWdpdGFsIC0gQ2VydGljw6FtYXJhIFMu
-QS4xIzAhBgNVBAMMGkFDIFJhw616IENlcnRpY8OhbWFyYSBTLkEuMIICIjANBgkq
-hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAq2uJo1PMSCMI+8PPUZYILrgIem08kBeG
-qentLhM0R7LQcNzJPNCNyu5LF6vQhbCnIwTLqKL85XXbQMpiiY9QngE9JlsYhBzL
-fDe3fezTf3MZsGqy2IiKLUV0qPezuMDU2s0iiXRNWhU5cxh0T7XrmafBHoi0wpOQ
-Y5fzp6cSsgkiBzPZkc0OnB8OIMfuuzONj8LSWKdf/WU34ojC2I+GdV75LaeHM/J4
-Ny+LvB2GNzmxlPLYvEqcgxhaBvzz1NS6jBUJJfD5to0EfhcSM2tXSExP2yYe68yQ
-54v5aHxwD6Mq0Do43zeX4lvegGHTgNiRg0JaTASJaBE8rF9ogEHMYELODVoqDA+b
-MMCm8Ibbq0nXl21Ii/kDwFJnmxL3wvIumGVC2daa49AZMQyth9VXAnow6IYm+48j
-ilSH5L887uvDdUhfHjlvgWJsxS3EF1QZtzeNnDeRyPYL1epjb4OsOMLzP96a++Ej
-YfDIJss2yKHzMI+ko6Kh3VOz3vCaMh+DkXkwwakfU5tTohVTP92dsxA7SH2JD/zt
-A/X7JWR1DhcZDY8AFmd5ekD8LVkH2ZD6mq093ICK5lw1omdMEWux+IBkAC1vImHF
-rEsm5VoQgpukg3s0956JkSCXjrdCx2bD0Omk1vUgjcTDlaxECp1bczwmPS9KvqfJ
-pxAe+59QafMCAwEAAaOB5jCB4zAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE
-AwIBBjAdBgNVHQ4EFgQU0QnQ6dfOeXRU+Tows/RtLAMDG2gwgaAGA1UdIASBmDCB
-lTCBkgYEVR0gADCBiTArBggrBgEFBQcCARYfaHR0cDovL3d3dy5jZXJ0aWNhbWFy
-YS5jb20vZHBjLzBaBggrBgEFBQcCAjBOGkxMaW1pdGFjaW9uZXMgZGUgZ2FyYW50
-7WFzIGRlIGVzdGUgY2VydGlmaWNhZG8gc2UgcHVlZGVuIGVuY29udHJhciBlbiBs
-YSBEUEMuMA0GCSqGSIb3DQEBBQUAA4ICAQBclLW4RZFNjmEfAygPU3zmpFmps4p6
-xbD/CHwso3EcIRNnoZUSQDWDg4902zNc8El2CoFS3UnUmjIz75uny3XlesuXEpBc
-unvFm9+7OSPI/5jOCk0iAUgHforA1SBClETvv3eiiWdIG0ADBaGJ7M9i4z0ldma/
-Jre7Ir5v/zlXdLp6yQGVwZVR6Kss+LGGIOk/yzVb0hfpKv6DExdA7ohiZVvVO2Dp
-ezy4ydV/NgIlqmjCMRW3MGXrfx1IebHPOeJCgBbT9ZMj/EyXyVo3bHwi2ErN0o42
-gzmRkBDI8ck1fj+404HGIGQatlDCIaR43NAvO2STdPCWkPHv+wlaNECW8DYSwaN0
-jJN+Qd53i+yG2dIPPy3RzECiiWZIHiCznCNZc6lEc7wkeZBWN7PGKX6jD/EpOe9+
-XCgycDWs2rjIdWb8m0w5R44bb5tNAlQiM+9hup4phO9OSzNHdpdqy35f/RWmnkJD
-W2ZaiogN9xa5P1FlK2Zqi9E4UqLWRhH6/JocdJ6PlwsCT2TG9WjTSy3/pDceiz+/
-RL5hRqGEPQgnTIEgd4kI6mdAXmwIUV80WoyWaM3X94nCHNMyAK9Sy9NgWyo6R35r
-MDOhYil/SrnhLecUIw4OGEfhefwVVdCx/CVxY3UzHCMrr1zZ7Ud3YA47Dx7SwNxk
-BYn8eNZcLCZDqQ==
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number:
- 07:7e:52:93:7b:e0:15:e3:57:f0:69:8c:cb:ec:0c
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=CO, O=Sociedad Cameral de Certificaci\xC3\xB3n Digital - Certic\xC3\xA1mara S.A., CN=AC Ra\xC3\xADz Certic\xC3\xA1mara S.A.
- Validity
- Not Before: Nov 27 20:46:29 2006 GMT
- Not After : Apr 2 21:42:02 2030 GMT
- Subject: C=CO, O=Sociedad Cameral de Certificaci\xC3\xB3n Digital - Certic\xC3\xA1mara S.A., CN=AC Ra\xC3\xADz Certic\xC3\xA1mara S.A.
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (4096 bit)
- Modulus:
- 00:ab:6b:89:a3:53:cc:48:23:08:fb:c3:cf:51:96:
- 08:2e:b8:08:7a:6d:3c:90:17:86:a9:e9:ed:2e:13:
- 34:47:b2:d0:70:dc:c9:3c:d0:8d:ca:ee:4b:17:ab:
- d0:85:b0:a7:23:04:cb:a8:a2:fc:e5:75:db:40:ca:
- 62:89:8f:50:9e:01:3d:26:5b:18:84:1c:cb:7c:37:
- b7:7d:ec:d3:7f:73:19:b0:6a:b2:d8:88:8a:2d:45:
- 74:a8:f7:b3:b8:c0:d4:da:cd:22:89:74:4d:5a:15:
- 39:73:18:74:4f:b5:eb:99:a7:c1:1e:88:b4:c2:93:
- 90:63:97:f3:a7:a7:12:b2:09:22:07:33:d9:91:cd:
- 0e:9c:1f:0e:20:c7:ee:bb:33:8d:8f:c2:d2:58:a7:
- 5f:fd:65:37:e2:88:c2:d8:8f:86:75:5e:f9:2d:a7:
- 87:33:f2:78:37:2f:8b:bc:1d:86:37:39:b1:94:f2:
- d8:bc:4a:9c:83:18:5a:06:fc:f3:d4:d4:ba:8c:15:
- 09:25:f0:f9:b6:8d:04:7e:17:12:33:6b:57:48:4c:
- 4f:db:26:1e:eb:cc:90:e7:8b:f9:68:7c:70:0f:a3:
- 2a:d0:3a:38:df:37:97:e2:5b:de:80:61:d3:80:d8:
- 91:83:42:5a:4c:04:89:68:11:3c:ac:5f:68:80:41:
- cc:60:42:ce:0d:5a:2a:0c:0f:9b:30:c0:a6:f0:86:
- db:ab:49:d7:97:6d:48:8b:f9:03:c0:52:67:9b:12:
- f7:c2:f2:2e:98:65:42:d9:d6:9a:e3:d0:19:31:0c:
- ad:87:d5:57:02:7a:30:e8:86:26:fb:8f:23:8a:54:
- 87:e4:bf:3c:ee:eb:c3:75:48:5f:1e:39:6f:81:62:
- 6c:c5:2d:c4:17:54:19:b7:37:8d:9c:37:91:c8:f6:
- 0b:d5:ea:63:6f:83:ac:38:c2:f3:3f:de:9a:fb:e1:
- 23:61:f0:c8:26:cb:36:c8:a1:f3:30:8f:a4:a3:a2:
- a1:dd:53:b3:de:f0:9a:32:1f:83:91:79:30:c1:a9:
- 1f:53:9b:53:a2:15:53:3f:dd:9d:b3:10:3b:48:7d:
- 89:0f:fc:ed:03:f5:fb:25:64:75:0e:17:19:0d:8f:
- 00:16:67:79:7a:40:fc:2d:59:07:d9:90:fa:9a:ad:
- 3d:dc:80:8a:e6:5c:35:a2:67:4c:11:6b:b1:f8:80:
- 64:00:2d:6f:22:61:c5:ac:4b:26:e5:5a:10:82:9b:
- a4:83:7b:34:f7:9e:89:91:20:97:8e:b7:42:c7:66:
- c3:d0:e9:a4:d6:f5:20:8d:c4:c3:95:ac:44:0a:9d:
- 5b:73:3c:26:3d:2f:4a:be:a7:c9:a7:10:1e:fb:9f:
- 50:69:f3
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints: critical
- CA:TRUE
- X509v3 Key Usage: critical
- Certificate Sign, CRL Sign
- X509v3 Subject Key Identifier:
- D1:09:D0:E9:D7:CE:79:74:54:F9:3A:30:B3:F4:6D:2C:03:03:1B:68
- X509v3 Certificate Policies:
- Policy: X509v3 Any Policy
- CPS: http://www.certicamara.com/dpc/
- User Notice:
- Explicit Text: Limitaciones de garantías de este certificado se pueden encontrar en la DPC.
-
- Signature Algorithm: sha1WithRSAEncryption
- 5c:94:b5:b8:45:91:4d:8e:61:1f:03:28:0f:53:7c:e6:a4:59:
- a9:b3:8a:7a:c5:b0:ff:08:7c:2c:a3:71:1c:21:13:67:a1:95:
- 12:40:35:83:83:8f:74:db:33:5c:f0:49:76:0a:81:52:dd:49:
- d4:9a:32:33:ef:9b:a7:cb:75:e5:7a:cb:97:12:90:5c:ba:7b:
- c5:9b:df:bb:39:23:c8:ff:98:ce:0a:4d:22:01:48:07:7e:8a:
- c0:d5:20:42:94:44:ef:bf:77:a2:89:67:48:1b:40:03:05:a1:
- 89:ec:cf:62:e3:3d:25:76:66:bf:26:b7:bb:22:be:6f:ff:39:
- 57:74:ba:7a:c9:01:95:c1:95:51:e8:ab:2c:f8:b1:86:20:e9:
- 3f:cb:35:5b:d2:17:e9:2a:fe:83:13:17:40:ee:88:62:65:5b:
- d5:3b:60:e9:7b:3c:b8:c9:d5:7f:36:02:25:aa:68:c2:31:15:
- b7:30:65:eb:7f:1d:48:79:b1:cf:39:e2:42:80:16:d3:f5:93:
- 23:fc:4c:97:c9:5a:37:6c:7c:22:d8:4a:cd:d2:8e:36:83:39:
- 91:90:10:c8:f1:c9:35:7e:3f:b8:d3:81:c6:20:64:1a:b6:50:
- c2:21:a4:78:dc:d0:2f:3b:64:93:74:f0:96:90:f1:ef:fb:09:
- 5a:34:40:96:f0:36:12:c1:a3:74:8c:93:7e:41:de:77:8b:ec:
- 86:d9:d2:0f:3f:2d:d1:cc:40:a2:89:66:48:1e:20:b3:9c:23:
- 59:73:a9:44:73:bc:24:79:90:56:37:b3:c6:29:7e:a3:0f:f1:
- 29:39:ef:7e:5c:28:32:70:35:ac:da:b8:c8:75:66:fc:9b:4c:
- 39:47:8e:1b:6f:9b:4d:02:54:22:33:ef:61:ba:9e:29:84:ef:
- 4e:4b:33:47:76:97:6a:cb:7e:5f:fd:15:a6:9e:42:43:5b:66:
- 5a:8a:88:0d:f7:16:b9:3f:51:65:2b:66:6a:8b:d1:38:52:a2:
- d6:46:11:fa:fc:9a:1c:74:9e:8f:97:0b:02:4f:64:c6:f5:68:
- d3:4b:2d:ff:a4:37:1e:8b:3f:bf:44:be:61:46:a1:84:3d:08:
- 27:4c:81:20:77:89:08:ea:67:40:5e:6c:08:51:5f:34:5a:8c:
- 96:68:cd:d7:f7:89:c2:1c:d3:32:00:af:52:cb:d3:60:5b:2a:
- 3a:47:7e:6b:30:33:a1:62:29:7f:4a:b9:e1:2d:e7:14:23:0e:
- 0e:18:47:e1:79:fc:15:55:d0:b1:fc:25:71:63:75:33:1c:23:
- 2b:af:5c:d9:ed:47:77:60:0e:3b:0f:1e:d2:c0:dc:64:05:89:
- fc:78:d6:5c:2c:26:43:a9
-SHA1 Fingerprint=CB:A1:C5:F8:B0:E3:5E:B8:B9:45:12:D3:F9:34:A2:E9:06:10:D3:36
diff --git a/luni/src/main/files/cacerts/c90bc37d.0 b/luni/src/main/files/cacerts/c90bc37d.0
new file mode 100644
index 0000000..e4460c1
--- /dev/null
+++ b/luni/src/main/files/cacerts/c90bc37d.0
@@ -0,0 +1,80 @@
+-----BEGIN CERTIFICATE-----
+MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
+MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT
+MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
+b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG
+9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI
+2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx
+1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ
+q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
+tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
+vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
+BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
+5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
+1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
+NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
+Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
+8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
+pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
+MrY=
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 03:3a:f1:e6:a7:11:a9:a0:bb:28:64:b1:1d:09:fa:e5
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G2
+ Validity
+ Not Before: Aug 1 12:00:00 2013 GMT
+ Not After : Jan 15 12:00:00 2038 GMT
+ Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G2
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (2048 bit)
+ Modulus:
+ 00:bb:37:cd:34:dc:7b:6b:c9:b2:68:90:ad:4a:75:
+ ff:46:ba:21:0a:08:8d:f5:19:54:c9:fb:88:db:f3:
+ ae:f2:3a:89:91:3c:7a:e6:ab:06:1a:6b:cf:ac:2d:
+ e8:5e:09:24:44:ba:62:9a:7e:d6:a3:a8:7e:e0:54:
+ 75:20:05:ac:50:b7:9c:63:1a:6c:30:dc:da:1f:19:
+ b1:d7:1e:de:fd:d7:e0:cb:94:83:37:ae:ec:1f:43:
+ 4e:dd:7b:2c:d2:bd:2e:a5:2f:e4:a9:b8:ad:3a:d4:
+ 99:a4:b6:25:e9:9b:6b:00:60:92:60:ff:4f:21:49:
+ 18:f7:67:90:ab:61:06:9c:8f:f2:ba:e9:b4:e9:92:
+ 32:6b:b5:f3:57:e8:5d:1b:cd:8c:1d:ab:95:04:95:
+ 49:f3:35:2d:96:e3:49:6d:dd:77:e3:fb:49:4b:b4:
+ ac:55:07:a9:8f:95:b3:b4:23:bb:4c:6d:45:f0:f6:
+ a9:b2:95:30:b4:fd:4c:55:8c:27:4a:57:14:7c:82:
+ 9d:cd:73:92:d3:16:4a:06:0c:8c:50:d1:8f:1e:09:
+ be:17:a1:e6:21:ca:fd:83:e5:10:bc:83:a5:0a:c4:
+ 67:28:f6:73:14:14:3d:46:76:c3:87:14:89:21:34:
+ 4d:af:0f:45:0c:a6:49:a1:ba:bb:9c:c5:b1:33:83:
+ 29:85
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Digital Signature, Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ 4E:22:54:20:18:95:E6:E3:6E:E6:0F:FA:FA:B9:12:ED:06:17:8F:39
+ Signature Algorithm: sha256WithRSAEncryption
+ 60:67:28:94:6f:0e:48:63:eb:31:dd:ea:67:18:d5:89:7d:3c:
+ c5:8b:4a:7f:e9:be:db:2b:17:df:b0:5f:73:77:2a:32:13:39:
+ 81:67:42:84:23:f2:45:67:35:ec:88:bf:f8:8f:b0:61:0c:34:
+ a4:ae:20:4c:84:c6:db:f8:35:e1:76:d9:df:a6:42:bb:c7:44:
+ 08:86:7f:36:74:24:5a:da:6c:0d:14:59:35:bd:f2:49:dd:b6:
+ 1f:c9:b3:0d:47:2a:3d:99:2f:bb:5c:bb:b5:d4:20:e1:99:5f:
+ 53:46:15:db:68:9b:f0:f3:30:d5:3e:31:e2:8d:84:9e:e3:8a:
+ da:da:96:3e:35:13:a5:5f:f0:f9:70:50:70:47:41:11:57:19:
+ 4e:c0:8f:ae:06:c4:95:13:17:2f:1b:25:9f:75:f2:b1:8e:99:
+ a1:6f:13:b1:41:71:fe:88:2a:c8:4f:10:20:55:d7:f3:14:45:
+ e5:e0:44:f4:ea:87:95:32:93:0e:fe:53:46:fa:2c:9d:ff:8b:
+ 22:b9:4b:d9:09:45:a4:de:a4:b8:9a:58:dd:1b:7d:52:9f:8e:
+ 59:43:88:81:a4:9e:26:d5:6f:ad:dd:0d:c6:37:7d:ed:03:92:
+ 1b:e5:77:5f:76:ee:3c:8d:c4:5d:56:5b:a2:d9:66:6e:b3:35:
+ 37:e5:32:b6
+SHA1 Fingerprint=DF:3C:24:F9:BF:D6:66:76:1B:26:80:73:FE:06:D1:CC:8D:4F:82:A4
diff --git a/luni/src/main/files/cacerts/d06393bb.0 b/luni/src/main/files/cacerts/d06393bb.0
new file mode 100644
index 0000000..0029410
--- /dev/null
+++ b/luni/src/main/files/cacerts/d06393bb.0
@@ -0,0 +1,80 @@
+-----BEGIN CERTIFICATE-----
+MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx
+KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd
+BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl
+YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1
+OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy
+aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50
+ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G
+CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd
+AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC
+FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi
+1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq
+jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ
+wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj
+QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/
+WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy
+NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC
+uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw
+IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6
+g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN
+9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP
+BSeOE6Fuwg==
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number: 1 (0x1)
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=DE, O=T-Systems Enterprise Services GmbH, OU=T-Systems Trust Center, CN=T-TeleSec GlobalRoot Class 2
+ Validity
+ Not Before: Oct 1 10:40:14 2008 GMT
+ Not After : Oct 1 23:59:59 2033 GMT
+ Subject: C=DE, O=T-Systems Enterprise Services GmbH, OU=T-Systems Trust Center, CN=T-TeleSec GlobalRoot Class 2
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (2048 bit)
+ Modulus:
+ 00:aa:5f:da:1b:5f:e8:73:91:e5:da:5c:f4:a2:e6:
+ 47:e5:f3:68:55:60:05:1d:02:a4:b3:9b:59:f3:1e:
+ 8a:af:34:ad:fc:0d:c2:d9:48:19:ee:69:8f:c9:20:
+ fc:21:aa:07:19:ed:b0:5c:ac:65:c7:5f:ed:02:7c:
+ 7b:7c:2d:1b:d6:ba:b9:80:c2:18:82:16:84:fa:66:
+ b0:08:c6:54:23:81:e4:cd:b9:49:3f:f6:4f:6e:37:
+ 48:28:38:0f:c5:be:e7:68:70:fd:39:97:4d:d2:c7:
+ 98:91:50:aa:c4:44:b3:23:7d:39:47:e9:52:62:d6:
+ 12:93:5e:b7:31:96:42:05:fb:76:a7:1e:a3:f5:c2:
+ fc:e9:7a:c5:6c:a9:71:4f:ea:cb:78:bc:60:af:c7:
+ de:f4:d9:cb:be:7e:33:a5:6e:94:83:f0:34:fa:21:
+ ab:ea:8e:72:a0:3f:a4:de:30:5b:ef:86:4d:6a:95:
+ 5b:43:44:a8:10:15:1c:e5:01:57:c5:98:f1:e6:06:
+ 28:91:aa:20:c5:b7:53:26:51:43:b2:0b:11:95:58:
+ e1:c0:0f:76:d9:c0:8d:7c:81:f3:72:70:9e:6f:fe:
+ 1a:8e:d9:5f:35:c6:b2:6f:34:7c:be:48:4f:e2:5a:
+ 39:d7:d8:9d:78:9e:9f:86:3e:03:5e:19:8b:44:a2:
+ d5:c7
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ BF:59:20:36:00:79:A0:A0:22:6B:8C:D5:F2:61:D2:B8:2C:CB:82:4A
+ Signature Algorithm: sha256WithRSAEncryption
+ 31:03:a2:61:0b:1f:74:e8:72:36:c6:6d:f9:4d:9e:fa:22:a8:
+ e1:81:56:cf:cd:bb:9f:ea:ab:91:19:38:af:aa:7c:15:4d:f3:
+ b6:a3:8d:a5:f4:8e:f6:44:a9:a7:e8:21:95:ad:3e:00:62:16:
+ 88:f0:02:ba:fc:61:23:e6:33:9b:30:7a:6b:36:62:7b:ad:04:
+ 23:84:58:65:e2:db:2b:8a:e7:25:53:37:62:53:5f:bc:da:01:
+ 62:29:a2:a6:27:71:e6:3a:22:7e:c1:6f:1d:95:70:20:4a:07:
+ 34:df:ea:ff:15:80:e5:ba:d7:7a:d8:5b:75:7c:05:7a:29:47:
+ 7e:40:a8:31:13:77:cd:40:3b:b4:51:47:7a:2e:11:e3:47:11:
+ de:9d:66:d0:8b:d5:54:66:fa:83:55:ea:7c:c2:29:89:1b:e9:
+ 6f:b3:ce:e2:05:84:c9:2f:3e:78:85:62:6e:c9:5f:c1:78:63:
+ 74:58:c0:48:18:0c:99:39:eb:a4:cc:1a:b5:79:5a:8d:15:9c:
+ d8:14:0d:f6:7a:07:57:c7:22:83:05:2d:3c:9b:25:26:3d:18:
+ b3:a9:43:7c:c8:c8:ab:64:8f:0e:a3:bf:9c:1b:9d:30:db:da:
+ d0:19:2e:aa:3c:f1:fb:33:80:76:e4:cd:ad:19:4f:05:27:8e:
+ 13:a1:6e:c2
+SHA1 Fingerprint=59:0D:2D:7D:88:4F:40:2E:61:7E:A5:62:32:17:65:CF:17:D8:94:E9
diff --git a/luni/src/main/files/cacerts/d537fba6.0 b/luni/src/main/files/cacerts/d537fba6.0
deleted file mode 100644
index 0ae2700..0000000
--- a/luni/src/main/files/cacerts/d537fba6.0
+++ /dev/null
@@ -1,96 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIEKzCCAxOgAwIBAgIEOsylTDANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJE
-SzEVMBMGA1UEChMMVERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQg
-Um9vdCBDQTAeFw0wMTA0MDUxNjMzMTdaFw0yMTA0MDUxNzAzMTdaMEMxCzAJBgNV
-BAYTAkRLMRUwEwYDVQQKEwxUREMgSW50ZXJuZXQxHTAbBgNVBAsTFFREQyBJbnRl
-cm5ldCBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxLhA
-vJHVYx/XmaCLDEAedLdInUaMArLgJF/wGROnN4NrXceO+YQwzho7+vvOi20jxsNu
-Zp+Jpd/gQlBn+h9sHvTQBda/ytZO5GhgbEaqHF1j4QeGDmUApy6mcca8uYGoOn0a
-0vnRrEvLznWv3Hv6gXPU/Lq9QYjUdLP5Xjg6PEOo0pVOd20TDJ2PeAG3WiAfAzc1
-4izbSysseLlJ28TQx5yc5IogCSEWVmb/Bexb4/DPqyQkXsN/cHoSxNK1EKC2IeGN
-eGlVRGn1ypYcNIUXJXfi9i8nmHj9eQY6otZaQ8H/7AQ77hPv01ha/5Lr7K7a8jcD
-R0G2l8ktCkEiu7vmpwIDAQABo4IBJTCCASEwEQYJYIZIAYb4QgEBBAQDAgAHMGUG
-A1UdHwReMFwwWqBYoFakVDBSMQswCQYDVQQGEwJESzEVMBMGA1UEChMMVERDIElu
-dGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTENMAsGA1UEAxME
-Q1JMMTArBgNVHRAEJDAigA8yMDAxMDQwNTE2MzMxN1qBDzIwMjEwNDA1MTcwMzE3
-WjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUbGQBx/2FbazI2p5QCIUItTxWqFAw
-HQYDVR0OBBYEFGxkAcf9hW2syNqeUAiFCLU8VqhQMAwGA1UdEwQFMAMBAf8wHQYJ
-KoZIhvZ9B0EABBAwDhsIVjUuMDo0LjADAgSQMA0GCSqGSIb3DQEBBQUAA4IBAQBO
-Q8zR3R0QGwZ/t6T609lN+yOfI1Rb5osvBCiLtSdtiaHsmGnc540mgwV5dOy0uaOX
-wTUA/RXaOYE6lTGQ3pfphqiZdwzlWqCE/xIWrG64jcN7ksKsLtB9KOy282A4aW8+
-2ARVPp7MVdK6/rtHBNcK2RYKNCn1WBPVT8+PVkuzHu7TmHnaCB4Mb7j4Fifvwm89
-9qNLPg7kbWzbO0ESm70NRyN/PErQr8Cv9u8btRXE64PECV90i9kR+8JWsTz4cMo0
-jUNAE4z9mQNUecYu6oah9jrUCbz0vGbMPVjQV0kK7iXiQe4T+Zs4NNEA9X7nlB38
-aQNiuJkFBT1reBK9sG9l
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 986490188 (0x3acca54c)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=DK, O=TDC Internet, OU=TDC Internet Root CA
- Validity
- Not Before: Apr 5 16:33:17 2001 GMT
- Not After : Apr 5 17:03:17 2021 GMT
- Subject: C=DK, O=TDC Internet, OU=TDC Internet Root CA
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (2048 bit)
- Modulus:
- 00:c4:b8:40:bc:91:d5:63:1f:d7:99:a0:8b:0c:40:
- 1e:74:b7:48:9d:46:8c:02:b2:e0:24:5f:f0:19:13:
- a7:37:83:6b:5d:c7:8e:f9:84:30:ce:1a:3b:fa:fb:
- ce:8b:6d:23:c6:c3:6e:66:9f:89:a5:df:e0:42:50:
- 67:fa:1f:6c:1e:f4:d0:05:d6:bf:ca:d6:4e:e4:68:
- 60:6c:46:aa:1c:5d:63:e1:07:86:0e:65:00:a7:2e:
- a6:71:c6:bc:b9:81:a8:3a:7d:1a:d2:f9:d1:ac:4b:
- cb:ce:75:af:dc:7b:fa:81:73:d4:fc:ba:bd:41:88:
- d4:74:b3:f9:5e:38:3a:3c:43:a8:d2:95:4e:77:6d:
- 13:0c:9d:8f:78:01:b7:5a:20:1f:03:37:35:e2:2c:
- db:4b:2b:2c:78:b9:49:db:c4:d0:c7:9c:9c:e4:8a:
- 20:09:21:16:56:66:ff:05:ec:5b:e3:f0:cf:ab:24:
- 24:5e:c3:7f:70:7a:12:c4:d2:b5:10:a0:b6:21:e1:
- 8d:78:69:55:44:69:f5:ca:96:1c:34:85:17:25:77:
- e2:f6:2f:27:98:78:fd:79:06:3a:a2:d6:5a:43:c1:
- ff:ec:04:3b:ee:13:ef:d3:58:5a:ff:92:eb:ec:ae:
- da:f2:37:03:47:41:b6:97:c9:2d:0a:41:22:bb:bb:
- e6:a7
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- Netscape Cert Type:
- SSL CA, S/MIME CA, Object Signing CA
- X509v3 CRL Distribution Points:
-
- Full Name:
- DirName: C = DK, O = TDC Internet, OU = TDC Internet Root CA, CN = CRL1
-
- X509v3 Private Key Usage Period:
- Not Before: Apr 5 16:33:17 2001 GMT, Not After: Apr 5 17:03:17 2021 GMT
- X509v3 Key Usage:
- Certificate Sign, CRL Sign
- X509v3 Authority Key Identifier:
- keyid:6C:64:01:C7:FD:85:6D:AC:C8:DA:9E:50:08:85:08:B5:3C:56:A8:50
-
- X509v3 Subject Key Identifier:
- 6C:64:01:C7:FD:85:6D:AC:C8:DA:9E:50:08:85:08:B5:3C:56:A8:50
- X509v3 Basic Constraints:
- CA:TRUE
- 1.2.840.113533.7.65.0:
- 0...V5.0:4.0....
- Signature Algorithm: sha1WithRSAEncryption
- 4e:43:cc:d1:dd:1d:10:1b:06:7f:b7:a4:fa:d3:d9:4d:fb:23:
- 9f:23:54:5b:e6:8b:2f:04:28:8b:b5:27:6d:89:a1:ec:98:69:
- dc:e7:8d:26:83:05:79:74:ec:b4:b9:a3:97:c1:35:00:fd:15:
- da:39:81:3a:95:31:90:de:97:e9:86:a8:99:77:0c:e5:5a:a0:
- 84:ff:12:16:ac:6e:b8:8d:c3:7b:92:c2:ac:2e:d0:7d:28:ec:
- b6:f3:60:38:69:6f:3e:d8:04:55:3e:9e:cc:55:d2:ba:fe:bb:
- 47:04:d7:0a:d9:16:0a:34:29:f5:58:13:d5:4f:cf:8f:56:4b:
- b3:1e:ee:d3:98:79:da:08:1e:0c:6f:b8:f8:16:27:ef:c2:6f:
- 3d:f6:a3:4b:3e:0e:e4:6d:6c:db:3b:41:12:9b:bd:0d:47:23:
- 7f:3c:4a:d0:af:c0:af:f6:ef:1b:b5:15:c4:eb:83:c4:09:5f:
- 74:8b:d9:11:fb:c2:56:b1:3c:f8:70:ca:34:8d:43:40:13:8c:
- fd:99:03:54:79:c6:2e:ea:86:a1:f6:3a:d4:09:bc:f4:bc:66:
- cc:3d:58:d0:57:49:0a:ee:25:e2:41:ee:13:f9:9b:38:34:d1:
- 00:f5:7e:e7:94:1d:fc:69:03:62:b8:99:05:05:3d:6b:78:12:
- bd:b0:6f:65
-SHA1 Fingerprint=21:FC:BD:8E:7F:6C:AF:05:1B:D1:B3:43:EC:A8:E7:61:47:F2:0F:8A
diff --git a/luni/src/main/files/cacerts/e442e424.0 b/luni/src/main/files/cacerts/e442e424.0
new file mode 100644
index 0000000..c715660
--- /dev/null
+++ b/luni/src/main/files/cacerts/e442e424.0
@@ -0,0 +1,120 @@
+-----BEGIN CERTIFICATE-----
+MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL
+BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc
+BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00
+MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
+aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG
+SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR
+/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu
+FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR
+U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c
+ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR
+FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k
+A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw
+eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl
+sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp
+VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q
+A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+
+ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB
+BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD
+ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px
+KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI
+FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv
+oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg
+u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP
+0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf
+3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl
+8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+
+DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN
+PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/
+ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 2e:f5:9b:02:28:a7:db:7a:ff:d5:a3:a9:ee:bd:03:a0:cf:12:6a:1d
+ Signature Algorithm: sha256WithRSAEncryption
+ Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 3 G3
+ Validity
+ Not Before: Jan 12 20:26:32 2012 GMT
+ Not After : Jan 12 20:26:32 2042 GMT
+ Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 3 G3
+ Subject Public Key Info:
+ Public Key Algorithm: rsaEncryption
+ Public-Key: (4096 bit)
+ Modulus:
+ 00:b3:cb:0e:10:67:8e:ea:14:97:a7:32:2a:0a:56:
+ 36:7f:68:4c:c7:b3:6f:3a:23:14:91:ff:19:7f:a5:
+ ca:ac:ee:b3:76:9d:7a:e9:8b:1b:ab:6b:31:db:fa:
+ 0b:53:4c:af:c5:a5:1a:79:3c:8a:4c:ff:ac:df:25:
+ de:4e:d9:82:32:0b:44:de:ca:db:8c:ac:a3:6e:16:
+ 83:3b:a6:64:4b:32:89:fb:16:16:38:7e:eb:43:e2:
+ d3:74:4a:c2:62:0a:73:0a:dd:49:b3:57:d2:b0:0a:
+ 85:9d:71:3c:de:a3:cb:c0:32:f3:01:39:20:43:1b:
+ 35:d1:53:b3:b1:ee:c5:93:69:82:3e:16:b5:28:46:
+ a1:de:ea:89:09:ed:43:b8:05:46:8a:86:f5:59:47:
+ be:1b:6f:01:21:10:b9:fd:a9:d2:28:ca:10:39:09:
+ ca:13:36:cf:9c:ad:ad:40:74:79:2b:02:3f:34:ff:
+ fa:20:69:7d:d3:ee:61:f5:ba:b3:e7:30:d0:37:23:
+ 86:72:61:45:29:48:59:68:6f:77:a6:2e:81:be:07:
+ 4d:6f:af:ce:c4:45:13:91:14:70:06:8f:1f:9f:f8:
+ 87:69:b1:0e:ef:c3:89:19:eb:ea:1c:61:fc:7a:6c:
+ 8a:dc:d6:03:0b:9e:26:ba:12:dd:d4:54:39:ab:26:
+ a3:33:ea:75:81:da:2d:cd:0f:4f:e4:03:d1:ef:15:
+ 97:1b:6b:90:c5:02:90:93:66:02:21:b1:47:de:8b:
+ 9a:4a:80:b9:55:8f:b5:a2:2f:c0:d6:33:67:da:7e:
+ c4:a7:b4:04:44:eb:47:fb:e6:58:b9:f7:0c:f0:7b:
+ 2b:b1:c0:70:29:c3:40:62:2d:3b:48:69:dc:23:3c:
+ 48:eb:7b:09:79:a9:6d:da:a8:30:98:cf:80:72:03:
+ 88:a6:5b:46:ae:72:79:7c:08:03:21:65:ae:b7:e1:
+ 1c:a5:b1:2a:a2:31:de:66:04:f7:c0:74:e8:71:de:
+ ff:3d:59:cc:96:26:12:8b:85:95:57:1a:ab:6b:75:
+ 0b:44:3d:11:28:3c:7b:61:b7:e2:8f:67:4f:e5:ec:
+ 3c:4c:60:80:69:57:38:1e:01:5b:8d:55:e8:c7:df:
+ c0:cc:77:23:34:49:75:7c:f6:98:11:eb:2d:de:ed:
+ 41:2e:14:05:02:7f:e0:fe:20:eb:35:e7:11:ac:22:
+ ce:57:3d:de:c9:30:6d:10:03:85:cd:f1:ff:8c:16:
+ b5:c1:b2:3e:88:6c:60:7f:90:4f:95:f7:f6:2d:ad:
+ 01:39:07:04:fa:75:80:7d:bf:49:50:ed:ef:c9:c4:
+ 7c:1c:eb:80:7e:db:b6:d0:dd:13:fe:c9:d3:9c:d7:
+ b2:97:a9
+ Exponent: 65537 (0x10001)
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ C6:17:D0:BC:A8:EA:02:43:F2:1B:06:99:5D:2B:90:20:B9:D7:9C:E4
+ Signature Algorithm: sha256WithRSAEncryption
+ 34:61:d9:56:b5:12:87:55:4d:dd:a3:35:31:46:bb:a4:07:72:
+ bc:5f:61:62:e8:a5:fb:0b:37:b1:3c:b6:b3:fa:29:9d:7f:02:
+ f5:a4:c9:a8:93:b7:7a:71:28:69:8f:73:e1:52:90:da:d5:be:
+ 3a:e5:b7:76:6a:56:80:21:df:5d:e6:e9:3a:9e:e5:3e:f6:a2:
+ 69:c7:2a:0a:b0:18:47:dc:20:70:7d:52:a3:3e:59:7c:c1:ba:
+ c9:c8:15:40:61:ca:72:d6:70:ac:d2:b7:f0:1c:e4:86:29:f0:
+ ce:ef:68:63:d0:b5:20:8a:15:61:9a:7e:86:98:b4:c9:c2:76:
+ fb:cc:ba:30:16:cc:a3:61:c6:74:13:e5:6b:ef:a3:15:ea:03:
+ fe:13:8b:64:e4:d3:c1:d2:e8:84:fb:49:d1:10:4d:79:66:eb:
+ aa:fd:f4:8d:31:1e:70:14:ad:dc:de:67:13:4c:81:15:61:bc:
+ b7:d9:91:77:71:19:81:60:bb:f0:58:a5:b5:9c:0b:f7:8f:22:
+ 55:27:c0:4b:01:6d:3b:99:0d:d4:1d:9b:63:67:2f:d0:ee:0d:
+ ca:66:bc:94:4f:a6:ad:ed:fc:ee:63:ac:57:3f:65:25:cf:b2:
+ 86:8f:d0:08:ff:b8:76:14:6e:de:e5:27:ec:ab:78:b5:53:b9:
+ b6:3f:e8:20:f9:d2:a8:be:61:46:ca:87:8c:84:f3:f9:f1:a0:
+ 68:9b:22:1e:81:26:9b:10:04:91:71:c0:06:1f:dc:a0:d3:b9:
+ 56:a7:e3:98:2d:7f:83:9d:df:8c:2b:9c:32:8e:32:94:f0:01:
+ 3c:22:2a:9f:43:c2:2e:c3:98:39:07:38:7b:fc:5e:00:42:1f:
+ f3:32:26:79:83:84:f6:e5:f0:c1:51:12:c0:0b:1e:04:23:0c:
+ 54:a5:4c:2f:49:c5:4a:d1:b6:6e:60:0d:6b:fc:6b:8b:85:24:
+ 64:b7:89:0e:ab:25:47:5b:3c:cf:7e:49:bd:c7:e9:0a:c6:da:
+ f7:7e:0e:17:08:d3:48:97:d0:71:92:f0:0f:39:3e:34:6a:1c:
+ 7d:d8:f2:22:ae:bb:69:f4:33:b4:a6:48:55:d1:0f:0e:26:e8:
+ ec:b6:0b:2d:a7:85:35:cd:fd:59:c8:9f:d1:cd:3e:5a:29:34:
+ b9:3d:84:ce:b1:65:d4:59:91:91:56:75:21:c1:77:9e:f9:7a:
+ e1:60:9d:d3:ad:04:18:f4:7c:eb:5e:93:8f:53:4a:22:29:f8:
+ 48:2b:3e:4d:86:ac:5b:7f:cb:06:99:59:60:d8:58:65:95:8d:
+ 44:d1:f7:7f:7e:27:7f:7d:ae:80:f5:07:4c:b6:3e:9c:71:54:
+ 99:04:4b:fd:58:f9:98:f4
+SHA1 Fingerprint=48:12:BD:92:3C:A8:C4:39:06:E7:30:6D:27:96:E6:A4:CF:22:2E:7D
diff --git a/luni/src/main/files/cacerts/ed39abd0.0 b/luni/src/main/files/cacerts/ed39abd0.0
new file mode 100644
index 0000000..188e375
--- /dev/null
+++ b/luni/src/main/files/cacerts/ed39abd0.0
@@ -0,0 +1,53 @@
+-----BEGIN CERTIFICATE-----
+MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw
+CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu
+ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe
+Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw
+EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x
+IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF
+K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG
+fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO
+Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd
+BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx
+AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/
+oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8
+sycX
+-----END CERTIFICATE-----
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 05:55:56:bc:f2:5e:a4:35:35:c3:a4:0f:d5:ab:45:72
+ Signature Algorithm: ecdsa-with-SHA384
+ Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G3
+ Validity
+ Not Before: Aug 1 12:00:00 2013 GMT
+ Not After : Jan 15 12:00:00 2038 GMT
+ Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G3
+ Subject Public Key Info:
+ Public Key Algorithm: id-ecPublicKey
+ Public-Key: (384 bit)
+ pub:
+ 04:dd:a7:d9:bb:8a:b8:0b:fb:0b:7f:21:d2:f0:be:
+ be:73:f3:33:5d:1a:bc:34:ea:de:c6:9b:bc:d0:95:
+ f6:f0:cc:d0:0b:ba:61:5b:51:46:7e:9e:2d:9f:ee:
+ 8e:63:0c:17:ec:07:70:f5:cf:84:2e:40:83:9c:e8:
+ 3f:41:6d:3b:ad:d3:a4:14:59:36:78:9d:03:43:ee:
+ 10:13:6c:72:de:ae:88:a7:a1:6b:b5:43:ce:67:dc:
+ 23:ff:03:1c:a3:e2:3e
+ ASN1 OID: secp384r1
+ X509v3 extensions:
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ X509v3 Key Usage: critical
+ Digital Signature, Certificate Sign, CRL Sign
+ X509v3 Subject Key Identifier:
+ B3:DB:48:A4:F9:A1:C5:D8:AE:36:41:CC:11:63:69:62:29:BC:4B:C6
+ Signature Algorithm: ecdsa-with-SHA384
+ 30:65:02:31:00:ad:bc:f2:6c:3f:12:4a:d1:2d:39:c3:0a:09:
+ 97:73:f4:88:36:8c:88:27:bb:e6:88:8d:50:85:a7:63:f9:9e:
+ 32:de:66:93:0f:f1:cc:b1:09:8f:dd:6c:ab:fa:6b:7f:a0:02:
+ 30:39:66:5b:c2:64:8d:b8:9e:50:dc:a8:d5:49:a2:ed:c7:dc:
+ d1:49:7f:17:01:b8:c8:86:8f:4e:8c:88:2b:a8:9a:a9:8a:c5:
+ d1:00:bd:f8:54:e2:9a:e5:5b:7c:b3:27:17
+SHA1 Fingerprint=7E:04:DE:89:6A:3E:66:6D:00:E6:87:D3:3F:FA:D9:3B:E8:3D:34:9E
diff --git a/luni/src/main/files/cacerts/f4996e82.0 b/luni/src/main/files/cacerts/f4996e82.0
deleted file mode 100644
index 4f59124..0000000
--- a/luni/src/main/files/cacerts/f4996e82.0
+++ /dev/null
@@ -1,52 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0
-IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz
-BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y
-aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG
-9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIyMjM0OFoXDTE5MDYy
-NTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y
-azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
-YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw
-Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl
-cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9Y
-LqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIiGQj4/xEjm84H9b9pGib+
-TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCmDuJWBQ8Y
-TfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0
-LBwGlN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLW
-I8sogTLDAHkY7FkXicnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPw
-nXS3qT6gpf+2SQMT2iLM7XGCK5nPOrf1LXLI
------END CERTIFICATE-----
-Certificate:
- Data:
- Version: 1 (0x0)
- Serial Number: 1 (0x1)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 1 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com
- Validity
- Not Before: Jun 25 22:23:48 1999 GMT
- Not After : Jun 25 22:23:48 2019 GMT
- Subject: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 1 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:d8:59:82:7a:89:b8:96:ba:a6:2f:68:6f:58:2e:
- a7:54:1c:06:6e:f4:ea:8d:48:bc:31:94:17:f0:f3:
- 4e:bc:b2:b8:35:92:76:b0:d0:a5:a5:01:d7:00:03:
- 12:22:19:08:f8:ff:11:23:9b:ce:07:f5:bf:69:1a:
- 26:fe:4e:e9:d1:7f:9d:2c:40:1d:59:68:6e:a6:f8:
- 58:b0:9d:1a:8f:d3:3f:f1:dc:19:06:81:a8:0e:e0:
- 3a:dd:c8:53:45:09:06:e6:0f:70:c3:fa:40:a6:0e:
- e2:56:05:0f:18:4d:fc:20:82:d1:73:55:74:8d:76:
- 72:a0:1d:9d:1d:c0:dd:3f:71
- Exponent: 65537 (0x10001)
- Signature Algorithm: sha1WithRSAEncryption
- 50:68:3d:49:f4:2c:1c:06:94:df:95:60:7f:96:7b:17:fe:4f:
- 71:ad:64:c8:dd:77:d2:ef:59:55:e8:3f:e8:8e:05:2a:21:f2:
- 07:d2:b5:a7:52:fe:9c:b1:b6:e2:5b:77:17:40:ea:72:d6:23:
- cb:28:81:32:c3:00:79:18:ec:59:17:89:c9:c6:6a:1e:71:c9:
- fd:b7:74:a5:25:45:69:c5:48:ab:19:e1:45:8a:25:6b:19:ee:
- e5:bb:12:f5:7f:f7:a6:8d:51:c3:f0:9d:74:b7:a9:3e:a0:a5:
- ff:b6:49:03:13:da:22:cc:ed:71:82:2b:99:cf:3a:b7:f5:2d:
- 72:c8
-SHA1 Fingerprint=E5:DF:74:3C:B6:01:C4:9B:98:43:DC:AB:8C:E8:6A:81:10:9F:E4:8E
diff --git a/luni/src/main/java/android/system/ErrnoException.java b/luni/src/main/java/android/system/ErrnoException.java
new file mode 100644
index 0000000..90155c8
--- /dev/null
+++ b/luni/src/main/java/android/system/ErrnoException.java
@@ -0,0 +1,82 @@
+/*
+ * 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 android.system;
+
+import java.io.IOException;
+import java.net.SocketException;
+import libcore.io.Libcore;
+
+/**
+ * A checked exception thrown when {@link Os} methods fail. This exception contains the native
+ * errno value, for comparison against the constants in {@link OsConstants}, should sophisticated
+ * callers need to adjust their behavior based on the exact failure.
+ */
+public final class ErrnoException extends Exception {
+ private final String functionName;
+
+ /**
+ * The errno value, for comparison with the {@code E} constants in {@link OsConstants}.
+ */
+ public final int errno;
+
+ /**
+ * Constructs an instance with the given function name and errno value.
+ */
+ public ErrnoException(String functionName, int errno) {
+ this.functionName = functionName;
+ this.errno = errno;
+ }
+
+ /**
+ * Constructs an instance with the given function name, errno value, and cause.
+ */
+ public ErrnoException(String functionName, int errno, Throwable cause) {
+ super(cause);
+ this.functionName = functionName;
+ this.errno = errno;
+ }
+
+ /**
+ * Converts the stashed function name and errno value to a human-readable string.
+ * We do this here rather than in the constructor so that callers only pay for
+ * this if they need it.
+ */
+ @Override public String getMessage() {
+ String errnoName = OsConstants.errnoName(errno);
+ if (errnoName == null) {
+ errnoName = "errno " + errno;
+ }
+ String description = Libcore.os.strerror(errno);
+ return functionName + " failed: " + errnoName + " (" + description + ")";
+ }
+
+ /**
+ * @hide - internal use only.
+ */
+ public IOException rethrowAsIOException() throws IOException {
+ IOException newException = new IOException(getMessage());
+ newException.initCause(this);
+ throw newException;
+ }
+
+ /**
+ * @hide - internal use only.
+ */
+ public SocketException rethrowAsSocketException() throws SocketException {
+ throw new SocketException(getMessage(), this);
+ }
+}
diff --git a/luni/src/main/java/android/system/GaiException.java b/luni/src/main/java/android/system/GaiException.java
new file mode 100644
index 0000000..dc10566
--- /dev/null
+++ b/luni/src/main/java/android/system/GaiException.java
@@ -0,0 +1,83 @@
+/*
+ * 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 android.system;
+
+import java.net.UnknownHostException;
+import libcore.io.Libcore;
+
+/**
+ * An unchecked exception thrown when {@code getaddrinfo} or {@code getnameinfo} fails.
+ * This exception contains the native {@link #error} value, should sophisticated
+ * callers need to adjust their behavior based on the exact failure.
+ *
+ * @hide
+ */
+public final class GaiException extends RuntimeException {
+ private final String functionName;
+
+ /**
+ * The native error value, for comparison with the {@code GAI_} constants in {@link OsConstants}.
+ */
+ public final int error;
+
+ /**
+ * Constructs an instance with the given function name and error value.
+ */
+ public GaiException(String functionName, int error) {
+ this.functionName = functionName;
+ this.error = error;
+ }
+
+ /**
+ * Constructs an instance with the given function name, error value, and cause.
+ */
+ public GaiException(String functionName, int error, Throwable cause) {
+ super(cause);
+ this.functionName = functionName;
+ this.error = error;
+ }
+
+ /**
+ * Converts the stashed function name and error value to a human-readable string.
+ * We do this here rather than in the constructor so that callers only pay for
+ * this if they need it.
+ */
+ @Override public String getMessage() {
+ String gaiName = OsConstants.gaiName(error);
+ if (gaiName == null) {
+ gaiName = "GAI_ error " + error;
+ }
+ String description = Libcore.os.gai_strerror(error);
+ return functionName + " failed: " + gaiName + " (" + description + ")";
+ }
+
+ /**
+ * @hide - internal use only.
+ */
+ public UnknownHostException rethrowAsUnknownHostException(String detailMessage) throws UnknownHostException {
+ UnknownHostException newException = new UnknownHostException(detailMessage);
+ newException.initCause(this);
+ throw newException;
+ }
+
+ /**
+ * @hide - internal use only.
+ */
+ public UnknownHostException rethrowAsUnknownHostException() throws UnknownHostException {
+ throw rethrowAsUnknownHostException(getMessage());
+ }
+}
diff --git a/luni/src/main/java/android/system/Os.java b/luni/src/main/java/android/system/Os.java
new file mode 100644
index 0000000..0b80b52
--- /dev/null
+++ b/luni/src/main/java/android/system/Os.java
@@ -0,0 +1,539 @@
+/*
+ * 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 android.system;
+
+import android.system.ErrnoException;
+import android.system.GaiException;
+import android.system.StructAddrinfo;
+import android.system.StructFlock;
+import android.system.StructGroupReq;
+import android.system.StructGroupSourceReq;
+import android.system.StructLinger;
+import android.system.StructPasswd;
+import android.system.StructPollfd;
+import android.system.StructStat;
+import android.system.StructStatVfs;
+import android.system.StructTimeval;
+import android.system.StructUcred;
+import android.system.StructUtsname;
+import android.util.MutableInt;
+import android.util.MutableLong;
+import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.nio.ByteBuffer;
+import libcore.io.Libcore;
+
+/**
+ * Access to low-level system functionality. Most of these are system calls. Most users will want
+ * to use higher-level APIs where available, but this class provides access to the underlying
+ * primitives used to implement the higher-level APIs.
+ *
+ * <p>The corresponding constants can be found in {@link OsConstants}.
+ */
+public final class Os {
+ private Os() {}
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/accept.2.html">accept(2)</a>.
+ */
+ public static FileDescriptor accept(FileDescriptor fd, InetSocketAddress peerAddress) throws ErrnoException, SocketException { return Libcore.os.accept(fd, peerAddress); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/access.2.html">access(2)</a>.
+ */
+ public static boolean access(String path, int mode) throws ErrnoException { return Libcore.os.access(path, mode); }
+
+ /** @hide */ public static InetAddress[] android_getaddrinfo(String node, StructAddrinfo hints, int netId) throws GaiException { return Libcore.os.android_getaddrinfo(node, hints, netId); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/bind.2.html">bind(2)</a>.
+ */
+ public static void bind(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException { Libcore.os.bind(fd, address, port); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/chmod.2.html">chmod(2)</a>.
+ */
+ public static void chmod(String path, int mode) throws ErrnoException { Libcore.os.chmod(path, mode); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/chown.2.html">chown(2)</a>.
+ */
+ public static void chown(String path, int uid, int gid) throws ErrnoException { Libcore.os.chown(path, uid, gid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/close.2.html">close(2)</a>.
+ */
+ public static void close(FileDescriptor fd) throws ErrnoException { Libcore.os.close(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/connect.2.html">connect(2)</a>.
+ */
+ public static void connect(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException { Libcore.os.connect(fd, address, port); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/dup.2.html">dup(2)</a>.
+ */
+ public static FileDescriptor dup(FileDescriptor oldFd) throws ErrnoException { return Libcore.os.dup(oldFd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/dup2.2.html">dup2(2)</a>.
+ */
+ public static FileDescriptor dup2(FileDescriptor oldFd, int newFd) throws ErrnoException { return Libcore.os.dup2(oldFd, newFd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/environ.3.html">environ(3)</a>.
+ */
+ public static String[] environ() { return Libcore.os.environ(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/execv.2.html">execv(2)</a>.
+ */
+ public static void execv(String filename, String[] argv) throws ErrnoException { Libcore.os.execv(filename, argv); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/execve.2.html">execve(2)</a>.
+ */
+ public static void execve(String filename, String[] argv, String[] envp) throws ErrnoException { Libcore.os.execve(filename, argv, envp); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html">fchmod(2)</a>.
+ */
+ public static void fchmod(FileDescriptor fd, int mode) throws ErrnoException { Libcore.os.fchmod(fd, mode); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/fchown.2.html">fchown(2)</a>.
+ */
+ public static void fchown(FileDescriptor fd, int uid, int gid) throws ErrnoException { Libcore.os.fchown(fd, uid, gid); }
+
+ /** @hide */ public static int fcntlVoid(FileDescriptor fd, int cmd) throws ErrnoException { return Libcore.os.fcntlVoid(fd, cmd); }
+ /** @hide */ public static int fcntlLong(FileDescriptor fd, int cmd, long arg) throws ErrnoException { return Libcore.os.fcntlLong(fd, cmd, arg); }
+ /** @hide */ public static int fcntlFlock(FileDescriptor fd, int cmd, StructFlock arg) throws ErrnoException { return Libcore.os.fcntlFlock(fd, cmd, arg); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html">fdatasync(2)</a>.
+ */
+ public static void fdatasync(FileDescriptor fd) throws ErrnoException { Libcore.os.fdatasync(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/fstat.2.html">fstat(2)</a>.
+ */
+ public static StructStat fstat(FileDescriptor fd) throws ErrnoException { return Libcore.os.fstat(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/fstatvfs.2.html">fstatvfs(2)</a>.
+ */
+ public static StructStatVfs fstatvfs(FileDescriptor fd) throws ErrnoException { return Libcore.os.fstatvfs(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/fsync.2.html">fsync(2)</a>.
+ */
+ public static void fsync(FileDescriptor fd) throws ErrnoException { Libcore.os.fsync(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html">ftruncate(2)</a>.
+ */
+ public static void ftruncate(FileDescriptor fd, long length) throws ErrnoException { Libcore.os.ftruncate(fd, length); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/gai_strerror.3.html">gai_strerror(3)</a>.
+ */
+ public static String gai_strerror(int error) { return Libcore.os.gai_strerror(error); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getegid.2.html">getegid(2)</a>.
+ */
+ public static int getegid() { return Libcore.os.getegid(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/geteuid.2.html">geteuid(2)</a>.
+ */
+ public static int geteuid() { return Libcore.os.geteuid(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getgid.2.html">getgid(2)</a>.
+ */
+ public static int getgid() { return Libcore.os.getgid(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/getenv.3.html">getenv(3)</a>.
+ */
+ public static String getenv(String name) { return Libcore.os.getenv(name); }
+
+ /** @hide */ public static String getnameinfo(InetAddress address, int flags) throws GaiException { return Libcore.os.getnameinfo(address, flags); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getpeername.2.html">getpeername(2)</a>.
+ */
+ public static SocketAddress getpeername(FileDescriptor fd) throws ErrnoException { return Libcore.os.getpeername(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getpid.2.html">getpid(2)</a>.
+ */
+ public static int getpid() { return Libcore.os.getpid(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getppid.2.html">getppid(2)</a>.
+ */
+ public static int getppid() { return Libcore.os.getppid(); }
+
+ /** @hide */ public static StructPasswd getpwnam(String name) throws ErrnoException { return Libcore.os.getpwnam(name); }
+
+ /** @hide */ public static StructPasswd getpwuid(int uid) throws ErrnoException { return Libcore.os.getpwuid(uid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getsockname.2.html">getsockname(2)</a>.
+ */
+ public static SocketAddress getsockname(FileDescriptor fd) throws ErrnoException { return Libcore.os.getsockname(fd); }
+
+ /** @hide */ public static int getsockoptByte(FileDescriptor fd, int level, int option) throws ErrnoException { return Libcore.os.getsockoptByte(fd, level, option); }
+ /** @hide */ public static InetAddress getsockoptInAddr(FileDescriptor fd, int level, int option) throws ErrnoException { return Libcore.os.getsockoptInAddr(fd, level, option); }
+ /** @hide */ public static int getsockoptInt(FileDescriptor fd, int level, int option) throws ErrnoException { return Libcore.os.getsockoptInt(fd, level, option); }
+ /** @hide */ public static StructLinger getsockoptLinger(FileDescriptor fd, int level, int option) throws ErrnoException { return Libcore.os.getsockoptLinger(fd, level, option); }
+ /** @hide */ public static StructTimeval getsockoptTimeval(FileDescriptor fd, int level, int option) throws ErrnoException { return Libcore.os.getsockoptTimeval(fd, level, option); }
+ /** @hide */ public static StructUcred getsockoptUcred(FileDescriptor fd, int level, int option) throws ErrnoException { return Libcore.os.getsockoptUcred(fd, level, option); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/gettid.2.html">gettid(2)</a>.
+ */
+ public static int gettid() { return Libcore.os.gettid(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/getuid.2.html">getuid(2)</a>.
+ */
+ public static int getuid() { return Libcore.os.getuid(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/if_indextoname.3.html">if_indextoname(3)</a>.
+ */
+ public static String if_indextoname(int index) { return Libcore.os.if_indextoname(index); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/inet_pton.3.html">inet_pton(3)</a>.
+ */
+ public static InetAddress inet_pton(int family, String address) { return Libcore.os.inet_pton(family, address); }
+
+ /** @hide */ public static InetAddress ioctlInetAddress(FileDescriptor fd, int cmd, String interfaceName) throws ErrnoException { return Libcore.os.ioctlInetAddress(fd, cmd, interfaceName); }
+ /** @hide */ public static int ioctlInt(FileDescriptor fd, int cmd, MutableInt arg) throws ErrnoException { return Libcore.os.ioctlInt(fd, cmd, arg); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/isatty.3.html">isatty(3)</a>.
+ */
+ public static boolean isatty(FileDescriptor fd) { return Libcore.os.isatty(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/kill.2.html">kill(2)</a>.
+ */
+ public static void kill(int pid, int signal) throws ErrnoException { Libcore.os.kill(pid, signal); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/lchown.2.html">lchown(2)</a>.
+ */
+ public static void lchown(String path, int uid, int gid) throws ErrnoException { Libcore.os.lchown(path, uid, gid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/link.2.html">link(2)</a>.
+ */
+ public static void link(String oldPath, String newPath) throws ErrnoException { Libcore.os.link(oldPath, newPath); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/listen.2.html">listen(2)</a>.
+ */
+ public static void listen(FileDescriptor fd, int backlog) throws ErrnoException { Libcore.os.listen(fd, backlog); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/lseek.2.html">lseek(2)</a>.
+ */
+ public static long lseek(FileDescriptor fd, long offset, int whence) throws ErrnoException { return Libcore.os.lseek(fd, offset, whence); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/lstat.2.html">lstat(2)</a>.
+ */
+ public static StructStat lstat(String path) throws ErrnoException { return Libcore.os.lstat(path); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/mincore.2.html">mincore(2)</a>.
+ */
+ public static void mincore(long address, long byteCount, byte[] vector) throws ErrnoException { Libcore.os.mincore(address, byteCount, vector); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html">mkdir(2)</a>.
+ */
+ public static void mkdir(String path, int mode) throws ErrnoException { Libcore.os.mkdir(path, mode); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/mkfifo.3.html">mkfifo(3)</a>.
+ */
+ public static void mkfifo(String path, int mode) throws ErrnoException { Libcore.os.mkfifo(path, mode); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/mlock.2.html">mlock(2)</a>.
+ */
+ public static void mlock(long address, long byteCount) throws ErrnoException { Libcore.os.mlock(address, byteCount); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/mmap.2.html">mmap(2)</a>.
+ */
+ public static long mmap(long address, long byteCount, int prot, int flags, FileDescriptor fd, long offset) throws ErrnoException { return Libcore.os.mmap(address, byteCount, prot, flags, fd, offset); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/msync.2.html">msync(2)</a>.
+ */
+ public static void msync(long address, long byteCount, int flags) throws ErrnoException { Libcore.os.msync(address, byteCount, flags); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/munlock.2.html">munlock(2)</a>.
+ */
+ public static void munlock(long address, long byteCount) throws ErrnoException { Libcore.os.munlock(address, byteCount); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/munmap.2.html">munmap(2)</a>.
+ */
+ public static void munmap(long address, long byteCount) throws ErrnoException { Libcore.os.munmap(address, byteCount); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>.
+ */
+ public static FileDescriptor open(String path, int flags, int mode) throws ErrnoException { return Libcore.os.open(path, flags, mode); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/pipe.2.html">pipe(2)</a>.
+ */
+ public static FileDescriptor[] pipe() throws ErrnoException { return Libcore.os.pipe(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/poll.2.html">poll(2)</a>.
+ */
+ public static int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException { return Libcore.os.poll(fds, timeoutMs); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/posix_fallocate.2.html">posix_fallocate(2)</a>.
+ */
+ public static void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException { Libcore.os.posix_fallocate(fd, offset, length); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/prctl.2.html">prctl(2)</a>.
+ */
+ public static int prctl(int option, long arg2, long arg3, long arg4, long arg5) throws ErrnoException { return Libcore.os.prctl(option, arg2, arg3, arg4, arg5); };
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/pread.2.html">pread(2)</a>.
+ */
+ public static int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException { return Libcore.os.pread(fd, buffer, offset); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/pread.2.html">pread(2)</a>.
+ */
+ public static int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException { return Libcore.os.pread(fd, bytes, byteOffset, byteCount, offset); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html">pwrite(2)</a>.
+ */
+ public static int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException { return Libcore.os.pwrite(fd, buffer, offset); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html">pwrite(2)</a>.
+ */
+ public static int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException { return Libcore.os.pwrite(fd, bytes, byteOffset, byteCount, offset); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</a>.
+ */
+ public static int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException { return Libcore.os.read(fd, buffer); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</a>.
+ */
+ public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException { return Libcore.os.read(fd, bytes, byteOffset, byteCount); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/readlink.2.html">readlink(2)</a>.
+ */
+ public static String readlink(String path) throws ErrnoException { return Libcore.os.readlink(path); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/readv.2.html">readv(2)</a>.
+ */
+ public static int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException { return Libcore.os.readv(fd, buffers, offsets, byteCounts); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/recvfrom.2.html">recvfrom(2)</a>.
+ */
+ public static int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException { return Libcore.os.recvfrom(fd, buffer, flags, srcAddress); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/recvfrom.2.html">recvfrom(2)</a>.
+ */
+ public static int recvfrom(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException { return Libcore.os.recvfrom(fd, bytes, byteOffset, byteCount, flags, srcAddress); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/remove.3.html">remove(3)</a>.
+ */
+ public static void remove(String path) throws ErrnoException { Libcore.os.remove(path); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/rename.2.html">rename(2)</a>.
+ */
+ public static void rename(String oldPath, String newPath) throws ErrnoException { Libcore.os.rename(oldPath, newPath); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/sendfile.2.html">sendfile(2)</a>.
+ */
+ public static long sendfile(FileDescriptor outFd, FileDescriptor inFd, MutableLong inOffset, long byteCount) throws ErrnoException { return Libcore.os.sendfile(outFd, inFd, inOffset, byteCount); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/sendto.2.html">sendto(2)</a>.
+ */
+ public static int sendto(FileDescriptor fd, ByteBuffer buffer, int flags, InetAddress inetAddress, int port) throws ErrnoException, SocketException { return Libcore.os.sendto(fd, buffer, flags, inetAddress, port); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/sendto.2.html">sendto(2)</a>.
+ */
+ public static int sendto(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetAddress inetAddress, int port) throws ErrnoException, SocketException { return Libcore.os.sendto(fd, bytes, byteOffset, byteCount, flags, inetAddress, port); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/setegid.2.html">setegid(2)</a>.
+ */
+ public static void setegid(int egid) throws ErrnoException { Libcore.os.setegid(egid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/setenv.3.html">setenv(3)</a>.
+ */
+ public static void setenv(String name, String value, boolean overwrite) throws ErrnoException { Libcore.os.setenv(name, value, overwrite); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/seteuid.2.html">seteuid(2)</a>.
+ */
+ public static void seteuid(int euid) throws ErrnoException { Libcore.os.seteuid(euid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.
+ */
+ public static void setgid(int gid) throws ErrnoException { Libcore.os.setgid(gid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/setsid.2.html">setsid(2)</a>.
+ */
+ public static int setsid() throws ErrnoException { return Libcore.os.setsid(); }
+
+ /** @hide */ public static void setsockoptByte(FileDescriptor fd, int level, int option, int value) throws ErrnoException { Libcore.os.setsockoptByte(fd, level, option, value); }
+ /** @hide */ public static void setsockoptIfreq(FileDescriptor fd, int level, int option, String value) throws ErrnoException { Libcore.os.setsockoptIfreq(fd, level, option, value); }
+ /** @hide */ public static void setsockoptInt(FileDescriptor fd, int level, int option, int value) throws ErrnoException { Libcore.os.setsockoptInt(fd, level, option, value); }
+ /** @hide */ public static void setsockoptIpMreqn(FileDescriptor fd, int level, int option, int value) throws ErrnoException { Libcore.os.setsockoptIpMreqn(fd, level, option, value); }
+ /** @hide */ public static void setsockoptGroupReq(FileDescriptor fd, int level, int option, StructGroupReq value) throws ErrnoException { Libcore.os.setsockoptGroupReq(fd, level, option, value); }
+ /** @hide */ public static void setsockoptGroupSourceReq(FileDescriptor fd, int level, int option, StructGroupSourceReq value) throws ErrnoException { Libcore.os.setsockoptGroupSourceReq(fd, level, option, value); }
+ /** @hide */ public static void setsockoptLinger(FileDescriptor fd, int level, int option, StructLinger value) throws ErrnoException { Libcore.os.setsockoptLinger(fd, level, option, value); }
+ /** @hide */ public static void setsockoptTimeval(FileDescriptor fd, int level, int option, StructTimeval value) throws ErrnoException { Libcore.os.setsockoptTimeval(fd, level, option, value); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.
+ */
+ public static void setuid(int uid) throws ErrnoException { Libcore.os.setuid(uid); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/shutdown.2.html">shutdown(2)</a>.
+ */
+ public static void shutdown(FileDescriptor fd, int how) throws ErrnoException { Libcore.os.shutdown(fd, how); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/socket.2.html">socket(2)</a>.
+ */
+ public static FileDescriptor socket(int domain, int type, int protocol) throws ErrnoException { return Libcore.os.socket(domain, type, protocol); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/socketpair.2.html">socketpair(2)</a>.
+ */
+ public static void socketpair(int domain, int type, int protocol, FileDescriptor fd1, FileDescriptor fd2) throws ErrnoException { Libcore.os.socketpair(domain, type, protocol, fd1, fd2); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/stat.2.html">stat(2)</a>.
+ */
+ public static StructStat stat(String path) throws ErrnoException { return Libcore.os.stat(path); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/statvfs.2.html">statvfs(2)</a>.
+ */
+ public static StructStatVfs statvfs(String path) throws ErrnoException { return Libcore.os.statvfs(path); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/strerror.3.html">strerror(2)</a>.
+ */
+ public static String strerror(int errno) { return Libcore.os.strerror(errno); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/strsignal.3.html">strsignal(3)</a>.
+ */
+ public static String strsignal(int signal) { return Libcore.os.strsignal(signal); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/symlink.2.html">symlink(2)</a>.
+ */
+ public static void symlink(String oldPath, String newPath) throws ErrnoException { Libcore.os.symlink(oldPath, newPath); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/sysconf.3.html">sysconf(3)</a>.
+ */
+ public static long sysconf(int name) { return Libcore.os.sysconf(name); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/tcdrain.3.html">tcdrain(3)</a>.
+ */
+ public static void tcdrain(FileDescriptor fd) throws ErrnoException { Libcore.os.tcdrain(fd); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/tcsendbreak.3.html">tcsendbreak(3)</a>.
+ */
+ public static void tcsendbreak(FileDescriptor fd, int duration) throws ErrnoException { Libcore.os.tcsendbreak(fd, duration); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/umask.2.html">umask(2)</a>.
+ */
+ public static int umask(int mask) { return Libcore.os.umask(mask); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/uname.2.html">uname(2)</a>.
+ */
+ public static StructUtsname uname() { return Libcore.os.uname(); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man3/unsetenv.3.html">unsetenv(3)</a>.
+ */
+ public static void unsetenv(String name) throws ErrnoException { Libcore.os.unsetenv(name); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/waitpid.2.html">waitpid(2)</a>.
+ */
+ public static int waitpid(int pid, MutableInt status, int options) throws ErrnoException { return Libcore.os.waitpid(pid, status, options); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/write.2.html">write(2)</a>.
+ */
+ public static int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException { return Libcore.os.write(fd, buffer); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/write.2.html">write(2)</a>.
+ */
+ public static int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException { return Libcore.os.write(fd, bytes, byteOffset, byteCount); }
+
+ /**
+ * See <a href="http://man7.org/linux/man-pages/man2/writev.2.html">writev(2)</a>.
+ */
+ public static int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException { return Libcore.os.writev(fd, buffers, offsets, byteCounts); }
+}
diff --git a/luni/src/main/java/libcore/io/OsConstants.java b/luni/src/main/java/android/system/OsConstants.java
index edecdd9..c758eb7 100644
--- a/luni/src/main/java/libcore/io/OsConstants.java
+++ b/luni/src/main/java/android/system/OsConstants.java
@@ -14,25 +14,83 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
+/**
+ * Constants and helper functions for use with {@link Os}.
+ */
public final class OsConstants {
- private OsConstants() { }
+ private OsConstants() {
+ }
+ /**
+ * Tests whether the given mode is a block device.
+ */
public static boolean S_ISBLK(int mode) { return (mode & S_IFMT) == S_IFBLK; }
+
+ /**
+ * Tests whether the given mode is a character device.
+ */
public static boolean S_ISCHR(int mode) { return (mode & S_IFMT) == S_IFCHR; }
+
+ /**
+ * Tests whether the given mode is a directory.
+ */
public static boolean S_ISDIR(int mode) { return (mode & S_IFMT) == S_IFDIR; }
+
+ /**
+ * Tests whether the given mode is a FIFO.
+ */
public static boolean S_ISFIFO(int mode) { return (mode & S_IFMT) == S_IFIFO; }
+
+ /**
+ * Tests whether the given mode is a regular file.
+ */
public static boolean S_ISREG(int mode) { return (mode & S_IFMT) == S_IFREG; }
+
+ /**
+ * Tests whether the given mode is a symbolic link.
+ */
public static boolean S_ISLNK(int mode) { return (mode & S_IFMT) == S_IFLNK; }
+
+ /**
+ * Tests whether the given mode is a socket.
+ */
public static boolean S_ISSOCK(int mode) { return (mode & S_IFMT) == S_IFSOCK; }
+ /**
+ * Extracts the exit status of a child. Only valid if WIFEXITED returns true.
+ */
public static int WEXITSTATUS(int status) { return (status & 0xff00) >> 8; }
+
+ /**
+ * Tests whether the child dumped core. Only valid if WIFSIGNALED returns true.
+ */
public static boolean WCOREDUMP(int status) { return (status & 0x80) != 0; }
+
+ /**
+ * Returns the signal that caused the child to exit. Only valid if WIFSIGNALED returns true.
+ */
public static int WTERMSIG(int status) { return status & 0x7f; }
+
+ /**
+ * Returns the signal that cause the child to stop. Only valid if WIFSTOPPED returns true.
+ */
public static int WSTOPSIG(int status) { return WEXITSTATUS(status); }
+
+ /**
+ * Tests whether the child exited normally.
+ */
public static boolean WIFEXITED(int status) { return (WTERMSIG(status) == 0); }
+
+ /**
+ * Tests whether the child was stopped (not terminated) by a signal.
+ */
public static boolean WIFSTOPPED(int status) { return (WTERMSIG(status) == 0x7f); }
+
+ /**
+ * Tests whether the child was terminated by a signal.
+ */
public static boolean WIFSIGNALED(int status) { return (WTERMSIG(status + 1) >= 2); }
public static final int AF_INET = placeholder();
@@ -48,6 +106,7 @@ public final class OsConstants {
public static final int AI_V4MAPPED = placeholder();
public static final int CAP_AUDIT_CONTROL = placeholder();
public static final int CAP_AUDIT_WRITE = placeholder();
+ public static final int CAP_BLOCK_SUSPEND = placeholder();
public static final int CAP_CHOWN = placeholder();
public static final int CAP_DAC_OVERRIDE = placeholder();
public static final int CAP_DAC_READ_SEARCH = placeholder();
@@ -194,6 +253,15 @@ public final class OsConstants {
public static final int F_SETOWN = placeholder();
public static final int F_UNLCK = placeholder();
public static final int F_WRLCK = placeholder();
+ public static final int IFA_F_DADFAILED = placeholder();
+ public static final int IFA_F_DEPRECATED = placeholder();
+ public static final int IFA_F_HOMEADDRESS = placeholder();
+ public static final int IFA_F_NODAD = placeholder();
+ public static final int IFA_F_OPTIMISTIC = placeholder();
+ public static final int IFA_F_PERMANENT = placeholder();
+ public static final int IFA_F_SECONDARY = placeholder();
+ public static final int IFA_F_TEMPORARY = placeholder();
+ public static final int IFA_F_TENTATIVE = placeholder();
public static final int IFF_ALLMULTI = placeholder();
public static final int IFF_AUTOMEDIA = placeholder();
public static final int IFF_BROADCAST = placeholder();
@@ -240,6 +308,10 @@ public final class OsConstants {
public static final int MAP_SHARED = placeholder();
public static final int MCAST_JOIN_GROUP = placeholder();
public static final int MCAST_LEAVE_GROUP = placeholder();
+ public static final int MCAST_JOIN_SOURCE_GROUP = placeholder();
+ public static final int MCAST_LEAVE_SOURCE_GROUP = placeholder();
+ public static final int MCAST_BLOCK_SOURCE = placeholder();
+ public static final int MCAST_UNBLOCK_SOURCE = placeholder();
public static final int MCL_CURRENT = placeholder();
public static final int MCL_FUTURE = placeholder();
public static final int MSG_CTRUNC = placeholder();
@@ -279,11 +351,19 @@ public final class OsConstants {
public static final int POLLRDNORM = placeholder();
public static final int POLLWRBAND = placeholder();
public static final int POLLWRNORM = placeholder();
+ public static final int PR_GET_DUMPABLE = placeholder();
+ public static final int PR_SET_DUMPABLE = placeholder();
+ public static final int PR_SET_NO_NEW_PRIVS = placeholder();
public static final int PROT_EXEC = placeholder();
public static final int PROT_NONE = placeholder();
public static final int PROT_READ = placeholder();
public static final int PROT_WRITE = placeholder();
public static final int R_OK = placeholder();
+ public static final int RT_SCOPE_HOST = placeholder();
+ public static final int RT_SCOPE_LINK = placeholder();
+ public static final int RT_SCOPE_NOWHERE = placeholder();
+ public static final int RT_SCOPE_SITE = placeholder();
+ public static final int RT_SCOPE_UNIVERSE = placeholder();
public static final int SEEK_CUR = placeholder();
public static final int SEEK_END = placeholder();
public static final int SEEK_SET = placeholder();
@@ -476,6 +556,10 @@ public final class OsConstants {
public static final int _SC_XOPEN_VERSION = placeholder();
public static final int _SC_XOPEN_XCU_VERSION = placeholder();
+ /**
+ * Returns the string name of a getaddrinfo(3) error value.
+ * For example, "EAI_AGAIN".
+ */
public static String gaiName(int error) {
if (error == EAI_AGAIN) {
return "EAI_AGAIN";
@@ -513,6 +597,10 @@ public final class OsConstants {
return null;
}
+ /**
+ * Returns the string name of an errno value.
+ * For example, "EACCES". See {@link Os#strerror} for human-readable errno descriptions.
+ */
public static String errnoName(int errno) {
if (errno == E2BIG) {
return "E2BIG";
diff --git a/luni/src/main/java/libcore/io/StructAddrinfo.java b/luni/src/main/java/android/system/StructAddrinfo.java
index 8c8181d..2425946 100644
--- a/luni/src/main/java/libcore/io/StructAddrinfo.java
+++ b/luni/src/main/java/android/system/StructAddrinfo.java
@@ -14,38 +14,45 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
import java.net.InetAddress;
+import libcore.util.Objects;
/**
* Information returned/taken by getaddrinfo(3). Corresponds to C's {@code struct addrinfo} from
* <a href="http://pubs.opengroup.org/onlinepubs/009695399/basedefs/netdb.h.html">&lt;netdb.h&gt;</a>
*
* TODO: we currently only _take_ a StructAddrinfo; getaddrinfo returns an InetAddress[].
+ *
+ * @hide
*/
public final class StructAddrinfo {
- /** Flags describing the kind of lookup to be done. (Such as AI_ADDRCONFIG.) */
- public int ai_flags;
+ /** Flags describing the kind of lookup to be done. (Such as AI_ADDRCONFIG.) */
+ public int ai_flags;
+
+ /** Desired address family for results. (Such as AF_INET6 for IPv6. AF_UNSPEC means "any".) */
+ public int ai_family;
- /** Desired address family for results. (Such as AF_INET6 for IPv6. AF_UNSPEC means "any".) */
- public int ai_family;
+ /** Socket type. (Such as SOCK_DGRAM. 0 means "any".) */
+ public int ai_socktype;
- /** Socket type. (Such as SOCK_DGRAM. 0 means "any".) */
- public int ai_socktype;
+ /** Protocol. (Such as IPPROTO_IPV6 IPv6. 0 means "any".) */
+ public int ai_protocol;
- /** Protocol. (Such as IPPROTO_IPV6 IPv6. 0 means "any".) */
- public int ai_protocol;
+ /** Address length. (Not useful in Java.) */
+ // public int ai_addrlen;
- /** Address length. (Not useful in Java.) */
- // public int ai_addrlen;
+ /** Address. */
+ public InetAddress ai_addr;
- /** Address. */
- public InetAddress ai_addr;
+ /** Canonical name of service location (if AI_CANONNAME provided in ai_flags). */
+ // public String ai_canonname;
- /** Canonical name of service location (if AI_CANONNAME provided in ai_flags). */
- // public String ai_canonname;
+ /** Next element in linked list. */
+ public StructAddrinfo ai_next;
- /** Next element in linked list. */
- public StructAddrinfo ai_next;
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
}
diff --git a/luni/src/main/java/libcore/io/StructFlock.java b/luni/src/main/java/android/system/StructFlock.java
index 11c29df..92cd95a 100644
--- a/luni/src/main/java/libcore/io/StructFlock.java
+++ b/luni/src/main/java/android/system/StructFlock.java
@@ -14,26 +14,34 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
+
+import libcore.util.Objects;
/**
* Information returned/taken by fcntl(2) F_GETFL and F_SETFL. Corresponds to C's
* {@code struct flock} from
* <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/fcntl.h.html">&lt;fcntl.h&gt;</a>
+ *
+ * @hide
*/
public final class StructFlock {
- /** The operation type, one of F_RDLCK, F_WRLCK, or F_UNLCK. */
- public short l_type;
+ /** The operation type, one of F_RDLCK, F_WRLCK, or F_UNLCK. */
+ public short l_type;
+
+ /** How to interpret l_start, one of SEEK_CUR, SEEK_END, SEEK_SET. */
+ public short l_whence;
- /** How to interpret l_start, one of SEEK_CUR, SEEK_END, SEEK_SET. */
- public short l_whence;
+ /** Start offset. */
+ public long l_start; /*off_t*/
- /** Start offset. */
- public long l_start; /*off_t*/
+ /** Byte count to operate on. */
+ public long l_len; /*off_t*/
- /** Byte count to operate on. */
- public long l_len; /*off_t*/
+ /** Process blocking our lock (filled in by F_GETLK, otherwise unused). */
+ public int l_pid; /*pid_t*/
- /** Process blocking our lock (filled in by F_GETLK, otherwise unused). */
- public int l_pid; /*pid_t*/
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
}
diff --git a/luni/src/main/java/libcore/io/StructGroupReq.java b/luni/src/main/java/android/system/StructGroupReq.java
index 0bdf783..8ed5950 100644
--- a/luni/src/main/java/libcore/io/StructGroupReq.java
+++ b/luni/src/main/java/android/system/StructGroupReq.java
@@ -14,23 +14,26 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
import java.net.InetAddress;
+import libcore.util.Objects;
/**
* Corresponds to C's {@code struct group_req}.
+ *
+ * @hide
*/
public final class StructGroupReq {
- public final int gr_interface;
- public final InetAddress gr_group;
+ public final int gr_interface;
+ public final InetAddress gr_group;
- public StructGroupReq(int gr_interface, InetAddress gr_group) {
- this.gr_interface = gr_interface;
- this.gr_group = gr_group;
- }
+ public StructGroupReq(int gr_interface, InetAddress gr_group) {
+ this.gr_interface = gr_interface;
+ this.gr_group = gr_group;
+ }
- @Override public String toString() {
- return "StructGroupReq[gr_interface=" + gr_interface + ",gr_group=" + gr_group + "]";
- }
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
}
diff --git a/luni/src/main/java/android/system/StructGroupSourceReq.java b/luni/src/main/java/android/system/StructGroupSourceReq.java
new file mode 100644
index 0000000..c300338
--- /dev/null
+++ b/luni/src/main/java/android/system/StructGroupSourceReq.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2014 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 android.system;
+
+import java.net.InetAddress;
+import libcore.util.Objects;
+
+/**
+ * Corresponds to C's {@code struct group_source_req}.
+ *
+ * @hide
+ */
+public final class StructGroupSourceReq {
+ public final int gsr_interface;
+ public final InetAddress gsr_group;
+ public final InetAddress gsr_source;
+
+ public StructGroupSourceReq(int gsr_interface, InetAddress gsr_group, InetAddress gsr_source) {
+ this.gsr_interface = gsr_interface;
+ this.gsr_group = gsr_group;
+ this.gsr_source = gsr_source;
+ }
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
+}
diff --git a/luni/src/main/java/libcore/io/StructLinger.java b/luni/src/main/java/android/system/StructLinger.java
index 9f149af..55ffc5c 100644
--- a/luni/src/main/java/libcore/io/StructLinger.java
+++ b/luni/src/main/java/android/system/StructLinger.java
@@ -14,29 +14,33 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
+
+import libcore.util.Objects;
/**
* Corresponds to C's {@code struct linger} from
* <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_socket.h.html">&lt;sys/socket.h&gt;</a>
+ *
+ * @hide
*/
public final class StructLinger {
- /** Whether or not linger is enabled. Non-zero is on. */
- public final int l_onoff;
+ /** Whether or not linger is enabled. Non-zero is on. */
+ public final int l_onoff;
- /** Linger time in seconds. */
- public final int l_linger;
+ /** Linger time in seconds. */
+ public final int l_linger;
- public StructLinger(int l_onoff, int l_linger) {
- this.l_onoff = l_onoff;
- this.l_linger = l_linger;
- }
+ public StructLinger(int l_onoff, int l_linger) {
+ this.l_onoff = l_onoff;
+ this.l_linger = l_linger;
+ }
- public boolean isOn() {
- return l_onoff != 0;
- }
+ public boolean isOn() {
+ return l_onoff != 0;
+ }
- @Override public String toString() {
- return "StructLinger[l_onoff=" + l_onoff + ",l_linger=" + l_linger + "]";
- }
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
}
diff --git a/luni/src/main/java/android/system/StructPasswd.java b/luni/src/main/java/android/system/StructPasswd.java
new file mode 100644
index 0000000..04a7826
--- /dev/null
+++ b/luni/src/main/java/android/system/StructPasswd.java
@@ -0,0 +1,48 @@
+/*
+ * 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 android.system;
+
+import libcore.util.Objects;
+
+/**
+ * Information returned by {@link Os#getpwnam} and {@link Os#getpwuid}. Corresponds to C's
+ * {@code struct passwd} from {@code &lt;pwd.h&gt;}.
+ *
+ * @hide
+ */
+public final class StructPasswd {
+ public final String pw_name;
+ public final int pw_uid;
+ public final int pw_gid;
+ public final String pw_dir;
+ public final String pw_shell;
+
+ /**
+ * Constructs an instance with the given field values.
+ */
+ public StructPasswd(String pw_name, int pw_uid, int pw_gid, String pw_dir, String pw_shell) {
+ this.pw_name = pw_name;
+ this.pw_uid = pw_uid;
+ this.pw_gid = pw_gid;
+ this.pw_dir = pw_dir;
+ this.pw_shell = pw_shell;
+ }
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
+}
diff --git a/luni/src/main/java/android/system/StructPollfd.java b/luni/src/main/java/android/system/StructPollfd.java
new file mode 100644
index 0000000..b812612
--- /dev/null
+++ b/luni/src/main/java/android/system/StructPollfd.java
@@ -0,0 +1,49 @@
+/*
+ * 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 android.system;
+
+import java.io.FileDescriptor;
+import libcore.util.Objects;
+
+/**
+ * Used as an in/out parameter to {@link Os#poll}.
+ * Corresponds to C's {@code struct pollfd} from {@code &lt;poll.h&gt;}.
+ */
+public final class StructPollfd {
+ /** The file descriptor to poll. */
+ public FileDescriptor fd;
+
+ /**
+ * The events we're interested in. POLLIN corresponds to being in select(2)'s read fd set,
+ * POLLOUT to the write fd set.
+ */
+ public short events;
+
+ /** The events that actually happened. */
+ public short revents;
+
+ /**
+ * A non-standard extension that lets callers conveniently map back to the object
+ * their fd belongs to. This is used by Selector, for example, to associate each
+ * FileDescriptor with the corresponding SelectionKey.
+ */
+ public Object userData;
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
+}
diff --git a/luni/src/main/java/android/system/StructStat.java b/luni/src/main/java/android/system/StructStat.java
new file mode 100644
index 0000000..a6958c1
--- /dev/null
+++ b/luni/src/main/java/android/system/StructStat.java
@@ -0,0 +1,98 @@
+/*
+ * 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 android.system;
+
+import libcore.util.Objects;
+
+/**
+ * File information returned by {@link Os#fstat}, {@link Os#lstat}, and {@link Os#stat}.
+ * Corresponds to C's {@code struct stat} from {@code &lt;stat.h&gt;}.
+ */
+public final class StructStat {
+ /** Device ID of device containing file. */
+ public final long st_dev; /*dev_t*/
+
+ /** File serial number (inode). */
+ public final long st_ino; /*ino_t*/
+
+ /** Mode (permissions) of file. */
+ public final int st_mode; /*mode_t*/
+
+ /** Number of hard links to the file. */
+ public final long st_nlink; /*nlink_t*/
+
+ /** User ID of file. */
+ public final int st_uid; /*uid_t*/
+
+ /** Group ID of file. */
+ public final int st_gid; /*gid_t*/
+
+ /** Device ID (if file is character or block special). */
+ public final long st_rdev; /*dev_t*/
+
+ /**
+ * For regular files, the file size in bytes.
+ * For symbolic links, the length in bytes of the pathname contained in the symbolic link.
+ * For a shared memory object, the length in bytes.
+ * For a typed memory object, the length in bytes.
+ * For other file types, the use of this field is unspecified.
+ */
+ public final long st_size; /*off_t*/
+
+ /** Time of last access. */
+ public final long st_atime; /*time_t*/
+
+ /** Time of last data modification. */
+ public final long st_mtime; /*time_t*/
+
+ /** Time of last status change. */
+ public final long st_ctime; /*time_t*/
+
+ /**
+ * A file system-specific preferred I/O block size for this object.
+ * For some file system types, this may vary from file to file.
+ */
+ public final long st_blksize; /*blksize_t*/
+
+ /** Number of blocks allocated for this object. */
+ public final long st_blocks; /*blkcnt_t*/
+
+ /**
+ * Constructs an instance with the given field values.
+ */
+ public StructStat(long st_dev, long st_ino, int st_mode, long st_nlink, int st_uid, int st_gid,
+ long st_rdev, long st_size, long st_atime, long st_mtime, long st_ctime,
+ long st_blksize, long st_blocks) {
+ this.st_dev = st_dev;
+ this.st_ino = st_ino;
+ this.st_mode = st_mode;
+ this.st_nlink = st_nlink;
+ this.st_uid = st_uid;
+ this.st_gid = st_gid;
+ this.st_rdev = st_rdev;
+ this.st_size = st_size;
+ this.st_atime = st_atime;
+ this.st_mtime = st_mtime;
+ this.st_ctime = st_ctime;
+ this.st_blksize = st_blksize;
+ this.st_blocks = st_blocks;
+ }
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
+}
diff --git a/luni/src/main/java/libcore/io/StructStatVfs.java b/luni/src/main/java/android/system/StructStatVfs.java
index bb78ff2..942a39a 100644
--- a/luni/src/main/java/libcore/io/StructStatVfs.java
+++ b/luni/src/main/java/android/system/StructStatVfs.java
@@ -14,10 +14,12 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
+
+import libcore.util.Objects;
/**
- * File information returned by fstatvfs(2) and statvfs(2).
+ * File information returned by {@link Os#fstatvfs} and {@link Os#statvfs}.
*/
public final class StructStatVfs {
/** File system block size (used for block counts). */
@@ -53,7 +55,10 @@ public final class StructStatVfs {
/** Maximum filename length. */
public final long f_namemax; /*unsigned long*/
- StructStatVfs(long f_bsize, long f_frsize, long f_blocks, long f_bfree, long f_bavail,
+ /**
+ * Constructs an instance with the given field values.
+ */
+ public StructStatVfs(long f_bsize, long f_frsize, long f_blocks, long f_bfree, long f_bavail,
long f_files, long f_ffree, long f_favail,
long f_fsid, long f_flag, long f_namemax) {
this.f_bsize = f_bsize;
@@ -68,4 +73,8 @@ public final class StructStatVfs {
this.f_flag = f_flag;
this.f_namemax = f_namemax;
}
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
}
diff --git a/luni/src/main/java/libcore/io/StructTimeval.java b/luni/src/main/java/android/system/StructTimeval.java
index 0ed3509..8a155b4 100644
--- a/luni/src/main/java/libcore/io/StructTimeval.java
+++ b/luni/src/main/java/android/system/StructTimeval.java
@@ -14,35 +14,39 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
+
+import libcore.util.Objects;
/**
* Corresponds to C's {@code struct timeval} from
* <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_time.h.html">&lt;sys/time.h&gt;</a>
+ *
+ * @hide
*/
public final class StructTimeval {
- /** Seconds. */
- public final long tv_sec;
-
- /** Microseconds. */
- public final long tv_usec;
-
- private StructTimeval(long tv_sec, long tv_usec) {
- this.tv_sec = tv_sec;
- this.tv_usec = tv_usec;
- }
-
- public static StructTimeval fromMillis(long millis) {
- long tv_sec = millis / 1000;
- long tv_usec = (millis - (tv_sec * 1000)) * 1000;
- return new StructTimeval(tv_sec, tv_usec);
- }
-
- public long toMillis() {
- return (tv_sec * 1000) + (tv_usec / 1000);
- }
-
- @Override public String toString() {
- return "StructTimeval[tv_sec=" + tv_sec + ",tv_usec=" + tv_usec + "]";
- }
+ /** Seconds. */
+ public final long tv_sec;
+
+ /** Microseconds. */
+ public final long tv_usec;
+
+ private StructTimeval(long tv_sec, long tv_usec) {
+ this.tv_sec = tv_sec;
+ this.tv_usec = tv_usec;
+ }
+
+ public static StructTimeval fromMillis(long millis) {
+ long tv_sec = millis / 1000;
+ long tv_usec = (millis - (tv_sec * 1000)) * 1000;
+ return new StructTimeval(tv_sec, tv_usec);
+ }
+
+ public long toMillis() {
+ return (tv_sec * 1000) + (tv_usec / 1000);
+ }
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
}
diff --git a/luni/src/main/java/libcore/io/StructUcred.java b/luni/src/main/java/android/system/StructUcred.java
index 359995d..a1e3cd6 100644
--- a/luni/src/main/java/libcore/io/StructUcred.java
+++ b/luni/src/main/java/android/system/StructUcred.java
@@ -14,10 +14,14 @@
* limitations under the License.
*/
-package libcore.io;
+package android.system;
+
+import libcore.util.Objects;
/**
* Corresponds to C's {@code struct ucred}.
+ *
+ * @hide
*/
public final class StructUcred {
/** The peer's process id. */
@@ -29,13 +33,13 @@ public final class StructUcred {
/** The peer process' gid. */
public final int gid;
- private StructUcred(int pid, int uid, int gid) {
+ public StructUcred(int pid, int uid, int gid) {
this.pid = pid;
this.uid = uid;
this.gid = gid;
}
@Override public String toString() {
- return "StructUcred[pid=" + pid + ",uid=" + uid + ",gid=" + gid + "]";
+ return Objects.toString(this);
}
}
diff --git a/luni/src/main/java/android/system/StructUtsname.java b/luni/src/main/java/android/system/StructUtsname.java
new file mode 100644
index 0000000..5d9127b
--- /dev/null
+++ b/luni/src/main/java/android/system/StructUtsname.java
@@ -0,0 +1,55 @@
+/*
+ * 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 android.system;
+
+import libcore.util.Objects;
+
+/**
+ * Information returned by {@link Os#uname}.
+ * Corresponds to C's {@code struct utsname} from {@code &lt;sys/utsname.h&gt;}.
+ */
+public final class StructUtsname {
+ /** The OS name, such as "Linux". */
+ public final String sysname;
+
+ /** The machine's unqualified name on some implementation-defined network. */
+ public final String nodename;
+
+ /** The OS release, such as "2.6.35-27-generic". */
+ public final String release;
+
+ /** The OS version, such as "#48-Ubuntu SMP Tue Feb 22 20:25:29 UTC 2011". */
+ public final String version;
+
+ /** The machine architecture, such as "armv7l" or "x86_64". */
+ public final String machine;
+
+ /**
+ * Constructs an instance with the given field values.
+ */
+ public StructUtsname(String sysname, String nodename, String release, String version, String machine) {
+ this.sysname = sysname;
+ this.nodename = nodename;
+ this.release = release;
+ this.version = version;
+ this.machine = machine;
+ }
+
+ @Override public String toString() {
+ return Objects.toString(this);
+ }
+}
diff --git a/luni/src/main/java/libcore/util/MutableBoolean.java b/luni/src/main/java/android/util/MutableBoolean.java
index 359a8f9..5a8a200 100644
--- a/luni/src/main/java/libcore/util/MutableBoolean.java
+++ b/luni/src/main/java/android/util/MutableBoolean.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableBoolean {
- public boolean value;
+ public boolean value;
- public MutableBoolean(boolean value) {
- this.value = value;
- }
+ public MutableBoolean(boolean value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableByte.java b/luni/src/main/java/android/util/MutableByte.java
index 13f780b..7397ba4 100644
--- a/luni/src/main/java/libcore/util/MutableByte.java
+++ b/luni/src/main/java/android/util/MutableByte.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableByte {
- public byte value;
+ public byte value;
- public MutableByte(byte value) {
- this.value = value;
- }
+ public MutableByte(byte value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableChar.java b/luni/src/main/java/android/util/MutableChar.java
index 1cafc3c..f435331 100644
--- a/luni/src/main/java/libcore/util/MutableChar.java
+++ b/luni/src/main/java/android/util/MutableChar.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableChar {
- public char value;
+ public char value;
- public MutableChar(char value) {
- this.value = value;
- }
+ public MutableChar(char value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableDouble.java b/luni/src/main/java/android/util/MutableDouble.java
index 4473ae6..f62f47e 100644
--- a/luni/src/main/java/libcore/util/MutableDouble.java
+++ b/luni/src/main/java/android/util/MutableDouble.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableDouble {
- public double value;
+ public double value;
- public MutableDouble(double value) {
- this.value = value;
- }
+ public MutableDouble(double value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableFloat.java b/luni/src/main/java/android/util/MutableFloat.java
index f81fba5..6b5441c 100644
--- a/luni/src/main/java/libcore/util/MutableFloat.java
+++ b/luni/src/main/java/android/util/MutableFloat.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableFloat {
- public float value;
+ public float value;
- public MutableFloat(float value) {
- this.value = value;
- }
+ public MutableFloat(float value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableInt.java b/luni/src/main/java/android/util/MutableInt.java
index c8feb3a..2f93030 100644
--- a/luni/src/main/java/libcore/util/MutableInt.java
+++ b/luni/src/main/java/android/util/MutableInt.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableInt {
- public int value;
+ public int value;
- public MutableInt(int value) {
- this.value = value;
- }
+ public MutableInt(int value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableLong.java b/luni/src/main/java/android/util/MutableLong.java
index ad9b78e..94beab5 100644
--- a/luni/src/main/java/libcore/util/MutableLong.java
+++ b/luni/src/main/java/android/util/MutableLong.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableLong {
- public long value;
+ public long value;
- public MutableLong(long value) {
- this.value = value;
- }
+ public MutableLong(long value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/libcore/util/MutableShort.java b/luni/src/main/java/android/util/MutableShort.java
index 78b4c33..cdd9923 100644
--- a/luni/src/main/java/libcore/util/MutableShort.java
+++ b/luni/src/main/java/android/util/MutableShort.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package libcore.util;
+package android.util;
+/**
+ */
public final class MutableShort {
- public short value;
+ public short value;
- public MutableShort(short value) {
- this.value = value;
- }
+ public MutableShort(short value) {
+ this.value = value;
+ }
}
diff --git a/luni/src/main/java/java/io/BufferedInputStream.java b/luni/src/main/java/java/io/BufferedInputStream.java
index 5a810e7..85236b6 100644
--- a/luni/src/main/java/java/io/BufferedInputStream.java
+++ b/luni/src/main/java/java/io/BufferedInputStream.java
@@ -37,6 +37,13 @@ import java.util.Arrays;
*/
public class BufferedInputStream extends FilterInputStream {
/**
+ * The default buffer size if it is not specified.
+ *
+ * @hide
+ */
+ public static final int DEFAULT_BUFFER_SIZE = 8192;
+
+ /**
* The buffer containing the current bytes read from the target InputStream.
*/
protected volatile byte[] buf;
@@ -73,7 +80,7 @@ public class BufferedInputStream extends FilterInputStream {
* @param in the {@code InputStream} the buffer reads from.
*/
public BufferedInputStream(InputStream in) {
- this(in, 8192);
+ this(in, DEFAULT_BUFFER_SIZE);
}
/**
@@ -325,7 +332,7 @@ public class BufferedInputStream extends FilterInputStream {
if (buf == null) {
throw new IOException("Stream is closed");
}
- if (-1 == markpos) {
+ if (markpos == -1) {
throw new IOException("Mark has been invalidated.");
}
pos = markpos;
diff --git a/luni/src/main/java/java/io/Console.java b/luni/src/main/java/java/io/Console.java
index a1d2097..fe07694c 100644
--- a/luni/src/main/java/java/io/Console.java
+++ b/luni/src/main/java/java/io/Console.java
@@ -16,9 +16,7 @@
package java.io;
import java.util.Formatter;
-import libcore.io.ErrnoException;
import libcore.io.Libcore;
-import static libcore.io.OsConstants.*;
/**
* Provides access to the console, if available. The system-wide instance can
@@ -48,12 +46,12 @@ public final class Console implements Flushable {
}
try {
return new Console(System.in, System.out);
- } catch (IOException ex) {
+ } catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
- private Console(InputStream in, OutputStream out) throws IOException {
+ private Console(InputStream in, OutputStream out) throws UnsupportedEncodingException {
this.reader = new ConsoleReader(in);
this.writer = new ConsoleWriter(out);
}
@@ -129,48 +127,17 @@ public final class Console implements Flushable {
}
/**
- * Reads a password from the console. The password will not be echoed to the display.
- *
- * @return a character array containing the password, or null at EOF.
+ * This method is unimplemented on Android.
*/
public char[] readPassword() {
- synchronized (CONSOLE_LOCK) {
- int previousState = setEcho(false, 0);
- try {
- String password = readLine();
- writer.println(); // We won't have echoed the user's newline.
- return (password == null) ? null : password.toCharArray();
- } finally {
- setEcho(true, previousState);
- }
- }
- }
-
- private static int setEcho(boolean on, int previousState) {
- try {
- return setEchoImpl(on, previousState);
- } catch (IOException ex) {
- throw new IOError(ex);
- }
+ throw new UnsupportedOperationException();
}
- private static native int setEchoImpl(boolean on, int previousState) throws IOException;
/**
- * Reads a password from the console. The password will not be echoed to the display.
- * A formatted prompt is also displayed.
- *
- * @param format the format string (see {@link java.util.Formatter#format})
- * @param args
- * the list of arguments passed to the formatter. If there are
- * more arguments than required by {@code format},
- * additional arguments are ignored.
- * @return a character array containing the password, or null at EOF.
+ * This method is unimplemented on Android.
*/
public char[] readPassword(String format, Object... args) {
- synchronized (CONSOLE_LOCK) {
- format(format, args);
- return readPassword();
- }
+ throw new UnsupportedOperationException();
}
/**
@@ -181,7 +148,7 @@ public final class Console implements Flushable {
}
private static class ConsoleReader extends BufferedReader {
- public ConsoleReader(InputStream in) throws IOException {
+ public ConsoleReader(InputStream in) throws UnsupportedEncodingException {
super(new InputStreamReader(in, System.getProperty("file.encoding")), 256);
lock = CONSOLE_LOCK;
}
diff --git a/luni/src/main/java/java/io/File.java b/luni/src/main/java/java/io/File.java
index a8b4810..d107c28 100644
--- a/luni/src/main/java/java/io/File.java
+++ b/luni/src/main/java/java/io/File.java
@@ -17,19 +17,19 @@
package java.io;
+import android.system.ErrnoException;
+import android.system.StructStat;
+import android.system.StructStatVfs;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
-import libcore.io.ErrnoException;
+import libcore.io.DeleteOnExit;
import libcore.io.IoUtils;
import libcore.io.Libcore;
-import libcore.io.StructStat;
-import libcore.io.StructStatVfs;
-import org.apache.harmony.luni.util.DeleteOnExit;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* An "abstract" representation of a file system entity identified by a
@@ -411,15 +411,10 @@ public class File implements Serializable, Comparable<File> {
* if an I/O error occurs.
*/
public String getCanonicalPath() throws IOException {
- return realpath(getAbsolutePath());
+ return canonicalizePath(getAbsolutePath());
}
- /**
- * TODO: move this stuff to libcore.os.
- * @hide
- */
- private static native String realpath(String path);
- private static native String readlink(String path);
+ private static native String canonicalizePath(String path);
/**
* Returns a new file created using the canonical path of this file.
diff --git a/luni/src/main/java/java/io/FileDescriptor.java b/luni/src/main/java/java/io/FileDescriptor.java
index e4eb06c..eba0e4d 100644
--- a/luni/src/main/java/java/io/FileDescriptor.java
+++ b/luni/src/main/java/java/io/FileDescriptor.java
@@ -17,9 +17,9 @@
package java.io;
-import libcore.io.ErrnoException;
+import android.system.ErrnoException;
import libcore.io.Libcore;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* Wraps a Unix file descriptor. It's possible to get the file descriptor used by some
@@ -105,6 +105,15 @@ public final class FileDescriptor {
this.descriptor = fd;
}
+ /**
+ * @hide internal use only
+ */
+ public boolean isSocket() {
+ return isSocket(descriptor);
+ }
+
+ private static native boolean isSocket(int fd);
+
@Override public String toString() {
return "FileDescriptor[" + descriptor + "]";
}
diff --git a/luni/src/main/java/java/io/FileInputStream.java b/luni/src/main/java/java/io/FileInputStream.java
index b2e620f..7944ef1 100644
--- a/luni/src/main/java/java/io/FileInputStream.java
+++ b/luni/src/main/java/java/io/FileInputStream.java
@@ -19,15 +19,13 @@ package java.io;
import dalvik.system.CloseGuard;
-import java.nio.NioUtils;
+import android.system.ErrnoException;
import java.nio.channels.FileChannel;
-import java.util.Arrays;
-import libcore.io.ErrnoException;
+import java.nio.NioUtils;
import libcore.io.IoBridge;
-import libcore.io.IoUtils;
import libcore.io.Libcore;
import libcore.io.Streams;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* An input stream that reads bytes from a file.
@@ -75,7 +73,7 @@ public class FileInputStream extends InputStream {
if (file == null) {
throw new NullPointerException("file == null");
}
- this.fd = IoBridge.open(file.getAbsolutePath(), O_RDONLY);
+ this.fd = IoBridge.open(file.getPath(), O_RDONLY);
this.shouldClose = true;
guard.open("close");
}
@@ -118,7 +116,7 @@ public class FileInputStream extends InputStream {
channel.close();
}
if (shouldClose) {
- IoUtils.close(fd);
+ IoBridge.closeAndSignalBlockedThreads(fd);
} else {
// An owned fd has been invalidated by IoUtils.close, but
// we need to explicitly stop using an unowned fd (http://b/4361076).
diff --git a/luni/src/main/java/java/io/FileOutputStream.java b/luni/src/main/java/java/io/FileOutputStream.java
index e04ab5f..f91ee20 100644
--- a/luni/src/main/java/java/io/FileOutputStream.java
+++ b/luni/src/main/java/java/io/FileOutputStream.java
@@ -20,10 +20,9 @@ package java.io;
import dalvik.system.CloseGuard;
import java.nio.NioUtils;
import java.nio.channels.FileChannel;
-import java.util.Arrays;
import libcore.io.IoBridge;
-import libcore.io.IoUtils;
-import static libcore.io.OsConstants.*;
+
+import static android.system.OsConstants.*;
/**
* An output stream that writes bytes to a file. If the output file exists, it
@@ -85,7 +84,7 @@ public class FileOutputStream extends OutputStream {
throw new NullPointerException("file == null");
}
this.mode = O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC);
- this.fd = IoBridge.open(file.getAbsolutePath(), mode);
+ this.fd = IoBridge.open(file.getPath(), mode);
this.shouldClose = true;
this.guard.open("close");
}
@@ -136,7 +135,7 @@ public class FileOutputStream extends OutputStream {
channel.close();
}
if (shouldClose) {
- IoUtils.close(fd);
+ IoBridge.closeAndSignalBlockedThreads(fd);
} else {
// An owned fd has been invalidated by IoUtils.close, but
// we need to explicitly stop using an unowned fd (http://b/4361076).
diff --git a/luni/src/main/java/java/io/InputStream.java b/luni/src/main/java/java/io/InputStream.java
index 973382e..c489b2a 100644
--- a/luni/src/main/java/java/io/InputStream.java
+++ b/luni/src/main/java/java/io/InputStream.java
@@ -209,19 +209,21 @@ public abstract class InputStream extends Object implements Closeable {
}
/**
- * Skips at most {@code n} bytes in this stream. This method does nothing and returns
- * 0 if {@code n} is negative, but some subclasses may throw.
+ * Skips at most {@code byteCount} bytes in this stream. The number of actual
+ * bytes skipped may be anywhere between 0 and {@code byteCount}. If
+ * {@code byteCount} is negative, this method does nothing and returns 0, but
+ * some subclasses may throw.
*
- * <p>Note the "at most" in the description of this method: this method may choose to skip
- * fewer bytes than requested. Callers should <i>always</i> check the return value.
+ * <p>Note the "at most" in the description of this method: this method may
+ * choose to skip fewer bytes than requested. Callers should <i>always</i>
+ * check the return value.
*
- * <p>This default implementation reads bytes into a temporary
- * buffer. Concrete subclasses should provide their own implementation.
+ * <p>This default implementation reads bytes into a temporary buffer. Concrete
+ * subclasses should provide their own implementation.
*
- * @param byteCount the number of bytes to skip.
* @return the number of bytes actually skipped.
- * @throws IOException
- * if this stream is closed or another IOException occurs.
+ * @throws IOException if this stream is closed or another IOException
+ * occurs.
*/
public long skip(long byteCount) throws IOException {
return Streams.skipByReading(this, byteCount);
diff --git a/luni/src/main/java/java/io/InputStreamReader.java b/luni/src/main/java/java/io/InputStreamReader.java
index 01e7f29..d57b916 100644
--- a/luni/src/main/java/java/io/InputStreamReader.java
+++ b/luni/src/main/java/java/io/InputStreamReader.java
@@ -23,8 +23,6 @@ import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
-import java.nio.charset.MalformedInputException;
-import java.nio.charset.UnmappableCharacterException;
import java.util.Arrays;
/**
@@ -260,7 +258,9 @@ public class InputStreamReader extends Reader {
if (result == CoderResult.UNDERFLOW && endOfInput) {
result = decoder.decode(bytes, out, true);
- decoder.flush(out);
+ if (result == CoderResult.UNDERFLOW) {
+ result = decoder.flush(out);
+ }
decoder.reset();
}
if (result.isMalformed() || result.isUnmappable()) {
diff --git a/luni/src/main/java/java/io/ObjectInputStream.java b/luni/src/main/java/java/io/ObjectInputStream.java
index 17a6974..3a89b52 100644
--- a/luni/src/main/java/java/io/ObjectInputStream.java
+++ b/luni/src/main/java/java/io/ObjectInputStream.java
@@ -1739,9 +1739,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput, Objec
*/
protected Class<?> resolveProxyClass(String[] interfaceNames)
throws IOException, ClassNotFoundException {
- // TODO: This method is opportunity for performance enhancement
- // We can cache the classloader and recently used interfaces.
- ClassLoader loader = ClassLoader.getSystemClassLoader();
+ ClassLoader loader = callerClassLoader;
Class<?>[] interfaces = new Class<?>[interfaceNames.length];
for (int i = 0; i < interfaceNames.length; i++) {
interfaces[i] = Class.forName(interfaceNames[i], false, loader);
diff --git a/luni/src/main/java/java/io/ObjectOutput.java b/luni/src/main/java/java/io/ObjectOutput.java
index 2e454ec..e6d7b0c 100644
--- a/luni/src/main/java/java/io/ObjectOutput.java
+++ b/luni/src/main/java/java/io/ObjectOutput.java
@@ -18,7 +18,7 @@
package java.io;
/**
- * Defines an interface for classes that allow reading serialized objects.
+ * Defines an interface for classes that allow writing serialized objects.
*
* @see ObjectOutputStream
* @see ObjectInput
diff --git a/luni/src/main/java/java/io/ObjectOutputStream.java b/luni/src/main/java/java/io/ObjectOutputStream.java
index 6a2fbed..f67919d 100644
--- a/luni/src/main/java/java/io/ObjectOutputStream.java
+++ b/luni/src/main/java/java/io/ObjectOutputStream.java
@@ -39,15 +39,13 @@ import libcore.io.SizeOf;
*/
public class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants {
- private static final Class<?>[] WRITE_UNSHARED_PARAM_TYPES = new Class[] { Object.class };
-
/*
* Mask to zero SC_BLOC_DATA bit.
*/
private static final byte NOT_SC_BLOCK_DATA = (byte) (SC_BLOCK_DATA ^ 0xFF);
/*
- * How many nested levels to writeObject. We may not need this.
+ * How many nested levels to writeObject.
*/
private int nestedLevels;
@@ -98,11 +96,6 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
private int protocolVersion;
/*
- * Used to detect nested exception when saving an exception due to an error
- */
- private StreamCorruptedException nestedException;
-
- /*
* Used to keep track of the PutField object for the class/object being
* written
*/
@@ -271,7 +264,6 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
this.subclassOverridingImplementation = false;
resetState();
- this.nestedException = new StreamCorruptedException();
// So write...() methods can be used by
// subclasses during writeStreamHeader()
primitiveTypes = this.output;
@@ -462,20 +454,6 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
output.flush();
}
- /*
- * These methods get the value of a field named fieldName of object
- * instance. The field is declared by declaringClass. The field is the same
- * type as the method return value.
- *
- * these methods could be implemented non-natively on top of
- * java.lang.reflect at the expense of extra object creation
- * (java.lang.reflect.Field). Otherwise Serialization could not fetch
- * private fields, except by the use of a native method like this one.
- *
- * @throws NoSuchFieldError If the field does not exist.
- */
- private static native Object getFieldL(Object instance, Class<?> declaringClass, String fieldName, String fieldTypeName);
-
/**
* Return the next handle to be used to indicate cyclic
* references being saved to the stream.
@@ -1236,7 +1214,7 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
// The handle for the classDesc is NOT the handle for the class object
// being dumped. We must allocate a new handle and return it.
if (clDesc.isEnum()) {
- writeEnumDesc(object, clDesc, unshared);
+ writeEnumDesc(clDesc, unshared);
} else {
writeClassDesc(clDesc, unshared);
}
@@ -1521,14 +1499,15 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
primitiveTypes = output;
}
} catch (IOException ioEx1) {
- // This will make it pass through until the top caller. It also
- // lets it pass through the nested exception.
- if (nestedLevels == 0 && ioEx1 != nestedException) {
+ // This will make it pass through until the top caller. Only the top caller writes the
+ // exception (where it can).
+ if (nestedLevels == 0) {
try {
writeNewException(ioEx1);
} catch (IOException ioEx2) {
- nestedException.fillInStackTrace();
- throw nestedException;
+ // If writing the exception to the output stream causes another exception there
+ // is no need to propagate the second exception or generate a third exception,
+ // both of which might obscure details of the root cause.
}
}
throw ioEx1; // and then we propagate the original exception
@@ -1563,9 +1542,8 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
writeNull();
return -1;
}
- int handle = -1;
if (!unshared) {
- handle = dumpCycle(object);
+ int handle = dumpCycle(object);
if (handle != -1) {
return handle; // cyclic reference
}
@@ -1592,7 +1570,7 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
if (clDesc.isSerializable() && computeClassBasedReplacement) {
if (clDesc.hasMethodWriteReplace()){
Method methodWriteReplace = clDesc.getMethodWriteReplace();
- Object replObj = null;
+ Object replObj;
try {
replObj = methodWriteReplace.invoke(object, (Object[]) null);
} catch (IllegalAccessException iae) {
@@ -1677,7 +1655,7 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
}
// write for Enum Class Desc only, which is different from other classes
- private ObjectStreamClass writeEnumDesc(Class<?> theClass, ObjectStreamClass classDesc, boolean unshared)
+ private ObjectStreamClass writeEnumDesc(ObjectStreamClass classDesc, boolean unshared)
throws IOException {
// write classDesc, classDesc for enum is different
@@ -1716,7 +1694,7 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
if (superClassDesc != null) {
// super class is also enum
superClassDesc.setFlags((byte) (SC_SERIALIZABLE | SC_ENUM));
- writeEnumDesc(superClassDesc.forClass(), superClassDesc, unshared);
+ writeEnumDesc(superClassDesc, unshared);
} else {
output.writeByte(TC_NULL);
}
@@ -1740,7 +1718,7 @@ public class ObjectOutputStream extends OutputStream implements ObjectOutput, Ob
theClass = theClass.getSuperclass();
}
ObjectStreamClass classDesc = ObjectStreamClass.lookup(theClass);
- writeEnumDesc(theClass, classDesc, unshared);
+ writeEnumDesc(classDesc, unshared);
int previousHandle = -1;
if (unshared) {
diff --git a/luni/src/main/java/java/io/OutputStreamWriter.java b/luni/src/main/java/java/io/OutputStreamWriter.java
index d69c87a..bc8710d 100644
--- a/luni/src/main/java/java/io/OutputStreamWriter.java
+++ b/luni/src/main/java/java/io/OutputStreamWriter.java
@@ -122,8 +122,8 @@ public class OutputStreamWriter extends Writer {
}
/**
- * Closes this writer. This implementation flushes the buffer as well as the
- * target stream. The target stream is then closed and the resources for the
+ * Closes this writer. This implementation flushes the buffer but <strong>does not</strong>
+ * flush the target stream. The target stream is then closed and the resources for the
* buffer and converter are released.
*
* <p>Only the first invocation of this method has any effect. Subsequent calls
diff --git a/luni/src/main/java/java/io/PipedInputStream.java b/luni/src/main/java/java/io/PipedInputStream.java
index 2c27695..3e81cb8 100644
--- a/luni/src/main/java/java/io/PipedInputStream.java
+++ b/luni/src/main/java/java/io/PipedInputStream.java
@@ -390,6 +390,7 @@ public class PipedInputStream extends InputStream {
if (lastReader != null && !lastReader.isAlive()) {
throw new IOException("Pipe broken");
}
+
notifyAll();
wait(1000);
}
@@ -402,6 +403,10 @@ public class PipedInputStream extends InputStream {
if (in == -1) {
in = 0;
}
+ if (lastReader != null && !lastReader.isAlive()) {
+ throw new IOException("Pipe broken");
+ }
+
buffer[in++] = (byte) oneByte;
if (in == buffer.length) {
in = 0;
diff --git a/luni/src/main/java/java/io/PipedOutputStream.java b/luni/src/main/java/java/io/PipedOutputStream.java
index 1b139e9..4c431c1 100644
--- a/luni/src/main/java/java/io/PipedOutputStream.java
+++ b/luni/src/main/java/java/io/PipedOutputStream.java
@@ -140,7 +140,7 @@ public class PipedOutputStream extends OutputStream {
* @throws IOException
* if this stream is not connected, if the target stream is
* closed or if the thread reading from the target stream is no
- * longer alive. This case is currently not handled correctly.
+ * longer alive.
*/
@Override
public void write(byte[] buffer, int offset, int count) throws IOException {
diff --git a/luni/src/main/java/java/io/PipedReader.java b/luni/src/main/java/java/io/PipedReader.java
index 908505d..7bf9ed4 100644
--- a/luni/src/main/java/java/io/PipedReader.java
+++ b/luni/src/main/java/java/io/PipedReader.java
@@ -33,7 +33,7 @@ public class PipedReader extends Reader {
private Thread lastWriter;
- private boolean isClosed;
+ boolean isClosed;
/**
* The circular buffer through which data is passed. Data is read from the
diff --git a/luni/src/main/java/java/io/PipedWriter.java b/luni/src/main/java/java/io/PipedWriter.java
index ad8974b..e85f69c 100644
--- a/luni/src/main/java/java/io/PipedWriter.java
+++ b/luni/src/main/java/java/io/PipedWriter.java
@@ -17,8 +17,6 @@
package java.io;
-import java.util.Arrays;
-
/**
* Places information on a communications pipe. When two threads want to pass
* data back and forth, one creates a piped writer and the other creates a piped
@@ -115,6 +113,9 @@ public class PipedWriter extends Writer {
}
synchronized (reader) {
+ if (reader.isClosed) {
+ throw new IOException("Pipe is broken");
+ }
reader.notifyAll();
}
}
diff --git a/luni/src/main/java/java/io/RandomAccessFile.java b/luni/src/main/java/java/io/RandomAccessFile.java
index a60da3e..da99765 100644
--- a/luni/src/main/java/java/io/RandomAccessFile.java
+++ b/luni/src/main/java/java/io/RandomAccessFile.java
@@ -17,19 +17,18 @@
package java.io;
+import android.system.ErrnoException;
import dalvik.system.CloseGuard;
import java.nio.ByteOrder;
-import java.nio.NioUtils;
import java.nio.channels.FileChannel;
import java.nio.charset.ModifiedUtf8;
+import java.nio.NioUtils;
import java.util.Arrays;
-import libcore.io.ErrnoException;
import libcore.io.IoBridge;
-import libcore.io.IoUtils;
import libcore.io.Libcore;
import libcore.io.Memory;
import libcore.io.SizeOf;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* Allows reading from and writing to a file in a random-access manner. This is
@@ -115,7 +114,7 @@ public class RandomAccessFile implements DataInput, DataOutput, Closeable {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
this.mode = flags;
- this.fd = IoBridge.open(file.getAbsolutePath(), flags);
+ this.fd = IoBridge.open(file.getPath(), flags);
// if we are in "rws" mode, attempt to sync file+metadata
if (syncMetadata) {
@@ -163,7 +162,7 @@ public class RandomAccessFile implements DataInput, DataOutput, Closeable {
channel.close();
channel = null;
}
- IoUtils.close(fd);
+ IoBridge.closeAndSignalBlockedThreads(fd);
}
}
diff --git a/luni/src/main/java/java/lang/AbstractStringBuilder.java b/luni/src/main/java/java/lang/AbstractStringBuilder.java
index c3107f2..4d84078 100644
--- a/luni/src/main/java/java/lang/AbstractStringBuilder.java
+++ b/luni/src/main/java/java/lang/AbstractStringBuilder.java
@@ -17,9 +17,10 @@
package java.lang;
+import libcore.util.EmptyArray;
+
import java.io.InvalidObjectException;
import java.util.Arrays;
-import libcore.util.EmptyArray;
/**
* A modifiable {@link CharSequence sequence of characters} for use in creating
@@ -192,14 +193,8 @@ abstract class AbstractStringBuilder {
}
/**
- * Retrieves the character at the {@code index}.
- *
- * @param index
- * the index of the character to retrieve.
- * @return the char value.
- * @throws IndexOutOfBoundsException
- * if {@code index} is negative or greater than or equal to the
- * current {@link #length()}.
+ * Returns the character at {@code index}.
+ * @throws IndexOutOfBoundsException if {@code index < 0} or {@code index >= length()}.
*/
public char charAt(int index) {
if (index < 0 || index >= count) {
@@ -217,50 +212,46 @@ abstract class AbstractStringBuilder {
}
final void delete0(int start, int end) {
- if (start >= 0) {
- if (end > count) {
- end = count;
- }
- if (end == start) {
- return;
- }
- if (end > start) {
- int length = count - end;
- if (length >= 0) {
- if (!shared) {
- System.arraycopy(value, end, value, start, length);
- } else {
- char[] newData = new char[value.length];
- System.arraycopy(value, 0, newData, 0, start);
- System.arraycopy(value, end, newData, start, length);
- value = newData;
- shared = false;
- }
- }
- count -= end - start;
- return;
- }
+ // NOTE: StringBuilder#delete(int, int) is specified not to throw if
+ // the end index is >= count, as long as it's >= start. This means
+ // we have to clamp it to count here.
+ if (end > count) {
+ end = count;
}
- throw startEndAndLength(start, end);
- }
- final void deleteCharAt0(int index) {
- if (index < 0 || index >= count) {
- throw indexAndLength(index);
+ if (start < 0 || start > count || start > end) {
+ throw startEndAndLength(start, end);
}
- int length = count - index - 1;
- if (length > 0) {
+
+ // NOTE: StringBuilder#delete(int, int) throws only if start > count
+ // (start == count is considered valid, oddly enough). Since 'end' is
+ // already a clamped value, that case is handled here.
+ if (end == start) {
+ return;
+ }
+
+ // At this point we know for sure that end > start.
+ int length = count - end;
+ if (length >= 0) {
if (!shared) {
- System.arraycopy(value, index + 1, value, index, length);
+ System.arraycopy(value, end, value, start, length);
} else {
char[] newData = new char[value.length];
- System.arraycopy(value, 0, newData, 0, index);
- System.arraycopy(value, index + 1, newData, index, length);
+ System.arraycopy(value, 0, newData, 0, start);
+ System.arraycopy(value, end, newData, start, length);
value = newData;
shared = false;
}
}
- count--;
+ count -= end - start;
+ }
+
+ final void deleteCharAt0(int index) {
+ if (index < 0 || index >= count) {
+ throw indexAndLength(index);
+ }
+
+ delete0(index, index + 1);
}
/**
@@ -552,7 +543,7 @@ abstract class AbstractStringBuilder {
*
* @param length
* the new length of this StringBuffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code length < 0}.
* @see #length
*/
diff --git a/luni/src/main/java/java/lang/CaseMapper.java b/luni/src/main/java/java/lang/CaseMapper.java
index 5ec41f5..1da621c 100644
--- a/luni/src/main/java/java/lang/CaseMapper.java
+++ b/luni/src/main/java/java/lang/CaseMapper.java
@@ -18,6 +18,7 @@ package java.lang;
import java.util.Locale;
import libcore.icu.ICU;
+import libcore.icu.Transliterator;
/**
* Performs case operations as described by http://unicode.org/reports/tr21/tr21-5.html.
@@ -45,9 +46,10 @@ class CaseMapper {
*/
public static String toLowerCase(Locale locale, String s, char[] value, int offset, int count) {
// Punt hard cases to ICU4C.
+ // Note that Greek isn't a particularly hard case for toLowerCase, only toUpperCase.
String languageCode = locale.getLanguage();
if (languageCode.equals("tr") || languageCode.equals("az") || languageCode.equals("lt")) {
- return ICU.toLowerCase(s, locale.toString());
+ return ICU.toLowerCase(s, locale);
}
char[] newValue = null;
@@ -57,7 +59,7 @@ class CaseMapper {
char newCh;
if (ch == LATIN_CAPITAL_I_WITH_DOT || Character.isHighSurrogate(ch)) {
// Punt these hard cases.
- return ICU.toLowerCase(s, locale.toString());
+ return ICU.toLowerCase(s, locale);
} else if (ch == GREEK_CAPITAL_SIGMA && isFinalSigma(value, offset, count, i)) {
newCh = GREEK_SMALL_FINAL_SIGMA;
} else {
@@ -139,10 +141,19 @@ class CaseMapper {
return index;
}
+ private static final ThreadLocal<Transliterator> EL_UPPER = new ThreadLocal<Transliterator>() {
+ @Override protected Transliterator initialValue() {
+ return new Transliterator("el-Upper");
+ }
+ };
+
public static String toUpperCase(Locale locale, String s, char[] value, int offset, int count) {
String languageCode = locale.getLanguage();
if (languageCode.equals("tr") || languageCode.equals("az") || languageCode.equals("lt")) {
- return ICU.toUpperCase(s, locale.toString());
+ return ICU.toUpperCase(s, locale);
+ }
+ if (languageCode.equals("el")) {
+ return EL_UPPER.get().transliterate(s);
}
char[] output = null;
@@ -150,7 +161,7 @@ class CaseMapper {
for (int o = offset, end = offset + count; o < end; o++) {
char ch = value[o];
if (Character.isHighSurrogate(ch)) {
- return ICU.toUpperCase(s, locale.toString());
+ return ICU.toUpperCase(s, locale);
}
int index = upperIndex(ch);
if (index == -1) {
diff --git a/luni/src/main/java/java/lang/CharSequence.java b/luni/src/main/java/java/lang/CharSequence.java
index fc1ecd3..0e1ea3f 100644
--- a/luni/src/main/java/java/lang/CharSequence.java
+++ b/luni/src/main/java/java/lang/CharSequence.java
@@ -32,15 +32,8 @@ public interface CharSequence {
public int length();
/**
- * Returns the character at the specified index, with the first character
- * having index zero.
- *
- * @param index
- * the index of the character to return.
- * @return the requested character.
- * @throws IndexOutOfBoundsException
- * if {@code index < 0} or {@code index} is greater than the
- * length of this sequence.
+ * Returns the character at {@code index}.
+ * @throws IndexOutOfBoundsException if {@code index < 0} or {@code index >= length()}.
*/
public char charAt(int index);
diff --git a/luni/src/main/java/java/lang/Character.java b/luni/src/main/java/java/lang/Character.java
index 5762bd4..2046ba8 100644
--- a/luni/src/main/java/java/lang/Character.java
+++ b/luni/src/main/java/java/lang/Character.java
@@ -46,7 +46,7 @@ import java.util.Arrays;
* point or a UTF-16 unit that's part of a surrogate pair. The {@code int} type
* is used to represent all Unicode code points.
*
- * <a name="unicode_categories"><h3>Unicode categories</h3></a>
+ * <a name="unicode_categories"></a><h3>Unicode categories</h3>
* <p>Here's a list of the Unicode character categories and the corresponding Java constant,
* grouped semantically to provide a convenient overview. This table is also useful in
* conjunction with {@code \p} and {@code \P} in {@link java.util.regex.Pattern regular expressions}.
@@ -1489,7 +1489,7 @@ public final class Character implements Serializable, Comparable<Character> {
if (blockName == null) {
throw new NullPointerException("blockName == null");
}
- int block = forNameImpl(blockName);
+ int block = unicodeBlockForName(blockName);
if (block == -1) {
throw new IllegalArgumentException("Unknown block: " + blockName);
}
@@ -1510,7 +1510,7 @@ public final class Character implements Serializable, Comparable<Character> {
*/
public static UnicodeBlock of(int codePoint) {
checkValidCodePoint(codePoint);
- int block = ofImpl(codePoint);
+ int block = unicodeBlockForCodePoint(codePoint);
if (block == -1 || block >= BLOCKS.length) {
return null;
}
@@ -1522,9 +1522,14 @@ public final class Character implements Serializable, Comparable<Character> {
}
}
- private static native int forNameImpl(String blockName);
+ private static native int unicodeBlockForName(String blockName);
+
+ private static native int unicodeBlockForCodePoint(int codePoint);
+
+ private static native int unicodeScriptForName(String blockName);
+
+ private static native int unicodeScriptForCodePoint(int codePoint);
- private static native int ofImpl(int codePoint);
/**
* Constructs a new {@code Character} with the specified primitive char
@@ -2525,25 +2530,28 @@ public final class Character implements Serializable, Comparable<Character> {
}
/**
- * Gets the Unicode directionality of the specified character.
- *
- * @param codePoint
- * the Unicode code point to get the directionality of.
- * @return the Unicode directionality of {@code codePoint}.
+ * Returns the Unicode directionality of the given code point.
+ * This will be one of the {@code DIRECTIONALITY_} constants.
+ * For characters whose directionality is undefined, or whose
+ * directionality has no appropriate constant in this class,
+ * {@code DIRECTIONALITY_UNDEFINED} is returned.
*/
public static byte getDirectionality(int codePoint) {
if (getType(codePoint) == Character.UNASSIGNED) {
return Character.DIRECTIONALITY_UNDEFINED;
}
- byte directionality = getDirectionalityImpl(codePoint);
- if (directionality == -1) {
- return -1;
+ byte directionality = getIcuDirectionality(codePoint);
+ if (directionality >= 0 && directionality < DIRECTIONALITY.length) {
+ return DIRECTIONALITY[directionality];
}
- return DIRECTIONALITY[directionality];
+ return Character.DIRECTIONALITY_UNDEFINED;
}
- private static native byte getDirectionalityImpl(int codePoint);
+ /**
+ * @hide - internal use only.
+ */
+ public static native byte getIcuDirectionality(int codePoint);
/**
* Indicates whether the specified character is mirrored.
diff --git a/luni/src/main/java/java/lang/Double.java b/luni/src/main/java/java/lang/Double.java
index 456529b..cb8c301 100644
--- a/luni/src/main/java/java/lang/Double.java
+++ b/luni/src/main/java/java/lang/Double.java
@@ -171,7 +171,13 @@ public final class Double extends Number implements Comparable<Double> {
* {@code value}. All <em>Not-a-Number (NaN)</em> values are converted to a single NaN
* representation ({@code 0x7ff8000000000000L}) (compare to {@link #doubleToRawLongBits}).
*/
- public static native long doubleToLongBits(double value);
+ public static long doubleToLongBits(double value) {
+ if (value != value) {
+ return 0x7ff8000000000000L; // NaN.
+ } else {
+ return doubleToRawLongBits(value);
+ }
+ }
/**
* Returns an integer corresponding to the bits of the given
diff --git a/luni/src/main/java/java/lang/Float.java b/luni/src/main/java/java/lang/Float.java
index 900b2a0..5f316f1 100644
--- a/luni/src/main/java/java/lang/Float.java
+++ b/luni/src/main/java/java/lang/Float.java
@@ -199,7 +199,13 @@ public final class Float extends Number implements Comparable<Float> {
* float {@code value}. All <em>Not-a-Number (NaN)</em> values are converted to a single NaN
* representation ({@code 0x7fc00000}) (compare to {@link #floatToRawIntBits}).
*/
- public static native int floatToIntBits(float value);
+ public static int floatToIntBits(float value) {
+ if (value != value) {
+ return 0x7fc00000; // NaN.
+ } else {
+ return floatToRawIntBits(value);
+ }
+ }
/**
* Returns an integer corresponding to the bits of the given
diff --git a/luni/src/main/java/java/lang/Integer.java b/luni/src/main/java/java/lang/Integer.java
index fc38b41..8ae0312 100644
--- a/luni/src/main/java/java/lang/Integer.java
+++ b/luni/src/main/java/java/lang/Integer.java
@@ -126,7 +126,8 @@ public final class Integer extends Number implements Comparable<Integer> {
/**
* Compares two {@code int} values.
- * @return 0 if lhs = rhs, less than 0 if lhs &lt; rhs, and greater than 0 if lhs &gt; rhs.
+ * @return 0 if lhs = rhs, less than 0 if lhs &lt; rhs, and greater than 0
+ * if lhs &gt; rhs.
* @since 1.7
*/
public static int compare(int lhs, int rhs) {
@@ -140,24 +141,26 @@ public final class Integer extends Number implements Comparable<Integer> {
/**
* Parses the specified string and returns a {@code Integer} instance if the
* string can be decoded into an integer value. The string may be an
- * optional minus sign "-" followed by a hexadecimal ("0x..." or "#..."),
- * octal ("0..."), or decimal ("...") representation of an integer.
+ * optional sign character ("-" or "+") followed by a hexadecimal ("0x..."
+ * or "#..."), octal ("0..."), or decimal ("...") representation of an
+ * integer.
*
* @param string
* a string representation of an integer value.
* @return an {@code Integer} containing the value represented by
* {@code string}.
* @throws NumberFormatException
- * if {@code string} cannot be parsed as an integer value.
+ * if {@code string} cannot be parsed as an integer value.
*/
public static Integer decode(String string) throws NumberFormatException {
- int length = string.length(), i = 0;
+ int length = string.length();
if (length == 0) {
throw invalidInt(string);
}
+ int i = 0;
char firstDigit = string.charAt(i);
boolean negative = firstDigit == '-';
- if (negative) {
+ if (negative || firstDigit == '+') {
if (length == 1) {
throw invalidInt(string);
}
@@ -319,8 +322,8 @@ public final class Integer extends Number implements Comparable<Integer> {
/**
* Parses the specified string as a signed decimal integer value. The ASCII
- * character \u002d ('-') is recognized as the minus sign.
- *
+ * characters \u002d ('-') and \u002b ('+') are recognized as the minus and
+ * plus signs.
* @param string
* the string representation of an integer value.
* @return the primitive integer value represented by {@code string}.
@@ -333,7 +336,8 @@ public final class Integer extends Number implements Comparable<Integer> {
/**
* Parses the specified string as a signed integer value using the specified
- * radix. The ASCII character \u002d ('-') is recognized as the minus sign.
+ * radix. The ASCII characters \u002d ('-') and \u002b ('+') are recognized
+ * as the minus and plus signs.
*
* @param string
* the string representation of an integer value.
@@ -350,24 +354,56 @@ public final class Integer extends Number implements Comparable<Integer> {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("Invalid radix: " + radix);
}
- if (string == null) {
+ if (string == null || string.isEmpty()) {
throw invalidInt(string);
}
- int length = string.length(), i = 0;
- if (length == 0) {
+
+ char firstChar = string.charAt(0);
+ int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;
+ if (firstDigitIndex == string.length()) {
throw invalidInt(string);
}
- boolean negative = string.charAt(i) == '-';
- if (negative && ++i == length) {
+
+ return parse(string, firstDigitIndex, radix, firstChar == '-');
+ }
+
+ /**
+ * Equivalent to {@code parsePositiveInt(string, 10)}.
+ *
+ * @see #parsePositiveInt(String, int)
+ *
+ * @hide
+ */
+ public static int parsePositiveInt(String string) throws NumberFormatException {
+ return parsePositiveInt(string, 10);
+ }
+
+ /**
+ * Parses the specified string as a positive integer value using the
+ * specified radix. 0 is considered a positive integer.
+ * <p>
+ * This method behaves the same as {@link #parseInt(String, int)} except
+ * that it disallows leading '+' and '-' characters. See that method for
+ * error conditions.
+ *
+ * @see #parseInt(String, int)
+ *
+ * @hide
+ */
+ public static int parsePositiveInt(String string, int radix) throws NumberFormatException {
+ if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
+ throw new NumberFormatException("Invalid radix: " + radix);
+ }
+ if (string == null || string.length() == 0) {
throw invalidInt(string);
}
-
- return parse(string, i, radix, negative);
+ return parse(string, 0, radix, false);
}
private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {
int max = Integer.MIN_VALUE / radix;
- int result = 0, length = string.length();
+ int result = 0;
+ int length = string.length();
while (offset < length) {
int digit = Character.digit(string.charAt(offset++), radix);
if (digit == -1) {
diff --git a/luni/src/main/java/java/lang/Long.java b/luni/src/main/java/java/lang/Long.java
index 84169af..5c11564 100644
--- a/luni/src/main/java/java/lang/Long.java
+++ b/luni/src/main/java/java/lang/Long.java
@@ -127,8 +127,8 @@ public final class Long extends Number implements Comparable<Long> {
/**
* Parses the specified string and returns a {@code Long} instance if the
* string can be decoded into a long value. The string may be an optional
- * minus sign "-" followed by a hexadecimal ("0x..." or "#..."), octal
- * ("0..."), or decimal ("...") representation of a long.
+ * optional sign character ("-" or "+") followed by a hexadecimal ("0x..."
+ * or "#..."), octal ("0..."), or decimal ("...") representation of a long.
*
* @param string
* a string representation of a long value.
@@ -137,13 +137,15 @@ public final class Long extends Number implements Comparable<Long> {
* if {@code string} cannot be parsed as a long value.
*/
public static Long decode(String string) throws NumberFormatException {
- int length = string.length(), i = 0;
+ int length = string.length();
if (length == 0) {
throw invalidLong(string);
}
+
+ int i = 0;
char firstDigit = string.charAt(i);
boolean negative = firstDigit == '-';
- if (negative) {
+ if (negative || firstDigit == '+') {
if (length == 1) {
throw invalidLong(string);
}
@@ -306,7 +308,8 @@ public final class Long extends Number implements Comparable<Long> {
/**
* Parses the specified string as a signed decimal long value. The ASCII
- * character \u002d ('-') is recognized as the minus sign.
+ * characters \u002d ('-') and \u002b ('+') are recognized as the minus and
+ * plus signs.
*
* @param string
* the string representation of a long value.
@@ -320,7 +323,8 @@ public final class Long extends Number implements Comparable<Long> {
/**
* Parses the specified string as a signed long value using the specified
- * radix. The ASCII character \u002d ('-') is recognized as the minus sign.
+ * radix. The ASCII characters \u002d ('-') and \u002b ('+') are recognized
+ * as the minus and plus signs.
*
* @param string
* the string representation of a long value.
@@ -337,24 +341,22 @@ public final class Long extends Number implements Comparable<Long> {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("Invalid radix: " + radix);
}
- if (string == null) {
- throw invalidLong(string);
- }
- int length = string.length(), i = 0;
- if (length == 0) {
+ if (string == null || string.isEmpty()) {
throw invalidLong(string);
}
- boolean negative = string.charAt(i) == '-';
- if (negative && ++i == length) {
+ char firstChar = string.charAt(0);
+ int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;
+ if (firstDigitIndex == string.length()) {
throw invalidLong(string);
}
- return parse(string, i, radix, negative);
+ return parse(string, firstDigitIndex, radix, firstChar == '-');
}
private static long parse(String string, int offset, int radix, boolean negative) {
long max = Long.MIN_VALUE / radix;
- long result = 0, length = string.length();
+ long result = 0;
+ int length = string.length();
while (offset < length) {
int digit = Character.digit(string.charAt(offset++), radix);
if (digit == -1) {
@@ -378,6 +380,39 @@ public final class Long extends Number implements Comparable<Long> {
return result;
}
+ /**
+ * Equivalent to {@code parsePositiveLong(string, 10)}.
+ *
+ * @see #parsePositiveLong(String, int)
+ *
+ * @hide
+ */
+ public static long parsePositiveLong(String string) throws NumberFormatException {
+ return parsePositiveLong(string, 10);
+ }
+
+ /**
+ * Parses the specified string as a positive long value using the
+ * specified radix. 0 is considered a positive long.
+ * <p>
+ * This method behaves the same as {@link #parseLong(String, int)} except
+ * that it disallows leading '+' and '-' characters. See that method for
+ * error conditions.
+ *
+ * @see #parseLong(String, int)
+ *
+ * @hide
+ */
+ public static long parsePositiveLong(String string, int radix) throws NumberFormatException {
+ if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
+ throw new NumberFormatException("Invalid radix: " + radix);
+ }
+ if (string == null || string.length() == 0) {
+ throw invalidLong(string);
+ }
+ return parse(string, 0, radix, false);
+ }
+
@Override
public short shortValue() {
return (short) value;
diff --git a/luni/src/main/java/java/lang/ProcessManager.java b/luni/src/main/java/java/lang/ProcessManager.java
index 28314b7..ec87fda 100644
--- a/luni/src/main/java/java/lang/ProcessManager.java
+++ b/luni/src/main/java/java/lang/ProcessManager.java
@@ -16,23 +16,23 @@
package java.lang;
+import android.system.ErrnoException;
+import android.util.MutableInt;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.IOException;
import java.io.InputStream;
+import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-import libcore.io.ErrnoException;
import libcore.io.IoUtils;
import libcore.io.Libcore;
-import libcore.util.MutableInt;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* Manages child processes.
diff --git a/luni/src/main/java/java/lang/Runtime.java b/luni/src/main/java/java/lang/Runtime.java
index 8538f8a..a3cb83e 100644
--- a/luni/src/main/java/java/lang/Runtime.java
+++ b/luni/src/main/java/java/lang/Runtime.java
@@ -48,7 +48,7 @@ import java.util.StringTokenizer;
import libcore.io.IoUtils;
import libcore.io.Libcore;
import libcore.util.EmptyArray;
-import static libcore.io.OsConstants._SC_NPROCESSORS_CONF;
+import static android.system.OsConstants._SC_NPROCESSORS_CONF;
/**
* Allows Java applications to interface with the environment in which they are
@@ -307,57 +307,64 @@ public class Runtime {
}
/**
- * Loads and links the dynamic library that is identified through the
- * specified path. This method is similar to {@link #loadLibrary(String)},
- * but it accepts a full path specification whereas {@code loadLibrary} just
- * accepts the name of the library to load.
+ * Loads the shared library found at the given absolute path.
+ * This should be of the form {@code /path/to/library/libMyLibrary.so}.
+ * Most callers should use {@link #loadLibrary(String)} instead, and
+ * let the system find the correct file to load.
*
- * @param pathName
- * the absolute (platform dependent) path to the library to load.
- * @throws UnsatisfiedLinkError
- * if the library can not be loaded.
+ * @throws UnsatisfiedLinkError if the library can not be loaded,
+ * either because it's not found or because there is something wrong with it.
*/
- public void load(String pathName) {
- load(pathName, VMStack.getCallingClassLoader());
+ public void load(String absolutePath) {
+ load(absolutePath, VMStack.getCallingClassLoader());
}
/*
- * Loads and links the given library without security checks.
+ * Loads the given shared library using the given ClassLoader.
*/
- void load(String pathName, ClassLoader loader) {
- if (pathName == null) {
- throw new NullPointerException("pathName == null");
+ void load(String absolutePath, ClassLoader loader) {
+ if (absolutePath == null) {
+ throw new NullPointerException("absolutePath == null");
}
- String error = doLoad(pathName, loader);
+ String error = doLoad(absolutePath, loader);
if (error != null) {
throw new UnsatisfiedLinkError(error);
}
}
/**
- * Loads and links the library with the specified name. The mapping of the
- * specified library name to the full path for loading the library is
- * implementation-dependent.
+ * Loads a shared library. Class loaders have some influence over this
+ * process, but for a typical Android app, it works as follows:
*
- * @param libName
- * the name of the library to load.
- * @throws UnsatisfiedLinkError
- * if the library can not be loaded.
+ * <p>Given the name {@code "MyLibrary"}, that string will be passed to
+ * {@link System#mapLibraryName}. That means it would be a mistake
+ * for the caller to include the usual {@code "lib"} prefix and {@code ".so"}
+ * suffix.
+ *
+ * <p>That file will then be searched for on the application's native library
+ * search path. This consists of the application's own native library directory
+ * followed by the system's native library directories.
+ *
+ * @throws UnsatisfiedLinkError if the library can not be loaded,
+ * either because it's not found or because there is something wrong with it.
*/
- public void loadLibrary(String libName) {
- loadLibrary(libName, VMStack.getCallingClassLoader());
+ public void loadLibrary(String nickname) {
+ loadLibrary(nickname, VMStack.getCallingClassLoader());
}
/*
- * Searches for a library, then loads and links it without security checks.
+ * Searches for and loads the given shared library using the given ClassLoader.
*/
void loadLibrary(String libraryName, ClassLoader loader) {
if (loader != null) {
String filename = loader.findLibrary(libraryName);
if (filename == null) {
- throw new UnsatisfiedLinkError("Couldn't load " + libraryName +
- " from loader " + loader +
- ": findLibrary returned null");
+ // It's not necessarily true that the ClassLoader used
+ // System.mapLibraryName, but the default setup does, and it's
+ // misleading to say we didn't find "libMyLibrary.so" when we
+ // actually searched for "liblibMyLibrary.so.so".
+ throw new UnsatisfiedLinkError(loader + " couldn't find \"" +
+ System.mapLibraryName(libraryName) + "\"");
}
String error = doLoad(filename, loader);
if (error != null) {
diff --git a/luni/src/main/java/java/lang/StringToReal.java b/luni/src/main/java/java/lang/StringToReal.java
index 97f6d6b..4bd4fb1 100644
--- a/luni/src/main/java/java/lang/StringToReal.java
+++ b/luni/src/main/java/java/lang/StringToReal.java
@@ -122,20 +122,20 @@ final class StringToReal {
result.e = -result.e;
}
} catch (NumberFormatException ex) {
- // We already checked the string, so the exponent must have been out of range for an int.
+ // We already checked the string, so the exponent must have been out of range for an
+ // int.
if (negativeExponent) {
result.zero = true;
} else {
result.infinity = true;
}
- return result;
+ // Fall through: We want to check the content of the mantissa and throw an
+ // exception if it contains invalid characters. For example: "JUNK" * 10^12 should
+ // be treated as an error, not as infinity.
}
} else {
end = length;
}
- if (length == 0) {
- throw invalidReal(s, isDouble);
- }
int start = 0;
c = s.charAt(start);
@@ -151,7 +151,19 @@ final class StringToReal {
throw invalidReal(s, isDouble);
}
- int decimal = s.indexOf('.');
+ // Confirm that the mantissa should parse.
+ int decimal = -1;
+ for (int i = start; i < end; i++) {
+ char mc = s.charAt(i);
+ if (mc == '.') {
+ if (decimal != -1) {
+ throw invalidReal(s, isDouble);
+ }
+ decimal = i;
+ } else if (mc < '0' || mc > '9') {
+ throw invalidReal(s, isDouble);
+ }
+ }
if (decimal > -1) {
result.e -= end - decimal - 1;
s = s.substring(start, decimal) + s.substring(decimal + 1, end);
@@ -159,10 +171,17 @@ final class StringToReal {
s = s.substring(start, end);
}
- if ((length = s.length()) == 0) {
+ length = s.length();
+ if (length == 0) {
throw invalidReal(s, isDouble);
}
+ // All syntactic checks that might throw an exception are above. If we have established
+ // one of the non-exception error conditions we can stop here.
+ if (result.infinity || result.zero) {
+ return result;
+ }
+
end = length;
while (end > 1 && s.charAt(end - 1) == '0') {
--end;
@@ -237,7 +256,7 @@ final class StringToReal {
* the String that will be parsed to a floating point
* @return the double closest to the real number
*
- * @exception NumberFormatException
+ * @throws NumberFormatException
* if the String doesn't represent a double
*/
public static double parseDouble(String s) {
@@ -278,7 +297,7 @@ final class StringToReal {
* the String that will be parsed to a floating point
* @return the float closest to the real number
*
- * @exception NumberFormatException
+ * @throws NumberFormatException
* if the String doesn't represent a float
*/
public static float parseFloat(String s) {
diff --git a/luni/src/main/java/java/lang/System.java b/luni/src/main/java/java/lang/System.java
index 68ca506..55ca762 100644
--- a/luni/src/main/java/java/lang/System.java
+++ b/luni/src/main/java/java/lang/System.java
@@ -32,6 +32,9 @@
package java.lang;
+import android.system.ErrnoException;
+import android.system.StructPasswd;
+import android.system.StructUtsname;
import dalvik.system.VMRuntime;
import dalvik.system.VMStack;
import java.io.BufferedInputStream;
@@ -39,8 +42,8 @@ import java.io.Console;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.IOException;
import java.io.InputStream;
+import java.io.IOException;
import java.io.PrintStream;
import java.nio.channels.Channel;
import java.nio.channels.spi.SelectorProvider;
@@ -51,11 +54,7 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import libcore.icu.ICU;
-import libcore.io.ErrnoException;
import libcore.io.Libcore;
-import libcore.io.StructPasswd;
-import libcore.io.StructUtsname;
-import libcore.util.ZoneInfoDB;
/**
* Provides access to system-related information and resources including
@@ -83,12 +82,31 @@ public final class System {
public static final PrintStream err;
private static final String lineSeparator;
+ private static final Properties unchangeableSystemProperties;
private static Properties systemProperties;
+ /**
+ * Dedicated lock for GC / Finalization logic.
+ */
+ private static final Object lock = new Object();
+
+ /**
+ * Whether or not we need to do a GC before running the finalizers.
+ */
+ private static boolean runGC;
+
+ /**
+ * If we just ran finalization, we might want to do a GC to free the finalized objects.
+ * This lets us do gc/runFinlization/gc sequences but prevents back to back System.gc().
+ */
+ private static boolean justRanFinalization;
+
static {
err = new PrintStream(new FileOutputStream(FileDescriptor.err));
out = new PrintStream(new FileOutputStream(FileDescriptor.out));
in = new BufferedInputStream(new FileInputStream(FileDescriptor.in));
+ unchangeableSystemProperties = initUnchangeableSystemProperties();
+ systemProperties = createSystemProperties();
lineSeparator = System.getProperty("line.separator");
}
@@ -153,7 +171,433 @@ public final class System {
* @param length
* the number of elements to be copied.
*/
- public static native void arraycopy(Object src, int srcPos, Object dst, int dstPos, int length);
+
+ public static native void arraycopy(Object src, int srcPos,
+ Object dst, int dstPos, int length);
+
+ /**
+ * The char array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_CHAR_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The char[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(char[] src, int srcPos, char[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_CHAR_ARRAY_THRESHOLD) {
+ // Copy char by char for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for longer arrays.
+ arraycopyCharUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The char[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyCharUnchecked(char[] src, int srcPos,
+ char[] dst, int dstPos, int length);
+
+ /**
+ * The byte array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_BYTE_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The byte[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(byte[] src, int srcPos, byte[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_BYTE_ARRAY_THRESHOLD) {
+ // Copy byte by byte for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for longer arrays.
+ arraycopyByteUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The byte[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyByteUnchecked(byte[] src, int srcPos,
+ byte[] dst, int dstPos, int length);
+
+ /**
+ * The short array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_SHORT_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The short[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(short[] src, int srcPos, short[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_SHORT_ARRAY_THRESHOLD) {
+ // Copy short by short for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for longer arrays.
+ arraycopyShortUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The short[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyShortUnchecked(short[] src, int srcPos,
+ short[] dst, int dstPos, int length);
+
+ /**
+ * The short array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_INT_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The int[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(int[] src, int srcPos, int[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_INT_ARRAY_THRESHOLD) {
+ // Copy int by int for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for longer arrays.
+ arraycopyIntUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The int[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyIntUnchecked(int[] src, int srcPos,
+ int[] dst, int dstPos, int length);
+
+ /**
+ * The short array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_LONG_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The long[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(long[] src, int srcPos, long[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_LONG_ARRAY_THRESHOLD) {
+ // Copy long by long for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for longer arrays.
+ arraycopyLongUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The long[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyLongUnchecked(long[] src, int srcPos,
+ long[] dst, int dstPos, int length);
+
+ /**
+ * The short array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_FLOAT_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The float[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(float[] src, int srcPos, float[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_FLOAT_ARRAY_THRESHOLD) {
+ // Copy float by float for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for floater arrays.
+ arraycopyFloatUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The float[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyFloatUnchecked(float[] src, int srcPos,
+ float[] dst, int dstPos, int length);
+
+ /**
+ * The short array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_DOUBLE_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The double[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(double[] src, int srcPos, double[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_DOUBLE_ARRAY_THRESHOLD) {
+ // Copy double by double for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for floater arrays.
+ arraycopyDoubleUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The double[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyDoubleUnchecked(double[] src, int srcPos,
+ double[] dst, int dstPos, int length);
+
+ /**
+ * The short array length threshold below which to use a Java
+ * (non-native) version of arraycopy() instead of the native
+ * version. See b/7103825.
+ */
+ private static final int ARRAYCOPY_SHORT_BOOLEAN_ARRAY_THRESHOLD = 32;
+
+ /**
+ * The boolean[] specialized version of arraycopy().
+ *
+ * @hide internal use only
+ */
+ public static void arraycopy(boolean[] src, int srcPos, boolean[] dst, int dstPos, int length) {
+ if (src == null) {
+ throw new NullPointerException("src == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if (srcPos < 0 || dstPos < 0 || length < 0 ||
+ srcPos > src.length - length || dstPos > dst.length - length) {
+ throw new ArrayIndexOutOfBoundsException(
+ "src.length=" + src.length + " srcPos=" + srcPos +
+ " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length);
+ }
+ if (length <= ARRAYCOPY_SHORT_BOOLEAN_ARRAY_THRESHOLD) {
+ // Copy boolean by boolean for shorter arrays.
+ if (src == dst && srcPos < dstPos && dstPos < srcPos + length) {
+ // Copy backward (to avoid overwriting elements before
+ // they are copied in case of an overlap on the same
+ // array.)
+ for (int i = length - 1; i >= 0; --i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ } else {
+ // Copy forward.
+ for (int i = 0; i < length; ++i) {
+ dst[dstPos + i] = src[srcPos + i];
+ }
+ }
+ } else {
+ // Call the native version for floater arrays.
+ arraycopyBooleanUnchecked(src, srcPos, dst, dstPos, length);
+ }
+ }
+
+ /**
+ * The boolean[] specialized, unchecked, native version of
+ * arraycopy(). This assumes error checking has been done.
+ */
+ private static native void arraycopyBooleanUnchecked(boolean[] src, int srcPos,
+ boolean[] dst, int dstPos, int length);
/**
* Returns the current time in milliseconds since January 1, 1970 00:00:00.0 UTC.
@@ -196,7 +640,18 @@ public final class System {
* that the garbage collector will actually be run.
*/
public static void gc() {
- Runtime.getRuntime().gc();
+ boolean shouldRunGC;
+ synchronized(lock) {
+ shouldRunGC = justRanFinalization;
+ if (shouldRunGC) {
+ justRanFinalization = false;
+ } else {
+ runGC = true;
+ }
+ }
+ if (shouldRunGC) {
+ Runtime.getRuntime().gc();
+ }
}
/**
@@ -246,13 +701,10 @@ public final class System {
* @return the system properties.
*/
public static Properties getProperties() {
- if (systemProperties == null) {
- initSystemProperties();
- }
return systemProperties;
}
- private static void initSystemProperties() {
+ private static Properties initUnchangeableSystemProperties() {
VMRuntime runtime = VMRuntime.getRuntime();
Properties p = new Properties();
@@ -277,15 +729,6 @@ public final class System {
}
p.put("java.home", javaHome);
- // On Android, each app gets its own temporary directory. This is just a fallback
- // default, useful only on the host.
- p.put("java.io.tmpdir", "/tmp");
-
- String ldLibraryPath = getenv("LD_LIBRARY_PATH");
- if (ldLibraryPath != null) {
- p.put("java.library.path", ldLibraryPath);
- }
-
p.put("java.specification.name", "Dalvik Core Library");
p.put("java.specification.vendor", projectName);
p.put("java.specification.version", "0.9");
@@ -313,7 +756,6 @@ public final class System {
try {
StructPasswd passwd = Libcore.os.getpwuid(Libcore.os.getuid());
- p.put("user.home", passwd.pw_dir);
p.put("user.name", passwd.pw_name);
} catch (ErrnoException exception) {
throw new AssertionError(exception);
@@ -333,8 +775,36 @@ public final class System {
// Override built-in properties with settings from the command line.
parsePropertyAssignments(p, runtime.properties());
+ return p;
+ }
+
+ /**
+ * Inits an unchangeable system property with the given value.
+ * This is useful when the environment needs to change under native bridge emulation.
+ */
+ private static void initUnchangeableSystemProperty(String name, String value) {
+ checkPropertyName(name);
+ unchangeableSystemProperties.put(name, value);
+ }
+
+ private static void setDefaultChangeableProperties(Properties p) {
+ // On Android, each app gets its own temporary directory.
+ // (See android.app.ActivityThread.) This is just a fallback default,
+ // useful only on the host.
+ p.put("java.io.tmpdir", "/tmp");
- systemProperties = p;
+ // Android has always had an empty "user.home" (see docs for getProperty).
+ // This is not useful for normal android apps which need to use android specific
+ // APIs such as {@code Context.getFilesDir} and {@code Context.getCacheDir} but
+ // we make it changeable for backward compatibility, so that they can change it
+ // to a writeable location if required.
+ p.put("user.home", "");
+ }
+
+ private static Properties createSystemProperties() {
+ Properties p = new PropertiesWithNonOverrideableDefaults(unchangeableSystemProperties);
+ setDefaultChangeableProperties(p);
+ return p;
}
/**
@@ -360,7 +830,7 @@ public final class System {
* Returns the value of a particular system property or {@code null} if no
* such property exists.
*
- * <p>The following properties are always provided by the Dalvik VM:
+ * <p>The following properties are always provided by the Dalvik VM:</p>
* <p><table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
* <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
* <td><b>Name</b></td> <td><b>Meaning</b></td> <td><b>Example</b></td></tr>
@@ -401,7 +871,8 @@ public final class System {
*
* </table>
*
- * <p>It is a mistake to try to override any of these. Doing so will have unpredictable results.
+ * <p> All of the above properties except for {@code user.home} and {@code java.io.tmpdir}
+ * <b>cannot be modified</b>. Any attempt to change them will be a no-op.
*
* @param propertyName
* the name of the system property to look up.
@@ -418,22 +889,26 @@ public final class System {
*/
public static String getProperty(String name, String defaultValue) {
checkPropertyName(name);
- return getProperties().getProperty(name, defaultValue);
+ return systemProperties.getProperty(name, defaultValue);
}
/**
- * Sets the value of a particular system property.
+ * Sets the value of a particular system property. Most system properties
+ * are read only and cannot be cleared or modified. See {@link #setProperty} for a
+ * list of such properties.
*
* @return the old value of the property or {@code null} if the property
* didn't exist.
*/
public static String setProperty(String name, String value) {
checkPropertyName(name);
- return (String) getProperties().setProperty(name, value);
+ return (String) systemProperties.setProperty(name, value);
}
/**
- * Removes a specific system property.
+ * Removes a specific system property. Most system properties
+ * are read only and cannot be cleared or modified. See {@link #setProperty} for a
+ * list of such properties.
*
* @return the property value or {@code null} if the property didn't exist.
* @throws NullPointerException
@@ -443,7 +918,7 @@ public final class System {
*/
public static String clearProperty(String name) {
checkPropertyName(name);
- return (String) getProperties().remove(name);
+ return (String) systemProperties.remove(name);
}
private static void checkPropertyName(String name) {
@@ -500,27 +975,14 @@ public final class System {
}
/**
- * Loads and links the dynamic library that is identified through the
- * specified path. This method is similar to {@link #loadLibrary(String)},
- * but it accepts a full path specification whereas {@code loadLibrary} just
- * accepts the name of the library to load.
- *
- * @param pathName
- * the path of the file to be loaded.
+ * See {@link Runtime#load}.
*/
public static void load(String pathName) {
Runtime.getRuntime().load(pathName, VMStack.getCallingClassLoader());
}
/**
- * Loads and links the library with the specified name. The mapping of the
- * specified library name to the full path for loading the library is
- * implementation-dependent.
- *
- * @param libName
- * the name of the library to load.
- * @throws UnsatisfiedLinkError
- * if the library could not be loaded.
+ * See {@link Runtime#loadLibrary}.
*/
public static void loadLibrary(String libName) {
Runtime.getRuntime().loadLibrary(libName, VMStack.getCallingClassLoader());
@@ -575,7 +1037,18 @@ public final class System {
* to perform any outstanding object finalization.
*/
public static void runFinalization() {
+ boolean shouldRunGC;
+ synchronized(lock) {
+ shouldRunGC = runGC;
+ runGC = false;
+ }
+ if (shouldRunGC) {
+ Runtime.getRuntime().gc();
+ }
Runtime.getRuntime().runFinalization();
+ synchronized(lock) {
+ justRanFinalization = true;
+ }
}
/**
@@ -594,12 +1067,21 @@ public final class System {
}
/**
- * Sets all system properties. This does not take a copy; the passed-in object is used
- * directly. Passing null causes the VM to reinitialize the properties to how they were
- * when the VM was started.
+ * Attempts to set all system properties. Copies all properties from
+ * {@code p} and discards system properties that are read only and cannot
+ * be modified. See {@link #setProperty} for a list of such properties.
*/
public static void setProperties(Properties p) {
- systemProperties = p;
+ PropertiesWithNonOverrideableDefaults userProperties =
+ new PropertiesWithNonOverrideableDefaults(unchangeableSystemProperties);
+ if (p != null) {
+ userProperties.putAll(p);
+ } else {
+ // setProperties(null) is documented to restore defaults.
+ setDefaultChangeableProperties(userProperties);
+ }
+
+ systemProperties = userProperties;
}
/**
@@ -621,25 +1103,46 @@ public final class System {
/**
* Returns the platform specific file name format for the shared library
- * named by the argument.
- *
- * @param userLibName
- * the name of the library to look up.
- * @return the platform specific filename for the library.
+ * named by the argument. On Android, this would turn {@code "MyLibrary"} into
+ * {@code "libMyLibrary.so"}.
*/
- public static native String mapLibraryName(String userLibName);
+ public static native String mapLibraryName(String nickname);
/**
- * Sets the value of the named static field in the receiver to the passed in
- * argument.
- *
- * @param fieldName
- * the name of the field to set, one of in, out, or err
- * @param stream
- * the new value of the field
+ * Used to set System.err, System.in, and System.out.
*/
- private static native void setFieldImpl(String fieldName, String signature, Object stream);
+ private static native void setFieldImpl(String field, String signature, Object stream);
+ /**
+ * A properties class that prohibits changes to any of the properties
+ * contained in its defaults.
+ */
+ static final class PropertiesWithNonOverrideableDefaults extends Properties {
+ PropertiesWithNonOverrideableDefaults(Properties defaults) {
+ super(defaults);
+ }
+
+ @Override
+ public Object put(Object key, Object value) {
+ if (defaults.containsKey(key)) {
+ logE("Ignoring attempt to set property \"" + key +
+ "\" to value \"" + value + "\".");
+ return defaults.get(key);
+ }
+
+ return super.put(key, value);
+ }
+
+ @Override
+ public Object remove(Object key) {
+ if (defaults.containsKey(key)) {
+ logE("Ignoring attempt to remove property \"" + key + "\".");
+ return null;
+ }
+
+ return super.remove(key);
+ }
+ }
/**
* The unmodifiable environment variables map. System.getenv() specifies
diff --git a/luni/src/main/java/java/lang/ref/FinalizerReference.java b/luni/src/main/java/java/lang/ref/FinalizerReference.java
index 14eaae4..5416a80 100644
--- a/luni/src/main/java/java/lang/ref/FinalizerReference.java
+++ b/luni/src/main/java/java/lang/ref/FinalizerReference.java
@@ -83,12 +83,18 @@ public final class FinalizerReference<T> extends Reference<T> {
* Waits for all currently-enqueued references to be finalized.
*/
public static void finalizeAllEnqueued() throws InterruptedException {
- Sentinel sentinel = new Sentinel();
- enqueueSentinelReference(sentinel);
+ // Alloate a new sentinel, this creates a FinalizerReference.
+ Sentinel sentinel;
+ // Keep looping until we safely enqueue our sentinel FinalizerReference.
+ // This is done to prevent races where the GC updates the pendingNext
+ // before we get the chance.
+ do {
+ sentinel = new Sentinel();
+ } while (!enqueueSentinelReference(sentinel));
sentinel.awaitFinalization();
}
- private static void enqueueSentinelReference(Sentinel sentinel) {
+ private static boolean enqueueSentinelReference(Sentinel sentinel) {
synchronized (LIST_LOCK) {
// When a finalizable object is allocated, a FinalizerReference is added to the list.
// We search the list for that FinalizerReference (it should be at or near the head),
@@ -98,8 +104,20 @@ public final class FinalizerReference<T> extends Reference<T> {
FinalizerReference<Sentinel> sentinelReference = (FinalizerReference<Sentinel>) r;
sentinelReference.referent = null;
sentinelReference.zombie = sentinel;
- sentinelReference.enqueueInternal();
- return;
+ // Make a single element list, then enqueue the reference on the daemon unenqueued
+ // list. This is required instead of enqueuing directly on the finalizer queue
+ // since there could be recently freed objects in the unqueued list which are not
+ // yet on the finalizer queue. This could cause the sentinel to run before the
+ // objects are finalized. b/17381967
+ // Make circular list if unenqueued goes through native so that we can prevent
+ // races where the GC updates the pendingNext before we do. If it is non null, then
+ // we update the pending next to make a circular list while holding a lock.
+ // b/17462553
+ if (!sentinelReference.makeCircularListIfUnenqueued()) {
+ return false;
+ }
+ ReferenceQueue.add(sentinelReference);
+ return true;
}
}
}
@@ -108,6 +126,8 @@ public final class FinalizerReference<T> extends Reference<T> {
throw new AssertionError("newly-created live Sentinel not on list!");
}
+ private native boolean makeCircularListIfUnenqueued();
+
/**
* A marker object that we can immediately enqueue. When this object's
* finalize() method is called, we know all previously-enqueued finalizable
diff --git a/luni/src/main/java/java/lang/ref/Reference.java b/luni/src/main/java/java/lang/ref/Reference.java
deleted file mode 100644
index bd63535..0000000
--- a/luni/src/main/java/java/lang/ref/Reference.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.
- */
-/*
- * 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 java.lang.ref;
-
-/**
- * Provides an abstract class which describes behavior common to all reference
- * objects. It is not possible to create immediate subclasses of
- * {@code Reference} in addition to the ones provided by this package. It is
- * also not desirable to do so, since references require very close cooperation
- * with the system's garbage collector. The existing, specialized reference
- * classes should be used instead.
- *
- * <p>Three different type of references exist, each being weaker than the preceding one:
- * {@link java.lang.ref.SoftReference}, {@link java.lang.ref.WeakReference}, and
- * {@link java.lang.ref.PhantomReference}. "Weakness" here means that less restrictions are
- * being imposed on the garbage collector as to when it is allowed to
- * actually garbage-collect the referenced object.
- *
- * <p>In order to use reference objects properly it is important to understand
- * the different types of reachability that trigger their clearing and
- * enqueueing. The following table lists these, from strongest to weakest.
- * For each row, an object is said to have the reachability on the left side
- * if (and only if) it fulfills all of the requirements on the right side. In
- * all rows, consider the <em>root set</em> to be a set of references that
- * are "resistant" to garbage collection (that is, running threads, method
- * parameters, local variables, static fields and the like).
- *
- * <p><table>
- * <tr>
- * <td>Strongly reachable</td>
- * <td> <ul>
- * <li>There exists at least one path from the root set to the object that does not traverse any
- * instance of a {@code java.lang.ref.Reference} subclass.
- * </li>
- * </ul> </td>
- * </tr>
- *
- * <tr>
- * <td>Softly reachable</td>
- * <td> <ul>
- * <li>The object is not strongly reachable.</li>
- * <li>There exists at least one path from the root set to the object that does traverse
- * a {@code java.lang.ref.SoftReference} instance, but no {@code java.lang.ref.WeakReference}
- * or {@code java.lang.ref.PhantomReference} instances.</li>
- * </ul> </td>
- * </tr>
- *
- * <tr>
- * <td>Weakly reachable</td>
- * <td> <ul>
- * <li>The object is neither strongly nor softly reachable.</li>
- * <li>There exists at least one path from the root set to the object that does traverse a
- * {@code java.lang.ref.WeakReference} instance, but no {@code java.lang.ref.PhantomReference}
- * instances.</li>
- * </ul> </td>
- * </tr>
- *
- * <tr>
- * <td>Phantom-reachable</td>
- * <td> <ul>
- * <li>The object is neither strongly, softly, nor weakly reachable.</li>
- * <li>The object is referenced by a {@code java.lang.ref.PhantomReference} instance.</li>
- * <li>The object has already been finalized.</li>
- * </ul> </td>
- * </tr>
- * </table>
- */
-public abstract class Reference<T> {
-
- /**
- * The object to which this reference refers.
- * VM requirement: this field <em>must</em> be called "referent"
- * and be an object.
- */
- volatile T referent;
-
- /**
- * If non-null, the queue on which this reference will be enqueued
- * when the referent is appropriately reachable.
- * VM requirement: this field <em>must</em> be called "queue"
- * and be a java.lang.ref.ReferenceQueue.
- */
- volatile ReferenceQueue<? super T> queue;
-
- /**
- * Used internally by java.lang.ref.ReferenceQueue.
- * VM requirement: this field <em>must</em> be called "queueNext"
- * and be a java.lang.ref.Reference.
- */
- @SuppressWarnings("unchecked")
- volatile Reference queueNext;
-
- /**
- * Used internally by the VM. This field forms a circular and
- * singly linked list of reference objects discovered by the
- * garbage collector and awaiting processing by the reference
- * queue thread.
- *
- * @hide
- */
- public volatile Reference<?> pendingNext;
-
- /**
- * Constructs a new instance of this class.
- */
- Reference() {
- }
-
- Reference(T r, ReferenceQueue<? super T> q) {
- referent = r;
- queue = q;
- }
-
- /**
- * Makes the referent {@code null}. This does not force the reference
- * object to be enqueued.
- */
- public void clear() {
- referent = null;
- }
-
- /**
- * Adds an object to its reference queue.
- *
- * @return {@code true} if this call has caused the {@code Reference} to
- * become enqueued, or {@code false} otherwise
- *
- * @hide
- */
- public final synchronized boolean enqueueInternal() {
- if (queue != null && queueNext == null) {
- queue.enqueue(this);
- queue = null;
- return true;
- }
- return false;
- }
-
- /**
- * Forces the reference object to be enqueued if it has been associated with
- * a queue.
- *
- * @return {@code true} if this call has caused the {@code Reference} to
- * become enqueued, or {@code false} otherwise
- */
- public boolean enqueue() {
- return enqueueInternal();
- }
-
- /**
- * Returns the referent of the reference object.
- *
- * @return the referent to which reference refers, or {@code null} if the
- * object has been cleared.
- */
- public T get() {
- return referent;
- }
-
- /**
- * Checks whether the reference object has been enqueued.
- *
- * @return {@code true} if the {@code Reference} has been enqueued, {@code
- * false} otherwise
- */
- public boolean isEnqueued() {
- return queueNext != null;
- }
-
-}
diff --git a/luni/src/main/java/java/lang/ref/ReferenceQueue.java b/luni/src/main/java/java/lang/ref/ReferenceQueue.java
index 2b8089c..4c78fbf 100644
--- a/luni/src/main/java/java/lang/ref/ReferenceQueue.java
+++ b/luni/src/main/java/java/lang/ref/ReferenceQueue.java
@@ -28,6 +28,7 @@ public class ReferenceQueue<T> {
private static final int NANOS_PER_MILLI = 1000000;
private Reference<? extends T> head;
+ private Reference<? extends T> tail;
/**
* Constructs a new instance of this class.
@@ -48,18 +49,16 @@ public class ReferenceQueue<T> {
return null;
}
- Reference<? extends T> ret;
+ Reference<? extends T> ret = head;
- ret = head;
-
- if (head == head.queueNext) {
+ if (head == tail) {
+ tail = null;
head = null;
} else {
head = head.queueNext;
}
ret.queueNext = null;
-
return ret;
}
@@ -133,12 +132,16 @@ public class ReferenceQueue<T> {
* reference object to be enqueued.
*/
synchronized void enqueue(Reference<? extends T> reference) {
- if (head == null) {
- reference.queueNext = reference;
+ if (tail == null) {
+ head = reference;
} else {
- reference.queueNext = head;
+ tail.queueNext = reference;
}
- head = reference;
+
+ // The newly enqueued reference becomes the new tail, and always
+ // points to itself.
+ tail = reference;
+ tail.queueNext = reference;
notify();
}
@@ -150,9 +153,18 @@ public class ReferenceQueue<T> {
if (unenqueued == null) {
unenqueued = list;
} else {
- Reference<?> next = unenqueued.pendingNext;
- unenqueued.pendingNext = list.pendingNext;
- list.pendingNext = next;
+ // Find the last element in unenqueued.
+ Reference<?> last = unenqueued;
+ while (last.pendingNext != unenqueued) {
+ last = last.pendingNext;
+ }
+ // Add our list to the end. Update the pendingNext to point back to enqueued.
+ last.pendingNext = list;
+ last = list;
+ while (last.pendingNext != list) {
+ last = last.pendingNext;
+ }
+ last.pendingNext = unenqueued;
}
ReferenceQueue.class.notifyAll();
}
diff --git a/luni/src/main/java/java/lang/reflect/Array.java b/luni/src/main/java/java/lang/reflect/Array.java
index 088a434..a7dacfe 100644
--- a/luni/src/main/java/java/lang/reflect/Array.java
+++ b/luni/src/main/java/java/lang/reflect/Array.java
@@ -352,16 +352,16 @@ public final class Array {
public static Object newInstance(Class<?> componentType, int size) throws NegativeArraySizeException {
if (!componentType.isPrimitive()) {
return createObjectArray(componentType, size);
- } else if (componentType == boolean.class) {
- return new boolean[size];
- } else if (componentType == byte.class) {
- return new byte[size];
} else if (componentType == char.class) {
return new char[size];
- } else if (componentType == short.class) {
- return new short[size];
} else if (componentType == int.class) {
return new int[size];
+ } else if (componentType == byte.class) {
+ return new byte[size];
+ } else if (componentType == boolean.class) {
+ return new boolean[size];
+ } else if (componentType == short.class) {
+ return new short[size];
} else if (componentType == long.class) {
return new long[size];
} else if (componentType == float.class) {
diff --git a/luni/src/main/java/java/lang/reflect/Modifier.java b/luni/src/main/java/java/lang/reflect/Modifier.java
index 5f973d5..257064e 100644
--- a/luni/src/main/java/java/lang/reflect/Modifier.java
+++ b/luni/src/main/java/java/lang/reflect/Modifier.java
@@ -106,7 +106,7 @@ public class Modifier {
* require they implement.
* @hide
*/
- public static final int MIRANDA = 0x8000;
+ public static final int MIRANDA = 0x200000;
/**
* Dex addition to mark instance constructors and static class
diff --git a/luni/src/main/java/java/math/BigDecimal.java b/luni/src/main/java/java/math/BigDecimal.java
index 03ce8dd..f735607 100644
--- a/luni/src/main/java/java/math/BigDecimal.java
+++ b/luni/src/main/java/java/math/BigDecimal.java
@@ -1025,6 +1025,14 @@ public class BigDecimal extends Number implements Comparable<BigDecimal>, Serial
}
long diffScale = ((long)this.scale - divisor.scale) - scale;
+
+ // Check whether the diffScale will fit into an int. See http://b/17393664.
+ if (bitLength(diffScale) > 32) {
+ throw new ArithmeticException(
+ "Unable to perform divisor / dividend scaling: the difference in scale is too" +
+ " big (" + diffScale + ")");
+ }
+
if(this.bitLength < 64 && divisor.bitLength < 64 ) {
if(diffScale == 0) {
return dividePrimitiveLongs(this.smallValue,
diff --git a/luni/src/main/java/java/math/Multiplication.java b/luni/src/main/java/java/math/Multiplication.java
index 98cabee..093b1b7 100644
--- a/luni/src/main/java/java/math/Multiplication.java
+++ b/luni/src/main/java/java/math/Multiplication.java
@@ -125,49 +125,45 @@ class Multiplication {
} else if (exp <= 50) {
// To calculate: 10^exp
return BigInteger.TEN.pow(intExp);
- } else if (exp <= 1000) {
- // To calculate: 5^exp * 2^exp
- return bigFivePows[1].pow(intExp).shiftLeft(intExp);
}
- // "LARGE POWERS"
- /*
- * To check if there is free memory to allocate a BigInteger of the
- * estimated size, measured in bytes: 1 + [exp / log10(2)]
- */
- long byteArraySize = 1 + (long)(exp / 2.4082399653118496);
-
- if (byteArraySize > Runtime.getRuntime().freeMemory()) {
- throw new ArithmeticException();
- }
- if (exp <= Integer.MAX_VALUE) {
- // To calculate: 5^exp * 2^exp
- return bigFivePows[1].pow(intExp).shiftLeft(intExp);
- }
- /*
- * "HUGE POWERS"
- *
- * This branch probably won't be executed since the power of ten is too
- * big.
- */
- // To calculate: 5^exp
- BigInteger powerOfFive = bigFivePows[1].pow(Integer.MAX_VALUE);
- BigInteger res = powerOfFive;
- long longExp = exp - Integer.MAX_VALUE;
-
- intExp = (int)(exp % Integer.MAX_VALUE);
- while (longExp > Integer.MAX_VALUE) {
- res = res.multiply(powerOfFive);
- longExp -= Integer.MAX_VALUE;
- }
- res = res.multiply(bigFivePows[1].pow(intExp));
- // To calculate: 5^exp << exp
- res = res.shiftLeft(Integer.MAX_VALUE);
- longExp = exp - Integer.MAX_VALUE;
- while (longExp > Integer.MAX_VALUE) {
- res = res.shiftLeft(Integer.MAX_VALUE);
- longExp -= Integer.MAX_VALUE;
+
+ BigInteger res = null;
+ try {
+ // "LARGE POWERS"
+ if (exp <= Integer.MAX_VALUE) {
+ // To calculate: 5^exp * 2^exp
+ res = bigFivePows[1].pow(intExp).shiftLeft(intExp);
+ } else {
+ /*
+ * "HUGE POWERS"
+ *
+ * This branch probably won't be executed since the power of ten is too
+ * big.
+ */
+ // To calculate: 5^exp
+ BigInteger powerOfFive = bigFivePows[1].pow(Integer.MAX_VALUE);
+ res = powerOfFive;
+ long longExp = exp - Integer.MAX_VALUE;
+
+ intExp = (int) (exp % Integer.MAX_VALUE);
+ while (longExp > Integer.MAX_VALUE) {
+ res = res.multiply(powerOfFive);
+ longExp -= Integer.MAX_VALUE;
+ }
+ res = res.multiply(bigFivePows[1].pow(intExp));
+ // To calculate: 5^exp << exp
+ res = res.shiftLeft(Integer.MAX_VALUE);
+ longExp = exp - Integer.MAX_VALUE;
+ while (longExp > Integer.MAX_VALUE) {
+ res = res.shiftLeft(Integer.MAX_VALUE);
+ longExp -= Integer.MAX_VALUE;
+ }
+ res = res.shiftLeft(intExp);
+ }
+ } catch (OutOfMemoryError error) {
+ throw new ArithmeticException(error.getMessage());
}
- res = res.shiftLeft(intExp);
+
return res;
}
diff --git a/luni/src/main/java/java/net/AddressCache.java b/luni/src/main/java/java/net/AddressCache.java
index 194761a..2aba78b 100644
--- a/luni/src/main/java/java/net/AddressCache.java
+++ b/luni/src/main/java/java/net/AddressCache.java
@@ -37,8 +37,36 @@ class AddressCache {
private static final long TTL_NANOS = 2 * 1000000000L;
// The actual cache.
- private final BasicLruCache<String, AddressCacheEntry> cache
- = new BasicLruCache<String, AddressCacheEntry>(MAX_ENTRIES);
+ private final BasicLruCache<AddressCacheKey, AddressCacheEntry> cache
+ = new BasicLruCache<AddressCacheKey, AddressCacheEntry>(MAX_ENTRIES);
+
+ static class AddressCacheKey {
+ private final String mHostname;
+ private final int mNetId;
+
+ AddressCacheKey(String hostname, int netId) {
+ mHostname = hostname;
+ mNetId = netId;
+ }
+
+ @Override public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof AddressCacheKey)) {
+ return false;
+ }
+ AddressCacheKey lhs = (AddressCacheKey) o;
+ return mHostname.equals(lhs.mHostname) && mNetId == lhs.mNetId;
+ }
+
+ @Override public int hashCode() {
+ int result = 17;
+ result = 31 * result + mNetId;
+ result = 31 * result + mHostname.hashCode();
+ return result;
+ }
+ }
static class AddressCacheEntry {
// Either an InetAddress[] for a positive entry,
@@ -67,12 +95,12 @@ class AddressCache {
}
/**
- * Returns the cached InetAddress[] associated with 'hostname'. Returns null if nothing is known
- * about 'hostname'. Returns a String suitable for use as an UnknownHostException detail
- * message if 'hostname' is known not to exist.
+ * Returns the cached InetAddress[] for 'hostname' on network 'netId'. Returns null
+ * if nothing is known about 'hostname'. Returns a String suitable for use as an
+ * UnknownHostException detail message if 'hostname' is known not to exist.
*/
- public Object get(String hostname) {
- AddressCacheEntry entry = cache.get(hostname);
+ public Object get(String hostname, int netId) {
+ AddressCacheEntry entry = cache.get(new AddressCacheKey(hostname, netId));
// Do we have a valid cache entry?
if (entry != null && entry.expiryNanos >= System.nanoTime()) {
return entry.value;
@@ -86,15 +114,15 @@ class AddressCache {
* Associates the given 'addresses' with 'hostname'. The association will expire after a
* certain length of time.
*/
- public void put(String hostname, InetAddress[] addresses) {
- cache.put(hostname, new AddressCacheEntry(addresses));
+ public void put(String hostname, int netId, InetAddress[] addresses) {
+ cache.put(new AddressCacheKey(hostname, netId), new AddressCacheEntry(addresses));
}
/**
* Records that 'hostname' is known not to have any associated addresses. (I.e. insert a
* negative cache entry.)
*/
- public void putUnknownHost(String hostname, String detailMessage) {
- cache.put(hostname, new AddressCacheEntry(detailMessage));
+ public void putUnknownHost(String hostname, int netId, String detailMessage) {
+ cache.put(new AddressCacheKey(hostname, netId), new AddressCacheEntry(detailMessage));
}
}
diff --git a/luni/src/main/java/java/net/DatagramSocket.java b/luni/src/main/java/java/net/DatagramSocket.java
index 49f141a..f9b72d8 100644
--- a/luni/src/main/java/java/net/DatagramSocket.java
+++ b/luni/src/main/java/java/net/DatagramSocket.java
@@ -17,14 +17,14 @@
package java.net;
+import android.system.ErrnoException;
import java.io.Closeable;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.channels.DatagramChannel;
-import libcore.io.ErrnoException;
import libcore.io.IoBridge;
import libcore.io.Libcore;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* This class implements a UDP socket for sending and receiving {@code
@@ -114,6 +114,17 @@ public class DatagramSocket implements Closeable {
}
/**
+ * Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful close()
+ * took place, without actually performing an OS close().
+ *
+ * @hide used in java.nio
+ */
+ public void onClose() {
+ isClosed = true;
+ impl.onClose();
+ }
+
+ /**
* Disconnects this UDP datagram socket from the remote host. This method
* called on an unconnected socket does nothing.
*/
@@ -127,6 +138,19 @@ public class DatagramSocket implements Closeable {
isConnected = false;
}
+ /**
+ * Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful
+ * disconnect() took place, without actually performing a disconnect().
+ *
+ * @hide used in java.nio
+ */
+ public void onDisconnect() {
+ address = null;
+ port = -1;
+ isConnected = false;
+ impl.onDisconnect();
+ }
+
synchronized void createSocket(int aPort, InetAddress addr) throws SocketException {
impl = factory != null ? factory.createDatagramSocketImpl()
: new PlainDatagramSocketImpl();
@@ -152,8 +176,8 @@ public class DatagramSocket implements Closeable {
}
/**
- * Returns the local address to which this socket is bound,
- * or {@code null} if this socket is closed.
+ * Returns the local address to which this socket is bound, a wildcard address if this
+ * socket is not yet bound, or {@code null} if this socket is closed.
*/
public InetAddress getLocalAddress() {
try {
@@ -439,9 +463,12 @@ public class DatagramSocket implements Closeable {
*/
public void bind(SocketAddress localAddr) throws SocketException {
checkOpen();
- int localPort = 0;
- InetAddress addr = Inet4Address.ANY;
- if (localAddr != null) {
+ int localPort;
+ InetAddress addr;
+ if (localAddr == null) {
+ localPort = 0;
+ addr = Inet4Address.ANY;
+ } else {
if (!(localAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Local address not an InetSocketAddress: " +
localAddr.getClass());
@@ -459,6 +486,17 @@ public class DatagramSocket implements Closeable {
}
/**
+ * Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful bind()
+ * took place, without actually performing an OS bind().
+ *
+ * @hide used in java.nio
+ */
+ public void onBind(InetAddress localAddress, int localPort) {
+ isBound = true;
+ impl.onBind(localAddress, localPort);
+ }
+
+ /**
* Connects this datagram socket to the address and port specified by {@code peer}.
* Future calls to {@link #send} will use this as the default target, and {@link #receive}
* will only accept packets from this source.
@@ -492,6 +530,19 @@ public class DatagramSocket implements Closeable {
}
/**
+ * Sets the DatagramSocket and its related DatagramSocketImpl state as if a successful connect()
+ * took place, without actually performing an OS connect().
+ *
+ * @hide used in java.nio
+ */
+ public void onConnect(InetAddress remoteAddress, int remotePort) {
+ isConnected = true;
+ this.address = remoteAddress;
+ this.port = remotePort;
+ impl.onConnect(remoteAddress, remotePort);
+ }
+
+ /**
* Connects this datagram socket to the specific {@code address} and {@code port}.
* Future calls to {@link #send} will use this as the default target, and {@link #receive}
* will only accept packets from this source.
@@ -537,10 +588,11 @@ public class DatagramSocket implements Closeable {
}
/**
- * Returns the {@code SocketAddress} this socket is bound to, or null for an unbound socket.
+ * Returns the {@code SocketAddress} this socket is bound to, or {@code null} for an unbound or
+ * closed socket.
*/
public SocketAddress getLocalSocketAddress() {
- if (!isBound()) {
+ if (isClosed() || !isBound()) {
return null;
}
return new InetSocketAddress(getLocalAddress(), getLocalPort());
diff --git a/luni/src/main/java/java/net/DatagramSocketImpl.java b/luni/src/main/java/java/net/DatagramSocketImpl.java
index 097eb17..1a39987 100644
--- a/luni/src/main/java/java/net/DatagramSocketImpl.java
+++ b/luni/src/main/java/java/net/DatagramSocketImpl.java
@@ -268,4 +268,40 @@ public abstract class DatagramSocketImpl implements SocketOptions {
* if an error occurs while peeking at the data.
*/
protected abstract int peekData(DatagramPacket pack) throws IOException;
+
+ /**
+ * Initialize the bind() state.
+ * @hide used in java.nio.
+ */
+ protected void onBind(InetAddress localAddress, int localPort) {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
+
+ /**
+ * Initialize the connect() state.
+ * @hide used in java.nio.
+ */
+ protected void onConnect(InetAddress remoteAddress, int remotePort) {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
+
+ /**
+ * Initialize the disconnected state.
+ * @hide used in java.nio.
+ */
+ protected void onDisconnect() {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
+
+ /**
+ * Initialize the closed state.
+ * @hide used in java.nio.
+ */
+ protected void onClose() {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
}
diff --git a/luni/src/main/java/java/net/HttpCookie.java b/luni/src/main/java/java/net/HttpCookie.java
index ce1a8d2..dd81fd6 100644
--- a/luni/src/main/java/java/net/HttpCookie.java
+++ b/luni/src/main/java/java/net/HttpCookie.java
@@ -53,10 +53,12 @@ import libcore.util.Objects;
* in this format is {@code 1}.
* </ul>
*
- * <p>This implementation silently discards unrecognized attributes. In
- * particular, the {@code HttpOnly} attribute is widely served but isn't in any
- * of the above specs. It was introduced by Internet Explorer to prevent server
- * cookies from being exposed in the DOM to JavaScript, etc.
+ * <p>Support for the "HttpOnly" attribute specified in
+ * <a href="http://tools.ietf.org/html/rfc6265">RFC 6265</a> is also included. RFC 6265 is intended
+ * to obsolete RFC 2965. Support for features from RFC 2965 that have been deprecated by RFC 6265
+ * such as Cookie2, Set-Cookie2 headers and version information remain supported by this class.
+ *
+ * <p>This implementation silently discards unrecognized attributes.
*
* @since 1.6
*/
@@ -65,16 +67,17 @@ public final class HttpCookie implements Cloneable {
private static final Set<String> RESERVED_NAMES = new HashSet<String>();
static {
- RESERVED_NAMES.add("comment"); // RFC 2109 RFC 2965
- RESERVED_NAMES.add("commenturl"); // RFC 2965
- RESERVED_NAMES.add("discard"); // RFC 2965
- RESERVED_NAMES.add("domain"); // Netscape RFC 2109 RFC 2965
+ RESERVED_NAMES.add("comment"); // RFC 2109 RFC 2965 RFC 6265
+ RESERVED_NAMES.add("commenturl"); // RFC 2965 RFC 6265
+ RESERVED_NAMES.add("discard"); // RFC 2965 RFC 6265
+ RESERVED_NAMES.add("domain"); // Netscape RFC 2109 RFC 2965 RFC 6265
RESERVED_NAMES.add("expires"); // Netscape
- RESERVED_NAMES.add("max-age"); // RFC 2109 RFC 2965
- RESERVED_NAMES.add("path"); // Netscape RFC 2109 RFC 2965
- RESERVED_NAMES.add("port"); // RFC 2965
- RESERVED_NAMES.add("secure"); // Netscape RFC 2109 RFC 2965
- RESERVED_NAMES.add("version"); // RFC 2109 RFC 2965
+ RESERVED_NAMES.add("httponly"); // RFC 6265
+ RESERVED_NAMES.add("max-age"); // RFC 2109 RFC 2965 RFC 6265
+ RESERVED_NAMES.add("path"); // Netscape RFC 2109 RFC 2965 RFC 6265
+ RESERVED_NAMES.add("port"); // RFC 2965 RFC 6265
+ RESERVED_NAMES.add("secure"); // Netscape RFC 2109 RFC 2965 RFC 6265
+ RESERVED_NAMES.add("version"); // RFC 2109 RFC 2965 RFC 6265
}
/**
@@ -332,14 +335,26 @@ public final class HttpCookie implements Cloneable {
}
}
} else if (name.equals("max-age") && cookie.maxAge == -1L) {
- hasMaxAge = true;
- cookie.maxAge = Long.parseLong(value);
+ // RFCs 2109 and 2965 suggests a zero max-age as a way of deleting a cookie.
+ // RFC 6265 specifies the value must be > 0 but also describes what to do if the
+ // value is negative, zero or non-numeric in section 5.2.2. The RI does none of this
+ // and accepts negative, positive values and throws an IllegalArgumentException
+ // if the value is non-numeric.
+ try {
+ long maxAge = Long.parseLong(value);
+ hasMaxAge = true;
+ cookie.maxAge = maxAge;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid max-age: " + value);
+ }
} else if (name.equals("path") && cookie.path == null) {
cookie.path = value;
} else if (name.equals("port") && cookie.portList == null) {
cookie.portList = value != null ? value : "";
} else if (name.equals("secure")) {
cookie.secure = true;
+ } else if (name.equals("httponly")) {
+ cookie.httpOnly = true;
} else if (name.equals("version") && !hasVersion) {
cookie.version = Integer.parseInt(value);
}
@@ -430,6 +445,7 @@ public final class HttpCookie implements Cloneable {
private String path;
private String portList;
private boolean secure;
+ private boolean httpOnly;
private String value;
private int version = 1;
@@ -698,7 +714,21 @@ public final class HttpCookie implements Cloneable {
/**
* Returns a string representing this cookie in the format used by the
- * {@code Cookie} header line in an HTTP request.
+ * {@code Cookie} header line in an HTTP request as specified by RFC 2965 section 3.3.4.
+ *
+ * <p>The resulting string does not include a "Cookie:" prefix or any version information.
+ * The returned {@code String} is not suitable for passing to {@link #parse(String)}: Several of
+ * the attributes that would be needed to preserve all of the cookie's information are omitted.
+ * The String is formatted for an HTTP request not an HTTP response.
+ *
+ * <p>The attributes included and the format depends on the cookie's {@code version}:
+ * <ul>
+ * <li>Version 0: Includes only the name and value. Conforms to RFC 2965 (for
+ * version 0 cookies). This should also be used to conform with RFC 6265.
+ * </li>
+ * <li>Version 1: Includes the name and value, and Path, Domain and Port attributes.
+ * Conforms to RFC 2965 (for version 1 cookies).</li>
+ * </ul>
*/
@Override public String toString() {
if (version == 0) {
diff --git a/luni/src/main/java/java/net/HttpURLConnection.java b/luni/src/main/java/java/net/HttpURLConnection.java
index 89a4bc4..4e5b4ee 100644
--- a/luni/src/main/java/java/net/HttpURLConnection.java
+++ b/luni/src/main/java/java/net/HttpURLConnection.java
@@ -784,11 +784,15 @@ public abstract class HttpURLConnection extends URLConnection {
* only servers may not support this mode.
*
* <p>When HTTP chunked encoding is used, the stream is divided into
- * chunks, each prefixed with a header containing the chunk's size. Setting
- * a large chunk length requires a large internal buffer, potentially
- * wasting memory. Setting a small chunk length increases the number of
+ * chunks, each prefixed with a header containing the chunk's size.
+ * A large chunk length requires a large internal buffer, potentially
+ * wasting memory. A small chunk length increases the number of
* bytes that must be transmitted because of the header on every chunk.
- * Most caller should use {@code 0} to get the system default.
+ *
+ * <p>Implementation details: In some releases the {@code chunkLength} is
+ * treated as a hint: chunks sent to the server may actually be larger or
+ * smaller. To force a chunk to be sent to the server call
+ * {@link java.io.OutputStream#flush()}.
*
* @see #setFixedLengthStreamingMode
* @param chunkLength the length to use, or {@code 0} for the default chunk
diff --git a/luni/src/main/java/java/net/Inet4Address.java b/luni/src/main/java/java/net/Inet4Address.java
index 7c26639..f0b1b5b 100644
--- a/luni/src/main/java/java/net/Inet4Address.java
+++ b/luni/src/main/java/java/net/Inet4Address.java
@@ -20,7 +20,7 @@ package java.net;
import java.io.ObjectStreamException;
import java.nio.ByteOrder;
import libcore.io.Memory;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* An IPv4 address. See {@link InetAddress}.
diff --git a/luni/src/main/java/java/net/Inet6Address.java b/luni/src/main/java/java/net/Inet6Address.java
index 37e9c18..8ab0f8d 100644
--- a/luni/src/main/java/java/net/Inet6Address.java
+++ b/luni/src/main/java/java/net/Inet6Address.java
@@ -23,7 +23,7 @@ import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.util.Arrays;
import java.util.Enumeration;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* An IPv6 address. See {@link InetAddress}.
diff --git a/luni/src/main/java/java/net/InetAddress.java b/luni/src/main/java/java/net/InetAddress.java
index 98ad098..5cfa15a 100644
--- a/luni/src/main/java/java/net/InetAddress.java
+++ b/luni/src/main/java/java/net/InetAddress.java
@@ -17,6 +17,9 @@
package java.net;
+import android.system.ErrnoException;
+import android.system.GaiException;
+import android.system.StructAddrinfo;
import dalvik.system.BlockGuard;
import java.io.FileDescriptor;
import java.io.IOException;
@@ -28,18 +31,13 @@ import java.io.Serializable;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Collections;
-import java.util.Comparator;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
-import libcore.io.ErrnoException;
-import libcore.io.GaiException;
+import java.util.concurrent.CountDownLatch;
+import java.util.List;
import libcore.io.IoBridge;
import libcore.io.Libcore;
import libcore.io.Memory;
-import libcore.io.StructAddrinfo;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and
@@ -129,6 +127,9 @@ public class InetAddress implements Serializable {
private static final long serialVersionUID = 3286316764910316507L;
+ /** Using NetID of NETID_UNSET indicates resolution should be done on default network. */
+ private static final int NETID_UNSET = 0;
+
private int family;
byte[] ipaddress;
@@ -211,14 +212,29 @@ public class InetAddress implements Serializable {
* @throws UnknownHostException if the address lookup fails.
*/
public static InetAddress[] getAllByName(String host) throws UnknownHostException {
- return getAllByNameImpl(host).clone();
+ return getAllByNameImpl(host, NETID_UNSET).clone();
}
/**
- * Returns the InetAddresses for {@code host}. The returned array is shared
- * and must be cloned before it is returned to application code.
+ * Operates identically to {@code getAllByName} except host resolution is
+ * performed on the network designated by {@code netId}.
+ *
+ * @param host the hostname or literal IP string to be resolved.
+ * @param netId the network to use for host resolution.
+ * @return the array of addresses associated with the specified host.
+ * @throws UnknownHostException if the address lookup fails.
+ * @hide internal use only
*/
- private static InetAddress[] getAllByNameImpl(String host) throws UnknownHostException {
+ public static InetAddress[] getAllByNameOnNet(String host, int netId) throws UnknownHostException {
+ return getAllByNameImpl(host, netId).clone();
+ }
+
+ /**
+ * Returns the InetAddresses for {@code host} on network {@code netId}. The
+ * returned array is shared and must be cloned before it is returned to
+ * application code.
+ */
+ private static InetAddress[] getAllByNameImpl(String host, int netId) throws UnknownHostException {
if (host == null || host.isEmpty()) {
return loopbackAddresses();
}
@@ -233,7 +249,7 @@ public class InetAddress implements Serializable {
return new InetAddress[] { result };
}
- return lookupHostByName(host).clone();
+ return lookupHostByName(host, netId).clone();
}
private static InetAddress makeInetAddress(byte[] bytes, String hostName) throws UnknownHostException {
@@ -266,7 +282,7 @@ public class InetAddress implements Serializable {
hints.ai_flags = AI_NUMERICHOST;
InetAddress[] addresses = null;
try {
- addresses = Libcore.os.getaddrinfo(address, hints);
+ addresses = Libcore.os.android_getaddrinfo(address, hints, NETID_UNSET);
} catch (GaiException ignored) {
}
return (addresses != null) ? addresses[0] : null;
@@ -286,7 +302,22 @@ public class InetAddress implements Serializable {
* if the address lookup fails.
*/
public static InetAddress getByName(String host) throws UnknownHostException {
- return getAllByNameImpl(host)[0];
+ return getAllByNameImpl(host, NETID_UNSET)[0];
+ }
+
+ /**
+ * Operates identically to {@code getByName} except host resolution is
+ * performed on the network designated by {@code netId}.
+ *
+ * @param host
+ * the hostName to be resolved to an address or {@code null}.
+ * @param netId the network to use for host resolution.
+ * @return the {@code InetAddress} instance representing the host.
+ * @throws UnknownHostException if the address lookup fails.
+ * @hide internal use only
+ */
+ public static InetAddress getByNameOnNet(String host, int netId) throws UnknownHostException {
+ return getAllByNameImpl(host, netId)[0];
}
/**
@@ -362,7 +393,7 @@ public class InetAddress implements Serializable {
*/
public static InetAddress getLocalHost() throws UnknownHostException {
String host = Libcore.os.uname().nodename;
- return lookupHostByName(host)[0];
+ return lookupHostByName(host, NETID_UNSET)[0];
}
/**
@@ -379,12 +410,14 @@ public class InetAddress implements Serializable {
* Resolves a hostname to its IP addresses using a cache.
*
* @param host the hostname to resolve.
+ * @param netId the network to perform resolution upon.
* @return the IP addresses of the host.
*/
- private static InetAddress[] lookupHostByName(String host) throws UnknownHostException {
+ private static InetAddress[] lookupHostByName(String host, int netId)
+ throws UnknownHostException {
BlockGuard.getThreadPolicy().onNetwork();
// Do we have a result cached?
- Object cachedResult = addressCache.get(host);
+ Object cachedResult = addressCache.get(host, netId);
if (cachedResult != null) {
if (cachedResult instanceof InetAddress[]) {
// A cached positive result.
@@ -402,12 +435,12 @@ public class InetAddress implements Serializable {
// for SOCK_STREAM and one for SOCK_DGRAM. Since we do not return the family
// anyway, just pick one.
hints.ai_socktype = SOCK_STREAM;
- InetAddress[] addresses = Libcore.os.getaddrinfo(host, hints);
+ InetAddress[] addresses = Libcore.os.android_getaddrinfo(host, hints, netId);
// TODO: should getaddrinfo set the hostname of the InetAddresses it returns?
for (InetAddress address : addresses) {
address.hostName = host;
}
- addressCache.put(host, addresses);
+ addressCache.put(host, netId, addresses);
return addresses;
} catch (GaiException gaiException) {
// If the failure appears to have been a lack of INTERNET permission, throw a clear
@@ -420,7 +453,7 @@ public class InetAddress implements Serializable {
}
// Otherwise, throw an UnknownHostException.
String detailMessage = "Unable to resolve host \"" + host + "\": " + Libcore.os.gai_strerror(gaiException.error);
- addressCache.putUnknownHost(host, detailMessage);
+ addressCache.putUnknownHost(host, netId, detailMessage);
throw gaiException.rethrowAsUnknownHostException(detailMessage);
}
}
@@ -734,7 +767,7 @@ public class InetAddress implements Serializable {
}
}
- IoBridge.closeSocket(fd);
+ IoBridge.closeAndSignalBlockedThreads(fd);
return reached;
}
diff --git a/luni/src/main/java/java/net/InetUnixAddress.java b/luni/src/main/java/java/net/InetUnixAddress.java
index 44b9cba..51236e2 100644
--- a/luni/src/main/java/java/net/InetUnixAddress.java
+++ b/luni/src/main/java/java/net/InetUnixAddress.java
@@ -18,7 +18,7 @@ package java.net;
import java.nio.charset.StandardCharsets;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* An AF_UNIX address. See {@link InetAddress}.
diff --git a/luni/src/main/java/java/net/JarURLConnection.java b/luni/src/main/java/java/net/JarURLConnection.java
index 4b84893..e5c8fac 100644
--- a/luni/src/main/java/java/net/JarURLConnection.java
+++ b/luni/src/main/java/java/net/JarURLConnection.java
@@ -18,11 +18,13 @@
package java.net;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
+import libcore.net.UriCodec;
/**
* This class establishes a connection to a {@code jar:} URL using the {@code
@@ -64,12 +66,13 @@ public abstract class JarURLConnection extends URLConnection {
*/
protected JarURLConnection(URL url) throws MalformedURLException {
super(url);
- file = url.getFile();
+ file = decode(url.getFile());
+
int sepIdx;
if ((sepIdx = file.indexOf("!/")) < 0) {
throw new MalformedURLException();
}
- fileURL = new URL(url.getFile().substring(0,sepIdx));
+ fileURL = new URL(file.substring(0, sepIdx));
sepIdx += 2;
if (file.length() == sepIdx) {
return;
@@ -189,4 +192,17 @@ public abstract class JarURLConnection extends URLConnection {
Manifest m = getJarFile().getManifest();
return (m == null) ? null : m.getMainAttributes();
}
+
+ private static String decode(String encoded) throws MalformedURLException {
+ try {
+ // "+" means "+" in URLs. i.e. like RFC 3986, not like
+ // MIME application/x-www-form-urlencoded
+ final boolean convertPlus = false;
+ return UriCodec.decode(
+ encoded, convertPlus, StandardCharsets.UTF_8, true /* throwOnFailure */);
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unable to decode URL", e);
+ }
+ }
+
}
diff --git a/luni/src/main/java/java/net/MulticastSocket.java b/luni/src/main/java/java/net/MulticastSocket.java
index 6f4a582..24e66c5 100644
--- a/luni/src/main/java/java/net/MulticastSocket.java
+++ b/luni/src/main/java/java/net/MulticastSocket.java
@@ -229,6 +229,9 @@ public class MulticastSocket extends DatagramSocket {
private void checkJoinOrLeave(InetAddress groupAddr) throws IOException {
checkOpen();
+ if (groupAddr == null) {
+ throw new IllegalArgumentException("groupAddress == null");
+ }
if (!groupAddr.isMulticastAddress()) {
throw new IOException("Not a multicast group: " + groupAddr);
}
@@ -351,7 +354,8 @@ public class MulticastSocket extends DatagramSocket {
/**
* Disables multicast loopback if {@code disable == true}.
* See {@link SocketOptions#IP_MULTICAST_LOOP}, and note that the sense of this is the
- * opposite of the underlying Unix {@code IP_MULTICAST_LOOP}.
+ * opposite of the underlying Unix {@code IP_MULTICAST_LOOP}: true means disabled, false
+ * means enabled.
*
* @throws SocketException if an error occurs.
*/
diff --git a/luni/src/main/java/java/net/NetworkInterface.java b/luni/src/main/java/java/net/NetworkInterface.java
index 3128b98..852c09b 100644
--- a/luni/src/main/java/java/net/NetworkInterface.java
+++ b/luni/src/main/java/java/net/NetworkInterface.java
@@ -17,6 +17,7 @@
package java.net;
+import android.system.ErrnoException;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
@@ -26,10 +27,9 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
-import libcore.io.ErrnoException;
import libcore.io.IoUtils;
import libcore.io.Libcore;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* This class is used to represent a network interface of the local device. An
diff --git a/luni/src/main/java/java/net/PlainDatagramSocketImpl.java b/luni/src/main/java/java/net/PlainDatagramSocketImpl.java
index 3226527..eb0c99d 100644
--- a/luni/src/main/java/java/net/PlainDatagramSocketImpl.java
+++ b/luni/src/main/java/java/net/PlainDatagramSocketImpl.java
@@ -17,23 +17,15 @@
package java.net;
+import android.system.ErrnoException;
+import android.system.StructGroupReq;
import dalvik.system.CloseGuard;
import java.io.FileDescriptor;
import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocketImpl;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.NetworkInterface;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-import libcore.io.ErrnoException;
import libcore.io.IoBridge;
import libcore.io.Libcore;
-import libcore.io.StructGroupReq;
import libcore.util.EmptyArray;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* @hide used in java.nio.
@@ -78,15 +70,25 @@ public class PlainDatagramSocketImpl extends DatagramSocketImpl {
}
@Override
+ protected void onBind(InetAddress localAddress, int localPort) {
+ this.localPort = localPort;
+ }
+
+ @Override
public synchronized void close() {
guard.close();
try {
- IoBridge.closeSocket(fd);
+ IoBridge.closeAndSignalBlockedThreads(fd);
} catch (IOException ignored) {
}
}
@Override
+ protected void onClose() {
+ guard.close();
+ }
+
+ @Override
public void create() throws SocketException {
this.fd = IoBridge.socket(false);
}
@@ -179,7 +181,8 @@ public class PlainDatagramSocketImpl extends DatagramSocketImpl {
public void send(DatagramPacket packet) throws IOException {
int port = isNativeConnected ? 0 : packet.getPort();
InetAddress address = isNativeConnected ? null : packet.getAddress();
- IoBridge.sendto(fd, packet.getData(), packet.getOffset(), packet.getLength(), 0, address, port);
+ IoBridge.sendto(fd, packet.getData(), packet.getOffset(), packet.getLength(), 0, address,
+ port);
}
public void setOption(int option, Object value) throws SocketException {
@@ -211,6 +214,13 @@ public class PlainDatagramSocketImpl extends DatagramSocketImpl {
}
@Override
+ protected void onConnect(InetAddress remoteAddress, int remotePort) {
+ isNativeConnected = true;
+ connectedAddress = remoteAddress;
+ connectedPort = remotePort;
+ }
+
+ @Override
public void disconnect() {
try {
Libcore.os.connect(fd, InetAddress.UNSPECIFIED, 0);
@@ -224,6 +234,13 @@ public class PlainDatagramSocketImpl extends DatagramSocketImpl {
isNativeConnected = false;
}
+ @Override
+ protected void onDisconnect() {
+ connectedPort = -1;
+ connectedAddress = null;
+ isNativeConnected = false;
+ }
+
/**
* Set the received address and port in the packet. We do this when the
* Datagram socket is connected at the native level and the
diff --git a/luni/src/main/java/java/net/PlainSocketImpl.java b/luni/src/main/java/java/net/PlainSocketImpl.java
index 18942d6..4e5ba44 100644
--- a/luni/src/main/java/java/net/PlainSocketImpl.java
+++ b/luni/src/main/java/java/net/PlainSocketImpl.java
@@ -17,28 +17,19 @@
package java.net;
+import android.system.ErrnoException;
import dalvik.system.CloseGuard;
import java.io.FileDescriptor;
-import java.io.IOException;
import java.io.InputStream;
+import java.io.IOException;
import java.io.OutputStream;
-import java.net.ConnectException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketImpl;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Arrays;
-import libcore.io.ErrnoException;
import libcore.io.IoBridge;
import libcore.io.Libcore;
import libcore.io.Memory;
import libcore.io.Streams;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* @hide used in java.nio.
@@ -120,15 +111,6 @@ public class PlainSocketImpl extends SocketImpl {
return proxy != null && proxy.type() == Proxy.Type.SOCKS;
}
- public void initLocalPort(int localPort) {
- this.localport = localPort;
- }
-
- public void initRemoteAddressAndPort(InetAddress remoteAddress, int remotePort) {
- this.address = remoteAddress;
- this.port = remotePort;
- }
-
private void checkNotClosed() throws IOException {
if (!fd.valid()) {
throw new SocketException("Socket is closed");
@@ -148,7 +130,6 @@ public class PlainSocketImpl extends SocketImpl {
@Override protected void bind(InetAddress address, int port) throws IOException {
IoBridge.bind(fd, address, port);
- this.address = address;
if (port != 0) {
this.localport = port;
} else {
@@ -157,9 +138,19 @@ public class PlainSocketImpl extends SocketImpl {
}
@Override
+ public void onBind(InetAddress localAddress, int localPort) {
+ localport = localPort;
+ }
+
+ @Override
protected synchronized void close() throws IOException {
guard.close();
- IoBridge.closeSocket(fd);
+ IoBridge.closeAndSignalBlockedThreads(fd);
+ }
+
+ @Override
+ public void onClose() {
+ guard.close();
}
@Override
@@ -191,8 +182,14 @@ public class PlainSocketImpl extends SocketImpl {
} else {
IoBridge.connect(fd, normalAddr, aPort, timeout);
}
- super.address = normalAddr;
- super.port = aPort;
+ address = normalAddr;
+ port = aPort;
+ }
+
+ @Override
+ public void onConnect(InetAddress remoteAddress, int remotePort) {
+ address = remoteAddress;
+ port = remotePort;
}
@Override
diff --git a/luni/src/main/java/java/net/ServerSocket.java b/luni/src/main/java/java/net/ServerSocket.java
index 399511f..72b197f 100644
--- a/luni/src/main/java/java/net/ServerSocket.java
+++ b/luni/src/main/java/java/net/ServerSocket.java
@@ -21,6 +21,8 @@ import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.ServerSocketChannel;
+import libcore.io.IoBridge;
+
/**
* This class represents a server-side socket that waits for incoming client
* connections. A {@code ServerSocket} handles the requests and sends back an
@@ -49,6 +51,8 @@ public class ServerSocket implements Closeable {
private boolean isClosed;
+ private InetAddress localAddress;
+
/**
* Constructs a new unbound {@code ServerSocket}.
*
@@ -99,7 +103,7 @@ public class ServerSocket implements Closeable {
impl.create(true);
try {
impl.bind(addr, port);
- isBound = true;
+ readBackBindState();
impl.listen(backlog > 0 ? backlog : DEFAULT_BACKLOG);
} catch (IOException e) {
close();
@@ -109,6 +113,14 @@ public class ServerSocket implements Closeable {
}
/**
+ * Read the cached isBound and localAddress state from the underlying OS socket.
+ */
+ private void readBackBindState() throws SocketException {
+ localAddress = IoBridge.getSocketLocalAddress(impl.fd);
+ isBound = true;
+ }
+
+ /**
* Waits for an incoming request and blocks until the connection is opened.
* This method returns a socket object representing the just opened
* connection.
@@ -152,8 +164,8 @@ public class ServerSocket implements Closeable {
}
/**
- * Gets the local IP address of this server socket or {@code null} if the
- * socket is unbound. This is useful for multihomed hosts.
+ * Gets the local IP address of this server socket if this socket has ever been bound,
+ * {@code null} otherwise. This is useful for multihomed hosts.
*
* @return the local address of this server socket.
*/
@@ -161,12 +173,13 @@ public class ServerSocket implements Closeable {
if (!isBound()) {
return null;
}
- return impl.getInetAddress();
+ return localAddress;
}
/**
- * Gets the local port of this server socket or {@code -1} if the socket is
- * unbound.
+ * Gets the local port of this server socket or {@code -1} if the socket is not bound.
+ * If the socket has ever been bound this method will return the local port it was bound to,
+ * even after it has been closed.
*
* @return the local port this server is listening on.
*/
@@ -300,9 +313,12 @@ public class ServerSocket implements Closeable {
if (isBound()) {
throw new BindException("Socket is already bound");
}
- int port = 0;
- InetAddress addr = Inet4Address.ANY;
- if (localAddr != null) {
+ InetAddress addr;
+ int port;
+ if (localAddr == null) {
+ addr = Inet4Address.ANY;
+ port = 0;
+ } else {
if (!(localAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Local address not an InetSocketAddress: " +
localAddr.getClass());
@@ -317,7 +333,7 @@ public class ServerSocket implements Closeable {
synchronized (this) {
try {
impl.bind(addr, port);
- isBound = true;
+ readBackBindState();
impl.listen(backlog > 0 ? backlog : DEFAULT_BACKLOG);
} catch (IOException e) {
close();
@@ -327,8 +343,9 @@ public class ServerSocket implements Closeable {
}
/**
- * Gets the local socket address of this server socket or {@code null} if
- * the socket is unbound. This is useful on multihomed hosts.
+ * Gets the local socket address of this server socket or {@code null} if the socket is unbound.
+ * This is useful on multihomed hosts. If the socket has ever been bound this method will return
+ * the local address it was bound to, even after it has been closed.
*
* @return the local socket address and port this socket is bound to.
*/
@@ -336,7 +353,7 @@ public class ServerSocket implements Closeable {
if (!isBound()) {
return null;
}
- return new InetSocketAddress(getInetAddress(), getLocalPort());
+ return new InetSocketAddress(localAddress, getLocalPort());
}
/**
diff --git a/luni/src/main/java/java/net/Socket.java b/luni/src/main/java/java/net/Socket.java
index 36fdf28..5dd350a 100644
--- a/luni/src/main/java/java/net/Socket.java
+++ b/luni/src/main/java/java/net/Socket.java
@@ -312,12 +312,29 @@ public class Socket implements Closeable {
*/
public synchronized void close() throws IOException {
isClosed = true;
- // RI compatibility: the RI returns the any address (but the original local port) after close.
+ isConnected = false;
+ // RI compatibility: the RI returns the any address (but the original local port) after
+ // close.
localAddress = Inet4Address.ANY;
impl.close();
}
/**
+ * Sets the Socket and its related SocketImpl state as if a successful close() took place,
+ * without actually performing an OS close().
+ *
+ * @hide used in java.nio
+ */
+ public void onClose() {
+ isClosed = true;
+ isConnected = false;
+ // RI compatibility: the RI returns the any address (but the original local port) after
+ // close.
+ localAddress = Inet4Address.ANY;
+ impl.onClose();
+ }
+
+ /**
* Returns the IP address of the target host this socket is connected to, or null if this
* socket is not yet connected.
*/
@@ -329,7 +346,9 @@ public class Socket implements Closeable {
}
/**
- * Returns an input stream to read data from this socket.
+ * Returns an input stream to read data from this socket. If the socket has an associated
+ * {@link SocketChannel} and that channel is in non-blocking mode then reads from the
+ * stream will throw a {@link java.nio.channels.IllegalBlockingModeException}.
*
* @return the byte-oriented input stream.
* @throws IOException
@@ -353,15 +372,16 @@ public class Socket implements Closeable {
}
/**
- * Returns the local IP address this socket is bound to, or {@code InetAddress.ANY} if
- * the socket is unbound.
+ * Returns the local IP address this socket is bound to, or an address for which
+ * {@link InetAddress#isAnyLocalAddress()} returns true if the socket is closed or unbound.
*/
public InetAddress getLocalAddress() {
return localAddress;
}
/**
- * Returns the local port this socket is bound to, or -1 if the socket is unbound.
+ * Returns the local port this socket is bound to, or -1 if the socket is unbound. If the socket
+ * has been closed this method will still return the local port the socket was bound to.
*/
public int getLocalPort() {
if (!isBound()) {
@@ -371,7 +391,9 @@ public class Socket implements Closeable {
}
/**
- * Returns an output stream to write data into this socket.
+ * Returns an output stream to write data into this socket. If the socket has an associated
+ * {@link SocketChannel} and that channel is in non-blocking mode then writes to the
+ * stream will throw a {@link java.nio.channels.IllegalBlockingModeException}.
*
* @return the byte-oriented output stream.
* @throws IOException
@@ -564,6 +586,7 @@ public class Socket implements Closeable {
impl.bind(addr, localPort);
}
isBound = true;
+ cacheLocalAddress();
impl.connect(dstAddress, dstPort);
isConnected = true;
cacheLocalAddress();
@@ -672,9 +695,10 @@ public class Socket implements Closeable {
}
/**
- * Returns the local address and port of this socket as a SocketAddress or
- * null if the socket is unbound. This is useful on multihomed
- * hosts.
+ * Returns the local address and port of this socket as a SocketAddress or null if the socket
+ * has never been bound. If the socket is closed but has previously been bound then an address
+ * for which {@link InetAddress#isAnyLocalAddress()} returns true will be returned with the
+ * previously-bound port. This is useful on multihomed hosts.
*/
public SocketAddress getLocalSocketAddress() {
if (!isBound()) {
@@ -744,9 +768,12 @@ public class Socket implements Closeable {
throw new BindException("Socket is already bound");
}
- int port = 0;
- InetAddress addr = Inet4Address.ANY;
- if (localAddr != null) {
+ int port;
+ InetAddress addr;
+ if (localAddr == null) {
+ port = 0;
+ addr = Inet4Address.ANY;
+ } else {
if (!(localAddr instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Local address not an InetSocketAddress: " +
localAddr.getClass());
@@ -771,6 +798,18 @@ public class Socket implements Closeable {
}
/**
+ * Sets the Socket and its related SocketImpl state as if a successful bind() took place,
+ * without actually performing an OS bind().
+ *
+ * @hide used in java.nio
+ */
+ public void onBind(InetAddress localAddress, int localPort) {
+ isBound = true;
+ this.localAddress = localAddress;
+ impl.onBind(localAddress, localPort);
+ }
+
+ /**
* Connects this socket to the given remote host address and port specified
* by the SocketAddress {@code remoteAddr}.
*
@@ -851,6 +890,17 @@ public class Socket implements Closeable {
}
/**
+ * Sets the Socket and its related SocketImpl state as if a successful connect() took place,
+ * without actually performing an OS connect().
+ *
+ * @hide internal use only
+ */
+ public void onConnect(InetAddress remoteAddress, int remotePort) {
+ isConnected = true;
+ impl.onConnect(remoteAddress, remotePort);
+ }
+
+ /**
* Returns whether the incoming channel of the socket has already been
* closed.
*
diff --git a/luni/src/main/java/java/net/SocketImpl.java b/luni/src/main/java/java/net/SocketImpl.java
index 92de9cf..bd36ec7 100644
--- a/luni/src/main/java/java/net/SocketImpl.java
+++ b/luni/src/main/java/java/net/SocketImpl.java
@@ -294,4 +294,31 @@ public abstract class SocketImpl implements SocketOptions {
*/
protected void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
}
+
+ /**
+ * Initialize the bind() state.
+ * @hide used in java.nio.
+ */
+ public void onBind(InetAddress localAddress, int localPort) {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
+
+ /**
+ * Initialize the connect() state.
+ * @hide used in java.nio.
+ */
+ public void onConnect(InetAddress remoteAddress, int remotePort) {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
+
+ /**
+ * Initialize the close() state.
+ * @hide used in java.nio.
+ */
+ public void onClose() {
+ // Do not add any code to these methods. They are concrete only to preserve API
+ // compatibility.
+ }
}
diff --git a/luni/src/main/java/java/net/SocketOptions.java b/luni/src/main/java/java/net/SocketOptions.java
index e23fc97..d0df689 100644
--- a/luni/src/main/java/java/net/SocketOptions.java
+++ b/luni/src/main/java/java/net/SocketOptions.java
@@ -28,19 +28,27 @@ package java.net;
*/
public interface SocketOptions {
/**
- * Number of seconds to wait when closing a socket if there
- * is still some buffered data to be sent.
+ * Number of seconds to wait when closing a socket if there is still some buffered data to be
+ * sent.
*
- * <p>If this option is set to 0, the TCP socket is closed forcefully and the
- * call to {@code close} returns immediately.
+ * <p>The option can be set to disabled using {@link #setOption(int, Object)} with a value of
+ * {@code Boolean.FALSE}.
*
- * <p>If this option is set to a value greater than 0, the value is interpreted
- * as the number of seconds to wait. If all data could be sent
- * during this time, the socket is closed normally. Otherwise the connection will be
- * closed forcefully.
+ * <p>If this option is set to 0, the TCP socket is closed forcefully and the call to
+ * {@code close} returns immediately.
*
- * <p>Valid values for this option are in the range 0 to 65535 inclusive. (Larger
+ * If this option is disabled, closing a socket will return immediately and the close will be
+ * handled in the background.
+ *
+ * <p>If this option is set to a value greater than 0, the value is interpreted as the number of
+ * seconds to wait. If all data could be sent during this time, the socket is closed normally.
+ * Otherwise the connection will be closed forcefully.
+ *
+ * <p>Valid numeric values for this option are in the range 0 to 65535 inclusive. (Larger
* timeouts will be treated as 65535s timeouts; roughly 18 hours.)
+ *
+ * <p>This option is intended for use with sockets in blocking mode. The behavior of this option
+ * for non-blocking sockets is undefined.
*/
public static final int SO_LINGER = 128;
@@ -54,16 +62,21 @@ public interface SocketOptions {
public static final int SO_TIMEOUT = 4102;
/**
- * This boolean option specifies whether data is sent immediately on this socket.
- * As a side-effect this could lead to low packet efficiency. The
- * socket implementation uses the Nagle's algorithm to try to reach a higher
- * packet efficiency if this option is disabled.
+ * This boolean option specifies whether data is sent immediately on this socket or buffered.
+ * <p>
+ * If set to {@code Boolean.TRUE} the Nagle algorithm is disabled and there is no buffering.
+ * This could lead to low packet efficiency. When set to {@code Boolean.FALSE} the the socket
+ * implementation uses buffering to try to reach a higher packet efficiency.
+ *
+ * <p>See <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122: Requirements for Internet
+ * Hosts -- Communication Layers</a> for more information about buffering and the Nagle
+ * algorithm.
*/
public static final int TCP_NODELAY = 1;
/**
* This is an IPv4-only socket option whose functionality is subsumed by
- * {@link #IP_MULTICAST_IF} and not implemented on Android.
+ * {@link #IP_MULTICAST_IF2} and not implemented on Android.
*/
public static final int IP_MULTICAST_IF = 16;
@@ -73,9 +86,18 @@ public interface SocketOptions {
public static final int SO_BINDADDR = 15;
/**
- * This boolean option specifies whether a reuse of a local address is allowed even
- * if another socket is not yet removed by the operating system. It's only
- * available on a {@code MulticastSocket}.
+ * This boolean option specifies whether a reuse of a local address is allowed when another
+ * socket has not yet been removed by the operating system.
+ *
+ * <p>For connection-oriented sockets, if this option is disabled and if there is another socket
+ * in state TIME_WAIT on a given address then another socket binding to that address would fail.
+ * Setting this value after a socket is bound has no effect.
+ *
+ * <p>For datagram sockets this option determines whether several sockets can listen on the
+ * same address; when enabled each socket will receive a copy of the datagram.
+ *
+ * <p>See <a href="https://www.ietf.org/rfc/rfc793.txt">RFC 793: Transmission Control Protocol
+ * </a> for more information about socket re-use.
*/
public static final int SO_REUSEADDR = 4;
@@ -93,11 +115,18 @@ public interface SocketOptions {
* This is a hint to the kernel; the kernel may use a larger buffer.
*
* <p>For datagram sockets, packets larger than this value will be discarded.
+ *
+ * <p>See <a href="http://www.ietf.org/rfc/rfc1323.txt">RFC1323: TCP Extensions for High
+ * Performance</a> for more information about TCP/IP buffering.
*/
public static final int SO_RCVBUF = 4098;
/**
- * This boolean option specifies whether the kernel sends keepalive messages.
+ * This boolean option specifies whether the kernel sends keepalive messages on
+ * connection-oriented sockets.
+ *
+ * <p>See <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122: Requirements for Internet
+ * Hosts -- Communication Layers</a> for more information on keep-alive.
*/
public static final int SO_KEEPALIVE = 8;
@@ -114,15 +143,18 @@ public interface SocketOptions {
/**
* This boolean option specifies whether the local loopback of multicast packets is
- * enabled or disabled. This option is enabled by default on multicast
- * sockets. Note that the sense of this option in Java is the
- * <i>opposite</i> of the underlying Unix {@code IP_MULTICAST_LOOP}.
- * See {@link MulticastSocket#setLoopbackMode}.
+ * enabled or disabled. This loopback is enabled by default on multicast sockets.
+ *
+ * <p>See <a href="http://tools.ietf.org/rfc/rfc1112.txt">RFC 1112: Host Extensions for IP
+ * Multicasting</a> for more information about IP multicast.
+ *
+ * <p>See {@link MulticastSocket#setLoopbackMode}.
*/
public static final int IP_MULTICAST_LOOP = 18;
/**
- * This boolean option can be used to enable broadcasting on datagram sockets.
+ * This boolean option can be used to enable or disable broadcasting on datagram sockets. This
+ * option must be enabled to send broadcast messages. The default value is false.
*/
public static final int SO_BROADCAST = 32;
@@ -135,6 +167,9 @@ public interface SocketOptions {
/**
* This integer option sets the outgoing interface for multicast packets
* using an interface index.
+ *
+ * <p>See <a href="http://tools.ietf.org/rfc/rfc1112.txt">RFC 1112: Host Extensions for IP
+ * Multicasting</a> for more information about IP multicast.
*/
public static final int IP_MULTICAST_IF2 = 31;
diff --git a/luni/src/main/java/java/net/URI.java b/luni/src/main/java/java/net/URI.java
index 6b7b1da..f206473 100644
--- a/luni/src/main/java/java/net/URI.java
+++ b/luni/src/main/java/java/net/URI.java
@@ -461,11 +461,14 @@ public final class URI implements Comparable<URI>, Serializable {
if (index < (temp.length() - 1)) { // port part is not empty
try {
- tempPort = Integer.parseInt(temp.substring(index + 1));
- if (tempPort < 0) {
+ char firstPortChar = temp.charAt(index + 1);
+ if (firstPortChar >= '0' && firstPortChar <= '9') {
+ // allow only digits, no signs
+ tempPort = Integer.parseInt(temp.substring(index + 1));
+ } else {
if (forceServer) {
throw new URISyntaxException(authority,
- "Invalid port number", hostIndex + index + 1);
+ "Invalid port number", hostIndex + index + 1);
}
return;
}
@@ -766,33 +769,51 @@ public final class URI implements Comparable<URI>, Serializable {
}
/**
- * Returns true if {@code first} and {@code second} are equal after
- * unescaping hex sequences like %F1 and %2b.
+ * Returns true if the given URI escaped strings {@code first} and {@code second} are
+ * equal.
+ *
+ * TODO: This method assumes that both strings are escaped using the same escape rules
+ * yet it still performs case insensitive comparison of the escaped sequences.
+ * Why is this necessary ? We can just replace it with first.equals(second)
+ * otherwise.
*/
private boolean escapedEquals(String first, String second) {
- if (first.indexOf('%') != second.indexOf('%')) {
- return first.equals(second);
+ // This length test isn't a micro-optimization. We need it because we sometimes
+ // calculate the number of characters to match based on the length of the second
+ // string. If the second string is shorter than the first, we might attempt to match
+ // 0 chars, and regionMatches is specified to return true in that case.
+ if (first.length() != second.length()) {
+ return false;
}
- int index, prevIndex = 0;
- while ((index = first.indexOf('%', prevIndex)) != -1
- && second.indexOf('%', prevIndex) == index) {
- boolean match = first.substring(prevIndex, index).equals(
- second.substring(prevIndex, index));
- if (!match) {
+ int prevIndex = 0;
+ while (true) {
+ int index = first.indexOf('%', prevIndex);
+ int index1 = second.indexOf('%', prevIndex);
+ if (index != index1) {
+ return false;
+ }
+
+ // index == index1 from this point on.
+
+ if (index == -1) {
+ // No more escapes, match the remainder of the string
+ // normally.
+ return first.regionMatches(prevIndex, second, prevIndex,
+ second.length() - prevIndex);
+ }
+
+ if (!first.regionMatches(prevIndex, second, prevIndex, (index - prevIndex))) {
return false;
}
- match = first.substring(index + 1, index + 3).equalsIgnoreCase(
- second.substring(index + 1, index + 3));
- if (!match) {
+ if (!first.regionMatches(true /* ignore case */, index + 1, second, index + 1, 2)) {
return false;
}
index += 3;
prevIndex = index;
}
- return first.substring(prevIndex).equals(second.substring(prevIndex));
}
@Override public boolean equals(Object o) {
diff --git a/luni/src/main/java/java/net/URLConnection.java b/luni/src/main/java/java/net/URLConnection.java
index 74c15ce..2fb3f45 100644
--- a/luni/src/main/java/java/net/URLConnection.java
+++ b/luni/src/main/java/java/net/URLConnection.java
@@ -308,9 +308,8 @@ public abstract class URLConnection {
/**
* Returns the content length in bytes specified by the response header field
- * {@code content-length} or {@code -1} if this field is not set.
- *
- * @return the value of the response header field {@code content-length}.
+ * {@code content-length} or {@code -1} if this field is not set or cannot be represented as an
+ * {@code int}.
*/
public int getContentLength() {
return getHeaderFieldInt("Content-Length", -1);
@@ -531,7 +530,7 @@ public abstract class URLConnection {
/**
* Returns the specified header value as a number. Returns the {@code
* defaultValue} if no such header field could be found or the value could
- * not be parsed as an {@code Integer}.
+ * not be parsed as an {@code int}.
*
* @param field
* the header field name whose value is needed.
diff --git a/luni/src/main/java/java/net/URLStreamHandler.java b/luni/src/main/java/java/net/URLStreamHandler.java
index 8a6c264..d21bb9c 100644
--- a/luni/src/main/java/java/net/URLStreamHandler.java
+++ b/luni/src/main/java/java/net/URLStreamHandler.java
@@ -131,9 +131,11 @@ public abstract class URLStreamHandler {
host = spec.substring(hostStart, hostEnd);
int portStart = hostEnd + 1;
if (portStart < fileStart) {
- port = Integer.parseInt(spec.substring(portStart, fileStart));
- if (port < 0) {
- throw new IllegalArgumentException("port < 0: " + port);
+ char firstPortChar = spec.charAt(portStart);
+ if (firstPortChar >= '0' && firstPortChar <= '9') {
+ port = Integer.parseInt(spec.substring(portStart, fileStart));
+ } else {
+ throw new IllegalArgumentException("invalid port: " + port);
}
}
path = null;
diff --git a/luni/src/main/java/java/nio/Buffer.java b/luni/src/main/java/java/nio/Buffer.java
index 9b7be52..53ad171 100644
--- a/luni/src/main/java/java/nio/Buffer.java
+++ b/luni/src/main/java/java/nio/Buffer.java
@@ -85,22 +85,16 @@ public abstract class Buffer {
/**
* For direct buffers, the effective address of the data; zero otherwise.
* This is set in the constructor.
- * TODO: make this final at the cost of loads of extra constructors? [how many?]
*/
- long effectiveDirectAddress;
+ final long effectiveDirectAddress;
- /**
- * For direct buffers, the underlying MemoryBlock; null otherwise.
- */
- final MemoryBlock block;
-
- Buffer(int elementSizeShift, int capacity, MemoryBlock block) {
+ Buffer(int elementSizeShift, int capacity, long effectiveDirectAddress) {
this._elementSizeShift = elementSizeShift;
if (capacity < 0) {
throw new IllegalArgumentException("capacity < 0: " + capacity);
}
this.capacity = this.limit = capacity;
- this.block = block;
+ this.effectiveDirectAddress = effectiveDirectAddress;
}
/**
@@ -296,7 +290,7 @@ public abstract class Buffer {
* the new limit, must not be negative and not greater than
* capacity.
* @return this buffer.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if <code>newLimit</code> is invalid.
*/
public final Buffer limit(int newLimit) {
@@ -344,7 +338,7 @@ public abstract class Buffer {
* the new position, must be not negative and not greater than
* limit.
* @return this buffer.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if <code>newPosition</code> is invalid.
*/
public final Buffer position(int newPosition) {
@@ -377,7 +371,7 @@ public abstract class Buffer {
* Resets the position of this buffer to the <code>mark</code>.
*
* @return this buffer.
- * @exception InvalidMarkException
+ * @throws InvalidMarkException
* if the mark is not set.
*/
public final Buffer reset() {
@@ -409,4 +403,9 @@ public abstract class Buffer {
return getClass().getName() +
"[position=" + position + ",limit=" + limit + ",capacity=" + capacity + "]";
}
+
+ /** @hide for testing only */
+ public final int getElementSizeShift() {
+ return _elementSizeShift;
+ }
}
diff --git a/luni/src/main/java/java/nio/ByteArrayBuffer.java b/luni/src/main/java/java/nio/ByteArrayBuffer.java
index e8d7ecc..6a273ed 100644
--- a/luni/src/main/java/java/nio/ByteArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ByteArrayBuffer.java
@@ -38,7 +38,7 @@ final class ByteArrayBuffer extends ByteBuffer {
}
private ByteArrayBuffer(int capacity, byte[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity, null);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/ByteBuffer.java b/luni/src/main/java/java/nio/ByteBuffer.java
index 456a309..61093fa 100644
--- a/luni/src/main/java/java/nio/ByteBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBuffer.java
@@ -69,7 +69,11 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
if (capacity < 0) {
throw new IllegalArgumentException("capacity < 0: " + capacity);
}
- return new DirectByteBuffer(MemoryBlock.allocate(capacity), capacity, 0, false, null);
+ // Ensure alignment by 8.
+ MemoryBlock memoryBlock = MemoryBlock.allocate(capacity + 7);
+ long address = memoryBlock.toLong();
+ long alignedAddress = (address + 7) & ~(long)7;
+ return new DirectByteBuffer(memoryBlock, capacity, (int)(alignedAddress - address), false, null);
}
/**
@@ -101,7 +105,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created byte buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code byteCount} is invalid.
*/
public static ByteBuffer wrap(byte[] array, int start, int byteCount) {
@@ -112,17 +116,17 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
return buf;
}
- ByteBuffer(int capacity, MemoryBlock block) {
- super(0, capacity, block);
+ ByteBuffer(int capacity, long effectiveDirectAddress) {
+ super(0, capacity, effectiveDirectAddress);
}
/**
* Returns the byte array which this buffer is based on, if there is one.
*
* @return the byte array which this buffer is based on.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if this buffer is based on a read-only array.
- * @exception UnsupportedOperationException
+ * @throws UnsupportedOperationException
* if this buffer is not based on an array.
*/
@Override public final byte[] array() {
@@ -137,9 +141,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* position of the buffer.
*
* @return the offset of the byte array which this buffer is based on.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if this buffer is based on a read-only array.
- * @exception UnsupportedOperationException
+ * @throws UnsupportedOperationException
* if this buffer is not based on an array.
*/
@Override public final int arrayOffset() {
@@ -260,7 +264,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* cleared.
*
* @return {@code this}
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer compact();
@@ -274,7 +278,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @return a negative value if this is less than {@code other}; 0 if this
* equals to {@code other}; a positive value if this is greater
* than {@code other}.
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code other} is not a byte buffer.
*/
@Override public int compareTo(ByteBuffer otherBuffer) {
@@ -350,7 +354,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* Returns the byte at the current position and increases the position by 1.
*
* @return the byte at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract byte get();
@@ -365,7 +369,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param dst
* the destination byte array.
* @return {@code this}
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public ByteBuffer get(byte[] dst) {
@@ -386,8 +390,8 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the number of bytes to read, must not be negative and not
* greater than {@code dst.length - dstOffset}
* @return {@code this}
- * @exception IndexOutOfBoundsException if {@code dstOffset < 0 || byteCount < 0}
- * @exception BufferUnderflowException if {@code byteCount > remaining()}
+ * @throws IndexOutOfBoundsException if {@code dstOffset < 0 || byteCount < 0}
+ * @throws BufferUnderflowException if {@code byteCount > remaining()}
*/
public ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
Arrays.checkOffsetAndCount(dst.length, dstOffset, byteCount);
@@ -406,7 +410,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param index
* the index, must not be negative and less than limit.
* @return the byte at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract byte get(int index);
@@ -418,7 +422,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* according to the current byte order and returned.
*
* @return the char at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is greater than {@code limit - 2}.
*/
public abstract char getChar();
@@ -434,7 +438,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the index, must not be negative and equal or less than
* {@code limit - 2}.
* @return the char at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
*/
public abstract char getChar(int index);
@@ -447,7 +451,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* according to the current byte order and returned.
*
* @return the double at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is greater than {@code limit - 8}.
*/
public abstract double getDouble();
@@ -463,7 +467,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the index, must not be negative and equal or less than
* {@code limit - 8}.
* @return the double at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
*/
public abstract double getDouble(int index);
@@ -476,7 +480,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* according to the current byte order and returned.
*
* @return the float at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is greater than {@code limit - 4}.
*/
public abstract float getFloat();
@@ -492,7 +496,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the index, must not be negative and equal or less than
* {@code limit - 4}.
* @return the float at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
*/
public abstract float getFloat(int index);
@@ -504,7 +508,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* according to the current byte order and returned.
*
* @return the int at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is greater than {@code limit - 4}.
*/
public abstract int getInt();
@@ -520,7 +524,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the index, must not be negative and equal or less than
* {@code limit - 4}.
* @return the int at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
*/
public abstract int getInt(int index);
@@ -532,7 +536,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* according to the current byte order and returned.
*
* @return the long at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is greater than {@code limit - 8}.
*/
public abstract long getLong();
@@ -548,7 +552,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the index, must not be negative and equal or less than
* {@code limit - 8}.
* @return the long at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
*/
public abstract long getLong(int index);
@@ -560,7 +564,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* according to the current byte order and returned.
*
* @return the short at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is greater than {@code limit - 2}.
*/
public abstract short getShort();
@@ -576,7 +580,7 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the index, must not be negative and equal or less than
* {@code limit - 2}.
* @return the short at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
*/
public abstract short getShort(int index);
@@ -609,6 +613,30 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
@Override public abstract boolean isDirect();
/**
+ * Indicates whether this buffer is still accessible.
+ *
+ * @return {@code true} if this buffer is accessible, {@code false} if the
+ * buffer was made inaccessible (e.g. freed) and should not be used.
+ * @hide
+ */
+ public boolean isAccessible() {
+ return true;
+ }
+
+ /**
+ * Sets buffer accessibility (only supported for direct byte buffers). If
+ * {@code accessible} is {@code false}, {@link #isAccessible} will return
+ * false, and any attempt to access the buffer will throw an exception. If
+ * {@code true}, the buffer will become useable again, unless it has been
+ * freed.
+ *
+ * @hide
+ */
+ public void setAccessible(boolean accessible) {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
* Returns the byte order used by this buffer when converting bytes from/to
* other primitive types.
* <p>
@@ -667,9 +695,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param b
* the byte to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer put(byte b);
@@ -684,9 +712,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param src
* the source byte array.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final ByteBuffer put(byte[] src) {
@@ -707,11 +735,11 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* the number of bytes to write, must not be negative and not
* greater than {@code src.length - srcOffset}.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code byteCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code byteCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
@@ -733,21 +761,27 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param src
* the source byte buffer.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public ByteBuffer put(ByteBuffer src) {
+ if (!isAccessible()) {
+ throw new IllegalStateException("buffer is inaccessible");
+ }
if (isReadOnly()) {
throw new ReadOnlyBufferException();
}
if (src == this) {
throw new IllegalArgumentException("src == this");
}
+ if (!src.isAccessible()) {
+ throw new IllegalStateException("src buffer is inaccessible");
+ }
int srcByteCount = src.remaining();
if (srcByteCount > remaining()) {
throw new BufferOverflowException();
@@ -782,9 +816,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param b
* the byte to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer put(int index, byte b);
@@ -798,9 +832,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the char to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is greater than {@code limit - 2}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putChar(char value);
@@ -817,9 +851,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the char to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putChar(int index, char value);
@@ -833,9 +867,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the double to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is greater than {@code limit - 8}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putDouble(double value);
@@ -852,9 +886,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the double to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putDouble(int index, double value);
@@ -868,9 +902,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the float to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is greater than {@code limit - 4}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putFloat(float value);
@@ -887,9 +921,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the float to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putFloat(int index, float value);
@@ -903,9 +937,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the int to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is greater than {@code limit - 4}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putInt(int value);
@@ -922,9 +956,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the int to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putInt(int index, int value);
@@ -938,9 +972,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the long to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is greater than {@code limit - 8}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putLong(long value);
@@ -957,9 +991,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the long to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putLong(int index, long value);
@@ -973,9 +1007,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the short to write.
* @return {@code this}
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is greater than {@code limit - 2}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putShort(short value);
@@ -992,9 +1026,9 @@ public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer
* @param value
* the short to write.
* @return {@code this}
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if {@code index} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ByteBuffer putShort(int index, short value);
diff --git a/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java b/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java
index 16d0688..9d06cce 100644
--- a/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java
@@ -42,10 +42,9 @@ final class ByteBufferAsCharBuffer extends CharBuffer {
}
private ByteBufferAsCharBuffer(ByteBuffer byteBuffer) {
- super(byteBuffer.capacity() / SizeOf.CHAR);
+ super(byteBuffer.capacity() / SizeOf.CHAR, byteBuffer.effectiveDirectAddress);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
diff --git a/luni/src/main/java/java/nio/ByteBufferAsDoubleBuffer.java b/luni/src/main/java/java/nio/ByteBufferAsDoubleBuffer.java
index 044bf59..8271daf 100644
--- a/luni/src/main/java/java/nio/ByteBufferAsDoubleBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBufferAsDoubleBuffer.java
@@ -42,10 +42,9 @@ final class ByteBufferAsDoubleBuffer extends DoubleBuffer {
}
private ByteBufferAsDoubleBuffer(ByteBuffer byteBuffer) {
- super(byteBuffer.capacity() / SizeOf.DOUBLE);
+ super(byteBuffer.capacity() / SizeOf.DOUBLE, byteBuffer.effectiveDirectAddress);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
diff --git a/luni/src/main/java/java/nio/ByteBufferAsFloatBuffer.java b/luni/src/main/java/java/nio/ByteBufferAsFloatBuffer.java
index a67affe..eaf2b8f 100644
--- a/luni/src/main/java/java/nio/ByteBufferAsFloatBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBufferAsFloatBuffer.java
@@ -41,10 +41,9 @@ final class ByteBufferAsFloatBuffer extends FloatBuffer {
}
ByteBufferAsFloatBuffer(ByteBuffer byteBuffer) {
- super(byteBuffer.capacity() / SizeOf.FLOAT);
+ super(byteBuffer.capacity() / SizeOf.FLOAT, byteBuffer.effectiveDirectAddress);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
diff --git a/luni/src/main/java/java/nio/ByteBufferAsIntBuffer.java b/luni/src/main/java/java/nio/ByteBufferAsIntBuffer.java
index a3211b8..f584f1a 100644
--- a/luni/src/main/java/java/nio/ByteBufferAsIntBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBufferAsIntBuffer.java
@@ -42,10 +42,9 @@ final class ByteBufferAsIntBuffer extends IntBuffer {
}
private ByteBufferAsIntBuffer(ByteBuffer byteBuffer) {
- super(byteBuffer.capacity() / SizeOf.INT);
+ super(byteBuffer.capacity() / SizeOf.INT, byteBuffer.effectiveDirectAddress);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
diff --git a/luni/src/main/java/java/nio/ByteBufferAsLongBuffer.java b/luni/src/main/java/java/nio/ByteBufferAsLongBuffer.java
index 550c675..8afa66e 100644
--- a/luni/src/main/java/java/nio/ByteBufferAsLongBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBufferAsLongBuffer.java
@@ -42,10 +42,9 @@ final class ByteBufferAsLongBuffer extends LongBuffer {
}
private ByteBufferAsLongBuffer(ByteBuffer byteBuffer) {
- super(byteBuffer.capacity() / SizeOf.LONG);
+ super(byteBuffer.capacity() / SizeOf.LONG, byteBuffer.effectiveDirectAddress);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
diff --git a/luni/src/main/java/java/nio/ByteBufferAsShortBuffer.java b/luni/src/main/java/java/nio/ByteBufferAsShortBuffer.java
index ff81409..52afc0e 100644
--- a/luni/src/main/java/java/nio/ByteBufferAsShortBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBufferAsShortBuffer.java
@@ -41,10 +41,9 @@ final class ByteBufferAsShortBuffer extends ShortBuffer {
}
private ByteBufferAsShortBuffer(ByteBuffer byteBuffer) {
- super(byteBuffer.capacity() / SizeOf.SHORT);
+ super(byteBuffer.capacity() / SizeOf.SHORT, byteBuffer.effectiveDirectAddress);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
diff --git a/luni/src/main/java/java/nio/CharArrayBuffer.java b/luni/src/main/java/java/nio/CharArrayBuffer.java
index 245a799..8f9fd9b 100644
--- a/luni/src/main/java/java/nio/CharArrayBuffer.java
+++ b/luni/src/main/java/java/nio/CharArrayBuffer.java
@@ -33,7 +33,7 @@ final class CharArrayBuffer extends CharBuffer {
}
private CharArrayBuffer(int capacity, char[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/CharBuffer.java b/luni/src/main/java/java/nio/CharBuffer.java
index 92cab01..748a787 100644
--- a/luni/src/main/java/java/nio/CharBuffer.java
+++ b/luni/src/main/java/java/nio/CharBuffer.java
@@ -83,7 +83,7 @@ public abstract class CharBuffer extends Buffer implements
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created char buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code charCount} is invalid.
*/
public static CharBuffer wrap(char[] array, int start, int charCount) {
@@ -124,7 +124,7 @@ public abstract class CharBuffer extends Buffer implements
* the end index, must be no less than {@code start} and no
* greater than {@code cs.length()}.
* @return the created char buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code end} is invalid.
*/
public static CharBuffer wrap(CharSequence cs, int start, int end) {
@@ -137,8 +137,8 @@ public abstract class CharBuffer extends Buffer implements
return result;
}
- CharBuffer(int capacity) {
- super(1, capacity, null);
+ CharBuffer(int capacity, long effectiveDirectAddress) {
+ super(1, capacity, effectiveDirectAddress);
}
public final char[] array() {
@@ -165,17 +165,8 @@ public abstract class CharBuffer extends Buffer implements
public abstract CharBuffer asReadOnlyBuffer();
/**
- * Returns the character located at the specified index in the buffer. The
- * index value is referenced from the current buffer position.
- *
- * @param index
- * the index referenced from the current buffer position. It must
- * not be less than zero but less than the value obtained from a
- * call to {@code remaining()}.
- * @return the character located at the specified index (referenced from the
- * current position) in the buffer.
- * @exception IndexOutOfBoundsException
- * if the index is invalid.
+ * Returns the character located at the given offset <i>relative to the current position</i>.
+ * @throws IndexOutOfBoundsException if {@code index < 0} or {@code index >= remaining()}.
*/
public final char charAt(int index) {
if (index < 0 || index >= remaining()) {
@@ -192,7 +183,7 @@ public abstract class CharBuffer extends Buffer implements
* {@code remaining()}; the limit is set to capacity; the mark is cleared.
*
* @return this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract CharBuffer compact();
@@ -206,7 +197,7 @@ public abstract class CharBuffer extends Buffer implements
* @return a negative value if this is less than {@code otherBuffer}; 0 if
* this equals to {@code otherBuffer}; a positive value if this is
* greater than {@code otherBuffer}.
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code otherBuffer} is not a char buffer.
*/
public int compareTo(CharBuffer otherBuffer) {
@@ -278,7 +269,7 @@ public abstract class CharBuffer extends Buffer implements
* Returns the char at the current position and increases the position by 1.
*
* @return the char at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract char get();
@@ -293,7 +284,7 @@ public abstract class CharBuffer extends Buffer implements
* @param dst
* the destination char array.
* @return this buffer.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public CharBuffer get(char[] dst) {
@@ -314,9 +305,9 @@ public abstract class CharBuffer extends Buffer implements
* The number of chars to read, must be no less than zero and no
* greater than {@code dst.length - dstOffset}.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code dstOffset} or {@code charCount} is invalid.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code charCount} is greater than {@code remaining()}.
*/
public CharBuffer get(char[] dst, int dstOffset, int charCount) {
@@ -336,7 +327,7 @@ public abstract class CharBuffer extends Buffer implements
* @param index
* the index, must not be negative and less than limit.
* @return a char at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract char get(int index);
@@ -422,9 +413,9 @@ public abstract class CharBuffer extends Buffer implements
* @param c
* the char to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract CharBuffer put(char c);
@@ -439,9 +430,9 @@ public abstract class CharBuffer extends Buffer implements
* @param src
* the source char array.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final CharBuffer put(char[] src) {
@@ -462,11 +453,11 @@ public abstract class CharBuffer extends Buffer implements
* the number of chars to write, must be no less than zero and no
* greater than {@code src.length - srcOffset}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code charCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code charCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public CharBuffer put(char[] src, int srcOffset, int charCount) {
@@ -488,12 +479,12 @@ public abstract class CharBuffer extends Buffer implements
* @param src
* the source char buffer.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public CharBuffer put(CharBuffer src) {
@@ -522,9 +513,9 @@ public abstract class CharBuffer extends Buffer implements
* @param c
* the char to write.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract CharBuffer put(int index, char c);
@@ -539,9 +530,9 @@ public abstract class CharBuffer extends Buffer implements
* @param str
* the string to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than the length of string.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final CharBuffer put(String str) {
@@ -561,11 +552,11 @@ public abstract class CharBuffer extends Buffer implements
* the last char to write (excluding), must be less than
* {@code start} and not greater than {@code str.length()}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code end - start}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code end} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public CharBuffer put(String str, int start, int end) {
@@ -625,7 +616,7 @@ public abstract class CharBuffer extends Buffer implements
* {@code remaining()}.
* @return a new char buffer represents a sub-sequence of this buffer's
* current remaining content.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code end} is invalid.
*/
public abstract CharBuffer subSequence(int start, int end);
@@ -649,9 +640,9 @@ public abstract class CharBuffer extends Buffer implements
* @param c
* the char to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public CharBuffer append(char c) {
@@ -670,9 +661,9 @@ public abstract class CharBuffer extends Buffer implements
* @param csq
* the {@code CharSequence} to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than the length of csq.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public CharBuffer append(CharSequence csq) {
@@ -695,11 +686,11 @@ public abstract class CharBuffer extends Buffer implements
* the last char to write (excluding), must be less than
* {@code start} and not greater than {@code csq.length()}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code end - start}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code end} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public CharBuffer append(CharSequence csq, int start, int end) {
diff --git a/luni/src/main/java/java/nio/CharSequenceAdapter.java b/luni/src/main/java/java/nio/CharSequenceAdapter.java
index f686827..fb8a0f1 100644
--- a/luni/src/main/java/java/nio/CharSequenceAdapter.java
+++ b/luni/src/main/java/java/nio/CharSequenceAdapter.java
@@ -42,7 +42,7 @@ final class CharSequenceAdapter extends CharBuffer {
final CharSequence sequence;
CharSequenceAdapter(CharSequence chseq) {
- super(chseq.length());
+ super(chseq.length(), 0);
sequence = chseq;
}
diff --git a/luni/src/main/java/java/nio/DatagramChannelImpl.java b/luni/src/main/java/java/nio/DatagramChannelImpl.java
index 39f2128..9008637 100644
--- a/luni/src/main/java/java/nio/DatagramChannelImpl.java
+++ b/luni/src/main/java/java/nio/DatagramChannelImpl.java
@@ -17,15 +17,18 @@
package java.nio;
+import android.system.ErrnoException;
import java.io.FileDescriptor;
-import java.io.IOException;
import java.io.InterruptedIOException;
+import java.io.IOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.DatagramSocketImpl;
+import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
import java.net.PlainDatagramSocketImpl;
import java.net.SocketAddress;
import java.net.SocketException;
@@ -35,8 +38,10 @@ import java.nio.channels.DatagramChannel;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.spi.SelectorProvider;
+import java.nio.channels.UnresolvedAddressException;
+import java.nio.channels.UnsupportedAddressTypeException;
import java.util.Arrays;
-import libcore.io.ErrnoException;
+import java.util.Set;
import libcore.io.IoBridge;
import libcore.io.IoUtils;
import libcore.io.Libcore;
@@ -50,10 +55,13 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
private final FileDescriptor fd;
// Our internal DatagramSocket.
- private DatagramSocket socket = null;
+ private DatagramSocket socket;
+
+ // The remote address to be connected.
+ InetSocketAddress connectAddress;
- // The address to be connected.
- InetSocketAddress connectAddress = null;
+ // The local address.
+ InetAddress localAddress;
// local port
private int localPort;
@@ -98,19 +106,38 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
}
/**
- * @see java.nio.channels.DatagramChannel#isConnected()
+ * Initialise the isBound, localAddress and localPort state from the file descriptor. Used when
+ * some or all of the bound state has been left to the OS to decide, or when the Socket handled
+ * bind() or connect().
+ *
+ * @param updateSocketState
+ * if the associated socket (if present) needs to be updated
+ * @hide used to sync state, non-private to avoid synthetic method
*/
+ void onBind(boolean updateSocketState) {
+ SocketAddress sa;
+ try {
+ sa = Libcore.os.getsockname(fd);
+ } catch (ErrnoException errnoException) {
+ throw new AssertionError(errnoException);
+ }
+ isBound = true;
+ InetSocketAddress localSocketAddress = (InetSocketAddress) sa;
+ localAddress = localSocketAddress.getAddress();
+ localPort = localSocketAddress.getPort();
+ if (updateSocketState && socket != null) {
+ socket.onBind(localAddress, localPort);
+ }
+ }
+
@Override
synchronized public boolean isConnected() {
return connected;
}
- /**
- * @see java.nio.channels.DatagramChannel#connect(java.net.SocketAddress)
- */
@Override
synchronized public DatagramChannel connect(SocketAddress address) throws IOException {
- // must open
+ // must be open
checkOpen();
// status must be un-connected.
if (connected) {
@@ -119,43 +146,71 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
// check the address
InetSocketAddress inetSocketAddress = SocketChannelImpl.validateAddress(address);
+ InetAddress remoteAddress = inetSocketAddress.getAddress();
+ int remotePort = inetSocketAddress.getPort();
try {
begin();
- IoBridge.connect(fd, inetSocketAddress.getAddress(), inetSocketAddress.getPort());
+ IoBridge.connect(fd, remoteAddress, remotePort);
} catch (ConnectException e) {
// ConnectException means connect fail, not exception
} finally {
end(true);
}
- // set the connected address.
- connectAddress = inetSocketAddress;
- connected = true;
- isBound = true;
+ // connect() performs a bind() if an explicit bind() was not performed. Keep the local
+ // address state held by the channel and the socket up to date.
+ if (!isBound) {
+ onBind(true /* updateSocketState */);
+ }
+
+ // Keep the connected state held by the channel and the socket up to date.
+ onConnect(remoteAddress, remotePort, true /* updateSocketState */);
return this;
}
/**
- * @see java.nio.channels.DatagramChannel#disconnect()
+ * Initialize the state associated with being connected, optionally syncing the socket if there
+ * is one.
+ * @hide used to sync state, non-private to avoid synthetic method
*/
+ void onConnect(InetAddress remoteAddress, int remotePort, boolean updateSocketState) {
+ connected = true;
+ connectAddress = new InetSocketAddress(remoteAddress, remotePort);
+ if (updateSocketState && socket != null) {
+ socket.onConnect(remoteAddress, remotePort);
+ }
+ }
+
@Override
synchronized public DatagramChannel disconnect() throws IOException {
if (!isConnected() || !isOpen()) {
return this;
}
- connected = false;
- connectAddress = null;
+
+ // Keep the disconnected state held by the channel and the socket up to date.
+ onDisconnect(true /* updateSocketState */);
+
try {
Libcore.os.connect(fd, InetAddress.UNSPECIFIED, 0);
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsIOException();
}
- if (socket != null) {
- socket.disconnect();
- }
return this;
}
+ /**
+ * Initialize the state associated with being disconnected, optionally syncing the socket if
+ * there is one.
+ * @hide used to sync state, non-private to avoid synthetic method
+ */
+ void onDisconnect(boolean updateSocketState) {
+ connected = false;
+ connectAddress = null;
+ if (updateSocketState && socket != null && socket.isConnected()) {
+ socket.onDisconnect();
+ }
+ }
+
@Override
public SocketAddress receive(ByteBuffer target) throws IOException {
target.checkWritable();
@@ -191,7 +246,7 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
SocketAddress retAddr = null;
DatagramPacket receivePacket;
int oldposition = target.position();
- int received = 0;
+ int received;
// TODO: disallow mapped buffers and lose this conditional?
if (target.hasArray()) {
receivePacket = new DatagramPacket(target.array(), target.position() + target.arrayOffset(), target.remaining());
@@ -200,7 +255,7 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
}
do {
received = IoBridge.recvfrom(false, fd, receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength(), 0, receivePacket, isConnected());
- if (receivePacket != null && receivePacket.getAddress() != null) {
+ if (receivePacket.getAddress() != null) {
if (received > 0) {
if (target.hasArray()) {
target.position(oldposition + received);
@@ -220,10 +275,10 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
SocketAddress retAddr = null;
DatagramPacket receivePacket = new DatagramPacket(EmptyArray.BYTE, 0);
int oldposition = target.position();
- int received = 0;
+ int received;
do {
received = IoBridge.recvfrom(false, fd, target, 0, receivePacket, isConnected());
- if (receivePacket != null && receivePacket.getAddress() != null) {
+ if (receivePacket.getAddress() != null) {
// copy the data of received packet
if (received > 0) {
target.position(oldposition + received);
@@ -259,7 +314,9 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
if (sendCount > 0) {
source.position(oldPosition + sendCount);
}
- isBound = true;
+ if (!isBound) {
+ onBind(true /* updateSocketState */);
+ }
} finally {
end(sendCount >= 0);
}
@@ -276,7 +333,7 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
return 0;
}
- int readCount = 0;
+ int readCount;
if (target.isDirect() || target.hasArray()) {
readCount = readImpl(target);
if (readCount > 0) {
@@ -405,11 +462,12 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
}
@Override protected synchronized void implCloseSelectableChannel() throws IOException {
- connected = false;
+ // A closed channel is not connected.
+ onDisconnect(true /* updateSocketState */);
+ IoBridge.closeAndSignalBlockedThreads(fd);
+
if (socket != null && !socket.isClosed()) {
- socket.close();
- } else {
- IoBridge.closeSocket(fd);
+ socket.onClose();
}
}
@@ -420,7 +478,7 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
/*
* Status check, must be open.
*/
- private void checkOpen() throws IOException {
+ private void checkOpen() throws ClosedChannelException {
if (!isOpen()) {
throw new ClosedChannelException();
}
@@ -460,15 +518,29 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
/*
* The internal datagramChannelImpl.
*/
- private DatagramChannelImpl channelImpl;
+ private final DatagramChannelImpl channelImpl;
/*
* Constructor initialize the datagramSocketImpl and datagramChannelImpl
*/
- DatagramSocketAdapter(DatagramSocketImpl socketimpl,
- DatagramChannelImpl channelImpl) {
+ DatagramSocketAdapter(DatagramSocketImpl socketimpl, DatagramChannelImpl channelImpl) {
super(socketimpl);
this.channelImpl = channelImpl;
+
+ // Sync state socket state with the channel it is being created from
+ if (channelImpl.isBound) {
+ onBind(channelImpl.localAddress, channelImpl.localPort);
+ }
+ if (channelImpl.connected) {
+ onConnect(
+ channelImpl.connectAddress.getAddress(),
+ channelImpl.connectAddress.getPort());
+ } else {
+ onDisconnect();
+ }
+ if (!channelImpl.isOpen()) {
+ onClose();
+ }
}
/*
@@ -479,92 +551,78 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
return channelImpl;
}
- /**
- * @see java.net.DatagramSocket#isBound()
- */
- @Override
- public boolean isBound() {
- return channelImpl.isBound;
- }
-
- /**
- * @see java.net.DatagramSocket#isConnected()
- */
- @Override
- public boolean isConnected() {
- return channelImpl.isConnected();
- }
-
- /**
- * @see java.net.DatagramSocket#getInetAddress()
- */
@Override
- public InetAddress getInetAddress() {
- if (channelImpl.connectAddress == null) {
- return null;
- }
- return channelImpl.connectAddress.getAddress();
- }
-
- @Override public InetAddress getLocalAddress() {
- try {
- return IoBridge.getSocketLocalAddress(channelImpl.fd);
- } catch (SocketException ex) {
- return null;
+ public void bind(SocketAddress localAddr) throws SocketException {
+ if (channelImpl.isConnected()) {
+ throw new AlreadyConnectedException();
}
+ super.bind(localAddr);
+ channelImpl.onBind(false /* updateSocketState */);
}
- /**
- * @see java.net.DatagramSocket#getPort()
- */
@Override
- public int getPort() {
- if (channelImpl.connectAddress == null) {
- return -1;
+ public void connect(SocketAddress peer) throws SocketException {
+ if (isConnected()) {
+ // RI compatibility: If the socket is already connected this fails.
+ throw new IllegalStateException("Socket is already connected.");
}
- return channelImpl.connectAddress.getPort();
+ super.connect(peer);
+ // Connect may have performed an implicit bind(). Sync up here.
+ channelImpl.onBind(false /* updateSocketState */);
+
+ InetSocketAddress inetSocketAddress = (InetSocketAddress) peer;
+ channelImpl.onConnect(
+ inetSocketAddress.getAddress(), inetSocketAddress.getPort(),
+ false /* updateSocketState */);
}
- /**
- * @see java.net.DatagramSocket#bind(java.net.SocketAddress)
- */
@Override
- public void bind(SocketAddress localAddr) throws SocketException {
- if (channelImpl.isConnected()) {
- throw new AlreadyConnectedException();
+ public void connect(InetAddress address, int port) {
+ // To avoid implementing connect() twice call this.connect(SocketAddress) in preference
+ // to super.connect().
+ try {
+ connect(new InetSocketAddress(address, port));
+ } catch (SocketException e) {
+ // Ignored - there is nothing we can report here.
}
- super.bind(localAddr);
- channelImpl.isBound = true;
}
- /**
- * @see java.net.DatagramSocket#receive(java.net.DatagramPacket)
- */
@Override
public void receive(DatagramPacket packet) throws IOException {
if (!channelImpl.isBlocking()) {
throw new IllegalBlockingModeException();
}
+
+ boolean wasBound = isBound();
super.receive(packet);
+ if (!wasBound) {
+ // DatagramSocket.receive() will implicitly bind if it hasn't been done explicitly.
+ // Sync the channel state with the socket.
+ channelImpl.onBind(false /* updateSocketState */);
+ }
}
- /**
- * @see java.net.DatagramSocket#send(java.net.DatagramPacket)
- */
@Override
public void send(DatagramPacket packet) throws IOException {
if (!channelImpl.isBlocking()) {
throw new IllegalBlockingModeException();
}
+
+ // DatagramSocket.send() will implicitly bind if it hasn't been done explicitly. Force
+ // bind() here so that the channel state stays in sync with the socket.
+ boolean wasBound = isBound();
super.send(packet);
+ if (!wasBound) {
+ // DatagramSocket.send() will implicitly bind if it hasn't been done explicitly.
+ // Sync the channel state with the socket.
+ channelImpl.onBind(false /* updateSocketState */);
+ }
}
- /**
- * @see java.net.DatagramSocket#close()
- */
@Override
public void close() {
synchronized (channelImpl) {
+ super.close();
if (channelImpl.isOpen()) {
try {
channelImpl.close();
@@ -572,21 +630,13 @@ class DatagramChannelImpl extends DatagramChannel implements FileDescriptorChann
// Ignore
}
}
- super.close();
}
}
- /**
- * @see java.net.DatagramSocket#disconnect()
- */
@Override
public void disconnect() {
- try {
- channelImpl.disconnect();
- } catch (IOException e) {
- // Ignore
- }
super.disconnect();
+ channelImpl.onDisconnect(false /* updateSocketState */);
}
}
}
diff --git a/luni/src/main/java/java/nio/DirectByteBuffer.java b/luni/src/main/java/java/nio/DirectByteBuffer.java
index 1d12f2e..f19fb42 100644
--- a/luni/src/main/java/java/nio/DirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/DirectByteBuffer.java
@@ -30,15 +30,16 @@ class DirectByteBuffer extends MappedByteBuffer {
private final boolean isReadOnly;
protected DirectByteBuffer(MemoryBlock block, int capacity, int offset, boolean isReadOnly, MapMode mapMode) {
- super(block, capacity, mapMode);
+ super(block, capacity, mapMode, block.toLong() + offset);
long baseSize = block.getSize();
+ // We're throwing this exception after we passed a bogus value
+ // to the superclass constructor, but it doesn't make any
+ // difference in this case.
if (baseSize >= 0 && (capacity + offset) > baseSize) {
throw new IllegalArgumentException("capacity + offset > baseSize");
}
- this.effectiveDirectAddress = block.toLong() + offset;
-
this.offset = offset;
this.isReadOnly = isReadOnly;
}
@@ -49,6 +50,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
private static DirectByteBuffer copy(DirectByteBuffer other, int markOfOther, boolean isReadOnly) {
+ other.checkNotFreed();
DirectByteBuffer buf = new DirectByteBuffer(other.block, other.capacity(), other.offset, isReadOnly, other.mapMode);
buf.limit = other.limit;
buf.position = other.position();
@@ -61,6 +63,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer compact() {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -76,6 +79,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer slice() {
+ checkNotFreed();
return new DirectByteBuffer(block, remaining(), offset + position, isReadOnly, mapMode);
}
@@ -84,6 +88,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override byte[] protectedArray() {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -104,6 +109,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
+ checkIsAccessible();
checkGetBounds(1, dst.length, dstOffset, byteCount);
this.block.peekByteArray(offset + position, dst, dstOffset, byteCount);
position += byteCount;
@@ -111,42 +117,49 @@ class DirectByteBuffer extends MappedByteBuffer {
}
final void get(char[] dst, int dstOffset, int charCount) {
+ checkIsAccessible();
int byteCount = checkGetBounds(SizeOf.CHAR, dst.length, dstOffset, charCount);
this.block.peekCharArray(offset + position, dst, dstOffset, charCount, order.needsSwap);
position += byteCount;
}
final void get(double[] dst, int dstOffset, int doubleCount) {
+ checkIsAccessible();
int byteCount = checkGetBounds(SizeOf.DOUBLE, dst.length, dstOffset, doubleCount);
this.block.peekDoubleArray(offset + position, dst, dstOffset, doubleCount, order.needsSwap);
position += byteCount;
}
final void get(float[] dst, int dstOffset, int floatCount) {
+ checkIsAccessible();
int byteCount = checkGetBounds(SizeOf.FLOAT, dst.length, dstOffset, floatCount);
this.block.peekFloatArray(offset + position, dst, dstOffset, floatCount, order.needsSwap);
position += byteCount;
}
final void get(int[] dst, int dstOffset, int intCount) {
+ checkIsAccessible();
int byteCount = checkGetBounds(SizeOf.INT, dst.length, dstOffset, intCount);
this.block.peekIntArray(offset + position, dst, dstOffset, intCount, order.needsSwap);
position += byteCount;
}
final void get(long[] dst, int dstOffset, int longCount) {
+ checkIsAccessible();
int byteCount = checkGetBounds(SizeOf.LONG, dst.length, dstOffset, longCount);
this.block.peekLongArray(offset + position, dst, dstOffset, longCount, order.needsSwap);
position += byteCount;
}
final void get(short[] dst, int dstOffset, int shortCount) {
+ checkIsAccessible();
int byteCount = checkGetBounds(SizeOf.SHORT, dst.length, dstOffset, shortCount);
this.block.peekShortArray(offset + position, dst, dstOffset, shortCount, order.needsSwap);
position += byteCount;
}
@Override public final byte get() {
+ checkIsAccessible();
if (position == limit) {
throw new BufferUnderflowException();
}
@@ -154,11 +167,13 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final byte get(int index) {
+ checkIsAccessible();
checkIndex(index);
return this.block.peekByte(offset + index);
}
@Override public final char getChar() {
+ checkIsAccessible();
int newPosition = position + SizeOf.CHAR;
if (newPosition > limit) {
throw new BufferUnderflowException();
@@ -169,11 +184,13 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final char getChar(int index) {
+ checkIsAccessible();
checkIndex(index, SizeOf.CHAR);
return (char) this.block.peekShort(offset + index, order);
}
@Override public final double getDouble() {
+ checkIsAccessible();
int newPosition = position + SizeOf.DOUBLE;
if (newPosition > limit) {
throw new BufferUnderflowException();
@@ -184,11 +201,13 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final double getDouble(int index) {
+ checkIsAccessible();
checkIndex(index, SizeOf.DOUBLE);
return Double.longBitsToDouble(this.block.peekLong(offset + index, order));
}
@Override public final float getFloat() {
+ checkIsAccessible();
int newPosition = position + SizeOf.FLOAT;
if (newPosition > limit) {
throw new BufferUnderflowException();
@@ -199,11 +218,13 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final float getFloat(int index) {
+ checkIsAccessible();
checkIndex(index, SizeOf.FLOAT);
return Float.intBitsToFloat(this.block.peekInt(offset + index, order));
}
@Override public final int getInt() {
+ checkIsAccessible();
int newPosition = position + SizeOf.INT;
if (newPosition > limit) {
throw new BufferUnderflowException();
@@ -214,11 +235,13 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final int getInt(int index) {
+ checkIsAccessible();
checkIndex(index, SizeOf.INT);
return this.block.peekInt(offset + index, order);
}
@Override public final long getLong() {
+ checkIsAccessible();
int newPosition = position + SizeOf.LONG;
if (newPosition > limit) {
throw new BufferUnderflowException();
@@ -229,11 +252,13 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final long getLong(int index) {
+ checkIsAccessible();
checkIndex(index, SizeOf.LONG);
return this.block.peekLong(offset + index, order);
}
@Override public final short getShort() {
+ checkIsAccessible();
int newPosition = position + SizeOf.SHORT;
if (newPosition > limit) {
throw new BufferUnderflowException();
@@ -244,6 +269,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public final short getShort(int index) {
+ checkIsAccessible();
checkIndex(index, SizeOf.SHORT);
return this.block.peekShort(offset + index, order);
}
@@ -252,35 +278,56 @@ class DirectByteBuffer extends MappedByteBuffer {
return true;
}
+ /** @hide */
+ @Override public final boolean isAccessible() {
+ return block.isAccessible();
+ }
+
+ /** @hide */
+ @Override public void setAccessible(boolean accessible) {
+ block.setAccessible(accessible);
+ }
+
+ /**
+ * Invalidates the buffer. Subsequent operations which touch the inner
+ * buffer will throw {@link IllegalStateException}.
+ */
public final void free() {
block.free();
}
@Override public final CharBuffer asCharBuffer() {
+ checkNotFreed();
return ByteBufferAsCharBuffer.asCharBuffer(this);
}
@Override public final DoubleBuffer asDoubleBuffer() {
+ checkNotFreed();
return ByteBufferAsDoubleBuffer.asDoubleBuffer(this);
}
@Override public final FloatBuffer asFloatBuffer() {
+ checkNotFreed();
return ByteBufferAsFloatBuffer.asFloatBuffer(this);
}
@Override public final IntBuffer asIntBuffer() {
+ checkNotFreed();
return ByteBufferAsIntBuffer.asIntBuffer(this);
}
@Override public final LongBuffer asLongBuffer() {
+ checkNotFreed();
return ByteBufferAsLongBuffer.asLongBuffer(this);
}
@Override public final ShortBuffer asShortBuffer() {
+ checkNotFreed();
return ByteBufferAsShortBuffer.asShortBuffer(this);
}
@Override public ByteBuffer put(byte value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -292,6 +339,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer put(int index, byte value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -301,6 +349,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -311,42 +360,49 @@ class DirectByteBuffer extends MappedByteBuffer {
}
final void put(char[] src, int srcOffset, int charCount) {
+ checkIsAccessible();
int byteCount = checkPutBounds(SizeOf.CHAR, src.length, srcOffset, charCount);
this.block.pokeCharArray(offset + position, src, srcOffset, charCount, order.needsSwap);
position += byteCount;
}
final void put(double[] src, int srcOffset, int doubleCount) {
+ checkIsAccessible();
int byteCount = checkPutBounds(SizeOf.DOUBLE, src.length, srcOffset, doubleCount);
this.block.pokeDoubleArray(offset + position, src, srcOffset, doubleCount, order.needsSwap);
position += byteCount;
}
final void put(float[] src, int srcOffset, int floatCount) {
+ checkIsAccessible();
int byteCount = checkPutBounds(SizeOf.FLOAT, src.length, srcOffset, floatCount);
this.block.pokeFloatArray(offset + position, src, srcOffset, floatCount, order.needsSwap);
position += byteCount;
}
final void put(int[] src, int srcOffset, int intCount) {
+ checkIsAccessible();
int byteCount = checkPutBounds(SizeOf.INT, src.length, srcOffset, intCount);
this.block.pokeIntArray(offset + position, src, srcOffset, intCount, order.needsSwap);
position += byteCount;
}
final void put(long[] src, int srcOffset, int longCount) {
+ checkIsAccessible();
int byteCount = checkPutBounds(SizeOf.LONG, src.length, srcOffset, longCount);
this.block.pokeLongArray(offset + position, src, srcOffset, longCount, order.needsSwap);
position += byteCount;
}
final void put(short[] src, int srcOffset, int shortCount) {
+ checkIsAccessible();
int byteCount = checkPutBounds(SizeOf.SHORT, src.length, srcOffset, shortCount);
this.block.pokeShortArray(offset + position, src, srcOffset, shortCount, order.needsSwap);
position += byteCount;
}
@Override public ByteBuffer putChar(char value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -360,6 +416,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putChar(int index, char value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -369,6 +426,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putDouble(double value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -382,6 +440,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putDouble(int index, double value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -391,6 +450,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putFloat(float value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -404,6 +464,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putFloat(int index, float value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -413,6 +474,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putInt(int value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -426,6 +488,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putInt(int index, int value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -435,6 +498,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putLong(long value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -448,6 +512,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putLong(int index, long value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -457,6 +522,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putShort(short value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -470,6 +536,7 @@ class DirectByteBuffer extends MappedByteBuffer {
}
@Override public ByteBuffer putShort(int index, short value) {
+ checkIsAccessible();
if (isReadOnly) {
throw new ReadOnlyBufferException();
}
@@ -477,4 +544,18 @@ class DirectByteBuffer extends MappedByteBuffer {
this.block.pokeShort(offset + index, value, order);
return this;
}
+
+ private void checkIsAccessible() {
+ checkNotFreed();
+ if (!block.isAccessible()) {
+ throw new IllegalStateException("buffer is inaccessible");
+ }
+ }
+
+ private void checkNotFreed() {
+ if (block.isFreed()) {
+ throw new IllegalStateException("buffer was freed");
+ }
+ }
+
}
diff --git a/luni/src/main/java/java/nio/DoubleArrayBuffer.java b/luni/src/main/java/java/nio/DoubleArrayBuffer.java
index f8e4e59..a2d9e79 100644
--- a/luni/src/main/java/java/nio/DoubleArrayBuffer.java
+++ b/luni/src/main/java/java/nio/DoubleArrayBuffer.java
@@ -33,7 +33,7 @@ final class DoubleArrayBuffer extends DoubleBuffer {
}
private DoubleArrayBuffer(int capacity, double[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/DoubleBuffer.java b/luni/src/main/java/java/nio/DoubleBuffer.java
index 2fa74d2..f3062fb 100644
--- a/luni/src/main/java/java/nio/DoubleBuffer.java
+++ b/luni/src/main/java/java/nio/DoubleBuffer.java
@@ -81,7 +81,7 @@ public abstract class DoubleBuffer extends Buffer implements
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created double buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code doubleCount} is invalid.
*/
public static DoubleBuffer wrap(double[] array, int start, int doubleCount) {
@@ -92,8 +92,8 @@ public abstract class DoubleBuffer extends Buffer implements
return buf;
}
- DoubleBuffer(int capacity) {
- super(3, capacity, null);
+ DoubleBuffer(int capacity, long effectiveDirectAddress) {
+ super(3, capacity, effectiveDirectAddress);
}
public final double[] array() {
@@ -127,7 +127,7 @@ public abstract class DoubleBuffer extends Buffer implements
* limit is set to capacity; the mark is cleared.
*
* @return this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract DoubleBuffer compact();
@@ -141,7 +141,7 @@ public abstract class DoubleBuffer extends Buffer implements
* @return a negative value if this is less than {@code other}; 0 if this
* equals to {@code other}; a positive value if this is greater
* than {@code other}.
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code other} is not a double buffer.
*/
public int compareTo(DoubleBuffer otherBuffer) {
@@ -223,7 +223,7 @@ public abstract class DoubleBuffer extends Buffer implements
* 1.
*
* @return the double at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract double get();
@@ -238,7 +238,7 @@ public abstract class DoubleBuffer extends Buffer implements
* @param dst
* the destination double array.
* @return this buffer.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public DoubleBuffer get(double[] dst) {
@@ -259,9 +259,9 @@ public abstract class DoubleBuffer extends Buffer implements
* the number of doubles to read, must be no less than zero and
* not greater than {@code dst.length - dstOffset}.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code dstOffset} or {@code doubleCount} is invalid.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code doubleCount} is greater than {@code remaining()}.
*/
public DoubleBuffer get(double[] dst, int dstOffset, int doubleCount) {
@@ -281,7 +281,7 @@ public abstract class DoubleBuffer extends Buffer implements
* @param index
* the index, must not be negative and less than limit.
* @return a double at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract double get(int index);
@@ -360,9 +360,9 @@ public abstract class DoubleBuffer extends Buffer implements
* @param d
* the double to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract DoubleBuffer put(double d);
@@ -377,9 +377,9 @@ public abstract class DoubleBuffer extends Buffer implements
* @param src
* the source double array.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final DoubleBuffer put(double[] src) {
@@ -400,11 +400,11 @@ public abstract class DoubleBuffer extends Buffer implements
* the number of doubles to write, must be no less than zero and
* not greater than {@code src.length - srcOffset}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code doubleCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code doubleCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public DoubleBuffer put(double[] src, int srcOffset, int doubleCount) {
@@ -426,12 +426,12 @@ public abstract class DoubleBuffer extends Buffer implements
* @param src
* the source double buffer.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public DoubleBuffer put(DoubleBuffer src) {
@@ -459,9 +459,9 @@ public abstract class DoubleBuffer extends Buffer implements
* @param d
* the double to write.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract DoubleBuffer put(int index, double d);
diff --git a/luni/src/main/java/java/nio/FileChannelImpl.java b/luni/src/main/java/java/nio/FileChannelImpl.java
index a1be7fb..d72b9f0 100644
--- a/luni/src/main/java/java/nio/FileChannelImpl.java
+++ b/luni/src/main/java/java/nio/FileChannelImpl.java
@@ -17,12 +17,17 @@
package java.nio;
+import android.system.ErrnoException;
+import android.system.StructFlock;
+import android.util.MutableLong;
import java.io.Closeable;
import java.io.FileDescriptor;
import java.io.IOException;
+import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
+import java.nio.channels.FileLockInterruptionException;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.OverlappingFileLockException;
@@ -32,11 +37,8 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
-import libcore.io.ErrnoException;
import libcore.io.Libcore;
-import libcore.io.StructFlock;
-import libcore.util.MutableLong;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* Our concrete implementation of the abstract FileChannel class.
@@ -50,7 +52,7 @@ final class FileChannelImpl extends FileChannel {
}
};
- private final Object stream;
+ private final Closeable ioObject;
private final FileDescriptor fd;
private final int mode;
@@ -61,9 +63,9 @@ final class FileChannelImpl extends FileChannel {
* Create a new file channel implementation class that wraps the given
* fd and operates in the specified mode.
*/
- public FileChannelImpl(Object stream, FileDescriptor fd, int mode) {
+ public FileChannelImpl(Closeable ioObject, FileDescriptor fd, int mode) {
this.fd = fd;
- this.stream = stream;
+ this.ioObject = ioObject;
this.mode = mode;
}
@@ -86,9 +88,7 @@ final class FileChannelImpl extends FileChannel {
}
protected void implCloseChannel() throws IOException {
- if (stream instanceof Closeable) {
- ((Closeable) stream).close();
- }
+ ioObject.close();
}
private FileLock basicLock(long position, long size, boolean shared, boolean wait) throws IOException {
@@ -166,7 +166,11 @@ final class FileChannelImpl extends FileChannel {
resultLock = basicLock(position, size, shared, true);
completed = true;
} finally {
- end(completed);
+ try {
+ end(completed);
+ } catch (ClosedByInterruptException e) {
+ throw new FileLockInterruptionException();
+ }
}
}
return resultLock;
@@ -461,6 +465,9 @@ final class FileChannelImpl extends FileChannel {
throw errnoException.rethrowAsIOException();
}
}
+ if (position() > size) {
+ position(size);
+ }
return this;
}
diff --git a/luni/src/main/java/java/nio/FloatArrayBuffer.java b/luni/src/main/java/java/nio/FloatArrayBuffer.java
index 698174c..ac512a5 100644
--- a/luni/src/main/java/java/nio/FloatArrayBuffer.java
+++ b/luni/src/main/java/java/nio/FloatArrayBuffer.java
@@ -33,7 +33,7 @@ final class FloatArrayBuffer extends FloatBuffer {
}
private FloatArrayBuffer(int capacity, float[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/FloatBuffer.java b/luni/src/main/java/java/nio/FloatBuffer.java
index cb7e55e..68514c5 100644
--- a/luni/src/main/java/java/nio/FloatBuffer.java
+++ b/luni/src/main/java/java/nio/FloatBuffer.java
@@ -80,9 +80,9 @@ public abstract class FloatBuffer extends Buffer implements
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created float buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code floatCount} is invalid.
- * @exception NullPointerException
+ * @throws NullPointerException
* if {@code array} is null.
*/
public static FloatBuffer wrap(float[] array, int start, int floatCount) {
@@ -93,8 +93,8 @@ public abstract class FloatBuffer extends Buffer implements
return buf;
}
- FloatBuffer(int capacity) {
- super(2, capacity, null);
+ FloatBuffer(int capacity, long effectiveDirectAddress) {
+ super(2, capacity, effectiveDirectAddress);
}
public final float[] array() {
@@ -128,7 +128,7 @@ public abstract class FloatBuffer extends Buffer implements
* limit is set to capacity; the mark is cleared.
*
* @return this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract FloatBuffer compact();
@@ -142,7 +142,7 @@ public abstract class FloatBuffer extends Buffer implements
* @return a negative value if this is less than {@code otherBuffer}; 0 if
* this equals to {@code otherBuffer}; a positive value if this is
* greater than {@code otherBuffer}.
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code otherBuffer} is not a float buffer.
*/
public int compareTo(FloatBuffer otherBuffer) {
@@ -224,7 +224,7 @@ public abstract class FloatBuffer extends Buffer implements
* 1.
*
* @return the float at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract float get();
@@ -239,7 +239,7 @@ public abstract class FloatBuffer extends Buffer implements
* @param dst
* the destination float array.
* @return this buffer.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public FloatBuffer get(float[] dst) {
@@ -260,9 +260,9 @@ public abstract class FloatBuffer extends Buffer implements
* the number of floats to read, must be no less than zero and no
* greater than {@code dst.length - dstOffset}.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code dstOffset} or {@code floatCount} is invalid.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code floatCount} is greater than {@code remaining()}.
*/
public FloatBuffer get(float[] dst, int dstOffset, int floatCount) {
@@ -282,7 +282,7 @@ public abstract class FloatBuffer extends Buffer implements
* @param index
* the index, must not be negative and less than limit.
* @return a float at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract float get(int index);
@@ -359,9 +359,9 @@ public abstract class FloatBuffer extends Buffer implements
* @param f
* the float to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract FloatBuffer put(float f);
@@ -376,9 +376,9 @@ public abstract class FloatBuffer extends Buffer implements
* @param src
* the source float array.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final FloatBuffer put(float[] src) {
@@ -399,11 +399,11 @@ public abstract class FloatBuffer extends Buffer implements
* the number of floats to write, must be no less than zero and
* no greater than {@code src.length - srcOffset}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code floatCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code floatCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public FloatBuffer put(float[] src, int srcOffset, int floatCount) {
@@ -425,12 +425,12 @@ public abstract class FloatBuffer extends Buffer implements
* @param src
* the source float buffer.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public FloatBuffer put(FloatBuffer src) {
@@ -458,9 +458,9 @@ public abstract class FloatBuffer extends Buffer implements
* @param f
* the float to write.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract FloatBuffer put(int index, float f);
diff --git a/luni/src/main/java/java/nio/IntArrayBuffer.java b/luni/src/main/java/java/nio/IntArrayBuffer.java
index a5f9f39..423b1af 100644
--- a/luni/src/main/java/java/nio/IntArrayBuffer.java
+++ b/luni/src/main/java/java/nio/IntArrayBuffer.java
@@ -33,7 +33,7 @@ final class IntArrayBuffer extends IntBuffer {
}
private IntArrayBuffer(int capacity, int[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/IntBuffer.java b/luni/src/main/java/java/nio/IntBuffer.java
index a20f6c2..50e95b0 100644
--- a/luni/src/main/java/java/nio/IntBuffer.java
+++ b/luni/src/main/java/java/nio/IntBuffer.java
@@ -78,7 +78,7 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created int buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code intCount} is invalid.
*/
public static IntBuffer wrap(int[] array, int start, int intCount) {
@@ -89,8 +89,8 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
return buf;
}
- IntBuffer(int capacity) {
- super(2, capacity, null);
+ IntBuffer(int capacity, long effectiveDirectAddress) {
+ super(2, capacity, effectiveDirectAddress);
}
public final int[] array() {
@@ -124,7 +124,7 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* limit is set to capacity; the mark is cleared.
*
* @return this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract IntBuffer compact();
@@ -138,7 +138,7 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @return a negative value if this is less than {@code other}; 0 if this
* equals to {@code other}; a positive value if this is greater
* than {@code other}.
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code other} is not an int buffer.
*/
public int compareTo(IntBuffer otherBuffer) {
@@ -210,7 +210,7 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* Returns the int at the current position and increases the position by 1.
*
* @return the int at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract int get();
@@ -225,7 +225,7 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @param dst
* the destination int array.
* @return this buffer.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public IntBuffer get(int[] dst) {
@@ -246,9 +246,9 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* the number of ints to read, must be no less than zero and not
* greater than {@code dst.length - dstOffset}.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code dstOffset} or {@code intCount} is invalid.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code intCount} is greater than {@code remaining()}.
*/
public IntBuffer get(int[] dst, int dstOffset, int intCount) {
@@ -268,7 +268,7 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @param index
* the index, must not be negative and less than limit.
* @return an int at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract int get(int index);
@@ -345,9 +345,9 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @param i
* the int to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract IntBuffer put(int i);
@@ -362,9 +362,9 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @param src
* the source int array.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final IntBuffer put(int[] src) {
@@ -385,11 +385,11 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* the number of ints to write, must be no less than zero and not
* greater than {@code src.length - srcOffset}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code intCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code intCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public IntBuffer put(int[] src, int srcOffset, int intCount) {
@@ -414,12 +414,12 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @param src
* the source int buffer.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public IntBuffer put(IntBuffer src) {
@@ -447,9 +447,9 @@ public abstract class IntBuffer extends Buffer implements Comparable<IntBuffer>
* @param i
* the int to write.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract IntBuffer put(int index, int i);
diff --git a/luni/src/main/java/java/nio/IoVec.java b/luni/src/main/java/java/nio/IoVec.java
index f14f4f2..e20709c 100644
--- a/luni/src/main/java/java/nio/IoVec.java
+++ b/luni/src/main/java/java/nio/IoVec.java
@@ -16,10 +16,10 @@
package java.nio;
+import android.system.ErrnoException;
import java.io.FileDescriptor;
import java.io.IOException;
import libcore.io.Libcore;
-import libcore.io.ErrnoException;
/**
* Used to implement java.nio read(ByteBuffer[])/write(ByteBuffer[]) operations as POSIX readv(2)
diff --git a/luni/src/main/java/java/nio/LongArrayBuffer.java b/luni/src/main/java/java/nio/LongArrayBuffer.java
index 6419d73..f03a91e 100644
--- a/luni/src/main/java/java/nio/LongArrayBuffer.java
+++ b/luni/src/main/java/java/nio/LongArrayBuffer.java
@@ -33,7 +33,7 @@ final class LongArrayBuffer extends LongBuffer {
}
private LongArrayBuffer(int capacity, long[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/LongBuffer.java b/luni/src/main/java/java/nio/LongBuffer.java
index 55adab6..09f8418 100644
--- a/luni/src/main/java/java/nio/LongBuffer.java
+++ b/luni/src/main/java/java/nio/LongBuffer.java
@@ -80,7 +80,7 @@ public abstract class LongBuffer extends Buffer implements
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created long buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code longCount} is invalid.
*/
public static LongBuffer wrap(long[] array, int start, int longCount) {
@@ -91,8 +91,8 @@ public abstract class LongBuffer extends Buffer implements
return buf;
}
- LongBuffer(int capacity) {
- super(3, capacity, null);
+ LongBuffer(int capacity, long effectiveDirectAddress) {
+ super(3, capacity, effectiveDirectAddress);
}
public final long[] array() {
@@ -126,7 +126,7 @@ public abstract class LongBuffer extends Buffer implements
* limit is set to capacity; the mark is cleared.
*
* @return this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract LongBuffer compact();
@@ -140,7 +140,7 @@ public abstract class LongBuffer extends Buffer implements
* @return a negative value if this is less than {@code otherBuffer}; 0 if
* this equals to {@code otherBuffer}; a positive value if this is
* greater than {@code otherBuffer}
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code otherBuffer} is not a long buffer.
*/
public int compareTo(LongBuffer otherBuffer) {
@@ -212,7 +212,7 @@ public abstract class LongBuffer extends Buffer implements
* Returns the long at the current position and increase the position by 1.
*
* @return the long at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract long get();
@@ -227,7 +227,7 @@ public abstract class LongBuffer extends Buffer implements
* @param dst
* the destination long array.
* @return this buffer.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public LongBuffer get(long[] dst) {
@@ -248,9 +248,9 @@ public abstract class LongBuffer extends Buffer implements
* the number of longs to read, must be no less than zero and not
* greater than {@code dst.length - dstOffset}.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code dstOffset} or {@code longCount} is invalid.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code longCount} is greater than {@code remaining()}.
*/
public LongBuffer get(long[] dst, int dstOffset, int longCount) {
@@ -270,7 +270,7 @@ public abstract class LongBuffer extends Buffer implements
* @param index
* the index, must not be negative and less than limit.
* @return the long at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract long get(int index);
@@ -349,9 +349,9 @@ public abstract class LongBuffer extends Buffer implements
* @param l
* the long to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract LongBuffer put(long l);
@@ -366,9 +366,9 @@ public abstract class LongBuffer extends Buffer implements
* @param src
* the source long array.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final LongBuffer put(long[] src) {
@@ -389,11 +389,11 @@ public abstract class LongBuffer extends Buffer implements
* the number of longs to write, must be no less than zero and
* not greater than {@code src.length - srcOffset}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code longCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code longCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public LongBuffer put(long[] src, int srcOffset, int longCount) {
@@ -415,12 +415,12 @@ public abstract class LongBuffer extends Buffer implements
* @param src
* the source long buffer.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public LongBuffer put(LongBuffer src) {
@@ -448,9 +448,9 @@ public abstract class LongBuffer extends Buffer implements
* @param l
* the long to write.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract LongBuffer put(int index, long l);
diff --git a/luni/src/main/java/java/nio/MappedByteBuffer.java b/luni/src/main/java/java/nio/MappedByteBuffer.java
index 2d44d0f..ce19c0c 100644
--- a/luni/src/main/java/java/nio/MappedByteBuffer.java
+++ b/luni/src/main/java/java/nio/MappedByteBuffer.java
@@ -16,11 +16,11 @@
package java.nio;
+import android.system.ErrnoException;
import java.nio.channels.FileChannel.MapMode;
-import libcore.io.ErrnoException;
import libcore.io.Libcore;
-import libcore.io.Memory;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.MS_SYNC;
+import static android.system.OsConstants._SC_PAGE_SIZE;
/**
* {@code MappedByteBuffer} is a special kind of direct byte buffer which maps a
@@ -38,10 +38,12 @@ import static libcore.io.OsConstants.*;
*/
public abstract class MappedByteBuffer extends ByteBuffer {
final MapMode mapMode;
+ final MemoryBlock block;
- MappedByteBuffer(MemoryBlock block, int capacity, MapMode mapMode) {
- super(capacity, block);
+ MappedByteBuffer(MemoryBlock block, int capacity, MapMode mapMode, long effectiveDirectAddress) {
+ super(capacity, effectiveDirectAddress);
this.mapMode = mapMode;
+ this.block = block;
}
/**
diff --git a/luni/src/main/java/java/nio/MemoryBlock.java b/luni/src/main/java/java/nio/MemoryBlock.java
index 718b020..b62e3c6 100644
--- a/luni/src/main/java/java/nio/MemoryBlock.java
+++ b/luni/src/main/java/java/nio/MemoryBlock.java
@@ -17,14 +17,18 @@
package java.nio;
+import android.system.ErrnoException;
import dalvik.system.VMRuntime;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.channels.FileChannel.MapMode;
-import libcore.io.ErrnoException;
import libcore.io.Libcore;
import libcore.io.Memory;
-import static libcore.io.OsConstants.*;
+
+import static android.system.OsConstants.MAP_PRIVATE;
+import static android.system.OsConstants.MAP_SHARED;
+import static android.system.OsConstants.PROT_READ;
+import static android.system.OsConstants.PROT_WRITE;
class MemoryBlock {
/**
@@ -44,8 +48,8 @@ class MemoryBlock {
// a state where munmap(2) could return an error.
throw new AssertionError(errnoException);
}
- address = 0;
}
+ super.free();
}
@Override protected void finalize() throws Throwable {
@@ -74,7 +78,7 @@ class MemoryBlock {
@Override public void free() {
array = null;
- address = 0;
+ super.free();
}
}
@@ -90,6 +94,8 @@ class MemoryBlock {
protected long address;
protected final long size;
+ private boolean accessible;
+ private boolean freed;
public static MemoryBlock mmap(FileDescriptor fd, long offset, long size, MapMode mapMode) throws IOException {
if (size == 0) {
@@ -134,6 +140,8 @@ class MemoryBlock {
private MemoryBlock(long address, long size) {
this.address = address;
this.size = size;
+ accessible = true;
+ freed = false;
}
// Used to support array/arrayOffset/hasArray for direct buffers.
@@ -142,6 +150,20 @@ class MemoryBlock {
}
public void free() {
+ address = 0;
+ freed = true;
+ }
+
+ public boolean isFreed() {
+ return freed;
+ }
+
+ public boolean isAccessible() {
+ return !isFreed() && accessible;
+ }
+
+ public final void setAccessible(boolean accessible) {
+ this.accessible = accessible;
}
public final void pokeByte(int offset, byte value) {
diff --git a/luni/src/main/java/java/nio/NIOAccess.java b/luni/src/main/java/java/nio/NIOAccess.java
index 12af44d..ddb102e 100644
--- a/luni/src/main/java/java/nio/NIOAccess.java
+++ b/luni/src/main/java/java/nio/NIOAccess.java
@@ -24,17 +24,11 @@ final class NIOAccess {
/**
* Returns the underlying native pointer to the data of the given
* Buffer starting at the Buffer's current position, or 0 if the
- * Buffer is not backed by native heap storage. Note that this is
- * different than what the Harmony implementation calls a "base
- * address."
- *
- * @param b the Buffer to be queried
- * @return the native pointer to the Buffer's data at its current
- * position, or 0 if there is none
+ * Buffer is not backed by native heap storage.
*/
static long getBasePointer(Buffer b) {
long address = b.effectiveDirectAddress;
- if (address == 0) {
+ if (address == 0L) {
return 0L;
}
return address + (b.position << b._elementSizeShift);
@@ -43,10 +37,6 @@ final class NIOAccess {
/**
* Returns the underlying Java array containing the data of the
* given Buffer, or null if the Buffer is not backed by a Java array.
- *
- * @param b the Buffer to be queried
- * @return the Java array containing the Buffer's data, or null if
- * there is none
*/
static Object getBaseArray(Buffer b) {
return b.hasArray() ? b.array() : null;
@@ -58,9 +48,6 @@ final class NIOAccess {
* the actual start of the data. The start of the data takes into
* account the Buffer's current position. This method is only
* meaningful if getBaseArray() returns non-null.
- *
- * @param b the Buffer to be queried
- * @return the data offset in bytes to the start of this Buffer's data
*/
static int getBaseArrayOffset(Buffer b) {
return b.hasArray() ? ((b.arrayOffset() + b.position) << b._elementSizeShift) : 0;
diff --git a/luni/src/main/java/java/nio/NioUtils.java b/luni/src/main/java/java/nio/NioUtils.java
index a1a46b6..f2a0b10 100644
--- a/luni/src/main/java/java/nio/NioUtils.java
+++ b/luni/src/main/java/java/nio/NioUtils.java
@@ -16,8 +16,12 @@
package java.nio;
+import java.io.Closeable;
import java.io.FileDescriptor;
+import java.io.IOException;
+import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
+import java.util.Set;
/**
* @hide internal use only
@@ -43,8 +47,8 @@ public final class NioUtils {
/**
* Helps bridge between io and nio.
*/
- public static FileChannel newFileChannel(Object stream, FileDescriptor fd, int mode) {
- return new FileChannelImpl(stream, fd, mode);
+ public static FileChannel newFileChannel(Closeable ioObject, FileDescriptor fd, int mode) {
+ return new FileChannelImpl(ioObject, fd, mode);
}
/**
diff --git a/luni/src/main/java/java/nio/PipeImpl.java b/luni/src/main/java/java/nio/PipeImpl.java
index d4dde3b..ebc8a91 100644
--- a/luni/src/main/java/java/nio/PipeImpl.java
+++ b/luni/src/main/java/java/nio/PipeImpl.java
@@ -16,16 +16,16 @@
package java.nio;
+import android.system.ErrnoException;
import java.io.Closeable;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.channels.Pipe;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
-import libcore.io.ErrnoException;
import libcore.io.IoUtils;
import libcore.io.Libcore;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/*
* Implements {@link java.nio.channels.Pipe}.
diff --git a/luni/src/main/java/java/nio/SelectorImpl.java b/luni/src/main/java/java/nio/SelectorImpl.java
index d63fa63..45406b1 100644
--- a/luni/src/main/java/java/nio/SelectorImpl.java
+++ b/luni/src/main/java/java/nio/SelectorImpl.java
@@ -15,33 +15,38 @@
*/
package java.nio;
+import android.system.ErrnoException;
+import android.system.StructPollfd;
import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
import java.io.IOException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.IllegalSelectorException;
-import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
-import static java.nio.channels.SelectionKey.*;
import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.AbstractSelectionKey;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UnsafeArrayList;
-import libcore.io.ErrnoException;
import libcore.io.IoBridge;
import libcore.io.IoUtils;
import libcore.io.Libcore;
-import libcore.io.StructPollfd;
-import libcore.util.EmptyArray;
-import static libcore.io.OsConstants.*;
+
+import static android.system.OsConstants.EINTR;
+import static android.system.OsConstants.POLLERR;
+import static android.system.OsConstants.POLLHUP;
+import static android.system.OsConstants.POLLIN;
+import static android.system.OsConstants.POLLOUT;
+import static java.nio.channels.SelectionKey.OP_ACCEPT;
+import static java.nio.channels.SelectionKey.OP_CONNECT;
+import static java.nio.channels.SelectionKey.OP_READ;
+import static java.nio.channels.SelectionKey.OP_WRITE;
/*
* Default implementation of java.nio.channels.Selector
@@ -255,7 +260,7 @@ final class SelectorImpl extends AbstractSelector {
int ops = key.interestOpsNoCheck();
int selectedOps = 0;
- if ((pollFd.revents & POLLHUP) != 0) {
+ if ((pollFd.revents & POLLHUP) != 0 || (pollFd.revents & POLLERR) != 0) {
// If there was an error condition, we definitely want to wake listeners,
// regardless of what they're waiting for. Failure is always interesting.
selectedOps |= ops;
@@ -321,6 +326,7 @@ final class SelectorImpl extends AbstractSelector {
try {
Libcore.os.write(wakeupOut, new byte[] { 1 }, 0, 1);
} catch (ErrnoException ignored) {
+ } catch (InterruptedIOException ignored) {
}
return this;
}
diff --git a/luni/src/main/java/java/nio/ServerSocketChannelImpl.java b/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
index 3fb61a3..ae33672 100644
--- a/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
+++ b/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
@@ -17,13 +17,13 @@
package java.nio;
+import android.system.ErrnoException;
import java.io.FileDescriptor;
import java.io.IOException;
-import java.net.PlainServerSocketImpl;
+import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
-import java.net.SocketImpl;
import java.net.SocketTimeoutException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.IllegalBlockingModeException;
@@ -31,9 +31,11 @@ import java.nio.channels.NotYetBoundException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
-import libcore.io.ErrnoException;
+import java.nio.channels.UnresolvedAddressException;
+import java.nio.channels.UnsupportedAddressTypeException;
+import java.util.Set;
import libcore.io.IoUtils;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* The default ServerSocketChannel.
@@ -41,31 +43,28 @@ import static libcore.io.OsConstants.*;
final class ServerSocketChannelImpl extends ServerSocketChannel implements FileDescriptorChannel {
private final ServerSocketAdapter socket;
- private final SocketImpl impl;
-
- private boolean isBound = false;
private final Object acceptLock = new Object();
public ServerSocketChannelImpl(SelectorProvider sp) throws IOException {
super(sp);
this.socket = new ServerSocketAdapter(this);
- this.impl = socket.getImpl$();
}
@Override public ServerSocket socket() {
return socket;
}
- @Override public SocketChannel accept() throws IOException {
+ @Override
+ public SocketChannel accept() throws IOException {
if (!isOpen()) {
throw new ClosedChannelException();
}
- if (!isBound) {
+ if (!socket.isBound()) {
throw new NotYetBoundException();
}
- // Create an empty socket channel. This will be populated by ServerSocketAdapter.accept.
+ // Create an empty socket channel. This will be populated by ServerSocketAdapter.implAccept.
SocketChannelImpl result = new SocketChannelImpl(provider(), false);
try {
begin();
@@ -81,9 +80,9 @@ final class ServerSocketChannelImpl extends ServerSocketChannel implements FileD
}
}
} finally {
- end(result.socket().isConnected());
+ end(result.isConnected());
}
- return result.socket().isConnected() ? result : null;
+ return result.isConnected() ? result : null;
}
private boolean shouldThrowSocketTimeoutExceptionFromAccept(SocketTimeoutException e) {
@@ -100,17 +99,19 @@ final class ServerSocketChannelImpl extends ServerSocketChannel implements FileD
}
@Override protected void implConfigureBlocking(boolean blocking) throws IOException {
- IoUtils.setBlocking(impl.getFD$(), blocking);
+ IoUtils.setBlocking(socket.getFD$(), blocking);
}
+ @Override
synchronized protected void implCloseSelectableChannel() throws IOException {
if (!socket.isClosed()) {
socket.close();
}
}
+ @Override
public FileDescriptor getFD() {
- return impl.getFD$();
+ return socket.getFD$();
}
private static class ServerSocketAdapter extends ServerSocket {
@@ -120,13 +121,8 @@ final class ServerSocketChannelImpl extends ServerSocketChannel implements FileD
this.channelImpl = aChannelImpl;
}
- @Override public void bind(SocketAddress localAddress, int backlog) throws IOException {
- super.bind(localAddress, backlog);
- channelImpl.isBound = true;
- }
-
@Override public Socket accept() throws IOException {
- if (!channelImpl.isBound) {
+ if (!isBound()) {
throw new IllegalBlockingModeException();
}
SocketChannel sc = channelImpl.accept();
@@ -142,9 +138,12 @@ final class ServerSocketChannelImpl extends ServerSocketChannel implements FileD
try {
synchronized (this) {
super.implAccept(clientSocket);
- clientSocketChannel.setConnected();
- clientSocketChannel.setBound(true);
- clientSocketChannel.finishAccept();
+
+ // Sync the client socket's associated channel state with the Socket and OS.
+ InetSocketAddress remoteAddress =
+ new InetSocketAddress(
+ clientSocket.getInetAddress(), clientSocket.getPort());
+ clientSocketChannel.onAccept(remoteAddress, false /* updateSocketState */);
}
connectOK = true;
} finally {
@@ -159,23 +158,17 @@ final class ServerSocketChannelImpl extends ServerSocketChannel implements FileD
return channelImpl;
}
- @Override public boolean isBound() {
- return channelImpl.isBound;
- }
-
- @Override public void bind(SocketAddress localAddress) throws IOException {
- super.bind(localAddress);
- channelImpl.isBound = true;
- }
-
@Override public void close() throws IOException {
synchronized (channelImpl) {
+ super.close();
if (channelImpl.isOpen()) {
channelImpl.close();
- } else {
- super.close();
}
}
}
+
+ private FileDescriptor getFD$() {
+ return super.getImpl$().getFD$();
+ }
}
}
diff --git a/luni/src/main/java/java/nio/ShortArrayBuffer.java b/luni/src/main/java/java/nio/ShortArrayBuffer.java
index a092cb0..3c41174 100644
--- a/luni/src/main/java/java/nio/ShortArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ShortArrayBuffer.java
@@ -33,7 +33,7 @@ final class ShortArrayBuffer extends ShortBuffer {
}
private ShortArrayBuffer(int capacity, short[] backingArray, int arrayOffset, boolean isReadOnly) {
- super(capacity);
+ super(capacity, 0);
this.backingArray = backingArray;
this.arrayOffset = arrayOffset;
this.isReadOnly = isReadOnly;
diff --git a/luni/src/main/java/java/nio/ShortBuffer.java b/luni/src/main/java/java/nio/ShortBuffer.java
index 8da01ed..cbc5a47 100644
--- a/luni/src/main/java/java/nio/ShortBuffer.java
+++ b/luni/src/main/java/java/nio/ShortBuffer.java
@@ -80,7 +80,7 @@ public abstract class ShortBuffer extends Buffer implements
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created short buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code start} or {@code shortCount} is invalid.
*/
public static ShortBuffer wrap(short[] array, int start, int shortCount) {
@@ -91,8 +91,8 @@ public abstract class ShortBuffer extends Buffer implements
return buf;
}
- ShortBuffer(int capacity) {
- super(1, capacity, null);
+ ShortBuffer(int capacity, long effectiveDirectAddress) {
+ super(1, capacity, effectiveDirectAddress);
}
public final short[] array() {
@@ -126,7 +126,7 @@ public abstract class ShortBuffer extends Buffer implements
* limit is set to capacity; the mark is cleared.
*
* @return this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ShortBuffer compact();
@@ -140,7 +140,7 @@ public abstract class ShortBuffer extends Buffer implements
* @return a negative value if this is less than {@code otherBuffer}; 0 if
* this equals to {@code otherBuffer}; a positive value if this is
* greater than {@code otherBuffer}.
- * @exception ClassCastException
+ * @throws ClassCastException
* if {@code otherBuffer} is not a short buffer.
*/
public int compareTo(ShortBuffer otherBuffer) {
@@ -213,7 +213,7 @@ public abstract class ShortBuffer extends Buffer implements
* 1.
*
* @return the short at the current position.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if the position is equal or greater than limit.
*/
public abstract short get();
@@ -228,7 +228,7 @@ public abstract class ShortBuffer extends Buffer implements
* @param dst
* the destination short array.
* @return this buffer.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
public ShortBuffer get(short[] dst) {
@@ -249,9 +249,9 @@ public abstract class ShortBuffer extends Buffer implements
* the number of shorts to read, must be no less than zero and
* not greater than {@code dst.length - dstOffset}.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code dstOffset} or {@code shortCount} is invalid.
- * @exception BufferUnderflowException
+ * @throws BufferUnderflowException
* if {@code shortCount} is greater than {@code remaining()}.
*/
public ShortBuffer get(short[] dst, int dstOffset, int shortCount) {
@@ -271,7 +271,7 @@ public abstract class ShortBuffer extends Buffer implements
* @param index
* the index, must not be negative and less than limit.
* @return a short at the specified index.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
*/
public abstract short get(int index);
@@ -348,9 +348,9 @@ public abstract class ShortBuffer extends Buffer implements
* @param s
* the short to write.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if position is equal or greater than limit.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ShortBuffer put(short s);
@@ -365,9 +365,9 @@ public abstract class ShortBuffer extends Buffer implements
* @param src
* the source short array.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public final ShortBuffer put(short[] src) {
@@ -388,11 +388,11 @@ public abstract class ShortBuffer extends Buffer implements
* the number of shorts to write, must be no less than zero and
* not greater than {@code src.length - srcOffset}.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code remaining()} is less than {@code shortCount}.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if either {@code srcOffset} or {@code shortCount} is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public ShortBuffer put(short[] src, int srcOffset, int shortCount) {
@@ -414,12 +414,12 @@ public abstract class ShortBuffer extends Buffer implements
* @param src
* the source short buffer.
* @return this buffer.
- * @exception BufferOverflowException
+ * @throws BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* if {@code src} is this buffer.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public ShortBuffer put(ShortBuffer src) {
@@ -447,9 +447,9 @@ public abstract class ShortBuffer extends Buffer implements
* @param s
* the short to write.
* @return this buffer.
- * @exception IndexOutOfBoundsException
+ * @throws IndexOutOfBoundsException
* if index is invalid.
- * @exception ReadOnlyBufferException
+ * @throws ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
public abstract ShortBuffer put(int index, short s);
diff --git a/luni/src/main/java/java/nio/SocketChannelImpl.java b/luni/src/main/java/java/nio/SocketChannelImpl.java
index 714005f..d5cb716 100644
--- a/luni/src/main/java/java/nio/SocketChannelImpl.java
+++ b/luni/src/main/java/java/nio/SocketChannelImpl.java
@@ -17,9 +17,12 @@
package java.nio;
+import android.system.ErrnoException;
import java.io.FileDescriptor;
-import java.io.IOException;
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
import java.io.InputStream;
+import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Inet4Address;
@@ -30,7 +33,6 @@ import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketUtils;
-import java.net.UnknownHostException;
import java.nio.channels.AlreadyConnectedException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ConnectionPendingException;
@@ -38,15 +40,15 @@ import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.NoConnectionPendingException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.SelectorProvider;
import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.UnsupportedAddressTypeException;
-import java.nio.channels.spi.SelectorProvider;
import java.util.Arrays;
-import libcore.io.ErrnoException;
-import libcore.io.Libcore;
+import java.util.Set;
import libcore.io.IoBridge;
import libcore.io.IoUtils;
-import static libcore.io.OsConstants.*;
+import libcore.io.Libcore;
+import static android.system.OsConstants.*;
/*
* The default implementation class of java.nio.channels.SocketChannel.
@@ -74,6 +76,7 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
// The address to be connected.
private InetSocketAddress connectAddress = null;
+ // The local address the socket is bound to.
private InetAddress localAddress = null;
private int localPort;
@@ -133,20 +136,34 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
return socket;
}
- @Override
- synchronized public boolean isConnected() {
- return status == SOCKET_STATUS_CONNECTED;
- }
-
- /*
- * Status setting used by other class.
+ /**
+ * Initialise the isBound, localAddress and localPort state from the file descriptor. Used when
+ * some or all of the bound state has been left to the OS to decide, or when the Socket handled
+ * bind() or connect().
+ *
+ * @param updateSocketState
+ * if the associated socket (if present) needs to be updated
+ * @hide package visible for other nio classes
*/
- synchronized void setConnected() {
- status = SOCKET_STATUS_CONNECTED;
+ void onBind(boolean updateSocketState) {
+ SocketAddress sa;
+ try {
+ sa = Libcore.os.getsockname(fd);
+ } catch (ErrnoException errnoException) {
+ throw new AssertionError(errnoException);
+ }
+ isBound = true;
+ InetSocketAddress localSocketAddress = (InetSocketAddress) sa;
+ localAddress = localSocketAddress.getAddress();
+ localPort = localSocketAddress.getPort();
+ if (updateSocketState && socket != null) {
+ socket.onBind(localAddress, localPort);
+ }
}
- void setBound(boolean flag) {
- isBound = flag;
+ @Override
+ synchronized public boolean isConnected() {
+ return status == SOCKET_STATUS_CONNECTED;
}
@Override
@@ -169,16 +186,22 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
normalAddr = InetAddress.getLocalHost();
}
+ boolean isBlocking = isBlocking();
boolean finished = false;
+ int newStatus;
try {
- if (isBlocking()) {
+ if (isBlocking) {
begin();
}
- finished = IoBridge.connect(fd, normalAddr, port);
- isBound = finished;
+ // When in blocking mode, IoBridge.connect() will return without an exception when the
+ // socket is connected. When in non-blocking mode it will return without an exception
+ // without knowing the result of the connection attempt, which could still be going on.
+ IoBridge.connect(fd, normalAddr, port);
+ newStatus = isBlocking ? SOCKET_STATUS_CONNECTED : SOCKET_STATUS_PENDING;
+ finished = true;
} catch (IOException e) {
if (isEINPROGRESS(e)) {
- status = SOCKET_STATUS_PENDING;
+ newStatus = SOCKET_STATUS_PENDING;
} else {
if (isOpen()) {
close();
@@ -187,26 +210,36 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
throw e;
}
} finally {
- if (isBlocking()) {
+ if (isBlocking) {
end(finished);
}
}
- initLocalAddressAndPort();
- connectAddress = inetSocketAddress;
- if (socket != null) {
- socket.socketImpl().initRemoteAddressAndPort(connectAddress.getAddress(),
- connectAddress.getPort());
+ // If the channel was not bound, a connection attempt will have caused an implicit bind() to
+ // take place. Keep the local address state held by the channel and the socket up to date.
+ if (!isBound) {
+ onBind(true /* updateSocketState */);
}
- synchronized (this) {
- if (isBlocking()) {
- status = (finished ? SOCKET_STATUS_CONNECTED : SOCKET_STATUS_UNCONNECTED);
- } else {
- status = SOCKET_STATUS_PENDING;
- }
+ // Keep the connected state held by the channel and the socket up to date.
+ onConnectStatusChanged(inetSocketAddress, newStatus, true /* updateSocketState */);
+
+ return status == SOCKET_STATUS_CONNECTED;
+ }
+
+ /**
+ * Initialise the connect() state with the supplied information.
+ *
+ * @param updateSocketState
+ * if the associated socket (if present) needs to be updated
+ * @hide package visible for other nio classes
+ */
+ void onConnectStatusChanged(InetSocketAddress address, int status, boolean updateSocketState) {
+ this.status = status;
+ connectAddress = address;
+ if (status == SOCKET_STATUS_CONNECTED && updateSocketState && socket != null) {
+ socket.onConnect(connectAddress.getAddress(), connectAddress.getPort());
}
- return finished;
}
private boolean isEINPROGRESS(IOException e) {
@@ -222,21 +255,6 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
return false;
}
- private void initLocalAddressAndPort() {
- SocketAddress sa;
- try {
- sa = Libcore.os.getsockname(fd);
- } catch (ErrnoException errnoException) {
- throw new AssertionError(errnoException);
- }
- InetSocketAddress isa = (InetSocketAddress) sa;
- localAddress = isa.getAddress();
- localPort = isa.getPort();
- if (socket != null) {
- socket.socketImpl().initLocalPort(localPort);
- }
- }
-
@Override
public boolean finishConnect() throws IOException {
synchronized (this) {
@@ -257,7 +275,6 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
InetAddress inetAddress = connectAddress.getAddress();
int port = connectAddress.getPort();
finished = IoBridge.isConnected(fd, inetAddress, port, 0, 0); // Return immediately.
- isBound = finished;
} catch (ConnectException e) {
if (isOpen()) {
close();
@@ -270,15 +287,13 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
synchronized (this) {
status = (finished ? SOCKET_STATUS_CONNECTED : status);
- isBound = finished;
+ if (finished && socket != null) {
+ socket.onConnect(connectAddress.getAddress(), connectAddress.getPort());
+ }
}
return finished;
}
- void finishAccept() {
- initLocalAddressAndPort();
- }
-
@Override
public int read(ByteBuffer dst) throws IOException {
dst.checkWritable();
@@ -447,23 +462,17 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
}
/*
- * Get local address.
- */
- public InetAddress getLocalAddress() throws UnknownHostException {
- return isBound ? localAddress : Inet4Address.ANY;
- }
-
- /*
* Do really closing action here.
*/
@Override
protected synchronized void implCloseSelectableChannel() throws IOException {
if (status != SOCKET_STATUS_CLOSED) {
status = SOCKET_STATUS_CLOSED;
+ // IoBridge.closeAndSignalBlockedThreads(fd) is idempotent: It is safe to call on an
+ // already-closed file descriptor.
+ IoBridge.closeAndSignalBlockedThreads(fd);
if (socket != null && !socket.isClosed()) {
- socket.close();
- } else {
- IoBridge.closeSocket(fd);
+ socket.onClose();
}
}
}
@@ -479,6 +488,12 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
return fd;
}
+ /* @hide used by ServerSocketChannelImpl to sync channel state during accept() */
+ public void onAccept(InetSocketAddress remoteAddress, boolean updateSocketState) {
+ onBind(updateSocketState);
+ onConnectStatusChanged(remoteAddress, SOCKET_STATUS_CONNECTED, updateSocketState);
+ }
+
/*
* Adapter classes for internal socket.
*/
@@ -486,15 +501,24 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
private final SocketChannelImpl channel;
private final PlainSocketImpl socketImpl;
- SocketAdapter(PlainSocketImpl socketImpl, SocketChannelImpl channel) throws SocketException {
+ SocketAdapter(PlainSocketImpl socketImpl, SocketChannelImpl channel)
+ throws SocketException {
super(socketImpl);
this.socketImpl = socketImpl;
this.channel = channel;
SocketUtils.setCreated(this);
- }
- PlainSocketImpl socketImpl() {
- return socketImpl;
+ // Sync state socket state with the channel it is being created from
+ if (channel.isBound) {
+ onBind(channel.localAddress, channel.localPort);
+ }
+ if (channel.isConnected()) {
+ onConnect(channel.connectAddress.getAddress(), channel.connectAddress.getPort());
+ }
+ if (!channel.isOpen()) {
+ onClose();
+ }
+
}
@Override
@@ -503,25 +527,6 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
}
@Override
- public boolean isBound() {
- return channel.isBound;
- }
-
- @Override
- public boolean isConnected() {
- return channel.isConnected();
- }
-
- @Override
- public InetAddress getLocalAddress() {
- try {
- return channel.getLocalAddress();
- } catch (UnknownHostException e) {
- return null;
- }
- }
-
- @Override
public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
if (!channel.isBlocking()) {
throw new IllegalBlockingModeException();
@@ -530,10 +535,11 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
throw new AlreadyConnectedException();
}
super.connect(remoteAddr, timeout);
- channel.initLocalAddressAndPort();
+ channel.onBind(false);
if (super.isConnected()) {
- channel.setConnected();
- channel.isBound = super.isBound();
+ InetSocketAddress remoteInetAddress = (InetSocketAddress) remoteAddr;
+ channel.onConnectStatusChanged(
+ remoteInetAddress, SOCKET_STATUS_CONNECTED, false /* updateSocketState */);
}
}
@@ -546,47 +552,29 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
throw new ConnectionPendingException();
}
super.bind(localAddr);
- channel.initLocalAddressAndPort();
- channel.isBound = true;
+ channel.onBind(false);
}
@Override
public void close() throws IOException {
synchronized (channel) {
+ super.close();
if (channel.isOpen()) {
+ // channel.close() recognizes the socket is closed and avoids recursion. There
+ // is no channel.onClose() because the "closed" field is private.
channel.close();
- } else {
- super.close();
}
- channel.status = SocketChannelImpl.SOCKET_STATUS_CLOSED;
}
}
@Override
public OutputStream getOutputStream() throws IOException {
- checkOpenAndConnected();
- if (isOutputShutdown()) {
- throw new SocketException("Socket output is shutdown");
- }
- return new SocketChannelOutputStream(channel);
+ return new BlockingCheckOutputStream(super.getOutputStream(), channel);
}
@Override
public InputStream getInputStream() throws IOException {
- checkOpenAndConnected();
- if (isInputShutdown()) {
- throw new SocketException("Socket input is shutdown");
- }
- return new SocketChannelInputStream(channel);
- }
-
- private void checkOpenAndConnected() throws SocketException {
- if (!channel.isOpen()) {
- throw new SocketException("Socket is closed");
- }
- if (!channel.isConnected()) {
- throw new SocketException("Socket is not connected");
- }
+ return new BlockingCheckInputStream(super.getInputStream(), channel);
}
@Override
@@ -596,86 +584,92 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorChannel {
}
/*
- * This output stream delegates all operations to the associated channel.
* Throws an IllegalBlockingModeException if the channel is in non-blocking
* mode when performing write operations.
*/
- private static class SocketChannelOutputStream extends OutputStream {
+ private static class BlockingCheckOutputStream extends FilterOutputStream {
private final SocketChannel channel;
- public SocketChannelOutputStream(SocketChannel channel) {
+ public BlockingCheckOutputStream(OutputStream out, SocketChannel channel) {
+ super(out);
this.channel = channel;
}
- /*
- * Closes this stream and channel.
- *
- * @exception IOException thrown if an error occurs during the close
- */
@Override
- public void close() throws IOException {
- channel.close();
+ public void write(byte[] buffer, int offset, int byteCount) throws IOException {
+ checkBlocking();
+ out.write(buffer, offset, byteCount);
}
@Override
- public void write(byte[] buffer, int offset, int byteCount) throws IOException {
- Arrays.checkOffsetAndCount(buffer.length, offset, byteCount);
- ByteBuffer buf = ByteBuffer.wrap(buffer, offset, byteCount);
- if (!channel.isBlocking()) {
- throw new IllegalBlockingModeException();
- }
- channel.write(buf);
+ public void write(int oneByte) throws IOException {
+ checkBlocking();
+ out.write(oneByte);
}
@Override
- public void write(int oneByte) throws IOException {
+ public void write(byte[] buffer) throws IOException {
+ checkBlocking();
+ out.write(buffer);
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ // channel.close() recognizes the socket is closed and avoids recursion. There is no
+ // channel.onClose() because the "closed" field is private.
+ channel.close();
+ }
+
+ private void checkBlocking() {
if (!channel.isBlocking()) {
throw new IllegalBlockingModeException();
}
- ByteBuffer buffer = ByteBuffer.allocate(1);
- buffer.put(0, (byte) (oneByte & 0xFF));
- channel.write(buffer);
}
}
/*
- * This input stream delegates all operations to the associated channel.
* Throws an IllegalBlockingModeException if the channel is in non-blocking
* mode when performing read operations.
*/
- private static class SocketChannelInputStream extends InputStream {
+ private static class BlockingCheckInputStream extends FilterInputStream {
private final SocketChannel channel;
- public SocketChannelInputStream(SocketChannel channel) {
+ public BlockingCheckInputStream(InputStream in, SocketChannel channel) {
+ super(in);
this.channel = channel;
}
- /*
- * Closes this stream and channel.
- */
@Override
- public void close() throws IOException {
- channel.close();
+ public int read() throws IOException {
+ checkBlocking();
+ return in.read();
}
@Override
- public int read() throws IOException {
- if (!channel.isBlocking()) {
- throw new IllegalBlockingModeException();
- }
- ByteBuffer buf = ByteBuffer.allocate(1);
- int result = channel.read(buf);
- return (result == -1) ? result : (buf.get(0) & 0xff);
+ public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
+ checkBlocking();
+ return in.read(buffer, byteOffset, byteCount);
}
@Override
- public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
- Arrays.checkOffsetAndCount(buffer.length, byteOffset, byteCount);
+ public int read(byte[] buffer) throws IOException {
+ checkBlocking();
+ return in.read(buffer);
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ // channel.close() recognizes the socket is closed and avoids recursion. There is no
+ // channel.onClose() because the "closed" field is private.
+ channel.close();
+ }
+
+ private void checkBlocking() {
if (!channel.isBlocking()) {
throw new IllegalBlockingModeException();
}
- ByteBuffer buf = ByteBuffer.wrap(buffer, byteOffset, byteCount);
- return channel.read(buf);
}
}
}
diff --git a/luni/src/main/java/java/nio/channels/DatagramChannel.java b/luni/src/main/java/java/nio/channels/DatagramChannel.java
index 486b168..2cff7f0 100644
--- a/luni/src/main/java/java/nio/channels/DatagramChannel.java
+++ b/luni/src/main/java/java/nio/channels/DatagramChannel.java
@@ -19,10 +19,13 @@ package java.nio.channels;
import java.io.IOException;
import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.SelectorProvider;
+import java.util.Set;
/**
* A {@code DatagramChannel} is a selectable channel that represents a partial
diff --git a/luni/src/main/java/java/nio/channels/FileChannel.java b/luni/src/main/java/java/nio/channels/FileChannel.java
index 298ea8b..d6c140b 100644
--- a/luni/src/main/java/java/nio/channels/FileChannel.java
+++ b/luni/src/main/java/java/nio/channels/FileChannel.java
@@ -77,7 +77,7 @@ import java.nio.channels.spi.AbstractInterruptibleChannel;
* content, size, etc.
*/
public abstract class FileChannel extends AbstractInterruptibleChannel
- implements GatheringByteChannel, ScatteringByteChannel, ByteChannel {
+ implements ByteChannel, GatheringByteChannel, ScatteringByteChannel {
/**
* {@code MapMode} defines file mapping mode constants.
@@ -281,10 +281,9 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
long position, long size) throws IOException;
/**
- * Returns the current value of the file position pointer.
+ * Returns the current position as a positive integer number of bytes from
+ * the start of the file.
*
- * @return the current position as a positive integer number of bytes from
- * the start of the file.
* @throws ClosedChannelException
* if this channel is closed.
* @throws IOException
@@ -302,9 +301,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* succeed but they will fill the bytes between the current end of file and
* the new position with the required number of (unspecified) byte values.
*
- * @param offset
- * the new file position, in bytes.
- * @return the receiver.
+ * @return this.
* @throws IllegalArgumentException
* if the new position is negative.
* @throws ClosedChannelException
@@ -312,7 +309,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* @throws IOException
* if another I/O error occurs.
*/
- public abstract FileChannel position(long offset) throws IOException;
+ public abstract FileChannel position(long newPosition) throws IOException;
/**
* Reads bytes from this file channel into the given buffer.
@@ -362,7 +359,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* the buffer to receive the bytes.
* @param position
* the (non-negative) position at which to read the bytes.
- * @return the number of bytes actually read.
+ * @return the number of bytes actually read, or -1 if the end of the file has been reached.
* @throws AsynchronousCloseException
* if this channel is closed by another thread while this method
* is executing.
@@ -398,7 +395,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
*
* @param buffers
* the array of byte buffers into which the bytes will be copied.
- * @return the number of bytes actually read.
+ * @return the number of bytes actually read, or -1 if the end of the file has been reached.
* @throws AsynchronousCloseException
* if this channel is closed by another thread during this read
* operation.
@@ -413,6 +410,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* if the channel has not been opened in a mode that permits
* reading.
*/
+ @Override
public final long read(ByteBuffer[] buffers) throws IOException {
return read(buffers, 0, buffers.length);
}
@@ -433,7 +431,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* the index of the first buffer to store bytes in.
* @param number
* the maximum number of buffers to store bytes in.
- * @return the number of bytes actually read.
+ * @return the number of bytes actually read, or -1 if the end of the file has been reached.
* @throws AsynchronousCloseException
* if this channel is closed by another thread during this read
* operation.
@@ -458,7 +456,6 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
/**
* Returns the size of the file underlying this channel in bytes.
*
- * @return the size of the file in bytes.
* @throws ClosedChannelException
* if this channel is closed.
* @throws IOException
@@ -712,6 +709,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* @throws NonWritableChannelException
* if this channel was not opened for writing.
*/
+ @Override
public final long write(ByteBuffer[] buffers) throws IOException {
return write(buffers, 0, buffers.length);
}
@@ -752,6 +750,7 @@ public abstract class FileChannel extends AbstractInterruptibleChannel
* @throws NonWritableChannelException
* if this channel was not opened for writing.
*/
+ @Override
public abstract long write(ByteBuffer[] buffers, int offset, int length)
throws IOException;
}
diff --git a/luni/src/main/java/java/nio/channels/FileLock.java b/luni/src/main/java/java/nio/channels/FileLock.java
index 360f826..5b26475 100644
--- a/luni/src/main/java/java/nio/channels/FileLock.java
+++ b/luni/src/main/java/java/nio/channels/FileLock.java
@@ -108,8 +108,6 @@ public abstract class FileLock implements AutoCloseable {
/**
* Returns the lock's {@link FileChannel}.
- *
- * @return the channel.
*/
public final FileChannel channel() {
return channel;
diff --git a/luni/src/main/java/java/nio/channels/ServerSocketChannel.java b/luni/src/main/java/java/nio/channels/ServerSocketChannel.java
index f3c3390..ef50155 100644
--- a/luni/src/main/java/java/nio/channels/ServerSocketChannel.java
+++ b/luni/src/main/java/java/nio/channels/ServerSocketChannel.java
@@ -19,8 +19,10 @@ package java.nio.channels;
import java.io.IOException;
import java.net.ServerSocket;
+import java.net.SocketAddress;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.SelectorProvider;
+import java.util.Set;
/**
* A {@code ServerSocketChannel} is a partial abstraction of a selectable,
@@ -35,7 +37,6 @@ import java.nio.channels.spi.SelectorProvider;
* related {@code ServerSocket} instance.
*/
public abstract class ServerSocketChannel extends AbstractSelectableChannel {
-
/**
* Constructs a new {@link ServerSocketChannel}.
*
diff --git a/luni/src/main/java/java/nio/channels/SocketChannel.java b/luni/src/main/java/java/nio/channels/SocketChannel.java
index 753c88f..a91fccd 100644
--- a/luni/src/main/java/java/nio/channels/SocketChannel.java
+++ b/luni/src/main/java/java/nio/channels/SocketChannel.java
@@ -23,36 +23,44 @@ import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.SelectorProvider;
+import java.util.Set;
/**
* A {@code SocketChannel} is a selectable channel that provides a partial
- * abstraction of stream connecting socket. {@code socket()} returns the related
- * {@link Socket} instance which can handle the socket.
- * <p>
- * A socket channel is open but not connected when created by {@code open()}.
- * After connecting it by calling {@code connect(SocketAddress)}, it will remain
- * connected until it gets closed. If the connection is non-blocking then
- * {@code connect(SocketAddress)} is used to initiate the connection, followed
- * by a call of {@code finishConnect()} to perform the final steps of
- * connecting. {@code isConnectionPending()} indicates if the connection is
- * blocked or not; {@code isConnected()} indicates if the socket is finally
- * connected or not.
- * <p>
- * The input and output sides of a channel can be shut down independently and
- * asynchronously without closing the channel. The {@code shutdownInput} method
+ * abstraction of stream connecting socket.
+ *
+ * The {@link #socket()} method returns a {@link Socket} instance which
+ * allows a wider range of socket operations than {@code SocketChannel} itself.
+ *
+ * <p>A socket channel is open but not connected when created by {@link #open}.
+ * After connecting it by calling {@link #connect(SocketAddress)}, it will remain
+ * connected until closed.
+ *
+ * <p>If the connection is non-blocking then
+ * {@link #connect(SocketAddress)} is used to initiate the connection, followed
+ * by a call of {@link #finishConnect} to perform the final steps of
+ * connecting. {@link #isConnectionPending} to tests whether we're still
+ * trying to connect; {@link #isConnected} tests whether the socket connect
+ * completed successfully. Note that realistic code should use a {@link Selector}
+ * instead of polling. Note also that {@link java.net.Socket} can connect with a
+ * timeout, which is the most common use for a non-blocking connect.
+ *
+ * <p>The input and output sides of a channel can be shut down independently and
+ * asynchronously without closing the channel. The {@link Socket#shutdownInput} method
+ * on the socket returned by {@link #socket}
* is used for the input side of a channel and subsequent read operations return
* -1, which means end of stream. If another thread is blocked in a read
* operation when the shutdown occurs, the read will end without effect and
- * return end of stream. The {@code shutdownOutput} method is used for the
+ * return end of stream. Likewise the {@link Socket#shutdownOutput} method is used for the
* output side of the channel; subsequent write operations throw a
* {@link ClosedChannelException}. If the output is shut down and another thread
* is blocked in a write operation, an {@link AsynchronousCloseException} will
* be thrown to the pending thread.
- * <p>
- * Socket channels are thread-safe, no more than one thread can read or write at
- * any given time. The {@code connect(SocketAddress)} and {@code
- * finishConnect()} methods are synchronized against each other; when they are
- * processing, calls to {@code read} and {@code write} will block.
+ *
+ * <p>Socket channels are thread-safe, no more than one thread can read or write at
+ * any given time. The {@link #connect(SocketAddress)} and {@link
+ * #finishConnect()} methods are synchronized against each other; when they are
+ * processing, calls to {@link #read} and {@link #write} will block.
*/
public abstract class SocketChannel extends AbstractSelectableChannel implements
ByteChannel, ScatteringByteChannel, GatheringByteChannel {
diff --git a/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java b/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java
index 8b32efa..5dfdd9f 100644
--- a/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java
+++ b/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java
@@ -25,13 +25,13 @@ final class CharsetDecoderICU extends CharsetDecoder {
private static final int INPUT_OFFSET = 0;
private static final int OUTPUT_OFFSET = 1;
- private static final int INVALID_BYTES = 2;
+ private static final int INVALID_BYTE_COUNT = 2;
/*
* data[INPUT_OFFSET] = on input contains the start of input and on output the number of input bytes consumed
* data[OUTPUT_OFFSET] = on input contains the start of output and on output the number of output chars written
- * data[INVALID_BYTES] = number of invalid bytes
+ * data[INVALID_BYTE_COUNT] = number of invalid bytes
*/
- private int[] data = new int[3];
+ private final int[] data = new int[3];
/* handle to the ICU converter that is opened */
private long converterHandle = 0;
@@ -90,7 +90,7 @@ final class CharsetDecoderICU extends CharsetDecoder {
NativeConverter.resetByteToChar(converterHandle);
data[INPUT_OFFSET] = 0;
data[OUTPUT_OFFSET] = 0;
- data[INVALID_BYTES] = 0;
+ data[INVALID_BYTE_COUNT] = 0;
output = null;
input = null;
allocatedInput = null;
@@ -107,15 +107,15 @@ final class CharsetDecoderICU extends CharsetDecoder {
data[INPUT_OFFSET] = 0;
data[OUTPUT_OFFSET] = getArray(out);
- data[INVALID_BYTES] = 0; // Make sure we don't see earlier errors.
+ data[INVALID_BYTE_COUNT] = 0; // Make sure we don't see earlier errors.
int error = NativeConverter.decode(converterHandle, input, inEnd, output, outEnd, data, true);
if (ICU.U_FAILURE(error)) {
if (error == ICU.U_BUFFER_OVERFLOW_ERROR) {
return CoderResult.OVERFLOW;
} else if (error == ICU.U_TRUNCATED_CHAR_FOUND) {
- if (data[INPUT_OFFSET] > 0) {
- return CoderResult.malformedForLength(data[INPUT_OFFSET]);
+ if (data[INVALID_BYTE_COUNT] > 0) {
+ return CoderResult.malformedForLength(data[INVALID_BYTE_COUNT]);
}
}
}
@@ -140,9 +140,9 @@ final class CharsetDecoderICU extends CharsetDecoder {
if (error == ICU.U_BUFFER_OVERFLOW_ERROR) {
return CoderResult.OVERFLOW;
} else if (error == ICU.U_INVALID_CHAR_FOUND) {
- return CoderResult.unmappableForLength(data[INVALID_BYTES]);
+ return CoderResult.unmappableForLength(data[INVALID_BYTE_COUNT]);
} else if (error == ICU.U_ILLEGAL_CHAR_FOUND) {
- return CoderResult.malformedForLength(data[INVALID_BYTES]);
+ return CoderResult.malformedForLength(data[INVALID_BYTE_COUNT]);
} else {
throw new AssertionError(error);
}
diff --git a/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java b/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java
index 4bc4354..3583e19 100644
--- a/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java
+++ b/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java
@@ -40,7 +40,7 @@ final class CharsetEncoderICU extends CharsetEncoder {
private static final int INPUT_OFFSET = 0;
private static final int OUTPUT_OFFSET = 1;
- private static final int INVALID_CHARS = 2;
+ private static final int INVALID_CHAR_COUNT = 2;
/*
* data[INPUT_OFFSET] = on input contains the start of input and on output the number of input chars consumed
* data[OUTPUT_OFFSET] = on input contains the start of output and on output the number of output bytes written
@@ -118,7 +118,7 @@ final class CharsetEncoderICU extends CharsetEncoder {
NativeConverter.resetCharToByte(converterHandle);
data[INPUT_OFFSET] = 0;
data[OUTPUT_OFFSET] = 0;
- data[INVALID_CHARS] = 0;
+ data[INVALID_CHAR_COUNT] = 0;
output = null;
input = null;
allocatedInput = null;
@@ -135,15 +135,15 @@ final class CharsetEncoderICU extends CharsetEncoder {
data[INPUT_OFFSET] = 0;
data[OUTPUT_OFFSET] = getArray(out);
- data[INVALID_CHARS] = 0; // Make sure we don't see earlier errors.
+ data[INVALID_CHAR_COUNT] = 0; // Make sure we don't see earlier errors.
int error = NativeConverter.encode(converterHandle, input, inEnd, output, outEnd, data, true);
if (ICU.U_FAILURE(error)) {
if (error == ICU.U_BUFFER_OVERFLOW_ERROR) {
return CoderResult.OVERFLOW;
} else if (error == ICU.U_TRUNCATED_CHAR_FOUND) {
- if (data[INPUT_OFFSET] > 0) {
- return CoderResult.malformedForLength(data[INPUT_OFFSET]);
+ if (data[INVALID_CHAR_COUNT] > 0) {
+ return CoderResult.malformedForLength(data[INVALID_CHAR_COUNT]);
}
}
}
@@ -161,7 +161,7 @@ final class CharsetEncoderICU extends CharsetEncoder {
data[INPUT_OFFSET] = getArray(in);
data[OUTPUT_OFFSET]= getArray(out);
- data[INVALID_CHARS] = 0; // Make sure we don't see earlier errors.
+ data[INVALID_CHAR_COUNT] = 0; // Make sure we don't see earlier errors.
try {
int error = NativeConverter.encode(converterHandle, input, inEnd, output, outEnd, data, false);
@@ -169,9 +169,9 @@ final class CharsetEncoderICU extends CharsetEncoder {
if (error == ICU.U_BUFFER_OVERFLOW_ERROR) {
return CoderResult.OVERFLOW;
} else if (error == ICU.U_INVALID_CHAR_FOUND) {
- return CoderResult.unmappableForLength(data[INVALID_CHARS]);
+ return CoderResult.unmappableForLength(data[INVALID_CHAR_COUNT]);
} else if (error == ICU.U_ILLEGAL_CHAR_FOUND) {
- return CoderResult.malformedForLength(data[INVALID_CHARS]);
+ return CoderResult.malformedForLength(data[INVALID_CHAR_COUNT]);
} else {
throw new AssertionError(error);
}
@@ -231,7 +231,7 @@ final class CharsetEncoderICU extends CharsetEncoder {
private void setPosition(ByteBuffer out) {
if (out.hasArray()) {
- out.position(out.position() + data[OUTPUT_OFFSET] - out.arrayOffset());
+ out.position(data[OUTPUT_OFFSET] - out.arrayOffset());
} else {
out.put(output, 0, data[OUTPUT_OFFSET]);
}
@@ -240,7 +240,17 @@ final class CharsetEncoderICU extends CharsetEncoder {
}
private void setPosition(CharBuffer in) {
- in.position(in.position() + data[INPUT_OFFSET] - data[INVALID_CHARS]);
+ int position = in.position() + data[INPUT_OFFSET] - data[INVALID_CHAR_COUNT];
+ if (position < 0) {
+ // The calculated position might be negative if we encountered an
+ // invalid char that spanned input buffers. We adjust it to 0 in this case.
+ //
+ // NOTE: The API doesn't allow us to adjust the position of the previous
+ // input buffer. (Doing that wouldn't serve any useful purpose anyway.)
+ position = 0;
+ }
+
+ in.position(position);
// release reference to input array, which may not be ours
input = null;
}
diff --git a/luni/src/main/java/java/security/AlgorithmParameterGenerator.java b/luni/src/main/java/java/security/AlgorithmParameterGenerator.java
index 61548d7..167204c 100644
--- a/luni/src/main/java/java/security/AlgorithmParameterGenerator.java
+++ b/luni/src/main/java/java/security/AlgorithmParameterGenerator.java
@@ -129,7 +129,8 @@ public class AlgorithmParameterGenerator {
/**
* Returns a new instance of {@code AlgorithmParameterGenerator} from the
- * specified provider for the specified algorithm.
+ * specified provider for the specified algorithm. The {@code provider}
+ * supplied does not have to be registered.
*
* @param algorithm
* the name of the algorithm to use.
diff --git a/luni/src/main/java/java/security/AlgorithmParameters.java b/luni/src/main/java/java/security/AlgorithmParameters.java
index 073460e..27af018 100644
--- a/luni/src/main/java/java/security/AlgorithmParameters.java
+++ b/luni/src/main/java/java/security/AlgorithmParameters.java
@@ -131,7 +131,8 @@ public class AlgorithmParameters {
/**
* Returns a new instance of {@code AlgorithmParameters} from the specified
- * provider for the specified algorithm.
+ * provider for the specified algorithm. The {@code provider} supplied does
+ * not have to be registered.
*
* @param algorithm
* the name of the algorithm to use.
diff --git a/luni/src/main/java/java/security/GuardedObject.java b/luni/src/main/java/java/security/GuardedObject.java
index 34a5113..dd2e98f 100644
--- a/luni/src/main/java/java/security/GuardedObject.java
+++ b/luni/src/main/java/java/security/GuardedObject.java
@@ -53,7 +53,7 @@ public class GuardedObject implements Serializable {
* SecurityException} is thrown.
*
* @return the guarded object.
- * @exception SecurityException
+ * @throws SecurityException
* if access is not granted to the guarded object.
*/
public Object getObject() throws SecurityException {
diff --git a/luni/src/main/java/java/security/KeyFactory.java b/luni/src/main/java/java/security/KeyFactory.java
index 3bd05b9..c22212f 100644
--- a/luni/src/main/java/java/security/KeyFactory.java
+++ b/luni/src/main/java/java/security/KeyFactory.java
@@ -112,7 +112,8 @@ public class KeyFactory {
/**
* Returns a new instance of {@code KeyFactory} that utilizes the specified
- * algorithm from the specified provider.
+ * algorithm from the specified provider. The {@code provider} supplied
+ * does not have to be registered.
*
* @param algorithm
* the name of the algorithm.
diff --git a/luni/src/main/java/java/security/KeyPairGenerator.java b/luni/src/main/java/java/security/KeyPairGenerator.java
index 8a713d0..d05e902 100644
--- a/luni/src/main/java/java/security/KeyPairGenerator.java
+++ b/luni/src/main/java/java/security/KeyPairGenerator.java
@@ -124,7 +124,8 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi {
/**
* Returns a new instance of {@code KeyPairGenerator} that utilizes the
- * specified algorithm from the specified provider.
+ * specified algorithm from the specified provider. The {@code provider}
+ * supplied does not have to be registered.
*
* @param algorithm
* the name of the algorithm to use
diff --git a/luni/src/main/java/java/security/KeyStore.java b/luni/src/main/java/java/security/KeyStore.java
index b0e4945..0611e59 100644
--- a/luni/src/main/java/java/security/KeyStore.java
+++ b/luni/src/main/java/java/security/KeyStore.java
@@ -159,7 +159,8 @@ public class KeyStore {
/**
* Returns a new instance of {@code KeyStore} from the specified provider
- * with the given type.
+ * with the given type. The {@code provider} supplied does not have to be
+ * registered.
*
* @param type
* the type of the returned {@code KeyStore}.
diff --git a/luni/src/main/java/java/security/MessageDigest.java b/luni/src/main/java/java/security/MessageDigest.java
index 658b41f..1d37a90 100644
--- a/luni/src/main/java/java/security/MessageDigest.java
+++ b/luni/src/main/java/java/security/MessageDigest.java
@@ -132,7 +132,8 @@ public abstract class MessageDigest extends MessageDigestSpi {
/**
* Returns a new instance of {@code MessageDigest} that utilizes the
- * specified algorithm from the specified provider.
+ * specified algorithm from the specified provider. The
+ * {@code provider} supplied does not have to be registered.
*
* @param algorithm
* the name of the algorithm to use
@@ -302,12 +303,12 @@ public abstract class MessageDigest extends MessageDigestSpi {
if (digesta.length != digestb.length) {
return false;
}
+ // Perform a constant time comparison to avoid timing attacks.
+ int v = 0;
for (int i = 0; i < digesta.length; i++) {
- if (digesta[i] != digestb[i]) {
- return false;
- }
+ v |= (digesta[i] ^ digestb[i]);
}
- return true;
+ return v == 0;
}
/**
@@ -351,14 +352,6 @@ public abstract class MessageDigest extends MessageDigestSpi {
}
}
- @Override
- public Object clone() throws CloneNotSupportedException {
- if (this instanceof Cloneable) {
- return super.clone();
- }
- throw new CloneNotSupportedException();
- }
-
/**
* Updates this {@code MessageDigest} using the given {@code input}.
*
@@ -420,12 +413,8 @@ public abstract class MessageDigest extends MessageDigestSpi {
// Returns a clone if the spiImpl is cloneable
@Override
public Object clone() throws CloneNotSupportedException {
- if (spiImpl instanceof Cloneable) {
- MessageDigestSpi spi = (MessageDigestSpi) spiImpl.clone();
- return new MessageDigestImpl(spi, getProvider(), getAlgorithm());
- }
-
- throw new CloneNotSupportedException();
+ MessageDigestSpi spi = (MessageDigestSpi) spiImpl.clone();
+ return new MessageDigestImpl(spi, getProvider(), getAlgorithm());
}
}
}
diff --git a/luni/src/main/java/java/security/Provider.java b/luni/src/main/java/java/security/Provider.java
index a6de19c..1704b58 100644
--- a/luni/src/main/java/java/security/Provider.java
+++ b/luni/src/main/java/java/security/Provider.java
@@ -804,6 +804,79 @@ public abstract class Provider extends Properties {
* provider it belongs and other properties.
*/
public static class Service {
+ /** Attribute name of supported key classes. */
+ private static final String ATTR_SUPPORTED_KEY_CLASSES = "SupportedKeyClasses";
+
+ /** Attribute name of supported key formats. */
+ private static final String ATTR_SUPPORTED_KEY_FORMATS = "SupportedKeyFormats";
+
+ /** Whether this type supports calls to {@link #supportsParameter(Object)}. */
+ private static final HashMap<String, Boolean> supportsParameterTypes
+ = new HashMap<String, Boolean>();
+ static {
+ // Does not support parameter
+ supportsParameterTypes.put("AlgorithmParameterGenerator", false);
+ supportsParameterTypes.put("AlgorithmParameters", false);
+ supportsParameterTypes.put("CertificateFactory", false);
+ supportsParameterTypes.put("CertPathBuilder", false);
+ supportsParameterTypes.put("CertPathValidator", false);
+ supportsParameterTypes.put("CertStore", false);
+ supportsParameterTypes.put("KeyFactory", false);
+ supportsParameterTypes.put("KeyGenerator", false);
+ supportsParameterTypes.put("KeyManagerFactory", false);
+ supportsParameterTypes.put("KeyPairGenerator", false);
+ supportsParameterTypes.put("KeyStore", false);
+ supportsParameterTypes.put("MessageDigest", false);
+ supportsParameterTypes.put("SecretKeyFactory", false);
+ supportsParameterTypes.put("SecureRandom", false);
+ supportsParameterTypes.put("SSLContext", false);
+ supportsParameterTypes.put("TrustManagerFactory", false);
+
+ // Supports parameter
+ supportsParameterTypes.put("Cipher", true);
+ supportsParameterTypes.put("KeyAgreement", true);
+ supportsParameterTypes.put("Mac", true);
+ supportsParameterTypes.put("Signature", true);
+ }
+
+ /** Constructor argument classes for calls to {@link #newInstance(Object)}. */
+ private static final HashMap<String, Class<?>> constructorParameterClasses = new HashMap<String, Class<?>>();
+ static {
+ // Types that take a parameter to newInstance
+ constructorParameterClasses.put("CertStore",
+ loadClassOrThrow("java.security.cert.CertStoreParameters"));
+
+ // Types that do not take any kind of parameter
+ constructorParameterClasses.put("AlgorithmParameterGenerator", null);
+ constructorParameterClasses.put("AlgorithmParameters", null);
+ constructorParameterClasses.put("CertificateFactory", null);
+ constructorParameterClasses.put("CertPathBuilder", null);
+ constructorParameterClasses.put("CertPathValidator", null);
+ constructorParameterClasses.put("KeyFactory", null);
+ constructorParameterClasses.put("KeyGenerator", null);
+ constructorParameterClasses.put("KeyManagerFactory", null);
+ constructorParameterClasses.put("KeyPairGenerator", null);
+ constructorParameterClasses.put("KeyStore", null);
+ constructorParameterClasses.put("MessageDigest", null);
+ constructorParameterClasses.put("SecretKeyFactory", null);
+ constructorParameterClasses.put("SecureRandom", null);
+ constructorParameterClasses.put("SSLContext", null);
+ constructorParameterClasses.put("TrustManagerFactory", null);
+ constructorParameterClasses.put("Cipher", null);
+ constructorParameterClasses.put("KeyAgreement", null);
+ constructorParameterClasses.put("Mac", null);
+ constructorParameterClasses.put("Signature", null);
+ }
+
+ /** Called to load a class if it's critical that the class exists. */
+ private static Class<?> loadClassOrThrow(String className) {
+ try {
+ return Provider.class.getClassLoader().loadClass(className);
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ }
+
// The provider
private Provider provider;
@@ -828,6 +901,15 @@ public abstract class Provider extends Properties {
// For newInstance() optimization
private String lastClassName;
+ /** Indicates whether supportedKeyClasses and supportedKeyFormats. */
+ private volatile boolean supportedKeysInitialized;
+
+ /** List of classes that this service supports. */
+ private Class<?>[] keyClasses;
+
+ /** List of key formats this service supports. */
+ private String[] keyFormats;
+
/**
* Constructs a new instance of {@code Service} with the given
* attributes.
@@ -993,28 +1075,52 @@ public abstract class Provider extends Properties {
throw new NoSuchAlgorithmException(type + " " + algorithm + " implementation not found: " + e);
}
}
- if (constructorParameter == null) {
- try {
- return implementation.newInstance();
- } catch (Exception e) {
- throw new NoSuchAlgorithmException(
- type + " " + algorithm + " implementation not found", e);
+
+ // We don't know whether this takes a parameter or not.
+ if (!constructorParameterClasses.containsKey(type)) {
+ if (constructorParameter == null) {
+ return newInstanceNoParameter();
+ } else {
+ return newInstanceWithParameter(constructorParameter,
+ constructorParameter.getClass());
}
}
- if (!supportsParameter(constructorParameter)) {
- throw new InvalidParameterException(type + ": service cannot use the parameter");
+
+ // A known type, but it's not required to have a parameter even if a
+ // class is specified.
+ if (constructorParameter == null) {
+ return newInstanceNoParameter();
}
- Class[] parameterTypes = new Class[1];
- Object[] initargs = { constructorParameter };
+ // Make sure the provided constructor class is valid.
+ final Class<?> expectedClass = constructorParameterClasses.get(type);
+ if (expectedClass == null) {
+ throw new IllegalArgumentException("Constructor parameter not supported for "
+ + type);
+ }
+ if (!expectedClass.isAssignableFrom(constructorParameter.getClass())) {
+ throw new IllegalArgumentException("Expecting constructor parameter of type "
+ + expectedClass.getName() + " but was "
+ + constructorParameter.getClass().getName());
+ }
+ return newInstanceWithParameter(constructorParameter, expectedClass);
+ }
+
+ private Object newInstanceWithParameter(Object constructorParameter,
+ Class<?> parameterClass) throws NoSuchAlgorithmException {
try {
- if (type.equalsIgnoreCase("CertStore")) {
- parameterTypes[0] = Class.forName("java.security.cert.CertStoreParameters");
- } else {
- parameterTypes[0] = constructorParameter.getClass();
- }
- return implementation.getConstructor(parameterTypes)
- .newInstance(initargs);
+ Class<?>[] parameterTypes = { parameterClass };
+ Object[] initargs = { constructorParameter };
+ return implementation.getConstructor(parameterTypes).newInstance(initargs);
+ } catch (Exception e) {
+ throw new NoSuchAlgorithmException(type + " " + algorithm
+ + " implementation not found", e);
+ }
+ }
+
+ private Object newInstanceNoParameter() throws NoSuchAlgorithmException {
+ try {
+ return implementation.newInstance();
} catch (Exception e) {
throw new NoSuchAlgorithmException(type + " " + algorithm
+ " implementation not found", e);
@@ -1031,7 +1137,111 @@ public abstract class Provider extends Properties {
* constructor parameter, {@code false} otherwise.
*/
public boolean supportsParameter(Object parameter) {
- return true;
+ Boolean supportsParameter = supportsParameterTypes.get(type);
+ if (supportsParameter == null) {
+ return true;
+ }
+ if (!supportsParameter) {
+ throw new InvalidParameterException("Cannot use a parameter with " + type);
+ }
+
+ /*
+ * Only Key parameters are allowed, but allow null since there might
+ * not be any listed classes or formats for this instance.
+ */
+ if (parameter != null && !(parameter instanceof Key)) {
+ throw new InvalidParameterException("Parameter should be of type Key");
+ }
+
+ ensureSupportedKeysInitialized();
+
+ // No restriction specified by Provider registration.
+ if (keyClasses == null && keyFormats == null) {
+ return true;
+ }
+
+ // Restriction specified by registration, so null is not acceptable.
+ if (parameter == null) {
+ return false;
+ }
+
+ Key keyParam = (Key) parameter;
+ if (keyClasses != null && isInArray(keyClasses, keyParam.getClass())) {
+ return true;
+ }
+ if (keyFormats != null && isInArray(keyFormats, keyParam.getFormat())) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Initialize the list of supported key classes and formats.
+ */
+ private void ensureSupportedKeysInitialized() {
+ if (supportedKeysInitialized) {
+ return;
+ }
+
+ final String supportedClassesString = getAttribute(ATTR_SUPPORTED_KEY_CLASSES);
+ if (supportedClassesString != null) {
+ String[] keyClassNames = supportedClassesString.split("\\|");
+ ArrayList<Class<?>> supportedClassList = new ArrayList<Class<?>>(
+ keyClassNames.length);
+ final ClassLoader classLoader = getProvider().getClass().getClassLoader();
+ for (String keyClassName : keyClassNames) {
+ try {
+ Class<?> keyClass = classLoader.loadClass(keyClassName);
+ if (Key.class.isAssignableFrom(keyClass)) {
+ supportedClassList.add(keyClass);
+ }
+ } catch (ClassNotFoundException ignored) {
+ }
+ }
+ keyClasses = supportedClassList.toArray(new Class<?>[supportedClassList.size()]);
+ }
+
+ final String supportedFormatString = getAttribute(ATTR_SUPPORTED_KEY_FORMATS);
+ if (supportedFormatString != null) {
+ keyFormats = supportedFormatString.split("\\|");
+ }
+
+ supportedKeysInitialized = true;
+ }
+
+ /**
+ * Check if an item is in the array. The array of supported key classes
+ * and formats is usually just a length of 1, so a simple array is
+ * faster than a Set.
+ */
+ private static <T> boolean isInArray(T[] itemList, T target) {
+ if (target == null) {
+ return false;
+ }
+ for (T item : itemList) {
+ if (target.equals(item)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check if an item is in the array. The array of supported key classes
+ * and formats is usually just a length of 1, so a simple array is
+ * faster than a Set.
+ */
+ private static boolean isInArray(Class<?>[] itemList, Class<?> target) {
+ if (target == null) {
+ return false;
+ }
+ for (Class<?> item : itemList) {
+ if (item.isAssignableFrom(target)) {
+ return true;
+ }
+ }
+ return false;
}
/**
diff --git a/luni/src/main/java/java/security/SecureRandom.java b/luni/src/main/java/java/security/SecureRandom.java
index 281885b..7a03801 100644
--- a/luni/src/main/java/java/security/SecureRandom.java
+++ b/luni/src/main/java/java/security/SecureRandom.java
@@ -46,8 +46,8 @@ import org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl;
* For deriving keys from passwords, see
* {@link javax.crypto.SecretKeyFactory}.
*
- * <h3><a name="insecure_seed">Seeding {@code SecureRandom} may be
- * insecure</a></h3>
+ * <h3><a name="insecure_seed"></a>Seeding {@code SecureRandom} may be
+ * insecure</h3>
* A seed is an array of bytes used to bootstrap random number generation.
* To produce cryptographically secure random numbers, both the seed and the
* algorithm must be secure.
@@ -190,7 +190,8 @@ public class SecureRandom extends Random {
/**
* Returns a new instance of {@code SecureRandom} that utilizes the
- * specified algorithm from the specified provider.
+ * specified algorithm from the specified provider. The
+ * {@code provider} supplied does not have to be registered.
*
* @param algorithm
* the name of the algorithm to use.
diff --git a/luni/src/main/java/java/security/Security.java b/luni/src/main/java/java/security/Security.java
index 0b6961b..b859f9a 100644
--- a/luni/src/main/java/java/security/Security.java
+++ b/luni/src/main/java/java/security/Security.java
@@ -19,6 +19,7 @@ package java.security;
import java.io.BufferedInputStream;
import java.io.InputStream;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
@@ -72,10 +73,9 @@ public final class Security {
// Register default providers
private static void registerDefaultProviders() {
secprops.put("security.provider.1", "com.android.org.conscrypt.OpenSSLProvider");
- secprops.put("security.provider.2", "org.apache.harmony.security.provider.cert.DRLCertFactory");
- secprops.put("security.provider.3", "com.android.org.bouncycastle.jce.provider.BouncyCastleProvider");
- secprops.put("security.provider.4", "org.apache.harmony.security.provider.crypto.CryptoProvider");
- secprops.put("security.provider.5", "com.android.org.conscrypt.JSSEProvider");
+ secprops.put("security.provider.2", "com.android.org.bouncycastle.jce.provider.BouncyCastleProvider");
+ secprops.put("security.provider.3", "org.apache.harmony.security.provider.crypto.CryptoProvider");
+ secprops.put("security.provider.4", "com.android.org.conscrypt.JSSEProvider");
}
/**
@@ -96,7 +96,7 @@ public final class Security {
String prop = "Alg." + propName + "." + algName;
Provider[] providers = getProviders();
for (Provider provider : providers) {
- for (Enumeration e = provider.propertyNames(); e.hasMoreElements(); ) {
+ for (Enumeration<?> e = provider.propertyNames(); e.hasMoreElements();) {
String propertyName = (String) e.nextElement();
if (propertyName.equalsIgnoreCase(prop)) {
return provider.getProperty(propertyName);
@@ -184,7 +184,8 @@ public final class Security {
* @return an array containing all installed providers.
*/
public static synchronized Provider[] getProviders() {
- return Services.getProviders();
+ ArrayList<Provider> providers = Services.getProviders();
+ return providers.toArray(new Provider[providers.size()]);
}
/**
@@ -274,7 +275,7 @@ public final class Security {
if (filter.isEmpty()) {
return null;
}
- java.util.List<Provider> result = Services.getProvidersList();
+ ArrayList<Provider> result = new ArrayList<Provider>(Services.getProviders());
Set<Entry<String, String>> keys = filter.entrySet();
Map.Entry<String, String> entry;
for (Iterator<Entry<String, String>> it = keys.iterator(); it.hasNext();) {
@@ -306,18 +307,7 @@ public final class Security {
if (serv.length() == 0 || alg.length() == 0) {
throw new InvalidParameterException();
}
- Provider p;
- for (int k = 0; k < result.size(); k++) {
- try {
- p = result.get(k);
- } catch (IndexOutOfBoundsException e) {
- break;
- }
- if (!p.implementsAlg(serv, alg, attribute, val)) {
- result.remove(p);
- k--;
- }
- }
+ filterProviders(result, serv, alg, attribute, val);
}
if (result.size() > 0) {
return result.toArray(new Provider[result.size()]);
@@ -325,6 +315,17 @@ public final class Security {
return null;
}
+ private static void filterProviders(ArrayList<Provider> providers, String service,
+ String algorithm, String attribute, String attrValue) {
+ Iterator<Provider> it = providers.iterator();
+ while (it.hasNext()) {
+ Provider p = it.next();
+ if (!p.implementsAlg(service, algorithm, attribute, attrValue)) {
+ it.remove();
+ }
+ }
+ }
+
/**
* Returns the value of the security property named by the argument.
*
@@ -347,6 +348,7 @@ public final class Security {
* Sets the value of the specified security property.
*/
public static void setProperty(String key, String value) {
+ Services.setNeedRefresh();
secprops.put(key, value);
}
@@ -384,9 +386,9 @@ public final class Security {
*
*/
private static void renumProviders() {
- Provider[] p = Services.getProviders();
- for (int i = 0; i < p.length; i++) {
- p[i].setProviderNumber(i + 1);
+ ArrayList<Provider> providers = Services.getProviders();
+ for (int i = 0; i < providers.size(); i++) {
+ providers.get(i).setProviderNumber(i + 1);
}
}
diff --git a/luni/src/main/java/java/security/Signature.java b/luni/src/main/java/java/security/Signature.java
index 0372c33..a39d59b 100644
--- a/luni/src/main/java/java/security/Signature.java
+++ b/luni/src/main/java/java/security/Signature.java
@@ -21,10 +21,11 @@ import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import org.apache.harmony.security.fortress.Engine;
-
+import org.apache.harmony.security.fortress.Engine.SpiAndProvider;
/**
* {@code Signature} is an engine class which is capable of creating and
@@ -39,13 +40,13 @@ public abstract class Signature extends SignatureSpi {
private static final String SERVICE = "Signature";
// Used to access common engine functionality
- private static Engine ENGINE = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// The provider
- private Provider provider;
+ Provider provider;
// The algorithm.
- private String algorithm;
+ final String algorithm;
/**
* Constant that indicates that this {@code Signature} instance has not yet
@@ -101,16 +102,7 @@ public abstract class Signature extends SignatureSpi {
if (algorithm == null) {
throw new NullPointerException("algorithm == null");
}
- Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
- Object spi = sap.spi;
- Provider provider = sap.provider;
- if (spi instanceof Signature) {
- Signature result = (Signature) spi;
- result.algorithm = algorithm;
- result.provider = provider;
- return result;
- }
- return new SignatureImpl((SignatureSpi) spi, provider, algorithm);
+ return getSignature(algorithm, null);
}
/**
@@ -143,12 +135,13 @@ public abstract class Signature extends SignatureSpi {
if (p == null) {
throw new NoSuchProviderException(provider);
}
- return getSignatureInstance(algorithm, p);
+ return getSignature(algorithm, p);
}
/**
* Returns a new instance of {@code Signature} that utilizes the specified
- * algorithm from the specified provider.
+ * algorithm from the specified provider. The {@code provider} supplied
+ * does not have to be registered.
*
* @param algorithm
* the name of the algorithm to use.
@@ -170,19 +163,68 @@ public abstract class Signature extends SignatureSpi {
if (provider == null) {
throw new IllegalArgumentException("provider == null");
}
- return getSignatureInstance(algorithm, provider);
+ return getSignature(algorithm, provider);
+ }
+
+ private static Signature getSignature(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException {
+ if (algorithm == null || algorithm.isEmpty()) {
+ throw new NoSuchAlgorithmException("Unknown algorithm: " + algorithm);
+ }
+
+ SpiAndProvider spiAndProvider = tryAlgorithm(null, provider, algorithm);
+ if (spiAndProvider == null) {
+ if (provider == null) {
+ throw new NoSuchAlgorithmException("No provider found for " + algorithm);
+ } else {
+ throw new NoSuchAlgorithmException("Provider " + provider.getName()
+ + " does not provide " + algorithm);
+ }
+ }
+ if (spiAndProvider.spi instanceof Signature) {
+ return (Signature) spiAndProvider.spi;
+ }
+ return new SignatureImpl(algorithm, provider);
+ }
+
+ private static Engine.SpiAndProvider tryAlgorithm(Key key, Provider provider, String algorithm) {
+ if (provider != null) {
+ Provider.Service service = provider.getService(SERVICE, algorithm);
+ if (service == null) {
+ return null;
+ }
+ return tryAlgorithmWithProvider(key, service);
+ }
+ ArrayList<Provider.Service> services = ENGINE.getServices(algorithm);
+ if (services == null) {
+ return null;
+ }
+ for (Provider.Service service : services) {
+ Engine.SpiAndProvider sap = tryAlgorithmWithProvider(key, service);
+ if (sap != null) {
+ return sap;
+ }
+ }
+ return null;
}
- private static Signature getSignatureInstance(String algorithm,
- Provider provider) throws NoSuchAlgorithmException {
- Object spi = ENGINE.getInstance(algorithm, provider, null);
- if (spi instanceof Signature) {
- Signature result = (Signature) spi;
- result.algorithm = algorithm;
- result.provider = provider;
- return result;
+ private static Engine.SpiAndProvider tryAlgorithmWithProvider(Key key, Provider.Service service) {
+ try {
+ if (key != null && !service.supportsParameter(key)) {
+ return null;
+ }
+
+ Engine.SpiAndProvider sap = ENGINE.getInstance(service, null);
+ if (sap.spi == null || sap.provider == null) {
+ return null;
+ }
+ if (!(sap.spi instanceof SignatureSpi)) {
+ return null;
+ }
+ return sap;
+ } catch (NoSuchAlgorithmException ignored) {
}
- return new SignatureImpl((SignatureSpi) spi, provider, algorithm);
+ return null;
}
/**
@@ -191,10 +233,18 @@ public abstract class Signature extends SignatureSpi {
* @return the provider associated with this {@code Signature}.
*/
public final Provider getProvider() {
+ ensureProviderChosen();
return provider;
}
/**
+ * This makes sure the provider is chosen since Signature is abstract and
+ * getProvider is final but we need to support late binding.
+ */
+ void ensureProviderChosen() {
+ }
+
+ /**
* Returns the name of the algorithm of this {@code Signature}.
*
* @return the name of the algorithm of this {@code Signature}.
@@ -237,10 +287,10 @@ public abstract class Signature extends SignatureSpi {
public final void initVerify(Certificate certificate)
throws InvalidKeyException {
if (certificate instanceof X509Certificate) {
- Set ce = ((X509Certificate) certificate).getCriticalExtensionOIDs();
+ Set<String> ce = ((X509Certificate) certificate).getCriticalExtensionOIDs();
boolean critical = false;
if (ce != null && !ce.isEmpty()) {
- for (Iterator i = ce.iterator(); i.hasNext();) {
+ for (Iterator<String> i = ce.iterator(); i.hasNext();) {
if ("2.5.29.15".equals(i.next())) {
//KeyUsage OID = 2.5.29.15
critical = true;
@@ -574,92 +624,115 @@ public abstract class Signature extends SignatureSpi {
return engineGetParameter(param);
}
- @Override
- public Object clone() throws CloneNotSupportedException {
- if (this instanceof Cloneable) {
- return super.clone();
- }
- throw new CloneNotSupportedException();
- }
-
/**
- *
* Internal Signature implementation
- *
*/
private static class SignatureImpl extends Signature {
+ /**
+ * Lock held while the SPI is initializing.
+ */
+ private final Object initLock = new Object();
+
+ // The provider specified when creating this instance.
+ private final Provider specifiedProvider;
+
private SignatureSpi spiImpl;
- // Constructor
- public SignatureImpl(SignatureSpi signatureSpi, Provider provider,
- String algorithm) {
+ public SignatureImpl(String algorithm, Provider provider) {
super(algorithm);
- super.provider = provider;
- spiImpl = signatureSpi;
+ this.specifiedProvider = provider;
+ }
+
+ private SignatureImpl(String algorithm, Provider provider, SignatureSpi spi) {
+ this(algorithm, provider);
+ spiImpl = spi;
+ }
+
+ @Override
+ void ensureProviderChosen() {
+ getSpi(null);
}
- // engineSign() implementation
@Override
protected byte[] engineSign() throws SignatureException {
- return spiImpl.engineSign();
+ return getSpi().engineSign();
}
- // engineUpdate() implementation
@Override
protected void engineUpdate(byte arg0) throws SignatureException {
- spiImpl.engineUpdate(arg0);
+ getSpi().engineUpdate(arg0);
}
- // engineVerify() implementation
@Override
protected boolean engineVerify(byte[] arg0) throws SignatureException {
- return spiImpl.engineVerify(arg0);
+ return getSpi().engineVerify(arg0);
}
- // engineUpdate() implementation
@Override
- protected void engineUpdate(byte[] arg0, int arg1, int arg2)
- throws SignatureException {
- spiImpl.engineUpdate(arg0, arg1, arg2);
+ protected void engineUpdate(byte[] arg0, int arg1, int arg2) throws SignatureException {
+ getSpi().engineUpdate(arg0, arg1, arg2);
}
- // engineInitSign() implementation
@Override
- protected void engineInitSign(PrivateKey arg0)
- throws InvalidKeyException {
- spiImpl.engineInitSign(arg0);
+ protected void engineInitSign(PrivateKey arg0) throws InvalidKeyException {
+ getSpi(arg0).engineInitSign(arg0);
}
- // engineInitVerify() implementation
@Override
- protected void engineInitVerify(PublicKey arg0)
- throws InvalidKeyException {
- spiImpl.engineInitVerify(arg0);
+ protected void engineInitVerify(PublicKey arg0) throws InvalidKeyException {
+ getSpi(arg0).engineInitVerify(arg0);
}
- // engineGetParameter() implementation
@Override
- protected Object engineGetParameter(String arg0)
- throws InvalidParameterException {
- return spiImpl.engineGetParameter(arg0);
+ protected Object engineGetParameter(String arg0) throws InvalidParameterException {
+ return getSpi().engineGetParameter(arg0);
}
- // engineSetParameter() implementation
@Override
protected void engineSetParameter(String arg0, Object arg1)
throws InvalidParameterException {
- spiImpl.engineSetParameter(arg0, arg1);
+ getSpi().engineSetParameter(arg0, arg1);
+ }
+
+ @Override
+ protected void engineSetParameter(AlgorithmParameterSpec arg0)
+ throws InvalidAlgorithmParameterException {
+ getSpi().engineSetParameter(arg0);
}
- // Returns a clone if the spiImpl is cloneable
@Override
public Object clone() throws CloneNotSupportedException {
- if (spiImpl instanceof Cloneable) {
- SignatureSpi spi = (SignatureSpi) spiImpl.clone();
- return new SignatureImpl(spi, getProvider(), getAlgorithm());
+ SignatureSpi spi = spiImpl != null ? (SignatureSpi) spiImpl.clone() : null;
+ return new SignatureImpl(getAlgorithm(), getProvider(), spi);
+ }
+
+ /**
+ * Makes sure a CipherSpi that matches this type is selected.
+ */
+ private SignatureSpi getSpi(Key key) {
+ synchronized (initLock) {
+ if (spiImpl != null && key == null) {
+ return spiImpl;
+ }
+
+ final Engine.SpiAndProvider sap = tryAlgorithm(key, specifiedProvider, algorithm);
+ if (sap == null) {
+ throw new ProviderException("No provider for " + getAlgorithm());
+ }
+
+ spiImpl = (SignatureSpi) sap.spi;
+ provider = sap.provider;
+
+ return spiImpl;
}
- throw new CloneNotSupportedException();
+ }
+
+ /**
+ * Convenience call when the Key is not available.
+ */
+ private SignatureSpi getSpi() {
+ return getSpi(null);
}
}
}
diff --git a/luni/src/main/java/java/security/SignatureSpi.java b/luni/src/main/java/java/security/SignatureSpi.java
index 27be30c..66c43d7 100644
--- a/luni/src/main/java/java/security/SignatureSpi.java
+++ b/luni/src/main/java/java/security/SignatureSpi.java
@@ -307,9 +307,6 @@ public abstract class SignatureSpi {
@Override
public Object clone() throws CloneNotSupportedException {
- if (this instanceof Cloneable) {
- return super.clone();
- }
- throw new CloneNotSupportedException();
+ return super.clone();
}
}
diff --git a/luni/src/main/java/java/security/cert/CRLReason.java b/luni/src/main/java/java/security/cert/CRLReason.java
new file mode 100644
index 0000000..6f663db
--- /dev/null
+++ b/luni/src/main/java/java/security/cert/CRLReason.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2014 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 java.security.cert;
+
+import java.io.Serializable;
+
+/**
+ * The reason a CRL entry was revoked. See <a
+ * href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280</a> for more information.
+ *
+ * @since 1.7
+ * @hide
+ */
+public enum CRLReason implements Comparable<CRLReason>, Serializable {
+ UNSPECIFIED,
+ KEY_COMPROMISE,
+ CA_COMPROMISE,
+ AFFILIATION_CHANGED,
+ SUPERSEDED,
+ CESSATION_OF_OPERATION,
+ CERTIFICATE_HOLD,
+ UNUSED,
+ REMOVE_FROM_CRL,
+ PRIVILEGE_WITHDRAWN,
+ AA_COMPROMISE;
+}
diff --git a/luni/src/main/java/java/security/cert/CertPathValidator.java b/luni/src/main/java/java/security/cert/CertPathValidator.java
index a3a666a..962f530 100644
--- a/luni/src/main/java/java/security/cert/CertPathValidator.java
+++ b/luni/src/main/java/java/security/cert/CertPathValidator.java
@@ -140,7 +140,8 @@ public class CertPathValidator {
/**
* Returns a new certification path validator for the specified algorithm
- * from the specified provider.
+ * from the specified provider. The {@code provider} supplied does not
+ * have to be registered.
*
* @param algorithm
* the algorithm name.
diff --git a/luni/src/main/java/java/security/cert/CertStore.java b/luni/src/main/java/java/security/cert/CertStore.java
index 72d356f..606c93b 100644
--- a/luni/src/main/java/java/security/cert/CertStore.java
+++ b/luni/src/main/java/java/security/cert/CertStore.java
@@ -151,7 +151,9 @@ public class CertStore {
/**
* Creates a new {@code CertStore} instance from the specified provider with
- * the specified type and initialized with the specified parameters.
+ * the specified type and initialized with the specified parameters. The
+ * {@code provider} supplied does not have to be registered.
+ *
* @param type
* the certificate store type.
* @param params
diff --git a/luni/src/main/java/java/security/cert/Certificate.java b/luni/src/main/java/java/security/cert/Certificate.java
index 15c1dbe..675cf9f 100644
--- a/luni/src/main/java/java/security/cert/Certificate.java
+++ b/luni/src/main/java/java/security/cert/Certificate.java
@@ -152,15 +152,15 @@ public abstract class Certificate implements Serializable {
* performed.
* @param sigProvider
* String the name of the signature provider.
- * @exception CertificateException
+ * @throws CertificateException
* if encoding errors are detected.
- * @exception NoSuchAlgorithmException
+ * @throws NoSuchAlgorithmException
* if an unsupported algorithm is detected.
- * @exception InvalidKeyException
+ * @throws InvalidKeyException
* if an invalid key is detected.
- * @exception NoSuchProviderException
+ * @throws NoSuchProviderException
* if the specified provider does not exists.
- * @exception SignatureException
+ * @throws SignatureException
* if signature errors are detected.
*/
public abstract void verify(PublicKey key, String sigProvider)
diff --git a/luni/src/main/java/java/security/cert/CertificateFactory.java b/luni/src/main/java/java/security/cert/CertificateFactory.java
index f882d52..2805c0e 100644
--- a/luni/src/main/java/java/security/cert/CertificateFactory.java
+++ b/luni/src/main/java/java/security/cert/CertificateFactory.java
@@ -128,7 +128,8 @@ public class CertificateFactory {
/**
* Creates a new {@code CertificateFactory} instance from the specified
- * provider that provides the requested certificate type.
+ * provider that provides the requested certificate type. The
+ * {@code provider} supplied does not have to be registered.
*
* @param type
* the certificate type.
@@ -280,7 +281,7 @@ public class CertificateFactory {
* @param inStream
* the stream from where data is read to create the CRL.
* @return an initialized CRL.
- * @exception CRLException
+ * @throws CRLException
* if parsing problems are detected.
*/
public final CRL generateCRL(InputStream inStream) throws CRLException {
@@ -294,7 +295,7 @@ public class CertificateFactory {
* @param inStream
* the stream from which the data is read to create the CRLs.
* @return an initialized collection of CRLs.
- * @exception CRLException
+ * @throws CRLException
* if parsing problems are detected.
*/
public final Collection<? extends CRL> generateCRLs(InputStream inStream)
diff --git a/luni/src/main/java/java/security/cert/CertificateFactorySpi.java b/luni/src/main/java/java/security/cert/CertificateFactorySpi.java
index 117ef65..d157d9c 100644
--- a/luni/src/main/java/java/security/cert/CertificateFactorySpi.java
+++ b/luni/src/main/java/java/security/cert/CertificateFactorySpi.java
@@ -44,7 +44,7 @@ public abstract class CertificateFactorySpi {
* the stream from which the data is read to create the
* certificate.
* @return an initialized certificate.
- * @exception CertificateException
+ * @throws CertificateException
* if parsing problems are detected.
*/
public abstract Certificate engineGenerateCertificate(InputStream inStream)
@@ -57,7 +57,7 @@ public abstract class CertificateFactorySpi {
* @param inStream
* the stream from where data is read to create the certificates.
* @return a collection of certificates.
- * @exception CertificateException
+ * @throws CertificateException
* if parsing problems are detected.
*/
public abstract Collection<? extends Certificate>
@@ -70,7 +70,7 @@ public abstract class CertificateFactorySpi {
* @param inStream
* the stream from where data is read to create the CRL.
* @return an CRL instance.
- * @exception CRLException
+ * @throws CRLException
* if parsing problems are detected.
*/
public abstract CRL engineGenerateCRL(InputStream inStream)
@@ -83,7 +83,7 @@ public abstract class CertificateFactorySpi {
* @param inStream
* the stream from which the data is read to create the CRLs.
* @return a collection of CRLs.
- * @exception CRLException
+ * @throws CRLException
* if parsing problems are detected.
*/
public abstract Collection<? extends CRL>
diff --git a/luni/src/main/java/java/security/cert/CertificateRevokedException.java b/luni/src/main/java/java/security/cert/CertificateRevokedException.java
new file mode 100644
index 0000000..4d88a4d
--- /dev/null
+++ b/luni/src/main/java/java/security/cert/CertificateRevokedException.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2014 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 java.security.cert;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import javax.security.auth.x500.X500Principal;
+import org.apache.harmony.security.x509.InvalidityDate;
+
+/**
+ * Exception that is thrown when a certificate is invalid because it has been
+ * revoked.
+ *
+ * @since 1.7
+ * @hide
+ */
+public class CertificateRevokedException extends CertificateException {
+
+ private static final long serialVersionUID = 7839996631571608627L;
+
+ private final Date revocationDate;
+
+ private final CRLReason reason;
+
+ private final X500Principal authority;
+
+ // Maps may not be serializable, so serialize it manually.
+ private transient Map<String, Extension> extensions;
+
+ /**
+ * @param revocationDate date the certificate was revoked
+ * @param reason reason the certificate was revoked if available
+ * @param authority authority that revoked the certificate
+ * @param extensions X.509 extensions associated with this revocation
+ */
+ public CertificateRevokedException(Date revocationDate, CRLReason reason,
+ X500Principal authority, Map<String, Extension> extensions) {
+ this.revocationDate = revocationDate;
+ this.reason = reason;
+ this.authority = authority;
+ this.extensions = extensions;
+ }
+
+ /**
+ * Returns the principal of the authority that issued the revocation.
+ */
+ public X500Principal getAuthorityName() {
+ return authority;
+ }
+
+ /**
+ * X.509 extensions that are associated with this revocation.
+ */
+ public Map<String, Extension> getExtensions() {
+ return Collections.unmodifiableMap(extensions);
+ }
+
+ /**
+ * Returns the date when the certificate was known to become invalid if
+ * available.
+ */
+ public Date getInvalidityDate() {
+ if (extensions == null) {
+ return null;
+ }
+
+ Extension invalidityDateExtension = extensions.get("2.5.29.24");
+ if (invalidityDateExtension == null) {
+ return null;
+ }
+
+ try {
+ InvalidityDate invalidityDate = new InvalidityDate(invalidityDateExtension.getValue());
+ return invalidityDate.getDate();
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the detail message of the thrown exception.
+ */
+ public String getMessage() {
+ StringBuffer sb = new StringBuffer("Certificate was revoked");
+ if (revocationDate != null) {
+ sb.append(" on ").append(revocationDate.toString());
+ }
+ if (reason != null) {
+ sb.append(" due to ").append(reason);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Returns the date the certificate was revoked.
+ */
+ public Date getRevocationDate() {
+ return (Date) revocationDate.clone();
+ }
+
+ /**
+ * Returns the reason the certificate was revoked if available.
+ */
+ public CRLReason getRevocationReason() {
+ return reason;
+ }
+
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+
+ int size = stream.readInt();
+ extensions = new HashMap<String, Extension>(size);
+ for (int i = 0; i < size; i++) {
+ String oid = (String) stream.readObject();
+ boolean critical = stream.readBoolean();
+ int valueLen = stream.readInt();
+ byte[] value = new byte[valueLen];
+ stream.read(value);
+ extensions.put(oid,
+ new org.apache.harmony.security.x509.Extension(oid, critical, value));
+ }
+ }
+
+ private void writeObject(ObjectOutputStream stream) throws IOException {
+ stream.defaultWriteObject();
+
+ stream.writeInt(extensions.size());
+ for (Extension e : extensions.values()) {
+ stream.writeObject(e.getId());
+ stream.writeBoolean(e.isCritical());
+ byte[] value = e.getValue();
+ stream.writeInt(value.length);
+ stream.write(value);
+ }
+ }
+}
diff --git a/luni/src/main/java/java/security/cert/Extension.java b/luni/src/main/java/java/security/cert/Extension.java
new file mode 100644
index 0000000..8013809
--- /dev/null
+++ b/luni/src/main/java/java/security/cert/Extension.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2014 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 java.security.cert;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * The Extension part of an X.509 certificate (as specified in <a
+ * href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280 &mdash; Internet X.509
+ * Public Key Infrastructure: Certificate and Certificate Revocation List (CRL)
+ * Profile</p>):
+ *
+ * <pre>
+ * Extension ::= SEQUENCE {
+ * extnID OBJECT IDENTIFIER,
+ * critical BOOLEAN DEFAULT FALSE,
+ * extnValue OCTET STRING
+ * }
+ * </pre>
+ *
+ * @since 1.7
+ * @hide
+ */
+public interface Extension {
+ /**
+ * Returns the OID (Object Identifier) for this extension encoded as a
+ * string (e.g., "2.5.29.15").
+ */
+ String getId();
+
+ /**
+ * Returns {@code true} if this extension is critical. If this is true and
+ * an implementation does not understand this extension, it must reject it.
+ * See RFC 3280 section 4.2 for more information.
+ */
+ boolean isCritical();
+
+ /**
+ * The DER-encoded value of this extension.
+ */
+ byte[] getValue();
+
+ /**
+ * Writes the DER-encoded extension to {@code out}.
+ *
+ * @throws IOException when there is an encoding error or error writing to
+ * {@code out}
+ */
+ void encode(OutputStream out) throws IOException;
+}
diff --git a/luni/src/main/java/java/security/cert/X509CRLEntry.java b/luni/src/main/java/java/security/cert/X509CRLEntry.java
index 4b4c15d..451cfd5 100644
--- a/luni/src/main/java/java/security/cert/X509CRLEntry.java
+++ b/luni/src/main/java/java/security/cert/X509CRLEntry.java
@@ -17,10 +17,13 @@
package java.security.cert;
+import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
+import org.apache.harmony.security.asn1.ASN1OctetString;
+import org.apache.harmony.security.x509.ReasonCode;
/**
* Abstract base class for entries in a certificate revocation list (CRL).
@@ -121,5 +124,25 @@ public abstract class X509CRLEntry implements X509Extension {
* @return a string representation of this instance.
*/
public abstract String toString();
-}
+ /**
+ * Returns the reason this CRL entry was revoked. If the implementation
+ * doesn't support reasons, this will return {@code null}.
+ *
+ * @since 1.7
+ * @hide
+ */
+ public CRLReason getRevocationReason() {
+ byte[] reasonBytes = getExtensionValue("2.5.29.21");
+ if (reasonBytes == null) {
+ return null;
+ }
+
+ try {
+ byte[] rawBytes = (byte[]) ASN1OctetString.getInstance().decode(reasonBytes);
+ return new ReasonCode(rawBytes).getReason();
+ } catch (IOException e) {
+ return null;
+ }
+ }
+} \ No newline at end of file
diff --git a/luni/src/main/java/java/security/interfaces/DSAParams.java b/luni/src/main/java/java/security/interfaces/DSAParams.java
index ed1fcb5..64ddb01 100644
--- a/luni/src/main/java/java/security/interfaces/DSAParams.java
+++ b/luni/src/main/java/java/security/interfaces/DSAParams.java
@@ -39,9 +39,9 @@ public interface DSAParams {
public BigInteger getP();
/**
- * Returns the subprime ({@code q} value.
+ * Returns the subprime ({@code q}) value.
*
- * @return the subprime ({@code q} value.
+ * @return the subprime ({@code q}) value.
*/
public BigInteger getQ();
diff --git a/luni/src/main/java/java/security/security.properties b/luni/src/main/java/java/security/security.properties
index dd5830d..a06283b 100644
--- a/luni/src/main/java/java/security/security.properties
+++ b/luni/src/main/java/java/security/security.properties
@@ -20,13 +20,11 @@
#
# Android's provider of OpenSSL backed implementations
security.provider.1=com.android.org.conscrypt.OpenSSLProvider
-# Favor Harmony's CertificateFactory.X509 over BouncyCastle's
-security.provider.2=org.apache.harmony.security.provider.cert.DRLCertFactory
# Android's stripped down BouncyCastle provider
-security.provider.3=com.android.org.bouncycastle.jce.provider.BouncyCastleProvider
+security.provider.2=com.android.org.bouncycastle.jce.provider.BouncyCastleProvider
# Remaining Harmony providers
-security.provider.4=org.apache.harmony.security.provider.crypto.CryptoProvider
-security.provider.5=com.android.org.conscrypt.JSSEProvider
+security.provider.3=org.apache.harmony.security.provider.crypto.CryptoProvider
+security.provider.4=com.android.org.conscrypt.JSSEProvider
diff --git a/luni/src/main/java/java/security/spec/ECParameterSpec.java b/luni/src/main/java/java/security/spec/ECParameterSpec.java
index 9860ac0..37b39ac 100644
--- a/luni/src/main/java/java/security/spec/ECParameterSpec.java
+++ b/luni/src/main/java/java/security/spec/ECParameterSpec.java
@@ -32,7 +32,7 @@ public class ECParameterSpec implements AlgorithmParameterSpec {
// Cofactor
private final int cofactor;
// Name of curve if available.
- private final String curveName;
+ private String curveName;
/**
* Creates a new {@code ECParameterSpec} with the specified elliptic curve,
@@ -52,23 +52,10 @@ public class ECParameterSpec implements AlgorithmParameterSpec {
*/
public ECParameterSpec(EllipticCurve curve, ECPoint generator,
BigInteger order, int cofactor) {
- this(curve, generator, order, cofactor, null);
- }
-
- /**
- * Creates a new {@code ECParameterSpec} with the specified named curve
- * and all of its parameters.
- *
- * @see #ECParameterSpec(EllipticCurve, ECPoint, BigInteger, int)
- * @hide
- */
- public ECParameterSpec(EllipticCurve curve, ECPoint generator,
- BigInteger order, int cofactor, String curveName) {
this.curve = curve;
this.generator = generator;
this.order = order;
this.cofactor = cofactor;
- this.curveName = curveName;
// throw NullPointerException if curve, generator or order is null
if (this.curve == null) {
throw new NullPointerException("curve == null");
@@ -125,6 +112,15 @@ public class ECParameterSpec implements AlgorithmParameterSpec {
}
/**
+ * Used to set the curve name if available.
+ *
+ * @hide
+ */
+ public void setCurveName(String curveName) {
+ this.curveName = curveName;
+ }
+
+ /**
* Returns the name of the curve if this is a named curve. Returns
* {@code null} if this is not known to be a named curve.
*
diff --git a/luni/src/main/java/java/sql/Date.java b/luni/src/main/java/java/sql/Date.java
index 4aac326..206d885 100644
--- a/luni/src/main/java/java/sql/Date.java
+++ b/luni/src/main/java/java/sql/Date.java
@@ -214,23 +214,19 @@ public class Date extends java.util.Date {
if (dateString == null) {
throw new IllegalArgumentException("dateString == null");
}
- int firstIndex = dateString.indexOf('-');
- int secondIndex = dateString.indexOf('-', firstIndex + 1);
- // secondIndex == -1 means none or only one separator '-' has been
- // found.
- // The string is separated into three parts by two separator characters,
- // if the first or the third part is null string, we should throw
- // IllegalArgumentException to follow RI
- if (secondIndex == -1 || firstIndex == 0
- || secondIndex + 1 == dateString.length()) {
+ if (dateString.length() > 10) {
+ // early fail to avoid parsing huge invalid strings
throw new IllegalArgumentException();
}
- // parse each part of the string
- int year = Integer.parseInt(dateString.substring(0, firstIndex));
- int month = Integer.parseInt(dateString.substring(firstIndex + 1,
- secondIndex));
- int day = Integer.parseInt(dateString.substring(secondIndex + 1,
- dateString.length()));
+
+ String[] parts = dateString.split("-");
+ if (parts.length != 3) {
+ throw new IllegalArgumentException();
+ }
+
+ int year = Integer.parsePositiveInt(parts[0]);
+ int month = Integer.parsePositiveInt(parts[1]);
+ int day = Integer.parsePositiveInt(parts[2]);
return new Date(year - 1900, month - 1, day);
}
diff --git a/luni/src/main/java/java/sql/Timestamp.java b/luni/src/main/java/java/sql/Timestamp.java
index f35fa9b..a45a2b8 100644
--- a/luni/src/main/java/java/sql/Timestamp.java
+++ b/luni/src/main/java/java/sql/Timestamp.java
@@ -408,7 +408,7 @@ public class Timestamp extends Date {
throw new IllegalArgumentException("Argument cannot be null");
}
- // omit trailing whitespace
+ // Omit trailing whitespace
s = s.trim();
if (!Pattern.matches(TIME_FORMAT_REGEX, s)) {
throw badTimestampString(s);
@@ -424,14 +424,14 @@ public class Timestamp extends Date {
* with the ParsePosition indicating the index of the "." which should
* precede the nanoseconds value
*/
- Date theDate;
+ Date date;
try {
- theDate = df.parse(s, pp);
+ date = df.parse(s, pp);
} catch (Exception e) {
throw badTimestampString(s);
}
- if (theDate == null) {
+ if (date == null) {
throw badTimestampString(s);
}
@@ -445,66 +445,38 @@ public class Timestamp extends Date {
*/
int position = pp.getIndex();
int remaining = s.length() - position;
- int theNanos;
+ int nanos;
if (remaining == 0) {
// First, allow for the case where no fraction of a second is given:
- theNanos = 0;
+ nanos = 0;
} else {
- /*
- * Case where fraction of a second is specified: Require 1 character
- * plus the "." in the remaining part of the string...
- */
- if ((s.length() - position) < ".n".length()) {
+ // Validate the string is in the range ".0" to ".999999999"
+ if (remaining < 2 || remaining > 10 || s.charAt(position) != '.') {
throw badTimestampString(s);
}
-
- /*
- * If we're strict, we should not allow any EXTRA characters after
- * the 9 digits
- */
- if ((s.length() - position) > ".nnnnnnnnn".length()) {
- throw badTimestampString(s);
- }
-
- // Require the next character to be a "."
- if (s.charAt(position) != '.') {
- throw new NumberFormatException("Bad input string format: expected '.' not '" +
- s.charAt(position) + "' in \"" + s + "\"");
- }
- // Get the length of the number string - need to account for the '.'
- int nanoLength = s.length() - position - 1;
-
- // Get the 9 characters following the "." as an integer
- String theNanoString = s.substring(position + 1, position + 1
- + nanoLength);
- /*
- * We must adjust for the cases where the nanos String was not 9
- * characters long by padding out with zeros
- */
- theNanoString = theNanoString + "000000000";
- theNanoString = theNanoString.substring(0, 9);
-
try {
- theNanos = Integer.parseInt(theNanoString);
- } catch (Exception e) {
- // If we get here, the string was not a number
+ nanos = Integer.parsePositiveInt(s.substring(position + 1));
+ } catch (NumberFormatException e) {
throw badTimestampString(s);
}
+ // We must adjust for the cases where the nanos String was not 9
+ // characters long (i.e. ".123" means 123000000 nanos)
+ if (nanos != 0) {
+ for (int i = remaining - 1; i < 9; i++) {
+ nanos *= 10;
+ }
+ }
}
- if (theNanos < 0 || theNanos > 999999999) {
- throw badTimestampString(s);
- }
-
- Timestamp theTimestamp = new Timestamp(theDate.getTime());
- theTimestamp.setNanos(theNanos);
+ Timestamp timestamp = new Timestamp(date.getTime());
+ timestamp.setNanos(nanos);
- return theTimestamp;
+ return timestamp;
}
private static IllegalArgumentException badTimestampString(String s) {
- throw new IllegalArgumentException("Timestamp format must be " +
+ return new IllegalArgumentException("Timestamp format must be " +
"yyyy-MM-dd HH:mm:ss.fffffffff; was '" + s + "'");
}
}
diff --git a/luni/src/main/java/java/text/Bidi.java b/luni/src/main/java/java/text/Bidi.java
index e4b30e6..d73ea4a 100644
--- a/luni/src/main/java/java/text/Bidi.java
+++ b/luni/src/main/java/java/text/Bidi.java
@@ -421,28 +421,20 @@ public final class Bidi {
/**
* Returns the base level.
- *
- * @return the base level.
*/
public int getBaseLevel() {
return baseLevel;
}
/**
- * Returns the length of the text in the {@code Bidi} object.
- *
- * @return the length.
+ * Returns the length of the text.
*/
public int getLength() {
return length;
}
/**
- * Returns the level of a specified character.
- *
- * @param offset
- * the offset of the character.
- * @return the level.
+ * Returns the level of the given character.
*/
public int getLevelAt(int offset) {
try {
@@ -453,74 +445,51 @@ public final class Bidi {
}
/**
- * Returns the number of runs in the bidirectional text.
- *
- * @return the number of runs, at least 1.
+ * Returns the number of runs in the text, at least 1.
*/
public int getRunCount() {
return unidirectional ? 1 : runs.length;
}
/**
- * Returns the level of the specified run.
- *
- * @param run
- * the index of the run.
- * @return the level of the run.
+ * Returns the level of the given run.
*/
public int getRunLevel(int run) {
return unidirectional ? baseLevel : runs[run].getLevel();
}
/**
- * Returns the limit offset of the specified run.
- *
- * @param run
- * the index of the run.
- * @return the limit offset of the run.
+ * Returns the limit offset of the given run.
*/
public int getRunLimit(int run) {
return unidirectional ? length : runs[run].getLimit();
}
/**
- * Returns the start offset of the specified run.
- *
- * @param run
- * the index of the run.
- * @return the start offset of the run.
+ * Returns the start offset of the given run.
*/
public int getRunStart(int run) {
return unidirectional ? 0 : runs[run].getStart();
}
/**
- * Indicates whether the text is from left to right, that is, both the base
+ * Returns true if the text is from left to right, that is, both the base
* direction and the text direction is from left to right.
- *
- * @return {@code true} if the text is from left to right; {@code false}
- * otherwise.
*/
public boolean isLeftToRight() {
return direction == UBiDiDirection_UBIDI_LTR;
}
/**
- * Indicates whether the text direction is mixed.
- *
- * @return {@code true} if the text direction is mixed; {@code false}
- * otherwise.
+ * Returns true if the text direction is mixed.
*/
public boolean isMixed() {
return direction == UBiDiDirection_UBIDI_MIXED;
}
/**
- * Indicates whether the text is from right to left, that is, both the base
+ * Returns true if the text is from right to left, that is, both the base
* direction and the text direction is from right to left.
- *
- * @return {@code true} if the text is from right to left; {@code false}
- * otherwise.
*/
public boolean isRightToLeft() {
return direction == UBiDiDirection_UBIDI_RTL;
diff --git a/luni/src/main/java/java/text/BreakIterator.java b/luni/src/main/java/java/text/BreakIterator.java
index b14647c..81545b2 100644
--- a/luni/src/main/java/java/text/BreakIterator.java
+++ b/luni/src/main/java/java/text/BreakIterator.java
@@ -268,13 +268,9 @@ public abstract class BreakIterator implements Cloneable {
/**
* Returns a new instance of {@code BreakIterator} to iterate over
* characters using the given locale.
- *
- * @param where
- * the given locale.
- * @return a new instance of {@code BreakIterator} using the given locale.
*/
- public static BreakIterator getCharacterInstance(Locale where) {
- return new RuleBasedBreakIterator(NativeBreakIterator.getCharacterInstance(where));
+ public static BreakIterator getCharacterInstance(Locale locale) {
+ return new RuleBasedBreakIterator(NativeBreakIterator.getCharacterInstance(locale));
}
/**
@@ -290,14 +286,9 @@ public abstract class BreakIterator implements Cloneable {
/**
* Returns a new instance of {@code BreakIterator} to iterate over
* line breaks using the given locale.
- *
- * @param where
- * the given locale.
- * @return a new instance of {@code BreakIterator} using the given locale.
- * @throws NullPointerException if {@code where} is {@code null}.
*/
- public static BreakIterator getLineInstance(Locale where) {
- return new RuleBasedBreakIterator(NativeBreakIterator.getLineInstance(where));
+ public static BreakIterator getLineInstance(Locale locale) {
+ return new RuleBasedBreakIterator(NativeBreakIterator.getLineInstance(locale));
}
/**
@@ -313,14 +304,9 @@ public abstract class BreakIterator implements Cloneable {
/**
* Returns a new instance of {@code BreakIterator} to iterate over
* sentence-breaks using the given locale.
- *
- * @param where
- * the given locale.
- * @return a new instance of {@code BreakIterator} using the given locale.
- * @throws NullPointerException if {@code where} is {@code null}.
*/
- public static BreakIterator getSentenceInstance(Locale where) {
- return new RuleBasedBreakIterator(NativeBreakIterator.getSentenceInstance(where));
+ public static BreakIterator getSentenceInstance(Locale locale) {
+ return new RuleBasedBreakIterator(NativeBreakIterator.getSentenceInstance(locale));
}
/**
@@ -336,14 +322,9 @@ public abstract class BreakIterator implements Cloneable {
/**
* Returns a new instance of {@code BreakIterator} to iterate over
* word-breaks using the given locale.
- *
- * @param where
- * the given locale.
- * @return a new instance of {@code BreakIterator} using the given locale.
- * @throws NullPointerException if {@code where} is {@code null}.
*/
- public static BreakIterator getWordInstance(Locale where) {
- return new RuleBasedBreakIterator(NativeBreakIterator.getWordInstance(where));
+ public static BreakIterator getWordInstance(Locale locale) {
+ return new RuleBasedBreakIterator(NativeBreakIterator.getWordInstance(locale));
}
/**
diff --git a/luni/src/main/java/java/text/CollationElementIterator.java b/luni/src/main/java/java/text/CollationElementIterator.java
index 5da3b65..4f75a9a 100644
--- a/luni/src/main/java/java/text/CollationElementIterator.java
+++ b/luni/src/main/java/java/text/CollationElementIterator.java
@@ -43,6 +43,11 @@ import libcore.icu.CollationElementIteratorICU;
* "&#92;u0086b": the first collation element is collation_element('a'), the
* second one is collation_element('e'), and the third collation element is
* collation_element('b').
+ *
+ * <p>Note that calls to {@code next} and {@code previous} can not be mixed.
+ * To change iteration direction, {@code reset}, {@code setOffset} or {@code setText}
+ * must be called to reset the iterator. If a change of direction is done without one
+ * of these calls, the result is undefined.
*/
public final class CollationElementIterator {
@@ -61,7 +66,7 @@ public final class CollationElementIterator {
}
/**
- * Obtains the maximum length of any expansion sequence that ends with the
+ * Returns the maximum length of any expansion sequence that ends with the
* specified collation element. Returns {@code 1} if there is no expansion
* with this collation element as the last element.
*
@@ -69,15 +74,13 @@ public final class CollationElementIterator {
* a collation element that has been previously obtained from a
* call to either the {@link #next()} or {@link #previous()}
* method.
- * @return the maximum length of any expansion sequence ending with the
- * specified collation element.
*/
public int getMaxExpansion(int order) {
return this.icuIterator.getMaxExpansion(order);
}
/**
- * Obtains the character offset in the source string corresponding to the
+ * Returns the character offset in the source string corresponding to the
* next collation element. This value could be any of:
* <ul>
* <li>The index of the first character in the source string that matches
@@ -94,42 +97,33 @@ public final class CollationElementIterator {
* <li>The length of the source string, if iteration has reached the end.
* </li>
* </ul>
- *
- * @return The position of the collation element in the source string that
- * will be returned by the next invocation of the {@link #next()}
- * method.
*/
public int getOffset() {
return this.icuIterator.getOffset();
}
/**
- * Obtains the next collation element in the source string.
- *
- * @return the next collation element or {@code NULLORDER} if the end
- * of the iteration has been reached.
+ * Returns the next collation element in the source string or {@code NULLORDER} if
+ * the end of the iteration has been reached.
*/
public int next() {
return this.icuIterator.next();
}
/**
- * Obtains the previous collation element in the source string.
- *
- * @return the previous collation element, or {@code NULLORDER} when
- * the start of the iteration has been reached.
+ * Returns the previous collation element in the source string or {@code NULLORDER} if
+ * the start of the iteration has been reached.
*/
public int previous() {
return this.icuIterator.previous();
}
/**
- * Obtains the primary order of the specified collation element, i.e. the
+ * Returns the primary order of the specified collation element, i.e. the
* first 16 bits. This value is unsigned.
*
* @param order
* the element of the collation.
- * @return the element's 16 bit primary order.
*/
public static final int primaryOrder(int order) {
return CollationElementIteratorICU.primaryOrder(order);
@@ -149,12 +143,11 @@ public final class CollationElementIterator {
}
/**
- * Obtains the secondary order of the specified collation element, i.e. the
+ * Returns the secondary order of the specified collation element, i.e. the
* 16th to 23th bits, inclusive. This value is unsigned.
*
* @param order
* the element of the collator.
- * @return the 8 bit secondary order of the element.
*/
public static final short secondaryOrder(int order) {
return (short) CollationElementIteratorICU.secondaryOrder(order);
@@ -209,12 +202,11 @@ public final class CollationElementIterator {
}
/**
- * Obtains the tertiary order of the specified collation element, i.e. the
+ * Returns the tertiary order of the specified collation element, i.e. the
* last 8 bits. This value is unsigned.
*
* @param order
* the element of the collation.
- * @return the 8 bit tertiary order of the element.
*/
public static final short tertiaryOrder(int order) {
return (short) CollationElementIteratorICU.tertiaryOrder(order);
diff --git a/luni/src/main/java/java/text/DateFormat.java b/luni/src/main/java/java/text/DateFormat.java
index ac64eed..3055843 100644
--- a/luni/src/main/java/java/text/DateFormat.java
+++ b/luni/src/main/java/java/text/DateFormat.java
@@ -388,6 +388,9 @@ public abstract class DateFormat extends Format {
*/
public static final DateFormat getDateInstance(int style, Locale locale) {
checkDateStyle(style);
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
return new SimpleDateFormat(LocaleData.get(locale).getDateFormat(style), locale);
}
@@ -440,6 +443,9 @@ public abstract class DateFormat extends Format {
public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) {
checkTimeStyle(timeStyle);
checkDateStyle(dateStyle);
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
LocaleData localeData = LocaleData.get(locale);
String pattern = localeData.getDateFormat(dateStyle) + " " + localeData.getTimeFormat(timeStyle);
return new SimpleDateFormat(pattern, locale);
@@ -457,6 +463,12 @@ public abstract class DateFormat extends Format {
}
/**
+ * @hide for internal use only.
+ */
+ public static final void set24HourTimePref(boolean is24Hour) {
+ }
+
+ /**
* Returns the {@code NumberFormat} used by this {@code DateFormat}.
*
* @return the {@code NumberFormat} used by this date format.
@@ -508,6 +520,10 @@ public abstract class DateFormat extends Format {
*/
public static final DateFormat getTimeInstance(int style, Locale locale) {
checkTimeStyle(style);
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
+
return new SimpleDateFormat(LocaleData.get(locale).getTimeFormat(style), locale);
}
diff --git a/luni/src/main/java/java/text/DateFormatSymbols.java b/luni/src/main/java/java/text/DateFormatSymbols.java
index e75b82c..ee34bbd 100644
--- a/luni/src/main/java/java/text/DateFormatSymbols.java
+++ b/luni/src/main/java/java/text/DateFormatSymbols.java
@@ -62,16 +62,14 @@ public class DateFormatSymbols implements Serializable, Cloneable {
transient LocaleData localeData;
// Localized display names.
- String[][] zoneStrings;
- // Has the user called setZoneStrings?
- transient boolean customZoneStrings;
+ private String[][] zoneStrings;
- /**
- * Locale, necessary to lazily load time zone strings. We force the time
- * zone names to load upon serialization, so this will never be needed
- * post deserialization.
+ /*
+ * Locale, necessary to lazily load time zone strings. Added to the serialized form for
+ * Android's L release. May be null if the object was deserialized using data from older
+ * releases. See b/16502916.
*/
- transient final Locale locale;
+ private final Locale locale;
/**
* Gets zone strings, initializing them if necessary. Does not create
@@ -102,7 +100,7 @@ public class DateFormatSymbols implements Serializable, Cloneable {
* the locale.
*/
public DateFormatSymbols(Locale locale) {
- this.locale = locale;
+ this.locale = LocaleData.mapInvalidAndNullLocales(locale);
this.localPatternChars = SimpleDateFormat.PATTERN_CHARS;
this.localeData = LocaleData.get(locale);
@@ -152,6 +150,12 @@ public class DateFormatSymbols implements Serializable, Cloneable {
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
+
+ Locale locale = this.locale;
+ if (locale == null) {
+ // Before the L release Android did not serialize the locale. Handle its absence.
+ locale = Locale.getDefault();
+ }
this.localeData = LocaleData.get(locale);
}
@@ -215,7 +219,6 @@ public class DateFormatSymbols implements Serializable, Cloneable {
// 'zoneStrings' is so large, we just print a representative value.
return getClass().getName() +
"[amPmStrings=" + Arrays.toString(ampms) +
- ",customZoneStrings=" + customZoneStrings +
",eras=" + Arrays.toString(eras) +
",localPatternChars=" + localPatternChars +
",months=" + Arrays.toString(months) +
@@ -251,8 +254,6 @@ public class DateFormatSymbols implements Serializable, Cloneable {
/**
* Returns the pattern characters used by {@link SimpleDateFormat} to
* specify date and time fields.
- *
- * @return a string containing the pattern characters.
*/
public String getLocalPatternChars() {
return localPatternChars;
@@ -485,6 +486,25 @@ public class DateFormatSymbols implements Serializable, Cloneable {
}
}
this.zoneStrings = clone2dStringArray(zoneStrings);
- this.customZoneStrings = true;
+ }
+
+ /**
+ * Returns the display name of the timezone specified. Returns null if no name was found in the
+ * zone strings.
+ *
+ * @param daylight whether to return the daylight savings or the standard name
+ * @param style one of the {@link TimeZone} styles such as {@link TimeZone#SHORT}
+ *
+ * @hide used internally
+ */
+ String getTimeZoneDisplayName(TimeZone tz, boolean daylight, int style) {
+ if (style != TimeZone.SHORT && style != TimeZone.LONG) {
+ throw new IllegalArgumentException("Bad style: " + style);
+ }
+
+ // If custom zone strings have been set with setZoneStrings() we use those. Otherwise we
+ // use the ones from LocaleData.
+ String[][] zoneStrings = internalZoneStrings();
+ return TimeZoneNames.getDisplayName(zoneStrings, tz.getID(), daylight, style);
}
}
diff --git a/luni/src/main/java/java/text/DecimalFormat.java b/luni/src/main/java/java/text/DecimalFormat.java
index 948bec1..554fd74 100644
--- a/luni/src/main/java/java/text/DecimalFormat.java
+++ b/luni/src/main/java/java/text/DecimalFormat.java
@@ -373,11 +373,11 @@ import libcore.icu.NativeDecimalFormat;
* digits is fixed at one and there is no exponent grouping.
* <li>Exponential patterns may not contain grouping separators.
* </ul>
- * <a name="sigdig">
+ * <a name="sigdig"></a>
* <h4> <strong><font color="red">NEW</font>&nbsp;</strong> Significant
* Digits</h4>
* <p>
- * </a> {@code DecimalFormat} has two ways of controlling how many digits are
+ * {@code DecimalFormat} has two ways of controlling how many digits are
* shown: (a) significant digit counts or (b) integer and fraction digit counts.
* Integer and fraction digit counts are described above. When a formatter uses
* significant digits counts, the number of integer and fraction digits is not
@@ -487,6 +487,12 @@ import libcore.icu.NativeDecimalFormat;
* <em>escapes</em> the following character. If there is no character after
* the pad escape, then the pattern is illegal.</li>
* </ul>
+ *
+ * <h4>Serialization</h4>
+ * <p>
+ * Features marked as <strong><font color="red">NEW</font></strong> and patterns that use
+ * characters not documented above are unlikely to serialize/deserialize correctly.
+ *
* <h4>Synchronization</h4>
* <p>
* {@code DecimalFormat} objects are not synchronized. Multiple threads should
@@ -574,6 +580,7 @@ public class DecimalFormat extends NumberFormat {
*/
public void applyLocalizedPattern(String pattern) {
ndf.applyLocalizedPattern(pattern);
+ updateFieldsFromNative();
}
/**
@@ -586,7 +593,18 @@ public class DecimalFormat extends NumberFormat {
* if the pattern cannot be parsed.
*/
public void applyPattern(String pattern) {
+ // The underlying ICU4C accepts a super-set of the pattern spec documented by the Android
+ // APIs. For example, rounding increments (pattern characters '1'-'9'). They will work but
+ // see class doc for issues with serialization/deserialization they may cause.
ndf.applyPattern(pattern);
+ updateFieldsFromNative();
+ }
+
+ private void updateFieldsFromNative() {
+ maximumIntegerDigits = ndf.getMaximumIntegerDigits();
+ minimumIntegerDigits = ndf.getMinimumIntegerDigits();
+ maximumFractionDigits = ndf.getMaximumFractionDigits();
+ minimumFractionDigits = ndf.getMinimumFractionDigits();
}
/**
@@ -659,21 +677,6 @@ public class DecimalFormat extends NumberFormat {
@Override
public StringBuffer format(double value, StringBuffer buffer, FieldPosition position) {
checkBufferAndFieldPosition(buffer, position);
- // All float/double/Float/Double formatting ends up here...
- if (roundingMode == RoundingMode.UNNECESSARY) {
- // ICU4C doesn't support this rounding mode, so we have to fake it.
- try {
- setRoundingMode(RoundingMode.UP);
- String upResult = format(value, new StringBuffer(), new FieldPosition(0)).toString();
- setRoundingMode(RoundingMode.DOWN);
- String downResult = format(value, new StringBuffer(), new FieldPosition(0)).toString();
- if (!upResult.equals(downResult)) {
- throw new ArithmeticException("rounding mode UNNECESSARY but rounding required");
- }
- } finally {
- setRoundingMode(RoundingMode.UNNECESSARY);
- }
- }
buffer.append(ndf.formatDouble(value, position));
return buffer;
}
@@ -735,16 +738,6 @@ public class DecimalFormat extends NumberFormat {
}
/**
- * Returns the multiplier which is applied to the number before formatting
- * or after parsing.
- *
- * @return the multiplier.
- */
- public int getMultiplier() {
- return ndf.getMultiplier();
- }
-
- /**
* Returns the prefix which is formatted or parsed before a negative number.
*
* @return the negative prefix.
@@ -826,16 +819,10 @@ public class DecimalFormat extends NumberFormat {
// In this implementation, NativeDecimalFormat is wrapped to
// fulfill most of the format and parse feature. And this method is
// delegated to the wrapped instance of NativeDecimalFormat.
+ super.setParseIntegerOnly(value);
ndf.setParseIntegerOnly(value);
}
- /**
- * Indicates whether parsing with this decimal format will only
- * return numbers of type {@code java.lang.Integer}.
- *
- * @return {@code true} if this {@code DecimalFormat}'s parse method only
- * returns {@code java.lang.Integer}; {@code false} otherwise.
- */
@Override
public boolean isParseIntegerOnly() {
return ndf.isParseIntegerOnly();
@@ -898,9 +885,6 @@ public class DecimalFormat extends NumberFormat {
/**
* Sets the {@code DecimalFormatSymbols} used by this decimal format.
- *
- * @param value
- * the {@code DecimalFormatSymbols} to set.
*/
public void setDecimalFormatSymbols(DecimalFormatSymbols value) {
if (value != null) {
@@ -913,24 +897,17 @@ public class DecimalFormat extends NumberFormat {
/**
* Sets the currency used by this decimal format. The min and max fraction
* digits remain the same.
- *
- * @param currency
- * the currency this {@code DecimalFormat} should use.
- * @see DecimalFormatSymbols#setCurrency(Currency)
*/
@Override
public void setCurrency(Currency currency) {
- ndf.setCurrency(Currency.getInstance(currency.getCurrencyCode()));
- symbols.setCurrency(currency);
+ Currency instance = Currency.getInstance(currency.getCurrencyCode());
+ symbols.setCurrency(instance);
+ ndf.setCurrency(symbols.getCurrencySymbol(), currency.getCurrencyCode());
}
/**
- * Sets whether the decimal separator is shown when there are no fractional
+ * Sets whether the decimal separator is shown even when there are no fractional
* digits.
- *
- * @param value
- * {@code true} if the decimal separator should always be
- * formatted; {@code false} otherwise.
*/
public void setDecimalSeparatorAlwaysShown(boolean value) {
ndf.setDecimalSeparatorAlwaysShown(value);
@@ -940,20 +917,14 @@ public class DecimalFormat extends NumberFormat {
* Sets the number of digits grouped together by the grouping separator.
* This only allows to set the primary grouping size; the secondary grouping
* size can only be set with a pattern.
- *
- * @param value
- * the number of digits grouped together.
*/
public void setGroupingSize(int value) {
ndf.setGroupingSize(value);
}
/**
- * Sets whether or not grouping will be used in this format. Grouping
- * affects both parsing and formatting.
- *
- * @param value
- * {@code true} if grouping is used; {@code false} otherwise.
+ * Sets whether or not digit grouping will be used in this format. Grouping
+ * affects both formatting and parsing.
*/
@Override
public void setGroupingUsed(boolean value) {
@@ -961,9 +932,8 @@ public class DecimalFormat extends NumberFormat {
}
/**
- * Indicates whether grouping will be used in this format.
- *
- * @return {@code true} if grouping is used; {@code false} otherwise.
+ * Returns true if digit grouping is used in this format. Grouping affects both
+ * formatting and parsing.
*/
@Override
public boolean isGroupingUsed() {
@@ -974,8 +944,6 @@ public class DecimalFormat extends NumberFormat {
* Sets the maximum number of digits after the decimal point.
* If the value passed is negative then it is replaced by 0.
* Regardless of this setting, no more than 340 digits will be used.
- *
- * @param value the maximum number of fraction digits.
*/
@Override
public void setMaximumFractionDigits(int value) {
@@ -989,8 +957,6 @@ public class DecimalFormat extends NumberFormat {
* Sets the maximum number of digits before the decimal point.
* If the value passed is negative then it is replaced by 0.
* Regardless of this setting, no more than 309 digits will be used.
- *
- * @param value the maximum number of integer digits.
*/
@Override
public void setMaximumIntegerDigits(int value) {
@@ -1002,8 +968,6 @@ public class DecimalFormat extends NumberFormat {
* Sets the minimum number of digits after the decimal point.
* If the value passed is negative then it is replaced by 0.
* Regardless of this setting, no more than 340 digits will be used.
- *
- * @param value the minimum number of fraction digits.
*/
@Override
public void setMinimumFractionDigits(int value) {
@@ -1015,8 +979,6 @@ public class DecimalFormat extends NumberFormat {
* Sets the minimum number of digits before the decimal point.
* If the value passed is negative then it is replaced by 0.
* Regardless of this setting, no more than 309 digits will be used.
- *
- * @param value the minimum number of integer digits.
*/
@Override
public void setMinimumIntegerDigits(int value) {
@@ -1025,11 +987,20 @@ public class DecimalFormat extends NumberFormat {
}
/**
+ * Returns the multiplier which is applied to the number before formatting
+ * or after parsing. The multiplier is meant for tasks like parsing percentages.
+ * For example, given a multiplier of 100, 1.23 would be formatted as "123" and
+ * "123" would be parsed as 1.23.
+ */
+ public int getMultiplier() {
+ return ndf.getMultiplier();
+ }
+
+ /**
* Sets the multiplier which is applied to the number before formatting or
- * after parsing.
- *
- * @param value
- * the multiplier.
+ * after parsing. The multiplier meant for tasks like parsing percentages.
+ * For example, given a multiplier of 100, 1.23 would be formatted as "123" and
+ * "123" would be parsed as 1.23.
*/
public void setMultiplier(int value) {
ndf.setMultiplier(value);
@@ -1037,9 +1008,6 @@ public class DecimalFormat extends NumberFormat {
/**
* Sets the prefix which is formatted or parsed before a negative number.
- *
- * @param value
- * the negative prefix.
*/
public void setNegativePrefix(String value) {
ndf.setNegativePrefix(value);
@@ -1047,9 +1015,6 @@ public class DecimalFormat extends NumberFormat {
/**
* Sets the suffix which is formatted or parsed after a negative number.
- *
- * @param value
- * the negative suffix.
*/
public void setNegativeSuffix(String value) {
ndf.setNegativeSuffix(value);
@@ -1057,9 +1022,6 @@ public class DecimalFormat extends NumberFormat {
/**
* Sets the prefix which is formatted or parsed before a positive number.
- *
- * @param value
- * the positive prefix.
*/
public void setPositivePrefix(String value) {
ndf.setPositivePrefix(value);
@@ -1067,9 +1029,6 @@ public class DecimalFormat extends NumberFormat {
/**
* Sets the suffix which is formatted or parsed after a positive number.
- *
- * @param value
- * the positive suffix.
*/
public void setPositiveSuffix(String value) {
ndf.setPositiveSuffix(value);
@@ -1239,9 +1198,12 @@ public class DecimalFormat extends NumberFormat {
throw new NullPointerException("roundingMode == null");
}
this.roundingMode = roundingMode;
- if (roundingMode != RoundingMode.UNNECESSARY) { // ICU4C doesn't support UNNECESSARY.
- double roundingIncrement = 1.0 / Math.pow(10, Math.max(0, getMaximumFractionDigits()));
- ndf.setRoundingMode(roundingMode, roundingIncrement);
- }
+ // DecimalFormat does not allow specification of a rounding increment. If anything other
+ // than 0.0 is used here the resulting DecimalFormat cannot be deserialized because the
+ // serialization format does not include rounding increment information.
+ double roundingIncrement = 0.0;
+ ndf.setRoundingMode(roundingMode, roundingIncrement);
}
+
+ public String toString() { return ndf.toString(); }
}
diff --git a/luni/src/main/java/java/text/DecimalFormatSymbols.java b/luni/src/main/java/java/text/DecimalFormatSymbols.java
index 708b291..fba2d6e 100644
--- a/luni/src/main/java/java/text/DecimalFormatSymbols.java
+++ b/luni/src/main/java/java/text/DecimalFormatSymbols.java
@@ -50,7 +50,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
private char percent;
private char perMill;
private char monetarySeparator;
- private char minusSign;
+ private String minusSign;
private String infinity, NaN, currencySymbol, intlCurrencySymbol;
private transient Currency currency;
@@ -81,6 +81,11 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
* the locale.
*/
public DecimalFormatSymbols(Locale locale) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
+
+ locale = LocaleData.mapInvalidAndNullLocales(locale);
LocaleData localeData = LocaleData.get(locale);
this.zeroDigit = localeData.zeroDigit;
this.digit = '#';
@@ -179,7 +184,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
groupingSeparator == obj.groupingSeparator &&
infinity.equals(obj.infinity) &&
intlCurrencySymbol.equals(obj.intlCurrencySymbol) &&
- minusSign == obj.minusSign &&
+ minusSign.equals(obj.minusSign) &&
monetarySeparator == obj.monetarySeparator &&
NaN.equals(obj.NaN) &&
patternSeparator == obj.patternSeparator &&
@@ -288,6 +293,16 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
* @return the minus sign as a character.
*/
public char getMinusSign() {
+ if (minusSign.length() == 1) {
+ return minusSign.charAt(0);
+ }
+
+ throw new UnsupportedOperationException(
+ "Minus sign spans multiple characters: " + minusSign);
+ }
+
+ /** @hide */
+ public String getMinusSignString() {
return minusSign;
}
@@ -366,7 +381,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
result = 31*result + percent;
result = 31*result + perMill;
result = 31*result + monetarySeparator;
- result = 31*result + minusSign;
+ result = 31*result + minusSign.hashCode();
result = 31*result + exponentSeparator.hashCode();
result = 31*result + infinity.hashCode();
result = 31*result + NaN.hashCode();
@@ -487,7 +502,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
* the minus sign character.
*/
public void setMinusSign(char value) {
- this.minusSign = value;
+ this.minusSign = String.valueOf(value);
}
/**
diff --git a/luni/src/main/java/java/text/FieldPosition.java b/luni/src/main/java/java/text/FieldPosition.java
index d5bccc7..c26ba33 100644
--- a/luni/src/main/java/java/text/FieldPosition.java
+++ b/luni/src/main/java/java/text/FieldPosition.java
@@ -21,152 +21,114 @@ package java.text;
* Identifies fields in formatted strings. If a {@code FieldPosition} is passed
* to the format method with such a parameter, then the indices will be set to
* the start and end indices of the field in the formatted string.
- * <p>
- * A {@code FieldPosition} can be created by using the integer constants in the
+ *
+ * <p>A {@code FieldPosition} can be created by using the integer constants in the
* various format classes (for example {@code NumberFormat.INTEGER_FIELD}) or
* one of the fields of type {@code Format.Field}.
- * <p>
- * If more than one field information is needed, the method
+ *
+ * <p>If more than one field position is needed, the method
* {@link NumberFormat#formatToCharacterIterator(Object)} should be used.
*/
public class FieldPosition {
- private int myField, beginIndex, endIndex;
-
- private Format.Field myAttribute;
-
- /**
- * Constructs a new {@code FieldPosition} for the specified field.
- *
- * @param field
- * the field to identify.
- */
- public FieldPosition(int field) {
- myField = field;
- }
-
- /**
- * Constructs a new {@code FieldPosition} for the specified {@code Field}
- * attribute.
- *
- * @param attribute
- * the field attribute to identify.
- */
- public FieldPosition(Format.Field attribute) {
- myAttribute = attribute;
- myField = -1;
- }
-
- /**
- * Constructs a new {@code FieldPosition} for the specified {@code Field}
- * attribute and field id.
- *
- * @param attribute
- * the field attribute to identify.
- * @param field
- * the field to identify.
- */
- public FieldPosition(Format.Field attribute, int field) {
- myAttribute = attribute;
- myField = field;
- }
-
- void clear() {
- beginIndex = endIndex = 0;
- }
-
- /**
- * Compares the specified object to this field position and indicates if
- * they are equal. In order to be equal, {@code object} must be an instance
- * of {@code FieldPosition} with the same field, begin index and end index.
- *
- * @param object
- * the object to compare with this object.
- * @return {@code true} if the specified object is equal to this field
- * position; {@code false} otherwise.
- * @see #hashCode
- */
- @Override
- public boolean equals(Object object) {
- if (!(object instanceof FieldPosition)) {
- return false;
- }
- FieldPosition pos = (FieldPosition) object;
- return myField == pos.myField && myAttribute == pos.myAttribute
- && beginIndex == pos.beginIndex && endIndex == pos.endIndex;
- }
-
- /**
- * Returns the index of the beginning of the field.
- *
- * @return the first index of the field.
- */
- public int getBeginIndex() {
- return beginIndex;
- }
-
- /**
- * Returns the index one past the end of the field.
- *
- * @return one past the index of the last character in the field.
- */
- public int getEndIndex() {
- return endIndex;
- }
-
- /**
- * Returns the field which is being identified.
- *
- * @return the field constant.
- */
- public int getField() {
- return myField;
- }
-
- /**
- * Returns the attribute which is being identified.
- *
- * @return the field.
- */
- public Format.Field getFieldAttribute() {
- return myAttribute;
- }
-
- @Override
- public int hashCode() {
- int attributeHash = (myAttribute == null) ? 0 : myAttribute.hashCode();
- return attributeHash + myField * 10 + beginIndex * 100 + endIndex;
- }
-
- /**
- * Sets the index of the beginning of the field.
- *
- * @param index
- * the index of the first character in the field.
- */
- public void setBeginIndex(int index) {
- beginIndex = index;
- }
-
- /**
- * Sets the index of the end of the field.
- *
- * @param index
- * one past the index of the last character in the field.
- */
- public void setEndIndex(int index) {
- endIndex = index;
- }
-
- /**
- * Returns the string representation of this field position.
- *
- * @return the string representation of this field position.
- */
- @Override
- public String toString() {
- return getClass().getName() + "[attribute=" + myAttribute + ", field="
- + myField + ", beginIndex=" + beginIndex + ", endIndex="
- + endIndex + "]";
+ private int field;
+ private int beginIndex;
+ private int endIndex;
+ private Format.Field attribute;
+
+ /**
+ * Constructs a new {@code FieldPosition} for the given field id.
+ */
+ public FieldPosition(int field) {
+ this.field = field;
+ }
+
+ /**
+ * Constructs a new {@code FieldPosition} for the given {@code Field} attribute.
+ */
+ public FieldPosition(Format.Field attribute) {
+ this.attribute = attribute;
+ this.field = -1;
+ }
+
+ /**
+ * Constructs a new {@code FieldPosition} for the given {@code Field} attribute and field id.
+ */
+ public FieldPosition(Format.Field attribute, int field) {
+ this.attribute = attribute;
+ this.field = field;
+ }
+
+ /**
+ * Compares the given object to this field position and indicates if
+ * they are equal. In order to be equal, {@code object} must be an instance
+ * of {@code FieldPosition} with the same field, begin index and end index.
+ */
+ @Override public boolean equals(Object object) {
+ if (!(object instanceof FieldPosition)) {
+ return false;
}
+ FieldPosition pos = (FieldPosition) object;
+ return field == pos.field && this.attribute == pos.attribute &&
+ beginIndex == pos.beginIndex && endIndex == pos.endIndex;
+ }
+
+ /**
+ * Returns the index of the beginning of the field.
+ */
+ public int getBeginIndex() {
+ return beginIndex;
+ }
+
+ /**
+ * Returns the index one past the end of the field.
+ */
+ public int getEndIndex() {
+ return endIndex;
+ }
+
+ /**
+ * Returns the field which is being identified.
+ */
+ public int getField() {
+ return field;
+ }
+
+ /**
+ * Returns the attribute which is being identified.
+ */
+ public Format.Field getFieldAttribute() {
+ return attribute;
+ }
+
+ @Override public int hashCode() {
+ int attributeHash = (attribute == null) ? 0 : attribute.hashCode();
+ return attributeHash + field * 10 + beginIndex * 100 + endIndex;
+ }
+
+ /**
+ * Sets the index of the beginning of the field.
+ */
+ public void setBeginIndex(int index) {
+ beginIndex = index;
+ }
+
+ /**
+ * Sets the index of the end of the field.
+ */
+ public void setEndIndex(int index) {
+ endIndex = index;
+ }
+
+ /**
+ * Returns the string representation of this field position.
+ */
+ @Override public String toString() {
+ return getClass().getName() + "[" +
+ "attribute=" + attribute +
+ ",field=" + field +
+ ",beginIndex=" + beginIndex +
+ ",endIndex=" + endIndex +
+ "]";
+ }
}
diff --git a/luni/src/main/java/java/text/MessageFormat.java b/luni/src/main/java/java/text/MessageFormat.java
index 2ab78db..cf306a7 100644
--- a/luni/src/main/java/java/text/MessageFormat.java
+++ b/luni/src/main/java/java/text/MessageFormat.java
@@ -45,7 +45,7 @@ import libcore.util.EmptyArray;
* behavior. Any locale-specific behavior is defined by the pattern that you
* provide as well as the subformats used for inserted arguments.
*
- * <h4><a name="patterns">Patterns and their interpretation</a></h4>
+ * <h4><a name="patterns"></a>Patterns and their interpretation</h4>
*
* {@code MessageFormat} uses patterns of the following form:
* <blockquote>
@@ -321,7 +321,7 @@ import libcore.util.EmptyArray;
* // result now equals {new String("z")}
* </pre>
* </blockquote>
- * <h4><a name="synchronization">Synchronization</a></h4>
+ * <h4><a name="synchronization"></a>Synchronization</h4>
* <p>
* Message formats are not synchronized. It is recommended to create separate
* format instances for each thread. If multiple threads access a format
diff --git a/luni/src/main/java/java/text/NumberFormat.java b/luni/src/main/java/java/text/NumberFormat.java
index 36fdd0f..a1f10d4 100644
--- a/luni/src/main/java/java/text/NumberFormat.java
+++ b/luni/src/main/java/java/text/NumberFormat.java
@@ -155,8 +155,10 @@ public abstract class NumberFormat extends Format {
private boolean groupingUsed = true, parseIntegerOnly = false;
- private int maximumIntegerDigits = 40, minimumIntegerDigits = 1,
- maximumFractionDigits = 3, minimumFractionDigits = 0;
+ int maximumIntegerDigits = 40;
+ int minimumIntegerDigits = 1;
+ int maximumFractionDigits = 3;
+ int minimumFractionDigits = 0;
/**
* Used by subclasses. This was public in Java 5.
@@ -208,8 +210,7 @@ public abstract class NumberFormat extends Format {
* @return the formatted string.
*/
public final String format(double value) {
- return format(value, new StringBuffer(), new FieldPosition(0))
- .toString();
+ return format(value, new StringBuffer(), new FieldPosition(0)).toString();
}
/**
@@ -241,8 +242,7 @@ public abstract class NumberFormat extends Format {
* @return the formatted string.
*/
public final String format(long value) {
- return format(value, new StringBuffer(), new FieldPosition(0))
- .toString();
+ return format(value, new StringBuffer(), new FieldPosition(0)).toString();
}
/**
@@ -301,7 +301,11 @@ public abstract class NumberFormat extends Format {
double dv = ((Number) object).doubleValue();
return format(dv, buffer, field);
}
- throw new IllegalArgumentException("Bad class: " + object.getClass());
+ if (object == null) {
+ throw new IllegalArgumentException("Can't format null object");
+ } else {
+ throw new IllegalArgumentException("Bad class: " + object.getClass());
+ }
}
/**
@@ -349,6 +353,10 @@ public abstract class NumberFormat extends Format {
* @return a {@code NumberFormat} for handling currency values.
*/
public static NumberFormat getCurrencyInstance(Locale locale) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
+
return getInstance(LocaleData.get(locale).currencyPattern, locale);
}
@@ -372,6 +380,10 @@ public abstract class NumberFormat extends Format {
* @return a {@code NumberFormat} for handling integers.
*/
public static NumberFormat getIntegerInstance(Locale locale) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
+
NumberFormat result = getInstance(LocaleData.get(locale).integerPattern, locale);
result.setParseIntegerOnly(true);
return result;
@@ -465,6 +477,9 @@ public abstract class NumberFormat extends Format {
* @return a {@code NumberFormat} for handling {@code Number} objects.
*/
public static NumberFormat getNumberInstance(Locale locale) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
return getInstance(LocaleData.get(locale).numberPattern, locale);
}
@@ -492,6 +507,10 @@ public abstract class NumberFormat extends Format {
* treated as 5,300%, which is rarely what you intended.
*/
public static NumberFormat getPercentInstance(Locale locale) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
+
return getInstance(LocaleData.get(locale).percentPattern, locale);
}
@@ -514,11 +533,8 @@ public abstract class NumberFormat extends Format {
}
/**
- * Indicates whether this number format only parses integer numbers. Parsing
+ * Returns true if this number format only parses integer numbers. Parsing
* stops if a decimal separator is encountered.
- *
- * @return {@code true} if this number format only parses integers,
- * {@code false} if if parsese integers as well as fractions.
*/
public boolean isParseIntegerOnly() {
return parseIntegerOnly;
@@ -742,10 +758,6 @@ public abstract class NumberFormat extends Format {
* The instances of this inner class are used as attribute keys and values
* in {@code AttributedCharacterIterator} that the
* {@link NumberFormat#formatToCharacterIterator(Object)} method returns.
- * <p>
- * There is no public constructor in this class, the only instances are the
- * constants defined here.
- * <p>
*/
public static class Field extends Format.Field {
@@ -809,9 +821,6 @@ public abstract class NumberFormat extends Format {
/**
* Constructs a new instance of {@code NumberFormat.Field} with the
* given field name.
- *
- * @param fieldName
- * the field name.
*/
protected Field(String fieldName) {
super(fieldName);
diff --git a/luni/src/main/java/java/text/RuleBasedCollator.java b/luni/src/main/java/java/text/RuleBasedCollator.java
index cda06db..4e84ef7 100644
--- a/luni/src/main/java/java/text/RuleBasedCollator.java
+++ b/luni/src/main/java/java/text/RuleBasedCollator.java
@@ -20,243 +20,60 @@ package java.text;
import libcore.icu.RuleBasedCollatorICU;
/**
- * A concrete implementation class for {@code Collation}.
- * <p>
- * {@code RuleBasedCollator} has the following restrictions for efficiency
- * (other subclasses may be used for more complex languages):
- * <ol>
- * <li> If a French secondary ordering is specified it applies to the whole
- * collator object.</li>
- * <li> All non-mentioned Unicode characters are at the end of the collation
- * order.</li>
- * <li> If a character is not located in the {@code RuleBasedCollator}, the
- * default Unicode Collation Algorithm (UCA) rule-based table is automatically
- * searched as a backup.</li>
- * </ol>
- * <p>
- * The collation table is composed of a list of collation rules, where each rule
- * is of three forms:
- * <blockquote>
- * <pre>
- * &lt;modifier&gt;
- * &lt;relation&gt; &lt;text-argument&gt;
- * &lt;reset&gt; &lt;text-argument&gt;
- * </pre>
- * </blockquote>
- * <p>
- * The rule elements are defined as follows:
- * <ul type="disc">
- * <li><strong>Modifier</strong>: There is a single modifier which is used to
- * specify that all accents (secondary differences) are backwards:
- * <ul type=square>
- * <li>'@' : Indicates that accents are sorted backwards, as in French.
- * </ul>
- * </li>
- * <li><strong>Relation</strong>: The relations are the following:
- * <ul type=square>
- * <li>'&lt;' : Greater, as a letter difference (primary)
- * <li>';' : Greater, as an accent difference (secondary)
- * <li>',' : Greater, as a case difference (tertiary)
- * <li>'=' : Equal
- * </ul>
- * </li>
- * <li><strong>Text-Argument</strong>: A text-argument is any sequence of
- * characters, excluding special characters (that is, common whitespace
- * characters [0009-000D, 0020] and rule syntax characters [0021-002F,
- * 003A-0040, 005B-0060, 007B-007E]). If those characters are desired, you can
- * put them in single quotes (for example, use '&amp;' for ampersand). Note that
- * unquoted white space characters are ignored; for example, {@code b c} is
- * treated as {@code bc}.</li>
- * <li><strong>Reset</strong>: There is a single reset which is used primarily
- * for contractions and expansions, but which can also be used to add a
- * modification at the end of a set of rules:
- * <ul type=square>
- * <li>'&amp;' : Indicates that the next rule follows the position to where the reset
- * text-argument would be sorted.
- * </ul>
- * </li>
- * </ul>
- * <p>
- * This sounds more complicated than it is in practice. For example, the
- * following are equivalent ways of expressing the same thing:
- * <blockquote>
+ * A concrete subclass of {@link Collator}.
+ * It is based on the ICU RuleBasedCollator which implements the
+ * CLDR and Unicode collation algorithms.
+ *
+ * <p>Most of the time, you create a {@link Collator} instance for a {@link java.util.Locale}
+ * by calling the {@link Collator#getInstance} factory method.
+ * You can construct a {@code RuleBasedCollator} if you need a custom sort order.
+ *
+ * <p>The root collator's sort order is the CLDR root collation order
+ * which in turn is the Unicode default sort order with a few modifications.
+ * A {@code RuleBasedCollator} is built from a rule {@code String} which changes the
+ * sort order of some characters and strings relative to the default order.
+ *
+ * <p>A rule string usually contains one or more rule chains.
+ * A rule chain consists of a reset followed by one or more rules.
+ * The reset anchors the following rules in the default sort order.
+ * The rules change the order of the their characters and strings
+ * relative to the reset point.
+ *
+ * <p>A reset is an ampersand {@code &amp;} followed by one or more characters for the reset position.
+ * A rule is a relation operator, which specifies the level of difference,
+ * also followed by one or more characters.
+ * A multi-character rule creates a "contraction".
+ * A multi-character reset position usually creates "expansions".
+ *
+ * <p>For example, the following rules
+ * make "ä" sort with a diacritic-like (secondary) difference from "ae"
+ * (like in German phonebook sorting),
+ * and make "Ã¥" and "aa" sort as a base letter (primary) after "z" (like in Danish).
+ * Uppercase forms sort with a case-like (tertiary) difference after their lowercase forms.
*
- * <pre>
- * a < b < c
- * a < b & b < c
- * a < c & a < b
- * </pre>
- *
- * </blockquote>
- * <p>
- * Notice that the order is important, as the subsequent item goes immediately
- * after the text-argument. The following are not equivalent:
* <blockquote>
- *
* <pre>
- * a < b & a < c
- * a < c & a < b
+ * &amp;AE&lt;&lt;ä &lt;&lt;&lt;Ä
+ * &amp;z&lt;Ã¥&lt;&lt;&lt;Ã…&lt;&lt;&lt;aa&lt;&lt;&lt;Aa&lt;&lt;&lt;AA
* </pre>
- *
* </blockquote>
- * <p>
- * Either the text-argument must already be present in the sequence, or some
- * initial substring of the text-argument must be present. For example
- * {@code "a < b & ae < e"} is valid since "a" is present in the sequence before
- * "ae" is reset. In this latter case, "ae" is not entered and treated as a
- * single character; instead, "e" is sorted as if it were expanded to two
- * characters: "a" followed by an "e". This difference appears in natural
- * languages: in traditional Spanish "ch" is treated as if it contracts to a
- * single character (expressed as {@code "c < ch < d"}), while in traditional
- * German a-umlaut is treated as if it expands to two characters (expressed as
- * {@code "a,A < b,B ... & ae;\u00e3 & AE;\u00c3"}, where \u00e3 and \u00c3
- * are the escape sequences for a-umlaut).
- * <h4>Ignorable Characters</h4>
- * <p>
- * For ignorable characters, the first rule must start with a relation (the
- * examples we have used above are really fragments; {@code "a < b"} really
- * should be {@code "< a < b"}). If, however, the first relation is not
- * {@code "<"}, then all text-arguments up to the first {@code "<"} are
- * ignorable. For example, {@code ", - < a < b"} makes {@code "-"} an ignorable
- * character.
- * <h4>Normalization and Accents</h4>
- * <p>
- * {@code RuleBasedCollator} automatically processes its rule table to include
- * both pre-composed and combining-character versions of accented characters.
- * Even if the provided rule string contains only base characters and separate
- * combining accent characters, the pre-composed accented characters matching
- * all canonical combinations of characters from the rule string will be entered
- * in the table.
- * <p>
- * This allows you to use a RuleBasedCollator to compare accented strings even
- * when the collator is set to NO_DECOMPOSITION. However, if the strings to be
- * collated contain combining sequences that may not be in canonical order, you
- * should set the collator to CANONICAL_DECOMPOSITION to enable sorting of
- * combining sequences. For more information, see <a
- * href="http://www.aw.com/devpress">The Unicode Standard, Version 3.0</a>.
- * <h4>Errors</h4>
- * <p>
- * The following rules are not valid:
- * <ul type="disc">
- * <li>A text-argument contains unquoted punctuation symbols, for example
- * {@code "a < b-c < d"}.</li>
- * <li>A relation or reset character is not followed by a text-argument, for
- * example {@code "a < , b"}.</li>
- * <li>A reset where the text-argument (or an initial substring of the
- * text-argument) is not already in the sequence or allocated in the default UCA
- * table, for example {@code "a < b & e < f"}.</li>
- * </ul>
- * <p>
- * If you produce one of these errors, {@code RuleBasedCollator} throws a
- * {@code ParseException}.
- * <h4>Examples</h4>
- * <p>
- * Normally, to create a rule-based collator object, you will use
- * {@code Collator}'s factory method {@code getInstance}. However, to create a
- * rule-based collator object with specialized rules tailored to your needs, you
- * construct the {@code RuleBasedCollator} with the rules contained in a
- * {@code String} object. For example:
- * <blockquote>
- *
- * <pre>
- * String Simple = "< a < b < c < d";
- * RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
- * </pre>
- *
- * </blockquote>
- * <p>
- * Or:
- * <blockquote>
- *
- * <pre>
- * String Norwegian = "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I"
- * + "< j,J< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R"
- * + "< s,S< t,T< u,U< v,V< w,W< x,X< y,Y< z,Z"
- * + "< \u00E5=a\u030A,\u00C5=A\u030A"
- * + ";aa,AA< \u00E6,\u00C6< \u00F8,\u00D8";
- * RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
- * </pre>
- *
- * </blockquote>
- * <p>
- * Combining {@code Collator}s is as simple as concatenating strings. Here is
- * an example that combines two {@code Collator}s from two different locales:
- * <blockquote>
- *
- * <pre>
- * // Create an en_US Collator object
- * RuleBasedCollator en_USCollator = (RuleBasedCollator)Collator
- * .getInstance(new Locale("en", "US", ""));
- *
- * // Create a da_DK Collator object
- * RuleBasedCollator da_DKCollator = (RuleBasedCollator)Collator
- * .getInstance(new Locale("da", "DK", ""));
*
- * // Combine the two collators
- * // First, get the collation rules from en_USCollator
- * String en_USRules = en_USCollator.getRules();
- *
- * // Second, get the collation rules from da_DKCollator
- * String da_DKRules = da_DKCollator.getRules();
- *
- * RuleBasedCollator newCollator = new RuleBasedCollator(en_USRules + da_DKRules);
- * // newCollator has the combined rules
- * </pre>
- *
- * </blockquote>
- * <p>
- * The next example shows to make changes on an existing table to create a new
- * {@code Collator} object. For example, add {@code "& C < ch, cH, Ch, CH"} to
- * the {@code en_USCollator} object to create your own:
- * <blockquote>
- *
- * <pre>
- * // Create a new Collator object with additional rules
- * String addRules = "& C < ch, cH, Ch, CH";
- *
- * RuleBasedCollator myCollator = new RuleBasedCollator(en_USCollator + addRules);
- * // myCollator contains the new rules
- * </pre>
- *
- * </blockquote>
- * <p>
- * The following example demonstrates how to change the order of non-spacing
- * accents:
- * <blockquote>
- *
- * <pre>
- * // old rule
- * String oldRules = "= \u00a8 ; \u00af ; \u00bf" + "< a , A ; ae, AE ; \u00e6 , \u00c6"
- * + "< b , B < c, C < e, E & C < d, D";
- *
- * // change the order of accent characters
- * String addOn = "& \u00bf ; \u00af ; \u00a8;";
- *
- * RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
- * </pre>
- *
- * </blockquote>
- * <p>
- * The last example shows how to put new primary ordering in before the default
- * setting. For example, in the Japanese {@code Collator}, you can either sort
- * English characters before or after Japanese characters:
- * <blockquote>
- *
- * <pre>
- * // get en_US Collator rules
- * RuleBasedCollator en_USCollator = (RuleBasedCollator)
- * Collator.getInstance(Locale.US);
- *
- * // add a few Japanese character to sort before English characters
- * // suppose the last character before the first base letter 'a' in
- * // the English collation rule is \u30A2
- * String jaString = "& \u30A2 , \u30FC < \u30C8";
+ * <p>For details see
+ * <ul>
+ * <li>CLDR <a href="http://www.unicode.org/reports/tr35/tr35-collation.html#Rules">Collation Rule Syntax</a>
+ * <li>ICU User Guide <a href="http://userguide.icu-project.org/collation/customization">Collation Customization</a>
+ * </ul>
*
- * RuleBasedCollator myJapaneseCollator =
- * new RuleBasedCollator(en_USCollator.getRules() + jaString);
- * </pre>
+ * <p>Note: earlier versions of {@code RuleBasedCollator} up to and including Android 4.4 (KitKat)
+ * allowed the omission of the reset from the first rule chain.
+ * This was interpreted as an implied reset after the last non-Han script in the default order.
+ * However, this is not a useful reset position, except for large tailorings of
+ * Han characters themselves.
+ * Starting with the CLDR 24 collation specification and the ICU 53 implementation,
+ * the initial reset is required.
*
- * </blockquote>
+ * <p>If the rule string does not follow the syntax, then {@code RuleBasedCollator} throws a
+ * {@code ParseException}.
*/
public class RuleBasedCollator extends Collator {
RuleBasedCollator(RuleBasedCollatorICU wrapper) {
@@ -265,13 +82,11 @@ public class RuleBasedCollator extends Collator {
/**
* Constructs a new instance of {@code RuleBasedCollator} using the
- * specified {@code rules}. The {@code rules} are usually either
- * hand-written based on the {@link RuleBasedCollator class description} or
- * the result of a former {@link #getRules()} call.
+ * specified {@code rules}. (See the {@link RuleBasedCollator class description}.)
* <p>
- * Note that the {@code rules} are actually interpreted as a delta to the
- * standard Unicode Collation Algorithm (UCA). This differs
- * slightly from other implementations which work with full {@code rules}
+ * Note that the {@code rules} are interpreted as a delta to the
+ * default sort order. This differs
+ * from other implementations which work with full {@code rules}
* specifications and may result in different behavior.
*
* @param rules
@@ -286,9 +101,6 @@ public class RuleBasedCollator extends Collator {
if (rules == null) {
throw new NullPointerException("rules == null");
}
- if (rules.isEmpty()) {
- throw new ParseException("empty rules", 0);
- }
try {
icuColl = new RuleBasedCollatorICU(rules);
} catch (Exception e) {
@@ -336,14 +148,9 @@ public class RuleBasedCollator extends Collator {
/**
* Returns the collation rules of this collator. These {@code rules} can be
* fed into the {@code RuleBasedCollator(String)} constructor.
- * <p>
- * Note that the {@code rules} are actually interpreted as a delta to the
- * standard Unicode Collation Algorithm (UCA). Hence, an empty {@code rules}
- * string results in the default UCA rules being applied. This differs
- * slightly from other implementations which work with full {@code rules}
- * specifications and may result in different behavior.
*
- * @return the collation rules.
+ * <p>The returned string will be empty unless you constructed the instance yourself.
+ * The string forms of the collation rules are omitted to save space on the device.
*/
public String getRules() {
return icuColl.getRules();
@@ -367,13 +174,6 @@ public class RuleBasedCollator extends Collator {
* the collation rules, strength and decomposition mode for this
* {@code RuleBasedCollator}. See the {@code Collator} class description
* for an example of use.
- * <p>
- * General recommendation: If comparisons are to be done with the same strings
- * multiple times, it is more efficient to generate {@code CollationKey}
- * objects for the strings and use
- * {@code CollationKey.compareTo(CollationKey)} for the comparisons. If each
- * string is compared to only once, using
- * {@code RuleBasedCollator.compare(String, String)} has better performance.
*
* @param source
* the source text.
diff --git a/luni/src/main/java/java/text/SimpleDateFormat.java b/luni/src/main/java/java/text/SimpleDateFormat.java
index 5fd8a56..8f83ff7 100644
--- a/luni/src/main/java/java/text/SimpleDateFormat.java
+++ b/luni/src/main/java/java/text/SimpleDateFormat.java
@@ -517,7 +517,8 @@ public class SimpleDateFormat extends DateFormat {
int next, last = -1, count = 0;
calendar.setTime(date);
if (field != null) {
- field.clear();
+ field.setBeginIndex(0);
+ field.setEndIndex(0);
}
final int patternLength = pattern.length();
@@ -623,8 +624,7 @@ public class SimpleDateFormat extends DateFormat {
break;
case MILLISECOND_FIELD:
dateFormatField = Field.MILLISECOND;
- int value = calendar.get(Calendar.MILLISECOND);
- appendNumber(buffer, count, value);
+ appendMilliseconds(buffer, count, calendar.get(Calendar.MILLISECOND));
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
@@ -740,15 +740,9 @@ public class SimpleDateFormat extends DateFormat {
TimeZone tz = calendar.getTimeZone();
boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
int style = count < 4 ? TimeZone.SHORT : TimeZone.LONG;
- if (!formatData.customZoneStrings) {
- buffer.append(tz.getDisplayName(daylight, style, formatData.locale));
- return;
- }
- // We can't call TimeZone.getDisplayName() because it would not use
- // the custom DateFormatSymbols of this SimpleDateFormat.
- String custom = TimeZoneNames.getDisplayName(formatData.zoneStrings, tz.getID(), daylight, style);
- if (custom != null) {
- buffer.append(custom);
+ String zoneString = formatData.getTimeZoneDisplayName(tz, daylight, style);
+ if (zoneString != null) {
+ buffer.append(zoneString);
return;
}
}
@@ -759,21 +753,29 @@ public class SimpleDateFormat extends DateFormat {
// See http://www.unicode.org/reports/tr35/#Date_Format_Patterns for the different counts.
// @param generalTimeZone "GMT-08:00" rather than "-0800".
private void appendNumericTimeZone(StringBuffer buffer, int count, boolean generalTimeZone) {
- int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
- char sign = '+';
- if (offset < 0) {
- sign = '-';
- offset = -offset;
- }
- if (generalTimeZone || count == 4) {
- buffer.append("GMT");
+ int offsetMillis = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
+ boolean includeGmt = generalTimeZone || count == 4;
+ boolean includeMinuteSeparator = generalTimeZone || count >= 4;
+ buffer.append(TimeZone.createGmtOffsetString(includeGmt, includeMinuteSeparator,
+ offsetMillis));
+ }
+
+ private void appendMilliseconds(StringBuffer buffer, int count, int value) {
+ // Unlike other fields, milliseconds are truncated by count. So 361 formatted SS is "36".
+ numberFormat.setMinimumIntegerDigits((count > 3) ? 3 : count);
+ numberFormat.setMaximumIntegerDigits(10);
+ // We need to left-justify.
+ if (count == 1) {
+ value /= 100;
+ } else if (count == 2) {
+ value /= 10;
}
- buffer.append(sign);
- appendNumber(buffer, 2, offset / 3600000);
- if (generalTimeZone || count >= 4) {
- buffer.append(':');
+ FieldPosition p = new FieldPosition(0);
+ numberFormat.format(Integer.valueOf(value), buffer, p);
+ if (count > 3) {
+ numberFormat.setMinimumIntegerDigits(count - 3);
+ numberFormat.format(Integer.valueOf(0), buffer, p);
}
- appendNumber(buffer, 2, (offset % 3600000) / 60000);
}
private void appendNumber(StringBuffer buffer, int count, int value) {
@@ -905,8 +907,7 @@ public class SimpleDateFormat extends DateFormat {
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
- field = Calendar.MILLISECOND;
- break;
+ return parseFractionalSeconds(string, offset, absolute);
case STAND_ALONE_DAY_OF_WEEK_FIELD:
return parseDayOfWeek(string, offset, true);
case DAY_OF_WEEK_FIELD:
@@ -951,6 +952,31 @@ public class SimpleDateFormat extends DateFormat {
return offset;
}
+ /**
+ * Parses the fractional seconds section of a formatted date and assigns
+ * it to the {@code Calendar.MILLISECOND} field. Note that fractional seconds
+ * are somewhat unique, because they are zero suffixed.
+ */
+ private int parseFractionalSeconds(String string, int offset, int count) {
+ final ParsePosition parsePosition = new ParsePosition(offset);
+ final Number fractionalSeconds = parseNumber(count, string, parsePosition);
+ if (fractionalSeconds == null) {
+ return -parsePosition.getErrorIndex() - 1;
+ }
+
+ // NOTE: We could've done this using two parses instead. The first parse
+ // looking at |count| digits (to verify the date matched the format), and
+ // then a second parse that consumed just the first three digits. That
+ // would've avoided the floating point arithmetic, but would've demanded
+ // that we round values ourselves.
+ final double result = fractionalSeconds.doubleValue();
+ final int numDigitsParsed = parsePosition.getIndex() - offset;
+ final double divisor = Math.pow(10, numDigitsParsed);
+
+ calendar.set(Calendar.MILLISECOND, (int) ((result / divisor) * 1000));
+ return parsePosition.getIndex();
+ }
+
private int parseDayOfWeek(String string, int offset, boolean standAlone) {
LocaleData ld = formatData.localeData;
int index = parseText(string, offset,
@@ -1085,25 +1111,7 @@ public class SimpleDateFormat extends DateFormat {
}
if (max == 0) {
position.setIndex(index);
- Number n = numberFormat.parse(string, position);
- // In RTL locales, NumberFormat might have parsed "2012-" in an ISO date as the
- // negative number -2012.
- // Ideally, we wouldn't have this broken API that exposes a NumberFormat and expects
- // us to use it. The next best thing would be a way to ask the NumberFormat to parse
- // positive numbers only, but icu4c supports negative (BCE) years. The best we can do
- // is try to recognize when icu4c has done this, and undo it.
- if (n != null && n.longValue() < 0) {
- if (numberFormat instanceof DecimalFormat) {
- DecimalFormat df = (DecimalFormat) numberFormat;
- char lastChar = string.charAt(position.getIndex() - 1);
- char minusSign = df.getDecimalFormatSymbols().getMinusSign();
- if (lastChar == minusSign) {
- n = Long.valueOf(-n.longValue()); // Make the value positive.
- position.setIndex(position.getIndex() - 1); // Spit out the negative sign.
- }
- }
- }
- return n;
+ return numberFormat.parse(string, position);
}
int result = 0;
@@ -1168,6 +1176,8 @@ public class SimpleDateFormat extends DateFormat {
if (foundGMT) {
offset += 3;
}
+
+ // Check for an offset, which may have been preceded by "GMT"
char sign;
if (offset < string.length() && ((sign = string.charAt(offset)) == '+' || sign == '-')) {
ParsePosition position = new ParsePosition(offset + 1);
@@ -1195,10 +1205,14 @@ public class SimpleDateFormat extends DateFormat {
calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return position.getIndex();
}
+
+ // If there was "GMT" but no offset.
if (foundGMT) {
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
return offset;
}
+
+ // Exhaustively look for the string in this DateFormat's localized time zone strings.
for (String[] row : formatData.internalZoneStrings()) {
for (int i = TimeZoneNames.LONG_NAME; i < TimeZoneNames.NAME_COUNT; ++i) {
if (row[i] == null) {
diff --git a/luni/src/main/java/java/text/spi/BreakIteratorProvider.java b/luni/src/main/java/java/text/spi/BreakIteratorProvider.java
deleted file mode 100644
index a28bc53..0000000
--- a/luni/src/main/java/java/text/spi/BreakIteratorProvider.java
+++ /dev/null
@@ -1,90 +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 java.text.spi;
-
-import java.text.BreakIterator;
-import java.util.Locale;
-import java.util.spi.LocaleServiceProvider;
-
-/**
- * This abstract class should be extended by service providers that provide
- * instances of {@code BreakIterator}.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class BreakIteratorProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected BreakIteratorProvider() {
- // Do nothing.
- }
-
- /**
- * Returns an instance of {@code BreakIterator} for word breaks in the
- * given locale.
- *
- * @param locale the locale
- * @return an instance of {@code BreakIterator}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract BreakIterator getWordInstance(Locale locale);
-
- /**
- * Returns an instance of {@code BreakIterator} for line breaks in the
- * given locale.
- *
- * @param locale the locale
- * @return an instance of {@code BreakIterator}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract BreakIterator getLineInstance(Locale locale);
-
- /**
- * Returns an instance of {@code BreakIterator} for character breaks in the
- * given locale.
- *
- * @param locale the locale
- * @return an instance of {@code BreakIterator}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract BreakIterator getCharacterInstance(Locale locale);
-
- /**
- * Returns an instance of {@code BreakIterator} for sentence breaks in the
- * given locale.
- *
- * @param locale the locale
- * @return an instance of {@code BreakIterator}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract BreakIterator getSentenceInstance(Locale locale);
-}
diff --git a/luni/src/main/java/java/text/spi/CollatorProvider.java b/luni/src/main/java/java/text/spi/CollatorProvider.java
deleted file mode 100644
index 0862432..0000000
--- a/luni/src/main/java/java/text/spi/CollatorProvider.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 java.text.spi;
-
-import java.text.Collator;
-import java.util.Locale;
-import java.util.spi.LocaleServiceProvider;
-
-/**
- * This abstract class should be extended by service providers which provide
- * instances of {@code Collator}.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class CollatorProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected CollatorProvider() {
- // Do nothing.
- }
-
- /**
- * Returns an instance of {@code Collator} for the given locale.
- *
- * @param locale the locale
- * @return an instance of {@code Collator}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract Collator getInstance(Locale locale);
-}
diff --git a/luni/src/main/java/java/text/spi/DateFormatProvider.java b/luni/src/main/java/java/text/spi/DateFormatProvider.java
deleted file mode 100644
index 59fefed..0000000
--- a/luni/src/main/java/java/text/spi/DateFormatProvider.java
+++ /dev/null
@@ -1,81 +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 java.text.spi;
-
-import java.text.DateFormat;
-import java.util.Locale;
-import java.util.spi.LocaleServiceProvider;
-
-/**
- * This abstract class should be extended by service providers that provide
- * instances of {@code DateFormat}.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class DateFormatProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected DateFormatProvider() {
- // Do nothing.
- }
-
- /**
- * Returns an instance of {@code DateFormat} that formats times
- * in the given style for the given locale.
- *
- * @param style the given time formatting style.
- * @param locale the locale
- * @return an instance of {@code DateFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract DateFormat getTimeInstance(int style, Locale locale);
-
- /**
- * Returns an instance of {@code DateFormat} that formats dates
- * in the given style for the given locale.
- *
- * @param style the given date formatting style.
- * @param locale the locale
- * @return an instance of {@code DateFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract DateFormat getDateInstance(int style, Locale locale);
-
- /**
- * Returns an instance of {@code DateFormat} that formats dates and times
- * in the given style for the given locale.
- *
- * @param dateStyle the given date formatting style.
- * @param timeStyle the given time formatting style.
- * @param locale the locale
- * @return an instance of {@code DateFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale);
-}
diff --git a/luni/src/main/java/java/text/spi/DateFormatSymbolsProvider.java b/luni/src/main/java/java/text/spi/DateFormatSymbolsProvider.java
deleted file mode 100644
index cb34b71..0000000
--- a/luni/src/main/java/java/text/spi/DateFormatSymbolsProvider.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 java.text.spi;
-
-import java.text.DateFormatSymbols;
-import java.util.Locale;
-import java.util.spi.LocaleServiceProvider;
-
-/**
- * This abstract class should be extended by service providers that provide
- * instances of {@code DateFormatSymbols}.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class DateFormatSymbolsProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected DateFormatSymbolsProvider() {
- // Do nothing.
- }
-
- /**
- * Returns an instance of {@code DateFormatSymbols} for the given locale.
- *
- * @param locale the locale
- * @return an instance of {@code DateFormatSymbols}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract DateFormatSymbols getInstance(Locale locale);
-}
diff --git a/luni/src/main/java/java/text/spi/DecimalFormatSymbolsProvider.java b/luni/src/main/java/java/text/spi/DecimalFormatSymbolsProvider.java
deleted file mode 100644
index f9f5e7d..0000000
--- a/luni/src/main/java/java/text/spi/DecimalFormatSymbolsProvider.java
+++ /dev/null
@@ -1,51 +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 java.text.spi;
-
-import java.text.DecimalFormatSymbols;
-import java.util.Locale;
-import java.util.spi.LocaleServiceProvider;
-
-/**
- * This abstract class should be extended by service providers that provide
- * instances of {@code DecimalFormatSymbols}.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class DecimalFormatSymbolsProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected DecimalFormatSymbolsProvider() {
- // Do nothing.
- }
-
- /**
- * Returns an instance of {@code DecimalFormatSymbols} for the given locale.
- *
- * @param locale the locale
- * @return an instance of {@code DecimalFormatSymbols}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract DecimalFormatSymbols getInstance(Locale locale);
-
-}
diff --git a/luni/src/main/java/java/text/spi/NumberFormatProvider.java b/luni/src/main/java/java/text/spi/NumberFormatProvider.java
deleted file mode 100644
index c889f78..0000000
--- a/luni/src/main/java/java/text/spi/NumberFormatProvider.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 java.text.spi;
-
-import java.text.NumberFormat;
-import java.util.Locale;
-import java.util.spi.LocaleServiceProvider;
-
-/**
- * This abstract class should be extended by service providers that provide
- * {@code NumberFormat} instances.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class NumberFormatProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected NumberFormatProvider() {
- // Do nothing.
- }
-
- /**
- * Returns an instance of {@code NumberFormat} that formats
- * monetary values for the given locale.
- *
- * @param locale the locale
- * @return an instance of {@code NumberFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract NumberFormat getCurrencyInstance(Locale locale);
-
- /**
- * Returns an instance of {@code NumberFormat} that formats
- * integer values for the given locale. The returned {@code NumberFormat}
- * is configured to round floating point numbers to the nearest integer
- * using half-even rounding mode for formatting, and to parse only the
- * integer part of an input string.
- *
- * @param locale the locale
- * @return an instance of {@code NumberFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract NumberFormat getIntegerInstance(Locale locale);
-
- /**
- * Returns an instance of {@code NumberFormat} class for general
- * use in the given locale.
- *
- * @param locale the locale
- * @return an instance of {@code NumberFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract NumberFormat getNumberInstance(Locale locale);
-
- /**
- * Returns an instance of {@code NumberFormat} class that formats
- * percentage values for the given locale.
- *
- * @param locale the locale
- * @return an instance of {@code NumberFormat}
- * @throws NullPointerException if {@code locale == null}
- * @throws IllegalArgumentException
- * if locale isn't one of the locales returned from
- * getAvailableLocales().
- */
- public abstract NumberFormat getPercentInstance(Locale locale);
-}
diff --git a/luni/src/main/java/java/util/Arrays.java b/luni/src/main/java/java/util/Arrays.java
index d3e05a0..3b477d0 100644
--- a/luni/src/main/java/java/util/Arrays.java
+++ b/luni/src/main/java/java/util/Arrays.java
@@ -1319,31 +1319,25 @@ public class Arrays {
/*
* element is an array
*/
- if (!cl.isPrimitive()) {
+ if (element instanceof Object[]) {
return deepHashCode((Object[]) element);
- }
- if (cl.equals(int.class)) {
+ } else if (cl == int.class) {
return hashCode((int[]) element);
- }
- if (cl.equals(char.class)) {
+ } else if (cl == char.class) {
return hashCode((char[]) element);
- }
- if (cl.equals(boolean.class)) {
+ } else if (cl == boolean.class) {
return hashCode((boolean[]) element);
- }
- if (cl.equals(byte.class)) {
+ } else if (cl == byte.class) {
return hashCode((byte[]) element);
- }
- if (cl.equals(long.class)) {
+ } else if (cl == long.class) {
return hashCode((long[]) element);
- }
- if (cl.equals(float.class)) {
+ } else if (cl == float.class) {
return hashCode((float[]) element);
- }
- if (cl.equals(double.class)) {
+ } else if (cl == double.class) {
return hashCode((double[]) element);
+ } else {
+ return hashCode((short[]) element);
}
- return hashCode((short[]) element);
}
/**
@@ -1665,32 +1659,25 @@ public class Arrays {
/*
* compare as arrays
*/
- if (!cl1.isPrimitive()) {
+ if (e1 instanceof Object[]) {
return deepEquals((Object[]) e1, (Object[]) e2);
- }
-
- if (cl1.equals(int.class)) {
+ } else if (cl1 == int.class) {
return equals((int[]) e1, (int[]) e2);
- }
- if (cl1.equals(char.class)) {
+ } else if (cl1 == char.class) {
return equals((char[]) e1, (char[]) e2);
- }
- if (cl1.equals(boolean.class)) {
+ } else if (cl1 == boolean.class) {
return equals((boolean[]) e1, (boolean[]) e2);
- }
- if (cl1.equals(byte.class)) {
+ } else if (cl1 == byte.class) {
return equals((byte[]) e1, (byte[]) e2);
- }
- if (cl1.equals(long.class)) {
+ } else if (cl1 == long.class) {
return equals((long[]) e1, (long[]) e2);
- }
- if (cl1.equals(float.class)) {
+ } else if (cl1 == float.class) {
return equals((float[]) e1, (float[]) e2);
- }
- if (cl1.equals(double.class)) {
+ } else if (cl1 == double.class) {
return equals((double[]) e1, (double[]) e2);
+ } else {
+ return equals((short[]) e1, (short[]) e2);
}
- return equals((short[]) e1, (short[]) e2);
}
/**
diff --git a/luni/src/main/java/java/util/Calendar.java b/luni/src/main/java/java/util/Calendar.java
index 4ed2ad1..fc4cef6 100644
--- a/luni/src/main/java/java/util/Calendar.java
+++ b/luni/src/main/java/java/util/Calendar.java
@@ -642,13 +642,24 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
/**
* Field number for {@code get} and {@code set} indicating the
- * raw offset from GMT in milliseconds.
+ * raw (non-DST) offset from GMT in milliseconds.
+ * Equivalent to {@link java.util.TimeZone#getRawOffset}.
+ *
+ * <p>To determine the total offset from GMT at the time represented
+ * by this calendar, you will need to add the {@code ZONE_OFFSET} and
+ * {@code DST_OFFSET} fields.
*/
public static final int ZONE_OFFSET = 15;
/**
* Field number for {@code get} and {@code set} indicating the
- * daylight savings offset in milliseconds.
+ * daylight savings offset from the {@code ZONE_OFFSET} in milliseconds.
+ * Equivalent to {@link java.util.TimeZone#getDSTSavings} if the represented time
+ * falls inside DST, or 0 otherwise.
+ *
+ * <p>To determine the total offset from GMT at the time represented
+ * by this calendar, you will need to add the {@code ZONE_OFFSET} and
+ * {@code DST_OFFSET} fields.
*/
public static final int DST_OFFSET = 16;
@@ -716,6 +727,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
*/
protected Calendar(TimeZone timezone, Locale locale) {
this(timezone);
+ locale = LocaleData.mapInvalidAndNullLocales(locale);
LocaleData localeData = LocaleData.get(locale);
setFirstDayOfWeek(localeData.firstDayOfWeek.intValue());
setMinimalDaysInFirstWeek(localeData.minimalDaysInFirstWeek.intValue());
diff --git a/luni/src/main/java/java/util/Collections.java b/luni/src/main/java/java/util/Collections.java
index ce4e579..4541d64 100644
--- a/luni/src/main/java/java/util/Collections.java
+++ b/luni/src/main/java/java/util/Collections.java
@@ -1212,7 +1212,7 @@ public class Collections {
int length = c.size();
Object[] result = new Object[length];
Iterator<?> it = iterator();
- for (int i = length; --i >= 0;) {
+ for (int i = 0; i < length; i++) {
result[i] = it.next();
}
return result;
diff --git a/luni/src/main/java/java/util/Currency.java b/luni/src/main/java/java/util/Currency.java
index b5b04a0..f43ddae 100644
--- a/luni/src/main/java/java/util/Currency.java
+++ b/luni/src/main/java/java/util/Currency.java
@@ -35,7 +35,7 @@ public final class Currency implements Serializable {
private Currency(String currencyCode) {
this.currencyCode = currencyCode;
- String symbol = ICU.getCurrencySymbol(Locale.US.toString(), currencyCode);
+ String symbol = ICU.getCurrencySymbol(Locale.US, currencyCode);
if (symbol == null) {
throw new IllegalArgumentException("Unsupported ISO 4217 currency code: " +
currencyCode);
@@ -65,6 +65,9 @@ public final class Currency implements Serializable {
*/
public static Currency getInstance(Locale locale) {
synchronized (localesToCurrencies) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
Currency currency = localesToCurrencies.get(locale);
if (currency != null) {
return currency;
@@ -123,7 +126,7 @@ public final class Currency implements Serializable {
* @since 1.7
*/
public String getDisplayName(Locale locale) {
- return ICU.getCurrencyDisplayName(locale.toString(), currencyCode);
+ return ICU.getCurrencyDisplayName(locale, currencyCode);
}
/**
@@ -146,10 +149,9 @@ public final class Currency implements Serializable {
* <p>If there is no locale-specific currency symbol, the ISO 4217 currency code is returned.
*/
public String getSymbol(Locale locale) {
- if (locale.getCountry().length() == 0) {
- return currencyCode;
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
}
-
// Check the locale first, in case the locale has the same currency.
LocaleData localeData = LocaleData.get(locale);
if (localeData.internationalCurrencySymbol.equals(currencyCode)) {
@@ -157,7 +159,7 @@ public final class Currency implements Serializable {
}
// Try ICU, and fall back to the currency code if ICU has nothing.
- String symbol = ICU.getCurrencySymbol(locale.toString(), currencyCode);
+ String symbol = ICU.getCurrencySymbol(locale, currencyCode);
return symbol != null ? symbol : currencyCode;
}
diff --git a/luni/src/main/java/java/util/EnumMap.java b/luni/src/main/java/java/util/EnumMap.java
index 827fb51..dfacb46 100644
--- a/luni/src/main/java/java/util/EnumMap.java
+++ b/luni/src/main/java/java/util/EnumMap.java
@@ -174,7 +174,7 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> implements
@Override
@SuppressWarnings("unchecked")
public String toString() {
- if (-1 == prePosition) {
+ if (prePosition == -1) {
return super.toString();
}
return type.get(
@@ -183,7 +183,7 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> implements
}
private void checkStatus() {
- if (-1 == prePosition) {
+ if (prePosition == -1) {
throw new IllegalStateException();
}
}
diff --git a/luni/src/main/java/java/util/Formatter.java b/luni/src/main/java/java/util/Formatter.java
index 98bdccc..dd9a09a 100644
--- a/luni/src/main/java/java/util/Formatter.java
+++ b/luni/src/main/java/java/util/Formatter.java
@@ -2065,7 +2065,7 @@ public final class Formatter implements Closeable, Flushable {
formatToken.setPrecision(FormatToken.UNSET);
int startIndex = 0;
- if (result.charAt(0) == localeData.minusSign) {
+ if (startsWithMinusSign(result, localeData.minusSign)) {
if (formatToken.flagParenthesis) {
return wrapParentheses(result);
}
@@ -2081,8 +2081,9 @@ public final class Formatter implements Closeable, Flushable {
}
char firstChar = result.charAt(0);
- if (formatToken.flagZero && (firstChar == '+' || firstChar == localeData.minusSign)) {
- startIndex = 1;
+ if (formatToken.flagZero && (firstChar == '+' ||
+ startsWithMinusSign(result, localeData.minusSign))) {
+ startIndex = localeData.minusSign.length();
}
if (conversionType == 'a' || conversionType == 'A') {
@@ -2091,6 +2092,20 @@ public final class Formatter implements Closeable, Flushable {
return padding(result, startIndex);
}
+ private static boolean startsWithMinusSign(CharSequence cs, String minusSign) {
+ if (cs.length() < minusSign.length()) {
+ return false;
+ }
+
+ for (int i = 0; i < minusSign.length(); ++i) {
+ if (minusSign.charAt(i) != cs.charAt(i)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
private void transformE(StringBuilder result) {
// All zeros in this method are *pattern* characters, so no localization.
final int precision = formatToken.getPrecision();
diff --git a/luni/src/main/java/java/util/GregorianCalendar.java b/luni/src/main/java/java/util/GregorianCalendar.java
index 9ff9ccc..be96684 100644
--- a/luni/src/main/java/java/util/GregorianCalendar.java
+++ b/luni/src/main/java/java/util/GregorianCalendar.java
@@ -331,7 +331,16 @@ public class GregorianCalendar extends Calendar {
setTimeInMillis(System.currentTimeMillis());
}
- GregorianCalendar(boolean ignored) {
+ /**
+ * A minimum-cost constructor that does not initialize the current time or perform any date
+ * calculations. For use internally when the time will be set later. Other constructors, such as
+ * {@link GregorianCalendar#GregorianCalendar()}, set the time to the current system clock
+ * and recalculate the fields incurring unnecessary cost when the time or fields will be set
+ * later.
+ *
+ * @hide used internally
+ */
+ public GregorianCalendar(boolean ignored) {
super(TimeZone.getDefault());
setFirstDayOfWeek(SUNDAY);
setMinimalDaysInFirstWeek(1);
@@ -458,16 +467,17 @@ public class GregorianCalendar extends Calendar {
complete();
}
- private void fullFieldsCalc(long timeVal, int zoneOffset) {
+ private void fullFieldsCalc() {
int millis = (int) (time % 86400000);
- long days = timeVal / 86400000;
+ long days = time / 86400000;
if (millis < 0) {
millis += 86400000;
days--;
}
- // Cannot add ZONE_OFFSET to time as it might overflow
- millis += zoneOffset;
+ // Adding fields[ZONE_OFFSET] to time might make it overflow, so we add
+ // it to millis (the number of milliseconds in the current day) instead.
+ millis += fields[ZONE_OFFSET];
while (millis < 0) {
millis += 86400000;
days--;
@@ -477,9 +487,9 @@ public class GregorianCalendar extends Calendar {
days++;
}
- int dayOfYear = computeYearAndDay(days, timeVal + zoneOffset);
+ int dayOfYear = computeYearAndDay(days, time + fields[ZONE_OFFSET]);
fields[DAY_OF_YEAR] = dayOfYear;
- if(fields[YEAR] == changeYear && gregorianCutover <= timeVal + zoneOffset){
+ if (fields[YEAR] == changeYear && gregorianCutover <= time + fields[ZONE_OFFSET]){
dayOfYear += currentYearSkew;
}
int month = dayOfYear / 32;
@@ -493,7 +503,7 @@ public class GregorianCalendar extends Calendar {
int dstOffset = fields[YEAR] <= 0 ? 0 : getTimeZone().getOffset(AD,
fields[YEAR], month, date, fields[DAY_OF_WEEK], millis);
if (fields[YEAR] > 0) {
- dstOffset -= zoneOffset;
+ dstOffset -= fields[ZONE_OFFSET];
}
fields[DST_OFFSET] = dstOffset;
if (dstOffset != 0) {
@@ -507,10 +517,10 @@ public class GregorianCalendar extends Calendar {
days++;
}
if (oldDays != days) {
- dayOfYear = computeYearAndDay(days, timeVal - zoneOffset
+ dayOfYear = computeYearAndDay(days, time - fields[ZONE_OFFSET]
+ dstOffset);
fields[DAY_OF_YEAR] = dayOfYear;
- if(fields[YEAR] == changeYear && gregorianCutover <= timeVal - zoneOffset + dstOffset){
+ if(fields[YEAR] == changeYear && gregorianCutover <= time - fields[ZONE_OFFSET] + dstOffset){
dayOfYear += currentYearSkew;
}
month = dayOfYear / 32;
@@ -567,10 +577,26 @@ public class GregorianCalendar extends Calendar {
TimeZone timeZone = getTimeZone();
int dstOffset = timeZone.inDaylightTime(new Date(time)) ? timeZone.getDSTSavings() : 0;
int zoneOffset = timeZone.getRawOffset();
+
+ // We unconditionally overwrite DST_OFFSET and ZONE_OFFSET with
+ // values from the timezone that's currently in use. This gives us
+ // much more consistent behavior, and matches ICU4J behavior (though
+ // it is inconsistent with the RI).
+ //
+ // Anything callers can do with ZONE_OFFSET they can do by constructing
+ // a SimpleTimeZone with the required offset.
+ //
+ // DST_OFFSET is a bit of a WTF, given that it's dependent on the rest
+ // of the fields. There's no sensible reason we'd want to allow it to
+ // be set, nor can we implement consistent full-fields calculation after
+ // this field is set without maintaining a large deal of additional state.
+ //
+ // At the very least, we will need isSet to differentiate between fields
+ // set by the user and fields set by our internal field calculation.
fields[DST_OFFSET] = dstOffset;
fields[ZONE_OFFSET] = zoneOffset;
- fullFieldsCalc(time, zoneOffset);
+ fullFieldsCalc();
for (int i = 0; i < FIELD_COUNT; i++) {
isSet[i] = true;
@@ -670,8 +696,16 @@ public class GregorianCalendar extends Calendar {
if (useMonth
&& (lastDateFieldSet == DAY_OF_WEEK || lastDateFieldSet == WEEK_OF_YEAR)) {
if (isSet[WEEK_OF_YEAR] && isSet[DAY_OF_WEEK]) {
- useMonth = lastDateFieldSet != WEEK_OF_YEAR && weekMonthSet
- && isSet[DAY_OF_WEEK];
+ if (lastDateFieldSet == WEEK_OF_YEAR) {
+ useMonth = false;
+ } else if (lastDateFieldSet == DAY_OF_WEEK) {
+ // DAY_OF_WEEK belongs to both the Month + Week + Day and the
+ // WeekOfYear + Day combinations. We're supposed to use the most
+ // recent combination, as specified by the single set field. We can't
+ // know for sure in this case, so we always prefer the week-month-day
+ // combination if week-month is already set.
+ useMonth = weekMonthSet;
+ }
} else if (isSet[DAY_OF_YEAR]) {
useMonth = isSet[DATE] && isSet[MONTH];
}
diff --git a/luni/src/main/java/java/util/HashMap.java b/luni/src/main/java/java/util/HashMap.java
index 80fbd0c..b6fe646 100644
--- a/luni/src/main/java/java/util/HashMap.java
+++ b/luni/src/main/java/java/util/HashMap.java
@@ -297,12 +297,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return e == null ? null : e.value;
}
- // Doug Lea's supplemental secondaryHash function (inlined).
- // Replace with Collections.secondaryHash when the VM is fast enough (http://b/8290590).
- int hash = key.hashCode();
- hash ^= (hash >>> 20) ^ (hash >>> 12);
- hash ^= (hash >>> 7) ^ (hash >>> 4);
-
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
e != null; e = e.next) {
@@ -327,12 +322,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return entryForNullKey != null;
}
- // Doug Lea's supplemental secondaryHash function (inlined).
- // Replace with Collections.secondaryHash when the VM is fast enough (http://b/8290590).
- int hash = key.hashCode();
- hash ^= (hash >>> 20) ^ (hash >>> 12);
- hash ^= (hash >>> 7) ^ (hash >>> 4);
-
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
e != null; e = e.next) {
@@ -344,15 +334,6 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return false;
}
- // Doug Lea's supplemental secondaryHash function (non-inlined).
- // Replace with Collections.secondaryHash when the VM is fast enough (http://b/8290590).
- static int secondaryHash(Object key) {
- int hash = key.hashCode();
- hash ^= (hash >>> 20) ^ (hash >>> 12);
- hash ^= (hash >>> 7) ^ (hash >>> 4);
- return hash;
- }
-
/**
* Returns whether this map contains the specified value.
*
@@ -401,7 +382,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return putValueForNullKey(value);
}
- int hash = secondaryHash(key);
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
int index = hash & (tab.length - 1);
for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
@@ -464,7 +445,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return;
}
- int hash = secondaryHash(key);
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
int index = hash & (tab.length - 1);
HashMapEntry<K, V> first = tab[index];
@@ -632,7 +613,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
if (key == null) {
return removeNullKey();
}
- int hash = secondaryHash(key);
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
int index = hash & (tab.length - 1);
for (HashMapEntry<K, V> e = tab[index], prev = null;
@@ -852,7 +833,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return e != null && Objects.equal(value, e.value);
}
- int hash = secondaryHash(key);
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
int index = hash & (tab.length - 1);
for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
@@ -880,7 +861,7 @@ public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Seria
return true;
}
- int hash = secondaryHash(key);
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
int index = hash & (tab.length - 1);
for (HashMapEntry<K, V> e = tab[index], prev = null;
diff --git a/luni/src/main/java/java/util/IllformedLocaleException.java b/luni/src/main/java/java/util/IllformedLocaleException.java
new file mode 100644
index 0000000..3dec1cd
--- /dev/null
+++ b/luni/src/main/java/java/util/IllformedLocaleException.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2014 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 java.util;
+
+/**
+ * Thrown when a locale subtag or field is not well formed.
+ *
+ * See {@link Locale} and {@link Locale.Builder}.
+ *
+ * @since 1.7
+ */
+public class IllformedLocaleException extends RuntimeException {
+
+ private final int errorIndex;
+
+ /**
+ * Constructs a new instance with no detail message and an error index
+ * of {@code -1}.
+ */
+ public IllformedLocaleException() {
+ this(null, -1);
+ }
+
+ /**
+ * Constructs a new instance with the specified error message.
+ */
+ public IllformedLocaleException(String message) {
+ this(message, -1);
+ }
+
+ /**
+ * Constructs a new instance with the specified error message and
+ * error index.
+ */
+ public IllformedLocaleException(String message, int errorIndex) {
+ super(message);
+ this.errorIndex = errorIndex;
+ }
+
+ public int getErrorIndex() {
+ return errorIndex;
+ }
+}
diff --git a/luni/src/main/java/java/util/LinkedHashMap.java b/luni/src/main/java/java/util/LinkedHashMap.java
index e61b0f9..3d6e6c3 100644
--- a/luni/src/main/java/java/util/LinkedHashMap.java
+++ b/luni/src/main/java/java/util/LinkedHashMap.java
@@ -74,7 +74,7 @@ public class LinkedHashMap<K, V> extends HashMap<K, V> {
*
* @param initialCapacity
* the initial capacity of this map.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* when the capacity is less than zero.
*/
public LinkedHashMap(int initialCapacity) {
@@ -247,8 +247,7 @@ public class LinkedHashMap<K, V> extends HashMap<K, V> {
return e.value;
}
- // Replace with Collections.secondaryHash when the VM is fast enough (http://b/8290590).
- int hash = secondaryHash(key);
+ int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
e != null; e = e.next) {
diff --git a/luni/src/main/java/java/util/Locale.java b/luni/src/main/java/java/util/Locale.java
index fc8f7c6..a6368e8 100644
--- a/luni/src/main/java/java/util/Locale.java
+++ b/luni/src/main/java/java/util/Locale.java
@@ -22,6 +22,7 @@ import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
import libcore.icu.ICU;
/**
@@ -40,7 +41,7 @@ import libcore.icu.ICU;
* rewriting happens even if you construct your own {@code Locale} object, not just for
* instances returned by the various lookup methods.
*
- * <a name="available_locales"><h3>Available locales</h3></a>
+ * <a name="available_locales"></a><h3>Available locales</h3>
* <p>This class' constructors do no error checking. You can create a {@code Locale} for languages
* and countries that don't exist, and you can create instances for combinations that don't
* exist (such as "de_US" for "German as spoken in the US").
@@ -59,7 +60,7 @@ import libcore.icu.ICU;
* device you're running on, or {@link Locale#getAvailableLocales} to get a list of all the locales
* available on the device you're running on.
*
- * <a name="locale_data"><h3>Locale data</h3></a>
+ * <a name="locale_data"></a><h3>Locale data</h3>
* <p>Note that locale data comes solely from ICU. User-supplied locale service providers (using
* the {@code java.text.spi} or {@code java.util.spi} mechanisms) are not supported.
*
@@ -79,24 +80,28 @@ import libcore.icu.ICU;
* <td><a href="http://cldr.unicode.org/index/downloads/cldr-1-8">CLDR 1.8</a></td>
* <td><a href="http://www.unicode.org/versions/Unicode5.2.0/">Unicode 5.2</a></td></tr>
* <tr><td>Android 4.0 (Ice Cream Sandwich)</td>
- * <td>ICU 4.6</td>
+ * <td><a href="http://site.icu-project.org/download/46">ICU 4.6</a></td>
* <td><a href="http://cldr.unicode.org/index/downloads/cldr-1-9">CLDR 1.9</a></td>
* <td><a href="http://www.unicode.org/versions/Unicode6.0.0/">Unicode 6.0</a></td></tr>
* <tr><td>Android 4.1 (Jelly Bean)</td>
- * <td>ICU 4.8</td>
+ * <td><a href="http://site.icu-project.org/download/48">ICU 4.8</a></td>
* <td><a href="http://cldr.unicode.org/index/downloads/cldr-2-0">CLDR 2.0</a></td>
* <td><a href="http://www.unicode.org/versions/Unicode6.0.0/">Unicode 6.0</a></td></tr>
* <tr><td>Android 4.3 (Jelly Bean MR2)</td>
- * <td>ICU 50</td>
+ * <td><a href="http://site.icu-project.org/download/50">ICU 50</a></td>
* <td><a href="http://cldr.unicode.org/index/downloads/cldr-22-1">CLDR 22.1</a></td>
* <td><a href="http://www.unicode.org/versions/Unicode6.2.0/">Unicode 6.2</a></td></tr>
* <tr><td>Android 4.4 (KitKat)</td>
- * <td>ICU 51</td>
+ * <td><a href="http://site.icu-project.org/download/51">ICU 51</a></td>
* <td><a href="http://cldr.unicode.org/index/downloads/cldr-23">CLDR 23</a></td>
* <td><a href="http://www.unicode.org/versions/Unicode6.2.0/">Unicode 6.2</a></td></tr>
+ * <tr><td>Android 5.0 (Lollipop)</td>
+ * <td><a href="http://site.icu-project.org/download/53">ICU 53</a></td>
+ * <td><a href="http://cldr.unicode.org/index/downloads/cldr-25">CLDR 25</a></td>
+ * <td><a href="http://www.unicode.org/versions/Unicode6.3.0/">Unicode 6.3</a></td></tr>
* </table>
*
- * <a name="default_locale"><h3>Be wary of the default locale</h3></a>
+ * <a name="default_locale"></a><h3>Be wary of the default locale</h3>
* <p>Note that there are many convenience methods that automatically use the default locale, but
* using them may lead to subtle bugs.
*
@@ -243,6 +248,31 @@ public final class Locale implements Cloneable, Serializable {
public static final Locale US = new Locale(true, "en", "US");
/**
+ * BCP-47 extension identifier (or "singleton") for the private
+ * use extension.
+ *
+ * See {@link #getExtension(char)} and {@link Builder#setExtension(char, String)}.
+ *
+ * @since 1.7
+ */
+ public static final char PRIVATE_USE_EXTENSION = 'x';
+
+ /**
+ * BCP-47 extension identifier (or "singleton") for the unicode locale extension.
+ *
+ *
+ * See {@link #getExtension(char)} and {@link Builder#setExtension(char, String)}.
+ *
+ * @since 1.7
+ */
+ public static final char UNICODE_LOCALE_EXTENSION = 'u';
+
+ /**
+ * ISO 639-3 generic code for undetermined languages.
+ */
+ private static final String UNDETERMINED_LANGUAGE = "und";
+
+ /**
* The current default locale. It is temporarily assigned to US because we
* need a default locale to lookup the real default locale.
*/
@@ -255,70 +285,663 @@ public final class Locale implements Cloneable, Serializable {
defaultLocale = new Locale(language, region, variant);
}
+ /**
+ * A class that helps construct {@link Locale} instances.
+ *
+ * Unlike the public {@code Locale} constructors, the methods of this class
+ * perform much stricter checks on their input.
+ *
+ * Validity checks on the {@code language}, {@code country}, {@code variant}
+ * and {@code extension} values are carried out as per the
+ * <a href="https://tools.ietf.org/html/bcp47">BCP-47</a> specification.
+ *
+ * In addition, we treat the <a href="http://www.unicode.org/reports/tr35/">
+ * Unicode locale extension</a> specially and provide methods to manipulate
+ * the structured state (keywords and attributes) specified therein.
+ *
+ * @since 1.7
+ */
+ public static final class Builder {
+ private String language;
+ private String region;
+ private String variant;
+ private String script;
+
+ private final Set<String> attributes;
+ private final Map<String, String> keywords;
+ private final Map<Character, String> extensions;
+
+ public Builder() {
+ language = region = variant = script = "";
+
+ // NOTE: We use sorted maps in the builder & the locale class itself
+ // because serialized forms of the unicode locale extension (and
+ // of the extension map itself) are specified to be in alphabetic
+ // order of keys.
+ attributes = new TreeSet<String>();
+ keywords = new TreeMap<String, String>();
+ extensions = new TreeMap<Character, String>();
+ }
+
+ /**
+ * Sets the locale language. If {@code language} is {@code null} or empty, the
+ * previous value is cleared.
+ *
+ * As per BCP-47, the language must be between 2 and 3 ASCII characters
+ * in length and must only contain characters in the range {@code [a-zA-Z]}.
+ *
+ * This value is usually an <a href="http://www.loc.gov/standards/iso639-2/">
+ * ISO-639-2</a> alpha-2 or alpha-3 code, though no explicit checks are
+ * carried out that it's a valid code in that namespace.
+ *
+ * Values are normalized to lower case.
+ *
+ * Note that we don't support BCP-47 "extlang" languages because they were
+ * only ever used to substitute for a lack of 3 letter language codes.
+ *
+ * @throws IllformedLocaleException if the language was invalid.
+ */
+ public Builder setLanguage(String language) {
+ this.language = normalizeAndValidateLanguage(language, true /* strict */);
+ return this;
+ }
+
+ private static String normalizeAndValidateLanguage(String language, boolean strict) {
+ if (language == null || language.isEmpty()) {
+ return "";
+ }
+
+ final String lowercaseLanguage = language.toLowerCase(Locale.ROOT);
+ if (!isValidBcp47Alpha(lowercaseLanguage, 2, 3)) {
+ if (strict) {
+ throw new IllformedLocaleException("Invalid language: " + language);
+ } else {
+ return UNDETERMINED_LANGUAGE;
+ }
+ }
+
+ return lowercaseLanguage;
+ }
+
+ /**
+ * Set the state of this builder to the parsed contents of the BCP-47 language
+ * tag {@code languageTag}.
+ *
+ * This method is equivalent to a call to {@link #clear} if {@code languageTag}
+ * is {@code null} or empty.
+ *
+ * <b>NOTE:</b> In contrast to {@link Locale#forLanguageTag(String)}, which
+ * simply ignores malformed input, this method will throw an exception if
+ * its input is malformed.
+ *
+ * @throws IllformedLocaleException if {@code languageTag} is not a well formed
+ * BCP-47 tag.
+ */
+ public Builder setLanguageTag(String languageTag) {
+ if (languageTag == null || languageTag.isEmpty()) {
+ clear();
+ return this;
+ }
+
+ final Locale fromIcu = forLanguageTag(languageTag, true /* strict */);
+ // When we ask ICU for strict parsing, it might return a null locale
+ // if the language tag is malformed.
+ if (fromIcu == null) {
+ throw new IllformedLocaleException("Invalid languageTag: " + languageTag);
+ }
+
+ setLocale(fromIcu);
+ return this;
+ }
+
+ /**
+ * Sets the locale region. If {@code region} is {@code null} or empty, the
+ * previous value is cleared.
+ *
+ * As per BCP-47, the region must either be a 2 character ISO-3166-1 code
+ * (each character in the range [a-zA-Z]) OR a 3 digit UN M.49 code.
+ *
+ * Values are normalized to upper case.
+ *
+ * @throws IllformedLocaleException if {@code} region is invalid.
+ */
+ public Builder setRegion(String region) {
+ this.region = normalizeAndValidateRegion(region, true /* strict */);
+ return this;
+ }
+
+ private static String normalizeAndValidateRegion(String region, boolean strict) {
+ if (region == null || region.isEmpty()) {
+ return "";
+ }
+
+ final String uppercaseRegion = region.toUpperCase(Locale.ROOT);
+ if (!isValidBcp47Alpha(uppercaseRegion, 2, 2) &&
+ !isUnM49AreaCode(uppercaseRegion)) {
+ if (strict) {
+ throw new IllformedLocaleException("Invalid region: " + region);
+ } else {
+ return "";
+ }
+ }
+
+ return uppercaseRegion;
+ }
+
+ /**
+ * Sets the locale variant. If {@code variant} is {@code null} or empty,
+ * the previous value is cleared.
+ *
+ * The input string my consist of one or more variants separated by
+ * valid separators ('-' or '_').
+ *
+ * As per BCP-47, each variant must be between 5 and 8 alphanumeric characters
+ * in length (each character in the range {@code [a-zA-Z0-9]}) but
+ * can be exactly 4 characters in length if the first character is a digit.
+ *
+ * Note that this is a much stricter interpretation of {@code variant}
+ * than the public {@code Locale} constructors. The latter allowed free form
+ * variants.
+ *
+ * Variants are case sensitive and all separators are normalized to {@code '_'}.
+ *
+ * @throws IllformedLocaleException if {@code} variant is invalid.
+ */
+ public Builder setVariant(String variant) {
+ this.variant = normalizeAndValidateVariant(variant);
+ return this;
+ }
+
+ private static String normalizeAndValidateVariant(String variant) {
+ if (variant == null || variant.isEmpty()) {
+ return "";
+ }
+
+ // Note that unlike extensions, we canonicalize to lower case alphabets
+ // and underscores instead of hyphens.
+ final String normalizedVariant = variant.replace('-', '_');
+ String[] subTags = normalizedVariant.split("_");
+
+ for (String subTag : subTags) {
+ if (!isValidVariantSubtag(subTag)) {
+ throw new IllformedLocaleException("Invalid variant: " + variant);
+ }
+ }
+
+ return normalizedVariant;
+ }
+
+ private static boolean isValidVariantSubtag(String subTag) {
+ // The BCP-47 spec states that :
+ // - Subtags can be between [5, 8] alphanumeric chars in length.
+ // - Subtags that start with a number are allowed to be 4 chars in length.
+ if (subTag.length() >= 5 && subTag.length() <= 8) {
+ if (isAsciiAlphaNum(subTag)) {
+ return true;
+ }
+ } else if (subTag.length() == 4) {
+ final char firstChar = subTag.charAt(0);
+ if ((firstChar >= '0' && firstChar <= '9') && isAsciiAlphaNum(subTag)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Sets the locale script. If {@code script} is {@code null} or empty,
+ * the previous value is cleared.
+ *
+ * As per BCP-47, the script must be 4 characters in length, and
+ * each character in the range {@code [a-zA-Z]}.
+ *
+ * A script usually represents a valid ISO 15924 script code, though no
+ * other registry or validity checks are performed.
+ *
+ * Scripts are normalized to title cased values.
+ *
+ * @throws IllformedLocaleException if {@code script} is invalid.
+ */
+ public Builder setScript(String script) {
+ this.script = normalizeAndValidateScript(script, true /* strict */);
+ return this;
+ }
+
+ private static String normalizeAndValidateScript(String script, boolean strict) {
+ if (script == null || script.isEmpty()) {
+ return "";
+ }
+
+ if (!isValidBcp47Alpha(script, 4, 4)) {
+ if (strict) {
+ throw new IllformedLocaleException("Invalid script: " + script);
+ } else {
+ return "";
+ }
+ }
+
+ return titleCaseAsciiWord(script);
+ }
+
+ /**
+ * Sets the state of the builder to the {@link Locale} represented by
+ * {@code locale}.
+ *
+ * Note that the locale's language, region and variant are validated as per
+ * the rules specified in {@link #setLanguage}, {@link #setRegion} and
+ * {@link #setVariant}.
+ *
+ * All existing builder state is discarded.
+ *
+ * @throws IllformedLocaleException if {@code locale} is invalid.
+ * @throws NullPointerException if {@code locale} is null.
+ */
+ public Builder setLocale(Locale locale) {
+ if (locale == null) {
+ throw new NullPointerException("locale == null");
+ }
+
+ // Make copies of the existing values so that we don't partially
+ // update the state if we encounter an error.
+ final String backupLanguage = language;
+ final String backupRegion = region;
+ final String backupVariant = variant;
+
+ try {
+ setLanguage(locale.getLanguage());
+ setRegion(locale.getCountry());
+ setVariant(locale.getVariant());
+ } catch (IllformedLocaleException ifle) {
+ language = backupLanguage;
+ region = backupRegion;
+ variant = backupVariant;
+
+ throw ifle;
+ }
+
+ // The following values can be set only via the builder class, so
+ // there's no need to normalize them or check their validity.
+
+ this.script = locale.getScript();
+
+ extensions.clear();
+ extensions.putAll(locale.extensions);
+
+ keywords.clear();
+ keywords.putAll(locale.unicodeKeywords);
+
+ attributes.clear();
+ attributes.addAll(locale.unicodeAttributes);
+
+ return this;
+ }
+
+ /**
+ * Adds the specified attribute to the list of attributes in the unicode
+ * locale extension.
+ *
+ * Attributes must be between 3 and 8 characters in length, and each character
+ * must be in the range {@code [a-zA-Z0-9]}.
+ *
+ * Attributes are normalized to lower case values. All added attributes and
+ * keywords are combined to form a complete unicode locale extension on
+ * {@link Locale} objects built by this builder, and accessible via
+ * {@link Locale#getExtension(char)} with the {@link Locale#UNICODE_LOCALE_EXTENSION}
+ * key.
+ *
+ * @throws IllformedLocaleException if {@code attribute} is invalid.
+ * @throws NullPointerException if {@code attribute} is null.
+ */
+ public Builder addUnicodeLocaleAttribute(String attribute) {
+ if (attribute == null) {
+ throw new NullPointerException("attribute == null");
+ }
+
+ final String lowercaseAttribute = attribute.toLowerCase(Locale.ROOT);
+ if (!isValidBcp47Alphanum(lowercaseAttribute, 3, 8)) {
+ throw new IllformedLocaleException("Invalid locale attribute: " + attribute);
+ }
+
+ attributes.add(lowercaseAttribute);
+
+ return this;
+ }
+
+ /**
+ * Removes an attribute from the list of attributes in the unicode locale
+ * extension.
+ *
+ * {@code attribute} must be valid as per the rules specified in
+ * {@link #addUnicodeLocaleAttribute}.
+ *
+ * This method has no effect if {@code attribute} hasn't already been
+ * added.
+ *
+ * @throws IllformedLocaleException if {@code attribute} is invalid.
+ * @throws NullPointerException if {@code attribute} is null.
+ */
+ public Builder removeUnicodeLocaleAttribute(String attribute) {
+ if (attribute == null) {
+ throw new NullPointerException("attribute == null");
+ }
+
+ // Weirdly, remove is specified to check whether the attribute
+ // is valid, so we have to perform the full alphanumeric check here.
+ final String lowercaseAttribute = attribute.toLowerCase(Locale.ROOT);
+ if (!isValidBcp47Alphanum(lowercaseAttribute, 3, 8)) {
+ throw new IllformedLocaleException("Invalid locale attribute: " + attribute);
+ }
+
+ attributes.remove(attribute);
+ return this;
+ }
+
+ /**
+ * Sets the extension identified by {@code key} to {@code value}.
+ *
+ * {@code key} must be in the range {@code [a-zA-Z0-9]}.
+ *
+ * If {@code value} is {@code null} or empty, the extension is removed.
+ *
+ * In the general case, {@code value} must be a series of subtags separated
+ * by ({@code "-"} or {@code "_"}). Each subtag must be between
+ * 2 and 8 characters in length, and each character in the subtag must be in
+ * the range {@code [a-zA-Z0-9]}.
+ *
+ * <p>
+ * There are two special cases :
+ * <li>
+ * <ul>
+ * The unicode locale extension
+ * ({@code key == 'u'}, {@link Locale#UNICODE_LOCALE_EXTENSION}) : Setting
+ * the unicode locale extension results in all existing keyword and attribute
+ * state being replaced by the parsed result of {@code value}. For example,
+ * {@code builder.setExtension('u', "baaaz-baaar-fo-baar-ba-baaz")}
+ * is equivalent to:
+ * <pre>
+ * builder.addUnicodeLocaleAttribute("baaaz");
+ * builder.addUnicodeLocaleAttribute("baaar");
+ * builder.setUnicodeLocaleKeyword("fo", "baar");
+ * builder.setUnicodeLocaleKeyword("ba", "baaa");
+ * </pre>
+ * </ul>
+ * <ul>
+ * The private use extension
+ * ({@code key == 'x'}, {@link Locale#PRIVATE_USE_EXTENSION}) : Each subtag in a
+ * private use extension can be between 1 and 8 characters in length (in contrast
+ * to a minimum length of 2 for all other extensions).
+ * </ul>
+ * </li>
+ *
+ * @throws IllformedLocaleException if {@code value} is invalid.
+ */
+ public Builder setExtension(char key, String value) {
+ if (value == null || value.isEmpty()) {
+ extensions.remove(key);
+ return this;
+ }
+
+ final String normalizedValue = value.toLowerCase(Locale.ROOT).replace('_', '-');
+ final String[] subtags = normalizedValue.split("-");
+
+ // Lengths for subtags in the private use extension should be [1, 8] chars.
+ // For all other extensions, they should be [2, 8] chars.
+ //
+ // http://www.rfc-editor.org/rfc/bcp/bcp47.txt
+ final int minimumLength = (key == PRIVATE_USE_EXTENSION) ? 1 : 2;
+ for (String subtag : subtags) {
+ if (!isValidBcp47Alphanum(subtag, minimumLength, 8)) {
+ throw new IllformedLocaleException(
+ "Invalid private use extension : " + value);
+ }
+ }
+
+ // We need to take special action in the case of unicode extensions,
+ // since we claim to understand their keywords and attributes.
+ if (key == UNICODE_LOCALE_EXTENSION) {
+ // First clear existing attributes and keywords.
+ extensions.clear();
+ attributes.clear();
+
+ parseUnicodeExtension(subtags, keywords, attributes);
+ } else {
+ extensions.put(key, normalizedValue);
+ }
+
+ return this;
+ }
+
+ /**
+ * Clears all extensions from this builder. Note that this also implicitly
+ * clears all state related to the unicode locale extension; all attributes
+ * and keywords set by {@link #addUnicodeLocaleAttribute} and
+ * {@link #setUnicodeLocaleKeyword} are cleared.
+ */
+ public Builder clearExtensions() {
+ extensions.clear();
+ attributes.clear();
+ keywords.clear();
+ return this;
+ }
+
+ /**
+ * Adds a key / type pair to the list of unicode locale extension keys.
+ *
+ * {@code key} must be 2 characters in length, and each character must be
+ * in the range {@code [a-zA-Z0-9]}.
+ *
+ * {#code type} can either be empty, or a series of one or more subtags
+ * separated by a separator ({@code "-"} or {@code "_"}). Each subtag must
+ * be between 3 and 8 characters in length and each character in the subtag
+ * must be in the range {@code [a-zA-Z0-9]}.
+ *
+ * Note that the type is normalized to lower case, and all separators
+ * are normalized to {@code "-"}. All added attributes and
+ * keywords are combined to form a complete unicode locale extension on
+ * {@link Locale} objects built by this builder, and accessible via
+ * {@link Locale#getExtension(char)} with the {@link Locale#UNICODE_LOCALE_EXTENSION}
+ * key.
+ *
+ * @throws IllformedLocaleException if {@code key} or {@code value} are
+ * invalid.
+ */
+ public Builder setUnicodeLocaleKeyword(String key, String type) {
+ if (key == null) {
+ throw new NullPointerException("key == null");
+ }
+
+ if (type == null && keywords != null) {
+ keywords.remove(key);
+ return this;
+ }
+
+ final String lowerCaseKey = key.toLowerCase(Locale.ROOT);
+ // The key must be exactly two alphanumeric characters.
+ if (lowerCaseKey.length() != 2 || !isAsciiAlphaNum(lowerCaseKey)) {
+ throw new IllformedLocaleException("Invalid unicode locale keyword: " + key);
+ }
+
+ // The type can be one or more alphanumeric strings of length [3, 8] characters,
+ // separated by a separator char, which is one of "_" or "-". Though the spec
+ // doesn't require it, we normalize all "_" to "-" to make the rest of our
+ // processing easier.
+ final String lowerCaseType = type.toLowerCase(Locale.ROOT).replace("_", "-");
+ if (!isValidTypeList(lowerCaseType)) {
+ throw new IllformedLocaleException("Invalid unicode locale type: " + type);
+ }
+
+ // Everything checks out fine, add the <key, type> mapping to the list.
+ keywords.put(lowerCaseKey, lowerCaseType);
+
+ return this;
+ }
+
+ /**
+ * Clears all existing state from this builder.
+ */
+ public Builder clear() {
+ clearExtensions();
+ language = region = variant = script = "";
+
+ return this;
+ }
+
+ /**
+ * Constructs a locale from the existing state of the builder. Note that this
+ * method is guaranteed to succeed since field validity checks are performed
+ * at the point of setting them.
+ */
+ public Locale build() {
+ // NOTE: We need to make a copy of attributes, keywords and extensions
+ // because the RI allows this builder to reused.
+ return new Locale(language, region, variant, script,
+ attributes, keywords, extensions,
+ true /* has validated fields */);
+ }
+ }
+
+ /**
+ * Returns a locale for a given BCP-47 language tag. This method is more
+ * lenient than {@link Builder#setLanguageTag}. For a given language tag, parsing
+ * will proceed up to the first malformed subtag. All subsequent tags are discarded.
+ * Note that language tags use {@code -} rather than {@code _}, for example {@code en-US}.
+ *
+ * @throws NullPointerException if {@code languageTag} is {@code null}.
+ *
+ * @since 1.7
+ */
+ public static Locale forLanguageTag(String languageTag) {
+ if (languageTag == null) {
+ throw new NullPointerException("languageTag == null");
+ }
+
+ return forLanguageTag(languageTag, false /* strict */);
+ }
+
private transient String countryCode;
private transient String languageCode;
private transient String variantCode;
+ private transient String scriptCode;
+
+ /* Sorted, Unmodifiable */
+ private transient Set<String> unicodeAttributes;
+ /* Sorted, Unmodifiable */
+ private transient Map<String, String> unicodeKeywords;
+ /* Sorted, Unmodifiable */
+ private transient Map<Character, String> extensions;
+
+ /**
+ * Whether this instance was constructed from a builder. We can make
+ * stronger assumptions about the validity of Locale fields if this was
+ * constructed by a builder.
+ */
+ private transient final boolean hasValidatedFields;
+
private transient String cachedToStringResult;
+ private transient String cachedLanguageTag;
+ private transient String cachedIcuLocaleId;
/**
* There's a circular dependency between toLowerCase/toUpperCase and
* Locale.US. Work around this by avoiding these methods when constructing
* the built-in locales.
- *
- * @param unused required for this constructor to have a unique signature
*/
- private Locale(boolean unused, String lowerCaseLanguageCode, String upperCaseCountryCode) {
+ private Locale(boolean hasValidatedFields, String lowerCaseLanguageCode,
+ String upperCaseCountryCode) {
this.languageCode = lowerCaseLanguageCode;
this.countryCode = upperCaseCountryCode;
this.variantCode = "";
+ this.scriptCode = "";
+
+ this.unicodeAttributes = Collections.EMPTY_SET;
+ this.unicodeKeywords = Collections.EMPTY_MAP;
+ this.extensions = Collections.EMPTY_MAP;
+
+ this.hasValidatedFields = hasValidatedFields;
}
/**
* Constructs a new {@code Locale} using the specified language.
*/
public Locale(String language) {
- this(language, "", "");
+ this(language, "", "", "", Collections.EMPTY_SET, Collections.EMPTY_MAP,
+ Collections.EMPTY_MAP, false /* has validated fields */);
}
/**
* Constructs a new {@code Locale} using the specified language and country codes.
*/
public Locale(String language, String country) {
- this(language, country, "");
+ this(language, country, "", "", Collections.EMPTY_SET, Collections.EMPTY_MAP,
+ Collections.EMPTY_MAP, false /* has validated fields */);
}
/**
- * Constructs a new {@code Locale} using the specified language, country,
- * and variant codes.
+ * Required by libcore.icu.ICU.
+ *
+ * @hide
*/
- public Locale(String language, String country, String variant) {
+ public Locale(String language, String country, String variant, String scriptCode,
+ /* nonnull */ Set<String> unicodeAttributes,
+ /* nonnull */ Map<String, String> unicodeKeywords,
+ /* nonnull */ Map<Character, String> extensions,
+ boolean hasValidatedFields) {
if (language == null || country == null || variant == null) {
throw new NullPointerException("language=" + language +
- ",country=" + country +
- ",variant=" + variant);
+ ",country=" + country +
+ ",variant=" + variant);
}
- if (language.isEmpty() && country.isEmpty()) {
- languageCode = "";
- countryCode = "";
- variantCode = variant;
- return;
+
+ if (hasValidatedFields) {
+ this.languageCode = adjustLanguageCode(language);
+ this.countryCode = country;
+ this.variantCode = variant;
+ } else {
+ if (language.isEmpty() && country.isEmpty()) {
+ languageCode = "";
+ countryCode = "";
+ variantCode = variant;
+ } else {
+ languageCode = adjustLanguageCode(language);
+ countryCode = country.toUpperCase(Locale.US);
+ variantCode = variant;
+ }
}
- languageCode = language.toLowerCase(Locale.US);
- // Map new language codes to the obsolete language
- // codes so the correct resource bundles will be used.
- if (languageCode.equals("he")) {
- languageCode = "iw";
- } else if (languageCode.equals("id")) {
- languageCode = "in";
- } else if (languageCode.equals("yi")) {
- languageCode = "ji";
+ this.scriptCode = scriptCode;
+
+ if (hasValidatedFields) {
+ Set<String> attribsCopy = new TreeSet<String>(unicodeAttributes);
+ Map<String, String> keywordsCopy = new TreeMap<String, String>(unicodeKeywords);
+ Map<Character, String> extensionsCopy = new TreeMap<Character, String>(extensions);
+
+ // We need to transform the list of attributes & keywords set on the
+ // builder to a unicode locale extension. i.e, if we have any keywords
+ // or attributes set, Locale#getExtension('u') should return a well
+ // formed extension.
+ addUnicodeExtensionToExtensionsMap(attribsCopy, keywordsCopy, extensionsCopy);
+
+ this.unicodeAttributes = Collections.unmodifiableSet(attribsCopy);
+ this.unicodeKeywords = Collections.unmodifiableMap(keywordsCopy);
+ this.extensions = Collections.unmodifiableMap(extensionsCopy);
+ } else {
+ this.unicodeAttributes = unicodeAttributes;
+ this.unicodeKeywords = unicodeKeywords;
+ this.extensions = extensions;
}
- countryCode = country.toUpperCase(Locale.US);
+ this.hasValidatedFields = hasValidatedFields;
+ }
- // Work around for be compatible with RI
- variantCode = variant;
+ /**
+ * Constructs a new {@code Locale} using the specified language, country,
+ * and variant codes.
+ */
+ public Locale(String language, String country, String variant) {
+ this(language, country, variant, "", Collections.EMPTY_SET,
+ Collections.EMPTY_MAP, Collections.EMPTY_MAP,
+ false /* has validated fields */);
}
@Override public Object clone() {
@@ -341,7 +964,10 @@ public final class Locale implements Cloneable, Serializable {
Locale o = (Locale) object;
return languageCode.equals(o.languageCode)
&& countryCode.equals(o.countryCode)
- && variantCode.equals(o.variantCode);
+ && variantCode.equals(o.variantCode)
+ && scriptCode.equals(o.scriptCode)
+ && extensions.equals(o.extensions);
+
}
return false;
}
@@ -399,9 +1025,16 @@ public final class Locale implements Cloneable, Serializable {
if (countryCode.isEmpty()) {
return "";
}
- String result = ICU.getDisplayCountryNative(toString(), locale.toString());
+
+ final String normalizedRegion = Builder.normalizeAndValidateRegion(
+ countryCode, false /* strict */);
+ if (normalizedRegion.isEmpty()) {
+ return countryCode;
+ }
+
+ String result = ICU.getDisplayCountry(this, locale);
if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
- result = ICU.getDisplayCountryNative(toString(), Locale.getDefault().toString());
+ result = ICU.getDisplayCountry(this, Locale.getDefault());
}
return result;
}
@@ -422,17 +1055,24 @@ public final class Locale implements Cloneable, Serializable {
return "";
}
- // http://b/8049507 --- frameworks/base should use fil_PH instead of tl_PH.
- // Until then, we're stuck covering their tracks, making it look like they're
- // using "fil" when they're not.
- String localeString = toString();
- if (languageCode.equals("tl")) {
- localeString = toNewString("fil", countryCode, variantCode);
+ // Hacks for backward compatibility.
+ //
+ // Our language tag will contain "und" if the languageCode is invalid
+ // or missing. ICU will then return "langue indéterminée" or the equivalent
+ // display language for the indeterminate language code.
+ //
+ // Sigh... ugh... and what not.
+ final String normalizedLanguage = Builder.normalizeAndValidateLanguage(
+ languageCode, false /* strict */);
+ if (UNDETERMINED_LANGUAGE.equals(normalizedLanguage)) {
+ return languageCode;
}
- String result = ICU.getDisplayLanguageNative(localeString, locale.toString());
+ // TODO: We need a new hack or a complete fix for http://b/8049507 --- We would
+ // cover the frameworks' tracks when they were using "tl" instead of "fil".
+ String result = ICU.getDisplayLanguage(this, locale);
if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
- result = ICU.getDisplayLanguageNative(localeString, Locale.getDefault().toString());
+ result = ICU.getDisplayLanguage(this, Locale.getDefault());
}
return result;
}
@@ -447,13 +1087,14 @@ public final class Locale implements Cloneable, Serializable {
/**
* Returns this locale's language name, country name, and variant, localized
* to {@code locale}. The exact output form depends on whether this locale
- * corresponds to a specific language, country and variant.
+ * corresponds to a specific language, script, country and variant.
*
* <p>For example:
* <ul>
* <li>{@code new Locale("en").getDisplayName(Locale.US)} -> {@code English}
* <li>{@code new Locale("en", "US").getDisplayName(Locale.US)} -> {@code English (United States)}
* <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.US)} -> {@code English (United States,Computer)}
+ * <li>{@code Locale.fromLanguageTag("zh-Hant-CN").getDisplayName(Locale.US)} -> {@code Chinese (Traditional Han,China)}
* <li>{@code new Locale("en").getDisplayName(Locale.FRANCE)} -> {@code anglais}
* <li>{@code new Locale("en", "US").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis)}
* <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis,informatique)}.
@@ -467,9 +1108,19 @@ public final class Locale implements Cloneable, Serializable {
buffer.append(displayLanguage.isEmpty() ? languageCode : displayLanguage);
++count;
}
+ if (!scriptCode.isEmpty()) {
+ if (count == 1) {
+ buffer.append(" (");
+ }
+ String displayScript = getDisplayScript(locale);
+ buffer.append(displayScript.isEmpty() ? scriptCode : displayScript);
+ ++count;
+ }
if (!countryCode.isEmpty()) {
if (count == 1) {
buffer.append(" (");
+ } else if (count == 2) {
+ buffer.append(",");
}
String displayCountry = getDisplayCountry(locale);
buffer.append(displayCountry.isEmpty() ? countryCode : displayCountry);
@@ -478,7 +1129,7 @@ public final class Locale implements Cloneable, Serializable {
if (!variantCode.isEmpty()) {
if (count == 1) {
buffer.append(" (");
- } else if (count == 2) {
+ } else if (count == 2 || count == 3) {
buffer.append(",");
}
String displayVariant = getDisplayVariant(locale);
@@ -495,6 +1146,8 @@ public final class Locale implements Cloneable, Serializable {
* Returns the full variant name in the default {@code Locale} for the variant code of
* this {@code Locale}. If there is no matching variant name, the variant code is
* returned.
+ *
+ * @since 1.7
*/
public final String getDisplayVariant() {
return getDisplayVariant(getDefault());
@@ -504,14 +1157,31 @@ public final class Locale implements Cloneable, Serializable {
* Returns the full variant name in the specified {@code Locale} for the variant code
* of this {@code Locale}. If there is no matching variant name, the variant code is
* returned.
+ *
+ * @since 1.7
*/
public String getDisplayVariant(Locale locale) {
- if (variantCode.length() == 0) {
+ if (variantCode.isEmpty()) {
+ return "";
+ }
+
+ try {
+ Builder.normalizeAndValidateVariant(variantCode);
+ } catch (IllformedLocaleException ilfe) {
return variantCode;
}
- String result = ICU.getDisplayVariantNative(toString(), locale.toString());
+
+ String result = ICU.getDisplayVariant(this, locale);
if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
- result = ICU.getDisplayVariantNative(toString(), Locale.getDefault().toString());
+ result = ICU.getDisplayVariant(this, Locale.getDefault());
+ }
+
+ // The "old style" locale constructors allow us to pass in variants that aren't
+ // valid BCP-47 variant subtags. When that happens, toLanguageTag will not emit
+ // them. Note that we know variantCode.length() > 0 due to the isEmpty check at
+ // the beginning of this function.
+ if (result.isEmpty()) {
+ return variantCode;
}
return result;
}
@@ -522,7 +1192,10 @@ public final class Locale implements Cloneable, Serializable {
* @throws MissingResourceException if there's no 3-letter country code for this locale.
*/
public String getISO3Country() {
- String code = ICU.getISO3CountryNative(toString());
+ // The results of getISO3Country do not depend on the languageCode,
+ // so we pass an arbitrarily selected language code here. This guards
+ // against errors caused by malformed or invalid language codes.
+ String code = ICU.getISO3Country("en-" + countryCode);
if (!countryCode.isEmpty() && code.isEmpty()) {
throw new MissingResourceException("No 3-letter country code for locale: " + this, "FormatData_" + this, "ShortCountry");
}
@@ -535,7 +1208,16 @@ public final class Locale implements Cloneable, Serializable {
* @throws MissingResourceException if there's no 3-letter language code for this locale.
*/
public String getISO3Language() {
- String code = ICU.getISO3LanguageNative(toString());
+ // For backward compatibility, we must return "" for an empty language
+ // code and not "und" which is the accurate ISO-639-3 code for an
+ // undetermined language.
+ if (languageCode.isEmpty()) {
+ return "";
+ }
+
+ // The results of getISO3Language do not depend on the country code
+ // or any of the other locale fields, so we pass just the language here.
+ String code = ICU.getISO3Language(languageCode);
if (!languageCode.isEmpty() && code.isEmpty()) {
throw new MissingResourceException("No 3-letter language code for locale: " + this, "FormatData_" + this, "ShortLanguage");
}
@@ -574,10 +1256,335 @@ public final class Locale implements Cloneable, Serializable {
return variantCode;
}
+ /**
+ * Returns the script code for this {@code Locale} or an empty {@code String} if no script
+ * was set.
+ *
+ * If set, the script code will be a title cased string of length 4, as per the ISO 15924
+ * specification.
+ *
+ * @since 1.7
+ */
+ public String getScript() {
+ return scriptCode;
+ }
+
+ /**
+ * Equivalent to {@code getDisplayScript(Locale.getDefault()))}
+ *
+ * @since 1.7
+ */
+ public String getDisplayScript() {
+ return getDisplayScript(getDefault());
+ }
+
+ /**
+ * Returns the name of this locale's script code, localized to {@link Locale}. If the
+ * script code is unknown, the return value of this method is the same as that of
+ * {@link #getScript()}.
+ *
+ * @since 1.7
+ */
+ public String getDisplayScript(Locale locale) {
+ if (scriptCode.isEmpty()) {
+ return "";
+ }
+
+ String result = ICU.getDisplayScript(this, locale);
+ if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
+ result = ICU.getDisplayScript(this, Locale.getDefault());
+ }
+
+ return result;
+
+ }
+
+ /**
+ * Returns a well formed BCP-47 language tag that identifies this locale.
+ *
+ * Note that this locale itself might consist of ill formed fields, since the
+ * public {@code Locale} constructors do not perform validity checks to maintain
+ * backwards compatibility. When this is the case, this method will either replace
+ * ill formed fields with standard BCP-47 subtags (For eg. "und" (undetermined)
+ * for invalid languages) or omit them altogether.
+ *
+ * Additionally, ill formed variants will result in the remainder of the tag
+ * (both variants and extensions) being moved to the private use extension,
+ * where they will appear after a subtag whose value is {@code "lvariant"}.
+ *
+ * It's also important to note that the BCP-47 tag is well formed in the sense
+ * that it is unambiguously parseable into its specified components. We do not
+ * require that any of the components are registered with the applicable registries.
+ * For example, we do not require scripts to be a registered ISO 15924 scripts or
+ * languages to appear in the ISO-639-2 code list.
+ *
+ * @since 1.7
+ */
+ public String toLanguageTag() {
+ if (cachedLanguageTag == null) {
+ cachedLanguageTag = makeLanguageTag();
+ }
+
+ return cachedLanguageTag;
+ }
+
+ /**
+ * Constructs a valid BCP-47 language tag from locale fields. Additional validation
+ * is required when this Locale was not constructed using a Builder and variants
+ * set this way are treated specially.
+ *
+ * In both cases, we convert empty language tags to "und", omit invalid country tags
+ * and perform a special case conversion of "no-NO-NY" to "nn-NO".
+ */
+ private String makeLanguageTag() {
+ // We only need to revalidate the language, country and variant because
+ // the rest of the fields can only be set via the builder which validates
+ // them anyway.
+ String language = "";
+ String region = "";
+ String variant = "";
+ String illFormedVariantSubtags = "";
+
+ if (hasValidatedFields) {
+ language = languageCode;
+ region = countryCode;
+ // Note that we are required to normalize hyphens to underscores
+ // in the builder, but we must use hyphens in the BCP-47 language tag.
+ variant = variantCode.replace('_', '-');
+ } else {
+ language = Builder.normalizeAndValidateLanguage(languageCode, false /* strict */);
+ region = Builder.normalizeAndValidateRegion(countryCode, false /* strict */);
+
+ try {
+ variant = Builder.normalizeAndValidateVariant(variantCode);
+ } catch (IllformedLocaleException ilfe) {
+ // If our variant is ill formed, we must attempt to split it into
+ // its constituent subtags and preserve the well formed bits and
+ // move the rest to the private use extension (if they're well
+ // formed extension subtags).
+ String split[] = splitIllformedVariant(variantCode);
+
+ variant = split[0];
+ illFormedVariantSubtags = split[1];
+ }
+ }
+
+ if (language.isEmpty()) {
+ language = UNDETERMINED_LANGUAGE;
+ }
+
+ if ("no".equals(language) && "NO".equals(region) && "NY".equals(variant)) {
+ language = "nn";
+ region = "NO";
+ variant = "";
+ }
+
+ final StringBuilder sb = new StringBuilder(16);
+ sb.append(language);
+
+ if (!scriptCode.isEmpty()) {
+ sb.append('-');
+ sb.append(scriptCode);
+ }
+
+ if (!region.isEmpty()) {
+ sb.append('-');
+ sb.append(region);
+ }
+
+ if (!variant.isEmpty()) {
+ sb.append('-');
+ sb.append(variant);
+ }
+
+ // Extensions (optional, omitted if empty). Note that we don't
+ // emit the private use extension here, but add it in the end.
+ for (Map.Entry<Character, String> extension : extensions.entrySet()) {
+ if (!extension.getKey().equals('x')) {
+ sb.append('-').append(extension.getKey());
+ sb.append('-').append(extension.getValue());
+ }
+ }
+
+ // The private use extension comes right at the very end.
+ final String privateUse = extensions.get('x');
+ if (privateUse != null) {
+ sb.append("-x-");
+ sb.append(privateUse);
+ }
+
+ // If we have any ill-formed variant subtags, we append them to the
+ // private use extension (or add a private use extension if one doesn't
+ // exist).
+ if (!illFormedVariantSubtags.isEmpty()) {
+ if (privateUse == null) {
+ sb.append("-x-lvariant-");
+ } else {
+ sb.append('-');
+ }
+ sb.append(illFormedVariantSubtags);
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Splits ill formed variants into a set of valid variant subtags (which
+ * can be used directly in language tag construction) and a set of invalid
+ * variant subtags (which can be appended to the private use extension),
+ * provided that each subtag is a valid private use extension subtag.
+ *
+ * This method returns a two element String array. The first element is a string
+ * containing the concatenation of valid variant subtags which can be appended
+ * to a BCP-47 tag directly and the second containing the concatenation of
+ * invalid variant subtags which can be appended to the private use extension
+ * directly.
+ *
+ * This method assumes that {@code variant} contains at least one ill formed
+ * variant subtag.
+ */
+ private static String[] splitIllformedVariant(String variant) {
+ final String normalizedVariant = variant.replace('_', '-');
+ final String[] subTags = normalizedVariant.split("-");
+
+ final String[] split = new String[] { "", "" };
+
+ // First go through the list of variant subtags and check if they're
+ // valid private use extension subtags. If they're not, we will omit
+ // the first such subtag and all subtags after.
+ //
+ // NOTE: |firstInvalidSubtag| is the index of the first variant
+ // subtag we decide to omit altogether, whereas |firstIllformedSubtag| is the
+ // index of the first subtag we decide to append to the private use extension.
+ //
+ // In other words:
+ // [0, firstIllformedSubtag) => expressed as variant subtags.
+ // [firstIllformedSubtag, firstInvalidSubtag) => expressed as private use
+ // extension subtags.
+ // [firstInvalidSubtag, subTags.length) => omitted.
+ int firstInvalidSubtag = subTags.length;
+ for (int i = 0; i < subTags.length; ++i) {
+ if (!isValidBcp47Alphanum(subTags[i], 1, 8)) {
+ firstInvalidSubtag = i;
+ break;
+ }
+ }
+
+ if (firstInvalidSubtag == 0) {
+ return split;
+ }
+
+ // We now consider each subtag that could potentially be appended to
+ // the private use extension and check if it's valid.
+ int firstIllformedSubtag = firstInvalidSubtag;
+ for (int i = 0; i < firstInvalidSubtag; ++i) {
+ final String subTag = subTags[i];
+ // The BCP-47 spec states that :
+ // - Subtags can be between [5, 8] alphanumeric chars in length.
+ // - Subtags that start with a number are allowed to be 4 chars in length.
+ if (subTag.length() >= 5 && subTag.length() <= 8) {
+ if (!isAsciiAlphaNum(subTag)) {
+ firstIllformedSubtag = i;
+ }
+ } else if (subTag.length() == 4) {
+ final char firstChar = subTag.charAt(0);
+ if (!(firstChar >= '0' && firstChar <= '9') || !isAsciiAlphaNum(subTag)) {
+ firstIllformedSubtag = i;
+ }
+ } else {
+ firstIllformedSubtag = i;
+ }
+ }
+
+ split[0] = concatenateRange(subTags, 0, firstIllformedSubtag);
+ split[1] = concatenateRange(subTags, firstIllformedSubtag, firstInvalidSubtag);
+
+ return split;
+ }
+
+ /**
+ * Builds a string by concatenating array elements within the range [start, end).
+ * The supplied range is assumed to be valid and no checks are performed.
+ */
+ private static String concatenateRange(String[] array, int start, int end) {
+ StringBuilder builder = new StringBuilder(32);
+ for (int i = start; i < end; ++i) {
+ if (i != start) {
+ builder.append('-');
+ }
+ builder.append(array[i]);
+ }
+
+ return builder.toString();
+ }
+
+ /**
+ * Returns the set of BCP-47 extensions this locale contains.
+ *
+ * See <a href="https://tools.ietf.org/html/bcp47#section-2.1">
+ * the IETF BCP-47 specification</a> (Section 2.2.6) for details.
+ *
+ * @since 1.7
+ */
+ public Set<Character> getExtensionKeys() {
+ return extensions.keySet();
+ }
+
+ /**
+ * Returns the BCP-47 extension whose key is {@code extensionKey}, or {@code null}
+ * if this locale does not contain the extension.
+ *
+ * Individual Keywords and attributes for the unicode
+ * locale extension can be fetched using {@link #getUnicodeLocaleAttributes()},
+ * {@link #getUnicodeLocaleKeys()} and {@link #getUnicodeLocaleType}.
+ *
+ * @since 1.7
+ */
+ public String getExtension(char extensionKey) {
+ return extensions.get(extensionKey);
+ }
+
+ /**
+ * Returns the {@code type} for the specified unicode locale extension {@code key}.
+ *
+ * For more information about types and keywords, see {@link Builder#setUnicodeLocaleKeyword}
+ * and <a href="http://www.unicode.org/reports/tr35/#BCP47">Unicode Technical Standard #35</a>
+ *
+ * @since 1.7
+ */
+ public String getUnicodeLocaleType(String keyWord) {
+ return unicodeKeywords.get(keyWord);
+ }
+
+ /**
+ * Returns the set of unicode locale extension attributes this locale contains.
+ *
+ * For more information about attributes, see {@link Builder#addUnicodeLocaleAttribute}
+ * and <a href="http://www.unicode.org/reports/tr35/#BCP47">Unicode Technical Standard #35</a>
+ *
+ * @since 1.7
+ */
+ public Set<String> getUnicodeLocaleAttributes() {
+ return unicodeAttributes;
+ }
+
+ /**
+ * Returns the set of unicode locale extension keywords this locale contains.
+ *
+ * For more information about types and keywords, see {@link Builder#setUnicodeLocaleKeyword}
+ * and <a href="http://www.unicode.org/reports/tr35/#BCP47">Unicode Technical Standard #35</a>
+ *
+ * @since 1.7
+ */
+ public Set<String> getUnicodeLocaleKeys() {
+ return unicodeKeywords.keySet();
+ }
+
@Override
public synchronized int hashCode() {
- return countryCode.hashCode() + languageCode.hashCode()
- + variantCode.hashCode();
+ return countryCode.hashCode()
+ + languageCode.hashCode() + variantCode.hashCode()
+ + scriptCode.hashCode() + extensions.hashCode();
}
/**
@@ -592,7 +1599,9 @@ public final class Locale implements Cloneable, Serializable {
if (locale == null) {
throw new NullPointerException("locale == null");
}
+ String languageTag = locale.toLanguageTag();
defaultLocale = locale;
+ ICU.setDefaultLocale(languageTag);
}
/**
@@ -610,30 +1619,59 @@ public final class Locale implements Cloneable, Serializable {
public final String toString() {
String result = cachedToStringResult;
if (result == null) {
- result = cachedToStringResult = toNewString(languageCode, countryCode, variantCode);
+ result = cachedToStringResult = toNewString(languageCode, countryCode, variantCode,
+ scriptCode, extensions);
}
return result;
}
- private static String toNewString(String languageCode, String countryCode, String variantCode) {
+ private static String toNewString(String languageCode, String countryCode,
+ String variantCode, String scriptCode, Map<Character, String> extensions) {
// The string form of a locale that only has a variant is the empty string.
if (languageCode.length() == 0 && countryCode.length() == 0) {
return "";
}
+
// Otherwise, the output format is "ll_cc_variant", where language and country are always
// two letters, but the variant is an arbitrary length. A size of 11 characters has room
// for "en_US_POSIX", the largest "common" value. (In practice, the string form is almost
// always 5 characters: "ll_cc".)
StringBuilder result = new StringBuilder(11);
result.append(languageCode);
- if (countryCode.length() > 0 || variantCode.length() > 0) {
+
+ final boolean hasScriptOrExtensions = !scriptCode.isEmpty() || !extensions.isEmpty();
+
+ if (!countryCode.isEmpty() || !variantCode.isEmpty() || hasScriptOrExtensions) {
result.append('_');
}
result.append(countryCode);
- if (variantCode.length() > 0) {
+ if (!variantCode.isEmpty() || hasScriptOrExtensions) {
result.append('_');
}
result.append(variantCode);
+
+ if (hasScriptOrExtensions) {
+ if (!variantCode.isEmpty()) {
+ result.append('_');
+ }
+
+ // Note that this is notably different from the BCP-47 spec (for
+ // backwards compatibility). We are forced to append a "#" before the script tag.
+ // and also put the script code right at the end.
+ result.append("#");
+ if (!scriptCode.isEmpty() ) {
+ result.append(scriptCode);
+ }
+
+ // Note the use of "-" instead of "_" before the extensions.
+ if (!extensions.isEmpty()) {
+ if (!scriptCode.isEmpty()) {
+ result.append('-');
+ }
+ result.append(serializeExtensions(extensions));
+ }
+ }
+
return result.toString();
}
@@ -642,6 +1680,8 @@ public final class Locale implements Cloneable, Serializable {
new ObjectStreamField("hashcode", int.class),
new ObjectStreamField("language", String.class),
new ObjectStreamField("variant", String.class),
+ new ObjectStreamField("script", String.class),
+ new ObjectStreamField("extensions", String.class),
};
private void writeObject(ObjectOutputStream stream) throws IOException {
@@ -650,6 +1690,12 @@ public final class Locale implements Cloneable, Serializable {
fields.put("hashcode", -1);
fields.put("language", languageCode);
fields.put("variant", variantCode);
+ fields.put("script", scriptCode);
+
+ if (!extensions.isEmpty()) {
+ fields.put("extensions", serializeExtensions(extensions));
+ }
+
stream.writeFields();
}
@@ -658,5 +1704,545 @@ public final class Locale implements Cloneable, Serializable {
countryCode = (String) fields.get("country", "");
languageCode = (String) fields.get("language", "");
variantCode = (String) fields.get("variant", "");
+ scriptCode = (String) fields.get("script", "");
+
+ this.unicodeKeywords = Collections.EMPTY_MAP;
+ this.unicodeAttributes = Collections.EMPTY_SET;
+ this.extensions = Collections.EMPTY_MAP;
+
+ String extensions = (String) fields.get("extensions", null);
+ if (extensions != null) {
+ readExtensions(extensions);
+ }
+ }
+
+ private void readExtensions(String extensions) {
+ Map<Character, String> extensionsMap = new TreeMap<Character, String>();
+ parseSerializedExtensions(extensions, extensionsMap);
+ this.extensions = Collections.unmodifiableMap(extensionsMap);
+
+ if (extensionsMap.containsKey(UNICODE_LOCALE_EXTENSION)) {
+ String unicodeExtension = extensionsMap.get(UNICODE_LOCALE_EXTENSION);
+ String[] subTags = unicodeExtension.split("-");
+
+ Map<String, String> unicodeKeywords = new TreeMap<String, String>();
+ Set<String> unicodeAttributes = new TreeSet<String>();
+ parseUnicodeExtension(subTags, unicodeKeywords, unicodeAttributes);
+
+ this.unicodeKeywords = Collections.unmodifiableMap(unicodeKeywords);
+ this.unicodeAttributes = Collections.unmodifiableSet(unicodeAttributes);
+ }
+ }
+
+ /**
+ * The serialized form for extensions is straightforward. It's simply
+ * of the form key1-value1-key2-value2 where each value might in turn contain
+ * multiple subtags separated by hyphens. Each key is guaranteed to be a single
+ * character in length.
+ *
+ * This method assumes that {@code extensionsMap} is non-empty.
+ *
+ * Visible for testing.
+ *
+ * @hide
+ */
+ public static String serializeExtensions(Map<Character, String> extensionsMap) {
+ Iterator<Map.Entry<Character, String>> entryIterator = extensionsMap.entrySet().iterator();
+ StringBuilder sb = new StringBuilder(64);
+
+ while (true) {
+ final Map.Entry<Character, String> entry = entryIterator.next();
+ sb.append(entry.getKey());
+ sb.append('-');
+ sb.append(entry.getValue());
+
+ if (entryIterator.hasNext()) {
+ sb.append('-');
+ } else {
+ break;
+ }
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Visible for testing.
+ *
+ * @hide
+ */
+ public static void parseSerializedExtensions(String extString, Map<Character, String> outputMap) {
+ // This probably isn't the most efficient approach, but it's the
+ // most straightforward to code.
+ //
+ // Start by splitting the string on "-". We will then keep track of
+ // where each of the extension keys (single characters) appear in the
+ // original string and then use those indices to construct substrings
+ // representing the values.
+ final String[] subTags = extString.split("-");
+ final int[] typeStartIndices = new int[subTags.length / 2];
+
+ int length = 0;
+ int count = 0;
+ for (String subTag : subTags) {
+ if (subTag.length() > 0) {
+ // Account for the length of the "-" at the end of each subtag.
+ length += (subTag.length() + 1);
+ }
+
+ if (subTag.length() == 1) {
+ typeStartIndices[count++] = length;
+ }
+ }
+
+ for (int i = 0; i < count; ++i) {
+ final int valueStart = typeStartIndices[i];
+ // Since the start Index points to the beginning of the next type
+ // ....prev-k-next.....
+ // |_ here
+ // (idx - 2) is the index of the next key
+ // (idx - 3) is the (non inclusive) end of the previous type.
+ final int valueEnd = (i == (count - 1)) ?
+ extString.length() : (typeStartIndices[i + 1] - 3);
+
+ outputMap.put(extString.charAt(typeStartIndices[i] - 2),
+ extString.substring(valueStart, valueEnd));
+ }
+ }
+
+
+ /**
+ * A UN M.49 is a 3 digit numeric code.
+ */
+ private static boolean isUnM49AreaCode(String code) {
+ if (code.length() != 3) {
+ return false;
+ }
+
+ for (int i = 0; i < 3; ++i) {
+ final char character = code.charAt(i);
+ if (!(character >= '0' && character <= '9')) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /*
+ * Checks whether a given string is an ASCII alphanumeric string.
+ */
+ private static boolean isAsciiAlphaNum(String string) {
+ for (int i = 0; i < string.length(); i++) {
+ final char character = string.charAt(i);
+ if (!(character >= 'a' && character <= 'z' ||
+ character >= 'A' && character <= 'Z' ||
+ character >= '0' && character <= '9')) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static boolean isValidBcp47Alpha(String string, int lowerBound, int upperBound) {
+ final int length = string.length();
+ if (length < lowerBound || length > upperBound) {
+ return false;
+ }
+
+ for (int i = 0; i < length; ++i) {
+ final char character = string.charAt(i);
+ if (!(character >= 'a' && character <= 'z' ||
+ character >= 'A' && character <= 'Z')) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static boolean isValidBcp47Alphanum(String attributeOrType,
+ int lowerBound, int upperBound) {
+ if (attributeOrType.length() < lowerBound || attributeOrType.length() > upperBound) {
+ return false;
+ }
+
+ return isAsciiAlphaNum(attributeOrType);
+ }
+
+ private static String titleCaseAsciiWord(String word) {
+ try {
+ byte[] chars = word.toLowerCase(Locale.ROOT).getBytes(StandardCharsets.US_ASCII);
+ chars[0] = (byte) ((int) chars[0] + 'A' - 'a');
+ return new String(chars, StandardCharsets.US_ASCII);
+ } catch (UnsupportedOperationException uoe) {
+ throw new AssertionError(uoe);
+ }
+ }
+
+ /**
+ * A type list must contain one or more alphanumeric subtags whose lengths
+ * are between 3 and 8.
+ */
+ private static boolean isValidTypeList(String lowerCaseTypeList) {
+ final String[] splitList = lowerCaseTypeList.split("-");
+ for (String type : splitList) {
+ if (!isValidBcp47Alphanum(type, 3, 8)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static void addUnicodeExtensionToExtensionsMap(
+ Set<String> attributes, Map<String, String> keywords,
+ Map<Character, String> extensions) {
+ if (attributes.isEmpty() && keywords.isEmpty()) {
+ return;
+ }
+
+ // Assume that the common case is a low number of keywords & attributes
+ // (usually one or two).
+ final StringBuilder sb = new StringBuilder(32);
+
+ // All attributes must appear before keywords, in lexical order.
+ if (!attributes.isEmpty()) {
+ Iterator<String> attributesIterator = attributes.iterator();
+ while (true) {
+ sb.append(attributesIterator.next());
+ if (attributesIterator.hasNext()) {
+ sb.append('-');
+ } else {
+ break;
+ }
+ }
+ }
+
+ if (!keywords.isEmpty()) {
+ if (!attributes.isEmpty()) {
+ sb.append('-');
+ }
+
+ Iterator<Map.Entry<String, String>> keywordsIterator = keywords.entrySet().iterator();
+ while (true) {
+ final Map.Entry<String, String> keyWord = keywordsIterator.next();
+ sb.append(keyWord.getKey());
+ if (!keyWord.getValue().isEmpty()) {
+ sb.append('-');
+ sb.append(keyWord.getValue());
+ }
+ if (keywordsIterator.hasNext()) {
+ sb.append('-');
+ } else {
+ break;
+ }
+ }
+ }
+
+ extensions.put(UNICODE_LOCALE_EXTENSION, sb.toString());
+ }
+
+ /**
+ * This extension is described by http://www.unicode.org/reports/tr35/#RFC5234
+ * unicode_locale_extensions = sep "u" (1*(sep keyword) / 1*(sep attribute) *(sep keyword)).
+ *
+ * It must contain at least one keyword or attribute and attributes (if any)
+ * must appear before keywords. Attributes can't appear after keywords because
+ * they will be indistinguishable from a subtag of the keyword type.
+ *
+ * Visible for testing.
+ *
+ * @hide
+ */
+ public static void parseUnicodeExtension(String[] subtags,
+ Map<String, String> keywords, Set<String> attributes) {
+ String lastKeyword = null;
+ List<String> subtagsForKeyword = new ArrayList<String>();
+ for (String subtag : subtags) {
+ if (subtag.length() == 2) {
+ if (subtagsForKeyword.size() > 0) {
+ keywords.put(lastKeyword, joinBcp47Subtags(subtagsForKeyword));
+ subtagsForKeyword.clear();
+ }
+
+ lastKeyword = subtag;
+ } else if (subtag.length() > 2) {
+ if (lastKeyword == null) {
+ attributes.add(subtag);
+ } else {
+ subtagsForKeyword.add(subtag);
+ }
+ }
+ }
+
+ if (subtagsForKeyword.size() > 0) {
+ keywords.put(lastKeyword, joinBcp47Subtags(subtagsForKeyword));
+ } else if (lastKeyword != null) {
+ keywords.put(lastKeyword, "");
+ }
+ }
+
+ /**
+ * Joins a list of subtags into a BCP-47 tag using the standard separator
+ * ("-").
+ */
+ private static String joinBcp47Subtags(List<String> strings) {
+ final int size = strings.size();
+
+ StringBuilder sb = new StringBuilder(strings.get(0).length());
+ for (int i = 0; i < size; ++i) {
+ sb.append(strings.get(i));
+ if (i != size - 1) {
+ sb.append('-');
+ }
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * @hide for internal use only.
+ */
+ public static String adjustLanguageCode(String languageCode) {
+ String adjusted = languageCode.toLowerCase(Locale.US);
+ // Map new language codes to the obsolete language
+ // codes so the correct resource bundles will be used.
+ if (languageCode.equals("he")) {
+ adjusted = "iw";
+ } else if (languageCode.equals("id")) {
+ adjusted = "in";
+ } else if (languageCode.equals("yi")) {
+ adjusted = "ji";
+ }
+
+ return adjusted;
+ }
+
+ /**
+ * Map of grandfathered language tags to their modern replacements.
+ */
+ private static final TreeMap<String, String> GRANDFATHERED_LOCALES;
+
+ static {
+ GRANDFATHERED_LOCALES = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
+
+ // From http://tools.ietf.org/html/bcp47
+ //
+ // grandfathered = irregular ; non-redundant tags registered
+ // / regular ; during the RFC 3066 era
+ // irregular =
+ GRANDFATHERED_LOCALES.put("en-GB-oed", "en-GB-x-oed");
+ GRANDFATHERED_LOCALES.put("i-ami", "ami");
+ GRANDFATHERED_LOCALES.put("i-bnn", "bnn");
+ GRANDFATHERED_LOCALES.put("i-default", "en-x-i-default");
+ GRANDFATHERED_LOCALES.put("i-enochian", "und-x-i-enochian");
+ GRANDFATHERED_LOCALES.put("i-hak", "hak");
+ GRANDFATHERED_LOCALES.put("i-klingon", "tlh");
+ GRANDFATHERED_LOCALES.put("i-lux", "lb");
+ GRANDFATHERED_LOCALES.put("i-mingo", "see-x-i-mingo");
+ GRANDFATHERED_LOCALES.put("i-navajo", "nv");
+ GRANDFATHERED_LOCALES.put("i-pwn", "pwn");
+ GRANDFATHERED_LOCALES.put("i-tao", "tao");
+ GRANDFATHERED_LOCALES.put("i-tay", "tay");
+ GRANDFATHERED_LOCALES.put("i-tsu", "tsu");
+ GRANDFATHERED_LOCALES.put("sgn-BE-FR", "sfb");
+ GRANDFATHERED_LOCALES.put("sgn-BE-NL", "vgt");
+ GRANDFATHERED_LOCALES.put("sgn-CH-DE", "sgg");
+
+ // regular =
+ GRANDFATHERED_LOCALES.put("art-lojban", "jbo");
+ GRANDFATHERED_LOCALES.put("cel-gaulish", "xtg-x-cel-gaulish");
+ GRANDFATHERED_LOCALES.put("no-bok", "nb");
+ GRANDFATHERED_LOCALES.put("no-nyn", "nn");
+ GRANDFATHERED_LOCALES.put("zh-guoyu", "cmn");
+ GRANDFATHERED_LOCALES.put("zh-hakka", "hak");
+ GRANDFATHERED_LOCALES.put("zh-min", "nan-x-zh-min");
+ GRANDFATHERED_LOCALES.put("zh-min-nan", "nan");
+ GRANDFATHERED_LOCALES.put("zh-xiang", "hsn");
+ }
+
+ private static String convertGrandfatheredTag(String original) {
+ final String converted = GRANDFATHERED_LOCALES.get(original);
+ return converted != null ? converted : original;
+ }
+
+ /**
+ * Scans elements of {@code subtags} in the range {@code [startIndex, endIndex)}
+ * and appends valid variant subtags upto the first invalid subtag (if any) to
+ * {@code normalizedVariants}.
+ */
+ private static void extractVariantSubtags(String[] subtags, int startIndex, int endIndex,
+ List<String> normalizedVariants) {
+ for (int i = startIndex; i < endIndex; i++) {
+ final String subtag = subtags[i];
+
+ if (Builder.isValidVariantSubtag(subtag)) {
+ normalizedVariants.add(subtag);
+ } else {
+ break;
+ }
+ }
+ }
+
+ /**
+ * Scans elements of {@code subtags} in the range {@code [startIndex, endIndex)}
+ * and inserts valid extensions into {@code extensions}. The scan is aborted
+ * when an invalid extension is encountered. Returns the index of the first
+ * unparsable element of {@code subtags}.
+ */
+ private static int extractExtensions(String[] subtags, int startIndex, int endIndex,
+ Map<Character, String> extensions) {
+ int privateUseExtensionIndex = -1;
+ int extensionKeyIndex = -1;
+
+ int i = startIndex;
+ for (; i < endIndex; i++) {
+ final String subtag = subtags[i];
+
+ final boolean parsingPrivateUse = (privateUseExtensionIndex != -1) &&
+ (extensionKeyIndex == privateUseExtensionIndex);
+
+ // Note that private use extensions allow subtags of length 1.
+ // Private use extensions *must* come last, so there's no ambiguity
+ // in that case.
+ if (subtag.length() == 1 && !parsingPrivateUse) {
+ // Emit the last extension we encountered if any. First check
+ // whether we encountered two keys in a row (which is an error).
+ // Also checks if we already have an extension with the same key,
+ // which is again an error.
+ if (extensionKeyIndex != -1) {
+ if ((i - 1) == extensionKeyIndex) {
+ return extensionKeyIndex;
+ }
+
+ final String key = subtags[extensionKeyIndex];
+ if (extensions.containsKey(key.charAt(0))) {
+ return extensionKeyIndex;
+ }
+
+ final String value = concatenateRange(subtags, extensionKeyIndex + 1, i);
+ extensions.put(key.charAt(0), value.toLowerCase(Locale.ROOT));
+ }
+
+ // Mark the start of the next extension. Also keep track of whether this
+ // is a private use extension, and throw an error if it doesn't come last.
+ extensionKeyIndex = i;
+ if ("x".equals(subtag)) {
+ privateUseExtensionIndex = i;
+ } else if (privateUseExtensionIndex != -1) {
+ // The private use extension must come last.
+ return privateUseExtensionIndex;
+ }
+ } else if (extensionKeyIndex != -1) {
+ // We must have encountered a valid key in order to start parsing
+ // its subtags.
+ if (!isValidBcp47Alphanum(subtag, parsingPrivateUse ? 1 : 2, 8)) {
+ return i;
+ }
+ } else {
+ // Encountered a value without a preceding key.
+ return i;
+ }
+ }
+
+ if (extensionKeyIndex != -1) {
+ if ((i - 1) == extensionKeyIndex) {
+ return extensionKeyIndex;
+ }
+
+ final String key = subtags[extensionKeyIndex];
+ if (extensions.containsKey(key.charAt(0))) {
+ return extensionKeyIndex;
+ }
+
+ final String value = concatenateRange(subtags, extensionKeyIndex + 1, i);
+ extensions.put(key.charAt(0), value.toLowerCase(Locale.ROOT));
+ }
+
+ return i;
+ }
+
+ private static Locale forLanguageTag(/* @Nonnull */ String tag, boolean strict) {
+ final String converted = convertGrandfatheredTag(tag);
+ final String[] subtags = converted.split("-");
+
+ int lastSubtag = subtags.length;
+ for (int i = 0; i < subtags.length; ++i) {
+ final String subtag = subtags[i];
+ if (subtag.isEmpty() || subtag.length() > 8) {
+ if (strict) {
+ throw new IllformedLocaleException("Invalid subtag at index: " + i
+ + " in tag: " + tag);
+ } else {
+ lastSubtag = (i - 1);
+ }
+
+ break;
+ }
+ }
+
+ final String languageCode = Builder.normalizeAndValidateLanguage(subtags[0], strict);
+ String scriptCode = "";
+ int nextSubtag = 1;
+ if (lastSubtag > nextSubtag) {
+ scriptCode = Builder.normalizeAndValidateScript(subtags[nextSubtag], false /* strict */);
+ if (!scriptCode.isEmpty()) {
+ nextSubtag++;
+ }
+ }
+
+ String regionCode = "";
+ if (lastSubtag > nextSubtag) {
+ regionCode = Builder.normalizeAndValidateRegion(subtags[nextSubtag], false /* strict */);
+ if (!regionCode.isEmpty()) {
+ nextSubtag++;
+ }
+ }
+
+ List<String> variants = null;
+ if (lastSubtag > nextSubtag) {
+ variants = new ArrayList<String>();
+ extractVariantSubtags(subtags, nextSubtag, lastSubtag, variants);
+ nextSubtag += variants.size();
+ }
+
+ Map<Character, String> extensions = Collections.EMPTY_MAP;
+ if (lastSubtag > nextSubtag) {
+ extensions = new TreeMap<Character, String>();
+ nextSubtag = extractExtensions(subtags, nextSubtag, lastSubtag, extensions);
+ }
+
+ if (nextSubtag != lastSubtag) {
+ if (strict) {
+ throw new IllformedLocaleException("Unparseable subtag: " + subtags[nextSubtag]
+ + " from language tag: " + tag);
+ }
+ }
+
+ Set<String> unicodeKeywords = Collections.EMPTY_SET;
+ Map<String, String> unicodeAttributes = Collections.EMPTY_MAP;
+ if (extensions.containsKey(UNICODE_LOCALE_EXTENSION)) {
+ unicodeKeywords = new TreeSet<String>();
+ unicodeAttributes = new TreeMap<String, String>();
+ parseUnicodeExtension(extensions.get(UNICODE_LOCALE_EXTENSION).split("-"),
+ unicodeAttributes, unicodeKeywords);
+ }
+
+ String variantCode = "";
+ if (variants != null && !variants.isEmpty()) {
+ StringBuilder variantsBuilder = new StringBuilder(variants.size() * 8);
+ for (int i = 0; i < variants.size(); ++i) {
+ if (i != 0) {
+ variantsBuilder.append('_');
+ }
+ variantsBuilder.append(variants.get(i));
+ }
+ variantCode = variantsBuilder.toString();
+ }
+
+ return new Locale(languageCode, regionCode, variantCode, scriptCode,
+ unicodeKeywords, unicodeAttributes, extensions, true /* has validated fields */);
}
}
diff --git a/luni/src/main/java/java/util/Properties.java b/luni/src/main/java/java/util/Properties.java
index cd19295..532d35c 100644
--- a/luni/src/main/java/java/util/Properties.java
+++ b/luni/src/main/java/java/util/Properties.java
@@ -52,7 +52,7 @@ import org.xml.sax.SAXParseException;
* values to be used when a given key is not found in this {@code Properties}
* instance.
*
- * <a name="character_encoding"><h3>Character Encoding</h3></a>
+ * <a name="character_encoding"></a><h3>Character Encoding</h3>
* <p>Note that in some cases {@code Properties} uses ISO-8859-1 instead of UTF-8.
* ISO-8859-1 is only capable of representing a tiny subset of Unicode.
* Use either the {@code loadFromXML}/{@code storeToXML} methods (which use UTF-8 by
diff --git a/luni/src/main/java/java/util/Random.java b/luni/src/main/java/java/util/Random.java
index 4a67244..091d584 100644
--- a/luni/src/main/java/java/util/Random.java
+++ b/luni/src/main/java/java/util/Random.java
@@ -56,15 +56,19 @@ public class Random implements Serializable {
private double nextNextGaussian;
/**
+ * Used to generate initial seeds.
+ */
+ private static volatile long seedBase = 0;
+
+ /**
* Constructs a random generator with an initial state that is
* unlikely to be duplicated by a subsequent instantiation.
- *
- * <p>The initial state (that is, the seed) is <i>partially</i> based
- * on the current time of day in milliseconds.
*/
public Random() {
- // Note: Using identityHashCode() to be hermetic wrt subclasses.
- setSeed(System.currentTimeMillis() + System.identityHashCode(this));
+ // Note: Don't use identityHashCode(this) since that causes the monitor to
+ // get inflated when we synchronize.
+ setSeed(System.nanoTime() + seedBase);
+ ++seedBase;
}
/**
@@ -85,6 +89,9 @@ public class Random implements Serializable {
* Volume 2: Seminumerical Algorithms</i>, section 3.2.1.
*
* <p>Most applications will want to use one of this class' convenience methods instead.
+ *
+ * <p>Subclasses only need to override this method to alter the behavior
+ * of all the public methods.
*/
protected synchronized int next(int bits) {
seed = (seed * multiplier + 0xbL) & ((1L << 48) - 1);
diff --git a/luni/src/main/java/java/util/Scanner.java b/luni/src/main/java/java/util/Scanner.java
index 7d504b7..7d0e795 100644
--- a/luni/src/main/java/java/util/Scanner.java
+++ b/luni/src/main/java/java/util/Scanner.java
@@ -159,12 +159,15 @@ public final class Scanner implements Closeable, Iterator<String> {
if (charsetName == null) {
throw new IllegalArgumentException("charsetName == null");
}
+
+ InputStreamReader streamReader;
try {
- setInput(new InputStreamReader(fis, charsetName));
+ streamReader = new InputStreamReader(fis, charsetName);
} catch (UnsupportedEncodingException e) {
IoUtils.closeQuietly(fis);
throw new IllegalArgumentException(e.getMessage());
}
+ initialize(streamReader);
}
/**
@@ -174,7 +177,7 @@ public final class Scanner implements Closeable, Iterator<String> {
* the string to be scanned.
*/
public Scanner(String src) {
- setInput(new StringReader(src));
+ initialize(new StringReader(src));
}
/**
@@ -203,11 +206,14 @@ public final class Scanner implements Closeable, Iterator<String> {
if (src == null) {
throw new NullPointerException("src == null");
}
+
+ InputStreamReader streamReader;
try {
- setInput(new InputStreamReader(src, charsetName));
+ streamReader = new InputStreamReader(src, charsetName);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e.getMessage());
}
+ initialize(streamReader);
}
/**
@@ -220,7 +226,7 @@ public final class Scanner implements Closeable, Iterator<String> {
if (src == null) {
throw new NullPointerException("src == null");
}
- setInput(src);
+ initialize(src);
}
/**
@@ -252,13 +258,14 @@ public final class Scanner implements Closeable, Iterator<String> {
if (charsetName == null) {
throw new IllegalArgumentException("charsetName == null");
}
- setInput(Channels.newReader(src, charsetName));
+ initialize(Channels.newReader(src, charsetName));
}
- private void setInput(Readable input) {
+ private void initialize(Readable input) {
this.input = input;
- buffer.limit(0);
- matcher = delimiter.matcher(buffer);
+ matcher = delimiter.matcher("");
+ matcher.useTransparentBounds(true);
+ matcher.useAnchoringBounds(false);
}
/**
@@ -535,7 +542,7 @@ public final class Scanner implements Closeable, Iterator<String> {
checkOpen();
checkNotNull(pattern);
matchSuccessful = false;
- saveCurrentStatus();
+ prepareForScan();
// if the next token exists, set the match region, otherwise return
// false
if (!setTokenRegion()) {
@@ -790,7 +797,7 @@ public final class Scanner implements Closeable, Iterator<String> {
* @throws IllegalStateException if this {@code Scanner} is closed.
*/
public boolean hasNextLine() {
- saveCurrentStatus();
+ prepareForScan();
String result = findWithinHorizon(LINE_PATTERN, 0);
recoverPreviousStatus();
return result != null;
@@ -954,7 +961,7 @@ public final class Scanner implements Closeable, Iterator<String> {
checkOpen();
checkNotNull(pattern);
matchSuccessful = false;
- saveCurrentStatus();
+ prepareForScan();
if (!setTokenRegion()) {
recoverPreviousStatus();
// if setting match region fails
@@ -1204,7 +1211,7 @@ public final class Scanner implements Closeable, Iterator<String> {
Pattern floatPattern = getFloatPattern();
String floatString = next(floatPattern);
floatString = removeLocaleInfoFromFloat(floatString);
- double doubleValue = 0;
+ double doubleValue;
try {
doubleValue = Double.parseDouble(floatString);
} catch (NumberFormatException e) {
@@ -1248,7 +1255,7 @@ public final class Scanner implements Closeable, Iterator<String> {
Pattern floatPattern = getFloatPattern();
String floatString = next(floatPattern);
floatString = removeLocaleInfoFromFloat(floatString);
- float floatValue = 0;
+ float floatValue;
try {
floatValue = Float.parseFloat(floatString);
} catch (NumberFormatException e) {
@@ -1310,7 +1317,7 @@ public final class Scanner implements Closeable, Iterator<String> {
Pattern integerPattern = getIntegerPattern(radix);
String intString = next(integerPattern);
intString = removeLocaleInfo(intString, int.class);
- int intValue = 0;
+ int intValue;
try {
intValue = Integer.parseInt(intString, radix);
} catch (NumberFormatException e) {
@@ -1340,7 +1347,7 @@ public final class Scanner implements Closeable, Iterator<String> {
matcher.usePattern(LINE_PATTERN);
matcher.region(findStartIndex, bufferLength);
- String result = null;
+ String result;
while (true) {
if (matcher.find()) {
if (inputExhausted || matcher.end() != bufferLength
@@ -1422,7 +1429,7 @@ public final class Scanner implements Closeable, Iterator<String> {
Pattern integerPattern = getIntegerPattern(radix);
String intString = next(integerPattern);
intString = removeLocaleInfo(intString, int.class);
- long longValue = 0;
+ long longValue;
try {
longValue = Long.parseLong(intString, radix);
} catch (NumberFormatException e) {
@@ -1484,7 +1491,7 @@ public final class Scanner implements Closeable, Iterator<String> {
Pattern integerPattern = getIntegerPattern(radix);
String intString = next(integerPattern);
intString = removeLocaleInfo(intString, int.class);
- short shortValue = 0;
+ short shortValue;
try {
shortValue = Short.parseShort(intString, radix);
} catch (NumberFormatException e) {
@@ -1662,23 +1669,46 @@ public final class Scanner implements Closeable, Iterator<String> {
}
/*
- * Change the matcher's string after reading input
+ * Change the matcher's input after modifying the contents of the buffer.
+ * The current implementation of Matcher causes a copy of the buffer to be taken.
*/
private void resetMatcher() {
- if (matcher == null) {
- matcher = delimiter.matcher(buffer);
- } else {
- matcher.reset(buffer);
- }
- matcher.useTransparentBounds(true);
- matcher.useAnchoringBounds(false);
+ matcher.reset(buffer);
matcher.region(findStartIndex, bufferLength);
}
/*
- * Save the matcher's last find position
- */
- private void saveCurrentStatus() {
+ * Recover buffer space for characters that are already processed and save the matcher's state
+ * in case parsing fails. See recoverPrevousState. This method must be called before
+ * any buffer offsets are calculated.
+ */
+ private void prepareForScan() {
+ // Compacting the buffer recovers space taken by already processed characters. This does not
+ // prevent the buffer growing in all situations but keeps the buffer small when delimiters
+ // exist regularly.
+ if (findStartIndex >= buffer.capacity() / 2) {
+ // When over half the buffer is filled with characters no longer being considered by the
+ // scanner we take the cost of compacting the buffer.
+
+ // Move all characters from [findStartIndex, findStartIndex + remaining()) to
+ // [0, remaining()).
+ int oldPosition = buffer.position();
+ buffer.position(findStartIndex);
+ buffer.compact();
+ buffer.position(oldPosition);
+
+ // Update Scanner state to reflect the new buffer state.
+ bufferLength -= findStartIndex;
+ findStartIndex = 0;
+ preStartIndex = -1;
+
+ // The matcher must also be informed that the buffer has changed because it operates on
+ // a String copy.
+ resetMatcher();
+ }
+
+ // Save the matcher's last find position so it can be returned to if the next token cannot
+ // be parsed.
preStartIndex = findStartIndex;
}
@@ -1822,7 +1852,7 @@ public final class Scanner implements Closeable, Iterator<String> {
boolean negative = removeLocaleSign(tokenBuilder);
// Remove group separator
String groupSeparator = String.valueOf(dfs.getGroupingSeparator());
- int separatorIndex = -1;
+ int separatorIndex;
while ((separatorIndex = tokenBuilder.indexOf(groupSeparator)) != -1) {
tokenBuilder.delete(separatorIndex, separatorIndex + 1);
}
@@ -1909,9 +1939,9 @@ public final class Scanner implements Closeable, Iterator<String> {
*/
private boolean setTokenRegion() {
// The position where token begins
- int tokenStartIndex = 0;
+ int tokenStartIndex;
// The position where token ends
- int tokenEndIndex = 0;
+ int tokenEndIndex;
// Use delimiter pattern
matcher.usePattern(delimiter);
matcher.region(findStartIndex, bufferLength);
@@ -1945,8 +1975,7 @@ public final class Scanner implements Closeable, Iterator<String> {
if (matcher.find()) {
findComplete = true;
// If just delimiter remains
- if (matcher.start() == findStartIndex
- && matcher.end() == bufferLength) {
+ if (matcher.start() == findStartIndex && matcher.end() == bufferLength) {
// If more input resource exists
if (!inputExhausted) {
readMore();
@@ -1964,7 +1993,7 @@ public final class Scanner implements Closeable, Iterator<String> {
}
}
tokenStartIndex = matcher.end();
- findStartIndex = matcher.end();
+ findStartIndex = tokenStartIndex;
return tokenStartIndex;
}
@@ -1984,7 +2013,7 @@ public final class Scanner implements Closeable, Iterator<String> {
setSuccess = true;
}
// If the first delimiter of scanner is not at the find start position
- if (-1 != findIndex && preStartIndex != matcher.start()) {
+ if (findIndex != -1 && preStartIndex != matcher.start()) {
tokenStartIndex = preStartIndex;
tokenEndIndex = matcher.start();
findStartIndex = matcher.start();
@@ -1996,7 +2025,7 @@ public final class Scanner implements Closeable, Iterator<String> {
}
private int findDelimiterAfter() {
- int tokenEndIndex = 0;
+ int tokenEndIndex;
boolean findComplete = false;
while (!findComplete) {
if (matcher.find()) {
@@ -2014,7 +2043,7 @@ public final class Scanner implements Closeable, Iterator<String> {
}
}
tokenEndIndex = matcher.start();
- findStartIndex = matcher.start();
+ findStartIndex = tokenEndIndex;
return tokenEndIndex;
}
@@ -2032,7 +2061,7 @@ public final class Scanner implements Closeable, Iterator<String> {
}
// Read input resource
- int readCount = 0;
+ int readCount;
try {
buffer.limit(buffer.capacity());
buffer.position(oldBufferLength);
diff --git a/luni/src/main/java/java/util/TimeZone.java b/luni/src/main/java/java/util/TimeZone.java
index c024e8d..854a4a6 100644
--- a/luni/src/main/java/java/util/TimeZone.java
+++ b/luni/src/main/java/java/util/TimeZone.java
@@ -63,7 +63,7 @@ import org.apache.harmony.luni.internal.util.TimezoneGetter;
*
* @see Calendar
* @see GregorianCalendar
- * @see SimpleDateFormat
+ * @see java.text.SimpleDateFormat
*/
public abstract class TimeZone implements Serializable, Cloneable {
private static final long serialVersionUID = 3581463369166924961L;
@@ -206,27 +206,48 @@ public abstract class TimeZone implements Serializable, Cloneable {
// upgrade to icu4c 50 and rewrite the underlying native code. See also the
// "element[j] != null" check in SimpleDateFormat.parseTimeZone, and the extra work in
// DateFormatSymbols.getZoneStrings.
-
- int offset = getRawOffset();
+ int offsetMillis = getRawOffset();
if (daylightTime) {
- offset += getDSTSavings();
+ offsetMillis += getDSTSavings();
}
- offset /= 60000;
+ return createGmtOffsetString(true /* includeGmt */, true /* includeMinuteSeparator */,
+ offsetMillis);
+ }
+
+ /**
+ * Returns a string representation of an offset from UTC.
+ *
+ * <p>The format is "[GMT](+|-)HH[:]MM". The output is not localized.
+ *
+ * @param includeGmt true to include "GMT", false to exclude
+ * @param includeMinuteSeparator true to include the separator between hours and minutes, false
+ * to exclude.
+ * @param offsetMillis the offset from UTC
+ *
+ * @hide used internally by SimpleDateFormat
+ */
+ public static String createGmtOffsetString(boolean includeGmt,
+ boolean includeMinuteSeparator, int offsetMillis) {
+ int offsetMinutes = offsetMillis / 60000;
char sign = '+';
- if (offset < 0) {
+ if (offsetMinutes < 0) {
sign = '-';
- offset = -offset;
+ offsetMinutes = -offsetMinutes;
}
StringBuilder builder = new StringBuilder(9);
- builder.append("GMT");
+ if (includeGmt) {
+ builder.append("GMT");
+ }
builder.append(sign);
- appendNumber(builder, 2, offset / 60);
- builder.append(':');
- appendNumber(builder, 2, offset % 60);
+ appendNumber(builder, 2, offsetMinutes / 60);
+ if (includeMinuteSeparator) {
+ builder.append(':');
+ }
+ appendNumber(builder, 2, offsetMinutes % 60);
return builder.toString();
}
- private void appendNumber(StringBuilder builder, int count, int value) {
+ private static void appendNumber(StringBuilder builder, int count, int value) {
String string = Integer.toString(value);
for (int i = 0; i < count - string.length(); i++) {
builder.append('0');
@@ -329,7 +350,6 @@ public abstract class TimeZone implements Serializable, Cloneable {
}
// Special cases? These can clone an existing instance.
- // TODO: should we just add a cache to ZoneInfoDB instead?
if (id.length() == 3) {
if (id.equals("GMT")) {
return (TimeZone) GMT.clone();
diff --git a/luni/src/main/java/java/util/Timer.java b/luni/src/main/java/java/util/Timer.java
index 25ac432..7192f9b 100644
--- a/luni/src/main/java/java/util/Timer.java
+++ b/luni/src/main/java/java/util/Timer.java
@@ -356,9 +356,7 @@ public class Timer {
* Creates a new named {@code Timer} which may be specified to be run as a
* daemon thread.
*
- * @param name the name of the {@code Timer}.
- * @param isDaemon true if {@code Timer}'s thread should be a daemon thread.
- * @throws NullPointerException is {@code name} is {@code null}
+ * @throws NullPointerException if {@code name == null}
*/
public Timer(String name, boolean isDaemon) {
if (name == null) {
@@ -371,8 +369,7 @@ public class Timer {
/**
* Creates a new named {@code Timer} which does not run as a daemon thread.
*
- * @param name the name of the Timer.
- * @throws NullPointerException is {@code name} is {@code null}
+ * @throws NullPointerException if {@code name == null}
*/
public Timer(String name) {
this(name, false);
diff --git a/luni/src/main/java/java/util/TreeSet.java b/luni/src/main/java/java/util/TreeSet.java
index 502329e..791ffa6 100644
--- a/luni/src/main/java/java/util/TreeSet.java
+++ b/luni/src/main/java/java/util/TreeSet.java
@@ -258,7 +258,7 @@ public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
/**
* Returns the first element in this set.
- * @exception NoSuchElementException when this TreeSet is empty
+ * @throws NoSuchElementException when this TreeSet is empty
*/
public E first() {
return backingMap.firstKey();
@@ -266,7 +266,7 @@ public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
/**
* Returns the last element in this set.
- * @exception NoSuchElementException when this TreeSet is empty
+ * @throws NoSuchElementException when this TreeSet is empty
*/
public E last() {
return backingMap.lastKey();
@@ -413,10 +413,10 @@ public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
* @return a subset where the elements are greater or equal to
* <code>start</code> and less than <code>end</code>
*
- * @exception ClassCastException
+ * @throws ClassCastException
* when the start or end object cannot be compared with the
* elements in this TreeSet
- * @exception NullPointerException
+ * @throws NullPointerException
* when the start or end object is null and the comparator
* cannot handle null
*/
@@ -434,10 +434,10 @@ public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
* the end element
* @return a subset where the elements are less than <code>end</code>
*
- * @exception ClassCastException
+ * @throws ClassCastException
* when the end object cannot be compared with the elements
* in this TreeSet
- * @exception NullPointerException
+ * @throws NullPointerException
* when the end object is null and the comparator cannot
* handle null
*/
@@ -457,10 +457,10 @@ public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,
* @return a subset where the elements are greater or equal to
* <code>start</code>
*
- * @exception ClassCastException
+ * @throws ClassCastException
* when the start object cannot be compared with the elements
* in this TreeSet
- * @exception NullPointerException
+ * @throws NullPointerException
* when the start object is null and the comparator cannot
* handle null
*/
diff --git a/luni/src/main/java/java/util/UUID.java b/luni/src/main/java/java/util/UUID.java
index 3594d87..020ac95 100644
--- a/luni/src/main/java/java/util/UUID.java
+++ b/luni/src/main/java/java/util/UUID.java
@@ -182,28 +182,17 @@ public final class UUID implements Serializable, Comparable<UUID> {
throw new NullPointerException("uuid == null");
}
- int[] position = new int[5];
- int lastPosition = 1;
- int startPosition = 0;
-
- int i = 0;
- for (; i < position.length && lastPosition > 0; i++) {
- position[i] = uuid.indexOf("-", startPosition);
- lastPosition = position[i];
- startPosition = position[i] + 1;
- }
-
- // should have and only can have four "-" in UUID
- if (i != position.length || lastPosition != -1) {
+ String[] parts = uuid.split("-");
+ if (parts.length != 5) {
throw new IllegalArgumentException("Invalid UUID: " + uuid);
}
- long m1 = Long.parseLong(uuid.substring(0, position[0]), 16);
- long m2 = Long.parseLong(uuid.substring(position[0] + 1, position[1]), 16);
- long m3 = Long.parseLong(uuid.substring(position[1] + 1, position[2]), 16);
+ long m1 = Long.parsePositiveLong(parts[0], 16);
+ long m2 = Long.parsePositiveLong(parts[1], 16);
+ long m3 = Long.parsePositiveLong(parts[2], 16);
- long lsb1 = Long.parseLong(uuid.substring(position[2] + 1, position[3]), 16);
- long lsb2 = Long.parseLong(uuid.substring(position[3] + 1), 16);
+ long lsb1 = Long.parsePositiveLong(parts[3], 16);
+ long lsb2 = Long.parsePositiveLong(parts[4], 16);
long msb = (m1 << 32) | (m2 << 16) | m3;
long lsb = (lsb1 << 48) | lsb2;
diff --git a/luni/src/main/java/java/util/concurrent/ConcurrentHashMap.java b/luni/src/main/java/java/util/concurrent/ConcurrentHashMap.java
index c85a5cc..ea3b1e9 100644
--- a/luni/src/main/java/java/util/concurrent/ConcurrentHashMap.java
+++ b/luni/src/main/java/java/util/concurrent/ConcurrentHashMap.java
@@ -5,865 +5,729 @@
*/
package java.util.concurrent;
-import java.util.concurrent.locks.*;
-import java.util.*;
+
+import java.io.ObjectStreamField;
import java.io.Serializable;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.LockSupport;
+import java.util.concurrent.locks.ReentrantLock;
// BEGIN android-note
// removed link to collections framework docs
+// removed links to hidden api
// END android-note
/**
* A hash table supporting full concurrency of retrievals and
- * adjustable expected concurrency for updates. This class obeys the
+ * high expected concurrency for updates. This class obeys the
* same functional specification as {@link java.util.Hashtable}, and
* includes versions of methods corresponding to each method of
- * <tt>Hashtable</tt>. However, even though all operations are
+ * {@code Hashtable}. However, even though all operations are
* thread-safe, retrieval operations do <em>not</em> entail locking,
* and there is <em>not</em> any support for locking the entire table
* in a way that prevents all access. This class is fully
- * interoperable with <tt>Hashtable</tt> in programs that rely on its
+ * interoperable with {@code Hashtable} in programs that rely on its
* thread safety but not on its synchronization details.
*
- * <p> Retrieval operations (including <tt>get</tt>) generally do not
- * block, so may overlap with update operations (including
- * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results
- * of the most recently <em>completed</em> update operations holding
- * upon their onset. For aggregate operations such as <tt>putAll</tt>
- * and <tt>clear</tt>, concurrent retrievals may reflect insertion or
- * removal of only some entries. Similarly, Iterators and
- * Enumerations return elements reflecting the state of the hash table
- * at some point at or since the creation of the iterator/enumeration.
- * They do <em>not</em> throw {@link ConcurrentModificationException}.
- * However, iterators are designed to be used by only one thread at a time.
+ * <p>Retrieval operations (including {@code get}) generally do not
+ * block, so may overlap with update operations (including {@code put}
+ * and {@code remove}). Retrievals reflect the results of the most
+ * recently <em>completed</em> update operations holding upon their
+ * onset. (More formally, an update operation for a given key bears a
+ * <em>happens-before</em> relation with any (non-null) retrieval for
+ * that key reporting the updated value.) For aggregate operations
+ * such as {@code putAll} and {@code clear}, concurrent retrievals may
+ * reflect insertion or removal of only some entries. Similarly,
+ * Iterators and Enumerations return elements reflecting the state of
+ * the hash table at some point at or since the creation of the
+ * iterator/enumeration. They do <em>not</em> throw {@link
+ * ConcurrentModificationException}. However, iterators are designed
+ * to be used by only one thread at a time. Bear in mind that the
+ * results of aggregate status methods including {@code size}, {@code
+ * isEmpty}, and {@code containsValue} are typically useful only when
+ * a map is not undergoing concurrent updates in other threads.
+ * Otherwise the results of these methods reflect transient states
+ * that may be adequate for monitoring or estimation purposes, but not
+ * for program control.
*
- * <p> The allowed concurrency among update operations is guided by
- * the optional <tt>concurrencyLevel</tt> constructor argument
- * (default <tt>16</tt>), which is used as a hint for internal sizing. The
- * table is internally partitioned to try to permit the indicated
- * number of concurrent updates without contention. Because placement
- * in hash tables is essentially random, the actual concurrency will
- * vary. Ideally, you should choose a value to accommodate as many
- * threads as will ever concurrently modify the table. Using a
- * significantly higher value than you need can waste space and time,
- * and a significantly lower value can lead to thread contention. But
- * overestimates and underestimates within an order of magnitude do
- * not usually have much noticeable impact. A value of one is
- * appropriate when it is known that only one thread will modify and
- * all others will only read. Also, resizing this or any other kind of
- * hash table is a relatively slow operation, so, when possible, it is
- * a good idea to provide estimates of expected table sizes in
- * constructors.
+ * <p>The table is dynamically expanded when there are too many
+ * collisions (i.e., keys that have distinct hash codes but fall into
+ * the same slot modulo the table size), with the expected average
+ * effect of maintaining roughly two bins per mapping (corresponding
+ * to a 0.75 load factor threshold for resizing). There may be much
+ * variance around this average as mappings are added and removed, but
+ * overall, this maintains a commonly accepted time/space tradeoff for
+ * hash tables. However, resizing this or any other kind of hash
+ * table may be a relatively slow operation. When possible, it is a
+ * good idea to provide a size estimate as an optional {@code
+ * initialCapacity} constructor argument. An additional optional
+ * {@code loadFactor} constructor argument provides a further means of
+ * customizing initial table capacity by specifying the table density
+ * to be used in calculating the amount of space to allocate for the
+ * given number of elements. Also, for compatibility with previous
+ * versions of this class, constructors may optionally specify an
+ * expected {@code concurrencyLevel} as an additional hint for
+ * internal sizing. Note that using many keys with exactly the same
+ * {@code hashCode()} is a sure way to slow down performance of any
+ * hash table. To ameliorate impact, when keys are {@link Comparable},
+ * this class may use comparison order among keys to help break ties.
*
* <p>This class and its views and iterators implement all of the
* <em>optional</em> methods of the {@link Map} and {@link Iterator}
* interfaces.
*
- * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
- * does <em>not</em> allow <tt>null</tt> to be used as a key or value.
+ * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
+ * does <em>not</em> allow {@code null} to be used as a key or value.
*
* @since 1.5
* @author Doug Lea
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
-public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
- implements ConcurrentMap<K, V>, Serializable {
+public class ConcurrentHashMap<K,V> extends java.util.AbstractMap<K,V>
+ implements ConcurrentMap<K,V>, Serializable {
private static final long serialVersionUID = 7249069246763182397L;
/*
- * The basic strategy is to subdivide the table among Segments,
- * each of which itself is a concurrently readable hash table. To
- * reduce footprint, all but one segments are constructed only
- * when first needed (see ensureSegment). To maintain visibility
- * in the presence of lazy construction, accesses to segments as
- * well as elements of segment's table must use volatile access,
- * which is done via Unsafe within methods segmentAt etc
- * below. These provide the functionality of AtomicReferenceArrays
- * but reduce the levels of indirection. Additionally,
- * volatile-writes of table elements and entry "next" fields
- * within locked operations use the cheaper "lazySet" forms of
- * writes (via putOrderedObject) because these writes are always
- * followed by lock releases that maintain sequential consistency
- * of table updates.
- *
- * Historical note: The previous version of this class relied
- * heavily on "final" fields, which avoided some volatile reads at
- * the expense of a large initial footprint. Some remnants of
- * that design (including forced construction of segment 0) exist
- * to ensure serialization compatibility.
+ * Overview:
+ *
+ * The primary design goal of this hash table is to maintain
+ * concurrent readability (typically method get(), but also
+ * iterators and related methods) while minimizing update
+ * contention. Secondary goals are to keep space consumption about
+ * the same or better than java.util.HashMap, and to support high
+ * initial insertion rates on an empty table by many threads.
+ *
+ * This map usually acts as a binned (bucketed) hash table. Each
+ * key-value mapping is held in a Node. Most nodes are instances
+ * of the basic Node class with hash, key, value, and next
+ * fields. However, various subclasses exist: TreeNodes are
+ * arranged in balanced trees, not lists. TreeBins hold the roots
+ * of sets of TreeNodes. ForwardingNodes are placed at the heads
+ * of bins during resizing. ReservationNodes are used as
+ * placeholders while establishing values in computeIfAbsent and
+ * related methods. The types TreeBin, ForwardingNode, and
+ * ReservationNode do not hold normal user keys, values, or
+ * hashes, and are readily distinguishable during search etc
+ * because they have negative hash fields and null key and value
+ * fields. (These special nodes are either uncommon or transient,
+ * so the impact of carrying around some unused fields is
+ * insignificant.)
+ *
+ * The table is lazily initialized to a power-of-two size upon the
+ * first insertion. Each bin in the table normally contains a
+ * list of Nodes (most often, the list has only zero or one Node).
+ * Table accesses require volatile/atomic reads, writes, and
+ * CASes. Because there is no other way to arrange this without
+ * adding further indirections, we use intrinsics
+ * (sun.misc.Unsafe) operations.
+ *
+ * We use the top (sign) bit of Node hash fields for control
+ * purposes -- it is available anyway because of addressing
+ * constraints. Nodes with negative hash fields are specially
+ * handled or ignored in map methods.
+ *
+ * Insertion (via put or its variants) of the first node in an
+ * empty bin is performed by just CASing it to the bin. This is
+ * by far the most common case for put operations under most
+ * key/hash distributions. Other update operations (insert,
+ * delete, and replace) require locks. We do not want to waste
+ * the space required to associate a distinct lock object with
+ * each bin, so instead use the first node of a bin list itself as
+ * a lock. Locking support for these locks relies on builtin
+ * "synchronized" monitors.
+ *
+ * Using the first node of a list as a lock does not by itself
+ * suffice though: When a node is locked, any update must first
+ * validate that it is still the first node after locking it, and
+ * retry if not. Because new nodes are always appended to lists,
+ * once a node is first in a bin, it remains first until deleted
+ * or the bin becomes invalidated (upon resizing).
+ *
+ * The main disadvantage of per-bin locks is that other update
+ * operations on other nodes in a bin list protected by the same
+ * lock can stall, for example when user equals() or mapping
+ * functions take a long time. However, statistically, under
+ * random hash codes, this is not a common problem. Ideally, the
+ * frequency of nodes in bins follows a Poisson distribution
+ * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
+ * parameter of about 0.5 on average, given the resizing threshold
+ * of 0.75, although with a large variance because of resizing
+ * granularity. Ignoring variance, the expected occurrences of
+ * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
+ * first values are:
+ *
+ * 0: 0.60653066
+ * 1: 0.30326533
+ * 2: 0.07581633
+ * 3: 0.01263606
+ * 4: 0.00157952
+ * 5: 0.00015795
+ * 6: 0.00001316
+ * 7: 0.00000094
+ * 8: 0.00000006
+ * more: less than 1 in ten million
+ *
+ * Lock contention probability for two threads accessing distinct
+ * elements is roughly 1 / (8 * #elements) under random hashes.
+ *
+ * Actual hash code distributions encountered in practice
+ * sometimes deviate significantly from uniform randomness. This
+ * includes the case when N > (1<<30), so some keys MUST collide.
+ * Similarly for dumb or hostile usages in which multiple keys are
+ * designed to have identical hash codes or ones that differs only
+ * in masked-out high bits. So we use a secondary strategy that
+ * applies when the number of nodes in a bin exceeds a
+ * threshold. These TreeBins use a balanced tree to hold nodes (a
+ * specialized form of red-black trees), bounding search time to
+ * O(log N). Each search step in a TreeBin is at least twice as
+ * slow as in a regular list, but given that N cannot exceed
+ * (1<<64) (before running out of addresses) this bounds search
+ * steps, lock hold times, etc, to reasonable constants (roughly
+ * 100 nodes inspected per operation worst case) so long as keys
+ * are Comparable (which is very common -- String, Long, etc).
+ * TreeBin nodes (TreeNodes) also maintain the same "next"
+ * traversal pointers as regular nodes, so can be traversed in
+ * iterators in the same way.
+ *
+ * The table is resized when occupancy exceeds a percentage
+ * threshold (nominally, 0.75, but see below). Any thread
+ * noticing an overfull bin may assist in resizing after the
+ * initiating thread allocates and sets up the replacement
+ * array. However, rather than stalling, these other threads may
+ * proceed with insertions etc. The use of TreeBins shields us
+ * from the worst case effects of overfilling while resizes are in
+ * progress. Resizing proceeds by transferring bins, one by one,
+ * from the table to the next table. To enable concurrency, the
+ * next table must be (incrementally) prefilled with place-holders
+ * serving as reverse forwarders to the old table. Because we are
+ * using power-of-two expansion, the elements from each bin must
+ * either stay at same index, or move with a power of two
+ * offset. We eliminate unnecessary node creation by catching
+ * cases where old nodes can be reused because their next fields
+ * won't change. On average, only about one-sixth of them need
+ * cloning when a table doubles. The nodes they replace will be
+ * garbage collectable as soon as they are no longer referenced by
+ * any reader thread that may be in the midst of concurrently
+ * traversing table. Upon transfer, the old table bin contains
+ * only a special forwarding node (with hash field "MOVED") that
+ * contains the next table as its key. On encountering a
+ * forwarding node, access and update operations restart, using
+ * the new table.
+ *
+ * Each bin transfer requires its bin lock, which can stall
+ * waiting for locks while resizing. However, because other
+ * threads can join in and help resize rather than contend for
+ * locks, average aggregate waits become shorter as resizing
+ * progresses. The transfer operation must also ensure that all
+ * accessible bins in both the old and new table are usable by any
+ * traversal. This is arranged by proceeding from the last bin
+ * (table.length - 1) up towards the first. Upon seeing a
+ * forwarding node, traversals (see class Traverser) arrange to
+ * move to the new table without revisiting nodes. However, to
+ * ensure that no intervening nodes are skipped, bin splitting can
+ * only begin after the associated reverse-forwarders are in
+ * place.
+ *
+ * The traversal scheme also applies to partial traversals of
+ * ranges of bins (via an alternate Traverser constructor)
+ * to support partitioned aggregate operations. Also, read-only
+ * operations give up if ever forwarded to a null table, which
+ * provides support for shutdown-style clearing, which is also not
+ * currently implemented.
+ *
+ * Lazy table initialization minimizes footprint until first use,
+ * and also avoids resizings when the first operation is from a
+ * putAll, constructor with map argument, or deserialization.
+ * These cases attempt to override the initial capacity settings,
+ * but harmlessly fail to take effect in cases of races.
+ *
+ * The element count is maintained using a specialization of
+ * LongAdder. We need to incorporate a specialization rather than
+ * just use a LongAdder in order to access implicit
+ * contention-sensing that leads to creation of multiple
+ * CounterCells. The counter mechanics avoid contention on
+ * updates but can encounter cache thrashing if read too
+ * frequently during concurrent access. To avoid reading so often,
+ * resizing under contention is attempted only upon adding to a
+ * bin already holding two or more nodes. Under uniform hash
+ * distributions, the probability of this occurring at threshold
+ * is around 13%, meaning that only about 1 in 8 puts check
+ * threshold (and after resizing, many fewer do so).
+ *
+ * TreeBins use a special form of comparison for search and
+ * related operations (which is the main reason we cannot use
+ * existing collections such as TreeMaps). TreeBins contain
+ * Comparable elements, but may contain others, as well as
+ * elements that are Comparable but not necessarily Comparable
+ * for the same T, so we cannot invoke compareTo among them. To
+ * handle this, the tree is ordered primarily by hash value, then
+ * by Comparable.compareTo order if applicable. On lookup at a
+ * node, if elements are not comparable or compare as 0 then both
+ * left and right children may need to be searched in the case of
+ * tied hash values. (This corresponds to the full list search
+ * that would be necessary if all elements were non-Comparable and
+ * had tied hashes.) The red-black balancing code is updated from
+ * pre-jdk-collections
+ * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
+ * based in turn on Cormen, Leiserson, and Rivest "Introduction to
+ * Algorithms" (CLR).
+ *
+ * TreeBins also require an additional locking mechanism. While
+ * list traversal is always possible by readers even during
+ * updates, tree traversal is not, mainly because of tree-rotations
+ * that may change the root node and/or its linkages. TreeBins
+ * include a simple read-write lock mechanism parasitic on the
+ * main bin-synchronization strategy: Structural adjustments
+ * associated with an insertion or removal are already bin-locked
+ * (and so cannot conflict with other writers) but must wait for
+ * ongoing readers to finish. Since there can be only one such
+ * waiter, we use a simple scheme using a single "waiter" field to
+ * block writers. However, readers need never block. If the root
+ * lock is held, they proceed along the slow traversal path (via
+ * next-pointers) until the lock becomes available or the list is
+ * exhausted, whichever comes first. These cases are not fast, but
+ * maximize aggregate expected throughput.
+ *
+ * Maintaining API and serialization compatibility with previous
+ * versions of this class introduces several oddities. Mainly: We
+ * leave untouched but unused constructor arguments refering to
+ * concurrencyLevel. We accept a loadFactor constructor argument,
+ * but apply it only to initial table capacity (which is the only
+ * time that we can guarantee to honor it.) We also declare an
+ * unused "Segment" class that is instantiated in minimal form
+ * only when serializing.
+ *
+ * This file is organized to make things a little easier to follow
+ * while reading than they might otherwise: First the main static
+ * declarations and utilities, then fields, then main public
+ * methods (with a few factorings of multiple public methods into
+ * internal ones), then sizing methods, trees, traversers, and
+ * bulk operations.
*/
/* ---------------- Constants -------------- */
/**
- * The default initial capacity for this table,
- * used when not otherwise specified in a constructor.
+ * The largest possible table capacity. This value must be
+ * exactly 1<<30 to stay within Java array allocation and indexing
+ * bounds for power of two table sizes, and is further required
+ * because the top two bits of 32bit hash fields are used for
+ * control purposes.
*/
- static final int DEFAULT_INITIAL_CAPACITY = 16;
+ private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
- * The default load factor for this table, used when not
- * otherwise specified in a constructor.
+ * The default initial table capacity. Must be a power of 2
+ * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
*/
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
+ private static final int DEFAULT_CAPACITY = 16;
/**
- * The default concurrency level for this table, used when not
- * otherwise specified in a constructor.
+ * The largest possible (non-power of two) array size.
+ * Needed by toArray and related methods.
*/
- static final int DEFAULT_CONCURRENCY_LEVEL = 16;
+ static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
- * The maximum capacity, used if a higher value is implicitly
- * specified by either of the constructors with arguments. MUST
- * be a power of two <= 1<<30 to ensure that entries are indexable
- * using ints.
+ * The default concurrency level for this table. Unused but
+ * defined for compatibility with previous versions of this class.
*/
- static final int MAXIMUM_CAPACITY = 1 << 30;
+ private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
/**
- * The minimum capacity for per-segment tables. Must be a power
- * of two, at least two to avoid immediate resizing on next use
- * after lazy construction.
+ * The load factor for this table. Overrides of this value in
+ * constructors affect only the initial table capacity. The
+ * actual floating point value isn't normally used -- it is
+ * simpler to use expressions such as {@code n - (n >>> 2)} for
+ * the associated resizing threshold.
*/
- static final int MIN_SEGMENT_TABLE_CAPACITY = 2;
+ private static final float LOAD_FACTOR = 0.75f;
/**
- * The maximum number of segments to allow; used to bound
- * constructor arguments. Must be power of two less than 1 << 24.
+ * The bin count threshold for using a tree rather than list for a
+ * bin. Bins are converted to trees when adding an element to a
+ * bin with at least this many nodes. The value must be greater
+ * than 2, and should be at least 8 to mesh with assumptions in
+ * tree removal about conversion back to plain bins upon
+ * shrinkage.
*/
- static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
+ static final int TREEIFY_THRESHOLD = 8;
/**
- * Number of unsynchronized retries in size and containsValue
- * methods before resorting to locking. This is used to avoid
- * unbounded retries if tables undergo continuous modification
- * which would make it impossible to obtain an accurate result.
+ * The bin count threshold for untreeifying a (split) bin during a
+ * resize operation. Should be less than TREEIFY_THRESHOLD, and at
+ * most 6 to mesh with shrinkage detection under removal.
*/
- static final int RETRIES_BEFORE_LOCK = 2;
-
- /* ---------------- Fields -------------- */
+ static final int UNTREEIFY_THRESHOLD = 6;
/**
- * Mask value for indexing into segments. The upper bits of a
- * key's hash code are used to choose the segment.
+ * The smallest table capacity for which bins may be treeified.
+ * (Otherwise the table is resized if too many nodes in a bin.)
+ * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
+ * conflicts between resizing and treeification thresholds.
*/
- final int segmentMask;
+ static final int MIN_TREEIFY_CAPACITY = 64;
/**
- * Shift value for indexing within segments.
+ * Minimum number of rebinnings per transfer step. Ranges are
+ * subdivided to allow multiple resizer threads. This value
+ * serves as a lower bound to avoid resizers encountering
+ * excessive memory contention. The value should be at least
+ * DEFAULT_CAPACITY.
*/
- final int segmentShift;
+ private static final int MIN_TRANSFER_STRIDE = 16;
- /**
- * The segments, each of which is a specialized hash table.
+ /*
+ * Encodings for Node hash fields. See above for explanation.
*/
- final Segment<K,V>[] segments;
+ static final int MOVED = 0x8fffffff; // (-1) hash for forwarding nodes
+ static final int TREEBIN = 0x80000000; // hash for roots of trees
+ static final int RESERVED = 0x80000001; // hash for transient reservations
+ static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
+
+ /** Number of CPUS, to place bounds on some sizings */
+ static final int NCPU = Runtime.getRuntime().availableProcessors();
- transient Set<K> keySet;
- transient Set<Map.Entry<K,V>> entrySet;
- transient Collection<V> values;
+ /** For serialization compatibility. */
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("segments", Segment[].class),
+ new ObjectStreamField("segmentMask", Integer.TYPE),
+ new ObjectStreamField("segmentShift", Integer.TYPE)
+ };
+
+ /* ---------------- Nodes -------------- */
/**
- * ConcurrentHashMap list entry. Note that this is never exported
- * out as a user-visible Map.Entry.
+ * Key-value entry. This class is never exported out as a
+ * user-mutable Map.Entry (i.e., one supporting setValue; see
+ * MapEntry below), but can be used for read-only traversals used
+ * in bulk tasks. Subclasses of Node with a negative hash field
+ * are special, and contain null keys and values (but are never
+ * exported). Otherwise, keys and vals are never null.
*/
- static final class HashEntry<K,V> {
+ static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
- volatile V value;
- volatile HashEntry<K,V> next;
+ volatile V val;
+ Node<K,V> next;
- HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
+ Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
- this.value = value;
+ this.val = val;
this.next = next;
}
- /**
- * Sets next field with volatile write semantics. (See above
- * about use of putOrderedObject.)
- */
- final void setNext(HashEntry<K,V> n) {
- UNSAFE.putOrderedObject(this, nextOffset, n);
+ public final K getKey() { return key; }
+ public final V getValue() { return val; }
+ public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
+ public final String toString(){ return key + "=" + val; }
+ public final V setValue(V value) {
+ throw new UnsupportedOperationException();
}
- // Unsafe mechanics
- static final sun.misc.Unsafe UNSAFE;
- static final long nextOffset;
- static {
- try {
- UNSAFE = sun.misc.Unsafe.getUnsafe();
- Class<?> k = HashEntry.class;
- nextOffset = UNSAFE.objectFieldOffset
- (k.getDeclaredField("next"));
- } catch (Exception e) {
- throw new Error(e);
+ public final boolean equals(Object o) {
+ Object k, v, u; Map.Entry<?,?> e;
+ return ((o instanceof Map.Entry) &&
+ (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
+ (v = e.getValue()) != null &&
+ (k == key || k.equals(key)) &&
+ (v == (u = val) || v.equals(u)));
+ }
+
+ /**
+ * Virtualized support for map.get(); overridden in subclasses.
+ */
+ Node<K,V> find(int h, Object k) {
+ Node<K,V> e = this;
+ if (k != null) {
+ do {
+ K ek;
+ if (e.hash == h &&
+ ((ek = e.key) == k || (ek != null && k.equals(ek))))
+ return e;
+ } while ((e = e.next) != null);
}
+ return null;
}
}
+ /* ---------------- Static utilities -------------- */
+
/**
- * Gets the ith element of given table (if nonnull) with volatile
- * read semantics. Note: This is manually integrated into a few
- * performance-sensitive methods to reduce call overhead.
+ * Spreads (XORs) higher bits of hash to lower and also forces top
+ * bit to 0. Because the table uses power-of-two masking, sets of
+ * hashes that vary only in bits above the current mask will
+ * always collide. (Among known examples are sets of Float keys
+ * holding consecutive whole numbers in small tables.) So we
+ * apply a transform that spreads the impact of higher bits
+ * downward. There is a tradeoff between speed, utility, and
+ * quality of bit-spreading. Because many common sets of hashes
+ * are already reasonably distributed (so don't benefit from
+ * spreading), and because we use trees to handle large sets of
+ * collisions in bins, we just XOR some shifted bits in the
+ * cheapest possible way to reduce systematic lossage, as well as
+ * to incorporate impact of the highest bits that would otherwise
+ * never be used in index calculations because of table bounds.
*/
- @SuppressWarnings("unchecked")
- static final <K,V> HashEntry<K,V> entryAt(HashEntry<K,V>[] tab, int i) {
- return (tab == null) ? null :
- (HashEntry<K,V>) UNSAFE.getObjectVolatile
- (tab, ((long)i << TSHIFT) + TBASE);
+ static final int spread(int h) {
+ return (h ^ (h >>> 16)) & HASH_BITS;
}
/**
- * Sets the ith element of given table, with volatile write
- * semantics. (See above about use of putOrderedObject.)
+ * Returns a power of two table size for the given desired capacity.
+ * See Hackers Delight, sec 3.2
*/
- static final <K,V> void setEntryAt(HashEntry<K,V>[] tab, int i,
- HashEntry<K,V> e) {
- UNSAFE.putOrderedObject(tab, ((long)i << TSHIFT) + TBASE, e);
+ private static final int tableSizeFor(int c) {
+ int n = c - 1;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
+
/**
- * Applies a supplemental hash function to a given hashCode, which
- * defends against poor quality hash functions. This is critical
- * because ConcurrentHashMap uses power-of-two length hash tables,
- * that otherwise encounter collisions for hashCodes that do not
- * differ in lower or upper bits.
+ * Returns x's Class if it is of the form "class C implements
+ * Comparable<C>", else null.
*/
- private static int hash(int h) {
- // Spread bits to regularize both segment and index locations,
- // using variant of single-word Wang/Jenkins hash.
- h += (h << 15) ^ 0xffffcd7d;
- h ^= (h >>> 10);
- h += (h << 3);
- h ^= (h >>> 6);
- h += (h << 2) + (h << 14);
- return h ^ (h >>> 16);
+ static Class<?> comparableClassFor(Object x) {
+ if (x instanceof Comparable) {
+ Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
+ if ((c = x.getClass()) == String.class) // bypass checks
+ return c;
+ if ((ts = c.getGenericInterfaces()) != null) {
+ for (int i = 0; i < ts.length; ++i) {
+ if (((t = ts[i]) instanceof ParameterizedType) &&
+ ((p = (ParameterizedType)t).getRawType() ==
+ Comparable.class) &&
+ (as = p.getActualTypeArguments()) != null &&
+ as.length == 1 && as[0] == c) // type arg is c
+ return c;
+ }
+ }
+ }
+ return null;
}
/**
- * Segments are specialized versions of hash tables. This
- * subclasses from ReentrantLock opportunistically, just to
- * simplify some locking and avoid separate construction.
+ * Returns k.compareTo(x) if x matches kc (k's screened comparable
+ * class), else 0.
*/
- static final class Segment<K,V> extends ReentrantLock implements Serializable {
- /*
- * Segments maintain a table of entry lists that are always
- * kept in a consistent state, so can be read (via volatile
- * reads of segments and tables) without locking. This
- * requires replicating nodes when necessary during table
- * resizing, so the old lists can be traversed by readers
- * still using old version of table.
- *
- * This class defines only mutative methods requiring locking.
- * Except as noted, the methods of this class perform the
- * per-segment versions of ConcurrentHashMap methods. (Other
- * methods are integrated directly into ConcurrentHashMap
- * methods.) These mutative methods use a form of controlled
- * spinning on contention via methods scanAndLock and
- * scanAndLockForPut. These intersperse tryLocks with
- * traversals to locate nodes. The main benefit is to absorb
- * cache misses (which are very common for hash tables) while
- * obtaining locks so that traversal is faster once
- * acquired. We do not actually use the found nodes since they
- * must be re-acquired under lock anyway to ensure sequential
- * consistency of updates (and in any case may be undetectably
- * stale), but they will normally be much faster to re-locate.
- * Also, scanAndLockForPut speculatively creates a fresh node
- * to use in put if no node is found.
- */
+ @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
+ static int compareComparables(Class<?> kc, Object k, Object x) {
+ return (x == null || x.getClass() != kc ? 0 :
+ ((Comparable)k).compareTo(x));
+ }
- private static final long serialVersionUID = 2249069246763182397L;
+ /* ---------------- Table element access -------------- */
- /**
- * The maximum number of times to tryLock in a prescan before
- * possibly blocking on acquire in preparation for a locked
- * segment operation. On multiprocessors, using a bounded
- * number of retries maintains cache acquired while locating
- * nodes.
- */
- static final int MAX_SCAN_RETRIES =
- Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
+ /*
+ * Volatile access methods are used for table elements as well as
+ * elements of in-progress next table while resizing. All uses of
+ * the tab arguments must be null checked by callers. All callers
+ * also paranoically precheck that tab's length is not zero (or an
+ * equivalent check), thus ensuring that any index argument taking
+ * the form of a hash value anded with (length - 1) is a valid
+ * index. Note that, to be correct wrt arbitrary concurrency
+ * errors by users, these checks must operate on local variables,
+ * which accounts for some odd-looking inline assignments below.
+ * Note that calls to setTabAt always occur within locked regions,
+ * and so do not need full volatile semantics, but still require
+ * ordering to maintain concurrent readability.
+ */
- /**
- * The per-segment table. Elements are accessed via
- * entryAt/setEntryAt providing volatile semantics.
- */
- transient volatile HashEntry<K,V>[] table;
+ @SuppressWarnings("unchecked")
+ static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
+ return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
+ }
- /**
- * The number of elements. Accessed only either within locks
- * or among other volatile reads that maintain visibility.
- */
- transient int count;
+ static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
+ Node<K,V> c, Node<K,V> v) {
+ return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
+ }
- /**
- * The total number of mutative operations in this segment.
- * Even though this may overflows 32 bits, it provides
- * sufficient accuracy for stability checks in CHM isEmpty()
- * and size() methods. Accessed only either within locks or
- * among other volatile reads that maintain visibility.
- */
- transient int modCount;
+ static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
+ U.putOrderedObject(tab, ((long)i << ASHIFT) + ABASE, v);
+ }
- /**
- * The table is rehashed when its size exceeds this threshold.
- * (The value of this field is always <tt>(int)(capacity *
- * loadFactor)</tt>.)
- */
- transient int threshold;
+ /* ---------------- Fields -------------- */
- /**
- * The load factor for the hash table. Even though this value
- * is same for all segments, it is replicated to avoid needing
- * links to outer object.
- * @serial
- */
- final float loadFactor;
+ /**
+ * The array of bins. Lazily initialized upon first insertion.
+ * Size is always a power of two. Accessed directly by iterators.
+ */
+ transient volatile Node<K,V>[] table;
- Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
- this.loadFactor = lf;
- this.threshold = threshold;
- this.table = tab;
- }
+ /**
+ * The next table to use; non-null only while resizing.
+ */
+ private transient volatile Node<K,V>[] nextTable;
- final V put(K key, int hash, V value, boolean onlyIfAbsent) {
- HashEntry<K,V> node = tryLock() ? null :
- scanAndLockForPut(key, hash, value);
- V oldValue;
- try {
- HashEntry<K,V>[] tab = table;
- int index = (tab.length - 1) & hash;
- HashEntry<K,V> first = entryAt(tab, index);
- for (HashEntry<K,V> e = first;;) {
- if (e != null) {
- K k;
- if ((k = e.key) == key ||
- (e.hash == hash && key.equals(k))) {
- oldValue = e.value;
- if (!onlyIfAbsent) {
- e.value = value;
- ++modCount;
- }
- break;
- }
- e = e.next;
- }
- else {
- if (node != null)
- node.setNext(first);
- else
- node = new HashEntry<K,V>(hash, key, value, first);
- int c = count + 1;
- if (c > threshold && tab.length < MAXIMUM_CAPACITY)
- rehash(node);
- else
- setEntryAt(tab, index, node);
- ++modCount;
- count = c;
- oldValue = null;
- break;
- }
- }
- } finally {
- unlock();
- }
- return oldValue;
- }
+ /**
+ * Base counter value, used mainly when there is no contention,
+ * but also as a fallback during table initialization
+ * races. Updated via CAS.
+ */
+ private transient volatile long baseCount;
- /**
- * Doubles size of table and repacks entries, also adding the
- * given node to new table
- */
- @SuppressWarnings("unchecked")
- private void rehash(HashEntry<K,V> node) {
- /*
- * Reclassify nodes in each list to new table. Because we
- * are using power-of-two expansion, the elements from
- * each bin must either stay at same index, or move with a
- * power of two offset. We eliminate unnecessary node
- * creation by catching cases where old nodes can be
- * reused because their next fields won't change.
- * Statistically, at the default threshold, only about
- * one-sixth of them need cloning when a table
- * doubles. The nodes they replace will be garbage
- * collectable as soon as they are no longer referenced by
- * any reader thread that may be in the midst of
- * concurrently traversing table. Entry accesses use plain
- * array indexing because they are followed by volatile
- * table write.
- */
- HashEntry<K,V>[] oldTable = table;
- int oldCapacity = oldTable.length;
- int newCapacity = oldCapacity << 1;
- threshold = (int)(newCapacity * loadFactor);
- HashEntry<K,V>[] newTable =
- (HashEntry<K,V>[]) new HashEntry<?,?>[newCapacity];
- int sizeMask = newCapacity - 1;
- for (int i = 0; i < oldCapacity ; i++) {
- HashEntry<K,V> e = oldTable[i];
- if (e != null) {
- HashEntry<K,V> next = e.next;
- int idx = e.hash & sizeMask;
- if (next == null) // Single node on list
- newTable[idx] = e;
- else { // Reuse consecutive sequence at same slot
- HashEntry<K,V> lastRun = e;
- int lastIdx = idx;
- for (HashEntry<K,V> last = next;
- last != null;
- last = last.next) {
- int k = last.hash & sizeMask;
- if (k != lastIdx) {
- lastIdx = k;
- lastRun = last;
- }
- }
- newTable[lastIdx] = lastRun;
- // Clone remaining nodes
- for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
- V v = p.value;
- int h = p.hash;
- int k = h & sizeMask;
- HashEntry<K,V> n = newTable[k];
- newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
- }
- }
- }
- }
- int nodeIndex = node.hash & sizeMask; // add the new node
- node.setNext(newTable[nodeIndex]);
- newTable[nodeIndex] = node;
- table = newTable;
- }
+ /**
+ * Table initialization and resizing control. When negative, the
+ * table is being initialized or resized: -1 for initialization,
+ * else -(1 + the number of active resizing threads). Otherwise,
+ * when table is null, holds the initial table size to use upon
+ * creation, or 0 for default. After initialization, holds the
+ * next element count value upon which to resize the table.
+ */
+ private transient volatile int sizeCtl;
- /**
- * Scans for a node containing given key while trying to
- * acquire lock, creating and returning one if not found. Upon
- * return, guarantees that lock is held. Unlike in most
- * methods, calls to method equals are not screened: Since
- * traversal speed doesn't matter, we might as well help warm
- * up the associated code and accesses as well.
- *
- * @return a new node if key not found, else null
- */
- private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
- HashEntry<K,V> first = entryForHash(this, hash);
- HashEntry<K,V> e = first;
- HashEntry<K,V> node = null;
- int retries = -1; // negative while locating node
- while (!tryLock()) {
- HashEntry<K,V> f; // to recheck first below
- if (retries < 0) {
- if (e == null) {
- if (node == null) // speculatively create node
- node = new HashEntry<K,V>(hash, key, value, null);
- retries = 0;
- }
- else if (key.equals(e.key))
- retries = 0;
- else
- e = e.next;
- }
- else if (++retries > MAX_SCAN_RETRIES) {
- lock();
- break;
- }
- else if ((retries & 1) == 0 &&
- (f = entryForHash(this, hash)) != first) {
- e = first = f; // re-traverse if entry changed
- retries = -1;
- }
- }
- return node;
- }
+ /**
+ * The next table index (plus one) to split while resizing.
+ */
+ private transient volatile int transferIndex;
- /**
- * Scans for a node containing the given key while trying to
- * acquire lock for a remove or replace operation. Upon
- * return, guarantees that lock is held. Note that we must
- * lock even if the key is not found, to ensure sequential
- * consistency of updates.
- */
- private void scanAndLock(Object key, int hash) {
- // similar to but simpler than scanAndLockForPut
- HashEntry<K,V> first = entryForHash(this, hash);
- HashEntry<K,V> e = first;
- int retries = -1;
- while (!tryLock()) {
- HashEntry<K,V> f;
- if (retries < 0) {
- if (e == null || key.equals(e.key))
- retries = 0;
- else
- e = e.next;
- }
- else if (++retries > MAX_SCAN_RETRIES) {
- lock();
- break;
- }
- else if ((retries & 1) == 0 &&
- (f = entryForHash(this, hash)) != first) {
- e = first = f;
- retries = -1;
- }
- }
- }
+ /**
+ * The least available table index to split while resizing.
+ */
+ private transient volatile int transferOrigin;
- /**
- * Remove; match on key only if value null, else match both.
- */
- final V remove(Object key, int hash, Object value) {
- if (!tryLock())
- scanAndLock(key, hash);
- V oldValue = null;
- try {
- HashEntry<K,V>[] tab = table;
- int index = (tab.length - 1) & hash;
- HashEntry<K,V> e = entryAt(tab, index);
- HashEntry<K,V> pred = null;
- while (e != null) {
- K k;
- HashEntry<K,V> next = e.next;
- if ((k = e.key) == key ||
- (e.hash == hash && key.equals(k))) {
- V v = e.value;
- if (value == null || value == v || value.equals(v)) {
- if (pred == null)
- setEntryAt(tab, index, next);
- else
- pred.setNext(next);
- ++modCount;
- --count;
- oldValue = v;
- }
- break;
- }
- pred = e;
- e = next;
- }
- } finally {
- unlock();
- }
- return oldValue;
- }
+ /**
+ * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
+ */
+ private transient volatile int cellsBusy;
- final boolean replace(K key, int hash, V oldValue, V newValue) {
- if (!tryLock())
- scanAndLock(key, hash);
- boolean replaced = false;
- try {
- HashEntry<K,V> e;
- for (e = entryForHash(this, hash); e != null; e = e.next) {
- K k;
- if ((k = e.key) == key ||
- (e.hash == hash && key.equals(k))) {
- if (oldValue.equals(e.value)) {
- e.value = newValue;
- ++modCount;
- replaced = true;
- }
- break;
- }
- }
- } finally {
- unlock();
- }
- return replaced;
- }
+ /**
+ * Table of counter cells. When non-null, size is a power of 2.
+ */
+ private transient volatile CounterCell[] counterCells;
- final V replace(K key, int hash, V value) {
- if (!tryLock())
- scanAndLock(key, hash);
- V oldValue = null;
- try {
- HashEntry<K,V> e;
- for (e = entryForHash(this, hash); e != null; e = e.next) {
- K k;
- if ((k = e.key) == key ||
- (e.hash == hash && key.equals(k))) {
- oldValue = e.value;
- e.value = value;
- ++modCount;
- break;
- }
- }
- } finally {
- unlock();
- }
- return oldValue;
- }
+ // views
+ private transient KeySetView<K,V> keySet;
+ private transient ValuesView<K,V> values;
+ private transient EntrySetView<K,V> entrySet;
- final void clear() {
- lock();
- try {
- HashEntry<K,V>[] tab = table;
- for (int i = 0; i < tab.length ; i++)
- setEntryAt(tab, i, null);
- ++modCount;
- count = 0;
- } finally {
- unlock();
- }
- }
- }
- // Accessing segments
+ /* ---------------- Public operations -------------- */
/**
- * Gets the jth element of given segment array (if nonnull) with
- * volatile element access semantics via Unsafe. (The null check
- * can trigger harmlessly only during deserialization.) Note:
- * because each element of segments array is set only once (using
- * fully ordered writes), some performance-sensitive methods rely
- * on this method only as a recheck upon null reads.
+ * Creates a new, empty map with the default initial table size (16).
*/
- @SuppressWarnings("unchecked")
- static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
- long u = (j << SSHIFT) + SBASE;
- return ss == null ? null :
- (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
+ public ConcurrentHashMap() {
}
/**
- * Returns the segment for the given index, creating it and
- * recording in segment table (via CAS) if not already present.
+ * Creates a new, empty map with an initial table size
+ * accommodating the specified number of elements without the need
+ * to dynamically resize.
*
- * @param k the index
- * @return the segment
- */
- @SuppressWarnings("unchecked")
- private Segment<K,V> ensureSegment(int k) {
- final Segment<K,V>[] ss = this.segments;
- long u = (k << SSHIFT) + SBASE; // raw offset
- Segment<K,V> seg;
- if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
- Segment<K,V> proto = ss[0]; // use segment 0 as prototype
- int cap = proto.table.length;
- float lf = proto.loadFactor;
- int threshold = (int)(cap * lf);
- HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry<?,?>[cap];
- if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
- == null) { // recheck
- Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
- while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
- == null) {
- if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
- break;
- }
- }
- }
- return seg;
- }
-
- // Hash-based segment and entry accesses
-
- /**
- * Gets the segment for the given hash code.
+ * @param initialCapacity The implementation performs internal
+ * sizing to accommodate this many elements.
+ * @throws IllegalArgumentException if the initial capacity of
+ * elements is negative
*/
- @SuppressWarnings("unchecked")
- private Segment<K,V> segmentForHash(int h) {
- long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
- return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u);
+ public ConcurrentHashMap(int initialCapacity) {
+ if (initialCapacity < 0)
+ throw new IllegalArgumentException();
+ int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
+ MAXIMUM_CAPACITY :
+ tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
+ this.sizeCtl = cap;
}
/**
- * Gets the table entry for the given segment and hash code.
+ * Creates a new map with the same mappings as the given map.
+ *
+ * @param m the map
*/
- @SuppressWarnings("unchecked")
- static final <K,V> HashEntry<K,V> entryForHash(Segment<K,V> seg, int h) {
- HashEntry<K,V>[] tab;
- return (seg == null || (tab = seg.table) == null) ? null :
- (HashEntry<K,V>) UNSAFE.getObjectVolatile
- (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
+ public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
+ this.sizeCtl = DEFAULT_CAPACITY;
+ putAll(m);
}
- /* ---------------- Public operations -------------- */
-
/**
- * Creates a new, empty map with the specified initial
- * capacity, load factor and concurrency level.
+ * Creates a new, empty map with an initial table size based on
+ * the given number of elements ({@code initialCapacity}) and
+ * initial table density ({@code loadFactor}).
*
* @param initialCapacity the initial capacity. The implementation
- * performs internal sizing to accommodate this many elements.
- * @param loadFactor the load factor threshold, used to control resizing.
- * Resizing may be performed when the average number of elements per
- * bin exceeds this threshold.
- * @param concurrencyLevel the estimated number of concurrently
- * updating threads. The implementation performs internal sizing
- * to try to accommodate this many threads.
- * @throws IllegalArgumentException if the initial capacity is
- * negative or the load factor or concurrencyLevel are
- * nonpositive.
- */
- @SuppressWarnings("unchecked")
- public ConcurrentHashMap(int initialCapacity,
- float loadFactor, int concurrencyLevel) {
- if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
- throw new IllegalArgumentException();
- if (concurrencyLevel > MAX_SEGMENTS)
- concurrencyLevel = MAX_SEGMENTS;
- // Find power-of-two sizes best matching arguments
- int sshift = 0;
- int ssize = 1;
- while (ssize < concurrencyLevel) {
- ++sshift;
- ssize <<= 1;
- }
- this.segmentShift = 32 - sshift;
- this.segmentMask = ssize - 1;
- if (initialCapacity > MAXIMUM_CAPACITY)
- initialCapacity = MAXIMUM_CAPACITY;
- int c = initialCapacity / ssize;
- if (c * ssize < initialCapacity)
- ++c;
- int cap = MIN_SEGMENT_TABLE_CAPACITY;
- while (cap < c)
- cap <<= 1;
- // create segments and segments[0]
- Segment<K,V> s0 =
- new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
- (HashEntry<K,V>[])new HashEntry<?,?>[cap]);
- Segment<K,V>[] ss = (Segment<K,V>[])new Segment<?,?>[ssize];
- UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
- this.segments = ss;
- }
-
- /**
- * Creates a new, empty map with the specified initial capacity
- * and load factor and with the default concurrencyLevel (16).
- *
- * @param initialCapacity The implementation performs internal
- * sizing to accommodate this many elements.
- * @param loadFactor the load factor threshold, used to control resizing.
- * Resizing may be performed when the average number of elements per
- * bin exceeds this threshold.
+ * performs internal sizing to accommodate this many elements,
+ * given the specified load factor.
+ * @param loadFactor the load factor (table density) for
+ * establishing the initial table size
* @throws IllegalArgumentException if the initial capacity of
* elements is negative or the load factor is nonpositive
*
* @since 1.6
*/
public ConcurrentHashMap(int initialCapacity, float loadFactor) {
- this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
+ this(initialCapacity, loadFactor, 1);
}
/**
- * Creates a new, empty map with the specified initial capacity,
- * and with default load factor (0.75) and concurrencyLevel (16).
+ * Creates a new, empty map with an initial table size based on
+ * the given number of elements ({@code initialCapacity}), table
+ * density ({@code loadFactor}), and number of concurrently
+ * updating threads ({@code concurrencyLevel}).
*
* @param initialCapacity the initial capacity. The implementation
- * performs internal sizing to accommodate this many elements.
- * @throws IllegalArgumentException if the initial capacity of
- * elements is negative.
+ * performs internal sizing to accommodate this many elements,
+ * given the specified load factor.
+ * @param loadFactor the load factor (table density) for
+ * establishing the initial table size
+ * @param concurrencyLevel the estimated number of concurrently
+ * updating threads. The implementation may use this value as
+ * a sizing hint.
+ * @throws IllegalArgumentException if the initial capacity is
+ * negative or the load factor or concurrencyLevel are
+ * nonpositive
*/
- public ConcurrentHashMap(int initialCapacity) {
- this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
+ public ConcurrentHashMap(int initialCapacity,
+ float loadFactor, int concurrencyLevel) {
+ if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
+ throw new IllegalArgumentException();
+ if (initialCapacity < concurrencyLevel) // Use at least as many bins
+ initialCapacity = concurrencyLevel; // as estimated threads
+ long size = (long)(1.0 + (long)initialCapacity / loadFactor);
+ int cap = (size >= (long)MAXIMUM_CAPACITY) ?
+ MAXIMUM_CAPACITY : tableSizeFor((int)size);
+ this.sizeCtl = cap;
}
- /**
- * Creates a new, empty map with a default initial capacity (16),
- * load factor (0.75) and concurrencyLevel (16).
- */
- public ConcurrentHashMap() {
- this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
- }
+ // Original (since JDK1.2) Map methods
/**
- * Creates a new map with the same mappings as the given map.
- * The map is created with a capacity of 1.5 times the number
- * of mappings in the given map or 16 (whichever is greater),
- * and a default load factor (0.75) and concurrencyLevel (16).
- *
- * @param m the map
+ * {@inheritDoc}
*/
- public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
- this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
- DEFAULT_INITIAL_CAPACITY),
- DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
- putAll(m);
+ public int size() {
+ long n = sumCount();
+ return ((n < 0L) ? 0 :
+ (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
+ (int)n);
}
/**
- * Returns <tt>true</tt> if this map contains no key-value mappings.
- *
- * @return <tt>true</tt> if this map contains no key-value mappings
+ * {@inheritDoc}
*/
public boolean isEmpty() {
- /*
- * Sum per-segment modCounts to avoid mis-reporting when
- * elements are concurrently added and removed in one segment
- * while checking another, in which case the table was never
- * actually empty at any point. (The sum ensures accuracy up
- * through at least 1<<31 per-segment modifications before
- * recheck.) Methods size() and containsValue() use similar
- * constructions for stability checks.
- */
- long sum = 0L;
- final Segment<K,V>[] segments = this.segments;
- for (int j = 0; j < segments.length; ++j) {
- Segment<K,V> seg = segmentAt(segments, j);
- if (seg != null) {
- if (seg.count != 0)
- return false;
- sum += seg.modCount;
- }
- }
- if (sum != 0L) { // recheck unless no modifications
- for (int j = 0; j < segments.length; ++j) {
- Segment<K,V> seg = segmentAt(segments, j);
- if (seg != null) {
- if (seg.count != 0)
- return false;
- sum -= seg.modCount;
- }
- }
- if (sum != 0L)
- return false;
- }
- return true;
- }
-
- /**
- * Returns the number of key-value mappings in this map. If the
- * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
- * <tt>Integer.MAX_VALUE</tt>.
- *
- * @return the number of key-value mappings in this map
- */
- public int size() {
- // Try a few times to get accurate count. On failure due to
- // continuous async changes in table, resort to locking.
- final Segment<K,V>[] segments = this.segments;
- final int segmentCount = segments.length;
-
- long previousSum = 0L;
- for (int retries = -1; retries < RETRIES_BEFORE_LOCK; retries++) {
- long sum = 0L; // sum of modCounts
- long size = 0L;
- for (int i = 0; i < segmentCount; i++) {
- Segment<K,V> segment = segmentAt(segments, i);
- if (segment != null) {
- sum += segment.modCount;
- size += segment.count;
- }
- }
- if (sum == previousSum)
- return ((size >>> 31) == 0) ? (int) size : Integer.MAX_VALUE;
- previousSum = sum;
- }
-
- long size = 0L;
- for (int i = 0; i < segmentCount; i++) {
- Segment<K,V> segment = ensureSegment(i);
- segment.lock();
- size += segment.count;
- }
- for (int i = 0; i < segmentCount; i++)
- segments[i].unlock();
- return ((size >>> 31) == 0) ? (int) size : Integer.MAX_VALUE;
+ return sumCount() <= 0L; // ignore transient negative values
}
/**
@@ -878,18 +742,20 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* @throws NullPointerException if the specified key is null
*/
public V get(Object key) {
- Segment<K,V> s; // manually integrate access methods to reduce overhead
- HashEntry<K,V>[] tab;
- int h = hash(key.hashCode());
- long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
- if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
- (tab = s.table) != null) {
- for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
- (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
- e != null; e = e.next) {
- K k;
- if ((k = e.key) == key || (e.hash == h && key.equals(k)))
- return e.value;
+ Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
+ int h = spread(key.hashCode());
+ if ((tab = table) != null && (n = tab.length) > 0 &&
+ (e = tabAt(tab, (n - 1) & h)) != null) {
+ if ((eh = e.hash) == h) {
+ if ((ek = e.key) == key || (ek != null && key.equals(ek)))
+ return e.val;
+ }
+ else if (eh < 0)
+ return (p = e.find(h, key)) != null ? p.val : null;
+ while ((e = e.next) != null) {
+ if (e.hash == h &&
+ ((ek = e.key) == key || (ek != null && key.equals(ek))))
+ return e.val;
}
}
return null;
@@ -898,149 +764,121 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
/**
* Tests if the specified object is a key in this table.
*
- * @param key possible key
- * @return <tt>true</tt> if and only if the specified object
+ * @param key possible key
+ * @return {@code true} if and only if the specified object
* is a key in this table, as determined by the
- * <tt>equals</tt> method; <tt>false</tt> otherwise.
+ * {@code equals} method; {@code false} otherwise
* @throws NullPointerException if the specified key is null
*/
- @SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
- Segment<K,V> s; // same as get() except no need for volatile value read
- HashEntry<K,V>[] tab;
- int h = hash(key.hashCode());
- long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
- if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
- (tab = s.table) != null) {
- for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
- (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
- e != null; e = e.next) {
- K k;
- if ((k = e.key) == key || (e.hash == h && key.equals(k)))
- return true;
- }
- }
- return false;
+ return get(key) != null;
}
/**
- * Returns <tt>true</tt> if this map maps one or more keys to the
- * specified value. Note: This method requires a full internal
- * traversal of the hash table, and so is much slower than
- * method <tt>containsKey</tt>.
+ * Returns {@code true} if this map maps one or more keys to the
+ * specified value. Note: This method may require a full traversal
+ * of the map, and is much slower than method {@code containsKey}.
*
* @param value value whose presence in this map is to be tested
- * @return <tt>true</tt> if this map maps one or more keys to the
+ * @return {@code true} if this map maps one or more keys to the
* specified value
* @throws NullPointerException if the specified value is null
*/
public boolean containsValue(Object value) {
- // Same idea as size()
if (value == null)
throw new NullPointerException();
- final Segment<K,V>[] segments = this.segments;
- long previousSum = 0L;
- int lockCount = 0;
- try {
- for (int retries = -1; ; retries++) {
- long sum = 0L; // sum of modCounts
- for (int j = 0; j < segments.length; j++) {
- Segment<K,V> segment;
- if (retries == RETRIES_BEFORE_LOCK) {
- segment = ensureSegment(j);
- segment.lock();
- lockCount++;
- } else {
- segment = segmentAt(segments, j);
- if (segment == null)
- continue;
- }
- HashEntry<K,V>[] tab = segment.table;
- if (tab != null) {
- for (int i = 0 ; i < tab.length; i++) {
- HashEntry<K,V> e;
- for (e = entryAt(tab, i); e != null; e = e.next) {
- V v = e.value;
- if (v != null && value.equals(v))
- return true;
- }
- }
- sum += segment.modCount;
- }
- }
- if ((retries >= 0 && sum == previousSum) || lockCount > 0)
- return false;
- previousSum = sum;
+ Node<K,V>[] t;
+ if ((t = table) != null) {
+ Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+ for (Node<K,V> p; (p = it.advance()) != null; ) {
+ V v;
+ if ((v = p.val) == value || (v != null && value.equals(v)))
+ return true;
}
- } finally {
- for (int j = 0; j < lockCount; j++)
- segments[j].unlock();
}
- }
-
- /**
- * Legacy method testing if some key maps into the specified value
- * in this table. This method is identical in functionality to
- * {@link #containsValue}, and exists solely to ensure
- * full compatibility with class {@link java.util.Hashtable},
- * which supported this method prior to introduction of the
- * Java Collections framework.
- *
- * @param value a value to search for
- * @return <tt>true</tt> if and only if some key maps to the
- * <tt>value</tt> argument in this table as
- * determined by the <tt>equals</tt> method;
- * <tt>false</tt> otherwise
- * @throws NullPointerException if the specified value is null
- */
- public boolean contains(Object value) {
- return containsValue(value);
+ return false;
}
/**
* Maps the specified key to the specified value in this table.
* Neither the key nor the value can be null.
*
- * <p> The value can be retrieved by calling the <tt>get</tt> method
+ * <p>The value can be retrieved by calling the {@code get} method
* with a key that is equal to the original key.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
- * @return the previous value associated with <tt>key</tt>, or
- * <tt>null</tt> if there was no mapping for <tt>key</tt>
+ * @return the previous value associated with {@code key}, or
+ * {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key or value is null
*/
- @SuppressWarnings("unchecked")
public V put(K key, V value) {
- Segment<K,V> s;
- if (value == null)
- throw new NullPointerException();
- int hash = hash(key.hashCode());
- int j = (hash >>> segmentShift) & segmentMask;
- if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
- (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
- s = ensureSegment(j);
- return s.put(key, hash, value, false);
+ return putVal(key, value, false);
}
- /**
- * {@inheritDoc}
- *
- * @return the previous value associated with the specified key,
- * or <tt>null</tt> if there was no mapping for the key
- * @throws NullPointerException if the specified key or value is null
- */
- @SuppressWarnings("unchecked")
- public V putIfAbsent(K key, V value) {
- Segment<K,V> s;
- if (value == null)
- throw new NullPointerException();
- int hash = hash(key.hashCode());
- int j = (hash >>> segmentShift) & segmentMask;
- if ((s = (Segment<K,V>)UNSAFE.getObject
- (segments, (j << SSHIFT) + SBASE)) == null)
- s = ensureSegment(j);
- return s.put(key, hash, value, true);
+ /** Implementation for put and putIfAbsent */
+ final V putVal(K key, V value, boolean onlyIfAbsent) {
+ if (key == null || value == null) throw new NullPointerException();
+ int hash = spread(key.hashCode());
+ int binCount = 0;
+ for (Node<K,V>[] tab = table;;) {
+ Node<K,V> f; int n, i, fh;
+ if (tab == null || (n = tab.length) == 0)
+ tab = initTable();
+ else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
+ if (casTabAt(tab, i, null,
+ new Node<K,V>(hash, key, value, null)))
+ break; // no lock when adding to empty bin
+ }
+ else if ((fh = f.hash) == MOVED)
+ tab = helpTransfer(tab, f);
+ else {
+ V oldVal = null;
+ synchronized (f) {
+ if (tabAt(tab, i) == f) {
+ if (fh >= 0) {
+ binCount = 1;
+ for (Node<K,V> e = f;; ++binCount) {
+ K ek;
+ if (e.hash == hash &&
+ ((ek = e.key) == key ||
+ (ek != null && key.equals(ek)))) {
+ oldVal = e.val;
+ if (!onlyIfAbsent)
+ e.val = value;
+ break;
+ }
+ Node<K,V> pred = e;
+ if ((e = e.next) == null) {
+ pred.next = new Node<K,V>(hash, key,
+ value, null);
+ break;
+ }
+ }
+ }
+ else if (f instanceof TreeBin) {
+ Node<K,V> p;
+ binCount = 2;
+ if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
+ value)) != null) {
+ oldVal = p.val;
+ if (!onlyIfAbsent)
+ p.val = value;
+ }
+ }
+ }
+ }
+ if (binCount != 0) {
+ if (binCount >= TREEIFY_THRESHOLD)
+ treeifyBin(tab, i);
+ if (oldVal != null)
+ return oldVal;
+ break;
+ }
+ }
+ }
+ addCount(1L, binCount);
+ return null;
}
/**
@@ -1051,8 +889,9 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* @param m mappings to be stored in this map
*/
public void putAll(Map<? extends K, ? extends V> m) {
+ tryPresize(m.size());
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
- put(e.getKey(), e.getValue());
+ putVal(e.getKey(), e.getValue(), false);
}
/**
@@ -1060,87 +899,147 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* This method does nothing if the key is not in the map.
*
* @param key the key that needs to be removed
- * @return the previous value associated with <tt>key</tt>, or
- * <tt>null</tt> if there was no mapping for <tt>key</tt>
+ * @return the previous value associated with {@code key}, or
+ * {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key is null
*/
public V remove(Object key) {
- int hash = hash(key.hashCode());
- Segment<K,V> s = segmentForHash(hash);
- return s == null ? null : s.remove(key, hash, null);
- }
-
- /**
- * {@inheritDoc}
- *
- * @throws NullPointerException if the specified key is null
- */
- public boolean remove(Object key, Object value) {
- int hash = hash(key.hashCode());
- Segment<K,V> s;
- return value != null && (s = segmentForHash(hash)) != null &&
- s.remove(key, hash, value) != null;
- }
-
- /**
- * {@inheritDoc}
- *
- * @throws NullPointerException if any of the arguments are null
- */
- public boolean replace(K key, V oldValue, V newValue) {
- int hash = hash(key.hashCode());
- if (oldValue == null || newValue == null)
- throw new NullPointerException();
- Segment<K,V> s = segmentForHash(hash);
- return s != null && s.replace(key, hash, oldValue, newValue);
+ return replaceNode(key, null, null);
}
/**
- * {@inheritDoc}
- *
- * @return the previous value associated with the specified key,
- * or <tt>null</tt> if there was no mapping for the key
- * @throws NullPointerException if the specified key or value is null
+ * Implementation for the four public remove/replace methods:
+ * Replaces node value with v, conditional upon match of cv if
+ * non-null. If resulting value is null, delete.
*/
- public V replace(K key, V value) {
- int hash = hash(key.hashCode());
- if (value == null)
- throw new NullPointerException();
- Segment<K,V> s = segmentForHash(hash);
- return s == null ? null : s.replace(key, hash, value);
+ final V replaceNode(Object key, V value, Object cv) {
+ int hash = spread(key.hashCode());
+ for (Node<K,V>[] tab = table;;) {
+ Node<K,V> f; int n, i, fh;
+ if (tab == null || (n = tab.length) == 0 ||
+ (f = tabAt(tab, i = (n - 1) & hash)) == null)
+ break;
+ else if ((fh = f.hash) == MOVED)
+ tab = helpTransfer(tab, f);
+ else {
+ V oldVal = null;
+ boolean validated = false;
+ synchronized (f) {
+ if (tabAt(tab, i) == f) {
+ if (fh >= 0) {
+ validated = true;
+ for (Node<K,V> e = f, pred = null;;) {
+ K ek;
+ if (e.hash == hash &&
+ ((ek = e.key) == key ||
+ (ek != null && key.equals(ek)))) {
+ V ev = e.val;
+ if (cv == null || cv == ev ||
+ (ev != null && cv.equals(ev))) {
+ oldVal = ev;
+ if (value != null)
+ e.val = value;
+ else if (pred != null)
+ pred.next = e.next;
+ else
+ setTabAt(tab, i, e.next);
+ }
+ break;
+ }
+ pred = e;
+ if ((e = e.next) == null)
+ break;
+ }
+ }
+ else if (f instanceof TreeBin) {
+ validated = true;
+ TreeBin<K,V> t = (TreeBin<K,V>)f;
+ TreeNode<K,V> r, p;
+ if ((r = t.root) != null &&
+ (p = r.findTreeNode(hash, key, null)) != null) {
+ V pv = p.val;
+ if (cv == null || cv == pv ||
+ (pv != null && cv.equals(pv))) {
+ oldVal = pv;
+ if (value != null)
+ p.val = value;
+ else if (t.removeTreeNode(p))
+ setTabAt(tab, i, untreeify(t.first));
+ }
+ }
+ }
+ }
+ }
+ if (validated) {
+ if (oldVal != null) {
+ if (value == null)
+ addCount(-1L, -1);
+ return oldVal;
+ }
+ break;
+ }
+ }
+ }
+ return null;
}
/**
* Removes all of the mappings from this map.
*/
public void clear() {
- final Segment<K,V>[] segments = this.segments;
- for (int j = 0; j < segments.length; ++j) {
- Segment<K,V> s = segmentAt(segments, j);
- if (s != null)
- s.clear();
+ long delta = 0L; // negative number of deletions
+ int i = 0;
+ Node<K,V>[] tab = table;
+ while (tab != null && i < tab.length) {
+ int fh;
+ Node<K,V> f = tabAt(tab, i);
+ if (f == null)
+ ++i;
+ else if ((fh = f.hash) == MOVED) {
+ tab = helpTransfer(tab, f);
+ i = 0; // restart
+ }
+ else {
+ synchronized (f) {
+ if (tabAt(tab, i) == f) {
+ Node<K,V> p = (fh >= 0 ? f :
+ (f instanceof TreeBin) ?
+ ((TreeBin<K,V>)f).first : null);
+ while (p != null) {
+ --delta;
+ p = p.next;
+ }
+ setTabAt(tab, i++, null);
+ }
+ }
+ }
}
+ if (delta != 0L)
+ addCount(delta, -1);
}
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
- * reflected in the set, and vice-versa. The set supports element
+ * reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from this map,
- * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
- * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
- * operations. It does not support the <tt>add</tt> or
- * <tt>addAll</tt> operations.
+ * via the {@code Iterator.remove}, {@code Set.remove},
+ * {@code removeAll}, {@code retainAll}, and {@code clear}
+ * operations. It does not support the {@code add} or
+ * {@code addAll} operations.
*
- * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
+ * <p>The view's {@code iterator} is a "weakly consistent" iterator
* that will never throw {@link ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
+ *
+ * @return the set view
+ *
*/
public Set<K> keySet() {
- Set<K> ks = keySet;
- return (ks != null) ? ks : (keySet = new KeySet());
+ KeySetView<K,V> ks;
+ return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
}
/**
@@ -1148,20 +1047,22 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. The collection
* supports element removal, which removes the corresponding
- * mapping from this map, via the <tt>Iterator.remove</tt>,
- * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
- * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
- * support the <tt>add</tt> or <tt>addAll</tt> operations.
+ * mapping from this map, via the {@code Iterator.remove},
+ * {@code Collection.remove}, {@code removeAll},
+ * {@code retainAll}, and {@code clear} operations. It does not
+ * support the {@code add} or {@code addAll} operations.
*
- * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
+ * <p>The view's {@code iterator} is a "weakly consistent" iterator
* that will never throw {@link ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
+ *
+ * @return the collection view
*/
public Collection<V> values() {
- Collection<V> vs = values;
- return (vs != null) ? vs : (values = new Values());
+ ValuesView<K,V> vs;
+ return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
}
/**
@@ -1169,20 +1070,329 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from the map,
- * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
- * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
- * operations. It does not support the <tt>add</tt> or
- * <tt>addAll</tt> operations.
+ * via the {@code Iterator.remove}, {@code Set.remove},
+ * {@code removeAll}, {@code retainAll}, and {@code clear}
+ * operations.
*
- * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
+ * <p>The view's {@code iterator} is a "weakly consistent" iterator
* that will never throw {@link ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
+ *
+ * @return the set view
*/
public Set<Map.Entry<K,V>> entrySet() {
- Set<Map.Entry<K,V>> es = entrySet;
- return (es != null) ? es : (entrySet = new EntrySet());
+ EntrySetView<K,V> es;
+ return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
+ }
+
+ /**
+ * Returns the hash code value for this {@link Map}, i.e.,
+ * the sum of, for each key-value pair in the map,
+ * {@code key.hashCode() ^ value.hashCode()}.
+ *
+ * @return the hash code value for this map
+ */
+ public int hashCode() {
+ int h = 0;
+ Node<K,V>[] t;
+ if ((t = table) != null) {
+ Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+ for (Node<K,V> p; (p = it.advance()) != null; )
+ h += p.key.hashCode() ^ p.val.hashCode();
+ }
+ return h;
+ }
+
+ /**
+ * Returns a string representation of this map. The string
+ * representation consists of a list of key-value mappings (in no
+ * particular order) enclosed in braces ("{@code {}}"). Adjacent
+ * mappings are separated by the characters {@code ", "} (comma
+ * and space). Each key-value mapping is rendered as the key
+ * followed by an equals sign ("{@code =}") followed by the
+ * associated value.
+ *
+ * @return a string representation of this map
+ */
+ public String toString() {
+ Node<K,V>[] t;
+ int f = (t = table) == null ? 0 : t.length;
+ Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
+ StringBuilder sb = new StringBuilder();
+ sb.append('{');
+ Node<K,V> p;
+ if ((p = it.advance()) != null) {
+ for (;;) {
+ K k = p.key;
+ V v = p.val;
+ sb.append(k == this ? "(this Map)" : k);
+ sb.append('=');
+ sb.append(v == this ? "(this Map)" : v);
+ if ((p = it.advance()) == null)
+ break;
+ sb.append(',').append(' ');
+ }
+ }
+ return sb.append('}').toString();
+ }
+
+ /**
+ * Compares the specified object with this map for equality.
+ * Returns {@code true} if the given object is a map with the same
+ * mappings as this map. This operation may return misleading
+ * results if either map is concurrently modified during execution
+ * of this method.
+ *
+ * @param o object to be compared for equality with this map
+ * @return {@code true} if the specified object is equal to this map
+ */
+ public boolean equals(Object o) {
+ if (o != this) {
+ if (!(o instanceof Map))
+ return false;
+ Map<?,?> m = (Map<?,?>) o;
+ Node<K,V>[] t;
+ int f = (t = table) == null ? 0 : t.length;
+ Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
+ for (Node<K,V> p; (p = it.advance()) != null; ) {
+ V val = p.val;
+ Object v = m.get(p.key);
+ if (v == null || (v != val && !v.equals(val)))
+ return false;
+ }
+ for (Map.Entry<?,?> e : m.entrySet()) {
+ Object mk, mv, v;
+ if ((mk = e.getKey()) == null ||
+ (mv = e.getValue()) == null ||
+ (v = get(mk)) == null ||
+ (mv != v && !mv.equals(v)))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Stripped-down version of helper class used in previous version,
+ * declared for the sake of serialization compatibility
+ */
+ static class Segment<K,V> extends ReentrantLock implements Serializable {
+ private static final long serialVersionUID = 2249069246763182397L;
+ final float loadFactor;
+ Segment(float lf) { this.loadFactor = lf; }
+ }
+
+ /**
+ * Saves the state of the {@code ConcurrentHashMap} instance to a
+ * stream (i.e., serializes it).
+ * @param s the stream
+ * @serialData
+ * the key (Object) and value (Object)
+ * for each key-value mapping, followed by a null pair.
+ * The key-value mappings are emitted in no particular order.
+ */
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws java.io.IOException {
+ // For serialization compatibility
+ // Emulate segment calculation from previous version of this class
+ int sshift = 0;
+ int ssize = 1;
+ while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
+ ++sshift;
+ ssize <<= 1;
+ }
+ int segmentShift = 32 - sshift;
+ int segmentMask = ssize - 1;
+ @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
+ new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
+ for (int i = 0; i < segments.length; ++i)
+ segments[i] = new Segment<K,V>(LOAD_FACTOR);
+ s.putFields().put("segments", segments);
+ s.putFields().put("segmentShift", segmentShift);
+ s.putFields().put("segmentMask", segmentMask);
+ s.writeFields();
+
+ Node<K,V>[] t;
+ if ((t = table) != null) {
+ Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+ for (Node<K,V> p; (p = it.advance()) != null; ) {
+ s.writeObject(p.key);
+ s.writeObject(p.val);
+ }
+ }
+ s.writeObject(null);
+ s.writeObject(null);
+ segments = null; // throw away
+ }
+
+ /**
+ * Reconstitutes the instance from a stream (that is, deserializes it).
+ * @param s the stream
+ */
+ private void readObject(java.io.ObjectInputStream s)
+ throws java.io.IOException, ClassNotFoundException {
+ /*
+ * To improve performance in typical cases, we create nodes
+ * while reading, then place in table once size is known.
+ * However, we must also validate uniqueness and deal with
+ * overpopulated bins while doing so, which requires
+ * specialized versions of putVal mechanics.
+ */
+ sizeCtl = -1; // force exclusion for table construction
+ s.defaultReadObject();
+ long size = 0L;
+ Node<K,V> p = null;
+ for (;;) {
+ @SuppressWarnings("unchecked") K k = (K) s.readObject();
+ @SuppressWarnings("unchecked") V v = (V) s.readObject();
+ if (k != null && v != null) {
+ p = new Node<K,V>(spread(k.hashCode()), k, v, p);
+ ++size;
+ }
+ else
+ break;
+ }
+ if (size == 0L)
+ sizeCtl = 0;
+ else {
+ int n;
+ if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
+ n = MAXIMUM_CAPACITY;
+ else {
+ int sz = (int)size;
+ n = tableSizeFor(sz + (sz >>> 1) + 1);
+ }
+ @SuppressWarnings({"rawtypes","unchecked"})
+ Node<K,V>[] tab = (Node<K,V>[])new Node[n];
+ int mask = n - 1;
+ long added = 0L;
+ while (p != null) {
+ boolean insertAtFront;
+ Node<K,V> next = p.next, first;
+ int h = p.hash, j = h & mask;
+ if ((first = tabAt(tab, j)) == null)
+ insertAtFront = true;
+ else {
+ K k = p.key;
+ if (first.hash < 0) {
+ TreeBin<K,V> t = (TreeBin<K,V>)first;
+ if (t.putTreeVal(h, k, p.val) == null)
+ ++added;
+ insertAtFront = false;
+ }
+ else {
+ int binCount = 0;
+ insertAtFront = true;
+ Node<K,V> q; K qk;
+ for (q = first; q != null; q = q.next) {
+ if (q.hash == h &&
+ ((qk = q.key) == k ||
+ (qk != null && k.equals(qk)))) {
+ insertAtFront = false;
+ break;
+ }
+ ++binCount;
+ }
+ if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
+ insertAtFront = false;
+ ++added;
+ p.next = first;
+ TreeNode<K,V> hd = null, tl = null;
+ for (q = p; q != null; q = q.next) {
+ TreeNode<K,V> t = new TreeNode<K,V>
+ (q.hash, q.key, q.val, null, null);
+ if ((t.prev = tl) == null)
+ hd = t;
+ else
+ tl.next = t;
+ tl = t;
+ }
+ setTabAt(tab, j, new TreeBin<K,V>(hd));
+ }
+ }
+ }
+ if (insertAtFront) {
+ ++added;
+ p.next = first;
+ setTabAt(tab, j, p);
+ }
+ p = next;
+ }
+ table = tab;
+ sizeCtl = n - (n >>> 2);
+ baseCount = added;
+ }
+ }
+
+ // ConcurrentMap methods
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return the previous value associated with the specified key,
+ * or {@code null} if there was no mapping for the key
+ * @throws NullPointerException if the specified key or value is null
+ */
+ public V putIfAbsent(K key, V value) {
+ return putVal(key, value, true);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws NullPointerException if the specified key is null
+ */
+ public boolean remove(Object key, Object value) {
+ if (key == null)
+ throw new NullPointerException();
+ return value != null && replaceNode(key, null, value) != null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws NullPointerException if any of the arguments are null
+ */
+ public boolean replace(K key, V oldValue, V newValue) {
+ if (key == null || oldValue == null || newValue == null)
+ throw new NullPointerException();
+ return replaceNode(key, newValue, oldValue) != null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return the previous value associated with the specified key,
+ * or {@code null} if there was no mapping for the key
+ * @throws NullPointerException if the specified key or value is null
+ */
+ public V replace(K key, V value) {
+ if (key == null || value == null)
+ throw new NullPointerException();
+ return replaceNode(key, value, null);
+ }
+ // Hashtable legacy methods
+
+ /**
+ * Legacy method testing if some key maps into the specified value
+ * in this table. This method is identical in functionality to
+ * {@link #containsValue(Object)}, and exists solely to ensure
+ * full compatibility with class {@link java.util.Hashtable}.
+ *
+ * @param value a value to search for
+ * @return {@code true} if and only if some key maps to the
+ * {@code value} argument in this table as
+ * determined by the {@code equals} method;
+ * {@code false} otherwise
+ * @throws NullPointerException if the specified value is null
+ */
+ public boolean contains(Object value) {
+ // BEGIN android-note
+ // removed deprecation
+ // END android-note
+ return containsValue(value);
}
/**
@@ -1192,7 +1402,9 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* @see #keySet()
*/
public Enumeration<K> keys() {
- return new KeyIterator();
+ Node<K,V>[] t;
+ int f = (t = table) == null ? 0 : t.length;
+ return new KeyIterator<K,V>(t, f, 0, f, this);
}
/**
@@ -1202,281 +1414,1787 @@ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
* @see #values()
*/
public Enumeration<V> elements() {
- return new ValueIterator();
+ Node<K,V>[] t;
+ int f = (t = table) == null ? 0 : t.length;
+ return new ValueIterator<K,V>(t, f, 0, f, this);
}
- /* ---------------- Iterator Support -------------- */
+ // ConcurrentHashMap-only methods
- abstract class HashIterator {
- int nextSegmentIndex;
- int nextTableIndex;
- HashEntry<K,V>[] currentTable;
- HashEntry<K, V> nextEntry;
- HashEntry<K, V> lastReturned;
+ /**
+ * Returns the number of mappings. This method should be used
+ * instead of {@link #size} because a ConcurrentHashMap may
+ * contain more mappings than can be represented as an int. The
+ * value returned is an estimate; the actual count may differ if
+ * there are concurrent insertions or removals.
+ *
+ * @return the number of mappings
+ * @since 1.8
+ *
+ * @hide
+ */
+ public long mappingCount() {
+ long n = sumCount();
+ return (n < 0L) ? 0L : n; // ignore transient negative values
+ }
- HashIterator() {
- nextSegmentIndex = segments.length - 1;
- nextTableIndex = -1;
- advance();
+ /**
+ * Creates a new {@link Set} backed by a ConcurrentHashMap
+ * from the given type to {@code Boolean.TRUE}.
+ *
+ * @return the new set
+ * @since 1.8
+ *
+ * @hide
+ */
+ public static <K> KeySetView<K,Boolean> newKeySet() {
+ return new KeySetView<K,Boolean>
+ (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
+ }
+
+ /**
+ * Creates a new {@link Set} backed by a ConcurrentHashMap
+ * from the given type to {@code Boolean.TRUE}.
+ *
+ * @param initialCapacity The implementation performs internal
+ * sizing to accommodate this many elements.
+ * @throws IllegalArgumentException if the initial capacity of
+ * elements is negative
+ * @return the new set
+ * @since 1.8
+ *
+ * @hide
+ */
+ public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
+ return new KeySetView<K,Boolean>
+ (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
+ }
+
+ /**
+ * Returns a {@link Set} view of the keys in this map, using the
+ * given common mapped value for any additions (i.e., {@link
+ * Collection#add} and {@link Collection#addAll(Collection)}).
+ * This is of course only appropriate if it is acceptable to use
+ * the same value for all additions from this view.
+ *
+ * @param mappedValue the mapped value to use for any additions
+ * @return the set view
+ * @throws NullPointerException if the mappedValue is null
+ *
+ * @hide
+ */
+ public Set<K> keySet(V mappedValue) {
+ if (mappedValue == null)
+ throw new NullPointerException();
+ return new KeySetView<K,V>(this, mappedValue);
+ }
+
+ /* ---------------- Special Nodes -------------- */
+
+ /**
+ * A node inserted at head of bins during transfer operations.
+ */
+ static final class ForwardingNode<K,V> extends Node<K,V> {
+ final Node<K,V>[] nextTable;
+ ForwardingNode(Node<K,V>[] tab) {
+ super(MOVED, null, null, null);
+ this.nextTable = tab;
+ }
+
+ Node<K,V> find(int h, Object k) {
+ Node<K,V> e; int n;
+ Node<K,V>[] tab = nextTable;
+ if (k != null && tab != null && (n = tab.length) > 0 &&
+ (e = tabAt(tab, (n - 1) & h)) != null) {
+ do {
+ int eh; K ek;
+ if ((eh = e.hash) == h &&
+ ((ek = e.key) == k || (ek != null && k.equals(ek))))
+ return e;
+ if (eh < 0)
+ return e.find(h, k);
+ } while ((e = e.next) != null);
+ }
+ return null;
+ }
+ }
+
+ /**
+ * A place-holder node used in computeIfAbsent and compute
+ */
+ static final class ReservationNode<K,V> extends Node<K,V> {
+ ReservationNode() {
+ super(RESERVED, null, null, null);
+ }
+
+ Node<K,V> find(int h, Object k) {
+ return null;
+ }
+ }
+
+ /* ---------------- Table Initialization and Resizing -------------- */
+
+ /**
+ * Initializes table, using the size recorded in sizeCtl.
+ */
+ private final Node<K,V>[] initTable() {
+ Node<K,V>[] tab; int sc;
+ while ((tab = table) == null || tab.length == 0) {
+ if ((sc = sizeCtl) < 0)
+ Thread.yield(); // lost initialization race; just spin
+ else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
+ try {
+ if ((tab = table) == null || tab.length == 0) {
+ int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
+ @SuppressWarnings({"rawtypes","unchecked"})
+ Node<K,V>[] nt = (Node<K,V>[])new Node[n];
+ table = tab = nt;
+ sc = n - (n >>> 2);
+ }
+ } finally {
+ sizeCtl = sc;
+ }
+ break;
+ }
+ }
+ return tab;
+ }
+
+ /**
+ * Adds to count, and if table is too small and not already
+ * resizing, initiates transfer. If already resizing, helps
+ * perform transfer if work is available. Rechecks occupancy
+ * after a transfer to see if another resize is already needed
+ * because resizings are lagging additions.
+ *
+ * @param x the count to add
+ * @param check if <0, don't check resize, if <= 1 only check if uncontended
+ */
+ private final void addCount(long x, int check) {
+ CounterCell[] as; long b, s;
+ if ((as = counterCells) != null ||
+ !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
+ CounterHashCode hc; CounterCell a; long v; int m;
+ boolean uncontended = true;
+ if ((hc = threadCounterHashCode.get()) == null ||
+ as == null || (m = as.length - 1) < 0 ||
+ (a = as[m & hc.code]) == null ||
+ !(uncontended =
+ U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
+ fullAddCount(x, hc, uncontended);
+ return;
+ }
+ if (check <= 1)
+ return;
+ s = sumCount();
+ }
+ if (check >= 0) {
+ Node<K,V>[] tab, nt; int sc;
+ while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
+ tab.length < MAXIMUM_CAPACITY) {
+ if (sc < 0) {
+ if (sc == -1 || transferIndex <= transferOrigin ||
+ (nt = nextTable) == null)
+ break;
+ if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
+ transfer(tab, nt);
+ }
+ else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
+ transfer(tab, null);
+ s = sumCount();
+ }
+ }
+ }
+
+ /**
+ * Helps transfer if a resize is in progress.
+ */
+ final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
+ Node<K,V>[] nextTab; int sc;
+ if ((f instanceof ForwardingNode) &&
+ (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
+ if (nextTab == nextTable && tab == table &&
+ transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
+ U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
+ transfer(tab, nextTab);
+ return nextTab;
+ }
+ return table;
+ }
+
+ /**
+ * Tries to presize table to accommodate the given number of elements.
+ *
+ * @param size number of elements (doesn't need to be perfectly accurate)
+ */
+ private final void tryPresize(int size) {
+ int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
+ tableSizeFor(size + (size >>> 1) + 1);
+ int sc;
+ while ((sc = sizeCtl) >= 0) {
+ Node<K,V>[] tab = table; int n;
+ if (tab == null || (n = tab.length) == 0) {
+ n = (sc > c) ? sc : c;
+ if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
+ try {
+ if (table == tab) {
+ @SuppressWarnings({"rawtypes","unchecked"})
+ Node<K,V>[] nt = (Node<K,V>[])new Node[n];
+ table = nt;
+ sc = n - (n >>> 2);
+ }
+ } finally {
+ sizeCtl = sc;
+ }
+ }
+ }
+ else if (c <= sc || n >= MAXIMUM_CAPACITY)
+ break;
+ else if (tab == table &&
+ U.compareAndSwapInt(this, SIZECTL, sc, -2))
+ transfer(tab, null);
+ }
+ }
+
+ /**
+ * Moves and/or copies the nodes in each bin to new table. See
+ * above for explanation.
+ */
+ private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
+ int n = tab.length, stride;
+ if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
+ stride = MIN_TRANSFER_STRIDE; // subdivide range
+ if (nextTab == null) { // initiating
+ try {
+ @SuppressWarnings({"rawtypes","unchecked"})
+ Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
+ nextTab = nt;
+ } catch (Throwable ex) { // try to cope with OOME
+ sizeCtl = Integer.MAX_VALUE;
+ return;
+ }
+ nextTable = nextTab;
+ transferOrigin = n;
+ transferIndex = n;
+ ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
+ for (int k = n; k > 0;) { // progressively reveal ready slots
+ int nextk = (k > stride) ? k - stride : 0;
+ for (int m = nextk; m < k; ++m)
+ nextTab[m] = rev;
+ for (int m = n + nextk; m < n + k; ++m)
+ nextTab[m] = rev;
+ U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
+ }
+ }
+ int nextn = nextTab.length;
+ ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
+ boolean advance = true;
+ for (int i = 0, bound = 0;;) {
+ int nextIndex, nextBound, fh; Node<K,V> f;
+ while (advance) {
+ if (--i >= bound)
+ advance = false;
+ else if ((nextIndex = transferIndex) <= transferOrigin) {
+ i = -1;
+ advance = false;
+ }
+ else if (U.compareAndSwapInt
+ (this, TRANSFERINDEX, nextIndex,
+ nextBound = (nextIndex > stride ?
+ nextIndex - stride : 0))) {
+ bound = nextBound;
+ i = nextIndex - 1;
+ advance = false;
+ }
+ }
+ if (i < 0 || i >= n || i + n >= nextn) {
+ for (int sc;;) {
+ if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
+ if (sc == -1) {
+ nextTable = null;
+ table = nextTab;
+ sizeCtl = (n << 1) - (n >>> 1);
+ }
+ return;
+ }
+ }
+ }
+ else if ((f = tabAt(tab, i)) == null) {
+ if (casTabAt(tab, i, null, fwd)) {
+ setTabAt(nextTab, i, null);
+ setTabAt(nextTab, i + n, null);
+ advance = true;
+ }
+ }
+ else if ((fh = f.hash) == MOVED)
+ advance = true; // already processed
+ else {
+ synchronized (f) {
+ if (tabAt(tab, i) == f) {
+ Node<K,V> ln, hn;
+ if (fh >= 0) {
+ int runBit = fh & n;
+ Node<K,V> lastRun = f;
+ for (Node<K,V> p = f.next; p != null; p = p.next) {
+ int b = p.hash & n;
+ if (b != runBit) {
+ runBit = b;
+ lastRun = p;
+ }
+ }
+ if (runBit == 0) {
+ ln = lastRun;
+ hn = null;
+ }
+ else {
+ hn = lastRun;
+ ln = null;
+ }
+ for (Node<K,V> p = f; p != lastRun; p = p.next) {
+ int ph = p.hash; K pk = p.key; V pv = p.val;
+ if ((ph & n) == 0)
+ ln = new Node<K,V>(ph, pk, pv, ln);
+ else
+ hn = new Node<K,V>(ph, pk, pv, hn);
+ }
+ }
+ else if (f instanceof TreeBin) {
+ TreeBin<K,V> t = (TreeBin<K,V>)f;
+ TreeNode<K,V> lo = null, loTail = null;
+ TreeNode<K,V> hi = null, hiTail = null;
+ int lc = 0, hc = 0;
+ for (Node<K,V> e = t.first; e != null; e = e.next) {
+ int h = e.hash;
+ TreeNode<K,V> p = new TreeNode<K,V>
+ (h, e.key, e.val, null, null);
+ if ((h & n) == 0) {
+ if ((p.prev = loTail) == null)
+ lo = p;
+ else
+ loTail.next = p;
+ loTail = p;
+ ++lc;
+ }
+ else {
+ if ((p.prev = hiTail) == null)
+ hi = p;
+ else
+ hiTail.next = p;
+ hiTail = p;
+ ++hc;
+ }
+ }
+ ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
+ (hc != 0) ? new TreeBin<K,V>(lo) : t;
+ hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
+ (lc != 0) ? new TreeBin<K,V>(hi) : t;
+ }
+ else
+ ln = hn = null;
+ setTabAt(nextTab, i, ln);
+ setTabAt(nextTab, i + n, hn);
+ setTabAt(tab, i, fwd);
+ advance = true;
+ }
+ }
+ }
+ }
+ }
+
+ /* ---------------- Conversion from/to TreeBins -------------- */
+
+ /**
+ * Replaces all linked nodes in bin at given index unless table is
+ * too small, in which case resizes instead.
+ */
+ private final void treeifyBin(Node<K,V>[] tab, int index) {
+ Node<K,V> b; int n, sc;
+ if (tab != null) {
+ if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
+ if (tab == table && (sc = sizeCtl) >= 0 &&
+ U.compareAndSwapInt(this, SIZECTL, sc, -2))
+ transfer(tab, null);
+ }
+ else if ((b = tabAt(tab, index)) != null) {
+ synchronized (b) {
+ if (tabAt(tab, index) == b) {
+ TreeNode<K,V> hd = null, tl = null;
+ for (Node<K,V> e = b; e != null; e = e.next) {
+ TreeNode<K,V> p =
+ new TreeNode<K,V>(e.hash, e.key, e.val,
+ null, null);
+ if ((p.prev = tl) == null)
+ hd = p;
+ else
+ tl.next = p;
+ tl = p;
+ }
+ setTabAt(tab, index, new TreeBin<K,V>(hd));
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns a list on non-TreeNodes replacing those in given list.
+ */
+ static <K,V> Node<K,V> untreeify(Node<K,V> b) {
+ Node<K,V> hd = null, tl = null;
+ for (Node<K,V> q = b; q != null; q = q.next) {
+ Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
+ if (tl == null)
+ hd = p;
+ else
+ tl.next = p;
+ tl = p;
+ }
+ return hd;
+ }
+
+ /* ---------------- TreeNodes -------------- */
+
+ /**
+ * Nodes for use in TreeBins
+ */
+ static final class TreeNode<K,V> extends Node<K,V> {
+ TreeNode<K,V> parent; // red-black tree links
+ TreeNode<K,V> left;
+ TreeNode<K,V> right;
+ TreeNode<K,V> prev; // needed to unlink next upon deletion
+ boolean red;
+
+ TreeNode(int hash, K key, V val, Node<K,V> next,
+ TreeNode<K,V> parent) {
+ super(hash, key, val, next);
+ this.parent = parent;
+ }
+
+ Node<K,V> find(int h, Object k) {
+ return findTreeNode(h, k, null);
}
/**
- * Sets nextEntry to first node of next non-empty table
- * (in backwards order, to simplify checks).
+ * Returns the TreeNode (or null if not found) for the given key
+ * starting at given root.
*/
- final void advance() {
- for (;;) {
- if (nextTableIndex >= 0) {
- if ((nextEntry = entryAt(currentTable,
- nextTableIndex--)) != null)
+ final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
+ if (k != null) {
+ TreeNode<K,V> p = this;
+ do {
+ int ph, dir; K pk; TreeNode<K,V> q;
+ TreeNode<K,V> pl = p.left, pr = p.right;
+ if ((ph = p.hash) > h)
+ p = pl;
+ else if (ph < h)
+ p = pr;
+ else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
+ return p;
+ else if (pl == null && pr == null)
break;
+ else if ((kc != null ||
+ (kc = comparableClassFor(k)) != null) &&
+ (dir = compareComparables(kc, k, pk)) != 0)
+ p = (dir < 0) ? pl : pr;
+ else if (pl == null)
+ p = pr;
+ else if (pr == null ||
+ (q = pr.findTreeNode(h, k, kc)) == null)
+ p = pl;
+ else
+ return q;
+ } while (p != null);
+ }
+ return null;
+ }
+ }
+
+ /* ---------------- TreeBins -------------- */
+
+ /**
+ * TreeNodes used at the heads of bins. TreeBins do not hold user
+ * keys or values, but instead point to list of TreeNodes and
+ * their root. They also maintain a parasitic read-write lock
+ * forcing writers (who hold bin lock) to wait for readers (who do
+ * not) to complete before tree restructuring operations.
+ */
+ static final class TreeBin<K,V> extends Node<K,V> {
+ TreeNode<K,V> root;
+ volatile TreeNode<K,V> first;
+ volatile Thread waiter;
+ volatile int lockState;
+ // values for lockState
+ static final int WRITER = 1; // set while holding write lock
+ static final int WAITER = 2; // set when waiting for write lock
+ static final int READER = 4; // increment value for setting read lock
+
+ /**
+ * Creates bin with initial set of nodes headed by b.
+ */
+ TreeBin(TreeNode<K,V> b) {
+ super(TREEBIN, null, null, null);
+ this.first = b;
+ TreeNode<K,V> r = null;
+ for (TreeNode<K,V> x = b, next; x != null; x = next) {
+ next = (TreeNode<K,V>)x.next;
+ x.left = x.right = null;
+ if (r == null) {
+ x.parent = null;
+ x.red = false;
+ r = x;
}
- else if (nextSegmentIndex >= 0) {
- Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
- if (seg != null && (currentTable = seg.table) != null)
- nextTableIndex = currentTable.length - 1;
+ else {
+ Object key = x.key;
+ int hash = x.hash;
+ Class<?> kc = null;
+ for (TreeNode<K,V> p = r;;) {
+ int dir, ph;
+ if ((ph = p.hash) > hash)
+ dir = -1;
+ else if (ph < hash)
+ dir = 1;
+ else if ((kc != null ||
+ (kc = comparableClassFor(key)) != null))
+ dir = compareComparables(kc, key, p.key);
+ else
+ dir = 0;
+ TreeNode<K,V> xp = p;
+ if ((p = (dir <= 0) ? p.left : p.right) == null) {
+ x.parent = xp;
+ if (dir <= 0)
+ xp.left = x;
+ else
+ xp.right = x;
+ r = balanceInsertion(r, x);
+ break;
+ }
+ }
}
- else
+ }
+ this.root = r;
+ }
+
+ /**
+ * Acquires write lock for tree restructuring.
+ */
+ private final void lockRoot() {
+ if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
+ contendedLock(); // offload to separate method
+ }
+
+ /**
+ * Releases write lock for tree restructuring.
+ */
+ private final void unlockRoot() {
+ lockState = 0;
+ }
+
+ /**
+ * Possibly blocks awaiting root lock.
+ */
+ private final void contendedLock() {
+ boolean waiting = false;
+ for (int s;;) {
+ if (((s = lockState) & WRITER) == 0) {
+ if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
+ if (waiting)
+ waiter = null;
+ return;
+ }
+ }
+ else if ((s & WAITER) == 0) {
+ if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
+ waiting = true;
+ waiter = Thread.currentThread();
+ }
+ }
+ else if (waiting)
+ LockSupport.park(this);
+ }
+ }
+
+ /**
+ * Returns matching node or null if none. Tries to search
+ * using tree comparisons from root, but continues linear
+ * search when lock not available.
+ */
+ final Node<K,V> find(int h, Object k) {
+ if (k != null) {
+ for (Node<K,V> e = first; e != null; e = e.next) {
+ int s; K ek;
+ if (((s = lockState) & (WAITER|WRITER)) != 0) {
+ if (e.hash == h &&
+ ((ek = e.key) == k || (ek != null && k.equals(ek))))
+ return e;
+ }
+ else if (U.compareAndSwapInt(this, LOCKSTATE, s,
+ s + READER)) {
+ TreeNode<K,V> r, p;
+ try {
+ p = ((r = root) == null ? null :
+ r.findTreeNode(h, k, null));
+ } finally {
+
+ Thread w;
+ int ls;
+ do {} while (!U.compareAndSwapInt
+ (this, LOCKSTATE,
+ ls = lockState, ls - READER));
+ if (ls == (READER|WAITER) && (w = waiter) != null)
+ LockSupport.unpark(w);
+ }
+ return p;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds or adds a node.
+ * @return null if added
+ */
+ final TreeNode<K,V> putTreeVal(int h, K k, V v) {
+ Class<?> kc = null;
+ for (TreeNode<K,V> p = root;;) {
+ int dir, ph; K pk; TreeNode<K,V> q, pr;
+ if (p == null) {
+ first = root = new TreeNode<K,V>(h, k, v, null, null);
+ break;
+ }
+ else if ((ph = p.hash) > h)
+ dir = -1;
+ else if (ph < h)
+ dir = 1;
+ else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
+ return p;
+ else if ((kc == null &&
+ (kc = comparableClassFor(k)) == null) ||
+ (dir = compareComparables(kc, k, pk)) == 0) {
+ if (p.left == null)
+ dir = 1;
+ else if ((pr = p.right) == null ||
+ (q = pr.findTreeNode(h, k, kc)) == null)
+ dir = -1;
+ else
+ return q;
+ }
+ TreeNode<K,V> xp = p;
+ if ((p = (dir < 0) ? p.left : p.right) == null) {
+ TreeNode<K,V> x, f = first;
+ first = x = new TreeNode<K,V>(h, k, v, f, xp);
+ if (f != null)
+ f.prev = x;
+ if (dir < 0)
+ xp.left = x;
+ else
+ xp.right = x;
+ if (!xp.red)
+ x.red = true;
+ else {
+ lockRoot();
+ try {
+ root = balanceInsertion(root, x);
+ } finally {
+ unlockRoot();
+ }
+ }
break;
+ }
}
+ assert checkInvariants(root);
+ return null;
}
- final HashEntry<K,V> nextEntry() {
- HashEntry<K,V> e = nextEntry;
- if (e == null)
- throw new NoSuchElementException();
- lastReturned = e; // cannot assign until after null check
- if ((nextEntry = e.next) == null)
- advance();
- return e;
+ /**
+ * Removes the given node, that must be present before this
+ * call. This is messier than typical red-black deletion code
+ * because we cannot swap the contents of an interior node
+ * with a leaf successor that is pinned by "next" pointers
+ * that are accessible independently of lock. So instead we
+ * swap the tree linkages.
+ *
+ * @return true if now too small, so should be untreeified
+ */
+ final boolean removeTreeNode(TreeNode<K,V> p) {
+ TreeNode<K,V> next = (TreeNode<K,V>)p.next;
+ TreeNode<K,V> pred = p.prev; // unlink traversal pointers
+ TreeNode<K,V> r, rl;
+ if (pred == null)
+ first = next;
+ else
+ pred.next = next;
+ if (next != null)
+ next.prev = pred;
+ if (first == null) {
+ root = null;
+ return true;
+ }
+ if ((r = root) == null || r.right == null || // too small
+ (rl = r.left) == null || rl.left == null)
+ return true;
+ lockRoot();
+ try {
+ TreeNode<K,V> replacement;
+ TreeNode<K,V> pl = p.left;
+ TreeNode<K,V> pr = p.right;
+ if (pl != null && pr != null) {
+ TreeNode<K,V> s = pr, sl;
+ while ((sl = s.left) != null) // find successor
+ s = sl;
+ boolean c = s.red; s.red = p.red; p.red = c; // swap colors
+ TreeNode<K,V> sr = s.right;
+ TreeNode<K,V> pp = p.parent;
+ if (s == pr) { // p was s's direct parent
+ p.parent = s;
+ s.right = p;
+ }
+ else {
+ TreeNode<K,V> sp = s.parent;
+ if ((p.parent = sp) != null) {
+ if (s == sp.left)
+ sp.left = p;
+ else
+ sp.right = p;
+ }
+ if ((s.right = pr) != null)
+ pr.parent = s;
+ }
+ p.left = null;
+ if ((p.right = sr) != null)
+ sr.parent = p;
+ if ((s.left = pl) != null)
+ pl.parent = s;
+ if ((s.parent = pp) == null)
+ r = s;
+ else if (p == pp.left)
+ pp.left = s;
+ else
+ pp.right = s;
+ if (sr != null)
+ replacement = sr;
+ else
+ replacement = p;
+ }
+ else if (pl != null)
+ replacement = pl;
+ else if (pr != null)
+ replacement = pr;
+ else
+ replacement = p;
+ if (replacement != p) {
+ TreeNode<K,V> pp = replacement.parent = p.parent;
+ if (pp == null)
+ r = replacement;
+ else if (p == pp.left)
+ pp.left = replacement;
+ else
+ pp.right = replacement;
+ p.left = p.right = p.parent = null;
+ }
+
+ root = (p.red) ? r : balanceDeletion(r, replacement);
+
+ if (p == replacement) { // detach pointers
+ TreeNode<K,V> pp;
+ if ((pp = p.parent) != null) {
+ if (p == pp.left)
+ pp.left = null;
+ else if (p == pp.right)
+ pp.right = null;
+ p.parent = null;
+ }
+ }
+ } finally {
+ unlockRoot();
+ }
+ assert checkInvariants(root);
+ return false;
+ }
+
+ /* ------------------------------------------------------------ */
+ // Red-black tree methods, all adapted from CLR
+
+ static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
+ TreeNode<K,V> p) {
+ TreeNode<K,V> r, pp, rl;
+ if (p != null && (r = p.right) != null) {
+ if ((rl = p.right = r.left) != null)
+ rl.parent = p;
+ if ((pp = r.parent = p.parent) == null)
+ (root = r).red = false;
+ else if (pp.left == p)
+ pp.left = r;
+ else
+ pp.right = r;
+ r.left = p;
+ p.parent = r;
+ }
+ return root;
+ }
+
+ static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
+ TreeNode<K,V> p) {
+ TreeNode<K,V> l, pp, lr;
+ if (p != null && (l = p.left) != null) {
+ if ((lr = p.left = l.right) != null)
+ lr.parent = p;
+ if ((pp = l.parent = p.parent) == null)
+ (root = l).red = false;
+ else if (pp.right == p)
+ pp.right = l;
+ else
+ pp.left = l;
+ l.right = p;
+ p.parent = l;
+ }
+ return root;
}
- public final boolean hasNext() { return nextEntry != null; }
- public final boolean hasMoreElements() { return nextEntry != null; }
+ static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
+ TreeNode<K,V> x) {
+ x.red = true;
+ for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
+ if ((xp = x.parent) == null) {
+ x.red = false;
+ return x;
+ }
+ else if (!xp.red || (xpp = xp.parent) == null)
+ return root;
+ if (xp == (xppl = xpp.left)) {
+ if ((xppr = xpp.right) != null && xppr.red) {
+ xppr.red = false;
+ xp.red = false;
+ xpp.red = true;
+ x = xpp;
+ }
+ else {
+ if (x == xp.right) {
+ root = rotateLeft(root, x = xp);
+ xpp = (xp = x.parent) == null ? null : xp.parent;
+ }
+ if (xp != null) {
+ xp.red = false;
+ if (xpp != null) {
+ xpp.red = true;
+ root = rotateRight(root, xpp);
+ }
+ }
+ }
+ }
+ else {
+ if (xppl != null && xppl.red) {
+ xppl.red = false;
+ xp.red = false;
+ xpp.red = true;
+ x = xpp;
+ }
+ else {
+ if (x == xp.left) {
+ root = rotateRight(root, x = xp);
+ xpp = (xp = x.parent) == null ? null : xp.parent;
+ }
+ if (xp != null) {
+ xp.red = false;
+ if (xpp != null) {
+ xpp.red = true;
+ root = rotateLeft(root, xpp);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
+ TreeNode<K,V> x) {
+ for (TreeNode<K,V> xp, xpl, xpr;;) {
+ if (x == null || x == root)
+ return root;
+ else if ((xp = x.parent) == null) {
+ x.red = false;
+ return x;
+ }
+ else if (x.red) {
+ x.red = false;
+ return root;
+ }
+ else if ((xpl = xp.left) == x) {
+ if ((xpr = xp.right) != null && xpr.red) {
+ xpr.red = false;
+ xp.red = true;
+ root = rotateLeft(root, xp);
+ xpr = (xp = x.parent) == null ? null : xp.right;
+ }
+ if (xpr == null)
+ x = xp;
+ else {
+ TreeNode<K,V> sl = xpr.left, sr = xpr.right;
+ if ((sr == null || !sr.red) &&
+ (sl == null || !sl.red)) {
+ xpr.red = true;
+ x = xp;
+ }
+ else {
+ if (sr == null || !sr.red) {
+ if (sl != null)
+ sl.red = false;
+ xpr.red = true;
+ root = rotateRight(root, xpr);
+ xpr = (xp = x.parent) == null ?
+ null : xp.right;
+ }
+ if (xpr != null) {
+ xpr.red = (xp == null) ? false : xp.red;
+ if ((sr = xpr.right) != null)
+ sr.red = false;
+ }
+ if (xp != null) {
+ xp.red = false;
+ root = rotateLeft(root, xp);
+ }
+ x = root;
+ }
+ }
+ }
+ else { // symmetric
+ if (xpl != null && xpl.red) {
+ xpl.red = false;
+ xp.red = true;
+ root = rotateRight(root, xp);
+ xpl = (xp = x.parent) == null ? null : xp.left;
+ }
+ if (xpl == null)
+ x = xp;
+ else {
+ TreeNode<K,V> sl = xpl.left, sr = xpl.right;
+ if ((sl == null || !sl.red) &&
+ (sr == null || !sr.red)) {
+ xpl.red = true;
+ x = xp;
+ }
+ else {
+ if (sl == null || !sl.red) {
+ if (sr != null)
+ sr.red = false;
+ xpl.red = true;
+ root = rotateLeft(root, xpl);
+ xpl = (xp = x.parent) == null ?
+ null : xp.left;
+ }
+ if (xpl != null) {
+ xpl.red = (xp == null) ? false : xp.red;
+ if ((sl = xpl.left) != null)
+ sl.red = false;
+ }
+ if (xp != null) {
+ xp.red = false;
+ root = rotateRight(root, xp);
+ }
+ x = root;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Recursive invariant check
+ */
+ static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
+ TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
+ tb = t.prev, tn = (TreeNode<K,V>)t.next;
+ if (tb != null && tb.next != t)
+ return false;
+ if (tn != null && tn.prev != t)
+ return false;
+ if (tp != null && t != tp.left && t != tp.right)
+ return false;
+ if (tl != null && (tl.parent != t || tl.hash > t.hash))
+ return false;
+ if (tr != null && (tr.parent != t || tr.hash < t.hash))
+ return false;
+ if (t.red && tl != null && tl.red && tr != null && tr.red)
+ return false;
+ if (tl != null && !checkInvariants(tl))
+ return false;
+ if (tr != null && !checkInvariants(tr))
+ return false;
+ return true;
+ }
+
+ private static final sun.misc.Unsafe U;
+ private static final long LOCKSTATE;
+ static {
+ try {
+ U = sun.misc.Unsafe.getUnsafe();
+ Class<?> k = TreeBin.class;
+ LOCKSTATE = U.objectFieldOffset
+ (k.getDeclaredField("lockState"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
+ }
+
+ /* ----------------Table Traversal -------------- */
+
+ /**
+ * Encapsulates traversal for methods such as containsValue; also
+ * serves as a base class for other iterators.
+ *
+ * Method advance visits once each still-valid node that was
+ * reachable upon iterator construction. It might miss some that
+ * were added to a bin after the bin was visited, which is OK wrt
+ * consistency guarantees. Maintaining this property in the face
+ * of possible ongoing resizes requires a fair amount of
+ * bookkeeping state that is difficult to optimize away amidst
+ * volatile accesses. Even so, traversal maintains reasonable
+ * throughput.
+ *
+ * Normally, iteration proceeds bin-by-bin traversing lists.
+ * However, if the table has been resized, then all future steps
+ * must traverse both the bin at the current index as well as at
+ * (index + baseSize); and so on for further resizings. To
+ * paranoically cope with potential sharing by users of iterators
+ * across threads, iteration terminates if a bounds checks fails
+ * for a table read.
+ */
+ static class Traverser<K,V> {
+ Node<K,V>[] tab; // current table; updated if resized
+ Node<K,V> next; // the next entry to use
+ int index; // index of bin to use next
+ int baseIndex; // current index of initial table
+ int baseLimit; // index bound for initial table
+ final int baseSize; // initial table size
+
+ Traverser(Node<K,V>[] tab, int size, int index, int limit) {
+ this.tab = tab;
+ this.baseSize = size;
+ this.baseIndex = this.index = index;
+ this.baseLimit = limit;
+ this.next = null;
+ }
+
+ /**
+ * Advances if possible, returning next valid node, or null if none.
+ */
+ final Node<K,V> advance() {
+ Node<K,V> e;
+ if ((e = next) != null)
+ e = e.next;
+ for (;;) {
+ Node<K,V>[] t; int i, n; K ek; // must use locals in checks
+ if (e != null)
+ return next = e;
+ if (baseIndex >= baseLimit || (t = tab) == null ||
+ (n = t.length) <= (i = index) || i < 0)
+ return next = null;
+ if ((e = tabAt(t, index)) != null && e.hash < 0) {
+ if (e instanceof ForwardingNode) {
+ tab = ((ForwardingNode<K,V>)e).nextTable;
+ e = null;
+ continue;
+ }
+ else if (e instanceof TreeBin)
+ e = ((TreeBin<K,V>)e).first;
+ else
+ e = null;
+ }
+ if ((index += baseSize) >= n)
+ index = ++baseIndex; // visit upper slots if present
+ }
+ }
+ }
+
+ /**
+ * Base of key, value, and entry Iterators. Adds fields to
+ * Traverser to support iterator.remove.
+ */
+ static class BaseIterator<K,V> extends Traverser<K,V> {
+ final ConcurrentHashMap<K,V> map;
+ Node<K,V> lastReturned;
+ BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
+ ConcurrentHashMap<K,V> map) {
+ super(tab, size, index, limit);
+ this.map = map;
+ advance();
+ }
+
+ public final boolean hasNext() { return next != null; }
+ public final boolean hasMoreElements() { return next != null; }
public final void remove() {
- if (lastReturned == null)
+ Node<K,V> p;
+ if ((p = lastReturned) == null)
throw new IllegalStateException();
- ConcurrentHashMap.this.remove(lastReturned.key);
lastReturned = null;
+ map.replaceNode(p.key, null, null);
+ }
+ }
+
+ static final class KeyIterator<K,V> extends BaseIterator<K,V>
+ implements Iterator<K>, Enumeration<K> {
+ KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
+ ConcurrentHashMap<K,V> map) {
+ super(tab, index, size, limit, map);
+ }
+
+ public final K next() {
+ Node<K,V> p;
+ if ((p = next) == null)
+ throw new NoSuchElementException();
+ K k = p.key;
+ lastReturned = p;
+ advance();
+ return k;
}
+
+ public final K nextElement() { return next(); }
}
- final class KeyIterator
- extends HashIterator
- implements Iterator<K>, Enumeration<K>
- {
- public final K next() { return super.nextEntry().key; }
- public final K nextElement() { return super.nextEntry().key; }
+ static final class ValueIterator<K,V> extends BaseIterator<K,V>
+ implements Iterator<V>, Enumeration<V> {
+ ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
+ ConcurrentHashMap<K,V> map) {
+ super(tab, index, size, limit, map);
+ }
+
+ public final V next() {
+ Node<K,V> p;
+ if ((p = next) == null)
+ throw new NoSuchElementException();
+ V v = p.val;
+ lastReturned = p;
+ advance();
+ return v;
+ }
+
+ public final V nextElement() { return next(); }
}
- final class ValueIterator
- extends HashIterator
- implements Iterator<V>, Enumeration<V>
- {
- public final V next() { return super.nextEntry().value; }
- public final V nextElement() { return super.nextEntry().value; }
+ static final class EntryIterator<K,V> extends BaseIterator<K,V>
+ implements Iterator<Map.Entry<K,V>> {
+ EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
+ ConcurrentHashMap<K,V> map) {
+ super(tab, index, size, limit, map);
+ }
+
+ public final Map.Entry<K,V> next() {
+ Node<K,V> p;
+ if ((p = next) == null)
+ throw new NoSuchElementException();
+ K k = p.key;
+ V v = p.val;
+ lastReturned = p;
+ advance();
+ return new MapEntry<K,V>(k, v, map);
+ }
}
/**
- * Custom Entry class used by EntryIterator.next(), that relays
- * setValue changes to the underlying map.
+ * Exported Entry for EntryIterator
*/
- final class WriteThroughEntry
- extends AbstractMap.SimpleEntry<K,V>
- {
- WriteThroughEntry(K k, V v) {
- super(k,v);
+ static final class MapEntry<K,V> implements Map.Entry<K,V> {
+ final K key; // non-null
+ V val; // non-null
+ final ConcurrentHashMap<K,V> map;
+ MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
+ this.key = key;
+ this.val = val;
+ this.map = map;
+ }
+ public K getKey() { return key; }
+ public V getValue() { return val; }
+ public int hashCode() { return key.hashCode() ^ val.hashCode(); }
+ public String toString() { return key + "=" + val; }
+
+ public boolean equals(Object o) {
+ Object k, v; Map.Entry<?,?> e;
+ return ((o instanceof Map.Entry) &&
+ (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
+ (v = e.getValue()) != null &&
+ (k == key || k.equals(key)) &&
+ (v == val || v.equals(val)));
}
/**
* Sets our entry's value and writes through to the map. The
- * value to return is somewhat arbitrary here. Since a
- * WriteThroughEntry does not necessarily track asynchronous
- * changes, the most recent "previous" value could be
- * different from what we return (or could even have been
- * removed in which case the put will re-establish). We do not
- * and cannot guarantee more.
+ * value to return is somewhat arbitrary here. Since we do not
+ * necessarily track asynchronous changes, the most recent
+ * "previous" value could be different from what we return (or
+ * could even have been removed, in which case the put will
+ * re-establish). We do not and cannot guarantee more.
*/
public V setValue(V value) {
if (value == null) throw new NullPointerException();
- V v = super.setValue(value);
- ConcurrentHashMap.this.put(getKey(), value);
+ V v = val;
+ val = value;
+ map.put(key, value);
return v;
}
}
- final class EntryIterator
- extends HashIterator
- implements Iterator<Entry<K,V>>
- {
- public Map.Entry<K,V> next() {
- HashEntry<K,V> e = super.nextEntry();
- return new WriteThroughEntry(e.key, e.value);
+ /* ----------------Views -------------- */
+
+ /**
+ * Base class for views.
+ *
+ */
+ abstract static class CollectionView<K,V,E>
+ implements Collection<E>, java.io.Serializable {
+ private static final long serialVersionUID = 7249069246763182397L;
+ final ConcurrentHashMap<K,V> map;
+ CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
+
+ /**
+ * Returns the map backing this view.
+ *
+ * @return the map backing this view
+ */
+ public ConcurrentHashMap<K,V> getMap() { return map; }
+
+ /**
+ * Removes all of the elements from this view, by removing all
+ * the mappings from the map backing this view.
+ */
+ public final void clear() { map.clear(); }
+ public final int size() { return map.size(); }
+ public final boolean isEmpty() { return map.isEmpty(); }
+
+ // implementations below rely on concrete classes supplying these
+ // abstract methods
+ /**
+ * Returns a "weakly consistent" iterator that will never
+ * throw {@link ConcurrentModificationException}, and
+ * guarantees to traverse elements as they existed upon
+ * construction of the iterator, and may (but is not
+ * guaranteed to) reflect any modifications subsequent to
+ * construction.
+ */
+ public abstract Iterator<E> iterator();
+ public abstract boolean contains(Object o);
+ public abstract boolean remove(Object o);
+
+ private static final String oomeMsg = "Required array size too large";
+
+ public final Object[] toArray() {
+ long sz = map.mappingCount();
+ if (sz > MAX_ARRAY_SIZE)
+ throw new OutOfMemoryError(oomeMsg);
+ int n = (int)sz;
+ Object[] r = new Object[n];
+ int i = 0;
+ for (E e : this) {
+ if (i == n) {
+ if (n >= MAX_ARRAY_SIZE)
+ throw new OutOfMemoryError(oomeMsg);
+ if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
+ n = MAX_ARRAY_SIZE;
+ else
+ n += (n >>> 1) + 1;
+ r = Arrays.copyOf(r, n);
+ }
+ r[i++] = e;
+ }
+ return (i == n) ? r : Arrays.copyOf(r, i);
+ }
+
+ @SuppressWarnings("unchecked")
+ public final <T> T[] toArray(T[] a) {
+ long sz = map.mappingCount();
+ if (sz > MAX_ARRAY_SIZE)
+ throw new OutOfMemoryError(oomeMsg);
+ int m = (int)sz;
+ T[] r = (a.length >= m) ? a :
+ (T[])java.lang.reflect.Array
+ .newInstance(a.getClass().getComponentType(), m);
+ int n = r.length;
+ int i = 0;
+ for (E e : this) {
+ if (i == n) {
+ if (n >= MAX_ARRAY_SIZE)
+ throw new OutOfMemoryError(oomeMsg);
+ if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
+ n = MAX_ARRAY_SIZE;
+ else
+ n += (n >>> 1) + 1;
+ r = Arrays.copyOf(r, n);
+ }
+ r[i++] = (T)e;
+ }
+ if (a == r && i < n) {
+ r[i] = null; // null-terminate
+ return r;
+ }
+ return (i == n) ? r : Arrays.copyOf(r, i);
+ }
+
+ /**
+ * Returns a string representation of this collection.
+ * The string representation consists of the string representations
+ * of the collection's elements in the order they are returned by
+ * its iterator, enclosed in square brackets ({@code "[]"}).
+ * Adjacent elements are separated by the characters {@code ", "}
+ * (comma and space). Elements are converted to strings as by
+ * {@link String#valueOf(Object)}.
+ *
+ * @return a string representation of this collection
+ */
+ public final String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ Iterator<E> it = iterator();
+ if (it.hasNext()) {
+ for (;;) {
+ Object e = it.next();
+ sb.append(e == this ? "(this Collection)" : e);
+ if (!it.hasNext())
+ break;
+ sb.append(',').append(' ');
+ }
+ }
+ return sb.append(']').toString();
}
+
+ public final boolean containsAll(Collection<?> c) {
+ if (c != this) {
+ for (Object e : c) {
+ if (e == null || !contains(e))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public final boolean removeAll(Collection<?> c) {
+ boolean modified = false;
+ for (Iterator<E> it = iterator(); it.hasNext();) {
+ if (c.contains(it.next())) {
+ it.remove();
+ modified = true;
+ }
+ }
+ return modified;
+ }
+
+ public final boolean retainAll(Collection<?> c) {
+ boolean modified = false;
+ for (Iterator<E> it = iterator(); it.hasNext();) {
+ if (!c.contains(it.next())) {
+ it.remove();
+ modified = true;
+ }
+ }
+ return modified;
+ }
+
}
- final class KeySet extends AbstractSet<K> {
- public Iterator<K> iterator() {
- return new KeyIterator();
+ /**
+ * A view of a ConcurrentHashMap as a {@link Set} of keys, in
+ * which additions may optionally be enabled by mapping to a
+ * common value. This class cannot be directly instantiated.
+ * See {@link #keySet() keySet()},
+ * {@link #keySet(Object) keySet(V)},
+ * {@link #newKeySet() newKeySet()},
+ * {@link #newKeySet(int) newKeySet(int)}.
+ *
+ * @since 1.8
+ *
+ * @hide
+ */
+ public static class KeySetView<K,V> extends CollectionView<K,V,K>
+ implements Set<K>, java.io.Serializable {
+ private static final long serialVersionUID = 7249069246763182397L;
+ private final V value;
+ KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
+ super(map);
+ this.value = value;
}
- public int size() {
- return ConcurrentHashMap.this.size();
+
+ /**
+ * Returns the default mapped value for additions,
+ * or {@code null} if additions are not supported.
+ *
+ * @return the default mapped value for additions, or {@code null}
+ * if not supported
+ */
+ public V getMappedValue() { return value; }
+
+ /**
+ * {@inheritDoc}
+ * @throws NullPointerException if the specified key is null
+ */
+ public boolean contains(Object o) { return map.containsKey(o); }
+
+ /**
+ * Removes the key from this map view, by removing the key (and its
+ * corresponding value) from the backing map. This method does
+ * nothing if the key is not in the map.
+ *
+ * @param o the key to be removed from the backing map
+ * @return {@code true} if the backing map contained the specified key
+ * @throws NullPointerException if the specified key is null
+ */
+ public boolean remove(Object o) { return map.remove(o) != null; }
+
+ /**
+ * @return an iterator over the keys of the backing map
+ */
+ public Iterator<K> iterator() {
+ Node<K,V>[] t;
+ ConcurrentHashMap<K,V> m = map;
+ int f = (t = m.table) == null ? 0 : t.length;
+ return new KeyIterator<K,V>(t, f, 0, f, m);
}
- public boolean isEmpty() {
- return ConcurrentHashMap.this.isEmpty();
+
+ /**
+ * Adds the specified key to this set view by mapping the key to
+ * the default mapped value in the backing map, if defined.
+ *
+ * @param e key to be added
+ * @return {@code true} if this set changed as a result of the call
+ * @throws NullPointerException if the specified key is null
+ * @throws UnsupportedOperationException if no default mapped value
+ * for additions was provided
+ */
+ public boolean add(K e) {
+ V v;
+ if ((v = value) == null)
+ throw new UnsupportedOperationException();
+ return map.putVal(e, v, true) == null;
}
- public boolean contains(Object o) {
- return ConcurrentHashMap.this.containsKey(o);
+
+ /**
+ * Adds all of the elements in the specified collection to this set,
+ * as if by calling {@link #add} on each one.
+ *
+ * @param c the elements to be inserted into this set
+ * @return {@code true} if this set changed as a result of the call
+ * @throws NullPointerException if the collection or any of its
+ * elements are {@code null}
+ * @throws UnsupportedOperationException if no default mapped value
+ * for additions was provided
+ */
+ public boolean addAll(Collection<? extends K> c) {
+ boolean added = false;
+ V v;
+ if ((v = value) == null)
+ throw new UnsupportedOperationException();
+ for (K e : c) {
+ if (map.putVal(e, v, true) == null)
+ added = true;
+ }
+ return added;
}
- public boolean remove(Object o) {
- return ConcurrentHashMap.this.remove(o) != null;
+
+ public int hashCode() {
+ int h = 0;
+ for (K e : this)
+ h += e.hashCode();
+ return h;
}
- public void clear() {
- ConcurrentHashMap.this.clear();
+
+ public boolean equals(Object o) {
+ Set<?> c;
+ return ((o instanceof Set) &&
+ ((c = (Set<?>)o) == this ||
+ (containsAll(c) && c.containsAll(this))));
}
+
}
- final class Values extends AbstractCollection<V> {
- public Iterator<V> iterator() {
- return new ValueIterator();
+ /**
+ * A view of a ConcurrentHashMap as a {@link Collection} of
+ * values, in which additions are disabled. This class cannot be
+ * directly instantiated. See {@link #values()}.
+ */
+ static final class ValuesView<K,V> extends CollectionView<K,V,V>
+ implements Collection<V>, java.io.Serializable {
+ private static final long serialVersionUID = 2249069246763182397L;
+ ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
+ public final boolean contains(Object o) {
+ return map.containsValue(o);
}
- public int size() {
- return ConcurrentHashMap.this.size();
+
+ public final boolean remove(Object o) {
+ if (o != null) {
+ for (Iterator<V> it = iterator(); it.hasNext();) {
+ if (o.equals(it.next())) {
+ it.remove();
+ return true;
+ }
+ }
+ }
+ return false;
}
- public boolean isEmpty() {
- return ConcurrentHashMap.this.isEmpty();
+
+ public final Iterator<V> iterator() {
+ ConcurrentHashMap<K,V> m = map;
+ Node<K,V>[] t;
+ int f = (t = m.table) == null ? 0 : t.length;
+ return new ValueIterator<K,V>(t, f, 0, f, m);
}
- public boolean contains(Object o) {
- return ConcurrentHashMap.this.containsValue(o);
+
+ public final boolean add(V e) {
+ throw new UnsupportedOperationException();
}
- public void clear() {
- ConcurrentHashMap.this.clear();
+ public final boolean addAll(Collection<? extends V> c) {
+ throw new UnsupportedOperationException();
}
+
}
- final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
- public Iterator<Map.Entry<K,V>> iterator() {
- return new EntryIterator();
- }
+ /**
+ * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
+ * entries. This class cannot be directly instantiated. See
+ * {@link #entrySet()}.
+ */
+ static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
+ implements Set<Map.Entry<K,V>>, java.io.Serializable {
+ private static final long serialVersionUID = 2249069246763182397L;
+ EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
+
public boolean contains(Object o) {
- if (!(o instanceof Map.Entry))
- return false;
- Map.Entry<?,?> e = (Map.Entry<?,?>)o;
- V v = ConcurrentHashMap.this.get(e.getKey());
- return v != null && v.equals(e.getValue());
+ Object k, v, r; Map.Entry<?,?> e;
+ return ((o instanceof Map.Entry) &&
+ (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
+ (r = map.get(k)) != null &&
+ (v = e.getValue()) != null &&
+ (v == r || v.equals(r)));
}
+
public boolean remove(Object o) {
- if (!(o instanceof Map.Entry))
- return false;
- Map.Entry<?,?> e = (Map.Entry<?,?>)o;
- return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
+ Object k, v; Map.Entry<?,?> e;
+ return ((o instanceof Map.Entry) &&
+ (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
+ (v = e.getValue()) != null &&
+ map.remove(k, v));
}
- public int size() {
- return ConcurrentHashMap.this.size();
+
+ /**
+ * @return an iterator over the entries of the backing map
+ */
+ public Iterator<Map.Entry<K,V>> iterator() {
+ ConcurrentHashMap<K,V> m = map;
+ Node<K,V>[] t;
+ int f = (t = m.table) == null ? 0 : t.length;
+ return new EntryIterator<K,V>(t, f, 0, f, m);
}
- public boolean isEmpty() {
- return ConcurrentHashMap.this.isEmpty();
+
+ public boolean add(Entry<K,V> e) {
+ return map.putVal(e.getKey(), e.getValue(), false) == null;
}
- public void clear() {
- ConcurrentHashMap.this.clear();
+
+ public boolean addAll(Collection<? extends Entry<K,V>> c) {
+ boolean added = false;
+ for (Entry<K,V> e : c) {
+ if (add(e))
+ added = true;
+ }
+ return added;
}
+
+ public final int hashCode() {
+ int h = 0;
+ Node<K,V>[] t;
+ if ((t = map.table) != null) {
+ Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+ for (Node<K,V> p; (p = it.advance()) != null; ) {
+ h += p.hashCode();
+ }
+ }
+ return h;
+ }
+
+ public final boolean equals(Object o) {
+ Set<?> c;
+ return ((o instanceof Set) &&
+ ((c = (Set<?>)o) == this ||
+ (containsAll(c) && c.containsAll(this))));
+ }
+
}
- /* ---------------- Serialization Support -------------- */
+
+ /* ---------------- Counters -------------- */
+
+ // Adapted from LongAdder and Striped64.
+ // See their internal docs for explanation.
+
+ // A padded cell for distributing counts
+ static final class CounterCell {
+ volatile long p0, p1, p2, p3, p4, p5, p6;
+ volatile long value;
+ volatile long q0, q1, q2, q3, q4, q5, q6;
+ CounterCell(long x) { value = x; }
+ }
/**
- * Saves the state of the <tt>ConcurrentHashMap</tt> instance to a
- * stream (i.e., serializes it).
- * @param s the stream
- * @serialData
- * the key (Object) and value (Object)
- * for each key-value mapping, followed by a null pair.
- * The key-value mappings are emitted in no particular order.
+ * Holder for the thread-local hash code determining which
+ * CounterCell to use. The code is initialized via the
+ * counterHashCodeGenerator, but may be moved upon collisions.
*/
- private void writeObject(java.io.ObjectOutputStream s)
- throws java.io.IOException {
- // force all segments for serialization compatibility
- for (int k = 0; k < segments.length; ++k)
- ensureSegment(k);
- s.defaultWriteObject();
-
- final Segment<K,V>[] segments = this.segments;
- for (int k = 0; k < segments.length; ++k) {
- Segment<K,V> seg = segmentAt(segments, k);
- seg.lock();
- try {
- HashEntry<K,V>[] tab = seg.table;
- for (int i = 0; i < tab.length; ++i) {
- HashEntry<K,V> e;
- for (e = entryAt(tab, i); e != null; e = e.next) {
- s.writeObject(e.key);
- s.writeObject(e.value);
- }
- }
- } finally {
- seg.unlock();
- }
- }
- s.writeObject(null);
- s.writeObject(null);
+ static final class CounterHashCode {
+ int code;
}
/**
- * Reconstitutes the <tt>ConcurrentHashMap</tt> instance from a
- * stream (i.e., deserializes it).
- * @param s the stream
+ * Generates initial value for per-thread CounterHashCodes.
*/
- @SuppressWarnings("unchecked")
- private void readObject(java.io.ObjectInputStream s)
- throws java.io.IOException, ClassNotFoundException {
- s.defaultReadObject();
+ static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
- // Re-initialize segments to be minimally sized, and let grow.
- int cap = MIN_SEGMENT_TABLE_CAPACITY;
- final Segment<K,V>[] segments = this.segments;
- for (int k = 0; k < segments.length; ++k) {
- Segment<K,V> seg = segments[k];
- if (seg != null) {
- seg.threshold = (int)(cap * seg.loadFactor);
- seg.table = (HashEntry<K,V>[]) new HashEntry<?,?>[cap];
+ /**
+ * Increment for counterHashCodeGenerator. See class ThreadLocal
+ * for explanation.
+ */
+ static final int SEED_INCREMENT = 0x61c88647;
+
+ /**
+ * Per-thread counter hash codes. Shared across all instances.
+ */
+ static final ThreadLocal<CounterHashCode> threadCounterHashCode =
+ new ThreadLocal<CounterHashCode>();
+
+ final long sumCount() {
+ CounterCell[] as = counterCells; CounterCell a;
+ long sum = baseCount;
+ if (as != null) {
+ for (int i = 0; i < as.length; ++i) {
+ if ((a = as[i]) != null)
+ sum += a.value;
}
}
+ return sum;
+ }
- // Read the keys and values, and put the mappings in the table
+ // See LongAdder version for explanation
+ private final void fullAddCount(long x, CounterHashCode hc,
+ boolean wasUncontended) {
+ int h;
+ if (hc == null) {
+ hc = new CounterHashCode();
+ int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
+ h = hc.code = (s == 0) ? 1 : s; // Avoid zero
+ threadCounterHashCode.set(hc);
+ }
+ else
+ h = hc.code;
+ boolean collide = false; // True if last slot nonempty
for (;;) {
- K key = (K) s.readObject();
- V value = (V) s.readObject();
- if (key == null)
- break;
- put(key, value);
+ CounterCell[] as; CounterCell a; int n; long v;
+ if ((as = counterCells) != null && (n = as.length) > 0) {
+ if ((a = as[(n - 1) & h]) == null) {
+ if (cellsBusy == 0) { // Try to attach new Cell
+ CounterCell r = new CounterCell(x); // Optimistic create
+ if (cellsBusy == 0 &&
+ U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
+ boolean created = false;
+ try { // Recheck under lock
+ CounterCell[] rs; int m, j;
+ if ((rs = counterCells) != null &&
+ (m = rs.length) > 0 &&
+ rs[j = (m - 1) & h] == null) {
+ rs[j] = r;
+ created = true;
+ }
+ } finally {
+ cellsBusy = 0;
+ }
+ if (created)
+ break;
+ continue; // Slot is now non-empty
+ }
+ }
+ collide = false;
+ }
+ else if (!wasUncontended) // CAS already known to fail
+ wasUncontended = true; // Continue after rehash
+ else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
+ break;
+ else if (counterCells != as || n >= NCPU)
+ collide = false; // At max size or stale
+ else if (!collide)
+ collide = true;
+ else if (cellsBusy == 0 &&
+ U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
+ try {
+ if (counterCells == as) {// Expand table unless stale
+ CounterCell[] rs = new CounterCell[n << 1];
+ for (int i = 0; i < n; ++i)
+ rs[i] = as[i];
+ counterCells = rs;
+ }
+ } finally {
+ cellsBusy = 0;
+ }
+ collide = false;
+ continue; // Retry with expanded table
+ }
+ h ^= h << 13; // Rehash
+ h ^= h >>> 17;
+ h ^= h << 5;
+ }
+ else if (cellsBusy == 0 && counterCells == as &&
+ U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
+ boolean init = false;
+ try { // Initialize table
+ if (counterCells == as) {
+ CounterCell[] rs = new CounterCell[2];
+ rs[h & 1] = new CounterCell(x);
+ counterCells = rs;
+ init = true;
+ }
+ } finally {
+ cellsBusy = 0;
+ }
+ if (init)
+ break;
+ }
+ else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
+ break; // Fall back on using base
}
+ hc.code = h; // Record index for next time
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE;
- private static final long SBASE;
- private static final int SSHIFT;
- private static final long TBASE;
- private static final int TSHIFT;
+ private static final sun.misc.Unsafe U;
+ private static final long SIZECTL;
+ private static final long TRANSFERINDEX;
+ private static final long TRANSFERORIGIN;
+ private static final long BASECOUNT;
+ private static final long CELLSBUSY;
+ private static final long CELLVALUE;
+ private static final long ABASE;
+ private static final int ASHIFT;
static {
- int ss, ts;
try {
- UNSAFE = sun.misc.Unsafe.getUnsafe();
- Class<?> tc = HashEntry[].class;
- Class<?> sc = Segment[].class;
- TBASE = UNSAFE.arrayBaseOffset(tc);
- SBASE = UNSAFE.arrayBaseOffset(sc);
- ts = UNSAFE.arrayIndexScale(tc);
- ss = UNSAFE.arrayIndexScale(sc);
+ U = sun.misc.Unsafe.getUnsafe();
+ Class<?> k = ConcurrentHashMap.class;
+ SIZECTL = U.objectFieldOffset
+ (k.getDeclaredField("sizeCtl"));
+ TRANSFERINDEX = U.objectFieldOffset
+ (k.getDeclaredField("transferIndex"));
+ TRANSFERORIGIN = U.objectFieldOffset
+ (k.getDeclaredField("transferOrigin"));
+ BASECOUNT = U.objectFieldOffset
+ (k.getDeclaredField("baseCount"));
+ CELLSBUSY = U.objectFieldOffset
+ (k.getDeclaredField("cellsBusy"));
+ Class<?> ck = CounterCell.class;
+ CELLVALUE = U.objectFieldOffset
+ (ck.getDeclaredField("value"));
+ Class<?> ak = Node[].class;
+ ABASE = U.arrayBaseOffset(ak);
+ int scale = U.arrayIndexScale(ak);
+ if ((scale & (scale - 1)) != 0)
+ throw new Error("data type scale not a power of two");
+ ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
} catch (Exception e) {
throw new Error(e);
}
- if ((ss & (ss-1)) != 0 || (ts & (ts-1)) != 0)
- throw new Error("data type scale not a power of two");
- SSHIFT = 31 - Integer.numberOfLeadingZeros(ss);
- TSHIFT = 31 - Integer.numberOfLeadingZeros(ts);
}
}
diff --git a/luni/src/main/java/java/util/concurrent/ConcurrentLinkedDeque.java b/luni/src/main/java/java/util/concurrent/ConcurrentLinkedDeque.java
index 54b53ae..b38d6a5 100644
--- a/luni/src/main/java/java/util/concurrent/ConcurrentLinkedDeque.java
+++ b/luni/src/main/java/java/util/concurrent/ConcurrentLinkedDeque.java
@@ -56,8 +56,6 @@ import java.util.Queue;
* actions subsequent to the access or removal of that element from
* the {@code ConcurrentLinkedDeque} in another thread.
*
- * @hide
- *
* @since 1.7
* @author Doug Lea
* @author Martin Buchholz
diff --git a/luni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java b/luni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java
index 873f825..b39a533 100644
--- a/luni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java
+++ b/luni/src/main/java/java/util/concurrent/ConcurrentLinkedQueue.java
@@ -31,7 +31,7 @@ import java.util.Queue;
* Like most other concurrent collection implementations, this class
* does not permit the use of {@code null} elements.
*
- * <p>This implementation employs an efficient &quot;wait-free&quot;
+ * <p>This implementation employs an efficient <em>non-blocking</em>
* algorithm based on one described in <a
* href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple,
* Fast, and Practical Non-Blocking and Blocking Concurrent Queue
diff --git a/luni/src/main/java/java/util/concurrent/CountedCompleter.java b/luni/src/main/java/java/util/concurrent/CountedCompleter.java
index ffe7582..d5f794e 100644
--- a/luni/src/main/java/java/util/concurrent/CountedCompleter.java
+++ b/luni/src/main/java/java/util/concurrent/CountedCompleter.java
@@ -8,14 +8,15 @@ package java.util.concurrent;
/**
* A {@link ForkJoinTask} with a completion action performed when
- * triggered and there are no remaining pending
- * actions. CountedCompleters are in general more robust in the
+ * triggered and there are no remaining pending actions.
+ * CountedCompleters are in general more robust in the
* presence of subtask stalls and blockage than are other forms of
* ForkJoinTasks, but are less intuitive to program. Uses of
* CountedCompleter are similar to those of other completion based
* components (such as {@link java.nio.channels.CompletionHandler})
* except that multiple <em>pending</em> completions may be necessary
- * to trigger the completion action {@link #onCompletion}, not just one.
+ * to trigger the completion action {@link #onCompletion(CountedCompleter)},
+ * not just one.
* Unless initialized otherwise, the {@linkplain #getPendingCount pending
* count} starts at zero, but may be (atomically) changed using
* methods {@link #setPendingCount}, {@link #addToPendingCount}, and
@@ -40,9 +41,10 @@ package java.util.concurrent;
* <p>A concrete CountedCompleter class must define method {@link
* #compute}, that should in most cases (as illustrated below), invoke
* {@code tryComplete()} once before returning. The class may also
- * optionally override method {@link #onCompletion} to perform an
- * action upon normal completion, and method {@link
- * #onExceptionalCompletion} to perform an action upon any exception.
+ * optionally override method {@link #onCompletion(CountedCompleter)}
+ * to perform an action upon normal completion, and method
+ * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to
+ * perform an action upon any exception.
*
* <p>CountedCompleters most often do not bear results, in which case
* they are normally declared as {@code CountedCompleter<Void>}, and
@@ -63,13 +65,14 @@ package java.util.concurrent;
* only as an internal helper for other computations, so its own task
* status (as reported in methods such as {@link ForkJoinTask#isDone})
* is arbitrary; this status changes only upon explicit invocations of
- * {@link #complete}, {@link ForkJoinTask#cancel}, {@link
- * ForkJoinTask#completeExceptionally} or upon exceptional completion
- * of method {@code compute}. Upon any exceptional completion, the
- * exception may be relayed to a task's completer (and its completer,
- * and so on), if one exists and it has not otherwise already
- * completed. Similarly, cancelling an internal CountedCompleter has
- * only a local effect on that completer, so is not often useful.
+ * {@link #complete}, {@link ForkJoinTask#cancel},
+ * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon
+ * exceptional completion of method {@code compute}. Upon any
+ * exceptional completion, the exception may be relayed to a task's
+ * completer (and its completer, and so on), if one exists and it has
+ * not otherwise already completed. Similarly, cancelling an internal
+ * CountedCompleter has only a local effect on that completer, so is
+ * not often useful.
*
* <p><b>Sample Usages.</b>
*
@@ -96,8 +99,8 @@ package java.util.concurrent;
* improve load balancing. In the recursive case, the second of each
* pair of subtasks to finish triggers completion of its parent
* (because no result combination is performed, the default no-op
- * implementation of method {@code onCompletion} is not overridden). A
- * static utility method sets up the base task and invokes it
+ * implementation of method {@code onCompletion} is not overridden).
+ * A static utility method sets up the base task and invokes it
* (here, implicitly using the {@link ForkJoinPool#commonPool()}).
*
* <pre> {@code
@@ -152,12 +155,11 @@ package java.util.concurrent;
* }
* }</pre>
*
- * As a further improvement, notice that the left task need not even
- * exist. Instead of creating a new one, we can iterate using the
- * original task, and add a pending count for each fork. Additionally,
- * because no task in this tree implements an {@link #onCompletion}
- * method, {@code tryComplete()} can be replaced with {@link
- * #propagateCompletion}.
+ * As a further improvement, notice that the left task need not even exist.
+ * Instead of creating a new one, we can iterate using the original task,
+ * and add a pending count for each fork. Additionally, because no task
+ * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
+ * {@code tryComplete()} can be replaced with {@link #propagateCompletion}.
*
* <pre> {@code
* class ForEach<E> ...
@@ -235,7 +237,7 @@ package java.util.concurrent;
*
* <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
* results of multiple subtasks usually need to access these results
- * in method {@link #onCompletion}. As illustrated in the following
+ * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
* class (that performs a simplified form of map-reduce where mappings
* and reductions are all of type {@code E}), one way to do this in
* divide and conquer designs is to have each subtask record its
@@ -357,7 +359,7 @@ package java.util.concurrent;
*
* <p><b>Triggers.</b> Some CountedCompleters are themselves never
* forked, but instead serve as bits of plumbing in other designs;
- * including those in which the completion of one of more async tasks
+ * including those in which the completion of one or more async tasks
* triggers another async task. For example:
*
* <pre> {@code
@@ -438,20 +440,21 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
}
/**
- * Performs an action when method {@link #completeExceptionally}
- * is invoked or method {@link #compute} throws an exception, and
- * this task has not otherwise already completed normally. On
- * entry to this method, this task {@link
- * ForkJoinTask#isCompletedAbnormally}. The return value of this
- * method controls further propagation: If {@code true} and this
- * task has a completer, then this completer is also completed
- * exceptionally. The default implementation of this method does
- * nothing except return {@code true}.
+ * Performs an action when method {@link
+ * #completeExceptionally(Throwable)} is invoked or method {@link
+ * #compute} throws an exception, and this task has not already
+ * otherwise completed normally. On entry to this method, this task
+ * {@link ForkJoinTask#isCompletedAbnormally}. The return value
+ * of this method controls further propagation: If {@code true}
+ * and this task has a completer that has not completed, then that
+ * completer is also completed exceptionally, with the same
+ * exception as this completer. The default implementation of
+ * this method does nothing except return {@code true}.
*
* @param ex the exception
* @param caller the task invoking this method (which may
* be this task itself)
- * @return true if this exception should be propagated to this
+ * @return {@code true} if this exception should be propagated to this
* task's completer, if one exists
*/
public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
@@ -492,7 +495,7 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
* @param delta the value to add
*/
public final void addToPendingCount(int delta) {
- int c; // note: can replace with intrinsic in jdk8
+ int c;
do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta));
}
@@ -502,7 +505,7 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
*
* @param expected the expected value
* @param count the new value
- * @return true if successful
+ * @return {@code true} if successful
*/
public final boolean compareAndSetPendingCount(int expected, int count) {
return U.compareAndSwapInt(this, PENDING, expected, count);
@@ -536,9 +539,9 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
/**
* If the pending count is nonzero, decrements the count;
- * otherwise invokes {@link #onCompletion} and then similarly
- * tries to complete this task's completer, if one exists,
- * else marks this task as complete.
+ * otherwise invokes {@link #onCompletion(CountedCompleter)}
+ * and then similarly tries to complete this task's completer,
+ * if one exists, else marks this task as complete.
*/
public final void tryComplete() {
CountedCompleter<?> a = this, s = a;
@@ -557,12 +560,12 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
/**
* Equivalent to {@link #tryComplete} but does not invoke {@link
- * #onCompletion} along the completion path: If the pending count
- * is nonzero, decrements the count; otherwise, similarly tries to
- * complete this task's completer, if one exists, else marks this
- * task as complete. This method may be useful in cases where
- * {@code onCompletion} should not, or need not, be invoked for
- * each completer in a computation.
+ * #onCompletion(CountedCompleter)} along the completion path:
+ * If the pending count is nonzero, decrements the count;
+ * otherwise, similarly tries to complete this task's completer, if
+ * one exists, else marks this task as complete. This method may be
+ * useful in cases where {@code onCompletion} should not, or need
+ * not, be invoked for each completer in a computation.
*/
public final void propagateCompletion() {
CountedCompleter<?> a = this, s = a;
@@ -579,13 +582,15 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
}
/**
- * Regardless of pending count, invokes {@link #onCompletion},
- * marks this task as complete and further triggers {@link
- * #tryComplete} on this task's completer, if one exists. The
- * given rawResult is used as an argument to {@link #setRawResult}
- * before invoking {@link #onCompletion} or marking this task as
- * complete; its value is meaningful only for classes overriding
- * {@code setRawResult}.
+ * Regardless of pending count, invokes
+ * {@link #onCompletion(CountedCompleter)}, marks this task as
+ * complete and further triggers {@link #tryComplete} on this
+ * task's completer, if one exists. The given rawResult is
+ * used as an argument to {@link #setRawResult} before invoking
+ * {@link #onCompletion(CountedCompleter)} or marking this task
+ * as complete; its value is meaningful only for classes
+ * overriding {@code setRawResult}. This method does not modify
+ * the pending count.
*
* <p>This method may be useful when forcing completion as soon as
* any one (versus all) of several subtask results are obtained.
@@ -604,7 +609,6 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
p.tryComplete();
}
-
/**
* If this task's pending count is zero, returns this task;
* otherwise decrements its pending count and returns {@code
@@ -668,8 +672,9 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
void internalPropagateException(Throwable ex) {
CountedCompleter<?> a = this, s = a;
while (a.onExceptionalCompletion(ex, s) &&
- (a = (s = a).completer) != null && a.status >= 0)
- a.recordExceptionalCompletion(ex);
+ (a = (s = a).completer) != null && a.status >= 0 &&
+ a.recordExceptionalCompletion(ex) == EXCEPTIONAL)
+ ;
}
/**
diff --git a/luni/src/main/java/java/util/concurrent/ForkJoinPool.java b/luni/src/main/java/java/util/concurrent/ForkJoinPool.java
index 87ffff3..9448616 100644
--- a/luni/src/main/java/java/util/concurrent/ForkJoinPool.java
+++ b/luni/src/main/java/java/util/concurrent/ForkJoinPool.java
@@ -6,6 +6,7 @@
package java.util.concurrent;
+import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -17,6 +18,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RunnableFuture;
+import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
@@ -37,7 +39,7 @@ import java.util.concurrent.TimeUnit;
* ForkJoinPool}s may also be appropriate for use with event-style
* tasks that are never joined.
*
- * <p>A static {@link #commonPool()} is available and appropriate for
+ * <p>A static {@code commonPool()} is available and appropriate for
* most applications. The common pool is used by any ForkJoinTask that
* is not explicitly submitted to a specified pool. Using the common
* pool normally reduces resource usage (its threads are slowly
@@ -49,9 +51,9 @@ import java.util.concurrent.TimeUnit;
* level; by default, equal to the number of available processors. The
* pool attempts to maintain enough active (or available) threads by
* dynamically adding, suspending, or resuming internal worker
- * threads, even if some tasks are stalled waiting to join
- * others. However, no such adjustments are guaranteed in the face of
- * blocked I/O or other unmanaged synchronization. The nested {@link
+ * threads, even if some tasks are stalled waiting to join others.
+ * However, no such adjustments are guaranteed in the face of blocked
+ * I/O or other unmanaged synchronization. The nested {@link
* ManagedBlocker} interface enables extension of the kinds of
* synchronization accommodated.
*
@@ -75,38 +77,45 @@ import java.util.concurrent.TimeUnit;
* there is little difference among choice of methods.
*
* <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Summary of task execution methods</caption>
* <tr>
* <td></td>
* <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
* <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
* </tr>
* <tr>
- * <td> <b>Arrange async execution</td>
+ * <td> <b>Arrange async execution</b></td>
* <td> {@link #execute(ForkJoinTask)}</td>
* <td> {@link ForkJoinTask#fork}</td>
* </tr>
* <tr>
- * <td> <b>Await and obtain result</td>
+ * <td> <b>Await and obtain result</b></td>
* <td> {@link #invoke(ForkJoinTask)}</td>
* <td> {@link ForkJoinTask#invoke}</td>
* </tr>
* <tr>
- * <td> <b>Arrange exec and obtain Future</td>
+ * <td> <b>Arrange exec and obtain Future</b></td>
* <td> {@link #submit(ForkJoinTask)}</td>
* <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
* </tr>
* </table>
*
* <p>The common pool is by default constructed with default
- * parameters, but these may be controlled by setting three {@link
- * System#getProperty system properties} with prefix {@code
- * java.util.concurrent.ForkJoinPool.common}: {@code parallelism} --
- * an integer greater than zero, {@code threadFactory} -- the class
- * name of a {@link ForkJoinWorkerThreadFactory}, and {@code
- * exceptionHandler} -- the class name of a {@link
- * java.lang.Thread.UncaughtExceptionHandler
- * Thread.UncaughtExceptionHandler}. Upon any error in establishing
- * these settings, default parameters are used.
+ * parameters, but these may be controlled by setting three
+ * {@linkplain System#getProperty system properties}:
+ * <ul>
+ * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
+ * - the parallelism level, a non-negative integer
+ * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
+ * - the class name of a {@link ForkJoinWorkerThreadFactory}
+ * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
+ * - the class name of a {@link UncaughtExceptionHandler}
+ * </ul>
+ * The system class loader is used to load these classes.
+ * Upon any error in establishing these settings, default parameters
+ * are used. It is possible to disable or limit the use of threads in
+ * the common pool by setting the parallelism property to zero, and/or
+ * using a factory that may return {@code null}.
*
* <p><b>Implementation notes</b>: This implementation restricts the
* maximum number of running threads to 32767. Attempts to create
@@ -118,7 +127,6 @@ import java.util.concurrent.TimeUnit;
* or internal resources have been exhausted.
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public class ForkJoinPool extends AbstractExecutorService {
@@ -153,32 +161,35 @@ public class ForkJoinPool extends AbstractExecutorService {
* (http://research.sun.com/scalable/pubs/index.html) and
* "Idempotent work stealing" by Michael, Saraswat, and Vechev,
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
- * The main differences ultimately stem from GC requirements that
- * we null out taken slots as soon as we can, to maintain as small
- * a footprint as possible even in programs generating huge
- * numbers of tasks. To accomplish this, we shift the CAS
- * arbitrating pop vs poll (steal) from being on the indices
- * ("base" and "top") to the slots themselves. So, both a
- * successful pop and poll mainly entail a CAS of a slot from
- * non-null to null. Because we rely on CASes of references, we
- * do not need tag bits on base or top. They are simple ints as
- * used in any circular array-based queue (see for example
- * ArrayDeque). Updates to the indices must still be ordered in a
- * way that guarantees that top == base means the queue is empty,
- * but otherwise may err on the side of possibly making the queue
- * appear nonempty when a push, pop, or poll have not fully
- * committed. Note that this means that the poll operation,
- * considered individually, is not wait-free. One thief cannot
- * successfully continue until another in-progress one (or, if
- * previously empty, a push) completes. However, in the
- * aggregate, we ensure at least probabilistic non-blockingness.
- * If an attempted steal fails, a thief always chooses a different
- * random victim target to try next. So, in order for one thief to
- * progress, it suffices for any in-progress poll or new push on
- * any empty queue to complete. (This is why we normally use
- * method pollAt and its variants that try once at the apparent
- * base index, else consider alternative actions, rather than
- * method poll.)
+ * See also "Correct and Efficient Work-Stealing for Weak Memory
+ * Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
+ * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
+ * analysis of memory ordering (atomic, volatile etc) issues. The
+ * main differences ultimately stem from GC requirements that we
+ * null out taken slots as soon as we can, to maintain as small a
+ * footprint as possible even in programs generating huge numbers
+ * of tasks. To accomplish this, we shift the CAS arbitrating pop
+ * vs poll (steal) from being on the indices ("base" and "top") to
+ * the slots themselves. So, both a successful pop and poll
+ * mainly entail a CAS of a slot from non-null to null. Because
+ * we rely on CASes of references, we do not need tag bits on base
+ * or top. They are simple ints as used in any circular
+ * array-based queue (see for example ArrayDeque). Updates to the
+ * indices must still be ordered in a way that guarantees that top
+ * == base means the queue is empty, but otherwise may err on the
+ * side of possibly making the queue appear nonempty when a push,
+ * pop, or poll have not fully committed. Note that this means
+ * that the poll operation, considered individually, is not
+ * wait-free. One thief cannot successfully continue until another
+ * in-progress one (or, if previously empty, a push) completes.
+ * However, in the aggregate, we ensure at least probabilistic
+ * non-blockingness. If an attempted steal fails, a thief always
+ * chooses a different random victim target to try next. So, in
+ * order for one thief to progress, it suffices for any
+ * in-progress poll or new push on any empty queue to
+ * complete. (This is why we normally use method pollAt and its
+ * variants that try once at the apparent base index, else
+ * consider alternative actions, rather than method poll.)
*
* This approach also enables support of a user mode in which local
* task processing is in FIFO, not LIFO order, simply by using
@@ -197,18 +208,17 @@ public class ForkJoinPool extends AbstractExecutorService {
* for work-stealing (this would contaminate lifo/fifo
* processing). Instead, we randomly associate submission queues
* with submitting threads, using a form of hashing. The
- * ThreadLocal Submitter class contains a value initially used as
- * a hash code for choosing existing queues, but may be randomly
- * repositioned upon contention with other submitters. In
- * essence, submitters act like workers except that they are
- * restricted to executing local tasks that they submitted (or in
- * the case of CountedCompleters, others with the same root task).
- * However, because most shared/external queue operations are more
- * expensive than internal, and because, at steady state, external
- * submitters will compete for CPU with workers, ForkJoinTask.join
- * and related methods disable them from repeatedly helping to
- * process tasks if all workers are active. Insertion of tasks in
- * shared mode requires a lock (mainly to protect in the case of
+ * Submitter probe value serves as a hash code for
+ * choosing existing queues, and may be randomly repositioned upon
+ * contention with other submitters. In essence, submitters act
+ * like workers except that they are restricted to executing local
+ * tasks that they submitted. However, because most
+ * shared/external queue operations are more expensive than
+ * internal, and because, at steady state, external submitters
+ * will compete for CPU with workers, ForkJoinTask.join and
+ * related methods disable them from repeatedly helping to process
+ * tasks if all workers are active. Insertion of tasks in shared
+ * mode requires a lock (mainly to protect in the case of
* resizing) but we use only a simple spinlock (using bits in
* field qlock), because submitters encountering a busy queue move
* on to try or create other queues -- they block only when
@@ -298,37 +308,35 @@ public class ForkJoinPool extends AbstractExecutorService {
* has not yet entered the wait queue. We solve this by requiring
* a full sweep of all workers (via repeated calls to method
* scan()) both before and after a newly waiting worker is added
- * to the wait queue. During a rescan, the worker might release
- * some other queued worker rather than itself, which has the same
- * net effect. Because enqueued workers may actually be rescanning
- * rather than waiting, we set and clear the "parker" field of
- * WorkQueues to reduce unnecessary calls to unpark. (This
- * requires a secondary recheck to avoid missed signals.) Note
- * the unusual conventions about Thread.interrupts surrounding
- * parking and other blocking: Because interrupts are used solely
- * to alert threads to check termination, which is checked anyway
- * upon blocking, we clear status (using Thread.interrupted)
- * before any call to park, so that park does not immediately
- * return due to status being set via some other unrelated call to
- * interrupt in user code.
+ * to the wait queue. Because enqueued workers may actually be
+ * rescanning rather than waiting, we set and clear the "parker"
+ * field of WorkQueues to reduce unnecessary calls to unpark.
+ * (This requires a secondary recheck to avoid missed signals.)
+ * Note the unusual conventions about Thread.interrupts
+ * surrounding parking and other blocking: Because interrupts are
+ * used solely to alert threads to check termination, which is
+ * checked anyway upon blocking, we clear status (using
+ * Thread.interrupted) before any call to park, so that park does
+ * not immediately return due to status being set via some other
+ * unrelated call to interrupt in user code.
*
* Signalling. We create or wake up workers only when there
* appears to be at least one task they might be able to find and
- * execute. However, many other threads may notice the same task
- * and each signal to wake up a thread that might take it. So in
- * general, pools will be over-signalled. When a submission is
- * added or another worker adds a task to a queue that has fewer
- * than two tasks, they signal waiting workers (or trigger
- * creation of new ones if fewer than the given parallelism level
- * -- signalWork), and may leave a hint to the unparked worker to
- * help signal others upon wakeup). These primary signals are
- * buttressed by others (see method helpSignal) whenever other
- * threads scan for work or do not have a task to process. On
- * most platforms, signalling (unpark) overhead time is noticeably
+ * execute. When a submission is added or another worker adds a
+ * task to a queue that has fewer than two tasks, they signal
+ * waiting workers (or trigger creation of new ones if fewer than
+ * the given parallelism level -- signalWork). These primary
+ * signals are buttressed by others whenever other threads remove
+ * a task from a queue and notice that there are other tasks there
+ * as well. So in general, pools will be over-signalled. On most
+ * platforms, signalling (unpark) overhead time is noticeably
* long, and the time between signalling a thread and it actually
* making progress can be very noticeably long, so it is worth
* offloading these delays from critical paths as much as
- * possible.
+ * possible. Additionally, workers spin-down gradually, by staying
+ * alive so long as they see the ctl state changing. Similar
+ * stability-sensing techniques are also used before blocking in
+ * awaitJoin and helpComplete.
*
* Trimming workers. To release resources after periods of lack of
* use, a worker starting to wait when the pool is quiescent will
@@ -409,12 +417,6 @@ public class ForkJoinPool extends AbstractExecutorService {
* to find work (see MAX_HELP) and fall back to suspending the
* worker and if necessary replacing it with another.
*
- * Helping actions for CountedCompleters are much simpler: Method
- * helpComplete can take and execute any task with the same root
- * as the task being waited on. However, this still entails some
- * traversal of completer chains, so is less efficient than using
- * CountedCompleters without explicit joins.
- *
* It is impossible to keep exactly the target parallelism number
* of threads running at any given time. Determining the
* existence of conservatively safe helping targets, the
@@ -441,7 +443,7 @@ public class ForkJoinPool extends AbstractExecutorService {
* Common Pool
* ===========
*
- * The static commonPool always exists after static
+ * The static common pool always exists after static
* initialization. Since it (or any other created pool) need
* never be used, we minimize initial construction overhead and
* footprint to the setup of about a dozen fields, with no nested
@@ -449,8 +451,11 @@ public class ForkJoinPool extends AbstractExecutorService {
* fullExternalPush during the first submission to the pool.
*
* When external threads submit to the common pool, they can
- * perform some subtask processing (see externalHelpJoin and
- * related methods). We do not need to record whether these
+ * perform subtask processing (see externalHelpJoin and related
+ * methods). This caller-helps policy makes it sensible to set
+ * common pool parallelism level to one (or more) less than the
+ * total number of available cores, or even zero for pure
+ * caller-runs. We do not need to record whether external
* submissions are to the common pool -- if not, externalHelpJoin
* returns quickly (at the most helping to signal some common pool
* workers). These submitters would otherwise be blocked waiting
@@ -520,6 +525,7 @@ public class ForkJoinPool extends AbstractExecutorService {
*
* @param pool the pool this thread works in
* @throws NullPointerException if the pool is null
+ * @return the new worker thread
*/
public ForkJoinWorkerThread newThread(ForkJoinPool pool);
}
@@ -536,26 +542,6 @@ public class ForkJoinPool extends AbstractExecutorService {
}
/**
- * Per-thread records for threads that submit to pools. Currently
- * holds only pseudo-random seed / index that is used to choose
- * submission queues in method externalPush. In the future, this may
- * also incorporate a means to implement different task rejection
- * and resubmission policies.
- *
- * Seeds for submitters and workers/workQueues work in basically
- * the same way but are initialized and updated using slightly
- * different mechanics. Both are initialized using the same
- * approach as in class ThreadLocal, where successive values are
- * unlikely to collide with previous values. Seeds are then
- * randomly modified upon collisions using xorshifts, which
- * requires a non-zero seed.
- */
- static final class Submitter {
- int seed;
- Submitter(int s) { seed = s; }
- }
-
- /**
* Class for artificial tasks that are used to replace the target
* of local joins if they are removed from an interior queue slot
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to
@@ -614,17 +600,8 @@ public class ForkJoinPool extends AbstractExecutorService {
* do not want multiple WorkQueue instances or multiple queue
* arrays sharing cache lines. (It would be best for queue objects
* and their arrays to share, but there is nothing available to
- * help arrange that). Unfortunately, because they are recorded
- * in a common array, WorkQueue instances are often moved to be
- * adjacent by garbage collectors. To reduce impact, we use field
- * padding that works OK on common platforms; this effectively
- * trades off slightly slower average field access for the sake of
- * avoiding really bad worst-case access. (Until better JVM
- * support is in place, this padding is dependent on transient
- * properties of JVM field layout rules.) We also take care in
- * allocating, sizing and resizing the array. Non-shared queue
- * arrays are initialized by workers before use. Others are
- * allocated on first use.
+ * help arrange that). The @Contended annotation alerts JVMs to
+ * try to keep instances apart.
*/
static final class WorkQueue {
/**
@@ -650,13 +627,12 @@ public class ForkJoinPool extends AbstractExecutorService {
// Heuristic padding to ameliorate unfortunate memory placements
volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
- int seed; // for random scanning; initialize nonzero
volatile int eventCount; // encoded inactivation count; < 0 if inactive
int nextWait; // encoded record of next event waiter
- int hint; // steal or signal hint (index)
- int poolIndex; // index of this queue in pool (or 0)
- final int mode; // 0: lifo, > 0: fifo, < 0: shared
int nsteals; // number of steals
+ int hint; // steal index hint
+ short poolIndex; // index of this queue in pool
+ final short mode; // 0: lifo, > 0: fifo, < 0: shared
volatile int qlock; // 1: locked, -1: terminate; else 0
volatile int base; // index of next slot for poll
int top; // index of next slot for push
@@ -674,8 +650,8 @@ public class ForkJoinPool extends AbstractExecutorService {
int seed) {
this.pool = pool;
this.owner = owner;
- this.mode = mode;
- this.seed = seed;
+ this.mode = (short)mode;
+ this.hint = seed; // store initial seed for runWorker
// Place indices in the center of array (that is not yet allocated)
base = top = INITIAL_QUEUE_CAPACITY >>> 1;
}
@@ -688,7 +664,7 @@ public class ForkJoinPool extends AbstractExecutorService {
return (n >= 0) ? 0 : -n; // ignore transient negative
}
- /**
+ /**
* Provides a more accurate estimate of whether this queue has
* any tasks than does queueSize, by checking whether a
* near-empty queue has at least one unclaimed task.
@@ -713,20 +689,18 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
final void push(ForkJoinTask<?> task) {
ForkJoinTask<?>[] a; ForkJoinPool p;
- int s = top, m, n;
+ int s = top, n;
if ((a = array) != null) { // ignore if queue removed
- int j = (((m = a.length - 1) & s) << ASHIFT) + ABASE;
- U.putOrderedObject(a, j, task);
- if ((n = (top = s + 1) - base) <= 2) {
- if ((p = pool) != null)
- p.signalWork(this);
- }
+ int m = a.length - 1;
+ U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task);
+ if ((n = (top = s + 1) - base) <= 2)
+ (p = pool).signalWork(p.workQueues, this);
else if (n >= m)
growArray();
}
}
- /**
+ /**
* Initializes or doubles the capacity of array. Call either
* by owner or with lock held -- it is OK for base, but not
* top, to move while resizings are in progress.
@@ -784,9 +758,8 @@ public class ForkJoinPool extends AbstractExecutorService {
if ((a = array) != null) {
int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
- base == b &&
- U.compareAndSwapObject(a, j, t, null)) {
- base = b + 1;
+ base == b && U.compareAndSwapObject(a, j, t, null)) {
+ U.putOrderedInt(this, QBASE, b + 1);
return t;
}
}
@@ -802,9 +775,8 @@ public class ForkJoinPool extends AbstractExecutorService {
int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
if (t != null) {
- if (base == b &&
- U.compareAndSwapObject(a, j, t, null)) {
- base = b + 1;
+ if (U.compareAndSwapObject(a, j, t, null)) {
+ U.putOrderedInt(this, QBASE, b + 1);
return t;
}
}
@@ -861,46 +833,43 @@ public class ForkJoinPool extends AbstractExecutorService {
ForkJoinTask.cancelIgnoringExceptions(t);
}
- /**
- * Computes next value for random probes. Scans don't require
- * a very high quality generator, but also not a crummy one.
- * Marsaglia xor-shift is cheap and works well enough. Note:
- * This is manually inlined in its usages in ForkJoinPool to
- * avoid writes inside busy scan loops.
- */
- final int nextSeed() {
- int r = seed;
- r ^= r << 13;
- r ^= r >>> 17;
- return seed = r ^= r << 5;
- }
-
// Specialized execution methods
/**
- * Pops and runs tasks until empty.
+ * Polls and runs tasks until empty.
*/
- private void popAndExecAll() {
- // A bit faster than repeated pop calls
- ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
- while ((a = array) != null && (m = a.length - 1) >= 0 &&
- (s = top - 1) - base >= 0 &&
- (t = ((ForkJoinTask<?>)
- U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
- != null) {
- if (U.compareAndSwapObject(a, j, t, null)) {
- top = s;
- t.doExec();
- }
- }
+ final void pollAndExecAll() {
+ for (ForkJoinTask<?> t; (t = poll()) != null;)
+ t.doExec();
}
/**
- * Polls and runs tasks until empty.
+ * Executes a top-level task and any local tasks remaining
+ * after execution.
*/
- private void pollAndExecAll() {
- for (ForkJoinTask<?> t; (t = poll()) != null;)
- t.doExec();
+ final void runTask(ForkJoinTask<?> task) {
+ if ((currentSteal = task) != null) {
+ task.doExec();
+ ForkJoinTask<?>[] a = array;
+ int md = mode;
+ ++nsteals;
+ currentSteal = null;
+ if (md != 0)
+ pollAndExecAll();
+ else if (a != null) {
+ int s, m = a.length - 1;
+ while ((s = top - 1) - base >= 0) {
+ long i = ((m & s) << ASHIFT) + ABASE;
+ ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObject(a, i);
+ if (t == null)
+ break;
+ if (U.compareAndSwapObject(a, i, t, null)) {
+ top = s;
+ t.doExec();
+ }
+ }
+ }
+ }
}
/**
@@ -911,13 +880,15 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return false if no progress can be made, else true
*/
final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
- boolean stat = true, removed = false, empty = true;
+ boolean stat;
ForkJoinTask<?>[] a; int m, s, b, n;
- if ((a = array) != null && (m = a.length - 1) >= 0 &&
+ if (task != null && (a = array) != null && (m = a.length - 1) >= 0 &&
(n = (s = top) - (b = base)) > 0) {
+ boolean removed = false, empty = true;
+ stat = true;
for (ForkJoinTask<?> t;;) { // traverse from s to b
- int j = ((--s & m) << ASHIFT) + ABASE;
- t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
+ long j = ((--s & m) << ASHIFT) + ABASE;
+ t = (ForkJoinTask<?>)U.getObject(a, j);
if (t == null) // inconsistent length
break;
else if (t == task) {
@@ -945,68 +916,95 @@ public class ForkJoinPool extends AbstractExecutorService {
break;
}
}
+ if (removed)
+ task.doExec();
}
- if (removed)
- task.doExec();
+ else
+ stat = false;
return stat;
}
/**
- * Polls for and executes the given task or any other task in
- * its CountedCompleter computation.
+ * Tries to poll for and execute the given task or any other
+ * task in its CountedCompleter computation.
*/
- final boolean pollAndExecCC(ForkJoinTask<?> root) {
- ForkJoinTask<?>[] a; int b; Object o;
- outer: while ((b = base) - top < 0 && (a = array) != null) {
+ final boolean pollAndExecCC(CountedCompleter<?> root) {
+ ForkJoinTask<?>[] a; int b; Object o; CountedCompleter<?> t, r;
+ if ((b = base) - top < 0 && (a = array) != null) {
long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
- if ((o = U.getObject(a, j)) == null ||
- !(o instanceof CountedCompleter))
- break;
- for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) {
- if (r == root) {
- if (base == b &&
- U.compareAndSwapObject(a, j, t, null)) {
- base = b + 1;
- t.doExec();
+ if ((o = U.getObjectVolatile(a, j)) == null)
+ return true; // retry
+ if (o instanceof CountedCompleter) {
+ for (t = (CountedCompleter<?>)o, r = t;;) {
+ if (r == root) {
+ if (base == b &&
+ U.compareAndSwapObject(a, j, t, null)) {
+ U.putOrderedInt(this, QBASE, b + 1);
+ t.doExec();
+ }
return true;
}
- else
- break; // restart
+ else if ((r = r.completer) == null)
+ break; // not part of root computation
}
- if ((r = r.completer) == null)
- break outer; // not part of root computation
}
}
return false;
}
/**
- * Executes a top-level task and any local tasks remaining
- * after execution.
+ * Tries to pop and execute the given task or any other task
+ * in its CountedCompleter computation.
*/
- final void runTask(ForkJoinTask<?> t) {
- if (t != null) {
- (currentSteal = t).doExec();
- currentSteal = null;
- ++nsteals;
- if (base - top < 0) { // process remaining local tasks
- if (mode == 0)
- popAndExecAll();
- else
- pollAndExecAll();
+ final boolean externalPopAndExecCC(CountedCompleter<?> root) {
+ ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
+ if (base - (s = top) < 0 && (a = array) != null) {
+ long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
+ if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
+ for (t = (CountedCompleter<?>)o, r = t;;) {
+ if (r == root) {
+ if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
+ if (top == s && array == a &&
+ U.compareAndSwapObject(a, j, t, null)) {
+ top = s - 1;
+ qlock = 0;
+ t.doExec();
+ }
+ else
+ qlock = 0;
+ }
+ return true;
+ }
+ else if ((r = r.completer) == null)
+ break;
+ }
}
}
+ return false;
}
/**
- * Executes a non-top-level (stolen) task.
+ * Internal version
*/
- final void runSubtask(ForkJoinTask<?> t) {
- if (t != null) {
- ForkJoinTask<?> ps = currentSteal;
- (currentSteal = t).doExec();
- currentSteal = ps;
+ final boolean internalPopAndExecCC(CountedCompleter<?> root) {
+ ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
+ if (base - (s = top) < 0 && (a = array) != null) {
+ long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
+ if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
+ for (t = (CountedCompleter<?>)o, r = t;;) {
+ if (r == root) {
+ if (U.compareAndSwapObject(a, j, t, null)) {
+ top = s - 1;
+ t.doExec();
+ }
+ return true;
+ }
+ else if ((r = r.completer) == null)
+ break;
+ }
+ }
}
+ return false;
}
/**
@@ -1023,6 +1021,7 @@ public class ForkJoinPool extends AbstractExecutorService {
// Unsafe mechanics
private static final sun.misc.Unsafe U;
+ private static final long QBASE;
private static final long QLOCK;
private static final int ABASE;
private static final int ASHIFT;
@@ -1031,6 +1030,8 @@ public class ForkJoinPool extends AbstractExecutorService {
U = sun.misc.Unsafe.getUnsafe();
Class<?> k = WorkQueue.class;
Class<?> ak = ForkJoinTask[].class;
+ QBASE = U.objectFieldOffset
+ (k.getDeclaredField("base"));
QLOCK = U.objectFieldOffset
(k.getDeclaredField("qlock"));
ABASE = U.arrayBaseOffset(ak);
@@ -1047,13 +1048,6 @@ public class ForkJoinPool extends AbstractExecutorService {
// static fields (initialized in static initializer below)
/**
- * Creates a new ForkJoinWorkerThread. This factory is used unless
- * overridden in ForkJoinPool constructors.
- */
- public static final ForkJoinWorkerThreadFactory
- defaultForkJoinWorkerThreadFactory;
-
- /**
* Per-thread submission bookkeeping. Shared across all pools
* to reduce ThreadLocal pollution and because random motion
* to avoid contention in one pool is likely to hold for others.
@@ -1063,6 +1057,13 @@ public class ForkJoinPool extends AbstractExecutorService {
static final ThreadLocal<Submitter> submitters;
/**
+ * Creates a new ForkJoinWorkerThread. This factory is used unless
+ * overridden in ForkJoinPool constructors.
+ */
+ public static final ForkJoinWorkerThreadFactory
+ defaultForkJoinWorkerThreadFactory;
+
+ /**
* Permission required for callers of methods that may start or
* kill threads.
*/
@@ -1074,12 +1075,15 @@ public class ForkJoinPool extends AbstractExecutorService {
* to paranoically avoid potential initialization circularities
* as well as to simplify generated code.
*/
- static final ForkJoinPool commonPool;
+ static final ForkJoinPool common;
/**
- * Common pool parallelism. Must equal commonPool.parallelism.
+ * Common pool parallelism. To allow simpler use and management
+ * when common pool threads are disabled, we allow the underlying
+ * common.parallelism field to be zero, but in that case still report
+ * parallelism as 1 to reflect resulting caller-runs mechanics.
*/
- static final int commonPoolParallelism;
+ static final int commonParallelism;
/**
* Sequence number for creating workerNamePrefix.
@@ -1114,7 +1118,7 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Tolerance for idle timeouts, to cope with timer undershoots
*/
- private static final long TIMEOUT_SLOP = 2000000L; // 20ms
+ private static final long TIMEOUT_SLOP = 2000000L;
/**
* The maximum stolen->joining link depth allowed in method
@@ -1216,30 +1220,19 @@ public class ForkJoinPool extends AbstractExecutorService {
static final int FIFO_QUEUE = 1;
static final int SHARED_QUEUE = -1;
- // bounds for #steps in scan loop -- must be power 2 minus 1
- private static final int MIN_SCAN = 0x1ff; // cover estimation slop
- private static final int MAX_SCAN = 0x1ffff; // 4 * max workers
-
- // Instance fields
-
- /*
- * Field layout of this class tends to matter more than one would
- * like. Runtime layout order is only loosely related to
- * declaration order and may differ across JVMs, but the following
- * empirically works OK on current JVMs.
- */
-
// Heuristic padding to ameliorate unfortunate memory placements
volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
+ // Instance fields
volatile long stealCount; // collects worker counts
volatile long ctl; // main pool control
volatile int plock; // shutdown status and seqLock
volatile int indexSeed; // worker/submitter index seed
- final int config; // mode and parallelism level
+ final short parallelism; // parallelism level
+ final short mode; // LIFO/FIFO
WorkQueue[] workQueues; // main registry
final ForkJoinWorkerThreadFactory factory;
- final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
+ final UncaughtExceptionHandler ueh; // per-worker UEH
final String workerNamePrefix; // to create worker name string
volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
@@ -1254,24 +1247,13 @@ public class ForkJoinPool extends AbstractExecutorService {
* a more conservative alternative to a pure spinlock.
*/
private int acquirePlock() {
- int spins = PL_SPINS, r = 0, ps, nps;
+ int spins = PL_SPINS, ps, nps;
for (;;) {
if (((ps = plock) & PL_LOCK) == 0 &&
U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
return nps;
- else if (r == 0) { // randomize spins if possible
- Thread t = Thread.currentThread(); WorkQueue w; Submitter z;
- if ((t instanceof ForkJoinWorkerThread) &&
- (w = ((ForkJoinWorkerThread)t).workQueue) != null)
- r = w.seed;
- else if ((z = submitters.get()) != null)
- r = z.seed;
- else
- r = 1;
- }
else if (spins >= 0) {
- r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
- if (r >= 0)
+ if (ThreadLocalRandom.current().nextInt() >= 0)
--spins;
}
else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
@@ -1303,48 +1285,15 @@ public class ForkJoinPool extends AbstractExecutorService {
}
/**
- * Performs secondary initialization, called when plock is zero.
- * Creates workQueue array and sets plock to a valid value. The
- * lock body must be exception-free (so no try/finally) so we
- * optimistically allocate new array outside the lock and throw
- * away if (very rarely) not needed. (A similar tactic is used in
- * fullExternalPush.) Because the plock seq value can eventually
- * wrap around zero, this method harmlessly fails to reinitialize
- * if workQueues exists, while still advancing plock.
- *
- * Additionally tries to create the first worker.
- */
- private void initWorkers() {
- WorkQueue[] ws, nws; int ps;
- int p = config & SMASK; // find power of two table size
- int n = (p > 1) ? p - 1 : 1; // ensure at least 2 slots
- n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
- n = (n + 1) << 1;
- if ((ws = workQueues) == null || ws.length == 0)
- nws = new WorkQueue[n];
- else
- nws = null;
- if (((ps = plock) & PL_LOCK) != 0 ||
- !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
- ps = acquirePlock();
- if (((ws = workQueues) == null || ws.length == 0) && nws != null)
- workQueues = nws;
- int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
- if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
- releasePlock(nps);
- tryAddWorker();
- }
-
- /**
* Tries to create and start one worker if fewer than target
* parallelism level exist. Adjusts counts etc on failure.
*/
private void tryAddWorker() {
- long c; int u;
+ long c; int u, e;
while ((u = (int)((c = ctl) >>> 32)) < 0 &&
- (u & SHORT_SIGN) != 0 && (int)c == 0) {
- long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
- ((u + UAC_UNIT) & UAC_MASK)) << 32;
+ (u & SHORT_SIGN) != 0 && (e = (int)c) >= 0) {
+ long nc = ((long)(((u + UTC_UNIT) & UTC_MASK) |
+ ((u + UAC_UNIT) & UAC_MASK)) << 32) | (long)e;
if (U.compareAndSwapLong(this, CTL, c, nc)) {
ForkJoinWorkerThreadFactory fac;
Throwable ex = null;
@@ -1355,8 +1304,8 @@ public class ForkJoinPool extends AbstractExecutorService {
wt.start();
break;
}
- } catch (Throwable e) {
- ex = e;
+ } catch (Throwable rex) {
+ ex = rex;
}
deregisterWorker(wt, ex);
break;
@@ -1377,14 +1326,14 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return the worker's queue
*/
final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
- Thread.UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
+ UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
wt.setDaemon(true);
if ((handler = ueh) != null)
wt.setUncaughtExceptionHandler(handler);
do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed,
s += SEED_INCREMENT) ||
s == 0); // skip 0
- WorkQueue w = new WorkQueue(this, wt, config >>> 16, s);
+ WorkQueue w = new WorkQueue(this, wt, mode, s);
if (((ps = plock) & PL_LOCK) != 0 ||
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
ps = acquirePlock();
@@ -1404,14 +1353,15 @@ public class ForkJoinPool extends AbstractExecutorService {
}
}
}
- w.eventCount = w.poolIndex = r; // volatile write orders
+ w.poolIndex = (short)r;
+ w.eventCount = r; // volatile write orders
ws[r] = w;
}
} finally {
if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
releasePlock(nps);
}
- wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex)));
+ wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1)));
return w;
}
@@ -1421,17 +1371,17 @@ public class ForkJoinPool extends AbstractExecutorService {
* array, and adjusts counts. If pool is shutting down, tries to
* complete termination.
*
- * @param wt the worker thread or null if construction failed
+ * @param wt the worker thread, or null if construction failed
* @param ex the exception causing failure, or null if none
*/
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
WorkQueue w = null;
if (wt != null && (w = wt.workQueue) != null) {
- int ps;
+ int ps; long sc;
w.qlock = -1; // ensure set
- long ns = w.nsteals, sc; // collect steal count
do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
- sc = stealCount, sc + ns));
+ sc = stealCount,
+ sc + w.nsteals));
if (((ps = plock) & PL_LOCK) != 0 ||
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
ps = acquirePlock();
@@ -1460,7 +1410,7 @@ public class ForkJoinPool extends AbstractExecutorService {
if (e > 0) { // activate or create replacement
if ((ws = workQueues) == null ||
(i = e & SMASK) >= ws.length ||
- (v = ws[i]) != null)
+ (v = ws[i]) == null)
break;
long nc = (((long)(v.nextWait & E_MASK)) |
((long)(u + UAC_UNIT) << 32));
@@ -1489,6 +1439,26 @@ public class ForkJoinPool extends AbstractExecutorService {
// Submissions
/**
+ * Per-thread records for threads that submit to pools. Currently
+ * holds only pseudo-random seed / index that is used to choose
+ * submission queues in method externalPush. In the future, this may
+ * also incorporate a means to implement different task rejection
+ * and resubmission policies.
+ *
+ * Seeds for submitters and workers/workQueues work in basically
+ * the same way but are initialized and updated using slightly
+ * different mechanics. Both are initialized using the same
+ * approach as in class ThreadLocal, where successive values are
+ * unlikely to collide with previous values. Seeds are then
+ * randomly modified upon collisions using xorshifts, which
+ * requires a non-zero seed.
+ */
+ static final class Submitter {
+ int seed;
+ Submitter(int s) { seed = s; }
+ }
+
+ /**
* Unless shutting down, adds the given task to a submission queue
* at submitter's current queue index (modulo submission
* range). Only the most common path is directly handled in this
@@ -1497,19 +1467,21 @@ public class ForkJoinPool extends AbstractExecutorService {
* @param task the task. Caller must ensure non-null.
*/
final void externalPush(ForkJoinTask<?> task) {
- WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a;
- if ((z = submitters.get()) != null && plock > 0 &&
- (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
- (q = ws[m & z.seed & SQMASK]) != null &&
+ Submitter z = submitters.get();
+ WorkQueue q; int r, m, s, n, am; ForkJoinTask<?>[] a;
+ int ps = plock;
+ WorkQueue[] ws = workQueues;
+ if (z != null && ps > 0 && ws != null && (m = (ws.length - 1)) >= 0 &&
+ (q = ws[m & (r = z.seed) & SQMASK]) != null && r != 0 &&
U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
- int b = q.base, s = q.top, n, an;
- if ((a = q.array) != null && (an = a.length) > (n = s + 1 - b)) {
- int j = (((an - 1) & s) << ASHIFT) + ABASE;
+ if ((a = q.array) != null &&
+ (am = a.length - 1) > (n = (s = q.top) - q.base)) {
+ int j = ((am & s) << ASHIFT) + ABASE;
U.putOrderedObject(a, j, task);
q.top = s + 1; // push on to deque
q.qlock = 0;
- if (n <= 2)
- signalWork(q);
+ if (n <= 1)
+ signalWork(ws, q);
return;
}
q.qlock = 0;
@@ -1520,13 +1492,19 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Full version of externalPush. This method is called, among
* other times, upon the first submission of the first task to the
- * pool, so must perform secondary initialization (via
- * initWorkers). It also detects first submission by an external
- * thread by looking up its ThreadLocal, and creates a new shared
- * queue if the one at index if empty or contended. The plock lock
- * body must be exception-free (so no try/finally) so we
- * optimistically allocate new queues outside the lock and throw
- * them away if (very rarely) not needed.
+ * pool, so must perform secondary initialization. It also
+ * detects first submission by an external thread by looking up
+ * its ThreadLocal, and creates a new shared queue if the one at
+ * index if empty or contended. The plock lock body must be
+ * exception-free (so no try/finally) so we optimistically
+ * allocate new queues outside the lock and throw them away if
+ * (very rarely) not needed.
+ *
+ * Secondary initialization occurs when plock is zero, to create
+ * workQueue array and set plock to a valid value. This lock body
+ * must also be exception-free. Because the plock seq value can
+ * eventually wrap around zero, this method harmlessly fails to
+ * reinitialize if workQueues exists, while still advancing plock.
*/
private void fullExternalPush(ForkJoinTask<?> task) {
int r = 0; // random index seed
@@ -1537,17 +1515,31 @@ public class ForkJoinPool extends AbstractExecutorService {
r += SEED_INCREMENT) && r != 0)
submitters.set(z = new Submitter(r));
}
- else if (r == 0) { // move to a different index
+ else if (r == 0) { // move to a different index
r = z.seed;
- r ^= r << 13; // same xorshift as WorkQueues
+ r ^= r << 13; // same xorshift as WorkQueues
r ^= r >>> 17;
- z.seed = r ^ (r << 5);
+ z.seed = r ^= (r << 5);
}
- else if ((ps = plock) < 0)
+ if ((ps = plock) < 0)
throw new RejectedExecutionException();
else if (ps == 0 || (ws = workQueues) == null ||
- (m = ws.length - 1) < 0)
- initWorkers();
+ (m = ws.length - 1) < 0) { // initialize workQueues
+ int p = parallelism; // find power of two table size
+ int n = (p > 1) ? p - 1 : 1; // ensure at least 2 slots
+ n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
+ n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
+ WorkQueue[] nws = ((ws = workQueues) == null || ws.length == 0 ?
+ new WorkQueue[n] : null);
+ if (((ps = plock) & PL_LOCK) != 0 ||
+ !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+ ps = acquirePlock();
+ if (((ws = workQueues) == null || ws.length == 0) && nws != null)
+ workQueues = nws;
+ int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
+ if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+ releasePlock(nps);
+ }
else if ((q = ws[k = r & m & SQMASK]) != null) {
if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
ForkJoinTask<?>[] a = q.array;
@@ -1565,7 +1557,7 @@ public class ForkJoinPool extends AbstractExecutorService {
q.qlock = 0; // unlock
}
if (submitted) {
- signalWork(q);
+ signalWork(ws, q);
return;
}
}
@@ -1573,6 +1565,7 @@ public class ForkJoinPool extends AbstractExecutorService {
}
else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
q = new WorkQueue(this, null, SHARED_QUEUE, r);
+ q.poolIndex = (short)k;
if (((ps = plock) & PL_LOCK) != 0 ||
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
ps = acquirePlock();
@@ -1583,7 +1576,7 @@ public class ForkJoinPool extends AbstractExecutorService {
releasePlock(nps);
}
else
- r = 0; // try elsewhere while lock held
+ r = 0;
}
}
@@ -1594,41 +1587,42 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
final void incrementActiveCount() {
long c;
- do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
+ do {} while (!U.compareAndSwapLong
+ (this, CTL, c = ctl, ((c & ~AC_MASK) |
+ ((c & AC_MASK) + AC_UNIT))));
}
/**
* Tries to create or activate a worker if too few are active.
*
- * @param q the (non-null) queue holding tasks to be signalled
+ * @param ws the worker array to use to find signallees
+ * @param q if non-null, the queue holding tasks to be processed
*/
- final void signalWork(WorkQueue q) {
- int hint = q.poolIndex;
- long c; int e, u, i, n; WorkQueue[] ws; WorkQueue w; Thread p;
- while ((u = (int)((c = ctl) >>> 32)) < 0) {
- if ((e = (int)c) > 0) {
- if ((ws = workQueues) != null && ws.length > (i = e & SMASK) &&
- (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
- long nc = (((long)(w.nextWait & E_MASK)) |
- ((long)(u + UAC_UNIT) << 32));
- if (U.compareAndSwapLong(this, CTL, c, nc)) {
- w.hint = hint;
- w.eventCount = (e + E_SEQ) & E_MASK;
- if ((p = w.parker) != null)
- U.unpark(p);
- break;
- }
- if (q.top - q.base <= 0)
- break;
- }
- else
- break;
- }
- else {
+ final void signalWork(WorkQueue[] ws, WorkQueue q) {
+ for (;;) {
+ long c; int e, u, i; WorkQueue w; Thread p;
+ if ((u = (int)((c = ctl) >>> 32)) >= 0)
+ break;
+ if ((e = (int)c) <= 0) {
if ((short)u < 0)
tryAddWorker();
break;
}
+ if (ws == null || ws.length <= (i = e & SMASK) ||
+ (w = ws[i]) == null)
+ break;
+ long nc = (((long)(w.nextWait & E_MASK)) |
+ ((long)(u + UAC_UNIT)) << 32);
+ int ne = (e + E_SEQ) & E_MASK;
+ if (w.eventCount == (e | INT_SIGN) &&
+ U.compareAndSwapLong(this, CTL, c, nc)) {
+ w.eventCount = ne;
+ if ((p = w.parker) != null)
+ U.unpark(p);
+ break;
+ }
+ if (q != null && q.base >= q.top)
+ break;
}
}
@@ -1639,214 +1633,154 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
final void runWorker(WorkQueue w) {
w.growArray(); // allocate queue
- do { w.runTask(scan(w)); } while (w.qlock >= 0);
+ for (int r = w.hint; scan(w, r) == 0; ) {
+ r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
+ }
}
/**
- * Scans for and, if found, returns one task, else possibly
+ * Scans for and, if found, runs one task, else possibly
* inactivates the worker. This method operates on single reads of
* volatile state and is designed to be re-invoked continuously,
* in part because it returns upon detecting inconsistencies,
* contention, or state changes that indicate possible success on
* re-invocation.
*
- * The scan searches for tasks across queues (starting at a random
- * index, and relying on registerWorker to irregularly scatter
- * them within array to avoid bias), checking each at least twice.
- * The scan terminates upon either finding a non-empty queue, or
- * completing the sweep. If the worker is not inactivated, it
- * takes and returns a task from this queue. Otherwise, if not
- * activated, it signals workers (that may include itself) and
- * returns so caller can retry. Also returns for true if the
- * worker array may have changed during an empty scan. On failure
- * to find a task, we take one of the following actions, after
- * which the caller will retry calling this method unless
- * terminated.
- *
- * * If pool is terminating, terminate the worker.
- *
- * * If not already enqueued, try to inactivate and enqueue the
- * worker on wait queue. Or, if inactivating has caused the pool
- * to be quiescent, relay to idleAwaitWork to possibly shrink
- * pool.
- *
- * * If already enqueued and none of the above apply, possibly
- * park awaiting signal, else lingering to help scan and signal.
- *
- * * If a non-empty queue discovered or left as a hint,
- * help wake up other workers before return.
+ * The scan searches for tasks across queues starting at a random
+ * index, checking each at least twice. The scan terminates upon
+ * either finding a non-empty queue, or completing the sweep. If
+ * the worker is not inactivated, it takes and runs a task from
+ * this queue. Otherwise, if not activated, it tries to activate
+ * itself or some other worker by signalling. On failure to find a
+ * task, returns (for retry) if pool state may have changed during
+ * an empty scan, or tries to inactivate if active, else possibly
+ * blocks or terminates via method awaitWork.
*
* @param w the worker (via its WorkQueue)
- * @return a task or null if none found
+ * @param r a random seed
+ * @return worker qlock status if would have waited, else 0
*/
- private final ForkJoinTask<?> scan(WorkQueue w) {
+ private final int scan(WorkQueue w, int r) {
WorkQueue[] ws; int m;
- int ps = plock; // read plock before ws
- if (w != null && (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
- int ec = w.eventCount; // ec is negative if inactive
- int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
- w.hint = -1; // update seed and clear hint
- int j = ((m + m + 1) | MIN_SCAN) & MAX_SCAN;
- do {
- WorkQueue q; ForkJoinTask<?>[] a; int b;
- if ((q = ws[(r + j) & m]) != null && (b = q.base) - q.top < 0 &&
- (a = q.array) != null) { // probably nonempty
- int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
- ForkJoinTask<?> t = (ForkJoinTask<?>)
- U.getObjectVolatile(a, i);
- if (q.base == b && ec >= 0 && t != null &&
- U.compareAndSwapObject(a, i, t, null)) {
- if ((q.base = b + 1) - q.top < 0)
- signalWork(q);
- return t; // taken
- }
- else if ((ec < 0 || j < m) && (int)(ctl >> AC_SHIFT) <= 0) {
- w.hint = (r + j) & m; // help signal below
- break; // cannot take
+ long c = ctl; // for consistency check
+ if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 && w != null) {
+ for (int j = m + m + 1, ec = w.eventCount;;) {
+ WorkQueue q; int b, e; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
+ if ((q = ws[(r - j) & m]) != null &&
+ (b = q.base) - q.top < 0 && (a = q.array) != null) {
+ long i = (((a.length - 1) & b) << ASHIFT) + ABASE;
+ if ((t = ((ForkJoinTask<?>)
+ U.getObjectVolatile(a, i))) != null) {
+ if (ec < 0)
+ helpRelease(c, ws, w, q, b);
+ else if (q.base == b &&
+ U.compareAndSwapObject(a, i, t, null)) {
+ U.putOrderedInt(q, QBASE, b + 1);
+ if ((b + 1) - q.top < 0)
+ signalWork(ws, q);
+ w.runTask(t);
+ }
}
+ break;
}
- } while (--j >= 0);
-
- int h, e, ns; long c, sc; WorkQueue q;
- if ((ns = w.nsteals) != 0) {
- if (U.compareAndSwapLong(this, STEALCOUNT,
- sc = stealCount, sc + ns))
- w.nsteals = 0; // collect steals and rescan
- }
- else if (plock != ps) // consistency check
- ; // skip
- else if ((e = (int)(c = ctl)) < 0)
- w.qlock = -1; // pool is terminating
- else {
- if ((h = w.hint) < 0) {
- if (ec >= 0) { // try to enqueue/inactivate
- long nc = (((long)ec |
- ((c - AC_UNIT) & (AC_MASK|TC_MASK))));
- w.nextWait = e; // link and mark inactive
+ else if (--j < 0) {
+ if ((ec | (e = (int)c)) < 0) // inactive or terminating
+ return awaitWork(w, c, ec);
+ else if (ctl == c) { // try to inactivate and enqueue
+ long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
+ w.nextWait = e;
w.eventCount = ec | INT_SIGN;
- if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
- w.eventCount = ec; // unmark on CAS failure
- else if ((int)(c >> AC_SHIFT) == 1 - (config & SMASK))
- idleAwaitWork(w, nc, c);
- }
- else if (w.eventCount < 0 && !tryTerminate(false, false) &&
- ctl == c) { // block
- Thread wt = Thread.currentThread();
- Thread.interrupted(); // clear status
- U.putObject(wt, PARKBLOCKER, this);
- w.parker = wt; // emulate LockSupport.park
- if (w.eventCount < 0) // recheck
- U.park(false, 0L);
- w.parker = null;
- U.putObject(wt, PARKBLOCKER, null);
- }
- }
- if ((h >= 0 || (h = w.hint) >= 0) &&
- (ws = workQueues) != null && h < ws.length &&
- (q = ws[h]) != null) { // signal others before retry
- WorkQueue v; Thread p; int u, i, s;
- for (int n = (config & SMASK) >>> 1;;) {
- int idleCount = (w.eventCount < 0) ? 0 : -1;
- if (((s = idleCount - q.base + q.top) <= n &&
- (n = s) <= 0) ||
- (u = (int)((c = ctl) >>> 32)) >= 0 ||
- (e = (int)c) <= 0 || m < (i = e & SMASK) ||
- (v = ws[i]) == null)
- break;
- long nc = (((long)(v.nextWait & E_MASK)) |
- ((long)(u + UAC_UNIT) << 32));
- if (v.eventCount != (e | INT_SIGN) ||
- !U.compareAndSwapLong(this, CTL, c, nc))
- break;
- v.hint = h;
- v.eventCount = (e + E_SEQ) & E_MASK;
- if ((p = v.parker) != null)
- U.unpark(p);
- if (--n <= 0)
- break;
+ if (!U.compareAndSwapLong(this, CTL, c, nc))
+ w.eventCount = ec; // back out
}
+ break;
}
}
}
- return null;
+ return 0;
}
/**
- * If inactivating worker w has caused the pool to become
- * quiescent, checks for pool termination, and, so long as this is
- * not the only worker, waits for event for up to a given
- * duration. On timeout, if ctl has not changed, terminates the
- * worker, which will in turn wake up another worker to possibly
- * repeat this process.
+ * A continuation of scan(), possibly blocking or terminating
+ * worker w. Returns without blocking if pool state has apparently
+ * changed since last invocation. Also, if inactivating w has
+ * caused the pool to become quiescent, checks for pool
+ * termination, and, so long as this is not the only worker, waits
+ * for event for up to a given duration. On timeout, if ctl has
+ * not changed, terminates the worker, which will in turn wake up
+ * another worker to possibly repeat this process.
*
* @param w the calling worker
- * @param currentCtl the ctl value triggering possible quiescence
- * @param prevCtl the ctl value to restore if thread is terminated
- */
- private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
- if (w != null && w.eventCount < 0 &&
- !tryTerminate(false, false) && (int)prevCtl != 0) {
- int dc = -(short)(currentCtl >>> TC_SHIFT);
- long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
- long deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
- Thread wt = Thread.currentThread();
- while (ctl == currentCtl) {
- Thread.interrupted(); // timed variant of version in scan()
- U.putObject(wt, PARKBLOCKER, this);
- w.parker = wt;
- if (ctl == currentCtl)
- U.park(false, parkTime);
- w.parker = null;
- U.putObject(wt, PARKBLOCKER, null);
- if (ctl != currentCtl)
- break;
- if (deadline - System.nanoTime() <= 0L &&
- U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
- w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
- w.qlock = -1; // shrink
- break;
+ * @param c the ctl value on entry to scan
+ * @param ec the worker's eventCount on entry to scan
+ */
+ private final int awaitWork(WorkQueue w, long c, int ec) {
+ int stat, ns; long parkTime, deadline;
+ if ((stat = w.qlock) >= 0 && w.eventCount == ec && ctl == c &&
+ !Thread.interrupted()) {
+ int e = (int)c;
+ int u = (int)(c >>> 32);
+ int d = (u >> UAC_SHIFT) + parallelism; // active count
+
+ if (e < 0 || (d <= 0 && tryTerminate(false, false)))
+ stat = w.qlock = -1; // pool is terminating
+ else if ((ns = w.nsteals) != 0) { // collect steals and retry
+ long sc;
+ w.nsteals = 0;
+ do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
+ sc = stealCount, sc + ns));
+ }
+ else {
+ long pc = ((d > 0 || ec != (e | INT_SIGN)) ? 0L :
+ ((long)(w.nextWait & E_MASK)) | // ctl to restore
+ ((long)(u + UAC_UNIT)) << 32);
+ if (pc != 0L) { // timed wait if last waiter
+ int dc = -(short)(c >>> TC_SHIFT);
+ parkTime = (dc < 0 ? FAST_IDLE_TIMEOUT:
+ (dc + 1) * IDLE_TIMEOUT);
+ deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
+ }
+ else
+ parkTime = deadline = 0L;
+ if (w.eventCount == ec && ctl == c) {
+ Thread wt = Thread.currentThread();
+ U.putObject(wt, PARKBLOCKER, this);
+ w.parker = wt; // emulate LockSupport.park
+ if (w.eventCount == ec && ctl == c)
+ U.park(false, parkTime); // must recheck before park
+ w.parker = null;
+ U.putObject(wt, PARKBLOCKER, null);
+ if (parkTime != 0L && ctl == c &&
+ deadline - System.nanoTime() <= 0L &&
+ U.compareAndSwapLong(this, CTL, c, pc))
+ stat = w.qlock = -1; // shrink pool
}
}
}
+ return stat;
}
/**
- * Scans through queues looking for work while joining a task; if
- * any present, signals. May return early if more signalling is
- * detectably unneeded.
- *
- * @param task return early if done
- * @param origin an index to start scan
- */
- private void helpSignal(ForkJoinTask<?> task, int origin) {
- WorkQueue[] ws; WorkQueue w; Thread p; long c; int m, u, e, i, s;
- if (task != null && task.status >= 0 &&
- (u = (int)(ctl >>> 32)) < 0 && (u >> UAC_SHIFT) < 0 &&
- (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
- outer: for (int k = origin, j = m; j >= 0; --j) {
- WorkQueue q = ws[k++ & m];
- for (int n = m;;) { // limit to at most m signals
- if (task.status < 0)
- break outer;
- if (q == null ||
- ((s = -q.base + q.top) <= n && (n = s) <= 0))
- break;
- if ((u = (int)((c = ctl) >>> 32)) >= 0 ||
- (e = (int)c) <= 0 || m < (i = e & SMASK) ||
- (w = ws[i]) == null)
- break outer;
- long nc = (((long)(w.nextWait & E_MASK)) |
- ((long)(u + UAC_UNIT) << 32));
- if (w.eventCount != (e | INT_SIGN))
- break outer;
- if (U.compareAndSwapLong(this, CTL, c, nc)) {
- w.eventCount = (e + E_SEQ) & E_MASK;
- if ((p = w.parker) != null)
- U.unpark(p);
- if (--n <= 0)
- break;
- }
- }
+ * Possibly releases (signals) a worker. Called only from scan()
+ * when a worker with apparently inactive status finds a non-empty
+ * queue. This requires revalidating all of the associated state
+ * from caller.
+ */
+ private final void helpRelease(long c, WorkQueue[] ws, WorkQueue w,
+ WorkQueue q, int b) {
+ WorkQueue v; int e, i; Thread p;
+ if (w != null && w.eventCount < 0 && (e = (int)c) > 0 &&
+ ws != null && ws.length > (i = e & SMASK) &&
+ (v = ws[i]) != null && ctl == c) {
+ long nc = (((long)(v.nextWait & E_MASK)) |
+ ((long)((int)(c >>> 32) + UAC_UNIT)) << 32);
+ int ne = (e + E_SEQ) & E_MASK;
+ if (q != null && q.base == b && w.eventCount < 0 &&
+ v.eventCount == (e | INT_SIGN) &&
+ U.compareAndSwapLong(this, CTL, c, nc)) {
+ v.eventCount = ne;
+ if ((p = v.parker) != null)
+ U.unpark(p);
}
}
}
@@ -1871,7 +1805,8 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
int stat = 0, steps = 0; // bound to avoid cycles
- if (joiner != null && task != null) { // hoist null checks
+ if (task != null && joiner != null &&
+ joiner.base - joiner.top >= 0) { // hoist checks
restart: for (;;) {
ForkJoinTask<?> subtask = task; // current target
for (WorkQueue j = joiner, v;;) { // v is stealer of subtask
@@ -1898,7 +1833,7 @@ public class ForkJoinPool extends AbstractExecutorService {
}
}
for (;;) { // help stealer or descend to its stealer
- ForkJoinTask[] a; int b;
+ ForkJoinTask[] a; int b;
if (subtask.status < 0) // surround probes with
continue restart; // consistency checks
if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
@@ -1909,13 +1844,23 @@ public class ForkJoinPool extends AbstractExecutorService {
v.currentSteal != subtask)
continue restart; // stale
stat = 1; // apparent progress
- if (t != null && v.base == b &&
- U.compareAndSwapObject(a, i, t, null)) {
- v.base = b + 1; // help stealer
- joiner.runSubtask(t);
+ if (v.base == b) {
+ if (t == null)
+ break restart;
+ if (U.compareAndSwapObject(a, i, t, null)) {
+ U.putOrderedInt(v, QBASE, b + 1);
+ ForkJoinTask<?> ps = joiner.currentSteal;
+ int jt = joiner.top;
+ do {
+ joiner.currentSteal = t;
+ t.doExec(); // clear local tasks too
+ } while (task.status >= 0 &&
+ joiner.top != jt &&
+ (t = joiner.pop()) != null);
+ joiner.currentSteal = ps;
+ break restart;
+ }
}
- else if (v.base == b && ++steps == MAX_HELP)
- break restart; // v apparently stalled
}
else { // empty -- try to descend
ForkJoinTask<?> next = v.currentJoin;
@@ -1942,27 +1887,33 @@ public class ForkJoinPool extends AbstractExecutorService {
* and run tasks within the target's computation.
*
* @param task the task to join
- * @param mode if shared, exit upon completing any task
- * if all workers are active
- */
- private int helpComplete(ForkJoinTask<?> task, int mode) {
- WorkQueue[] ws; WorkQueue q; int m, n, s, u;
- if (task != null && (ws = workQueues) != null &&
- (m = ws.length - 1) >= 0) {
- for (int j = 1, origin = j;;) {
+ */
+ private int helpComplete(WorkQueue joiner, CountedCompleter<?> task) {
+ WorkQueue[] ws; int m;
+ int s = 0;
+ if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 &&
+ joiner != null && task != null) {
+ int j = joiner.poolIndex;
+ int scans = m + m + 1;
+ long c = 0L; // for stability check
+ for (int k = scans; ; j += 2) {
+ WorkQueue q;
if ((s = task.status) < 0)
- return s;
- if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
- origin = j;
- if (mode == SHARED_QUEUE &&
- ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0))
+ break;
+ else if (joiner.internalPopAndExecCC(task))
+ k = scans;
+ else if ((s = task.status) < 0)
+ break;
+ else if ((q = ws[j & m]) != null && q.pollAndExecCC(task))
+ k = scans;
+ else if (--k < 0) {
+ if (c == (c = ctl))
break;
+ k = scans;
}
- else if ((j = (j + 2) & m) == origin)
- break;
}
}
- return 0;
+ return s;
}
/**
@@ -1971,17 +1922,22 @@ public class ForkJoinPool extends AbstractExecutorService {
* for blocking. Fails on contention or termination. Otherwise,
* adds a new thread if no idle workers are available and pool
* may become starved.
+ *
+ * @param c the assumed ctl value
*/
- final boolean tryCompensate() {
- int pc = config & SMASK, e, i, tc; long c;
- WorkQueue[] ws; WorkQueue w; Thread p;
- if ((ws = workQueues) != null && (e = (int)(c = ctl)) >= 0) {
- if (e != 0 && (i = e & SMASK) < ws.length &&
- (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
+ final boolean tryCompensate(long c) {
+ WorkQueue[] ws = workQueues;
+ int pc = parallelism, e = (int)c, m, tc;
+ if (ws != null && (m = ws.length - 1) >= 0 && e >= 0 && ctl == c) {
+ WorkQueue w = ws[e & m];
+ if (e != 0 && w != null) {
+ Thread p;
long nc = ((long)(w.nextWait & E_MASK) |
(c & (AC_MASK|TC_MASK)));
- if (U.compareAndSwapLong(this, CTL, c, nc)) {
- w.eventCount = (e + E_SEQ) & E_MASK;
+ int ne = (e + E_SEQ) & E_MASK;
+ if (w.eventCount == (e | INT_SIGN) &&
+ U.compareAndSwapLong(this, CTL, c, nc)) {
+ w.eventCount = ne;
if ((p = w.parker) != null)
U.unpark(p);
return true; // replace with idle worker
@@ -2024,23 +1980,20 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
int s = 0;
- if (joiner != null && task != null && (s = task.status) >= 0) {
+ if (task != null && (s = task.status) >= 0 && joiner != null) {
ForkJoinTask<?> prevJoin = joiner.currentJoin;
joiner.currentJoin = task;
- do {} while ((s = task.status) >= 0 && !joiner.isEmpty() &&
- joiner.tryRemoveAndExec(task)); // process local tasks
- if (s >= 0 && (s = task.status) >= 0) {
- helpSignal(task, joiner.poolIndex);
- if ((s = task.status) >= 0 &&
- (task instanceof CountedCompleter))
- s = helpComplete(task, LIFO_QUEUE);
- }
+ do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
+ (s = task.status) >= 0);
+ if (s >= 0 && (task instanceof CountedCompleter))
+ s = helpComplete(joiner, (CountedCompleter<?>)task);
+ long cc = 0; // for stability checks
while (s >= 0 && (s = task.status) >= 0) {
- if ((!joiner.isEmpty() || // try helping
- (s = tryHelpStealer(joiner, task)) == 0) &&
+ if ((s = tryHelpStealer(joiner, task)) == 0 &&
(s = task.status) >= 0) {
- helpSignal(task, joiner.poolIndex);
- if ((s = task.status) >= 0 && tryCompensate()) {
+ if (!tryCompensate(cc))
+ cc = ctl;
+ else {
if (task.trySetSignal() && (s = task.status) >= 0) {
synchronized (task) {
if (task.status >= 0) {
@@ -2053,9 +2006,11 @@ public class ForkJoinPool extends AbstractExecutorService {
task.notifyAll();
}
}
- long c; // re-activate
+ long c; // reactivate
do {} while (!U.compareAndSwapLong
- (this, CTL, c = ctl, c + AC_UNIT));
+ (this, CTL, c = ctl,
+ ((c & ~AC_MASK) |
+ ((c & AC_MASK) + AC_UNIT))));
}
}
}
@@ -2077,15 +2032,11 @@ public class ForkJoinPool extends AbstractExecutorService {
if (joiner != null && task != null && (s = task.status) >= 0) {
ForkJoinTask<?> prevJoin = joiner.currentJoin;
joiner.currentJoin = task;
- do {} while ((s = task.status) >= 0 && !joiner.isEmpty() &&
- joiner.tryRemoveAndExec(task));
- if (s >= 0 && (s = task.status) >= 0) {
- helpSignal(task, joiner.poolIndex);
- if ((s = task.status) >= 0 &&
- (task instanceof CountedCompleter))
- s = helpComplete(task, LIFO_QUEUE);
- }
- if (s >= 0 && joiner.isEmpty()) {
+ do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
+ (s = task.status) >= 0);
+ if (s >= 0) {
+ if (task instanceof CountedCompleter)
+ helpComplete(joiner, (CountedCompleter<?>)task);
do {} while (task.status >= 0 &&
tryHelpStealer(joiner, task) > 0);
}
@@ -2095,29 +2046,22 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Returns a (probably) non-empty steal queue, if one is found
- * during a random, then cyclic scan, else null. This method must
- * be retried by caller if, by the time it tries to use the queue,
- * it is empty.
- * @param r a (random) seed for scanning
- */
- private WorkQueue findNonEmptyStealQueue(int r) {
- for (WorkQueue[] ws;;) {
- int ps = plock, m, n;
- if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
- return null;
- for (int j = (m + 1) << 2; ;) {
- WorkQueue q = ws[(((r + j) << 1) | 1) & m];
- if (q != null && (n = q.base - q.top) < 0) {
- if (n < -1)
- signalWork(q);
- return q;
- }
- else if (--j < 0) {
- if (plock == ps)
- return null;
- break;
+ * during a scan, else null. This method must be retried by
+ * caller if, by the time it tries to use the queue, it is empty.
+ */
+ private WorkQueue findNonEmptyStealQueue() {
+ int r = ThreadLocalRandom.current().nextInt();
+ for (;;) {
+ int ps = plock, m; WorkQueue[] ws; WorkQueue q;
+ if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
+ for (int j = (m + 1) << 2; j >= 0; --j) {
+ if ((q = ws[(((r - j) << 1) | 1) & m]) != null &&
+ q.base - q.top < 0)
+ return q;
}
}
+ if (plock == ps)
+ return null;
}
}
@@ -2128,38 +2072,36 @@ public class ForkJoinPool extends AbstractExecutorService {
* find tasks either.
*/
final void helpQuiescePool(WorkQueue w) {
+ ForkJoinTask<?> ps = w.currentSteal;
for (boolean active = true;;) {
- ForkJoinTask<?> localTask; // exhaust local queue
- while ((localTask = w.nextLocalTask()) != null)
- localTask.doExec();
- // Similar to loop in scan(), but ignoring submissions
- WorkQueue q = findNonEmptyStealQueue(w.nextSeed());
- if (q != null) {
- ForkJoinTask<?> t; int b;
+ long c; WorkQueue q; ForkJoinTask<?> t; int b;
+ while ((t = w.nextLocalTask()) != null)
+ t.doExec();
+ if ((q = findNonEmptyStealQueue()) != null) {
if (!active) { // re-establish active count
- long c;
active = true;
do {} while (!U.compareAndSwapLong
- (this, CTL, c = ctl, c + AC_UNIT));
+ (this, CTL, c = ctl,
+ ((c & ~AC_MASK) |
+ ((c & AC_MASK) + AC_UNIT))));
+ }
+ if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
+ (w.currentSteal = t).doExec();
+ w.currentSteal = ps;
}
- if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
- w.runSubtask(t);
}
- else {
- long c;
- if (active) { // decrement active count without queuing
+ else if (active) { // decrement active count without queuing
+ long nc = ((c = ctl) & ~AC_MASK) | ((c & AC_MASK) - AC_UNIT);
+ if ((int)(nc >> AC_SHIFT) + parallelism == 0)
+ break; // bypass decrement-then-increment
+ if (U.compareAndSwapLong(this, CTL, c, nc))
active = false;
- do {} while (!U.compareAndSwapLong
- (this, CTL, c = ctl, c -= AC_UNIT));
- }
- else
- c = ctl; // re-increment on exit
- if ((int)(c >> AC_SHIFT) + (config & SMASK) == 0) {
- do {} while (!U.compareAndSwapLong
- (this, CTL, c = ctl, c + AC_UNIT));
- break;
- }
}
+ else if ((int)((c = ctl) >> AC_SHIFT) + parallelism <= 0 &&
+ U.compareAndSwapLong
+ (this, CTL, c, ((c & ~AC_MASK) |
+ ((c & AC_MASK) + AC_UNIT))))
+ break;
}
}
@@ -2173,7 +2115,7 @@ public class ForkJoinPool extends AbstractExecutorService {
WorkQueue q; int b;
if ((t = w.nextLocalTask()) != null)
return t;
- if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
+ if ((q = findNonEmptyStealQueue()) == null)
return null;
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
return t;
@@ -2229,7 +2171,7 @@ public class ForkJoinPool extends AbstractExecutorService {
static int getSurplusQueuedTaskCount() {
Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
- int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK;
+ int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).parallelism;
int n = (q = wt.workQueue).top - q.base;
int a = (int)(pool.ctl >> AC_SHIFT) + p;
return n - (a > (p >>>= 1) ? 0 :
@@ -2258,45 +2200,47 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return true if now terminating or terminated
*/
private boolean tryTerminate(boolean now, boolean enable) {
- if (this == commonPool) // cannot shut down
+ int ps;
+ if (this == common) // cannot shut down
return false;
+ if ((ps = plock) >= 0) { // enable by setting plock
+ if (!enable)
+ return false;
+ if ((ps & PL_LOCK) != 0 ||
+ !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+ ps = acquirePlock();
+ int nps = ((ps + PL_LOCK) & ~SHUTDOWN) | SHUTDOWN;
+ if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+ releasePlock(nps);
+ }
for (long c;;) {
- if (((c = ctl) & STOP_BIT) != 0) { // already terminating
- if ((short)(c >>> TC_SHIFT) == -(config & SMASK)) {
+ if (((c = ctl) & STOP_BIT) != 0) { // already terminating
+ if ((short)(c >>> TC_SHIFT) + parallelism <= 0) {
synchronized (this) {
- notifyAll(); // signal when 0 workers
+ notifyAll(); // signal when 0 workers
}
}
return true;
}
- if (plock >= 0) { // not yet enabled
- int ps;
- if (!enable)
- return false;
- if (((ps = plock) & PL_LOCK) != 0 ||
- !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
- ps = acquirePlock();
- if (!U.compareAndSwapInt(this, PLOCK, ps, SHUTDOWN))
- releasePlock(SHUTDOWN);
- }
- if (!now) { // check if idle & no tasks
- if ((int)(c >> AC_SHIFT) != -(config & SMASK) ||
- hasQueuedSubmissions())
+ if (!now) { // check if idle & no tasks
+ WorkQueue[] ws; WorkQueue w;
+ if ((int)(c >> AC_SHIFT) + parallelism > 0)
return false;
- // Check for unqueued inactive workers. One pass suffices.
- WorkQueue[] ws = workQueues; WorkQueue w;
- if (ws != null) {
- for (int i = 1; i < ws.length; i += 2) {
- if ((w = ws[i]) != null && w.eventCount >= 0)
+ if ((ws = workQueues) != null) {
+ for (int i = 0; i < ws.length; ++i) {
+ if ((w = ws[i]) != null &&
+ (!w.isEmpty() ||
+ ((i & 1) != 0 && w.eventCount >= 0))) {
+ signalWork(ws, w);
return false;
+ }
}
}
}
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
for (int pass = 0; pass < 3; ++pass) {
- WorkQueue[] ws = workQueues;
- if (ws != null) {
- WorkQueue w; Thread wt;
+ WorkQueue[] ws; WorkQueue w; Thread wt;
+ if ((ws = workQueues) != null) {
int n = ws.length;
for (int i = 0; i < n; ++i) {
if ((w = ws[i]) != null) {
@@ -2307,7 +2251,7 @@ public class ForkJoinPool extends AbstractExecutorService {
if (!wt.isInterrupted()) {
try {
wt.interrupt();
- } catch (SecurityException ignore) {
+ } catch (Throwable ignore) {
}
}
U.unpark(wt);
@@ -2318,7 +2262,7 @@ public class ForkJoinPool extends AbstractExecutorService {
// Wake up workers parked on event queue
int i, e; long cc; Thread p;
while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
- (i = e & SMASK) < n &&
+ (i = e & SMASK) < n && i >= 0 &&
(w = ws[i]) != null) {
long nc = ((long)(w.nextWait & E_MASK) |
((cc + AC_UNIT) & AC_MASK) |
@@ -2344,9 +2288,9 @@ public class ForkJoinPool extends AbstractExecutorService {
* least one task.
*/
static WorkQueue commonSubmitterQueue() {
- ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
+ Submitter z; ForkJoinPool p; WorkQueue[] ws; int m, r;
return ((z = submitters.get()) != null &&
- (p = commonPool) != null &&
+ (p = common) != null &&
(ws = p.workQueues) != null &&
(m = ws.length - 1) >= 0) ?
ws[m & z.seed & SQMASK] : null;
@@ -2355,127 +2299,57 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Tries to pop the given task from submitter's queue in common pool.
*/
- static boolean tryExternalUnpush(ForkJoinTask<?> t) {
- ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z;
- ForkJoinTask<?>[] a; int m, s;
- if (t != null &&
- (z = submitters.get()) != null &&
- (p = commonPool) != null &&
- (ws = p.workQueues) != null &&
- (m = ws.length - 1) >= 0 &&
- (q = ws[m & z.seed & SQMASK]) != null &&
- (s = q.top) != q.base &&
- (a = q.array) != null) {
+ final boolean tryExternalUnpush(ForkJoinTask<?> task) {
+ WorkQueue joiner; ForkJoinTask<?>[] a; int m, s;
+ Submitter z = submitters.get();
+ WorkQueue[] ws = workQueues;
+ boolean popped = false;
+ if (z != null && ws != null && (m = ws.length - 1) >= 0 &&
+ (joiner = ws[z.seed & m & SQMASK]) != null &&
+ joiner.base != (s = joiner.top) &&
+ (a = joiner.array) != null) {
long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
- if (U.getObject(a, j) == t &&
- U.compareAndSwapInt(q, QLOCK, 0, 1)) {
- if (q.array == a && q.top == s && // recheck
- U.compareAndSwapObject(a, j, t, null)) {
- q.top = s - 1;
- q.qlock = 0;
- return true;
+ if (U.getObject(a, j) == task &&
+ U.compareAndSwapInt(joiner, QLOCK, 0, 1)) {
+ if (joiner.top == s && joiner.array == a &&
+ U.compareAndSwapObject(a, j, task, null)) {
+ joiner.top = s - 1;
+ popped = true;
}
- q.qlock = 0;
+ joiner.qlock = 0;
}
}
- return false;
+ return popped;
}
- /**
- * Tries to pop and run local tasks within the same computation
- * as the given root. On failure, tries to help complete from
- * other queues via helpComplete.
- */
- private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) {
- ForkJoinTask<?>[] a; int m;
- if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 &&
- root != null && root.status >= 0) {
- for (;;) {
- int s, u; Object o; CountedCompleter<?> task = null;
- if ((s = q.top) - q.base > 0) {
- long j = ((m & (s - 1)) << ASHIFT) + ABASE;
- if ((o = U.getObject(a, j)) != null &&
- (o instanceof CountedCompleter)) {
- CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;
- do {
- if (r == root) {
- if (U.compareAndSwapInt(q, QLOCK, 0, 1)) {
- if (q.array == a && q.top == s &&
- U.compareAndSwapObject(a, j, t, null)) {
- q.top = s - 1;
- task = t;
- }
- q.qlock = 0;
- }
- break;
- }
- } while ((r = r.completer) != null);
- }
- }
- if (task != null)
- task.doExec();
- if (root.status < 0 ||
- (u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)
+ final int externalHelpComplete(CountedCompleter<?> task) {
+ WorkQueue joiner; int m, j;
+ Submitter z = submitters.get();
+ WorkQueue[] ws = workQueues;
+ int s = 0;
+ if (z != null && ws != null && (m = ws.length - 1) >= 0 &&
+ (joiner = ws[(j = z.seed) & m & SQMASK]) != null && task != null) {
+ int scans = m + m + 1;
+ long c = 0L; // for stability check
+ j |= 1; // poll odd queues
+ for (int k = scans; ; j += 2) {
+ WorkQueue q;
+ if ((s = task.status) < 0)
break;
- if (task == null) {
- helpSignal(root, q.poolIndex);
- if (root.status >= 0)
- helpComplete(root, SHARED_QUEUE);
+ else if (joiner.externalPopAndExecCC(task))
+ k = scans;
+ else if ((s = task.status) < 0)
break;
+ else if ((q = ws[j & m]) != null && q.pollAndExecCC(task))
+ k = scans;
+ else if (--k < 0) {
+ if (c == (c = ctl))
+ break;
+ k = scans;
}
}
}
- }
-
- /**
- * Tries to help execute or signal availability of the given task
- * from submitter's queue in common pool.
- */
- static void externalHelpJoin(ForkJoinTask<?> t) {
- // Some hard-to-avoid overlap with tryExternalUnpush
- ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; Submitter z;
- ForkJoinTask<?>[] a; int m, s, n;
- if (t != null &&
- (z = submitters.get()) != null &&
- (p = commonPool) != null &&
- (ws = p.workQueues) != null &&
- (m = ws.length - 1) >= 0 &&
- (q = ws[m & z.seed & SQMASK]) != null &&
- (a = q.array) != null) {
- int am = a.length - 1;
- if ((s = q.top) != q.base) {
- long j = ((am & (s - 1)) << ASHIFT) + ABASE;
- if (U.getObject(a, j) == t &&
- U.compareAndSwapInt(q, QLOCK, 0, 1)) {
- if (q.array == a && q.top == s &&
- U.compareAndSwapObject(a, j, t, null)) {
- q.top = s - 1;
- q.qlock = 0;
- t.doExec();
- }
- else
- q.qlock = 0;
- }
- }
- if (t.status >= 0) {
- if (t instanceof CountedCompleter)
- p.externalHelpComplete(q, t);
- else
- p.helpSignal(t, q.poolIndex);
- }
- }
- }
-
- /**
- * Restricted version of helpQuiescePool for external callers
- */
- static void externalHelpQuiescePool() {
- ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b;
- if ((p = commonPool) != null &&
- (q = p.findNonEmptyStealQueue(1)) != null &&
- (b = q.base) - q.top < 0 &&
- (t = q.pollAt(b)) != null)
- t.doExec();
+ return s;
}
// Exported methods
@@ -2529,49 +2403,65 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
public ForkJoinPool(int parallelism,
ForkJoinWorkerThreadFactory factory,
- Thread.UncaughtExceptionHandler handler,
+ UncaughtExceptionHandler handler,
boolean asyncMode) {
+ this(checkParallelism(parallelism),
+ checkFactory(factory),
+ handler,
+ (asyncMode ? FIFO_QUEUE : LIFO_QUEUE),
+ "ForkJoinPool-" + nextPoolId() + "-worker-");
checkPermission();
- if (factory == null)
- throw new NullPointerException();
+ }
+
+ private static int checkParallelism(int parallelism) {
if (parallelism <= 0 || parallelism > MAX_CAP)
throw new IllegalArgumentException();
- this.factory = factory;
- this.ueh = handler;
- this.config = parallelism | (asyncMode ? (FIFO_QUEUE << 16) : 0);
- long np = (long)(-parallelism); // offset ctl counts
- this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
- int pn = nextPoolId();
- StringBuilder sb = new StringBuilder("ForkJoinPool-");
- sb.append(Integer.toString(pn));
- sb.append("-worker-");
- this.workerNamePrefix = sb.toString();
+ return parallelism;
+ }
+
+ private static ForkJoinWorkerThreadFactory checkFactory
+ (ForkJoinWorkerThreadFactory factory) {
+ if (factory == null)
+ throw new NullPointerException();
+ return factory;
}
/**
- * Constructor for common pool, suitable only for static initialization.
- * Basically the same as above, but uses smallest possible initial footprint.
+ * Creates a {@code ForkJoinPool} with the given parameters, without
+ * any security checks or parameter validation. Invoked directly by
+ * makeCommonPool.
*/
- ForkJoinPool(int parallelism, long ctl,
- ForkJoinWorkerThreadFactory factory,
- Thread.UncaughtExceptionHandler handler) {
- this.config = parallelism;
- this.ctl = ctl;
+ private ForkJoinPool(int parallelism,
+ ForkJoinWorkerThreadFactory factory,
+ UncaughtExceptionHandler handler,
+ int mode,
+ String workerNamePrefix) {
+ this.workerNamePrefix = workerNamePrefix;
this.factory = factory;
this.ueh = handler;
- this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
+ this.mode = (short)mode;
+ this.parallelism = (short)parallelism;
+ long np = (long)(-parallelism); // offset ctl counts
+ this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
}
/**
- * Returns the common pool instance.
+ * Returns the common pool instance. This pool is statically
+ * constructed; its run state is unaffected by attempts to {@link
+ * #shutdown} or {@link #shutdownNow}. However this pool and any
+ * ongoing processing are automatically terminated upon program
+ * {@link System#exit}. Any program that relies on asynchronous
+ * task processing to complete before program termination should
+ * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
+ * before exit.
*
* @return the common pool instance
* @since 1.8
* @hide
*/
public static ForkJoinPool commonPool() {
- // assert commonPool != null : "static init error";
- return commonPool;
+ // assert common != null : "static init error";
+ return common;
}
// Execution methods
@@ -2627,7 +2517,7 @@ public class ForkJoinPool extends AbstractExecutorService {
if (task instanceof ForkJoinTask<?>) // avoid re-wrap
job = (ForkJoinTask<?>) task;
else
- job = new ForkJoinTask.AdaptedRunnableAction(task);
+ job = new ForkJoinTask.RunnableExecuteAction(task);
externalPush(job);
}
@@ -2729,7 +2619,7 @@ public class ForkJoinPool extends AbstractExecutorService {
*
* @return the handler, or {@code null} if none
*/
- public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
+ public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return ueh;
}
@@ -2739,7 +2629,8 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return the targeted parallelism level of this pool
*/
public int getParallelism() {
- return config & SMASK;
+ int par;
+ return ((par = parallelism) > 0) ? par : 1;
}
/**
@@ -2750,7 +2641,7 @@ public class ForkJoinPool extends AbstractExecutorService {
* @hide
*/
public static int getCommonPoolParallelism() {
- return commonPoolParallelism;
+ return commonParallelism;
}
/**
@@ -2762,7 +2653,7 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return the number of worker threads
*/
public int getPoolSize() {
- return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
+ return parallelism + (short)(ctl >>> TC_SHIFT);
}
/**
@@ -2772,7 +2663,7 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return {@code true} if this pool uses async mode
*/
public boolean getAsyncMode() {
- return (config >>> 16) == FIFO_QUEUE;
+ return mode == FIFO_QUEUE;
}
/**
@@ -2803,7 +2694,7 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return the number of active threads
*/
public int getActiveThreadCount() {
- int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
+ int r = parallelism + (int)(ctl >> AC_SHIFT);
return (r <= 0) ? 0 : r; // suppress momentarily negative values
}
@@ -2819,7 +2710,7 @@ public class ForkJoinPool extends AbstractExecutorService {
* @return {@code true} if all threads are currently idle
*/
public boolean isQuiescent() {
- return (int)(ctl >> AC_SHIFT) + (config & SMASK) == 0;
+ return parallelism + (int)(ctl >> AC_SHIFT) <= 0;
}
/**
@@ -2982,7 +2873,7 @@ public class ForkJoinPool extends AbstractExecutorService {
}
}
}
- int pc = (config & SMASK);
+ int pc = parallelism;
int tc = pc + (short)(c >>> TC_SHIFT);
int ac = pc + (int)(c >> AC_SHIFT);
if (ac < 0) // ignore transient negative
@@ -3008,15 +2899,10 @@ public class ForkJoinPool extends AbstractExecutorService {
* Possibly initiates an orderly shutdown in which previously
* submitted tasks are executed, but no new tasks will be
* accepted. Invocation has no effect on execution state if this
- * is the {@link #commonPool()}, and no additional effect if
+ * is the {@code commonPool()}, and no additional effect if
* already shut down. Tasks that are in the process of being
* submitted concurrently during the course of this method may or
* may not be rejected.
- *
- * @throws SecurityException if a security manager exists and
- * the caller is not permitted to modify threads
- * because it does not hold {@link
- * java.lang.RuntimePermission}{@code ("modifyThread")}
*/
public void shutdown() {
checkPermission();
@@ -3026,7 +2912,7 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Possibly attempts to cancel and/or stop all tasks, and reject
* all subsequently submitted tasks. Invocation has no effect on
- * execution state if this is the {@link #commonPool()}, and no
+ * execution state if this is the {@code commonPool()}, and no
* additional effect if already shut down. Otherwise, tasks that
* are in the process of being submitted or executed concurrently
* during the course of this method may or may not be
@@ -3051,7 +2937,7 @@ public class ForkJoinPool extends AbstractExecutorService {
public boolean isTerminated() {
long c = ctl;
return ((c & STOP_BIT) != 0L &&
- (short)(c >>> TC_SHIFT) == -(config & SMASK));
+ (short)(c >>> TC_SHIFT) + parallelism <= 0);
}
/**
@@ -3070,7 +2956,7 @@ public class ForkJoinPool extends AbstractExecutorService {
public boolean isTerminating() {
long c = ctl;
return ((c & STOP_BIT) != 0L &&
- (short)(c >>> TC_SHIFT) != -(config & SMASK));
+ (short)(c >>> TC_SHIFT) + parallelism > 0);
}
/**
@@ -3085,9 +2971,10 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Blocks until all tasks have completed execution after a
* shutdown request, or the timeout occurs, or the current thread
- * is interrupted, whichever happens first. Note that the {@link
- * #commonPool()} never terminates until program shutdown so
- * this method will always time out.
+ * is interrupted, whichever happens first. Because the {@code
+ * commonPool()} never terminates until program shutdown, when
+ * applied to the common pool, this method is equivalent to {@link
+ * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
@@ -3097,6 +2984,12 @@ public class ForkJoinPool extends AbstractExecutorService {
*/
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
+ if (Thread.interrupted())
+ throw new InterruptedException();
+ if (this == common) {
+ awaitQuiescence(timeout, unit);
+ return false;
+ }
long nanos = unit.toNanos(timeout);
if (isTerminated())
return true;
@@ -3117,6 +3010,59 @@ public class ForkJoinPool extends AbstractExecutorService {
}
/**
+ * If called by a ForkJoinTask operating in this pool, equivalent
+ * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
+ * waits and/or attempts to assist performing tasks until this
+ * pool {@link #isQuiescent} or the indicated timeout elapses.
+ *
+ * @param timeout the maximum time to wait
+ * @param unit the time unit of the timeout argument
+ * @return {@code true} if quiescent; {@code false} if the
+ * timeout elapsed.
+ */
+ public boolean awaitQuiescence(long timeout, TimeUnit unit) {
+ long nanos = unit.toNanos(timeout);
+ ForkJoinWorkerThread wt;
+ Thread thread = Thread.currentThread();
+ if ((thread instanceof ForkJoinWorkerThread) &&
+ (wt = (ForkJoinWorkerThread)thread).pool == this) {
+ helpQuiescePool(wt.workQueue);
+ return true;
+ }
+ long startTime = System.nanoTime();
+ WorkQueue[] ws;
+ int r = 0, m;
+ boolean found = true;
+ while (!isQuiescent() && (ws = workQueues) != null &&
+ (m = ws.length - 1) >= 0) {
+ if (!found) {
+ if ((System.nanoTime() - startTime) > nanos)
+ return false;
+ Thread.yield(); // cannot block
+ }
+ found = false;
+ for (int j = (m + 1) << 2; j >= 0; --j) {
+ ForkJoinTask<?> t; WorkQueue q; int b;
+ if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) {
+ found = true;
+ if ((t = q.pollAt(b)) != null)
+ t.doExec();
+ break;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Waits and/or attempts to assist performing tasks indefinitely
+ * until the {@code commonPool()} {@link #isQuiescent}.
+ */
+ static void quiesceCommonPool() {
+ common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
+ }
+
+ /**
* Interface for extending managed parallelism for tasks running
* in {@link ForkJoinPool}s.
*
@@ -3125,9 +3071,9 @@ public class ForkJoinPool extends AbstractExecutorService {
* not necessary. Method {@code block} blocks the current thread
* if necessary (perhaps internally invoking {@code isReleasable}
* before actually blocking). These actions are performed by any
- * thread invoking {@link ForkJoinPool#managedBlock}. The
- * unusual methods in this API accommodate synchronizers that may,
- * but don't usually, block for long periods. Similarly, they
+ * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
+ * The unusual methods in this API accommodate synchronizers that
+ * may, but don't usually, block for long periods. Similarly, they
* allow more efficient internal handling of cases in which
* additional workers may be, but usually are not, needed to
* ensure sufficient parallelism. Toward this end,
@@ -3185,6 +3131,7 @@ public class ForkJoinPool extends AbstractExecutorService {
/**
* Returns {@code true} if blocking is unnecessary.
+ * @return {@code true} if blocking is unnecessary
*/
boolean isReleasable();
}
@@ -3214,21 +3161,8 @@ public class ForkJoinPool extends AbstractExecutorService {
Thread t = Thread.currentThread();
if (t instanceof ForkJoinWorkerThread) {
ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
- while (!blocker.isReleasable()) { // variant of helpSignal
- WorkQueue[] ws; WorkQueue q; int m, u;
- if ((ws = p.workQueues) != null && (m = ws.length - 1) >= 0) {
- for (int i = 0; i <= m; ++i) {
- if (blocker.isReleasable())
- return;
- if ((q = ws[i]) != null && q.base - q.top < 0) {
- p.signalWork(q);
- if ((u = (int)(p.ctl >>> 32)) >= 0 ||
- (u >> UAC_SHIFT) >= 0)
- break;
- }
- }
- }
- if (p.tryCompensate()) {
+ while (!blocker.isReleasable()) {
+ if (p.tryCompensate(p.ctl)) {
try {
do {} while (!blocker.isReleasable() &&
!blocker.block());
@@ -3266,6 +3200,7 @@ public class ForkJoinPool extends AbstractExecutorService {
private static final long STEALCOUNT;
private static final long PLOCK;
private static final long INDEXSEED;
+ private static final long QBASE;
private static final long QLOCK;
static {
@@ -3285,6 +3220,8 @@ public class ForkJoinPool extends AbstractExecutorService {
PARKBLOCKER = U.objectFieldOffset
(tk.getDeclaredField("parkBlocker"));
Class<?> wk = WorkQueue.class;
+ QBASE = U.objectFieldOffset
+ (wk.getDeclaredField("base"));
QLOCK = U.objectFieldOffset
(wk.getDeclaredField("qlock"));
Class<?> ak = ForkJoinTask[].class;
@@ -3298,45 +3235,51 @@ public class ForkJoinPool extends AbstractExecutorService {
}
submitters = new ThreadLocal<Submitter>();
- ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory =
+ defaultForkJoinWorkerThreadFactory =
new DefaultForkJoinWorkerThreadFactory();
modifyThreadPermission = new RuntimePermission("modifyThread");
- /*
- * Establish common pool parameters. For extra caution,
- * computations to set up common pool state are here; the
- * constructor just assigns these values to fields.
- */
+ common = java.security.AccessController.doPrivileged
+ (new java.security.PrivilegedAction<ForkJoinPool>() {
+ public ForkJoinPool run() { return makeCommonPool(); }});
+ int par = common.parallelism; // report 1 even if threads disabled
+ commonParallelism = par > 0 ? par : 1;
+ }
- int par = 0;
- Thread.UncaughtExceptionHandler handler = null;
- try { // TBD: limit or report ignored exceptions?
+ /**
+ * Creates and returns the common pool, respecting user settings
+ * specified via system properties.
+ */
+ private static ForkJoinPool makeCommonPool() {
+ int parallelism = -1;
+ ForkJoinWorkerThreadFactory factory
+ = defaultForkJoinWorkerThreadFactory;
+ UncaughtExceptionHandler handler = null;
+ try { // ignore exceptions in accessing/parsing properties
String pp = System.getProperty
("java.util.concurrent.ForkJoinPool.common.parallelism");
- String hp = System.getProperty
- ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
String fp = System.getProperty
("java.util.concurrent.ForkJoinPool.common.threadFactory");
+ String hp = System.getProperty
+ ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
+ if (pp != null)
+ parallelism = Integer.parseInt(pp);
if (fp != null)
- fac = ((ForkJoinWorkerThreadFactory)ClassLoader.
- getSystemClassLoader().loadClass(fp).newInstance());
+ factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
+ getSystemClassLoader().loadClass(fp).newInstance());
if (hp != null)
- handler = ((Thread.UncaughtExceptionHandler)ClassLoader.
+ handler = ((UncaughtExceptionHandler)ClassLoader.
getSystemClassLoader().loadClass(hp).newInstance());
- if (pp != null)
- par = Integer.parseInt(pp);
} catch (Exception ignore) {
}
- if (par <= 0)
- par = Runtime.getRuntime().availableProcessors();
- if (par > MAX_CAP)
- par = MAX_CAP;
- commonPoolParallelism = par;
- long np = (long)(-par); // precompute initial ctl value
- long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
-
- commonPool = new ForkJoinPool(par, ct, fac, handler);
+ if (parallelism < 0 && // default 1 less than #cores
+ (parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0)
+ parallelism = 0;
+ if (parallelism > MAX_CAP)
+ parallelism = MAX_CAP;
+ return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
+ "ForkJoinPool.commonPool-worker-");
}
}
diff --git a/luni/src/main/java/java/util/concurrent/ForkJoinTask.java b/luni/src/main/java/java/util/concurrent/ForkJoinTask.java
index 818788e..c6bc6de 100644
--- a/luni/src/main/java/java/util/concurrent/ForkJoinTask.java
+++ b/luni/src/main/java/java/util/concurrent/ForkJoinTask.java
@@ -32,8 +32,8 @@ import java.lang.reflect.Constructor;
*
* <p>A "main" {@code ForkJoinTask} begins execution when it is
* explicitly submitted to a {@link ForkJoinPool}, or, if not already
- * engaged in a ForkJoin computation, commenced in the {@link
- * ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or
+ * engaged in a ForkJoin computation, commenced in the {@code
+ * ForkJoinPool.commonPool()} via {@link #fork}, {@link #invoke}, or
* related methods. Once started, it will usually in turn start other
* subtasks. As indicated by the name of this class, many programs
* using {@code ForkJoinTask} employ only methods {@link #fork} and
@@ -74,10 +74,9 @@ import java.lang.reflect.Constructor;
* but doing do requires three further considerations: (1) Completion
* of few if any <em>other</em> tasks should be dependent on a task
* that blocks on external synchronization or I/O. Event-style async
- * tasks that are never joined (for example, those subclassing {@link
- * CountedCompleter}) often fall into this category. (2) To minimize
- * resource impact, tasks should be small; ideally performing only the
- * (possibly) blocking action. (3) Unless the {@link
+ * tasks that are never joined often fall into this category.
+ * (2) To minimize resource impact, tasks should be small; ideally
+ * performing only the (possibly) blocking action. (3) Unless the {@link
* ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
* blocked tasks is known to be less than the pool's {@link
* ForkJoinPool#getParallelism} level, the pool cannot guarantee that
@@ -120,13 +119,11 @@ import java.lang.reflect.Constructor;
* <p>The ForkJoinTask class is not usually directly subclassed.
* Instead, you subclass one of the abstract classes that support a
* particular style of fork/join processing, typically {@link
- * RecursiveAction} for most computations that do not return results,
- * {@link RecursiveTask} for those that do, and {@link
- * CountedCompleter} for those in which completed actions trigger
- * other actions. Normally, a concrete ForkJoinTask subclass declares
- * fields comprising its parameters, established in a constructor, and
- * then defines a {@code compute} method that somehow uses the control
- * methods supplied by this base class.
+ * RecursiveAction} for most computations that do not return results
+ * and {@link RecursiveTask} for those that do. Normally, a concrete
+ * ForkJoinTask subclass declares fields comprising its parameters,
+ * established in a constructor, and then defines a {@code compute}
+ * method that somehow uses the control methods supplied by this base class.
*
* <p>Method {@link #join} and its variants are appropriate for use
* only when completion dependencies are acyclic; that is, the
@@ -136,11 +133,11 @@ import java.lang.reflect.Constructor;
* supports other methods and techniques (for example the use of
* {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
* may be of use in constructing custom subclasses for problems that
- * are not statically structured as DAGs. To support such usages a
+ * are not statically structured as DAGs. To support such usages, a
* ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
- * value using {@link #setForkJoinTaskTag} or {@link
- * #compareAndSetForkJoinTaskTag} and checked using {@link
- * #getForkJoinTaskTag}. The ForkJoinTask implementation does not use
+ * value using {@code setForkJoinTaskTag} or {@code
+ * compareAndSetForkJoinTaskTag} and checked using {@code
+ * getForkJoinTaskTag}. The ForkJoinTask implementation does not use
* these {@code protected} methods or tags for any purpose, but they
* may be of use in the construction of specialized subclasses. For
* example, parallel graph traversals can use the supplied methods to
@@ -178,7 +175,6 @@ import java.lang.reflect.Constructor;
* execution. Serialization is not relied on during execution itself.
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
@@ -286,25 +282,35 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*/
private int externalAwaitDone() {
int s;
- ForkJoinPool.externalHelpJoin(this);
- boolean interrupted = false;
- while ((s = status) >= 0) {
- if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
- synchronized (this) {
- if (status >= 0) {
- try {
- wait();
- } catch (InterruptedException ie) {
- interrupted = true;
+ ForkJoinPool cp = ForkJoinPool.common;
+ if ((s = status) >= 0) {
+ if (cp != null) {
+ if (this instanceof CountedCompleter)
+ s = cp.externalHelpComplete((CountedCompleter<?>)this);
+ else if (cp.tryExternalUnpush(this))
+ s = doExec();
+ }
+ if (s >= 0 && (s = status) >= 0) {
+ boolean interrupted = false;
+ do {
+ if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
+ synchronized (this) {
+ if (status >= 0) {
+ try {
+ wait();
+ } catch (InterruptedException ie) {
+ interrupted = true;
+ }
+ }
+ else
+ notifyAll();
}
}
- else
- notifyAll();
- }
+ } while ((s = status) >= 0);
+ if (interrupted)
+ Thread.currentThread().interrupt();
}
}
- if (interrupted)
- Thread.currentThread().interrupt();
return s;
}
@@ -313,9 +319,15 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*/
private int externalInterruptibleAwaitDone() throws InterruptedException {
int s;
+ ForkJoinPool cp = ForkJoinPool.common;
if (Thread.interrupted())
throw new InterruptedException();
- ForkJoinPool.externalHelpJoin(this);
+ if ((s = status) >= 0 && cp != null) {
+ if (this instanceof CountedCompleter)
+ cp.externalHelpComplete((CountedCompleter<?>)this);
+ else if (cp.tryExternalUnpush(this))
+ doExec();
+ }
while ((s = status) >= 0) {
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) {
@@ -329,7 +341,6 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
return s;
}
-
/**
* Implementation for join, get, quietlyJoin. Directly handles
* only cases of already-completed, external wait, and
@@ -601,14 +612,9 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
/**
* A version of "sneaky throw" to relay exceptions
*/
- static void rethrow(final Throwable ex) {
- if (ex != null) {
- if (ex instanceof Error)
- throw (Error)ex;
- if (ex instanceof RuntimeException)
- throw (RuntimeException)ex;
- throw uncheckedThrowable(ex, RuntimeException.class);
- }
+ static void rethrow(Throwable ex) {
+ if (ex != null)
+ ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
}
/**
@@ -617,8 +623,8 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
* unchecked exceptions
*/
@SuppressWarnings("unchecked") static <T extends Throwable>
- T uncheckedThrowable(final Throwable t, final Class<T> c) {
- return (T)t; // rely on vacuous cast
+ void uncheckedThrow(Throwable t) throws T {
+ throw (T)t; // rely on vacuous cast
}
/**
@@ -635,8 +641,8 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
/**
* Arranges to asynchronously execute this task in the pool the
- * current task is running in, if applicable, or using the {@link
- * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While
+ * current task is running in, if applicable, or using the {@code
+ * ForkJoinPool.commonPool()} if not {@link #inForkJoinPool}. While
* it is not necessarily enforced, it is a usage error to fork a
* task more than once unless it has completed and been
* reinitialized. Subsequent modifications to the state of this
@@ -653,7 +659,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
((ForkJoinWorkerThread)t).workQueue.push(this);
else
- ForkJoinPool.commonPool.externalPush(this);
+ ForkJoinPool.common.externalPush(this);
return this;
}
@@ -774,8 +780,6 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
* @param tasks the collection of tasks
* @return the tasks argument, to simplify usage
* @throws NullPointerException if tasks or any element are null
-
- * @hide
*/
public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
@@ -831,7 +835,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
* <p>This method is designed to be invoked by <em>other</em>
* tasks. To terminate the current task, you can just return or
* throw an unchecked exception from its computation method, or
- * invoke {@link #completeExceptionally}.
+ * invoke {@link #completeExceptionally(Throwable)}.
*
* @param mayInterruptIfRunning this value has no effect in the
* default implementation because interrupts are not used to
@@ -984,6 +988,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
// Messy in part because we measure in nanosecs, but wait in millisecs
int s; long ms;
long ns = unit.toNanos(timeout);
+ ForkJoinPool cp;
if ((s = status) >= 0 && ns > 0L) {
long deadline = System.nanoTime() + ns;
ForkJoinPool p = null;
@@ -995,8 +1000,12 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
w = wt.workQueue;
p.helpJoinOnce(w, this); // no retries on failure
}
- else
- ForkJoinPool.externalHelpJoin(this);
+ else if ((cp = ForkJoinPool.common) != null) {
+ if (this instanceof CountedCompleter)
+ cp.externalHelpComplete((CountedCompleter<?>)this);
+ else if (cp.tryExternalUnpush(this))
+ doExec();
+ }
boolean canBlock = false;
boolean interrupted = false;
try {
@@ -1004,7 +1013,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
if (w != null && w.qlock < 0)
cancelIgnoringExceptions(this);
else if (!canBlock) {
- if (p == null || p.tryCompensate())
+ if (p == null || p.tryCompensate(p.ctl))
canBlock = true;
}
else {
@@ -1080,7 +1089,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
wt.pool.helpQuiescePool(wt.workQueue);
}
else
- ForkJoinPool.externalHelpQuiescePool();
+ ForkJoinPool.quiesceCommonPool();
}
/**
@@ -1145,7 +1154,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
Thread t;
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
- ForkJoinPool.tryExternalUnpush(this));
+ ForkJoinPool.common.tryExternalUnpush(this));
}
/**
@@ -1316,7 +1325,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*
* @param e the expected tag value
* @param tag the new tag value
- * @return true if successful; i.e., the current value was
+ * @return {@code true} if successful; i.e., the current value was
* equal to e and is now tag.
* @since 1.8
* @hide
@@ -1370,6 +1379,24 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
}
/**
+ * Adaptor for Runnables in which failure forces worker exception
+ */
+ static final class RunnableExecuteAction extends ForkJoinTask<Void> {
+ final Runnable runnable;
+ RunnableExecuteAction(Runnable runnable) {
+ if (runnable == null) throw new NullPointerException();
+ this.runnable = runnable;
+ }
+ public final Void getRawResult() { return null; }
+ public final void setRawResult(Void v) { }
+ public final boolean exec() { runnable.run(); return true; }
+ void internalPropagateException(Throwable ex) {
+ rethrow(ex); // rethrow outside exec() catches.
+ }
+ private static final long serialVersionUID = 5232453952276885070L;
+ }
+
+ /**
* Adaptor for Callables
*/
static final class AdaptedCallable<T> extends ForkJoinTask<T>
@@ -1480,5 +1507,4 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
throw new Error(e);
}
}
-
}
diff --git a/luni/src/main/java/java/util/concurrent/ForkJoinWorkerThread.java b/luni/src/main/java/java/util/concurrent/ForkJoinWorkerThread.java
index f31763c..ae28700 100644
--- a/luni/src/main/java/java/util/concurrent/ForkJoinWorkerThread.java
+++ b/luni/src/main/java/java/util/concurrent/ForkJoinWorkerThread.java
@@ -14,11 +14,10 @@ package java.util.concurrent;
* scheduling or execution. However, you can override initialization
* and termination methods surrounding the main task processing loop.
* If you do create such a subclass, you will also need to supply a
- * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it
- * in a {@code ForkJoinPool}.
+ * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to
+ * {@linkplain ForkJoinPool#ForkJoinPool use it} in a {@code ForkJoinPool}.
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public class ForkJoinWorkerThread extends Thread {
@@ -61,16 +60,17 @@ public class ForkJoinWorkerThread extends Thread {
}
/**
- * Returns the index number of this thread in its pool. The
- * returned value ranges from zero to the maximum number of
- * threads (minus one) that have ever been created in the pool.
- * This method may be useful for applications that track status or
- * collect results per-worker rather than per-task.
+ * Returns the unique index number of this thread in its pool.
+ * The returned value ranges from zero to the maximum number of
+ * threads (minus one) that may exist in the pool, and does not
+ * change during the lifetime of the thread. This method may be
+ * useful for applications that track status or collect results
+ * per-worker-thread rather than per-task.
*
* @return the index number
*/
public int getPoolIndex() {
- return workQueue.poolIndex;
+ return workQueue.poolIndex >>> 1; // ignore odd/even tag bit
}
/**
diff --git a/luni/src/main/java/java/util/concurrent/LinkedTransferQueue.java b/luni/src/main/java/java/util/concurrent/LinkedTransferQueue.java
index cff5dbf..a041fb1 100644
--- a/luni/src/main/java/java/util/concurrent/LinkedTransferQueue.java
+++ b/luni/src/main/java/java/util/concurrent/LinkedTransferQueue.java
@@ -50,7 +50,6 @@ import java.util.concurrent.locks.LockSupport;
* the {@code LinkedTransferQueue} in another thread.
*
* @since 1.7
- * @hide
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
diff --git a/luni/src/main/java/java/util/concurrent/Phaser.java b/luni/src/main/java/java/util/concurrent/Phaser.java
index a9adbe5..a97d187 100644
--- a/luni/src/main/java/java/util/concurrent/Phaser.java
+++ b/luni/src/main/java/java/util/concurrent/Phaser.java
@@ -227,7 +227,6 @@ import java.util.concurrent.locks.LockSupport;
* of participants.
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public class Phaser {
diff --git a/luni/src/main/java/java/util/concurrent/RecursiveAction.java b/luni/src/main/java/java/util/concurrent/RecursiveAction.java
index 8d666f6..e3a6340 100644
--- a/luni/src/main/java/java/util/concurrent/RecursiveAction.java
+++ b/luni/src/main/java/java/util/concurrent/RecursiveAction.java
@@ -131,7 +131,6 @@ package java.util.concurrent;
* }}</pre>
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public abstract class RecursiveAction extends ForkJoinTask<Void> {
diff --git a/luni/src/main/java/java/util/concurrent/RecursiveTask.java b/luni/src/main/java/java/util/concurrent/RecursiveTask.java
index 421c9d3..80baa52 100644
--- a/luni/src/main/java/java/util/concurrent/RecursiveTask.java
+++ b/luni/src/main/java/java/util/concurrent/RecursiveTask.java
@@ -34,7 +34,6 @@ package java.util.concurrent;
* sequentially solve rather than subdividing.
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public abstract class RecursiveTask<V> extends ForkJoinTask<V> {
diff --git a/luni/src/main/java/java/util/concurrent/ScheduledThreadPoolExecutor.java b/luni/src/main/java/java/util/concurrent/ScheduledThreadPoolExecutor.java
index a52351b..483981d 100644
--- a/luni/src/main/java/java/util/concurrent/ScheduledThreadPoolExecutor.java
+++ b/luni/src/main/java/java/util/concurrent/ScheduledThreadPoolExecutor.java
@@ -690,7 +690,6 @@ public class ScheduledThreadPoolExecutor
* @param value if {@code true}, remove on cancellation, else don't
* @see #getRemoveOnCancelPolicy
* @since 1.7
- * @hide
*/
public void setRemoveOnCancelPolicy(boolean value) {
removeOnCancel = value;
@@ -705,7 +704,6 @@ public class ScheduledThreadPoolExecutor
* from the queue
* @see #setRemoveOnCancelPolicy
* @since 1.7
- * @hide
*/
public boolean getRemoveOnCancelPolicy() {
return removeOnCancel;
diff --git a/luni/src/main/java/java/util/concurrent/ThreadLocalRandom.java b/luni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
index a559321..5baf75f 100644
--- a/luni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
+++ b/luni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
@@ -30,7 +30,6 @@ import java.util.Random;
* generation methods.
*
* @since 1.7
- * @hide
* @author Doug Lea
*/
public class ThreadLocalRandom extends Random {
diff --git a/luni/src/main/java/java/util/concurrent/TransferQueue.java b/luni/src/main/java/java/util/concurrent/TransferQueue.java
index 9cd5773..4c2be6f 100644
--- a/luni/src/main/java/java/util/concurrent/TransferQueue.java
+++ b/luni/src/main/java/java/util/concurrent/TransferQueue.java
@@ -33,7 +33,6 @@ package java.util.concurrent;
* and {@code transfer} are effectively synonymous.
*
* @since 1.7
- * @hide
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
diff --git a/luni/src/main/java/java/util/concurrent/atomic/Fences.java b/luni/src/main/java/java/util/concurrent/atomic/Fences.java
index 7ecf45a..5714ba0 100644
--- a/luni/src/main/java/java/util/concurrent/atomic/Fences.java
+++ b/luni/src/main/java/java/util/concurrent/atomic/Fences.java
@@ -453,7 +453,6 @@ package java.util.concurrent.atomic;
*
* </dl>
*
- * @since 1.7
* @hide
* @author Doug Lea
*/
diff --git a/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java b/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
index 4c5e280..37aa9d0 100644
--- a/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
+++ b/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
@@ -1255,7 +1255,6 @@ public abstract class AbstractQueuedLongSynchronizer
* current thread, and {@code false} if the current thread
* is at the head of the queue or the queue is empty
* @since 1.7
- * @hide
*/
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
diff --git a/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java b/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
index 0350060..e711da5 100644
--- a/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
+++ b/luni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
@@ -1485,7 +1485,6 @@ public abstract class AbstractQueuedSynchronizer
* current thread, and {@code false} if the current thread
* is at the head of the queue or the queue is empty
* @since 1.7
- * @hide
*/
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
diff --git a/luni/src/main/java/java/util/jar/Attributes.java b/luni/src/main/java/java/util/jar/Attributes.java
index 7e32897..483621b 100644
--- a/luni/src/main/java/java/util/jar/Attributes.java
+++ b/luni/src/main/java/java/util/jar/Attributes.java
@@ -288,7 +288,7 @@ public class Attributes implements Cloneable, Map<Object, Object> {
* @param value
* the value to store in this {@code Attributes}.
* @return the value being stored.
- * @exception ClassCastException
+ * @throws ClassCastException
* when key is not an {@code Attributes.Name} or value is not
* a {@code String}.
*/
@@ -307,9 +307,14 @@ public class Attributes implements Cloneable, Map<Object, Object> {
* Attributes}).
*/
public void putAll(Map<?, ?> attrib) {
- if (attrib == null || !(attrib instanceof Attributes)) {
+ if (attrib == null) {
+ throw new NullPointerException("attrib == null");
+ }
+
+ if (!(attrib instanceof Attributes)) {
throw new ClassCastException(attrib.getClass().getName() + " not an Attributes");
}
+
this.map.putAll(attrib);
}
diff --git a/luni/src/main/java/java/util/jar/JarEntry.java b/luni/src/main/java/java/util/jar/JarEntry.java
index 381dd52..bceef63 100644
--- a/luni/src/main/java/java/util/jar/JarEntry.java
+++ b/luni/src/main/java/java/util/jar/JarEntry.java
@@ -20,14 +20,14 @@ package java.util.jar;
import java.io.IOException;
import java.security.CodeSigner;
import java.security.cert.CertPath;
+import java.security.cert.CertPathValidator;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
-import java.util.List;
+import java.util.Arrays;
import java.util.zip.ZipEntry;
-import javax.security.auth.x500.X500Principal;
/**
* Represents a single file in a JAR archive together with the manifest
@@ -39,7 +39,7 @@ import javax.security.auth.x500.X500Principal;
public class JarEntry extends ZipEntry {
private Attributes attributes;
- JarFile parentJar;
+ final JarFile parentJar;
CodeSigner signers[];
@@ -56,6 +56,7 @@ public class JarEntry extends ZipEntry {
*/
public JarEntry(String name) {
super(name);
+ parentJar = null;
}
/**
@@ -65,15 +66,35 @@ public class JarEntry extends ZipEntry {
* The ZipEntry to obtain values from.
*/
public JarEntry(ZipEntry entry) {
+ this(entry, null);
+ }
+
+ JarEntry(ZipEntry entry, JarFile parentJar) {
super(entry);
+ this.parentJar = parentJar;
+ }
+
+ /**
+ * Create a new {@code JarEntry} using the values obtained from the
+ * argument.
+ *
+ * @param je
+ * The {@code JarEntry} to obtain values from.
+ */
+ public JarEntry(JarEntry je) {
+ super(je);
+ parentJar = je.parentJar;
+ attributes = je.attributes;
+ signers = je.signers;
}
+
/**
* Returns the {@code Attributes} object associated with this entry or
* {@code null} if none exists.
*
* @return the {@code Attributes} for this entry.
- * @exception IOException
+ * @throws IOException
* If an error occurs obtaining the {@code Attributes}.
* @see Attributes
*/
@@ -93,8 +114,12 @@ public class JarEntry extends ZipEntry {
* entry or {@code null} if none exists. Make sure that the everything is
* read from the input stream before calling this method, or else the method
* returns {@code null}.
+ * <p>
+ * This method returns all the signers' unverified chains concatenated
+ * together in one array. To know which certificates were tied to the
+ * private keys that made the signatures on this entry, see
+ * {@link #getCodeSigners()} instead.
*
- * @return the certificate for this entry.
* @see java.security.cert.Certificate
*/
public Certificate[] getCertificates() {
@@ -105,7 +130,27 @@ public class JarEntry extends ZipEntry {
if (jarVerifier == null) {
return null;
}
- return jarVerifier.getCertificates(getName());
+
+ Certificate[][] certChains = jarVerifier.getCertificateChains(getName());
+ if (certChains == null) {
+ return null;
+ }
+
+ // Measure number of certs.
+ int count = 0;
+ for (Certificate[] chain : certChains) {
+ count += chain.length;
+ }
+
+ // Create new array and copy all the certs into it.
+ Certificate[] certs = new Certificate[count];
+ int i = 0;
+ for (Certificate[] chain : certChains) {
+ System.arraycopy(chain, 0, certs, i, chain.length);
+ i += chain.length;
+ }
+
+ return certs;
}
void setAttributes(Attributes attrib) {
@@ -113,86 +158,64 @@ public class JarEntry extends ZipEntry {
}
/**
- * Create a new {@code JarEntry} using the values obtained from the
- * argument.
- *
- * @param je
- * The {@code JarEntry} to obtain values from.
- */
- public JarEntry(JarEntry je) {
- super(je);
- parentJar = je.parentJar;
- attributes = je.attributes;
- signers = je.signers;
- }
-
- /**
* Returns the code signers for the digital signatures associated with the
* JAR file. If there is no such code signer, it returns {@code null}. Make
* sure that the everything is read from the input stream before calling
* this method, or else the method returns {@code null}.
+ * <p>
+ * Only the digital signature on the entry is cryptographically verified.
+ * None of the certificates in the the {@link CertPath} returned from
+ * {@link CodeSigner#getSignerCertPath()} are verified and must be verified
+ * by the caller if needed. See {@link CertPathValidator} for more
+ * information.
*
- * @return the code signers for the JAR entry.
+ * @return an array of CodeSigner for this JAR entry.
* @see CodeSigner
*/
public CodeSigner[] getCodeSigners() {
+ if (parentJar == null) {
+ return null;
+ }
+
+ JarVerifier jarVerifier = parentJar.verifier;
+ if (jarVerifier == null) {
+ return null;
+ }
+
if (signers == null) {
- signers = getCodeSigners(getCertificates());
+ signers = getCodeSigners(jarVerifier.getCertificateChains(getName()));
}
if (signers == null) {
return null;
}
- CodeSigner[] tmp = new CodeSigner[signers.length];
- System.arraycopy(signers, 0, tmp, 0, tmp.length);
- return tmp;
+ return signers.clone();
}
- private CodeSigner[] getCodeSigners(Certificate[] certs) {
- if (certs == null) {
+ private CodeSigner[] getCodeSigners(Certificate[][] certChains) {
+ if (certChains == null) {
return null;
}
- X500Principal prevIssuer = null;
- ArrayList<Certificate> list = new ArrayList<Certificate>(certs.length);
- ArrayList<CodeSigner> asigners = new ArrayList<CodeSigner>();
+ ArrayList<CodeSigner> asigners = new ArrayList<CodeSigner>(certChains.length);
- for (Certificate element : certs) {
- if (!(element instanceof X509Certificate)) {
- // Only X509Certificate-s are taken into account - see API spec.
- continue;
- }
- X509Certificate x509 = (X509Certificate) element;
- if (prevIssuer != null) {
- X500Principal subj = x509.getSubjectX500Principal();
- if (!prevIssuer.equals(subj)) {
- // Ok, this ends the previous chain,
- // so transform this one into CertPath ...
- addCodeSigner(asigners, list);
- // ... and start a new one
- list.clear();
- }// else { it's still the same chain }
-
- }
- prevIssuer = x509.getIssuerX500Principal();
- list.add(x509);
- }
- if (!list.isEmpty()) {
- addCodeSigner(asigners, list);
- }
- if (asigners.isEmpty()) {
- // 'signers' is 'null' already
- return null;
+ for (Certificate[] chain : certChains) {
+ addCodeSigner(asigners, chain);
}
CodeSigner[] tmp = new CodeSigner[asigners.size()];
asigners.toArray(tmp);
return tmp;
-
}
- private void addCodeSigner(ArrayList<CodeSigner> asigners,
- List<Certificate> list) {
+ private void addCodeSigner(ArrayList<CodeSigner> asigners, Certificate[] certs) {
+ for (Certificate cert : certs) {
+ // Only X509Certificate instances are counted. See API spec.
+ if (!(cert instanceof X509Certificate)) {
+ return;
+ }
+ }
+
CertPath certPath = null;
if (!isFactoryChecked) {
try {
@@ -207,7 +230,7 @@ public class JarEntry extends ZipEntry {
return;
}
try {
- certPath = factory.generateCertPath(list);
+ certPath = factory.generateCertPath(Arrays.asList(certs));
} catch (CertificateException ex) {
// do nothing
}
diff --git a/luni/src/main/java/java/util/jar/JarFile.java b/luni/src/main/java/java/util/jar/JarFile.java
index 5293a89..6b147f6 100644
--- a/luni/src/main/java/java/util/jar/JarFile.java
+++ b/luni/src/main/java/java/util/jar/JarFile.java
@@ -23,7 +23,9 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
+import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import libcore.io.Streams;
@@ -48,28 +50,24 @@ public class JarFile extends ZipFile {
// The manifest after it has been read from the JAR.
private Manifest manifest;
- // The entry for the MANIFEST.MF file before it is read.
- private ZipEntry manifestEntry;
+ // The entry for the MANIFEST.MF file before the first call to getManifest().
+ private byte[] manifestBytes;
JarVerifier verifier;
private boolean closed = false;
static final class JarFileInputStream extends FilterInputStream {
- private long count;
-
- private ZipEntry zipEntry;
-
- private JarVerifier.VerifierEntry entry;
+ private final JarVerifier.VerifierEntry entry;
+ private long count;
private boolean done = false;
- JarFileInputStream(InputStream is, ZipEntry ze,
- JarVerifier.VerifierEntry e) {
+ JarFileInputStream(InputStream is, long size, JarVerifier.VerifierEntry e) {
super(is);
- zipEntry = ze;
- count = zipEntry.getSize();
entry = e;
+
+ count = size;
}
@Override
@@ -140,6 +138,24 @@ public class JarFile extends ZipFile {
}
}
+ static final class JarFileEnumerator implements Enumeration<JarEntry> {
+ final Enumeration<? extends ZipEntry> ze;
+ final JarFile jf;
+
+ JarFileEnumerator(Enumeration<? extends ZipEntry> zenum, JarFile jf) {
+ ze = zenum;
+ this.jf = jf;
+ }
+
+ public boolean hasMoreElements() {
+ return ze.hasMoreElements();
+ }
+
+ public JarEntry nextElement() {
+ return new JarEntry(ze.nextElement(), jf /* parentJar */);
+ }
+ }
+
/**
* Create a new {@code JarFile} using the contents of the specified file.
*
@@ -163,11 +179,7 @@ public class JarFile extends ZipFile {
* If the file cannot be read.
*/
public JarFile(File file, boolean verify) throws IOException {
- super(file);
- if (verify) {
- verifier = new JarVerifier(file.getPath());
- }
- readMetaEntries();
+ this(file, verify, ZipFile.OPEN_READ);
}
/**
@@ -184,21 +196,30 @@ public class JarFile extends ZipFile {
* If the file cannot be read.
*/
public JarFile(File file, boolean verify, int mode) throws IOException {
- this(file, verify, mode, false);
- }
-
- /**
- * See previous constructor for other parameter definitions.
- * @param chainCheck
- * whether or not to check certificate chain signatures
- * @hide
- */
- public JarFile(File file, boolean verify, int mode, boolean chainCheck) throws IOException {
super(file, mode);
- if (verify) {
- verifier = new JarVerifier(file.getPath(), chainCheck);
+
+ // Step 1: Scan the central directory for meta entries (MANIFEST.mf
+ // & possibly the signature files) and read them fully.
+ HashMap<String, byte[]> metaEntries = readMetaEntries(this, verify);
+
+ // Step 2: Construct a verifier with the information we have.
+ // Verification is possible *only* if the JAR file contains a manifest
+ // *AND* it contains signing related information (signature block
+ // files and the signature files).
+ //
+ // TODO: Is this really the behaviour we want if verify == true ?
+ // We silently skip verification for files that have no manifest or
+ // no signatures.
+ if (verify && metaEntries.containsKey(MANIFEST_NAME) &&
+ metaEntries.size() > 1) {
+ // We create the manifest straight away, so that we can create
+ // the jar verifier as well.
+ manifest = new Manifest(metaEntries.get(MANIFEST_NAME), true);
+ verifier = new JarVerifier(getName(), manifest, metaEntries);
+ } else {
+ verifier = null;
+ manifestBytes = metaEntries.get(MANIFEST_NAME);
}
- readMetaEntries();
}
/**
@@ -226,21 +247,7 @@ public class JarFile extends ZipFile {
* If file cannot be opened or read.
*/
public JarFile(String filename, boolean verify) throws IOException {
- this(filename, verify, false);
- }
-
- /**
- * See previous constructor for other parameter definitions.
- * @param chainCheck
- * whether or not to check certificate chain signatures
- * @hide
- */
- public JarFile(String filename, boolean verify, boolean chainCheck) throws IOException {
- super(filename);
- if (verify) {
- verifier = new JarVerifier(filename, chainCheck);
- }
- readMetaEntries();
+ this(new File(filename), verify, ZipFile.OPEN_READ);
}
/**
@@ -253,26 +260,6 @@ public class JarFile extends ZipFile {
*/
@Override
public Enumeration<JarEntry> entries() {
- class JarFileEnumerator implements Enumeration<JarEntry> {
- Enumeration<? extends ZipEntry> ze;
-
- JarFile jf;
-
- JarFileEnumerator(Enumeration<? extends ZipEntry> zenum, JarFile jf) {
- ze = zenum;
- this.jf = jf;
- }
-
- public boolean hasMoreElements() {
- return ze.hasMoreElements();
- }
-
- public JarEntry nextElement() {
- JarEntry je = new JarEntry(ze.nextElement());
- je.parentJar = jf;
- return je;
- }
- }
return new JarFileEnumerator(super.entries(), this);
}
@@ -303,73 +290,70 @@ public class JarFile extends ZipFile {
if (closed) {
throw new IllegalStateException("JarFile has been closed");
}
+
if (manifest != null) {
return manifest;
}
- try {
- InputStream is = super.getInputStream(manifestEntry);
- if (verifier != null) {
- verifier.addMetaEntry(manifestEntry.getName(), Streams.readFully(is));
- is = super.getInputStream(manifestEntry);
- }
- try {
- manifest = new Manifest(is, verifier != null);
- } finally {
- is.close();
- }
- manifestEntry = null; // Can discard the entry now.
- } catch (NullPointerException e) {
- manifestEntry = null;
+
+ // If manifest == null && manifestBytes == null, there's no manifest.
+ if (manifestBytes == null) {
+ return null;
}
+
+ // We hit this code path only if the verification isn't necessary. If
+ // we did decide to verify this file, we'd have created the Manifest and
+ // the associated Verifier in the constructor itself.
+ manifest = new Manifest(manifestBytes, false);
+ manifestBytes = null;
+
return manifest;
}
/**
- * Called by the JarFile constructors, this method reads the contents of the
+ * Called by the JarFile constructors, Reads the contents of the
* file's META-INF/ directory and picks out the MANIFEST.MF file and
- * verifier signature files if they exist. Any signature files found are
- * registered with the verifier.
+ * verifier signature files if they exist.
*
* @throws IOException
* if there is a problem reading the jar file entries.
+ * @return a map of entry names to their {@code byte[]} content.
*/
- private void readMetaEntries() throws IOException {
+ static HashMap<String, byte[]> readMetaEntries(ZipFile zipFile,
+ boolean verificationRequired) throws IOException {
// Get all meta directory entries
- ZipEntry[] metaEntries = getMetaEntriesImpl();
- if (metaEntries == null) {
- verifier = null;
- return;
- }
+ List<ZipEntry> metaEntries = getMetaEntries(zipFile);
- boolean signed = false;
+ HashMap<String, byte[]> metaEntriesMap = new HashMap<String, byte[]>();
for (ZipEntry entry : metaEntries) {
String entryName = entry.getName();
// Is this the entry for META-INF/MANIFEST.MF ?
- if (manifestEntry == null && entryName.equalsIgnoreCase(MANIFEST_NAME)) {
- manifestEntry = entry;
+ //
+ // TODO: Why do we need the containsKey check ? Shouldn't we discard
+ // files that contain duplicate entries like this as invalid ?.
+ if (entryName.equalsIgnoreCase(MANIFEST_NAME) &&
+ !metaEntriesMap.containsKey(MANIFEST_NAME)) {
+
+ metaEntriesMap.put(MANIFEST_NAME, Streams.readFully(
+ zipFile.getInputStream(entry)));
+
// If there is no verifier then we don't need to look any further.
- if (verifier == null) {
+ if (!verificationRequired) {
break;
}
- } else {
+ } else if (verificationRequired) {
// Is this an entry that the verifier needs?
- if (verifier != null
- && (endsWithIgnoreCase(entryName, ".SF")
- || endsWithIgnoreCase(entryName, ".DSA")
- || endsWithIgnoreCase(entryName, ".RSA")
- || endsWithIgnoreCase(entryName, ".EC"))) {
- signed = true;
- InputStream is = super.getInputStream(entry);
- verifier.addMetaEntry(entryName, Streams.readFully(is));
+ if (endsWithIgnoreCase(entryName, ".SF")
+ || endsWithIgnoreCase(entryName, ".DSA")
+ || endsWithIgnoreCase(entryName, ".RSA")
+ || endsWithIgnoreCase(entryName, ".EC")) {
+ InputStream is = zipFile.getInputStream(entry);
+ metaEntriesMap.put(entryName.toUpperCase(Locale.US), Streams.readFully(is));
}
}
}
- // If there were no signature files, then no verifier work to do.
- if (!signed) {
- verifier = null;
- }
+ return metaEntriesMap;
}
private static boolean endsWithIgnoreCase(String s, String suffix) {
@@ -388,24 +372,21 @@ public class JarFile extends ZipFile {
*/
@Override
public InputStream getInputStream(ZipEntry ze) throws IOException {
- if (manifestEntry != null) {
+ if (manifestBytes != null) {
getManifest();
}
+
if (verifier != null) {
- verifier.setManifest(getManifest());
- if (manifest != null) {
- verifier.mainAttributesEnd = manifest.getMainAttributesEnd();
- }
if (verifier.readCertificates()) {
verifier.removeMetaEntries();
- if (manifest != null) {
- manifest.removeChunks();
- }
+ manifest.removeChunks();
+
if (!verifier.isSignedJar()) {
verifier = null;
}
}
}
+
InputStream in = super.getInputStream(ze);
if (in == null) {
return null;
@@ -417,7 +398,7 @@ public class JarFile extends ZipFile {
if (entry == null) {
return in;
}
- return new JarFileInputStream(in, ze, entry);
+ return new JarFileInputStream(in, ze.getSize(), entry);
}
/**
@@ -434,20 +415,17 @@ public class JarFile extends ZipFile {
if (ze == null) {
return ze;
}
- JarEntry je = new JarEntry(ze);
- je.parentJar = this;
- return je;
+ return new JarEntry(ze, this /* parentJar */);
}
/**
* Returns all the ZipEntry's that relate to files in the
* JAR's META-INF directory.
- *
- * @return the list of ZipEntry's or {@code null} if there are none.
*/
- private ZipEntry[] getMetaEntriesImpl() {
+ private static List<ZipEntry> getMetaEntries(ZipFile zipFile) {
List<ZipEntry> list = new ArrayList<ZipEntry>(8);
- Enumeration<? extends ZipEntry> allEntries = entries();
+
+ Enumeration<? extends ZipEntry> allEntries = zipFile.entries();
while (allEntries.hasMoreElements()) {
ZipEntry ze = allEntries.nextElement();
if (ze.getName().startsWith(META_DIR)
@@ -455,12 +433,8 @@ public class JarFile extends ZipFile {
list.add(ze);
}
}
- if (list.size() == 0) {
- return null;
- }
- ZipEntry[] result = new ZipEntry[list.size()];
- list.toArray(result);
- return result;
+
+ return list;
}
/**
diff --git a/luni/src/main/java/java/util/jar/JarInputStream.java b/luni/src/main/java/java/util/jar/JarInputStream.java
index 5e08b5d..585c135 100644
--- a/luni/src/main/java/java/util/jar/JarInputStream.java
+++ b/luni/src/main/java/java/util/jar/JarInputStream.java
@@ -21,9 +21,11 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.HashMap;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
+import libcore.io.Streams;
/**
* The input stream from which the JAR file to be read may be fetched. It is
@@ -31,15 +33,20 @@ import java.util.zip.ZipInputStream;
*
* @see ZipInputStream
*/
+// TODO: The semantics provided by this class are really weird. The jar file
+// spec does not impose any ordering constraints on the entries of a jar file.
+// In particular, the Manifest and META-INF directory *need not appear first*. This
+// class will silently skip certificate checks for jar files where the manifest
+// isn't the first entry. To do this correctly, we need O(input_stream_length) memory.
public class JarInputStream extends ZipInputStream {
private Manifest manifest;
- private boolean eos = false;
+ private boolean verified = false;
- private JarEntry mEntry;
+ private JarEntry currentJarEntry;
- private JarEntry jarEntry;
+ private JarEntry pendingJarEntry;
private boolean isMeta;
@@ -60,38 +67,44 @@ public class JarInputStream extends ZipInputStream {
*/
public JarInputStream(InputStream stream, boolean verify) throws IOException {
super(stream);
- if (verify) {
- verifier = new JarVerifier("JarInputStream");
- }
- if ((mEntry = getNextJarEntry()) == null) {
+
+ verifier = null;
+ pendingJarEntry = null;
+ currentJarEntry = null;
+
+ if (getNextJarEntry() == null) {
return;
}
- if (mEntry.getName().equalsIgnoreCase(JarFile.META_DIR)) {
- mEntry = null; // modifies behavior of getNextJarEntry()
+
+ if (currentJarEntry.getName().equalsIgnoreCase(JarFile.META_DIR)) {
+ // Fetch the next entry, in the hope that it's the manifest file.
closeEntry();
- mEntry = getNextJarEntry();
+ getNextJarEntry();
}
- if (mEntry.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
- mEntry = null;
- manifest = new Manifest(this, verify);
+
+ if (currentJarEntry.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
+ final byte[] manifestBytes = Streams.readFullyNoClose(this);
+ manifest = new Manifest(manifestBytes, verify);
closeEntry();
+
if (verify) {
- verifier.setManifest(manifest);
- if (manifest != null) {
- verifier.mainAttributesEnd = manifest.getMainAttributesEnd();
- }
+ HashMap<String, byte[]> metaEntries = new HashMap<String, byte[]>();
+ metaEntries.put(JarFile.MANIFEST_NAME, manifestBytes);
+ verifier = new JarVerifier("JarInputStream", manifest, metaEntries);
}
-
- } else {
- Attributes temp = new Attributes(3);
- temp.map.put("hidden", null);
- mEntry.setAttributes(temp);
- /*
- * if not from the first entry, we will not get enough
- * information,so no verify will be taken out.
- */
- verifier = null;
}
+
+ // There was no manifest available, so we should return the current
+ // entry the next time getNextEntry is called.
+ pendingJarEntry = currentJarEntry;
+ currentJarEntry = null;
+
+ // If the manifest isn't the first entry, we will not have enough
+ // information to perform verification on entries that precede it.
+ //
+ // TODO: Should we throw if verify == true in this case ?
+ // TODO: We need all meta entries to be placed before the manifest
+ // as well.
}
/**
@@ -138,32 +151,39 @@ public class JarInputStream extends ZipInputStream {
*/
@Override
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
- if (mEntry != null) {
+ if (currentJarEntry == null) {
return -1;
}
+
int r = super.read(buffer, byteOffset, byteCount);
- if (verStream != null && !eos) {
+ // verifier can be null if we've been asked not to verify or if
+ // the manifest wasn't found.
+ //
+ // verStream will be null if we're reading the manifest or if we have
+ // no signatures or if the digest for this entry isn't present in the
+ // manifest.
+ if (verifier != null && verStream != null && !verified) {
if (r == -1) {
- eos = true;
- if (verifier != null) {
- if (isMeta) {
- verifier.addMetaEntry(jarEntry.getName(),
- ((ByteArrayOutputStream) verStream)
- .toByteArray());
- try {
- verifier.readCertificates();
- } catch (SecurityException e) {
- verifier = null;
- throw e;
- }
- } else {
- ((JarVerifier.VerifierEntry) verStream).verify();
+ // We've hit the end of this stream for the first time, so attempt
+ // a verification.
+ verified = true;
+ if (isMeta) {
+ verifier.addMetaEntry(currentJarEntry.getName(),
+ ((ByteArrayOutputStream) verStream).toByteArray());
+ try {
+ verifier.readCertificates();
+ } catch (SecurityException e) {
+ verifier = null;
+ throw e;
}
+ } else {
+ ((JarVerifier.VerifierEntry) verStream).verify();
}
} else {
verStream.write(buffer, byteOffset, r);
}
}
+
return r;
}
@@ -177,26 +197,47 @@ public class JarInputStream extends ZipInputStream {
*/
@Override
public ZipEntry getNextEntry() throws IOException {
- if (mEntry != null) {
- jarEntry = mEntry;
- mEntry = null;
- jarEntry.setAttributes(null);
- } else {
- jarEntry = (JarEntry) super.getNextEntry();
- if (jarEntry == null) {
- return null;
- }
- if (verifier != null) {
- isMeta = jarEntry.getName().toUpperCase(Locale.US).startsWith(JarFile.META_DIR);
- if (isMeta) {
- verStream = new ByteArrayOutputStream();
- } else {
- verStream = verifier.initEntry(jarEntry.getName());
- }
+ // NOTE: This function must update the value of currentJarEntry
+ // as a side effect.
+
+ if (pendingJarEntry != null) {
+ JarEntry pending = pendingJarEntry;
+ pendingJarEntry = null;
+ currentJarEntry = pending;
+ return pending;
+ }
+
+ currentJarEntry = (JarEntry) super.getNextEntry();
+ if (currentJarEntry == null) {
+ return null;
+ }
+
+ if (verifier != null) {
+ isMeta = currentJarEntry.getName().toUpperCase(Locale.US).startsWith(JarFile.META_DIR);
+ if (isMeta) {
+ final int entrySize = (int) currentJarEntry.getSize();
+ verStream = new ByteArrayOutputStream(entrySize > 0 ? entrySize : 8192);
+ } else {
+ verStream = verifier.initEntry(currentJarEntry.getName());
}
}
- eos = false;
- return jarEntry;
+
+ verified = false;
+ return currentJarEntry;
+ }
+
+ @Override
+ public void closeEntry() throws IOException {
+ // NOTE: This was the old behavior. A call to closeEntry() before the
+ // first call to getNextEntry should be a no-op. If we don't return early
+ // here, the super class will close pendingJarEntry for us and reads will
+ // fail.
+ if (pendingJarEntry != null) {
+ return;
+ }
+
+ super.closeEntry();
+ currentJarEntry = null;
}
@Override
diff --git a/luni/src/main/java/java/util/jar/JarVerifier.java b/luni/src/main/java/java/util/jar/JarVerifier.java
index 8185c6d..467e298 100644
--- a/luni/src/main/java/java/util/jar/JarVerifier.java
+++ b/luni/src/main/java/java/util/jar/JarVerifier.java
@@ -17,6 +17,7 @@
package java.util.jar;
+import org.apache.harmony.security.utils.JarUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -31,10 +32,7 @@ import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.Vector;
import libcore.io.Base64;
-import org.apache.harmony.security.utils.JarUtils;
/**
* Non-public class used by {@link JarFile} and {@link JarInputStream} to manage
@@ -63,44 +61,42 @@ class JarVerifier {
};
private final String jarName;
+ private final Manifest manifest;
+ private final HashMap<String, byte[]> metaEntries;
+ private final int mainAttributesEnd;
- private Manifest man;
-
- private HashMap<String, byte[]> metaEntries = new HashMap<String, byte[]>(5);
-
- private final Hashtable<String, HashMap<String, Attributes>> signatures = new Hashtable<String, HashMap<String, Attributes>>(
- 5);
+ private final Hashtable<String, HashMap<String, Attributes>> signatures =
+ new Hashtable<String, HashMap<String, Attributes>>(5);
- private final Hashtable<String, Certificate[]> certificates = new Hashtable<String, Certificate[]>(
- 5);
+ private final Hashtable<String, Certificate[]> certificates =
+ new Hashtable<String, Certificate[]>(5);
- private final Hashtable<String, Certificate[]> verifiedEntries = new Hashtable<String, Certificate[]>();
-
- int mainAttributesEnd;
-
- /** Whether or not to check certificate chain signatures. */
- private final boolean chainCheck;
+ private final Hashtable<String, Certificate[][]> verifiedEntries =
+ new Hashtable<String, Certificate[][]>();
/**
* Stores and a hash and a message digest and verifies that massage digest
* matches the hash.
*/
- class VerifierEntry extends OutputStream {
+ static class VerifierEntry extends OutputStream {
- private String name;
+ private final String name;
- private MessageDigest digest;
+ private final MessageDigest digest;
- private byte[] hash;
+ private final byte[] hash;
- private Certificate[] certificates;
+ private final Certificate[][] certChains;
+
+ private final Hashtable<String, Certificate[][]> verifiedEntries;
VerifierEntry(String name, MessageDigest digest, byte[] hash,
- Certificate[] certificates) {
+ Certificate[][] certChains, Hashtable<String, Certificate[][]> verifedEntries) {
this.name = name;
this.digest = digest;
this.hash = hash;
- this.certificates = certificates;
+ this.certChains = certChains;
+ this.verifiedEntries = verifedEntries;
}
/**
@@ -122,7 +118,7 @@ class JarVerifier {
/**
* Verifies that the digests stored in the manifest match the decrypted
* digests from the .SF file. This indicates the validity of the
- * signing, not the integrity of the file, as it's digest must be
+ * signing, not the integrity of the file, as its digest must be
* calculated and verified when its contents are read.
*
* @throws SecurityException
@@ -133,40 +129,33 @@ class JarVerifier {
void verify() {
byte[] d = digest.digest();
if (!MessageDigest.isEqual(d, Base64.decode(hash))) {
- throw invalidDigest(JarFile.MANIFEST_NAME, name, jarName);
+ throw invalidDigest(JarFile.MANIFEST_NAME, name, name);
}
- verifiedEntries.put(name, certificates);
+ verifiedEntries.put(name, certChains);
}
-
}
- private SecurityException invalidDigest(String signatureFile, String name, String jarName) {
+ private static SecurityException invalidDigest(String signatureFile, String name,
+ String jarName) {
throw new SecurityException(signatureFile + " has invalid digest for " + name +
" in " + jarName);
}
- private SecurityException failedVerification(String jarName, String signatureFile) {
+ private static SecurityException failedVerification(String jarName, String signatureFile) {
throw new SecurityException(jarName + " failed verification of " + signatureFile);
}
/**
- * Convenience constructor for backward compatibility.
- */
- JarVerifier(String name) {
- this(name, false);
- }
-
- /**
* Constructs and returns a new instance of {@code JarVerifier}.
*
* @param name
* the name of the JAR file being verified.
- * @param chainCheck
- * whether to check the certificate chain signatures
*/
- JarVerifier(String name, boolean chainCheck) {
+ JarVerifier(String name, Manifest manifest, HashMap<String, byte[]> metaEntries) {
jarName = name;
- this.chainCheck = chainCheck;
+ this.manifest = manifest;
+ this.metaEntries = metaEntries;
+ this.mainAttributesEnd = manifest.getMainAttributesEnd();
}
/**
@@ -185,17 +174,17 @@ class JarVerifier {
// If no manifest is present by the time an entry is found,
// verification cannot occur. If no signature files have
// been found, do not verify.
- if (man == null || signatures.size() == 0) {
+ if (manifest == null || signatures.isEmpty()) {
return null;
}
- Attributes attributes = man.getAttributes(name);
+ Attributes attributes = manifest.getAttributes(name);
// entry has no digest
if (attributes == null) {
return null;
}
- ArrayList<Certificate> certs = new ArrayList<Certificate>();
+ ArrayList<Certificate[]> certChains = new ArrayList<Certificate[]>();
Iterator<Map.Entry<String, HashMap<String, Attributes>>> it = signatures.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, HashMap<String, Attributes>> entry = it.next();
@@ -203,15 +192,18 @@ class JarVerifier {
if (hm.get(name) != null) {
// Found an entry for entry name in .SF file
String signatureFile = entry.getKey();
- certs.addAll(getSignerCertificates(signatureFile, certificates));
+ Certificate[] certChain = certificates.get(signatureFile);
+ if (certChain != null) {
+ certChains.add(certChain);
+ }
}
}
// entry is not signed
- if (certs.isEmpty()) {
+ if (certChains.isEmpty()) {
return null;
}
- Certificate[] certificatesArray = certs.toArray(new Certificate[certs.size()]);
+ Certificate[][] certChainsArray = certChains.toArray(new Certificate[certChains.size()][]);
for (int i = 0; i < DIGEST_ALGORITHMS.length; i++) {
final String algorithm = DIGEST_ALGORITHMS[i];
@@ -223,9 +215,8 @@ class JarVerifier {
try {
return new VerifierEntry(name, MessageDigest.getInstance(algorithm), hashBytes,
- certificatesArray);
- } catch (NoSuchAlgorithmException e) {
- // ignored
+ certChainsArray, verifiedEntries);
+ } catch (NoSuchAlgorithmException ignored) {
}
}
return null;
@@ -266,18 +257,15 @@ class JarVerifier {
* corresponding signature file.
*/
synchronized boolean readCertificates() {
- if (metaEntries == null) {
+ if (metaEntries.isEmpty()) {
return false;
}
+
Iterator<String> it = metaEntries.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if (key.endsWith(".DSA") || key.endsWith(".RSA") || key.endsWith(".EC")) {
verifyCertificate(key);
- // Check for recursive class load
- if (metaEntries == null) {
- return false;
- }
it.remove();
}
}
@@ -295,9 +283,9 @@ class JarVerifier {
return;
}
- byte[] manifest = metaEntries.get(JarFile.MANIFEST_NAME);
+ byte[] manifestBytes = metaEntries.get(JarFile.MANIFEST_NAME);
// Manifest entry is required for any verifications.
- if (manifest == null) {
+ if (manifestBytes == null) {
return;
}
@@ -305,15 +293,7 @@ class JarVerifier {
try {
Certificate[] signerCertChain = JarUtils.verifySignature(
new ByteArrayInputStream(sfBytes),
- new ByteArrayInputStream(sBlockBytes),
- chainCheck);
- /*
- * Recursive call in loading security provider related class which
- * is in a signed JAR.
- */
- if (metaEntries == null) {
- return;
- }
+ new ByteArrayInputStream(sBlockBytes));
if (signerCertChain != null) {
certificates.put(signatureFile, signerCertChain);
}
@@ -350,22 +330,22 @@ class JarVerifier {
// such verification.
if (mainAttributesEnd > 0 && !createdBySigntool) {
String digestAttribute = "-Digest-Manifest-Main-Attributes";
- if (!verify(attributes, digestAttribute, manifest, 0, mainAttributesEnd, false, true)) {
+ if (!verify(attributes, digestAttribute, manifestBytes, 0, mainAttributesEnd, false, true)) {
throw failedVerification(jarName, signatureFile);
}
}
// Use .SF to verify the whole manifest.
String digestAttribute = createdBySigntool ? "-Digest" : "-Digest-Manifest";
- if (!verify(attributes, digestAttribute, manifest, 0, manifest.length, false, false)) {
+ if (!verify(attributes, digestAttribute, manifestBytes, 0, manifestBytes.length, false, false)) {
Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Attributes> entry = it.next();
- Manifest.Chunk chunk = man.getChunk(entry.getKey());
+ Manifest.Chunk chunk = manifest.getChunk(entry.getKey());
if (chunk == null) {
return;
}
- if (!verify(entry.getValue(), "-Digest", manifest,
+ if (!verify(entry.getValue(), "-Digest", manifestBytes,
chunk.start, chunk.end, createdBySigntool, false)) {
throw invalidDigest(signatureFile, entry.getKey(), jarName);
}
@@ -376,16 +356,6 @@ class JarVerifier {
}
/**
- * Associate this verifier with the specified {@link Manifest} object.
- *
- * @param mf
- * a {@code java.util.jar.Manifest} object.
- */
- void setManifest(Manifest mf) {
- man = mf;
- }
-
- /**
* Returns a <code>boolean</code> indication of whether or not the
* associated jar file is signed.
*
@@ -424,58 +394,23 @@ class JarVerifier {
}
/**
- * Returns all of the {@link java.security.cert.Certificate} instances that
+ * Returns all of the {@link java.security.cert.Certificate} chains that
* were used to verify the signature on the JAR entry called
- * {@code name}.
+ * {@code name}. Callers must not modify the returned arrays.
*
* @param name
* the name of a JAR entry.
- * @return an array of {@link java.security.cert.Certificate}.
+ * @return an array of {@link java.security.cert.Certificate} chains.
*/
- Certificate[] getCertificates(String name) {
- Certificate[] verifiedCerts = verifiedEntries.get(name);
- if (verifiedCerts == null) {
- return null;
- }
- return verifiedCerts.clone();
+ Certificate[][] getCertificateChains(String name) {
+ return verifiedEntries.get(name);
}
/**
* Remove all entries from the internal collection of data held about each
* JAR entry in the {@code META-INF} directory.
- *
- * @see #addMetaEntry(String, byte[])
*/
void removeMetaEntries() {
- metaEntries = null;
- }
-
- /**
- * Returns a {@code Vector} of all of the
- * {@link java.security.cert.Certificate}s that are associated with the
- * signing of the named signature file.
- *
- * @param signatureFileName
- * the name of a signature file.
- * @param certificates
- * a {@code Map} of all of the certificate chains discovered so
- * far while attempting to verify the JAR that contains the
- * signature file {@code signatureFileName}. This object is
- * previously set in the course of one or more calls to
- * {@link #verifyJarSignatureFile(String, String, String, Map, Map)}
- * where it was passed as the last argument.
- * @return all of the {@code Certificate} entries for the signer of the JAR
- * whose actions led to the creation of the named signature file.
- */
- public static Vector<Certificate> getSignerCertificates(
- String signatureFileName, Map<String, Certificate[]> certificates) {
- Vector<Certificate> result = new Vector<Certificate>();
- Certificate[] certChain = certificates.get(signatureFileName);
- if (certChain != null) {
- for (Certificate element : certChain) {
- result.add(element);
- }
- }
- return result;
+ metaEntries.clear();
}
}
diff --git a/luni/src/main/java/java/util/jar/Manifest.java b/luni/src/main/java/java/util/jar/Manifest.java
index b6ebddc..6a3936d 100644
--- a/luni/src/main/java/java/util/jar/Manifest.java
+++ b/luni/src/main/java/java/util/jar/Manifest.java
@@ -17,11 +17,9 @@
package java.util.jar;
-import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
@@ -43,26 +41,12 @@ public class Manifest implements Cloneable {
private static final byte[] VALUE_SEPARATOR = new byte[] { ':', ' ' };
- private static final Field BAIS_BUF = getByteArrayInputStreamField("buf");
- private static final Field BAIS_POS = getByteArrayInputStreamField("pos");
+ private final Attributes mainAttributes;
+ private final HashMap<String, Attributes> entries;
- private static Field getByteArrayInputStreamField(String name) {
- try {
- Field f = ByteArrayInputStream.class.getDeclaredField(name);
- f.setAccessible(true);
- return f;
- } catch (Exception ex) {
- throw new AssertionError(ex);
- }
- }
-
- private Attributes mainAttributes = new Attributes();
-
- private HashMap<String, Attributes> entries = new HashMap<String, Attributes>();
-
- static class Chunk {
- int start;
- int end;
+ static final class Chunk {
+ final int start;
+ final int end;
Chunk(int start, int end) {
this.start = start;
@@ -82,6 +66,8 @@ public class Manifest implements Cloneable {
* Creates a new {@code Manifest} instance.
*/
public Manifest() {
+ entries = new HashMap<String, Attributes>();
+ mainAttributes = new Attributes();
}
/**
@@ -94,7 +80,8 @@ public class Manifest implements Cloneable {
* if an IO error occurs while creating this {@code Manifest}
*/
public Manifest(InputStream is) throws IOException {
- read(is);
+ this();
+ read(Streams.readFully(is));
}
/**
@@ -111,11 +98,12 @@ public class Manifest implements Cloneable {
.getEntries()).clone();
}
- Manifest(InputStream is, boolean readChunks) throws IOException {
+ Manifest(byte[] manifestBytes, boolean readChunks) throws IOException {
+ this();
if (readChunks) {
chunks = new HashMap<String, Chunk>();
}
- read(is);
+ read(manifestBytes);
}
/**
@@ -192,58 +180,20 @@ public class Manifest implements Cloneable {
* If an error occurs reading the manifest.
*/
public void read(InputStream is) throws IOException {
- byte[] buf;
- if (is instanceof ByteArrayInputStream) {
- buf = exposeByteArrayInputStreamBytes((ByteArrayInputStream) is);
- } else {
- buf = Streams.readFullyNoClose(is);
- }
+ read(Streams.readFullyNoClose(is));
+ }
+ private void read(byte[] buf) throws IOException {
if (buf.length == 0) {
return;
}
- // a workaround for HARMONY-5662
- // replace EOF and NUL with another new line
- // which does not trigger an error
- byte b = buf[buf.length - 1];
- if (b == 0 || b == 26) {
- buf[buf.length - 1] = '\n';
- }
-
ManifestReader im = new ManifestReader(buf, mainAttributes);
mainEnd = im.getEndOfMainSection();
im.readEntries(entries, chunks);
}
/**
- * Returns a byte[] containing all the bytes from a ByteArrayInputStream.
- * Where possible, this returns the actual array rather than a copy.
- */
- private static byte[] exposeByteArrayInputStreamBytes(ByteArrayInputStream bais) {
- byte[] buffer;
- synchronized (bais) {
- byte[] buf;
- int pos;
- try {
- buf = (byte[]) BAIS_BUF.get(bais);
- pos = BAIS_POS.getInt(bais);
- } catch (IllegalAccessException iae) {
- throw new AssertionError(iae);
- }
- int available = bais.available();
- if (pos == 0 && buf.length == available) {
- buffer = buf;
- } else {
- buffer = new byte[available];
- System.arraycopy(buf, pos, buffer, 0, available);
- }
- bais.skip(available);
- }
- return buffer;
- }
-
- /**
* Returns the hash code for this instance.
*
* @return this {@code Manifest}'s hashCode.
diff --git a/luni/src/main/java/java/util/jar/StrictJarFile.java b/luni/src/main/java/java/util/jar/StrictJarFile.java
new file mode 100644
index 0000000..4a8af5f
--- /dev/null
+++ b/luni/src/main/java/java/util/jar/StrictJarFile.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2013 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 java.util.jar;
+
+import dalvik.system.CloseGuard;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+import java.security.cert.Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.zip.Inflater;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import libcore.io.IoUtils;
+import libcore.io.Streams;
+
+/**
+ * A subset of the JarFile API implemented as a thin wrapper over
+ * system/core/libziparchive.
+ *
+ * @hide for internal use only. Not API compatible (or as forgiving) as
+ * {@link java.util.jar.JarFile}
+ */
+public final class StrictJarFile {
+
+ private final long nativeHandle;
+
+ // NOTE: It's possible to share a file descriptor with the native
+ // code, at the cost of some additional complexity.
+ private final RandomAccessFile raf;
+
+ private final Manifest manifest;
+ private final JarVerifier verifier;
+
+ private final boolean isSigned;
+
+ private final CloseGuard guard = CloseGuard.get();
+ private boolean closed;
+
+ public StrictJarFile(String fileName) throws IOException {
+ this.nativeHandle = nativeOpenJarFile(fileName);
+ this.raf = new RandomAccessFile(fileName, "r");
+
+ try {
+ // Read the MANIFEST and signature files up front and try to
+ // parse them. We never want to accept a JAR File with broken signatures
+ // or manifests, so it's best to throw as early as possible.
+ HashMap<String, byte[]> metaEntries = getMetaEntries();
+ this.manifest = new Manifest(metaEntries.get(JarFile.MANIFEST_NAME), true);
+ this.verifier = new JarVerifier(fileName, manifest, metaEntries);
+
+ isSigned = verifier.readCertificates() && verifier.isSignedJar();
+ } catch (IOException ioe) {
+ nativeClose(this.nativeHandle);
+ throw ioe;
+ }
+
+ guard.open("close");
+ }
+
+ public Manifest getManifest() {
+ return manifest;
+ }
+
+ public Iterator<ZipEntry> iterator() throws IOException {
+ return new EntryIterator(nativeHandle, "");
+ }
+
+ public ZipEntry findEntry(String name) {
+ return nativeFindEntry(nativeHandle, name);
+ }
+
+ /**
+ * Return all certificate chains for a given {@link ZipEntry} belonging to this jar.
+ * This method MUST be called only after fully exhausting the InputStream belonging
+ * to this entry.
+ *
+ * Returns {@code null} if this jar file isn't signed or if this method is
+ * called before the stream is processed.
+ */
+ public Certificate[][] getCertificateChains(ZipEntry ze) {
+ if (isSigned) {
+ return verifier.getCertificateChains(ze.getName());
+ }
+
+ return null;
+ }
+
+ /**
+ * Return all certificates for a given {@link ZipEntry} belonging to this jar.
+ * This method MUST be called only after fully exhausting the InputStream belonging
+ * to this entry.
+ *
+ * Returns {@code null} if this jar file isn't signed or if this method is
+ * called before the stream is processed.
+ *
+ * @deprecated Switch callers to use getCertificateChains instead
+ */
+ @Deprecated
+ public Certificate[] getCertificates(ZipEntry ze) {
+ if (isSigned) {
+ Certificate[][] certChains = verifier.getCertificateChains(ze.getName());
+
+ // Measure number of certs.
+ int count = 0;
+ for (Certificate[] chain : certChains) {
+ count += chain.length;
+ }
+
+ // Create new array and copy all the certs into it.
+ Certificate[] certs = new Certificate[count];
+ int i = 0;
+ for (Certificate[] chain : certChains) {
+ System.arraycopy(chain, 0, certs, i, chain.length);
+ i += chain.length;
+ }
+
+ return certs;
+ }
+
+ return null;
+ }
+
+ public InputStream getInputStream(ZipEntry ze) {
+ final InputStream is = getZipInputStream(ze);
+
+ if (isSigned) {
+ JarVerifier.VerifierEntry entry = verifier.initEntry(ze.getName());
+ if (entry == null) {
+ return is;
+ }
+
+ return new JarFile.JarFileInputStream(is, ze.getSize(), entry);
+ }
+
+ return is;
+ }
+
+ public void close() throws IOException {
+ if (!closed) {
+ guard.close();
+
+ nativeClose(nativeHandle);
+ IoUtils.closeQuietly(raf);
+ closed = true;
+ }
+ }
+
+ private InputStream getZipInputStream(ZipEntry ze) {
+ if (ze.getMethod() == ZipEntry.STORED) {
+ return new ZipFile.RAFStream(raf, ze.getDataOffset(),
+ ze.getDataOffset() + ze.getSize());
+ } else {
+ final ZipFile.RAFStream wrapped = new ZipFile.RAFStream(
+ raf, ze.getDataOffset(), ze.getDataOffset() + ze.getCompressedSize());
+
+ int bufSize = Math.max(1024, (int) Math.min(ze.getSize(), 65535L));
+ return new ZipFile.ZipInflaterInputStream(wrapped, new Inflater(true), bufSize, ze);
+ }
+ }
+
+ static final class EntryIterator implements Iterator<ZipEntry> {
+ private final long iterationHandle;
+ private ZipEntry nextEntry;
+
+ EntryIterator(long nativeHandle, String prefix) throws IOException {
+ iterationHandle = nativeStartIteration(nativeHandle, prefix);
+ }
+
+ public ZipEntry next() {
+ if (nextEntry != null) {
+ final ZipEntry ze = nextEntry;
+ nextEntry = null;
+ return ze;
+ }
+
+ return nativeNextEntry(iterationHandle);
+ }
+
+ public boolean hasNext() {
+ if (nextEntry != null) {
+ return true;
+ }
+
+ final ZipEntry ze = nativeNextEntry(iterationHandle);
+ if (ze == null) {
+ return false;
+ }
+
+ nextEntry = ze;
+ return true;
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private HashMap<String, byte[]> getMetaEntries() throws IOException {
+ HashMap<String, byte[]> metaEntries = new HashMap<String, byte[]>();
+
+ Iterator<ZipEntry> entryIterator = new EntryIterator(nativeHandle, "META-INF/");
+ while (entryIterator.hasNext()) {
+ final ZipEntry entry = entryIterator.next();
+ metaEntries.put(entry.getName(), Streams.readFully(getInputStream(entry)));
+ }
+
+ return metaEntries;
+ }
+
+ private static native long nativeOpenJarFile(String fileName) throws IOException;
+ private static native long nativeStartIteration(long nativeHandle, String prefix);
+ private static native ZipEntry nativeNextEntry(long iterationHandle);
+ private static native ZipEntry nativeFindEntry(long nativeHandle, String entryName);
+ private static native void nativeClose(long nativeHandle);
+}
diff --git a/luni/src/main/java/java/util/logging/SocketHandler.java b/luni/src/main/java/java/util/logging/SocketHandler.java
index 85a9e6c..48bfc0e 100644
--- a/luni/src/main/java/java/util/logging/SocketHandler.java
+++ b/luni/src/main/java/java/util/logging/SocketHandler.java
@@ -108,12 +108,9 @@ public class SocketHandler extends StreamHandler {
// check the validity of the port number
int p = 0;
try {
- p = Integer.parseInt(port);
+ p = Integer.parsePositiveInt(port);
} catch (NumberFormatException e) {
- throw new IllegalArgumentException("Illegal port argument");
- }
- if (p <= 0) {
- throw new IllegalArgumentException("Illegal port argument");
+ throw new IllegalArgumentException("Illegal port argument " + port);
}
// establish the network connection
try {
diff --git a/luni/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java b/luni/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java
index 8f2d0aa..154c71e 100644
--- a/luni/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java
+++ b/luni/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java
@@ -24,10 +24,12 @@ package java.util.prefs;
*/
class FilePreferencesFactoryImpl implements PreferencesFactory {
// user root preferences
- private static final Preferences USER_ROOT = new FilePreferencesImpl(true);
+ private static final Preferences USER_ROOT = new FilePreferencesImpl(
+ System.getProperty("user.home") + "/.java/.userPrefs", true);
// system root preferences
- private static final Preferences SYSTEM_ROOT = new FilePreferencesImpl(false);
+ private static final Preferences SYSTEM_ROOT = new FilePreferencesImpl(
+ System.getProperty("java.home") + "/.systemPrefs", false);
public FilePreferencesFactoryImpl() {
}
@@ -39,5 +41,4 @@ class FilePreferencesFactoryImpl implements PreferencesFactory {
public Preferences systemRoot() {
return SYSTEM_ROOT;
}
-
}
diff --git a/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java b/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java
index bd367a6..de1ead4 100644
--- a/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java
+++ b/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java
@@ -30,20 +30,15 @@ import java.util.Set;
* TODO some sync mechanism with backend, Performance - check file edit date
*
* @since 1.4
+ *
+ * @hide
*/
-class FilePreferencesImpl extends AbstractPreferences {
-
+public class FilePreferencesImpl extends AbstractPreferences {
//prefs file name
private static final String PREFS_FILE_NAME = "prefs.xml";
- //home directory for user prefs
- private static String USER_HOME = System.getProperty("user.home") + "/.java/.userPrefs";
-
- //home directory for system prefs
- private static String SYSTEM_HOME = System.getProperty("java.home") + "/.systemPrefs";
-
//file path for this preferences node
- private String path;
+ private final String path;
//internal cache for prefs key-value pair
private Properties prefs;
@@ -67,13 +62,15 @@ class FilePreferencesImpl extends AbstractPreferences {
*/
/**
- * Construct root <code>FilePreferencesImpl</code> instance, construct
- * user root if userNode is true, system root otherwise
+ * Construct root <code>FilePreferencesImpl</code> instance rooted
+ * at the given path.
+ *
+ * @hide
*/
- FilePreferencesImpl(boolean userNode) {
+ public FilePreferencesImpl(String path, boolean isUserNode) {
super(null, "");
- this.userNode = userNode;
- path = userNode ? USER_HOME : SYSTEM_HOME;
+ this.path = path;
+ this.userNode = isUserNode;
initPrefs();
}
diff --git a/luni/src/main/java/java/util/prefs/Preferences.java b/luni/src/main/java/java/util/prefs/Preferences.java
index b808052..342be70 100644
--- a/luni/src/main/java/java/util/prefs/Preferences.java
+++ b/luni/src/main/java/java/util/prefs/Preferences.java
@@ -98,8 +98,17 @@ public abstract class Preferences {
*/
public static final int MAX_VALUE_LENGTH = 8192;
- //factory used to get user/system prefs root
- private static final PreferencesFactory factory = findPreferencesFactory();
+ // factory used to get user/system prefs root
+ private static volatile PreferencesFactory factory = findPreferencesFactory();
+
+ /**
+ * @hide for testing only.
+ */
+ public static PreferencesFactory setPreferencesFactory(PreferencesFactory pf) {
+ PreferencesFactory previous = factory;
+ factory = pf;
+ return previous;
+ }
private static PreferencesFactory findPreferencesFactory() {
// Try the system property first...
@@ -780,6 +789,11 @@ public abstract class Preferences {
public abstract void sync() throws BackingStoreException;
/**
+ * <strong>Legacy code; do not use.</strong> On Android, the Preference nodes
+ * corresponding to the "system" and "user" preferences are stored in sections
+ * of the file system that are inaccessible to apps. Further, allowing apps to set
+ * "system wide" preferences is contrary to android's security model.
+ *
* Returns the system preference node for the package of the given class.
* The absolute path of the returned node is one slash followed by the given
* class's full package name, replacing each period character ('.') with
@@ -796,11 +810,16 @@ public abstract class Preferences {
* @throws NullPointerException
* if the given class is {@code null}.
*/
- public static Preferences systemNodeForPackage (Class<?> c) {
+ public static Preferences systemNodeForPackage(Class<?> c) {
return factory.systemRoot().node(getNodeName(c));
}
/**
+ * <strong>Legacy code; do not use.</strong> On Android, the Preference nodes
+ * corresponding to the "system" and "user" preferences are stored in sections
+ * of the file system that are inaccessible to apps. Further, allowing apps to set
+ * "system wide" preferences is contrary to android's security model.
+ *
* Returns the root node of the system preference hierarchy.
*
* @return the system preference hierarchy root node.
@@ -810,6 +829,13 @@ public abstract class Preferences {
}
/**
+ *
+ * <strong>Legacy code; do not use.</strong> On Android, the Preference nodes
+ * corresponding to the "system" and "user" preferences are stored in sections
+ * of the file system that are inaccessible to apps. Further, allowing apps to set
+ * "system wide" preferences is contrary to android's security model.
+ *
+ * <p>
* Returns the user preference node for the package of the given class.
* The absolute path of the returned node is one slash followed by the given
* class's full package name, replacing each period character ('.') with
@@ -820,13 +846,11 @@ public abstract class Preferences {
* by this method won't necessarily be persisted until the method {@code
* flush()} is invoked.
*
- * @param c
- * the given class.
* @return the user preference node for the package of the given class.
* @throws NullPointerException
* if the given class is {@code null}.
*/
- public static Preferences userNodeForPackage (Class<?> c) {
+ public static Preferences userNodeForPackage(Class<?> c) {
return factory.userRoot().node(getNodeName(c));
}
@@ -840,6 +864,11 @@ public abstract class Preferences {
}
/**
+ * <strong>Legacy code; do not use.</strong> On Android, the Preference nodes
+ * corresponding to the "system" and "user" preferences are stored in sections
+ * of the file system that are inaccessible to apps. Further, allowing apps to set
+ * "system wide" preferences is contrary to android's security model.
+ *
* Returns the root node of the user preference hierarchy.
*
* @return the user preference hierarchy root node.
diff --git a/luni/src/main/java/java/util/regex/MatchResult.java b/luni/src/main/java/java/util/regex/MatchResult.java
index 76c17a8..c77206d 100644
--- a/luni/src/main/java/java/util/regex/MatchResult.java
+++ b/luni/src/main/java/java/util/regex/MatchResult.java
@@ -19,79 +19,65 @@ package java.util.regex;
/**
* Holds the results of a successful match of a {@link Pattern} against a
- * given string. The result is divided into groups, with one group for each
- * pair of parentheses in the regular expression and an additional group for
- * the whole regular expression. The start, end, and contents of each group
- * can be queried.
- *
- * @see Matcher
- * @see Matcher#toMatchResult()
+ * given string. Typically this is an instance of {@link Matcher}, but
+ * since that's a mutable class it's also possible to freeze its current
+ * state using {@link Matcher#toMatchResult}.
*/
public interface MatchResult {
/**
* Returns the index of the first character following the text that matched
* the whole regular expression.
- *
- * @return the character index.
*/
int end();
/**
* Returns the index of the first character following the text that matched
- * a given group.
- *
- * @param group
- * the group, ranging from 0 to groupCount() - 1, with 0
- * representing the whole pattern.
- *
- * @return the character index.
+ * a given group. See {@link #group} for an explanation of group indexes.
*/
int end(int group);
/**
* Returns the text that matched the whole regular expression.
- *
- * @return the text.
*/
String group();
/**
* Returns the text that matched a given group of the regular expression.
*
- * @param group
- * the group, ranging from 0 to groupCount() - 1, with 0
- * representing the whole pattern.
+ * <p>Explicit capturing groups in the pattern are numbered left to right in order
+ * of their <i>opening</i> parenthesis, starting at 1.
+ * The special group 0 represents the entire match (as if the entire pattern is surrounded
+ * by an implicit capturing group).
+ * For example, "a((b)c)" matching "abc" would give the following groups:
+ * <pre>
+ * 0 "abc"
+ * 1 "bc"
+ * 2 "b"
+ * </pre>
*
- * @return the text that matched the group.
+ * <p>An optional capturing group that failed to match as part of an overall
+ * successful match (for example, "a(b)?c" matching "ac") returns null.
+ * A capturing group that matched the empty string (for example, "a(b?)c" matching "ac")
+ * returns the empty string.
*/
String group(int group);
/**
- * Returns the number of groups in the result, which is always equal to
+ * Returns the number of groups in the results, which is always equal to
* the number of groups in the original regular expression.
- *
- * @return the number of groups.
*/
int groupCount();
/**
- * Returns the index of the first character of the text that matched
- * the whole regular expression.
- *
- * @return the character index.
+ * Returns the index of the first character of the text that matched the
+ * whole regular expression.
*/
int start();
/**
* Returns the index of the first character of the text that matched a given
- * group.
- *
- * @param group
- * the group, ranging from 0 to groupCount() - 1, with 0
- * representing the whole pattern.
- *
- * @return the character index.
+ * group. See {@link #group} for an explanation of group indexes.
*/
int start(int group);
}
diff --git a/luni/src/main/java/java/util/regex/MatchResultImpl.java b/luni/src/main/java/java/util/regex/MatchResultImpl.java
index b685757..6a0d948 100644
--- a/luni/src/main/java/java/util/regex/MatchResultImpl.java
+++ b/luni/src/main/java/java/util/regex/MatchResultImpl.java
@@ -32,7 +32,7 @@ class MatchResultImpl implements MatchResult {
/**
* Holds the offsets of the groups in the input text. The first two
- * elements specifiy start and end of the zero group, the next two specify
+ * elements specify start and end of the zero group, the next two specify
* group 1, and so on.
*/
private int[] offsets;
diff --git a/luni/src/main/java/java/util/regex/Matcher.java b/luni/src/main/java/java/util/regex/Matcher.java
index 02531d7..d181d45 100644
--- a/luni/src/main/java/java/util/regex/Matcher.java
+++ b/luni/src/main/java/java/util/regex/Matcher.java
@@ -276,8 +276,6 @@ public final class Matcher implements MatchResult {
* walk through the input and replace all matches of the {@code Pattern}
* with something else.
*
- * @param buffer
- * the {@code StringBuffer} to append to.
* @return the {@code StringBuffer}.
* @throws IllegalStateException
* if no successful match has been made.
@@ -325,57 +323,12 @@ public final class Matcher implements MatchResult {
/**
* Returns the {@link Pattern} instance used inside this matcher.
- *
- * @return the {@code Pattern} instance.
*/
public Pattern pattern() {
return pattern;
}
/**
- * Returns the text that matched a given group of the regular expression.
- * Explicit capturing groups in the pattern are numbered left to right in order
- * of their <i>opening</i> parenthesis, starting at 1.
- * The special group 0 represents the entire match (as if the entire pattern is surrounded
- * by an implicit capturing group).
- * For example, "a((b)c)" matching "abc" would give the following groups:
- * <pre>
- * 0 "abc"
- * 1 "bc"
- * 2 "b"
- * </pre>
- *
- * <p>An optional capturing group that failed to match as part of an overall
- * successful match (for example, "a(b)?c" matching "ac") returns null.
- * A capturing group that matched the empty string (for example, "a(b?)c" matching "ac")
- * returns the empty string.
- *
- * @throws IllegalStateException
- * if no successful match has been made.
- */
- public String group(int group) {
- ensureMatch();
- int from = matchOffsets[group * 2];
- int to = matchOffsets[(group * 2) + 1];
- if (from == -1 || to == -1) {
- return null;
- } else {
- return input.substring(from, to);
- }
- }
-
- /**
- * Returns the text that matched the whole regular expression.
- *
- * @return the text.
- * @throws IllegalStateException
- * if no successful match has been made.
- */
- public String group() {
- return group(0);
- }
-
- /**
* Returns true if there is another match in the input, starting
* from the given position. The region is ignored.
*
@@ -393,7 +346,7 @@ public final class Matcher implements MatchResult {
}
/**
- * Returns the next occurrence of the {@link Pattern} in the input. If a
+ * Moves to the next occurrence of the pattern in the input. If a
* previous match was successful, the method continues the search from the
* first character following that match in the input. Otherwise it searches
* either from the region start (if one has been set), or from position 0.
@@ -436,45 +389,8 @@ public final class Matcher implements MatchResult {
}
/**
- * Returns the index of the first character of the text that matched a given
- * group.
- *
- * @param group
- * the group, ranging from 0 to groupCount() - 1, with 0
- * representing the whole pattern.
- * @return the character index.
- * @throws IllegalStateException
- * if no successful match has been made.
- */
- public int start(int group) throws IllegalStateException {
- ensureMatch();
- return matchOffsets[group * 2];
- }
-
- /**
- * Returns the index of the first character following the text that matched
- * a given group.
- *
- * @param group
- * the group, ranging from 0 to groupCount() - 1, with 0
- * representing the whole pattern.
- * @return the character index.
- * @throws IllegalStateException
- * if no successful match has been made.
- */
- public int end(int group) {
- ensureMatch();
- return matchOffsets[(group * 2) + 1];
- }
-
- /**
* Returns a replacement string for the given one that has all backslashes
* and dollar signs escaped.
- *
- * @param s
- * the input string.
- * @return the input string, with all backslashes and dollar signs having
- * been escaped.
*/
public static String quoteReplacement(String s) {
StringBuilder result = new StringBuilder(s.length());
@@ -489,47 +405,10 @@ public final class Matcher implements MatchResult {
}
/**
- * Returns the index of the first character of the text that matched the
- * whole regular expression.
- *
- * @return the character index.
- * @throws IllegalStateException
- * if no successful match has been made.
- */
- public int start() {
- return start(0);
- }
-
- /**
- * Returns the number of groups in the results, which is always equal to
- * the number of groups in the original regular expression.
- *
- * @return the number of groups.
- */
- public int groupCount() {
- synchronized (this) {
- return groupCountImpl(address);
- }
- }
-
- /**
- * Returns the index of the first character following the text that matched
- * the whole regular expression.
- *
- * @return the character index.
- * @throws IllegalStateException
- * if no successful match has been made.
- */
- public int end() {
- return end(0);
- }
-
- /**
* Converts the current match into a separate {@link MatchResult} instance
* that is independent from this matcher. The new object is unaffected when
* the state of this matcher changes.
*
- * @return the new {@code MatchResult}.
* @throws IllegalStateException
* if no successful match has been made.
*/
@@ -544,8 +423,6 @@ public final class Matcher implements MatchResult {
* '^' and '$' meta-characters, otherwise not. Anchoring bounds are enabled
* by default.
*
- * @param value
- * the new value for anchoring bounds.
* @return the {@code Matcher} itself.
*/
public Matcher useAnchoringBounds(boolean value) {
@@ -572,8 +449,6 @@ public final class Matcher implements MatchResult {
* region are subject to lookahead and lookbehind, otherwise they are not.
* Transparent bounds are disabled by default.
*
- * @param value
- * the new value for transparent bounds.
* @return the {@code Matcher} itself.
*/
public Matcher useTransparentBounds(boolean value) {
@@ -666,6 +541,78 @@ public final class Matcher implements MatchResult {
" lastmatch=" + (matchFound ? group() : "") + "]";
}
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalStateException if no successful match has been made.
+ */
+ public int end() {
+ return end(0);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalStateException if no successful match has been made.
+ */
+ public int end(int group) {
+ ensureMatch();
+ return matchOffsets[(group * 2) + 1];
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalStateException if no successful match has been made.
+ */
+ public String group() {
+ return group(0);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalStateException if no successful match has been made.
+ */
+ public String group(int group) {
+ ensureMatch();
+ int from = matchOffsets[group * 2];
+ int to = matchOffsets[(group * 2) + 1];
+ if (from == -1 || to == -1) {
+ return null;
+ } else {
+ return input.substring(from, to);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public int groupCount() {
+ synchronized (this) {
+ return groupCountImpl(address);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalStateException if no successful match has been made.
+ */
+ public int start() {
+ return start(0);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalStateException if no successful match has been made.
+ */
+ public int start(int group) throws IllegalStateException {
+ ensureMatch();
+ return matchOffsets[group * 2];
+ }
+
private static native void closeImpl(long addr);
private static native boolean findImpl(long addr, String s, int startIndex, int[] offsets);
private static native boolean findNextImpl(long addr, String s, int[] offsets);
diff --git a/luni/src/main/java/java/util/regex/Pattern.java b/luni/src/main/java/java/util/regex/Pattern.java
index a33ee93..8f3fb12 100644
--- a/luni/src/main/java/java/util/regex/Pattern.java
+++ b/luni/src/main/java/java/util/regex/Pattern.java
@@ -183,7 +183,7 @@ import java.io.Serializable;
* <tr> <td> <i>a</i>|<i>b</i> </td> <td>Either expression <i>a</i> or expression <i>b</i>.</td> </tr>
* </table>
*
- * <a name="flags"><h3>Flags</h3></a>
+ * <a name="flags"></a><h3>Flags</h3>
* <p><table>
* <tr> <td> (?dimsux-dimsux:<i>a</i>) </td> <td>Evaluates the expression <i>a</i> with the given flags enabled/disabled.</td> </tr>
* <tr> <td> (?dimsux-dimsux) </td> <td>Evaluates the rest of the pattern with the given flags enabled/disabled.</td> </tr>
diff --git a/luni/src/main/java/java/util/spi/CurrencyNameProvider.java b/luni/src/main/java/java/util/spi/CurrencyNameProvider.java
deleted file mode 100644
index d717aa2..0000000
--- a/luni/src/main/java/java/util/spi/CurrencyNameProvider.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 java.util.spi;
-
-import java.util.Locale;
-
-/**
- * This abstract class should be extended by service providers that provide
- * localized currency symbols (currency names) from currency codes.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class CurrencyNameProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected CurrencyNameProvider() {
- // do nothing
- }
-
- /**
- * Returns the localized currency symbol for the given currency code.
- *
- * @param code an ISO 4217 currency code
- * @param locale a locale
- * @return the symbol or null if there is no available symbol in the locale
- * @throws NullPointerException
- * if {@code code == null || locale == null}
- * @throws IllegalArgumentException
- * if code or locale is not in a legal format or not available
- */
- public abstract String getSymbol(String code, Locale locale);
-}
diff --git a/luni/src/main/java/java/util/spi/LocaleNameProvider.java b/luni/src/main/java/java/util/spi/LocaleNameProvider.java
deleted file mode 100644
index 0d25074..0000000
--- a/luni/src/main/java/java/util/spi/LocaleNameProvider.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 java.util.spi;
-
-import java.util.Locale;
-
-/**
- * This abstract class should be extended by service providers that provide
- * localized locale names.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class LocaleNameProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected LocaleNameProvider() {
- // do nothing
- }
-
- /**
- * Returns the localized name for the given ISO 639 language code.
- *
- * @param languageCode an ISO 639 language code
- * @param locale a locale
- * @return the name or null if unavailable
- * @throws NullPointerException
- * if {@code code == null || locale == null}
- * @throws IllegalArgumentException
- * if code or locale is not in a legal format or not available
- */
- public abstract String getDisplayLanguage(String languageCode, Locale locale);
-
- /**
- * Returns the localized name for the given ISO 3166 country code.
- *
- * @param countryCode an ISO 3166 language code
- * @param locale a locale
- * @return the name or null if unavailable
- * @throws NullPointerException
- * if {@code code == null || locale == null}
- * @throws IllegalArgumentException
- * if code or locale is not in a legal format or not available
- */
- public abstract String getDisplayCountry(String countryCode, Locale locale);
-
- /**
- * Returns the localized name for the given variant code.
- *
- * @param variantCode a variant code
- * @param locale a locale
- * @return the name or null if unavailable
- * @throws NullPointerException
- * if {@code code == null || locale == null}
- * @throws IllegalArgumentException
- * if code or locale is not in a legal format or not available
- */
- public abstract String getDisplayVariant(String variantCode, Locale locale);
-}
diff --git a/luni/src/main/java/java/util/spi/LocaleServiceProvider.java b/luni/src/main/java/java/util/spi/LocaleServiceProvider.java
deleted file mode 100644
index b1b62de..0000000
--- a/luni/src/main/java/java/util/spi/LocaleServiceProvider.java
+++ /dev/null
@@ -1,40 +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 java.util.spi;
-
-import java.util.Locale;
-
-/**
- * The base class for all the locale related service provider interfaces (SPIs).
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected LocaleServiceProvider() {
- // do nothing
- }
-
- /**
- * Returns all locales for which this locale service provider has localized objects or names.
- */
- public abstract Locale[] getAvailableLocales();
-}
diff --git a/luni/src/main/java/java/util/spi/TimeZoneNameProvider.java b/luni/src/main/java/java/util/spi/TimeZoneNameProvider.java
deleted file mode 100644
index 533d14e..0000000
--- a/luni/src/main/java/java/util/spi/TimeZoneNameProvider.java
+++ /dev/null
@@ -1,51 +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 java.util.spi;
-
-import java.util.Locale;
-
-/**
- * This abstract class should be extended by service providers that provide
- * localized time zone names.
- * <p>Note that Android does not support user-supplied locale service providers.
- * @since 1.6
- * @hide
- */
-public abstract class TimeZoneNameProvider extends LocaleServiceProvider {
- /**
- * Default constructor, for use by subclasses.
- */
- protected TimeZoneNameProvider() {
- // do nothing
- }
-
- /**
- * Returns the localized name for the given time zone in the given locale.
- *
- * @param id the time zone id
- * @param daylight true to return the name for daylight saving time.
- * @param style TimeZone.LONG or TimeZone.SHORT
- * @param locale the locale
- * @return the readable time zone name, or null if it is unavailable
- * @throws NullPointerException
- * if {@code id == null || locale == null}
- * @throws IllegalArgumentException
- * if locale is not available or style is invalid
- */
- public abstract String getDisplayName(String id, boolean daylight, int style, Locale locale);
-}
diff --git a/luni/src/main/java/java/util/zip/Deflater.java b/luni/src/main/java/java/util/zip/Deflater.java
index 3365031..040058b 100644
--- a/luni/src/main/java/java/util/zip/Deflater.java
+++ b/luni/src/main/java/java/util/zip/Deflater.java
@@ -51,7 +51,7 @@ import libcore.util.EmptyArray;
* {@link DeflaterOutputStream} to handle all this for you. {@link DeflaterOutputStream} also helps
* minimize memory requirements&nbsp;&mdash; the sample code above is very expensive.
*
- * <a name="compression_level"><h3>Compression levels</h3></a>
+ * <a name="compression_level"></a><h3>Compression levels</h3>
* <p>A compression level must be {@link #DEFAULT_COMPRESSION} to compromise between speed and
* compression (currently equivalent to level 6), or between 0 ({@link #NO_COMPRESSION}, where
* the input is simply copied) and 9 ({@link #BEST_COMPRESSION}). Level 1 ({@link #BEST_SPEED})
@@ -347,7 +347,7 @@ public class Deflater {
/**
* Resets the {@code Deflater} to accept new input without affecting any
- * previously made settings for the compression strategy or level. This
+ * previous compression strategy or level settings. This
* operation <i>must</i> be called after {@link #finished} returns
* true if the {@code Deflater} is to be reused.
*/
@@ -417,7 +417,7 @@ public class Deflater {
* Sets the given <a href="#compression_level">compression level</a>
* to be used when compressing data. This value must be set
* prior to calling {@link #setInput setInput}.
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* If the compression level is invalid.
*/
public synchronized void setLevel(int level) {
@@ -435,7 +435,7 @@ public class Deflater {
* FILTERED, HUFFMAN_ONLY or DEFAULT_STRATEGY. This value must be set prior
* to calling {@link #setInput setInput}.
*
- * @exception IllegalArgumentException
+ * @throws IllegalArgumentException
* If the strategy specified is not one of FILTERED,
* HUFFMAN_ONLY or DEFAULT_STRATEGY.
*/
diff --git a/luni/src/main/java/java/util/zip/DeflaterInputStream.java b/luni/src/main/java/java/util/zip/DeflaterInputStream.java
index f987e39..16bf92f 100644
--- a/luni/src/main/java/java/util/zip/DeflaterInputStream.java
+++ b/luni/src/main/java/java/util/zip/DeflaterInputStream.java
@@ -133,17 +133,20 @@ public class DeflaterInputStream extends FilterInputStream {
def.setInput(buf, 0, bytesRead);
}
}
- int bytesDeflated = def.deflate(buf, 0, Math.min(buf.length, byteCount - count));
+ int bytesDeflated = def.deflate(buffer, byteOffset + count, byteCount - count);
if (bytesDeflated == -1) {
break;
}
- System.arraycopy(buf, 0, buffer, byteOffset + count, bytesDeflated);
count += bytesDeflated;
}
if (count == 0) {
count = -1;
available = false;
}
+
+ if (def.finished()) {
+ available = false;
+ }
return count;
}
diff --git a/luni/src/main/java/java/util/zip/DeflaterOutputStream.java b/luni/src/main/java/java/util/zip/DeflaterOutputStream.java
index 6cce5a5..3377afd 100644
--- a/luni/src/main/java/java/util/zip/DeflaterOutputStream.java
+++ b/luni/src/main/java/java/util/zip/DeflaterOutputStream.java
@@ -188,7 +188,10 @@ public class DeflaterOutputStream extends FilterOutputStream {
* Doing so may degrade compression but improve interactive behavior.
*/
@Override public void flush() throws IOException {
- if (syncFlush) {
+ // Though not documented, it's illegal to call deflate with any flush param
+ // other than Z_FINISH after the deflater has finished. See the error checking
+ // at the start of the deflate function in deflate.c.
+ if (syncFlush && !done) {
int byteCount;
while ((byteCount = def.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH)) != 0) {
out.write(buf, 0, byteCount);
diff --git a/luni/src/main/java/java/util/zip/GZIPInputStream.java b/luni/src/main/java/java/util/zip/GZIPInputStream.java
index 08599ea..1bfc496 100644
--- a/luni/src/main/java/java/util/zip/GZIPInputStream.java
+++ b/luni/src/main/java/java/util/zip/GZIPInputStream.java
@@ -20,9 +20,11 @@ package java.util.zip;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
+import java.io.PushbackInputStream;
import java.nio.ByteOrder;
import java.util.Arrays;
import libcore.io.Memory;
+import libcore.io.Streams;
/**
* The {@code GZIPInputStream} class is used to read data stored in the GZIP
@@ -43,6 +45,9 @@ import libcore.io.Memory;
* zis.close();
* }
* </pre>
+ *
+ * <p>Note that this class ignores all remaining data at the end of the last
+ * GZIP member.
*/
public class GZIPInputStream extends InflaterInputStream {
private static final int FCOMMENT = 16;
@@ -53,6 +58,8 @@ public class GZIPInputStream extends InflaterInputStream {
private static final int FNAME = 8;
+ private static final int GZIP_TRAILER_SIZE = 8;
+
/**
* The magic header for the GZIP format.
*/
@@ -94,48 +101,18 @@ public class GZIPInputStream extends InflaterInputStream {
*/
public GZIPInputStream(InputStream is, int size) throws IOException {
super(is, new Inflater(true), size);
- byte[] header = new byte[10];
- readFully(header, 0, header.length);
- short magic = Memory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN);
- if (magic != (short) GZIP_MAGIC) {
- throw new IOException(String.format("unknown format (magic number %x)", magic));
- }
- int flags = header[3];
- boolean hcrc = (flags & FHCRC) != 0;
- if (hcrc) {
- crc.update(header, 0, header.length);
- }
- if ((flags & FEXTRA) != 0) {
- readFully(header, 0, 2);
- if (hcrc) {
- crc.update(header, 0, 2);
- }
- int length = Memory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN) & 0xffff;
- while (length > 0) {
- int max = length > buf.length ? buf.length : length;
- int result = in.read(buf, 0, max);
- if (result == -1) {
- throw new EOFException();
- }
- if (hcrc) {
- crc.update(buf, 0, result);
- }
- length -= result;
- }
- }
- if ((flags & FNAME) != 0) {
- readZeroTerminated(hcrc);
- }
- if ((flags & FCOMMENT) != 0) {
- readZeroTerminated(hcrc);
- }
- if (hcrc) {
- readFully(header, 0, 2);
- short crc16 = Memory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN);
- if ((short) crc.getValue() != crc16) {
- throw new IOException("CRC mismatch");
+
+ try {
+ byte[] header = readHeader(is);
+ final short magic = Memory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN);
+ if (magic != (short) GZIP_MAGIC) {
+ throw new IOException(String.format("unknown format (magic number %x)", magic));
}
- crc.reset();
+
+ parseGzipHeader(is, header, crc, buf);
+ } catch (IOException e) {
+ close(); // release the inflater
+ throw e;
}
}
@@ -171,11 +148,109 @@ public class GZIPInputStream extends InflaterInputStream {
if (eos) {
verifyCrc();
+ eos = maybeReadNextMember();
+ if (!eos) {
+ crc.reset();
+ inf.reset();
+ eof = false;
+ len = 0;
+ }
}
return bytesRead;
}
+ private boolean maybeReadNextMember() throws IOException {
+ // If we have any unconsumed data in the inflater buffer, we have to
+ // scan that first. The fact that we've reached here implies we've
+ // successfully consumed the GZIP trailer.
+ final int remaining = inf.getRemaining() - GZIP_TRAILER_SIZE;
+ if (remaining > 0) {
+ // NOTE: We make sure we create a pushback stream exactly once,
+ // even if the input stream contains multiple members.
+ //
+ // The push back stream we create must therefore be able to contain
+ // (worst case) the entire buffer even though there may be fewer bytes
+ // remaining when it is first created.
+ if (!(in instanceof PushbackInputStream)) {
+ in = new PushbackInputStream(in, buf.length);
+ }
+ ((PushbackInputStream) in).unread(buf,
+ inf.getCurrentOffset() + GZIP_TRAILER_SIZE, remaining);
+ }
+
+ final byte[] buffer;
+ try {
+ buffer = readHeader(in);
+ } catch (EOFException eof) {
+ // We've reached the end of the stream and there are no more members
+ // to read. Note that we might also hit this if there are fewer than
+ // GZIP_HEADER_LENGTH bytes at the end of a member. We don't care
+ // because we're specified to ignore all data at the end of the last
+ // gzip record.
+ return true;
+ }
+
+ final short magic = Memory.peekShort(buffer, 0, ByteOrder.LITTLE_ENDIAN);
+ if (magic != (short) GZIP_MAGIC) {
+ // Don't throw here because we've already read one valid member
+ // from this stream.
+ return true;
+ }
+
+ // We've encountered the gzip magic number, so we assume there's another
+ // member in the stream.
+ parseGzipHeader(in, buffer, crc, buf);
+ return false;
+ }
+
+ private static byte[] readHeader(InputStream in) throws IOException {
+ byte[] header = new byte[10];
+ Streams.readFully(in, header, 0, header.length);
+ return header;
+ }
+
+ private static void parseGzipHeader(InputStream in, byte[] header,
+ CRC32 crc, byte[] scratch) throws IOException {
+ final byte flags = header[3];
+ final boolean hcrc = (flags & FHCRC) != 0;
+ if (hcrc) {
+ crc.update(header, 0, header.length);
+ }
+ if ((flags & FEXTRA) != 0) {
+ Streams.readFully(in, header, 0, 2);
+ if (hcrc) {
+ crc.update(header, 0, 2);
+ }
+ int length = Memory.peekShort(scratch, 0, ByteOrder.LITTLE_ENDIAN) & 0xffff;
+ while (length > 0) {
+ int max = length > scratch.length ? scratch.length : length;
+ int result = in.read(scratch, 0, max);
+ if (result == -1) {
+ throw new EOFException();
+ }
+ if (hcrc) {
+ crc.update(scratch, 0, result);
+ }
+ length -= result;
+ }
+ }
+ if ((flags & FNAME) != 0) {
+ readZeroTerminated(in, crc, hcrc);
+ }
+ if ((flags & FCOMMENT) != 0) {
+ readZeroTerminated(in, crc, hcrc);
+ }
+ if (hcrc) {
+ Streams.readFully(in, header, 0, 2);
+ short crc16 = Memory.peekShort(scratch, 0, ByteOrder.LITTLE_ENDIAN);
+ if ((short) crc.getValue() != crc16) {
+ throw new IOException("CRC mismatch");
+ }
+ crc.reset();
+ }
+ }
+
private void verifyCrc() throws IOException {
// Get non-compressed bytes read by fill
int size = inf.getRemaining();
@@ -184,7 +259,7 @@ public class GZIPInputStream extends InflaterInputStream {
int copySize = (size > trailerSize) ? trailerSize : size;
System.arraycopy(buf, len - size, b, 0, copySize);
- readFully(b, copySize, trailerSize - copySize);
+ Streams.readFully(in, b, copySize, trailerSize - copySize);
if (Memory.peekInt(b, 0, ByteOrder.LITTLE_ENDIAN) != (int) crc.getValue()) {
throw new IOException("CRC mismatch");
@@ -194,20 +269,11 @@ public class GZIPInputStream extends InflaterInputStream {
}
}
- private void readFully(byte[] buffer, int offset, int length) throws IOException {
- int result;
- while (length > 0) {
- result = in.read(buffer, offset, length);
- if (result == -1) {
- throw new EOFException();
- }
- offset += result;
- length -= result;
- }
- }
-
- private void readZeroTerminated(boolean hcrc) throws IOException {
+ private static void readZeroTerminated(InputStream in, CRC32 crc, boolean hcrc)
+ throws IOException {
int result;
+ // TODO: Fix these single byte reads. This method is used to consume the
+ // header FNAME & FCOMMENT which aren't widely used in gzip files.
while ((result = in.read()) > 0) {
if (hcrc) {
crc.update(result);
diff --git a/luni/src/main/java/java/util/zip/GZIPOutputStream.java b/luni/src/main/java/java/util/zip/GZIPOutputStream.java
index 8dd907b..0111292 100644
--- a/luni/src/main/java/java/util/zip/GZIPOutputStream.java
+++ b/luni/src/main/java/java/util/zip/GZIPOutputStream.java
@@ -51,7 +51,7 @@ public class GZIPOutputStream extends DeflaterOutputStream {
* the given stream.
*/
public GZIPOutputStream(OutputStream os) throws IOException {
- this(os, BUF_SIZE, true);
+ this(os, BUF_SIZE, false);
}
/**
@@ -65,11 +65,10 @@ public class GZIPOutputStream extends DeflaterOutputStream {
/**
* Constructs a new {@code GZIPOutputStream} to write data in GZIP format to
- * the given stream with the given internal buffer size and
- * flushing behavior (see {@link DeflaterOutputStream#flush}).
+ * the given stream with the given internal buffer size.
*/
public GZIPOutputStream(OutputStream os, int bufferSize) throws IOException {
- this(os, bufferSize, true);
+ this(os, bufferSize, false);
}
/**
diff --git a/luni/src/main/java/java/util/zip/Inflater.java b/luni/src/main/java/java/util/zip/Inflater.java
index ee10aa7..581ed94 100644
--- a/luni/src/main/java/java/util/zip/Inflater.java
+++ b/luni/src/main/java/java/util/zip/Inflater.java
@@ -170,6 +170,15 @@ public class Inflater {
}
/**
+ * Returns the offset of the next byte to read in the underlying buffer.
+ *
+ * For internal use only.
+ */
+ synchronized int getCurrentOffset() {
+ return inRead;
+ }
+
+ /**
* Returns the total number of bytes of input read by this {@code Inflater}. This
* method is limited to 32 bits; use {@link #getBytesRead} instead.
*/
diff --git a/luni/src/main/java/java/util/zip/InflaterInputStream.java b/luni/src/main/java/java/util/zip/InflaterInputStream.java
index 25b2fe8..e5ad3db 100644
--- a/luni/src/main/java/java/util/zip/InflaterInputStream.java
+++ b/luni/src/main/java/java/util/zip/InflaterInputStream.java
@@ -266,12 +266,7 @@ public class InflaterInputStream extends FilterInputStream {
}
/**
- * Reset the position of the stream to the last marked position. This
- * implementation overrides the supertype implementation and always throws
- * an {@link IOException IOException} when called.
- *
- * @throws IOException
- * if the method is called
+ * This operation is not supported and throws {@code IOException}.
*/
@Override
public void reset() throws IOException {
diff --git a/luni/src/main/java/java/util/zip/ZipEntry.java b/luni/src/main/java/java/util/zip/ZipEntry.java
index f64c717..217cc3c 100644
--- a/luni/src/main/java/java/util/zip/ZipEntry.java
+++ b/luni/src/main/java/java/util/zip/ZipEntry.java
@@ -20,14 +20,15 @@ package java.util.zip;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
+import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
-import libcore.io.Streams;
import libcore.io.BufferIterator;
import libcore.io.HeapBufferIterator;
+import libcore.io.Streams;
/**
* An entry within a zip file.
@@ -54,6 +55,8 @@ public class ZipEntry implements ZipConstants, Cloneable {
int nameLength = -1;
long localHeaderRelOffset = -1;
+ long dataOffset = -1;
+
/**
* Zip entry state: Deflated.
*/
@@ -64,6 +67,23 @@ public class ZipEntry implements ZipConstants, Cloneable {
*/
public static final int STORED = 0;
+ ZipEntry(String name, String comment, long crc, long compressedSize,
+ long size, int compressionMethod, int time, int modDate, byte[] extra,
+ int nameLength, long localHeaderRelOffset, long dataOffset) {
+ this.name = name;
+ this.comment = comment;
+ this.crc = crc;
+ this.compressedSize = compressedSize;
+ this.size = size;
+ this.compressionMethod = compressionMethod;
+ this.time = time;
+ this.modDate = modDate;
+ this.extra = extra;
+ this.nameLength = nameLength;
+ this.localHeaderRelOffset = localHeaderRelOffset;
+ this.dataOffset = dataOffset;
+ }
+
/**
* Constructs a new {@code ZipEntry} with the specified name. The name is actually a path,
* and may contain {@code /} characters.
@@ -75,9 +95,7 @@ public class ZipEntry implements ZipConstants, Cloneable {
if (name == null) {
throw new NullPointerException("name == null");
}
- if (name.length() > 0xFFFF) {
- throw new IllegalArgumentException("Name too long: " + name.length());
- }
+ validateStringLength("Name", name);
this.name = name;
}
@@ -184,11 +202,8 @@ public class ZipEntry implements ZipConstants, Cloneable {
this.comment = null;
return;
}
+ validateStringLength("Comment", comment);
- byte[] commentBytes = comment.getBytes(StandardCharsets.UTF_8);
- if (commentBytes.length > 0xffff) {
- throw new IllegalArgumentException("Comment too long: " + commentBytes.length);
- }
this.comment = comment;
}
@@ -287,6 +302,17 @@ public class ZipEntry implements ZipConstants, Cloneable {
}
}
+
+ /** @hide */
+ public void setDataOffset(long value) {
+ dataOffset = value;
+ }
+
+ /** @hide */
+ public long getDataOffset() {
+ return dataOffset;
+ }
+
/**
* Returns the string representation of this {@code ZipEntry}.
*
@@ -316,6 +342,7 @@ public class ZipEntry implements ZipConstants, Cloneable {
extra = ze.extra;
nameLength = ze.nameLength;
localHeaderRelOffset = ze.localHeaderRelOffset;
+ dataOffset = ze.dataOffset;
}
/**
@@ -344,12 +371,14 @@ public class ZipEntry implements ZipConstants, Cloneable {
/*
* Internal constructor. Creates a new ZipEntry by reading the
* Central Directory Entry (CDE) from "in", which must be positioned
- * at the CDE signature.
+ * at the CDE signature. If the GPBF_UTF8_FLAG is set in the CDE then
+ * UTF-8 is used to decode the string information, otherwise the
+ * defaultCharset is used.
*
* On exit, "in" will be positioned at the start of the next entry
* in the Central Directory.
*/
- ZipEntry(byte[] cdeHdrBuf, InputStream cdStream) throws IOException {
+ ZipEntry(byte[] cdeHdrBuf, InputStream cdStream, Charset defaultCharset) throws IOException {
Streams.readFully(cdStream, cdeHdrBuf, 0, cdeHdrBuf.length);
BufferIterator it = HeapBufferIterator.iterator(cdeHdrBuf, 0, cdeHdrBuf.length,
@@ -367,6 +396,13 @@ public class ZipEntry implements ZipConstants, Cloneable {
throw new ZipException("Invalid General Purpose Bit Flag: " + gpbf);
}
+ // If the GPBF_UTF8_FLAG is set then the character encoding is UTF-8 whatever the default
+ // provided.
+ Charset charset = defaultCharset;
+ if ((gpbf & ZipFile.GPBF_UTF8_FLAG) != 0) {
+ charset = StandardCharsets.UTF_8;
+ }
+
compressionMethod = it.readShort() & 0xffff;
time = it.readShort() & 0xffff;
modDate = it.readShort() & 0xffff;
@@ -389,19 +425,17 @@ public class ZipEntry implements ZipConstants, Cloneable {
if (containsNulByte(nameBytes)) {
throw new ZipException("Filename contains NUL byte: " + Arrays.toString(nameBytes));
}
- name = new String(nameBytes, 0, nameBytes.length, StandardCharsets.UTF_8);
+ name = new String(nameBytes, 0, nameBytes.length, charset);
if (extraLength > 0) {
extra = new byte[extraLength];
Streams.readFully(cdStream, extra, 0, extraLength);
}
- // The RI has always assumed UTF-8. (If GPBF_UTF8_FLAG isn't set, the encoding is
- // actually IBM-437.)
if (commentByteCount > 0) {
byte[] commentBytes = new byte[commentByteCount];
Streams.readFully(cdStream, commentBytes, 0, commentByteCount);
- comment = new String(commentBytes, 0, commentBytes.length, StandardCharsets.UTF_8);
+ comment = new String(commentBytes, 0, commentBytes.length, charset);
}
}
@@ -413,4 +447,14 @@ public class ZipEntry implements ZipConstants, Cloneable {
}
return false;
}
+
+ private static void validateStringLength(String argument, String string) {
+ // This check is not perfect: the character encoding is determined when the entry is
+ // written out. UTF-8 is probably a worst-case: most alternatives should be single byte per
+ // character.
+ byte[] bytes = string.getBytes(StandardCharsets.UTF_8);
+ if (bytes.length > 0xffff) {
+ throw new IllegalArgumentException(argument + " too long: " + bytes.length);
+ }
+ }
}
diff --git a/luni/src/main/java/java/util/zip/ZipFile.java b/luni/src/main/java/java/util/zip/ZipFile.java
index c25bbc1..b44156e 100644
--- a/luni/src/main/java/java/util/zip/ZipFile.java
+++ b/luni/src/main/java/java/util/zip/ZipFile.java
@@ -32,6 +32,7 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import libcore.io.BufferIterator;
import libcore.io.HeapBufferIterator;
+import libcore.io.IoUtils;
import libcore.io.Streams;
/**
@@ -108,6 +109,9 @@ public class ZipFile implements Closeable, ZipConstants {
/**
* Constructs a new {@code ZipFile} allowing read access to the contents of the given file.
+ *
+ * <p>UTF-8 is used to decode all comments and entry names in the file.
+ *
* @throws ZipException if a zip error occurs.
* @throws IOException if an {@code IOException} occurs.
*/
@@ -117,6 +121,9 @@ public class ZipFile implements Closeable, ZipConstants {
/**
* Constructs a new {@code ZipFile} allowing read access to the contents of the given file.
+ *
+ * <p>UTF-8 is used to decode all comments and entry names in the file.
+ *
* @throws IOException if an IOException occurs.
*/
public ZipFile(String name) throws IOException {
@@ -125,9 +132,11 @@ public class ZipFile implements Closeable, ZipConstants {
/**
* Constructs a new {@code ZipFile} allowing access to the given file.
- * The {@code mode} must be either {@code OPEN_READ} or {@code OPEN_READ|OPEN_DELETE}.
*
- * <p>If the {@code OPEN_DELETE} flag is supplied, the file will be deleted at or before the
+ * <p>UTF-8 is used to decode all comments and entry names in the file.
+ *
+ * <p>The {@code mode} must be either {@code OPEN_READ} or {@code OPEN_READ|OPEN_DELETE}.
+ * If the {@code OPEN_DELETE} flag is supplied, the file will be deleted at or before the
* time that the {@code ZipFile} is closed (the contents will remain accessible until
* this {@code ZipFile} is closed); it also calls {@code File.deleteOnExit}.
*
@@ -148,7 +157,19 @@ public class ZipFile implements Closeable, ZipConstants {
raf = new RandomAccessFile(filename, "r");
- readCentralDir();
+ // Make sure to close the RandomAccessFile if reading the central directory fails.
+ boolean mustCloseFile = true;
+ try {
+ readCentralDir();
+
+ // Read succeeded so do not close the underlying RandomAccessFile.
+ mustCloseFile = false;
+ } finally {
+ if (mustCloseFile) {
+ IoUtils.closeQuietly(raf);
+ }
+ }
+
guard.open("close");
}
@@ -357,6 +378,9 @@ public class ZipFile implements Closeable, ZipConstants {
raf.seek(0);
final int headerMagic = Integer.reverseBytes(raf.readInt());
+ if (headerMagic == ENDSIG) {
+ throw new ZipException("Empty zip archive not supported");
+ }
if (headerMagic != LOCSIG) {
throw new ZipException("Not a zip archive");
}
@@ -411,7 +435,7 @@ public class ZipFile implements Closeable, ZipConstants {
BufferedInputStream bufferedStream = new BufferedInputStream(rafStream, 4096);
byte[] hdrBuf = new byte[CENHDR]; // Reuse the same buffer for each entry.
for (int i = 0; i < numEntries; ++i) {
- ZipEntry newEntry = new ZipEntry(hdrBuf, bufferedStream);
+ ZipEntry newEntry = new ZipEntry(hdrBuf, bufferedStream, StandardCharsets.UTF_8);
if (newEntry.localHeaderRelOffset >= centralDirOffset) {
throw new ZipException("Local file header offset is after central directory");
}
@@ -434,16 +458,23 @@ public class ZipFile implements Closeable, ZipConstants {
* collisions.)
*
* <p>We could support mark/reset, but we don't currently need them.
+ *
+ * @hide
*/
- static class RAFStream extends InputStream {
+ public static class RAFStream extends InputStream {
private final RandomAccessFile sharedRaf;
private long endOffset;
private long offset;
- public RAFStream(RandomAccessFile raf, long initialOffset) throws IOException {
+
+ public RAFStream(RandomAccessFile raf, long initialOffset, long endOffset) {
sharedRaf = raf;
offset = initialOffset;
- endOffset = raf.length();
+ this.endOffset = endOffset;
+ }
+
+ public RAFStream(RandomAccessFile raf, long initialOffset) throws IOException {
+ this(raf, initialOffset, raf.length());
}
@Override public int available() throws IOException {
@@ -491,7 +522,8 @@ public class ZipFile implements Closeable, ZipConstants {
}
}
- static class ZipInflaterInputStream extends InflaterInputStream {
+ /** @hide */
+ public static class ZipInflaterInputStream extends InflaterInputStream {
private final ZipEntry entry;
private long bytesRead = 0;
diff --git a/luni/src/main/java/java/util/zip/ZipInputStream.java b/luni/src/main/java/java/util/zip/ZipInputStream.java
index 9c18f49..4c0034e 100644
--- a/luni/src/main/java/java/util/zip/ZipInputStream.java
+++ b/luni/src/main/java/java/util/zip/ZipInputStream.java
@@ -22,8 +22,7 @@ import java.io.InputStream;
import java.io.PushbackInputStream;
import java.nio.ByteOrder;
import java.nio.charset.ModifiedUtf8;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import libcore.io.Memory;
import libcore.io.Streams;
@@ -86,12 +85,14 @@ public class ZipInputStream extends InflaterInputStream implements ZipConstants
private final CRC32 crc = new CRC32();
- private byte[] nameBuf = new byte[256];
+ private byte[] stringBytesBuf = new byte[256];
- private char[] charBuf = new char[256];
+ private char[] stringCharBuf = new char[256];
/**
* Constructs a new {@code ZipInputStream} to read zip entries from the given input stream.
+ *
+ * <p>UTF-8 is used to decode all strings in the file.
*/
public ZipInputStream(InputStream stream) {
super(new PushbackInputStream(stream, BUF_SIZE), new Inflater(true));
@@ -125,12 +126,6 @@ public class ZipInputStream extends InflaterInputStream implements ZipConstants
if (currentEntry == null) {
return;
}
- if (currentEntry instanceof java.util.jar.JarEntry) {
- Attributes temp = ((JarEntry) currentEntry).getAttributes();
- if (temp != null && temp.containsKey("hidden")) {
- return;
- }
- }
/*
* The following code is careful to leave the ZipInputStream in a
@@ -257,14 +252,8 @@ public class ZipInputStream extends InflaterInputStream implements ZipConstants
}
int extraLength = peekShort(LOCEXT - LOCVER);
- if (nameLength > nameBuf.length) {
- nameBuf = new byte[nameLength];
- // The bytes are modified UTF-8, so the number of chars will always be less than or
- // equal to the number of bytes. It's fine if this buffer is too long.
- charBuf = new char[nameLength];
- }
- Streams.readFully(in, nameBuf, 0, nameLength);
- currentEntry = createZipEntry(ModifiedUtf8.decode(nameBuf, charBuf, 0, nameLength));
+ String name = readString(nameLength);
+ currentEntry = createZipEntry(name);
currentEntry.time = ceLastModifiedTime;
currentEntry.modDate = ceLastModifiedDate;
currentEntry.setMethod(ceCompressionMethod);
@@ -281,6 +270,22 @@ public class ZipInputStream extends InflaterInputStream implements ZipConstants
return currentEntry;
}
+ /**
+ * Reads bytes from the current stream position returning the string representation.
+ */
+ private String readString(int byteLength) throws IOException {
+ if (byteLength > stringBytesBuf.length) {
+ stringBytesBuf = new byte[byteLength];
+ }
+ Streams.readFully(in, stringBytesBuf, 0, byteLength);
+ // The number of chars will always be less than or equal to the number of bytes. It's
+ // fine if this buffer is too long.
+ if (byteLength > stringCharBuf.length) {
+ stringCharBuf = new char[byteLength];
+ }
+ return ModifiedUtf8.decode(stringBytesBuf, stringCharBuf, 0, byteLength);
+ }
+
private int peekShort(int offset) {
return Memory.peekShort(hdrBuf, offset, ByteOrder.LITTLE_ENDIAN) & 0xffff;
}
diff --git a/luni/src/main/java/java/util/zip/ZipOutputStream.java b/luni/src/main/java/java/util/zip/ZipOutputStream.java
index 04de03f..8278355 100644
--- a/luni/src/main/java/java/util/zip/ZipOutputStream.java
+++ b/luni/src/main/java/java/util/zip/ZipOutputStream.java
@@ -85,13 +85,19 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
private final CRC32 crc = new CRC32();
- private int offset = 0, curOffset = 0, nameLength;
+ private int offset = 0, curOffset = 0;
+ /** The charset-encoded name for the current entry. */
private byte[] nameBytes;
+ /** The charset-encoded comment for the current entry. */
+ private byte[] entryCommentBytes;
+
/**
- * Constructs a new {@code ZipOutputStream} that writes a zip file
- * to the given {@code OutputStream}.
+ * Constructs a new {@code ZipOutputStream} that writes a zip file to the given
+ * {@code OutputStream}.
+ *
+ * <p>UTF-8 will be used to encode the file comment, entry names and comments.
*/
public ZipOutputStream(OutputStream os) {
super(os, new Deflater(Deflater.DEFAULT_COMPRESSION, true));
@@ -153,8 +159,8 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
// Update the CentralDirectory
// http://www.pkware.com/documents/casestudies/APPNOTE.TXT
int flags = currentEntry.getMethod() == STORED ? 0 : ZipFile.GPBF_DATA_DESCRIPTOR_FLAG;
- // Since gingerbread, we always set the UTF-8 flag on individual files.
- // Some tools insist that the central directory also have the UTF-8 flag.
+ // Since gingerbread, we always set the UTF-8 flag on individual files if appropriate.
+ // Some tools insist that the central directory have the UTF-8 flag.
// http://code.google.com/p/android/issues/detail?id=20214
flags |= ZipFile.GPBF_UTF8_FLAG;
writeLong(cDir, CENSIG);
@@ -172,19 +178,14 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
curOffset += writeLong(cDir, crc.tbytes);
writeLong(cDir, crc.tbytes);
}
- curOffset += writeShort(cDir, nameLength);
+ curOffset += writeShort(cDir, nameBytes.length);
if (currentEntry.extra != null) {
curOffset += writeShort(cDir, currentEntry.extra.length);
} else {
writeShort(cDir, 0);
}
- String comment = currentEntry.getComment();
- byte[] commentBytes = EmptyArray.BYTE;
- if (comment != null) {
- commentBytes = comment.getBytes(StandardCharsets.UTF_8);
- }
- writeShort(cDir, commentBytes.length); // Comment length.
+ writeShort(cDir, entryCommentBytes.length); // Comment length.
writeShort(cDir, 0); // Disk Start
writeShort(cDir, 0); // Internal File Attributes
writeLong(cDir, 0); // External File Attributes
@@ -195,8 +196,9 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
cDir.write(currentEntry.extra);
}
offset += curOffset;
- if (commentBytes.length > 0) {
- cDir.write(commentBytes);
+ if (entryCommentBytes.length > 0) {
+ cDir.write(entryCommentBytes);
+ entryCommentBytes = EmptyArray.BYTE;
}
currentEntry = null;
crc.reset();
@@ -295,9 +297,13 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
throw new ZipException("Too many entries for the zip file format's 16-bit entry count");
}
nameBytes = ze.name.getBytes(StandardCharsets.UTF_8);
- nameLength = nameBytes.length;
- if (nameLength > 0xffff) {
- throw new IllegalArgumentException("Name too long: " + nameLength + " UTF-8 bytes");
+ checkSizeIsWithinShort("Name", nameBytes);
+ entryCommentBytes = EmptyArray.BYTE;
+ if (ze.comment != null) {
+ entryCommentBytes = ze.comment.getBytes(StandardCharsets.UTF_8);
+ // The comment is not written out until the entry is finished, but it is validated here
+ // to fail-fast.
+ checkSizeIsWithinShort("Comment", entryCommentBytes);
}
def.setLevel(compressionLevel);
@@ -310,7 +316,7 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
// http://www.pkware.com/documents/casestudies/APPNOTE.TXT
int flags = (method == STORED) ? 0 : ZipFile.GPBF_DATA_DESCRIPTOR_FLAG;
// Java always outputs UTF-8 filenames. (Before Java 7, the RI didn't set this flag and used
- // modified UTF-8. From Java 7, it sets this flag and uses normal UTF-8.)
+ // modified UTF-8. From Java 7, when using UTF_8 it sets this flag and uses normal UTF-8.)
flags |= ZipFile.GPBF_UTF8_FLAG;
writeLong(out, LOCSIG); // Entry header
writeShort(out, ZIP_VERSION_2_0); // Minimum version needed to extract.
@@ -331,7 +337,7 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
writeLong(out, 0);
writeLong(out, 0);
}
- writeShort(out, nameLength);
+ writeShort(out, nameBytes.length);
if (currentEntry.extra != null) {
writeShort(out, currentEntry.extra.length);
} else {
@@ -345,18 +351,16 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
/**
* Sets the comment associated with the file being written. See {@link ZipFile#getComment}.
- * @throws IllegalArgumentException if the comment is >= 64 Ki UTF-8 bytes.
+ * @throws IllegalArgumentException if the comment is >= 64 Ki encoded bytes.
*/
public void setComment(String comment) {
if (comment == null) {
- this.commentBytes = null;
+ this.commentBytes = EmptyArray.BYTE;
return;
}
byte[] newCommentBytes = comment.getBytes(StandardCharsets.UTF_8);
- if (newCommentBytes.length > 0xffff) {
- throw new IllegalArgumentException("Comment too long: " + newCommentBytes.length + " bytes");
- }
+ checkSizeIsWithinShort("Comment", newCommentBytes);
this.commentBytes = newCommentBytes;
}
@@ -400,7 +404,7 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
/**
* Writes data for the current entry to the underlying stream.
*
- * @exception IOException
+ * @throws IOException
* If an error occurs writing to the stream
*/
@Override
@@ -423,4 +427,11 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant
throw new IOException("Stream is closed");
}
}
+
+ private void checkSizeIsWithinShort(String property, byte[] bytes) {
+ if (bytes.length > 0xffff) {
+ throw new IllegalArgumentException(property + " too long in UTF-8:" + bytes.length +
+ " bytes");
+ }
+ }
}
diff --git a/luni/src/main/java/javax/crypto/Cipher.java b/luni/src/main/java/javax/crypto/Cipher.java
index ba40b86..2e3b341 100644
--- a/luni/src/main/java/javax/crypto/Cipher.java
+++ b/luni/src/main/java/javax/crypto/Cipher.java
@@ -26,11 +26,15 @@ import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
+import java.security.Provider.Service;
+import java.security.ProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
+import java.util.ArrayList;
+import java.util.Locale;
import java.util.Set;
import org.apache.harmony.crypto.internal.NullCipherSpi;
import org.apache.harmony.security.fortress.Engine;
@@ -54,7 +58,7 @@ import org.apache.harmony.security.fortress.Engine;
* <ul>
* {@code Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");}
* </ul>
- * When a block cipher is requested in in stream cipher mode, the number of bits
+ * When a block cipher is requested in stream cipher mode, the number of bits
* to be processed at a time can be optionally specified by appending it to the
* mode name. e.g. <i>"AES/CFB8/NoPadding"</i>. If no number is specified, a
* provider specific default value is used.
@@ -98,6 +102,11 @@ public class Cipher {
private int mode;
+ /** Items that need to be set on the Cipher instance. */
+ private enum NeedToSet {
+ NONE, MODE, PADDING, BOTH,
+ };
+
/**
* The service name.
*/
@@ -108,20 +117,46 @@ public class Cipher {
*/
private static final Engine ENGINE = new Engine(SERVICE);
+ /** The attribute used for supported paddings. */
+ private static final String ATTRIBUTE_PADDINGS = "SupportedPaddings";
+
+ /** The attribute used for supported modes. */
+ private static final String ATTRIBUTE_MODES = "SupportedModes";
+
/**
* The provider.
*/
private Provider provider;
/**
+ * The provider specified when instance created.
+ */
+ private final Provider specifiedProvider;
+
+ /**
* The SPI implementation.
*/
private CipherSpi spiImpl;
/**
+ * The SPI implementation.
+ */
+ private final CipherSpi specifiedSpi;
+
+ /**
* The transformation.
*/
- private String transformation;
+ private final String transformation;
+
+ /**
+ * The transformation split into parts.
+ */
+ private final String[] transformParts;
+
+ /**
+ * Lock held while the SPI is initializing.
+ */
+ private final Object initLock = new Object();
private static SecureRandom secureRandom;
@@ -138,19 +173,27 @@ public class Cipher {
* if either cipherSpi is {@code null} or provider is {@code
* null} and {@code cipherSpi} is a {@code NullCipherSpi}.
*/
- protected Cipher(CipherSpi cipherSpi, Provider provider,
- String transformation) {
+ protected Cipher(CipherSpi cipherSpi, Provider provider, String transformation) {
if (cipherSpi == null) {
throw new NullPointerException("cipherSpi == null");
}
if (!(cipherSpi instanceof NullCipherSpi) && provider == null) {
throw new NullPointerException("provider == null");
}
- this.provider = provider;
+ this.specifiedProvider = provider;
+ this.specifiedSpi = cipherSpi;
this.transformation = transformation;
- this.spiImpl = cipherSpi;
+ this.transformParts = null;
}
+ private Cipher(String transformation, String[] transformParts, Provider provider) {
+ this.transformation = transformation;
+ this.transformParts = transformParts;
+ this.specifiedProvider = provider;
+ this.specifiedSpi = null;
+ }
+
+
/**
* Creates a new Cipher for the specified transformation. The installed
* providers are searched in order for an implementation of the specified
@@ -211,7 +254,8 @@ public class Cipher {
}
/**
- * Creates a new cipher for the specified transformation.
+ * Creates a new cipher for the specified transformation. The
+ * {@code provider} supplied does not have to be registered.
*
* @param transformation
* the name of the transformation to create a cipher for.
@@ -234,8 +278,7 @@ public class Cipher {
if (provider == null) {
throw new IllegalArgumentException("provider == null");
}
- Cipher c = getCipher(transformation, provider);
- return c;
+ return getCipher(transformation, provider);
}
private static NoSuchAlgorithmException invalidTransformation(String transformation)
@@ -244,91 +287,31 @@ public class Cipher {
}
/**
- * Find appropriate Cipher according the specification rules
- *
- * @param transformation
- * @param provider
- * @return
- * @throws NoSuchAlgorithmException
- * @throws NoSuchPaddingException
+ * Create a Cipher instance but don't choose a CipherSpi until we have more
+ * information.
*/
- private static synchronized Cipher getCipher(String transformation, Provider provider)
+ private static Cipher getCipher(String transformation, Provider provider)
throws NoSuchAlgorithmException, NoSuchPaddingException {
-
if (transformation == null || transformation.isEmpty()) {
throw invalidTransformation(transformation);
}
- String[] transf = checkTransformation(transformation);
-
- boolean needSetPadding = false;
- boolean needSetMode = false;
- Object engineSpi = null;
- Provider engineProvider = provider;
- if (transf[1] == null && transf[2] == null) { // "algorithm"
+ String[] transformParts = checkTransformation(transformation);
+ if (tryCombinations(null, provider, transformParts) == null) {
if (provider == null) {
- Engine.SpiAndProvider sap = ENGINE.getInstance(transf[0], null);
- engineSpi = sap.spi;
- engineProvider = sap.provider;
+ throw new NoSuchAlgorithmException("No provider found for " + transformation);
} else {
- engineSpi = ENGINE.getInstance(transf[0], provider, null);
+ throw new NoSuchAlgorithmException("Provider " + provider.getName()
+ + " does not provide " + transformation);
}
- } else {
- String[] searchOrder = {
- transf[0] + "/" + transf[1] + "/" + transf[2], // "algorithm/mode/padding"
- transf[0] + "/" + transf[1], // "algorithm/mode"
- transf[0] + "//" + transf[2], // "algorithm//padding"
- transf[0] // "algorithm"
- };
- int i;
- for (i = 0; i < searchOrder.length; i++) {
- try {
- if (provider == null) {
- Engine.SpiAndProvider sap = ENGINE.getInstance(searchOrder[i], null);
- engineSpi = sap.spi;
- engineProvider = sap.provider;
- } else {
- engineSpi = ENGINE.getInstance(searchOrder[i], provider, null);
- }
- break;
- } catch (NoSuchAlgorithmException e) {
- if (i == searchOrder.length-1) {
- throw new NoSuchAlgorithmException(transformation, e);
- }
- }
- }
- switch (i) {
- case 1: // "algorithm/mode"
- needSetPadding = true;
- break;
- case 2: // "algorithm//padding"
- needSetMode = true;
- break;
- case 3: // "algorithm"
- needSetPadding = true;
- needSetMode = true;
- }
- }
- if (engineSpi == null || engineProvider == null) {
- throw new NoSuchAlgorithmException(transformation);
}
- if (!(engineSpi instanceof CipherSpi)) {
- throw new NoSuchAlgorithmException(engineSpi.getClass().getName());
- }
- CipherSpi cspi = (CipherSpi) engineSpi;
- Cipher c = new Cipher(cspi, engineProvider, transformation);
- if (needSetMode) {
- c.spiImpl.engineSetMode(transf[1]);
- }
- if (needSetPadding) {
- c.spiImpl.engineSetPadding(transf[2]);
- }
- return c;
+ return new Cipher(transformation, transformParts, provider);
}
- private static String[] checkTransformation(String transformation) throws NoSuchAlgorithmException {
+ private static String[] checkTransformation(String transformation)
+ throws NoSuchAlgorithmException {
// ignore an extra prefix / characters such as in
- // "/DES/CBC/PKCS5Paddin" http://b/3387688
+ // "/DES/CBC/PKCS5Padding" http://b/3387688
if (transformation.startsWith("/")) {
transformation = transformation.substring(1);
}
@@ -356,11 +339,163 @@ public class Cipher {
}
/**
+ * Makes sure a CipherSpi that matches this type is selected.
+ */
+ private CipherSpi getSpi(Key key) {
+ if (specifiedSpi != null) {
+ return specifiedSpi;
+ }
+
+ synchronized (initLock) {
+ if (spiImpl != null && key == null) {
+ return spiImpl;
+ }
+
+ final Engine.SpiAndProvider sap = tryCombinations(key, specifiedProvider,
+ transformParts);
+ if (sap == null) {
+ throw new ProviderException("No provider for " + transformation);
+ }
+
+ spiImpl = (CipherSpi) sap.spi;
+ provider = sap.provider;
+
+ return spiImpl;
+ }
+ }
+
+ /**
+ * Convenience call when the Key is not available.
+ */
+ private CipherSpi getSpi() {
+ return getSpi(null);
+ }
+
+ /**
+ * Try all combinations of mode strings:
+ *
+ * <pre>
+ * [cipher]/[mode]/[padding]
+ * [cipher]/[mode]
+ * [cipher]//[padding]
+ * [cipher]
+ * </pre>
+ */
+ private static Engine.SpiAndProvider tryCombinations(Key key, Provider provider,
+ String[] transformParts) {
+ Engine.SpiAndProvider sap = null;
+
+ if (transformParts[1] != null && transformParts[2] != null) {
+ sap = tryTransform(key, provider, transformParts[0] + "/" + transformParts[1] + "/"
+ + transformParts[2], transformParts, NeedToSet.NONE);
+ if (sap != null) {
+ return sap;
+ }
+ }
+
+ if (transformParts[1] != null) {
+ sap = tryTransform(key, provider, transformParts[0] + "/" + transformParts[1],
+ transformParts, NeedToSet.PADDING);
+ if (sap != null) {
+ return sap;
+ }
+ }
+
+ if (transformParts[2] != null) {
+ sap = tryTransform(key, provider, transformParts[0] + "//" + transformParts[2],
+ transformParts, NeedToSet.MODE);
+ if (sap != null) {
+ return sap;
+ }
+ }
+
+ return tryTransform(key, provider, transformParts[0], transformParts, NeedToSet.BOTH);
+ }
+
+ private static Engine.SpiAndProvider tryTransform(Key key, Provider provider, String transform,
+ String[] transformParts, NeedToSet type) {
+ if (provider != null) {
+ Provider.Service service = provider.getService(SERVICE, transform);
+ if (service == null) {
+ return null;
+ }
+ return tryTransformWithProvider(key, transformParts, type, service);
+ }
+ ArrayList<Provider.Service> services = ENGINE.getServices(transform);
+ if (services == null) {
+ return null;
+ }
+ for (Provider.Service service : services) {
+ Engine.SpiAndProvider sap = tryTransformWithProvider(key, transformParts, type, service);
+ if (sap != null) {
+ return sap;
+ }
+ }
+ return null;
+ }
+
+ private static Engine.SpiAndProvider tryTransformWithProvider(Key key, String[] transformParts,
+ NeedToSet type, Provider.Service service) {
+ try {
+ if (key != null && !service.supportsParameter(key)) {
+ return null;
+ }
+
+ /*
+ * Check to see if the Cipher even supports the attributes before
+ * trying to instantiate it.
+ */
+ if (!matchAttribute(service, ATTRIBUTE_MODES, transformParts[1])
+ || !matchAttribute(service, ATTRIBUTE_PADDINGS, transformParts[2])) {
+ return null;
+ }
+
+ Engine.SpiAndProvider sap = ENGINE.getInstance(service, null);
+ if (sap.spi == null || sap.provider == null) {
+ return null;
+ }
+ if (!(sap.spi instanceof CipherSpi)) {
+ return null;
+ }
+ CipherSpi spi = (CipherSpi) sap.spi;
+ if (((type == NeedToSet.MODE) || (type == NeedToSet.BOTH))
+ && (transformParts[1] != null)) {
+ spi.engineSetMode(transformParts[1]);
+ }
+ if (((type == NeedToSet.PADDING) || (type == NeedToSet.BOTH))
+ && (transformParts[2] != null)) {
+ spi.engineSetPadding(transformParts[2]);
+ }
+ return sap;
+ } catch (NoSuchAlgorithmException ignored) {
+ } catch (NoSuchPaddingException ignored) {
+ }
+ return null;
+ }
+
+ /**
+ * If the attribute listed exists, check that it matches the regular
+ * expression.
+ */
+ private static boolean matchAttribute(Service service, String attr, String value) {
+ if (value == null) {
+ return true;
+ }
+ final String pattern = service.getAttribute(attr);
+ if (pattern == null) {
+ return true;
+ }
+ final String valueUc = value.toUpperCase(Locale.US);
+ return valueUc.matches(pattern.toUpperCase(Locale.US));
+ }
+
+ /**
* Returns the provider of this cipher instance.
*
* @return the provider of this cipher instance.
*/
public final Provider getProvider() {
+ getSpi();
return provider;
}
@@ -382,7 +517,7 @@ public class Cipher {
* @return this ciphers block size.
*/
public final int getBlockSize() {
- return spiImpl.engineGetBlockSize();
+ return getSpi().engineGetBlockSize();
}
/**
@@ -399,7 +534,7 @@ public class Cipher {
if (mode == 0) {
throw new IllegalStateException("Cipher has not yet been initialized");
}
- return spiImpl.engineGetOutputSize(inputLen);
+ return getSpi().engineGetOutputSize(inputLen);
}
/**
@@ -408,7 +543,7 @@ public class Cipher {
* @return the <i>initialization vector</i> for this cipher instance.
*/
public final byte[] getIV() {
- return spiImpl.engineGetIV();
+ return getSpi().engineGetIV();
}
/**
@@ -423,7 +558,7 @@ public class Cipher {
* parameters.
*/
public final AlgorithmParameters getParameters() {
- return spiImpl.engineGetParameters();
+ return getSpi().engineGetParameters();
}
/**
@@ -442,6 +577,13 @@ public class Cipher {
}
+ private void checkMode(int mode) {
+ if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE && mode != UNWRAP_MODE
+ && mode != WRAP_MODE) {
+ throw new InvalidParameterException("Invalid mode: " + mode);
+ }
+ }
+
/**
* Initializes this cipher instance with the specified key.
* <p>
@@ -516,17 +658,10 @@ public class Cipher {
// FIXME InvalidKeyException
// if keysize exceeds the maximum allowable keysize
// (jurisdiction policy files)
- spiImpl.engineInit(opmode, key, random);
+ getSpi(key).engineInit(opmode, key, random);
mode = opmode;
}
- private void checkMode(int mode) {
- if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE
- && mode != UNWRAP_MODE && mode != WRAP_MODE) {
- throw new InvalidParameterException("Invalid mode: " + mode);
- }
- }
-
/**
* Initializes this cipher instance with the specified key and algorithm
* parameters.
@@ -613,7 +748,7 @@ public class Cipher {
// FIXME InvalidAlgorithmParameterException
// cryptographic strength exceed the legal limits
// (jurisdiction policy files)
- spiImpl.engineInit(opmode, key, params, random);
+ getSpi(key).engineInit(opmode, key, params, random);
mode = opmode;
}
@@ -704,7 +839,7 @@ public class Cipher {
// FIXME InvalidAlgorithmParameterException
// cryptographic strength exceed the legal limits
// (jurisdiction policy files)
- spiImpl.engineInit(opmode, key, params, random);
+ getSpi(key).engineInit(opmode, key, params, random);
mode = opmode;
}
@@ -828,7 +963,8 @@ public class Cipher {
// FIXME InvalidKeyException
// if keysize exceeds the maximum allowable keysize
// (jurisdiction policy files)
- spiImpl.engineInit(opmode, certificate.getPublicKey(), random);
+ final Key key = certificate.getPublicKey();
+ getSpi(key).engineInit(opmode, key, random);
mode = opmode;
}
@@ -856,7 +992,7 @@ public class Cipher {
if (input.length == 0) {
return null;
}
- return spiImpl.engineUpdate(input, 0, input.length);
+ return getSpi().engineUpdate(input, 0, input.length);
}
/**
@@ -890,7 +1026,7 @@ public class Cipher {
if (input.length == 0) {
return null;
}
- return spiImpl.engineUpdate(input, inputOffset, inputLen);
+ return getSpi().engineUpdate(input, inputOffset, inputLen);
}
private static void checkInputOffsetAndCount(int inputArrayLength,
@@ -986,7 +1122,7 @@ public class Cipher {
if (input.length == 0) {
return 0;
}
- return spiImpl.engineUpdate(input, inputOffset, inputLen, output,
+ return getSpi().engineUpdate(input, inputOffset, inputLen, output,
outputOffset);
}
@@ -1022,7 +1158,7 @@ public class Cipher {
if (input == output) {
throw new IllegalArgumentException("input == output");
}
- return spiImpl.engineUpdate(input, output);
+ return getSpi().engineUpdate(input, output);
}
/**
@@ -1053,7 +1189,7 @@ public class Cipher {
if (input.length == 0) {
return;
}
- spiImpl.engineUpdateAAD(input, 0, input.length);
+ getSpi().engineUpdateAAD(input, 0, input.length);
}
/**
@@ -1089,7 +1225,7 @@ public class Cipher {
if (input.length == 0) {
return;
}
- spiImpl.engineUpdateAAD(input, inputOffset, inputLen);
+ getSpi().engineUpdateAAD(input, inputOffset, inputLen);
}
/**
@@ -1115,7 +1251,7 @@ public class Cipher {
if (input == null) {
throw new IllegalArgumentException("input == null");
}
- spiImpl.engineUpdateAAD(input);
+ getSpi().engineUpdateAAD(input);
}
/**
@@ -1139,7 +1275,7 @@ public class Cipher {
if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE) {
throw new IllegalStateException();
}
- return spiImpl.engineDoFinal(null, 0, 0);
+ return getSpi().engineDoFinal(null, 0, 0);
}
/**
@@ -1175,7 +1311,7 @@ public class Cipher {
if (outputOffset < 0) {
throw new IllegalArgumentException("outputOffset < 0. outputOffset=" + outputOffset);
}
- return spiImpl.engineDoFinal(null, 0, 0, output, outputOffset);
+ return getSpi().engineDoFinal(null, 0, 0, output, outputOffset);
}
/**
@@ -1201,7 +1337,7 @@ public class Cipher {
if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE) {
throw new IllegalStateException();
}
- return spiImpl.engineDoFinal(input, 0, input.length);
+ return getSpi().engineDoFinal(input, 0, input.length);
}
/**
@@ -1236,7 +1372,7 @@ public class Cipher {
throw new IllegalStateException();
}
checkInputOffsetAndCount(input.length, inputOffset, inputLen);
- return spiImpl.engineDoFinal(input, inputOffset, inputLen);
+ return getSpi().engineDoFinal(input, inputOffset, inputLen);
}
/**
@@ -1314,7 +1450,7 @@ public class Cipher {
throw new IllegalStateException();
}
checkInputOffsetAndCount(input.length, inputOffset, inputLen);
- return spiImpl.engineDoFinal(input, inputOffset, inputLen, output,
+ return getSpi().engineDoFinal(input, inputOffset, inputLen, output,
outputOffset);
}
@@ -1354,7 +1490,7 @@ public class Cipher {
if (input == output) {
throw new IllegalArgumentException("input == output");
}
- return spiImpl.engineDoFinal(input, output);
+ return getSpi().engineDoFinal(input, output);
}
/**
@@ -1376,7 +1512,7 @@ public class Cipher {
if (mode != WRAP_MODE) {
throw new IllegalStateException();
}
- return spiImpl.engineWrap(key);
+ return getSpi().engineWrap(key);
}
/**
@@ -1406,7 +1542,7 @@ public class Cipher {
if (mode != UNWRAP_MODE) {
throw new IllegalStateException();
}
- return spiImpl.engineUnwrap(wrappedKey, wrappedKeyAlgorithm,
+ return getSpi().engineUnwrap(wrappedKey, wrappedKeyAlgorithm,
wrappedKeyType);
}
diff --git a/luni/src/main/java/javax/crypto/CipherInputStream.java b/luni/src/main/java/javax/crypto/CipherInputStream.java
index f2f59c1..3061655 100644
--- a/luni/src/main/java/javax/crypto/CipherInputStream.java
+++ b/luni/src/main/java/javax/crypto/CipherInputStream.java
@@ -17,6 +17,7 @@
package javax.crypto;
+import java.io.BufferedInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -34,11 +35,8 @@ import libcore.io.Streams;
* CipherInputStream} tries to read the data an decrypt them before returning.
*/
public class CipherInputStream extends FilterInputStream {
-
- private static final int I_BUFFER_SIZE = 20;
-
private final Cipher cipher;
- private final byte[] inputBuffer = new byte[I_BUFFER_SIZE];
+ private final byte[] inputBuffer;
private byte[] outputBuffer;
private int outputIndex; // index of the first byte to return from outputBuffer
private int outputLength; // count of the bytes to return from outputBuffer
@@ -60,6 +58,11 @@ public class CipherInputStream extends FilterInputStream {
public CipherInputStream(InputStream is, Cipher c) {
super(is);
this.cipher = c;
+ int blockSize = Math.max(c.getBlockSize(), 1);
+ int bufferSize = Math.max(blockSize,
+ BufferedInputStream.DEFAULT_BUFFER_SIZE / blockSize * blockSize);
+ inputBuffer = new byte[bufferSize];
+ outputBuffer = new byte[bufferSize + ((blockSize > 1) ? 2 * blockSize : 0)];
}
/**
@@ -76,19 +79,13 @@ public class CipherInputStream extends FilterInputStream {
}
/**
- * Reads the next byte from this cipher input stream.
- *
- * @return the next byte, or {@code -1} if the end of the stream is reached.
- * @throws IOException
- * if an error occurs.
+ * Attempts to fill the input buffer and process some data through the
+ * cipher. Returns {@code true} if output from the cipher is available to
+ * use.
*/
- @Override
- public int read() throws IOException {
+ private boolean fillBuffer() throws IOException {
if (finished) {
- return (outputIndex == outputLength) ? -1 : outputBuffer[outputIndex++] & 0xFF;
- }
- if (outputIndex < outputLength) {
- return outputBuffer[outputIndex++] & 0xFF;
+ return false;
}
outputIndex = 0;
outputLength = 0;
@@ -107,7 +104,7 @@ public class CipherInputStream extends FilterInputStream {
throw new IOException("Error while finalizing cipher", e);
}
finished = true;
- break;
+ return outputLength != 0;
}
try {
outputLength = cipher.update(inputBuffer, 0, byteCount, outputBuffer, 0);
@@ -115,7 +112,25 @@ public class CipherInputStream extends FilterInputStream {
throw new AssertionError(e); // should not happen since we sized with getOutputSize
}
}
- return read();
+ return true;
+ }
+
+ /**
+ * Reads the next byte from this cipher input stream.
+ *
+ * @return the next byte, or {@code -1} if the end of the stream is reached.
+ * @throws IOException
+ * if an error occurs.
+ */
+ @Override
+ public int read() throws IOException {
+ if (in == null) {
+ throw new NullPointerException("in == null");
+ }
+ if (outputIndex == outputLength && !fillBuffer()) {
+ return -1;
+ }
+ return outputBuffer[outputIndex++] & 0xFF;
}
/**
@@ -137,18 +152,18 @@ public class CipherInputStream extends FilterInputStream {
if (in == null) {
throw new NullPointerException("in == null");
}
-
- int i;
- for (i = 0; i < len; ++i) {
- int b = read();
- if (b == -1) {
- return (i == 0) ? -1 : i;
- }
- if (buf != null) {
- buf[off+i] = (byte) b;
- }
+ if (outputIndex == outputLength && !fillBuffer()) {
+ return -1;
+ }
+ int available = outputLength - outputIndex;
+ if (available < len) {
+ len = available;
+ }
+ if (buf != null) {
+ System.arraycopy(outputBuffer, outputIndex, buf, off, len);
}
- return i;
+ outputIndex += len;
+ return len;
}
@Override
@@ -158,7 +173,7 @@ public class CipherInputStream extends FilterInputStream {
@Override
public int available() throws IOException {
- return 0;
+ return outputLength - outputIndex;
}
/**
diff --git a/luni/src/main/java/javax/crypto/ExemptionMechanism.java b/luni/src/main/java/javax/crypto/ExemptionMechanism.java
index 8745b78..c2d42e6 100644
--- a/luni/src/main/java/javax/crypto/ExemptionMechanism.java
+++ b/luni/src/main/java/javax/crypto/ExemptionMechanism.java
@@ -142,6 +142,7 @@ public class ExemptionMechanism {
/**
* Returns a new {@code ExemptionMechanism} instance that provides the
* specified exemption mechanism algorithm from the specified provider.
+ * The {@code provider} supplied does not have to be registered.
*
* @param algorithm
* the name of the requested exemption mechanism.
diff --git a/luni/src/main/java/javax/crypto/KeyAgreement.java b/luni/src/main/java/javax/crypto/KeyAgreement.java
index 51b4cd1..abcfd0e 100644
--- a/luni/src/main/java/javax/crypto/KeyAgreement.java
+++ b/luni/src/main/java/javax/crypto/KeyAgreement.java
@@ -23,9 +23,11 @@ import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
+import java.security.ProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
+import java.util.ArrayList;
import org.apache.harmony.security.fortress.Engine;
/**
@@ -35,22 +37,33 @@ import org.apache.harmony.security.fortress.Engine;
*/
public class KeyAgreement {
+ // The service name.
+ private static final String SERVICE = "KeyAgreement";
+
// Used to access common engine functionality
- private static final Engine ENGINE = new Engine("KeyAgreement");
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store SecureRandom
private static final SecureRandom RANDOM = new SecureRandom();
// Store used provider
- private final Provider provider;
+ private Provider provider;
+
+ // Provider that was requested during creation.
+ private final Provider specifiedProvider;
// Store used spi implementation
- private final KeyAgreementSpi spiImpl;
+ private KeyAgreementSpi spiImpl;
// Store used algorithm name
private final String algorithm;
/**
+ * Lock held while the SPI is initializing.
+ */
+ private final Object initLock = new Object();
+
+ /**
* Creates a new {@code KeyAgreement} instance.
*
* @param keyAgreeSpi
@@ -62,9 +75,9 @@ public class KeyAgreement {
*/
protected KeyAgreement(KeyAgreementSpi keyAgreeSpi, Provider provider,
String algorithm) {
- this.provider = provider;
- this.algorithm = algorithm;
this.spiImpl = keyAgreeSpi;
+ this.specifiedProvider = provider;
+ this.algorithm = algorithm;
}
/**
@@ -82,6 +95,7 @@ public class KeyAgreement {
* @return the provider for this {@code KeyAgreement} instance.
*/
public final Provider getProvider() {
+ getSpi();
return provider;
}
@@ -96,13 +110,8 @@ public class KeyAgreement {
* @throws NullPointerException
* if the specified algorithm is {@code null}.
*/
- public static final KeyAgreement getInstance(String algorithm)
- throws NoSuchAlgorithmException {
- if (algorithm == null) {
- throw new NullPointerException("algorithm == null");
- }
- Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
- return new KeyAgreement((KeyAgreementSpi) sap.spi, sap.provider, algorithm);
+ public static final KeyAgreement getInstance(String algorithm) throws NoSuchAlgorithmException {
+ return getKeyAgreement(algorithm, null);
}
/**
@@ -124,9 +133,8 @@ public class KeyAgreement {
* @throws IllegalArgumentException
* if the specified provider name is {@code null} or empty.
*/
- public static final KeyAgreement getInstance(String algorithm,
- String provider) throws NoSuchAlgorithmException,
- NoSuchProviderException {
+ public static final KeyAgreement getInstance(String algorithm, String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException {
if (provider == null || provider.isEmpty()) {
throw new IllegalArgumentException("Provider is null or empty");
}
@@ -134,12 +142,13 @@ public class KeyAgreement {
if (impProvider == null) {
throw new NoSuchProviderException(provider);
}
- return getInstance(algorithm, impProvider);
+ return getKeyAgreement(algorithm, impProvider);
}
/**
* Create a new {@code KeyAgreement} for the specified algorithm from the
- * specified provider.
+ * specified provider. The {@code provider} supplied does not have to be
+ * registered.
*
* @param algorithm
* the name of the key agreement algorithm to create.
@@ -155,29 +164,108 @@ public class KeyAgreement {
* @throws NullPointerException
* if the specified algorithm name is {@code null}.
*/
- public static final KeyAgreement getInstance(String algorithm,
- Provider provider) throws NoSuchAlgorithmException {
+ public static final KeyAgreement getInstance(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException {
if (provider == null) {
throw new IllegalArgumentException("provider == null");
}
+ return getKeyAgreement(algorithm, provider);
+ }
+
+ private static KeyAgreement getKeyAgreement(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException {
if (algorithm == null) {
throw new NullPointerException("algorithm == null");
}
- Object spi = ENGINE.getInstance(algorithm, provider, null);
- return new KeyAgreement((KeyAgreementSpi) spi, provider, algorithm);
+
+ if (tryAlgorithm(null, provider, algorithm) == null) {
+ if (provider == null) {
+ throw new NoSuchAlgorithmException("No provider found for " + algorithm);
+ } else {
+ throw new NoSuchAlgorithmException("Provider " + provider.getName()
+ + " does not provide " + algorithm);
+ }
+ }
+ return new KeyAgreement(null, provider, algorithm);
+ }
+
+ private static Engine.SpiAndProvider tryAlgorithm(Key key, Provider provider, String algorithm) {
+ if (provider != null) {
+ Provider.Service service = provider.getService(SERVICE, algorithm);
+ if (service == null) {
+ return null;
+ }
+ return tryAlgorithmWithProvider(key, service);
+ }
+ ArrayList<Provider.Service> services = ENGINE.getServices(algorithm);
+ if (services == null) {
+ return null;
+ }
+ for (Provider.Service service : services) {
+ Engine.SpiAndProvider sap = tryAlgorithmWithProvider(key, service);
+ if (sap != null) {
+ return sap;
+ }
+ }
+ return null;
+ }
+
+ private static Engine.SpiAndProvider tryAlgorithmWithProvider(Key key, Provider.Service service) {
+ try {
+ if (key != null && !service.supportsParameter(key)) {
+ return null;
+ }
+
+ Engine.SpiAndProvider sap = ENGINE.getInstance(service, null);
+ if (sap.spi == null || sap.provider == null) {
+ return null;
+ }
+ if (!(sap.spi instanceof KeyAgreementSpi)) {
+ return null;
+ }
+ return sap;
+ } catch (NoSuchAlgorithmException ignored) {
+ }
+ return null;
+ }
+
+ /**
+ * Makes sure a KeyAgreementSpi that matches this type is selected.
+ */
+ private KeyAgreementSpi getSpi(Key key) {
+ synchronized (initLock) {
+ if (spiImpl != null && key == null) {
+ return spiImpl;
+ }
+
+ final Engine.SpiAndProvider sap = tryAlgorithm(key, specifiedProvider, algorithm);
+ if (sap == null) {
+ throw new ProviderException("No provider for " + getAlgorithm());
+ }
+
+ spiImpl = (KeyAgreementSpi) sap.spi;
+ provider = sap.provider;
+
+ return spiImpl;
+ }
+ }
+
+ /**
+ * Convenience call when the Key is not available.
+ */
+ private KeyAgreementSpi getSpi() {
+ return getSpi(null);
}
/**
* Initializes this {@code KeyAgreement} with the specified key.
*
- * @param key
- * the key to initialize this key agreement.
- * @throws InvalidKeyException
- * if the specified key cannot be used to initialize this key
- * agreement.
+ * @param key the key to initialize this key agreement.
+ * @throws InvalidKeyException if the specified key cannot be used to
+ * initialize this key agreement.
*/
public final void init(Key key) throws InvalidKeyException {
- spiImpl.engineInit(key, RANDOM);//new SecureRandom());
+ getSpi(key).engineInit(key, RANDOM);//new SecureRandom());
}
/**
@@ -194,7 +282,7 @@ public class KeyAgreement {
*/
public final void init(Key key, SecureRandom random)
throws InvalidKeyException {
- spiImpl.engineInit(key, random);
+ getSpi(key).engineInit(key, random);
}
/**
@@ -214,7 +302,7 @@ public class KeyAgreement {
*/
public final void init(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
- spiImpl.engineInit(key, params, RANDOM);//new SecureRandom());
+ getSpi(key).engineInit(key, params, RANDOM);//new SecureRandom());
}
/**
@@ -237,7 +325,7 @@ public class KeyAgreement {
public final void init(Key key, AlgorithmParameterSpec params,
SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException {
- spiImpl.engineInit(key, params, random);
+ getSpi(key).engineInit(key, params, random);
}
/**
@@ -259,7 +347,7 @@ public class KeyAgreement {
*/
public final Key doPhase(Key key, boolean lastPhase)
throws InvalidKeyException, IllegalStateException {
- return spiImpl.engineDoPhase(key, lastPhase);
+ return getSpi().engineDoPhase(key, lastPhase);
}
/**
@@ -270,7 +358,7 @@ public class KeyAgreement {
* if this key agreement is not complete.
*/
public final byte[] generateSecret() throws IllegalStateException {
- return spiImpl.engineGenerateSecret();
+ return getSpi().engineGenerateSecret();
}
/**
@@ -289,7 +377,7 @@ public class KeyAgreement {
*/
public final int generateSecret(byte[] sharedSecret, int offset)
throws IllegalStateException, ShortBufferException {
- return spiImpl.engineGenerateSecret(sharedSecret, offset);
+ return getSpi().engineGenerateSecret(sharedSecret, offset);
}
/**
@@ -311,7 +399,7 @@ public class KeyAgreement {
public final SecretKey generateSecret(String algorithm)
throws IllegalStateException, NoSuchAlgorithmException,
InvalidKeyException {
- return spiImpl.engineGenerateSecret(algorithm);
+ return getSpi().engineGenerateSecret(algorithm);
}
}
diff --git a/luni/src/main/java/javax/crypto/KeyGenerator.java b/luni/src/main/java/javax/crypto/KeyGenerator.java
index 606998a..fc409da 100644
--- a/luni/src/main/java/javax/crypto/KeyGenerator.java
+++ b/luni/src/main/java/javax/crypto/KeyGenerator.java
@@ -137,7 +137,8 @@ public class KeyGenerator {
/**
* Creates a new {@code KeyGenerator} instance that provides the specified
- * key algorithm from the specified provider.
+ * key algorithm from the specified provider. The {@code provider}
+ * supplied does not have to be registered.
*
* @param algorithm
* the name of the requested key algorithm.
diff --git a/luni/src/main/java/javax/crypto/Mac.java b/luni/src/main/java/javax/crypto/Mac.java
index c208456..5a73dc5 100644
--- a/luni/src/main/java/javax/crypto/Mac.java
+++ b/luni/src/main/java/javax/crypto/Mac.java
@@ -24,8 +24,10 @@ import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
+import java.security.ProviderException;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
+import java.util.ArrayList;
import org.apache.harmony.security.fortress.Engine;
@@ -35,18 +37,29 @@ import org.apache.harmony.security.fortress.Engine;
*/
public class Mac implements Cloneable {
+ // The service name.
+ private static final String SERVICE = "Mac";
+
//Used to access common engine functionality
- private static final Engine ENGINE = new Engine("Mac");
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store used provider
- private final Provider provider;
+ private Provider provider;
+
+ // Provider that was requested during creation.
+ private final Provider specifiedProvider;
// Store used spi implementation
- private final MacSpi spiImpl;
+ private MacSpi spiImpl;
// Store used algorithm name
private final String algorithm;
+ /**
+ * Lock held while the SPI is initializing.
+ */
+ private final Object initLock = new Object();
+
// Store Mac state (initialized or not initialized)
private boolean isInitMac;
@@ -61,7 +74,7 @@ public class Mac implements Cloneable {
* the name of the MAC algorithm.
*/
protected Mac(MacSpi macSpi, Provider provider, String algorithm) {
- this.provider = provider;
+ this.specifiedProvider = provider;
this.algorithm = algorithm;
this.spiImpl = macSpi;
this.isInitMac = false;
@@ -82,6 +95,7 @@ public class Mac implements Cloneable {
* @return the provider of this {@code Mac} instance.
*/
public final Provider getProvider() {
+ getSpi();
return provider;
}
@@ -100,11 +114,7 @@ public class Mac implements Cloneable {
*/
public static final Mac getInstance(String algorithm)
throws NoSuchAlgorithmException {
- if (algorithm == null) {
- throw new NullPointerException("algorithm == null");
- }
- Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
- return new Mac((MacSpi) sap.spi, sap.provider, algorithm);
+ return getMac(algorithm, null);
}
/**
@@ -136,12 +146,13 @@ public class Mac implements Cloneable {
if (impProvider == null) {
throw new NoSuchProviderException(provider);
}
- return getInstance(algorithm, impProvider);
+ return getMac(algorithm, impProvider);
}
/**
* Creates a new {@code Mac} instance that provides the specified MAC
- * algorithm from the specified provider.
+ * algorithm from the specified provider. The {@code provider} supplied
+ * does not have to be registered.
*
* @param algorithm
* the name of the requested MAC algorithm.
@@ -162,11 +173,102 @@ public class Mac implements Cloneable {
if (provider == null) {
throw new IllegalArgumentException("provider == null");
}
+ return getMac(algorithm, provider);
+ }
+
+ private static Mac getMac(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException {
if (algorithm == null) {
throw new NullPointerException("algorithm == null");
}
- Object spi = ENGINE.getInstance(algorithm, provider, null);
- return new Mac((MacSpi) spi, provider, algorithm);
+
+ if (tryAlgorithm(null, provider, algorithm) == null) {
+ if (provider == null) {
+ throw new NoSuchAlgorithmException("No provider found for " + algorithm);
+ } else {
+ throw new NoSuchAlgorithmException("Provider " + provider.getName()
+ + " does not provide " + algorithm);
+ }
+ }
+ return new Mac(null, provider, algorithm);
+ }
+
+ private static Engine.SpiAndProvider tryAlgorithm(Key key, Provider provider, String algorithm) {
+ if (provider != null) {
+ Provider.Service service = provider.getService(SERVICE, algorithm);
+ if (service == null) {
+ return null;
+ }
+ return tryAlgorithmWithProvider(key, service);
+ }
+ ArrayList<Provider.Service> services = ENGINE.getServices(algorithm);
+ if (services == null) {
+ return null;
+ }
+ for (Provider.Service service : services) {
+ Engine.SpiAndProvider sap = tryAlgorithmWithProvider(key, service);
+ if (sap != null) {
+ return sap;
+ }
+ }
+ return null;
+ }
+
+ private static Engine.SpiAndProvider tryAlgorithmWithProvider(Key key, Provider.Service service) {
+ try {
+ if (key != null && !service.supportsParameter(key)) {
+ return null;
+ }
+
+ Engine.SpiAndProvider sap = ENGINE.getInstance(service, null);
+ if (sap.spi == null || sap.provider == null) {
+ return null;
+ }
+ if (!(sap.spi instanceof MacSpi)) {
+ return null;
+ }
+ return sap;
+ } catch (NoSuchAlgorithmException ignored) {
+ }
+ return null;
+ }
+
+ /**
+ * Makes sure a MacSpi that matches this type is selected.
+ */
+ private MacSpi getSpi(Key key) {
+ synchronized (initLock) {
+ if (spiImpl != null && provider != null && key == null) {
+ return spiImpl;
+ }
+
+ if (algorithm == null) {
+ return null;
+ }
+
+ final Engine.SpiAndProvider sap = tryAlgorithm(key, specifiedProvider, algorithm);
+ if (sap == null) {
+ throw new ProviderException("No provider for " + getAlgorithm());
+ }
+
+ /*
+ * Set our Spi if we've never been initialized or if we have the Spi
+ * specified and have a null provider.
+ */
+ if (spiImpl == null || provider != null) {
+ spiImpl = (MacSpi) sap.spi;
+ }
+ provider = sap.provider;
+
+ return spiImpl;
+ }
+ }
+
+ /**
+ * Convenience call when the Key is not available.
+ */
+ private MacSpi getSpi() {
+ return getSpi(null);
}
/**
@@ -175,7 +277,7 @@ public class Mac implements Cloneable {
* @return the length of this MAC (in bytes).
*/
public final int getMacLength() {
- return spiImpl.engineGetMacLength();
+ return getSpi().engineGetMacLength();
}
/**
@@ -198,7 +300,7 @@ public class Mac implements Cloneable {
if (key == null) {
throw new InvalidKeyException("key == null");
}
- spiImpl.engineInit(key, params);
+ getSpi(key).engineInit(key, params);
isInitMac = true;
}
@@ -219,7 +321,7 @@ public class Mac implements Cloneable {
throw new InvalidKeyException("key == null");
}
try {
- spiImpl.engineInit(key, null);
+ getSpi(key).engineInit(key, null);
isInitMac = true;
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
@@ -238,7 +340,7 @@ public class Mac implements Cloneable {
if (!isInitMac) {
throw new IllegalStateException();
}
- spiImpl.engineUpdate(input);
+ getSpi().engineUpdate(input);
}
/**
@@ -269,7 +371,7 @@ public class Mac implements Cloneable {
+ " input.length=" + input.length
+ " offset=" + offset + ", len=" + len);
}
- spiImpl.engineUpdate(input, offset, len);
+ getSpi().engineUpdate(input, offset, len);
}
/**
@@ -285,7 +387,7 @@ public class Mac implements Cloneable {
throw new IllegalStateException();
}
if (input != null) {
- spiImpl.engineUpdate(input, 0, input.length);
+ getSpi().engineUpdate(input, 0, input.length);
}
}
@@ -304,7 +406,7 @@ public class Mac implements Cloneable {
throw new IllegalStateException();
}
if (input != null) {
- spiImpl.engineUpdate(input);
+ getSpi().engineUpdate(input);
} else {
throw new IllegalArgumentException("input == null");
}
@@ -326,7 +428,7 @@ public class Mac implements Cloneable {
if (!isInitMac) {
throw new IllegalStateException();
}
- return spiImpl.engineDoFinal();
+ return getSpi().engineDoFinal();
}
/**
@@ -361,11 +463,12 @@ public class Mac implements Cloneable {
if ((outOffset < 0) || (outOffset >= output.length)) {
throw new ShortBufferException("Incorrect outOffset: " + outOffset);
}
- int t = spiImpl.engineGetMacLength();
+ MacSpi spi = getSpi();
+ int t = spi.engineGetMacLength();
if (t > (output.length - outOffset)) {
throw new ShortBufferException("Output buffer is short. Needed " + t + " bytes.");
}
- byte[] result = spiImpl.engineDoFinal();
+ byte[] result = spi.engineDoFinal();
System.arraycopy(result, 0, output, outOffset, result.length);
}
@@ -389,10 +492,11 @@ public class Mac implements Cloneable {
if (!isInitMac) {
throw new IllegalStateException();
}
+ MacSpi spi = getSpi();
if (input != null) {
- spiImpl.engineUpdate(input, 0, input.length);
+ spi.engineUpdate(input, 0, input.length);
}
- return spiImpl.engineDoFinal();
+ return spi.engineDoFinal();
}
/**
@@ -403,7 +507,7 @@ public class Mac implements Cloneable {
* initialized with different parameters.
*/
public final void reset() {
- spiImpl.engineReset();
+ getSpi().engineReset();
}
/**
@@ -415,7 +519,11 @@ public class Mac implements Cloneable {
*/
@Override
public final Object clone() throws CloneNotSupportedException {
- MacSpi newSpiImpl = (MacSpi)spiImpl.clone();
+ MacSpi newSpiImpl = null;
+ final MacSpi spi = getSpi();
+ if (spi != null) {
+ newSpiImpl = (MacSpi) spi.clone();
+ }
Mac mac = new Mac(newSpiImpl, this.provider, this.algorithm);
mac.isInitMac = this.isInitMac;
return mac;
diff --git a/luni/src/main/java/javax/crypto/SealedObject.java b/luni/src/main/java/javax/crypto/SealedObject.java
index cfb970b..4b91184 100644
--- a/luni/src/main/java/javax/crypto/SealedObject.java
+++ b/luni/src/main/java/javax/crypto/SealedObject.java
@@ -19,6 +19,7 @@ package javax.crypto;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -29,6 +30,7 @@ import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
+import libcore.io.IoUtils;
/**
* A {@code SealedObject} is a wrapper around a {@code serializable} object
@@ -57,14 +59,21 @@ public class SealedObject implements Serializable {
private String paramsAlg;
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
- // We do unshared reads here to ensure we have our own clones of the byte[]s.
- encodedParams = (byte[]) s.readUnshared();
- encryptedContent = (byte[]) s.readUnshared();
- // These are regular shared reads because the algorithms used by a given stream are
- // almost certain to the be same for each object, and String is immutable anyway,
- // so there's no security concern about sharing.
- sealAlg = (String) s.readObject();
- paramsAlg = (String) s.readObject();
+ // This implementation is based on the latest recommendations for safe deserialization at
+ // the time of writing. See the Serialization spec section A.6.
+ ObjectInputStream.GetField fields = s.readFields();
+
+ // The mutable byte arrays are cloned and the immutable strings are not.
+ this.encodedParams = getSafeCopy(fields, "encodedParams");
+ this.encryptedContent = getSafeCopy(fields, "encryptedContent");
+ this.paramsAlg = (String) fields.get("paramsAlg", null);
+ this.sealAlg = (String) fields.get("sealAlg", null);
+ }
+
+ private static byte[] getSafeCopy(ObjectInputStream.GetField fields, String fieldName)
+ throws IOException {
+ byte[] fieldValue = (byte[]) fields.get(fieldName, null);
+ return fieldValue != null ? fieldValue.clone() : null;
}
/**
@@ -87,13 +96,14 @@ public class SealedObject implements Serializable {
* if the cipher is {@code null}.
*/
public SealedObject(Serializable object, Cipher c)
- throws IOException, IllegalBlockSizeException {
+ throws IOException, IllegalBlockSizeException {
if (c == null) {
throw new NullPointerException("c == null");
}
+ ObjectOutputStream oos = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(bos);
+ oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
AlgorithmParameters ap = c.getParameters();
@@ -105,6 +115,8 @@ public class SealedObject implements Serializable {
// should be never thrown because the cipher
// should be initialized for encryption
throw new IOException(e.toString());
+ } finally {
+ IoUtils.closeQuietly(oos);
}
}
@@ -119,8 +131,10 @@ public class SealedObject implements Serializable {
if (so == null) {
throw new NullPointerException("so == null");
}
- this.encryptedContent = so.encryptedContent;
- this.encodedParams = so.encodedParams;
+ // For safety: clone the mutable arrays so that each object has its own independent copy of
+ // the data.
+ this.encryptedContent = so.encryptedContent != null ? so.encryptedContent.clone() : null;
+ this.encodedParams = so.encodedParams != null ? so.encodedParams.clone() : null;
this.sealAlg = so.sealAlg;
this.paramsAlg = so.paramsAlg;
}
@@ -158,18 +172,14 @@ public class SealedObject implements Serializable {
try {
Cipher cipher = Cipher.getInstance(sealAlg);
if ((paramsAlg != null) && (paramsAlg.length() != 0)) {
- AlgorithmParameters params =
- AlgorithmParameters.getInstance(paramsAlg);
+ AlgorithmParameters params = AlgorithmParameters.getInstance(paramsAlg);
params.init(encodedParams);
cipher.init(Cipher.DECRYPT_MODE, key, params);
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
}
byte[] serialized = cipher.doFinal(encryptedContent);
- ObjectInputStream ois =
- new ObjectInputStream(
- new ByteArrayInputStream(serialized));
- return ois.readObject();
+ return readSerialized(serialized);
} catch (NoSuchPaddingException e) {
// should not be thrown because cipher text was made
// with existing padding
@@ -186,7 +196,7 @@ public class SealedObject implements Serializable {
// should not be thrown because the cipher text
// was correctly made
throw new NoSuchAlgorithmException(e.toString());
- } catch (IllegalStateException e) {
+ } catch (IllegalStateException e) {
// should never be thrown because cipher is initialized
throw new NoSuchAlgorithmException(e.toString());
}
@@ -217,10 +227,7 @@ public class SealedObject implements Serializable {
throw new NullPointerException("c == null");
}
byte[] serialized = c.doFinal(encryptedContent);
- ObjectInputStream ois =
- new ObjectInputStream(
- new ByteArrayInputStream(serialized));
- return ois.readObject();
+ return readSerialized(serialized);
}
/**
@@ -253,18 +260,14 @@ public class SealedObject implements Serializable {
try {
Cipher cipher = Cipher.getInstance(sealAlg, provider);
if ((paramsAlg != null) && (paramsAlg.length() != 0)) {
- AlgorithmParameters params =
- AlgorithmParameters.getInstance(paramsAlg);
+ AlgorithmParameters params = AlgorithmParameters.getInstance(paramsAlg);
params.init(encodedParams);
cipher.init(Cipher.DECRYPT_MODE, key, params);
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
}
byte[] serialized = cipher.doFinal(encryptedContent);
- ObjectInputStream ois =
- new ObjectInputStream(
- new ByteArrayInputStream(serialized));
- return ois.readObject();
+ return readSerialized(serialized);
} catch (NoSuchPaddingException e) {
// should not be thrown because cipher text was made
// with existing padding
@@ -286,4 +289,15 @@ public class SealedObject implements Serializable {
throw new NoSuchAlgorithmException(e.toString());
}
}
+
+ private static Object readSerialized(byte[] serialized)
+ throws IOException, ClassNotFoundException {
+ ObjectInputStream ois = null;
+ try {
+ ois = new ObjectInputStream(new ByteArrayInputStream(serialized));
+ return ois.readObject();
+ } finally {
+ IoUtils.closeQuietly(ois);
+ }
+ }
}
diff --git a/luni/src/main/java/javax/crypto/SecretKeyFactory.java b/luni/src/main/java/javax/crypto/SecretKeyFactory.java
index 8ab3eb8..9298b8e 100644
--- a/luni/src/main/java/javax/crypto/SecretKeyFactory.java
+++ b/luni/src/main/java/javax/crypto/SecretKeyFactory.java
@@ -143,7 +143,8 @@ public class SecretKeyFactory {
/**
* Creates a new {@code SecretKeyFactory} instance for the specified key
- * algorithm from the specified provider.
+ * algorithm from the specified provider. The {@code provider} supplied
+ * does not have to be registered.
*
* @param algorithm
* the name of the key algorithm.
diff --git a/luni/src/main/java/javax/net/ssl/SSLContext.java b/luni/src/main/java/javax/net/ssl/SSLContext.java
index a59f301..efc1947 100644
--- a/luni/src/main/java/javax/net/ssl/SSLContext.java
+++ b/luni/src/main/java/javax/net/ssl/SSLContext.java
@@ -82,6 +82,46 @@ public class SSLContext {
/**
* Creates a new {@code SSLContext} instance for the specified protocol.
*
+ * <p>The following protocols are supported:
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Protocol</th>
+ * <th>API Levels</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>Default</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>SSL</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>SSLv3</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.1</td>
+ * <td>16+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.2</td>
+ * <td>16+</td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
* @param protocol
* the requested protocol to create a context for.
* @return the created {@code SSLContext} instance.
@@ -103,6 +143,79 @@ public class SSLContext {
* Creates a new {@code SSLContext} instance for the specified protocol from
* the specified provider.
*
+ * <p>The following combinations are supported:
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Protocol</th>
+ * <th>Provider</th>
+ * <th>API Levels</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>Default</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>SSL</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>SSL</td>
+ * <td>HarmonyJSSE</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSLv3</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>SSLv3</td>
+ * <td>HarmonyJSSE</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS</td>
+ * <td>HarmonyJSSE</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1</td>
+ * <td>HarmonyJSSE</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.1</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>16+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.2</td>
+ * <td>AndroidOpenSSL</td>
+ * <td>16+</td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <p><strong>NOTE:</strong> The best practice is to rely on platform
+ * defaults rather than explicitly specify a provider.
+ * {@link #getDefault()} and {@link #getInstance(String)} are normally
+ * preferred over this method.
+ *
* @param protocol
* the requested protocol to create a context for.
* @param provider
@@ -201,16 +314,33 @@ public class SSLContext {
}
/**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
+ * Initializes this {@code SSLContext} instance. Three aspects of the context can be configured
+ * during initialization:
+ * <ul>
+ * <li>Providers of key material for key exchange and peer authentication
+ * ({@link KeyManager} instances),</li>
+ * <li>Providers of trust decisions about peers ({@link TrustManager} instances),
+ * </li>
+ * <li>Provider of randomness ({@link SecureRandom} instance).</li>
+ * </ul>
+ *
+ * <p>For each type of {@code KeyManager} or {@code TrustManager} used by this context, only the
+ * first matching instance from {@code km} or {@code tm} will be used. For example, only the
+ * first instance of {@link X509TrustManager} from {@code tm} will be used.
+ *
+ * <p>For any parameter set to {@code null} defaults will be used. In that case, the installed
+ * security providers will be searched for the highest priority implementation of the required
+ * primitives. For {@code km} and {@code tm}, the highest priority implementation
+ * of {@link KeyManagerFactory} and {@link TrustManagerFactory} will be used to obtain the
+ * required types of {@code KeyManager} and {@code TrustManager}. For {@code sr}, the default
+ * {@code SecureRandom} implementation will be used.
*
* @param km
- * the key sources or {@code null}.
+ * the key sources or {@code null} for default.
* @param tm
- * the trust decision sources or {@code null}.
+ * the trust decision sources or {@code null} for default.
* @param sr
- * the randomness source or {@code null.}
+ * the randomness source or {@code null} for default.
* @throws KeyManagementException
* if initializing this instance fails.
*/
diff --git a/luni/src/main/java/javax/net/ssl/SSLEngine.java b/luni/src/main/java/javax/net/ssl/SSLEngine.java
index a6c9946..cbf02ac 100644
--- a/luni/src/main/java/javax/net/ssl/SSLEngine.java
+++ b/luni/src/main/java/javax/net/ssl/SSLEngine.java
@@ -24,6 +24,629 @@ import java.nio.ByteBuffer;
* protocols. It includes the setup, handshake, and encrypt/decrypt
* functionality needed to create a secure connection.
*
+ * <h3>Default configuration</h3>
+ * <p>{@code SSLEngine} instances obtained from default {@link SSLContext} are configured as
+ * follows:
+ *
+ * <h4>Protocols</h4>
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Protocol</th>
+ * <th>Supported (API Levels)</th>
+ * <th>Enabled by default (API Levels)</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>SSLv3</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.1</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.2</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <h4>Cipher suites</h4>
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Cipher suite</th>
+ * <th>Supported (API Levels)</th>
+ * <th>Enabled by default (API Levels)</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_DSS_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_RSA_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_EXPORT_WITH_RC4_40_MD5</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_WITH_RC4_128_MD5</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_EXPORT_WITH_RC4_40_MD5</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_NULL_MD5</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_NULL_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_RC4_128_MD5</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_RC4_128_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_DES_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_DES_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_DSS_WITH_DES_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_RSA_WITH_DES_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_DES_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_NULL_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_RC4_128_SHA</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_NULL_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_RC4_128_SHA</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_NULL_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_RC4_128_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_NULL_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_RC4_128_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_AES_128_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_AES_256_CBC_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_NULL_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_RC4_128_SHA</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_EMPTY_RENEGOTIATION_INFO_SCSV</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_FALLBACK_SCSV</td>
+ * <td>21+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_NULL_WITH_NULL_NULL</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>21+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_AES_128_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_AES_256_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_RC4_128_SHA</td>
+ * <td>21+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_DES_CBC_SHA</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_NULL_MD5</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_NULL_SHA</td>
+ * <td>1-8</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_NULL_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <p><em>NOTE</em>: PSK cipher suites are enabled by default only if the {@code SSLContext} through
+ * which the engine was created has been initialized with a {@code PSKKeyManager}.
+ *
* @since 1.5
*/
public abstract class SSLEngine {
diff --git a/luni/src/main/java/javax/net/ssl/SSLEngineResult.java b/luni/src/main/java/javax/net/ssl/SSLEngineResult.java
index 8a98831..3360832 100644
--- a/luni/src/main/java/javax/net/ssl/SSLEngineResult.java
+++ b/luni/src/main/java/javax/net/ssl/SSLEngineResult.java
@@ -110,16 +110,16 @@ public class SSLEngineResult {
public SSLEngineResult(SSLEngineResult.Status status,
SSLEngineResult.HandshakeStatus handshakeStatus, int bytesConsumed, int bytesProduced) {
if (status == null) {
- throw new IllegalArgumentException("status is null");
+ throw new IllegalArgumentException("status == null");
}
if (handshakeStatus == null) {
- throw new IllegalArgumentException("handshakeStatus is null");
+ throw new IllegalArgumentException("handshakeStatus == null");
}
if (bytesConsumed < 0) {
- throw new IllegalArgumentException("bytesConsumed is negative");
+ throw new IllegalArgumentException("bytesConsumed < 0: " + bytesConsumed);
}
if (bytesProduced < 0) {
- throw new IllegalArgumentException("bytesProduced is negative");
+ throw new IllegalArgumentException("bytesProduced < 0: " + bytesProduced);
}
this.status = status;
this.handshakeStatus = handshakeStatus;
diff --git a/luni/src/main/java/javax/net/ssl/SSLParameters.java b/luni/src/main/java/javax/net/ssl/SSLParameters.java
index 6694ef2..054abe2 100644
--- a/luni/src/main/java/javax/net/ssl/SSLParameters.java
+++ b/luni/src/main/java/javax/net/ssl/SSLParameters.java
@@ -27,6 +27,7 @@ public class SSLParameters {
private String[] protocols;
private boolean needClientAuth;
private boolean wantClientAuth;
+ private String endpointIdentificationAlgorithm;
/**
* The default SSLParameters constructor. Cipher suites and
diff --git a/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java b/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
index cce72cd..03b8828 100644
--- a/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
+++ b/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
@@ -20,6 +20,7 @@ package javax.net.ssl;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.net.ServerSocketFactory;
+import org.apache.harmony.security.fortress.Services;
/**
* The factory for SSL server sockets.
@@ -32,6 +33,8 @@ public abstract class SSLServerSocketFactory extends ServerSocketFactory {
private static String defaultName;
+ private static int lastCacheVersion = -1;
+
/**
* Returns the default {@code SSLServerSocketFactory} instance. The default
* implementation is defined by the security property
@@ -40,6 +43,12 @@ public abstract class SSLServerSocketFactory extends ServerSocketFactory {
* @return the default {@code SSLServerSocketFactory} instance.
*/
public static synchronized ServerSocketFactory getDefault() {
+ int newCacheVersion = Services.getCacheVersion();
+ if (lastCacheVersion != newCacheVersion) {
+ defaultServerSocketFactory = null;
+ defaultName = null;
+ lastCacheVersion = newCacheVersion;
+ }
if (defaultServerSocketFactory != null) {
return defaultServerSocketFactory;
}
diff --git a/luni/src/main/java/javax/net/ssl/SSLSocket.java b/luni/src/main/java/javax/net/ssl/SSLSocket.java
index 5049f81..dc406e1 100644
--- a/luni/src/main/java/javax/net/ssl/SSLSocket.java
+++ b/luni/src/main/java/javax/net/ssl/SSLSocket.java
@@ -25,6 +25,715 @@ import java.net.UnknownHostException;
/**
* The extension of {@code Socket} providing secure protocols like SSL (Secure
* Sockets Layer) or TLS (Transport Layer Security).
+ *
+ * <h3>Default configuration</h3>
+ * <p>{@code SSLSocket} instances obtained from default {@link SSLSocketFactory},
+ * {@link SSLServerSocketFactory}, and {@link SSLContext} are configured as follows:
+ *
+ * <h4>Protocols</h4>
+ *
+ * <p>Client socket:
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Protocol</th>
+ * <th>Supported (API Levels)</th>
+ * <th>Enabled by default (API Levels)</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>SSLv3</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.1</td>
+ * <td>16+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.2</td>
+ * <td>16+</td>
+ * <td>20+</td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <p>Server socket:
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Protocol</th>
+ * <th>Supported (API Levels)</th>
+ * <th>Enabled by default (API Levels)</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>SSLv3</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.1</td>
+ * <td>16+</td>
+ * <td>16+</td>
+ * </tr>
+ * <tr>
+ * <td>TLSv1.2</td>
+ * <td>16+</td>
+ * <td>16+</td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <h4>Cipher suites</h4>
+ *
+ * <p>Methods that operate with cipher suite names (for example,
+ * {@link #getSupportedCipherSuites() getSupportedCipherSuites},
+ * {@link #setEnabledCipherSuites(String[]) setEnabledCipherSuites}) have used
+ * standard names for cipher suites since API Level 9, as listed in the table
+ * below. Prior to API Level 9, non-standard (OpenSSL) names had been used (see
+ * the table following this table).
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>Cipher suite</th>
+ * <th>Supported (API Levels)</th>
+ * <th>Enabled by default (API Levels)</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_DSS_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DHE_RSA_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_EXPORT_WITH_RC4_40_MD5</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_DH_anon_WITH_RC4_128_MD5</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_EXPORT_WITH_RC4_40_MD5</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_DES_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_NULL_MD5</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_NULL_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_RC4_128_MD5</td>
+ * <td>9+</td>
+ * <td>9-19</td>
+ * </tr>
+ * <tr>
+ * <td>SSL_RSA_WITH_RC4_128_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_DSS_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DHE_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_DH_anon_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_NULL_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_ECDSA_WITH_RC4_128_SHA</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_NULL_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDHE_RSA_WITH_RC4_128_SHA</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_NULL_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_ECDSA_WITH_RC4_128_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_NULL_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_RSA_WITH_RC4_128_SHA</td>
+ * <td>11+</td>
+ * <td>11-19</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_AES_128_CBC_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_AES_256_CBC_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_NULL_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_ECDH_anon_WITH_RC4_128_SHA</td>
+ * <td>11+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_EMPTY_RENEGOTIATION_INFO_SCSV</td>
+ * <td>11+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_FALLBACK_SCSV</td>
+ * <td>21+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>21+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_AES_128_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_AES_256_CBC_SHA</td>
+ * <td>21+</td>
+ * <td>21+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_PSK_WITH_RC4_128_SHA</td>
+ * <td>21+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>9+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_128_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_128_GCM_SHA256</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>9+</td>
+ * <td>11+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_256_CBC_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_AES_256_GCM_SHA384</td>
+ * <td>20+</td>
+ * <td>20+</td>
+ * </tr>
+ * <tr>
+ * <td>TLS_RSA_WITH_NULL_SHA256</td>
+ * <td>20+</td>
+ * <td></td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <p><em>NOTE</em>: PSK cipher suites are enabled by default only if the {@code SSLContext} through
+ * which the socket was created has been initialized with a {@code PSKKeyManager}.
+ *
+ * <p>API Levels 1 to 8 use OpenSSL names for cipher suites. The table below
+ * lists these OpenSSL names and their corresponding standard names used in API
+ * Levels 9 and newer.
+ * <table>
+ * <thead>
+ * <tr>
+ * <th>OpenSSL cipher suite</th>
+ * <th>Standard cipher suite</th>
+ * <th>Supported (API Levels)</th>
+ * <th>Enabled by default (API Levels)</th>
+ * </tr>
+ * </thead>
+ *
+ * <tbody>
+ * <tr>
+ * <td>AES128-SHA</td>
+ * <td>TLS_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>AES256-SHA</td>
+ * <td>TLS_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-8, 11+</td>
+ * </tr>
+ * <tr>
+ * <td>DES-CBC-MD5</td>
+ * <td>SSL_CK_DES_64_CBC_WITH_MD5</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>DES-CBC-SHA</td>
+ * <td>SSL_RSA_WITH_DES_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>DES-CBC3-MD5</td>
+ * <td>SSL_CK_DES_192_EDE3_CBC_WITH_MD5</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>DES-CBC3-SHA</td>
+ * <td>SSL_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>DHE-DSS-AES128-SHA</td>
+ * <td>TLS_DHE_DSS_WITH_AES_128_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>DHE-DSS-AES256-SHA</td>
+ * <td>TLS_DHE_DSS_WITH_AES_256_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-8, 11+</td>
+ * </tr>
+ * <tr>
+ * <td>DHE-RSA-AES128-SHA</td>
+ * <td>TLS_DHE_RSA_WITH_AES_128_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * <tr>
+ * <td>DHE-RSA-AES256-SHA</td>
+ * <td>TLS_DHE_RSA_WITH_AES_256_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-8, 11+</td>
+ * </tr>
+ * <tr>
+ * <td>EDH-DSS-DES-CBC-SHA</td>
+ * <td>SSL_DHE_DSS_WITH_DES_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EDH-DSS-DES-CBC3-SHA</td>
+ * <td>SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EDH-RSA-DES-CBC-SHA</td>
+ * <td>SSL_DHE_RSA_WITH_DES_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EDH-RSA-DES-CBC3-SHA</td>
+ * <td>SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EXP-DES-CBC-SHA</td>
+ * <td>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EXP-EDH-DSS-DES-CBC-SHA</td>
+ * <td>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EXP-EDH-RSA-DES-CBC-SHA</td>
+ * <td>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>EXP-RC2-CBC-MD5</td>
+ * <td>SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>EXP-RC4-MD5</td>
+ * <td>SSL_RSA_EXPORT_WITH_RC4_40_MD5</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>RC2-CBC-MD5</td>
+ * <td>SSL_CK_RC2_128_CBC_WITH_MD5</td>
+ * <td>1-8</td>
+ * <td>1-8</td>
+ * </tr>
+ * <tr>
+ * <td>RC4-MD5</td>
+ * <td>SSL_RSA_WITH_RC4_128_MD5</td>
+ * <td>1+</td>
+ * <td>1-19</td>
+ * </tr>
+ * <tr>
+ * <td>RC4-SHA</td>
+ * <td>SSL_RSA_WITH_RC4_128_SHA</td>
+ * <td>1+</td>
+ * <td>1+</td>
+ * </tr>
+ * </tbody>
+ * </table>
*/
public abstract class SSLSocket extends Socket {
@@ -188,13 +897,11 @@ public abstract class SSLSocket extends Socket {
public abstract SSLSession getSession();
/**
- * Registers the specified listener to receive notification on completion of a
- * handshake on this connection.
+ * Registers the specified listener to receive notification on completion of
+ * a handshake on this connection.
*
- * @param listener
- * the listener to register.
- * @throws IllegalArgumentException
- * if {@code listener} is {@code null}.
+ * @param listener the listener to register.
+ * @throws IllegalArgumentException if {@code listener} is {@code null}.
*/
public abstract void addHandshakeCompletedListener(HandshakeCompletedListener listener);
diff --git a/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java b/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java
index b07d0fd..b506fa6 100644
--- a/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java
+++ b/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java
@@ -22,6 +22,7 @@ import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.net.SocketFactory;
+import org.apache.harmony.security.fortress.Services;
/**
* The abstract factory implementation to create {@code SSLSocket}s.
@@ -32,7 +33,7 @@ public abstract class SSLSocketFactory extends SocketFactory {
// The default SSL socket factory
private static SocketFactory defaultSocketFactory;
- private static String defaultName;
+ private static int lastCacheVersion = -1;
/**
* Returns the default {@code SSLSocketFactory} instance. The default is
@@ -41,23 +42,39 @@ public abstract class SSLSocketFactory extends SocketFactory {
* @return the default ssl socket factory instance.
*/
public static synchronized SocketFactory getDefault() {
- if (defaultSocketFactory != null) {
+ int newCacheVersion = Services.getCacheVersion();
+ if (defaultSocketFactory != null && lastCacheVersion == newCacheVersion) {
return defaultSocketFactory;
}
- if (defaultName == null) {
- defaultName = Security.getProperty("ssl.SocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> sfc = Class.forName(defaultName, true, cl);
- defaultSocketFactory = (SocketFactory) sfc.newInstance();
- } catch (Exception e) {
- System.logE("Problem creating " + defaultName, e);
+ lastCacheVersion = newCacheVersion;
+
+ String newName = Security.getProperty("ssl.SocketFactory.provider");
+ if (newName != null) {
+ /* The cache could have been invalidated, but the provider name didn't change. This
+ * will be the most common state, so check for it early without resetting the default
+ * SocketFactory.
+ */
+ if (defaultSocketFactory != null) {
+ if (newName.equals(defaultSocketFactory.getClass().getName())) {
+ return defaultSocketFactory;
+ } else {
+ defaultSocketFactory = null;
}
}
+
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if (cl == null) {
+ cl = ClassLoader.getSystemClassLoader();
+ }
+ try {
+ final Class<?> sfc = Class.forName(newName, true, cl);
+ defaultSocketFactory = (SocketFactory) sfc.newInstance();
+ } catch (Exception e) {
+ System.logW("Could not create " + newName + " with ClassLoader "
+ + cl.toString() + ": " + e.getMessage());
+ }
+ } else {
+ defaultSocketFactory = null;
}
if (defaultSocketFactory == null) {
@@ -71,10 +88,12 @@ public abstract class SSLSocketFactory extends SocketFactory {
defaultSocketFactory = context.getSocketFactory();
}
}
+
if (defaultSocketFactory == null) {
// Use internal implementation
defaultSocketFactory = new DefaultSSLSocketFactory("No SSLSocketFactory installed");
}
+
return defaultSocketFactory;
}
diff --git a/luni/src/main/java/javax/security/cert/Certificate.java b/luni/src/main/java/javax/security/cert/Certificate.java
index b3e31f6..08ce36b 100644
--- a/luni/src/main/java/javax/security/cert/Certificate.java
+++ b/luni/src/main/java/javax/security/cert/Certificate.java
@@ -126,15 +126,15 @@ public abstract class Certificate {
* public key for which verification should be performed.
* @param sigProvider
* the name of the signature provider.
- * @exception CertificateException
+ * @throws CertificateException
* if encoding errors are detected
- * @exception NoSuchAlgorithmException
+ * @throws NoSuchAlgorithmException
* if an unsupported algorithm is detected
- * @exception InvalidKeyException
+ * @throws InvalidKeyException
* if an invalid key is detected
- * @exception NoSuchProviderException
+ * @throws NoSuchProviderException
* if the specified provider does not exists.
- * @exception SignatureException
+ * @throws SignatureException
* if signature errors are detected
*/
public abstract void verify(PublicKey key, String sigProvider)
@@ -157,4 +157,3 @@ public abstract class Certificate {
*/
public abstract PublicKey getPublicKey();
}
-
diff --git a/luni/src/main/java/javax/xml/transform/overview.html b/luni/src/main/java/javax/xml/transform/overview.html
index 918db9b..fe3372b 100644
--- a/luni/src/main/java/javax/xml/transform/overview.html
+++ b/luni/src/main/java/javax/xml/transform/overview.html
@@ -177,7 +177,7 @@
<H3>TRaX Patterns</H3>
<ul>
<p>
-<b><a name="pattern-Processor">Processor</a></b>
+<b><a name="pattern-Processor"></a>Processor</b>
<br>
<br>
<i>Intent: </i>Generic concept for the
@@ -191,7 +191,7 @@
operations. Different Processors can be used concurrently by different
threads.</p>
<p>
-<b><a name="pattern-TransformerFactory">TransformerFactory</a></b>
+<b><a name="pattern-TransformerFactory"></a>TransformerFactory</b>
<br>
<br>
<i>Intent: </i>Serve as a vendor-neutral Processor interface for
@@ -205,7 +205,7 @@
TransformerFactory may not perform multiple concurrent
operations.</p>
<p>
-<b><a name="pattern-Templates">Templates</a></b>
+<b><a name="pattern-Templates"></a>Templates</b>
<br>
<br>
<i>Intent: </i>The
@@ -215,7 +215,7 @@
<i>Thread safety: </i>Thread-safe for concurrent
usage over multiple threads once construction is complete.</p>
<p>
-<b><a name="pattern-Transformer">Transformer</a></b>
+<b><a name="pattern-Transformer"></a>Transformer</b>
<br>
<br>
<i>Intent: </i>Act as a per-thread
@@ -228,7 +228,7 @@
<i>Notes: </i>The Transformer is bound to the Templates
object that created it.</p>
<p>
-<b><a name="pattern-Source">Source</a></b>
+<b><a name="pattern-Source"></a>Source</b>
<br>
<br>
<i>Intent: </i>Serve as a
@@ -239,7 +239,7 @@
threads for read-only operations; must be synchronized for edit
operations.</p>
<p>
-<b><a name="pattern-Result">Result</a></b>
+<b><a name="pattern-Result"></a>Result</b>
<br>
<br>
<i>Potential alternate name: </i>ResultTarget<br>
diff --git a/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java b/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
index 5779d17..d9f105d 100644
--- a/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
+++ b/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
@@ -37,15 +37,6 @@ import java.text.CharacterIterator;
* @stable ICU 2.4
*/
public final class CollationElementIteratorICU {
- // public data member -------------------------------------------
-
- /**
- * @stable ICU 2.4
- */
- public static final int NULLORDER = 0xFFFFFFFF;
-
- // public methods -----------------------------------------------
-
/**
* Reset the collation elements to their initial state.
* This will move the 'cursor' to the beginning of the text.
diff --git a/luni/src/main/java/libcore/icu/DateIntervalFormat.java b/luni/src/main/java/libcore/icu/DateIntervalFormat.java
index ab9085f..3855654 100644
--- a/luni/src/main/java/libcore/icu/DateIntervalFormat.java
+++ b/luni/src/main/java/libcore/icu/DateIntervalFormat.java
@@ -92,7 +92,7 @@ public final class DateIntervalFormat {
// This is not the behavior of icu4c's DateIntervalFormat, but it's the historical behavior
// of Android's DateUtils.formatDateRange.
if (startMs != endMs && endsAtMidnight &&
- ((flags & FORMAT_SHOW_TIME) == 0 || julianDay(startCalendar) == julianDay(endCalendar))) {
+ ((flags & FORMAT_SHOW_TIME) == 0 || dayDistance(startCalendar, endCalendar) <= 1)) {
endCalendar.roll(Calendar.DAY_OF_MONTH, false);
endMs -= DAY_IN_MS;
}
@@ -224,8 +224,12 @@ public final class DateIntervalFormat {
return c.get(Calendar.YEAR) == now.get(Calendar.YEAR);
}
+ private static int dayDistance(Calendar c1, Calendar c2) {
+ return julianDay(c2) - julianDay(c1);
+ }
+
private static int julianDay(Calendar c) {
- long utcMs = c.get(Calendar.MILLISECOND) + c.get(Calendar.ZONE_OFFSET);
+ long utcMs = c.getTimeInMillis() + c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);
return (int) (utcMs / DAY_IN_MS) + EPOCH_JULIAN_DAY;
}
diff --git a/luni/src/main/java/libcore/icu/ICU.java b/luni/src/main/java/libcore/icu/ICU.java
index 76d9c54..0ef3f93 100644
--- a/luni/src/main/java/libcore/icu/ICU.java
+++ b/luni/src/main/java/libcore/icu/ICU.java
@@ -16,8 +16,13 @@
package libcore.icu;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
import libcore.util.BasicLruCache;
/**
@@ -53,30 +58,173 @@ public final class ICU {
return isoCountries.clone();
}
+ private static final int IDX_LANGUAGE = 0;
+ private static final int IDX_SCRIPT = 1;
+ private static final int IDX_REGION = 2;
+ private static final int IDX_VARIANT = 3;
+
+ /*
+ * Parse the {Language, Script, Region, Variant*} section of the ICU locale
+ * ID. This is the bit that appears before the keyword separate "@". The general
+ * structure is a series of ASCII alphanumeric strings (subtags)
+ * separated by underscores.
+ *
+ * Each subtag is interpreted according to its position in the list of subtags
+ * AND its length (groan...). The various cases are explained in comments
+ * below.
+ */
+ private static void parseLangScriptRegionAndVariants(String string,
+ String[] outputArray) {
+ final int first = string.indexOf('_');
+ final int second = string.indexOf('_', first + 1);
+ final int third = string.indexOf('_', second + 1);
+
+ if (first == -1) {
+ outputArray[IDX_LANGUAGE] = string;
+ } else if (second == -1) {
+ // Language and country ("ja_JP") OR
+ // Language and script ("en_Latn") OR
+ // Language and variant ("en_POSIX").
+
+ outputArray[IDX_LANGUAGE] = string.substring(0, first);
+ final String secondString = string.substring(first + 1);
+
+ if (secondString.length() == 4) {
+ // 4 Letter ISO script code.
+ outputArray[IDX_SCRIPT] = secondString;
+ } else if (secondString.length() == 2 || secondString.length() == 3) {
+ // 2 or 3 Letter region code.
+ outputArray[IDX_REGION] = secondString;
+ } else {
+ // If we're here, the length of the second half is either 1 or greater
+ // than 5. Assume that ICU won't hand us malformed tags, and therefore
+ // assume the rest of the string is a series of variant tags.
+ outputArray[IDX_VARIANT] = secondString;
+ }
+ } else if (third == -1) {
+ // Language and country and variant ("ja_JP_TRADITIONAL") OR
+ // Language and script and variant ("en_Latn_POSIX") OR
+ // Language and script and region ("en_Latn_US"). OR
+ // Language and variant with multiple subtags ("en_POSIX_XISOP")
+
+ outputArray[IDX_LANGUAGE] = string.substring(0, first);
+ final String secondString = string.substring(first + 1, second);
+ final String thirdString = string.substring(second + 1);
+
+ if (secondString.length() == 4) {
+ // The second subtag is a script.
+ outputArray[IDX_SCRIPT] = secondString;
+
+ // The third subtag can be either a region or a variant, depending
+ // on its length.
+ if (thirdString.length() == 2 || thirdString.length() == 3 ||
+ thirdString.isEmpty()) {
+ outputArray[IDX_REGION] = thirdString;
+ } else {
+ outputArray[IDX_VARIANT] = thirdString;
+ }
+ } else if (secondString.isEmpty() ||
+ secondString.length() == 2 || secondString.length() == 3) {
+ // The second string is a region, and the third a variant.
+ outputArray[IDX_REGION] = secondString;
+ outputArray[IDX_VARIANT] = thirdString;
+ } else {
+ // Variant with multiple subtags.
+ outputArray[IDX_VARIANT] = string.substring(first + 1);
+ }
+ } else {
+ // Language, script, region and variant with 1 or more subtags
+ // ("en_Latn_US_POSIX") OR
+ // Language, region and variant with 2 or more subtags
+ // (en_US_POSIX_VARIANT).
+ outputArray[IDX_LANGUAGE] = string.substring(0, first);
+ final String secondString = string.substring(first + 1, second);
+ if (secondString.length() == 4) {
+ outputArray[IDX_SCRIPT] = secondString;
+ outputArray[IDX_REGION] = string.substring(second + 1, third);
+ outputArray[IDX_VARIANT] = string.substring(third + 1);
+ } else {
+ outputArray[IDX_REGION] = secondString;
+ outputArray[IDX_VARIANT] = string.substring(second + 1);
+ }
+ }
+ }
+
/**
* Returns the appropriate {@code Locale} given a {@code String} of the form returned
* by {@code toString}. This is very lenient, and doesn't care what's between the underscores:
* this method can parse strings that {@code Locale.toString} won't produce.
* Used to remove duplication.
*/
- public static Locale localeFromString(String localeName) {
- int first = localeName.indexOf('_');
- int second = localeName.indexOf('_', first + 1);
- if (first == -1) {
- // Language only ("ja").
- return new Locale(localeName);
- } else if (second == -1) {
- // Language and country ("ja_JP").
- String language = localeName.substring(0, first);
- String country = localeName.substring(first + 1);
- return new Locale(language, country);
+ public static Locale localeFromIcuLocaleId(String localeId) {
+ // @ == ULOC_KEYWORD_SEPARATOR_UNICODE (uloc.h).
+ final int extensionsIndex = localeId.indexOf('@');
+
+ Map<Character, String> extensionsMap = Collections.EMPTY_MAP;
+ Map<String, String> unicodeKeywordsMap = Collections.EMPTY_MAP;
+ Set<String> unicodeAttributeSet = Collections.EMPTY_SET;
+
+ if (extensionsIndex != -1) {
+ extensionsMap = new HashMap<Character, String>();
+ unicodeKeywordsMap = new HashMap<String, String>();
+ unicodeAttributeSet = new HashSet<String>();
+
+ // ICU sends us a semi-colon (ULOC_KEYWORD_ITEM_SEPARATOR) delimited string
+ // containing all "keywords" it could parse. An ICU keyword is a key-value pair
+ // separated by an "=" (ULOC_KEYWORD_ASSIGN).
+ //
+ // Each keyword item can be one of three things :
+ // - A unicode extension attribute list: In this case the item key is "attribute"
+ // and the value is a hyphen separated list of unicode attributes.
+ // - A unicode extension keyword: In this case, the item key will be larger than
+ // 1 char in length, and the value will be the unicode extension value.
+ // - A BCP-47 extension subtag: In this case, the item key will be exactly one
+ // char in length, and the value will be a sequence of unparsed subtags that
+ // represent the extension.
+ //
+ // Note that this implies that unicode extension keywords are "promoted" to
+ // to the same namespace as the top level extension subtags and their values.
+ // There can't be any collisions in practice because the BCP-47 spec imposes
+ // restrictions on their lengths.
+ final String extensionsString = localeId.substring(extensionsIndex + 1);
+ final String[] extensions = extensionsString.split(";");
+ for (String extension : extensions) {
+ // This is the special key for the unicode attributes
+ if (extension.startsWith("attribute=")) {
+ String unicodeAttributeValues = extension.substring("attribute=".length());
+ for (String unicodeAttribute : unicodeAttributeValues.split("-")) {
+ unicodeAttributeSet.add(unicodeAttribute);
+ }
+ } else {
+ final int separatorIndex = extension.indexOf('=');
+
+ if (separatorIndex == 1) {
+ // This is a BCP-47 extension subtag.
+ final String value = extension.substring(2);
+ final char extensionId = extension.charAt(0);
+
+ extensionsMap.put(extensionId, value);
+ } else {
+ // This is a unicode extension keyword.
+ unicodeKeywordsMap.put(extension.substring(0, separatorIndex),
+ extension.substring(separatorIndex + 1));
+ }
+ }
+ }
+ }
+
+ final String[] outputArray = new String[] { "", "", "", "" };
+ if (extensionsIndex == -1) {
+ parseLangScriptRegionAndVariants(localeId, outputArray);
} else {
- // Language and country and variant ("ja_JP_TRADITIONAL").
- String language = localeName.substring(0, first);
- String country = localeName.substring(first + 1, second);
- String variant = localeName.substring(second + 1);
- return new Locale(language, country, variant);
+ parseLangScriptRegionAndVariants(localeId.substring(0, extensionsIndex),
+ outputArray);
}
+
+ return new Locale(outputArray[IDX_LANGUAGE], outputArray[IDX_REGION],
+ outputArray[IDX_VARIANT], outputArray[IDX_SCRIPT],
+ unicodeAttributeSet, unicodeKeywordsMap, extensionsMap,
+ true /* has validated fields */);
}
public static Locale[] localesFromStrings(String[] localeNames) {
@@ -85,7 +233,7 @@ public final class ICU {
// both so that we never need to convert back when talking to it.
LinkedHashSet<Locale> set = new LinkedHashSet<Locale>();
for (String localeName : localeNames) {
- set.add(localeFromString(localeName));
+ set.add(localeFromIcuLocaleId(localeName));
}
return set.toArray(new Locale[set.size()]);
}
@@ -125,19 +273,20 @@ public final class ICU {
return localesFromStrings(getAvailableNumberFormatLocalesNative());
}
- public static String getBestDateTimePattern(String skeleton, String localeName) {
- String key = skeleton + "\t" + localeName;
+ public static String getBestDateTimePattern(String skeleton, Locale locale) {
+ String languageTag = locale.toLanguageTag();
+ String key = skeleton + "\t" + languageTag;
synchronized (CACHED_PATTERNS) {
String pattern = CACHED_PATTERNS.get(key);
if (pattern == null) {
- pattern = getBestDateTimePatternNative(skeleton, localeName);
+ pattern = getBestDateTimePatternNative(skeleton, languageTag);
CACHED_PATTERNS.put(key, pattern);
}
return pattern;
}
}
- private static native String getBestDateTimePatternNative(String skeleton, String localeName);
+ private static native String getBestDateTimePatternNative(String skeleton, String languageTag);
public static char[] getDateFormatOrder(String pattern) {
char[] result = new char[3];
@@ -197,8 +346,17 @@ public final class ICU {
// --- Case mapping.
- public static native String toLowerCase(String s, String localeName);
- public static native String toUpperCase(String s, String localeName);
+ public static String toLowerCase(String s, Locale locale) {
+ return toLowerCase(s, locale.toLanguageTag());
+ }
+
+ private static native String toLowerCase(String s, String languageTag);
+
+ public static String toUpperCase(String s, Locale locale) {
+ return toUpperCase(s, locale.toLanguageTag());
+ }
+
+ private static native String toUpperCase(String s, String languageTag);
// --- Errors.
@@ -224,22 +382,79 @@ public final class ICU {
public static native String[] getAvailableCurrencyCodes();
public static native String getCurrencyCode(String countryCode);
- public static native String getCurrencyDisplayName(String locale, String currencyCode);
+
+ public static String getCurrencyDisplayName(Locale locale, String currencyCode) {
+ return getCurrencyDisplayName(locale.toLanguageTag(), currencyCode);
+ }
+
+ private static native String getCurrencyDisplayName(String languageTag, String currencyCode);
+
public static native int getCurrencyFractionDigits(String currencyCode);
- public static native String getCurrencySymbol(String locale, String currencyCode);
+ public static native int getCurrencyNumericCode(String currencyCode);
+
+ public static String getCurrencySymbol(Locale locale, String currencyCode) {
+ return getCurrencySymbol(locale.toLanguageTag(), currencyCode);
+ }
+
+ private static native String getCurrencySymbol(String languageTag, String currencyCode);
+
+ public static String getDisplayCountry(Locale targetLocale, Locale locale) {
+ return getDisplayCountryNative(targetLocale.toLanguageTag(), locale.toLanguageTag());
+ }
- public static native String getDisplayCountryNative(String countryCode, String locale);
- public static native String getDisplayLanguageNative(String languageCode, String locale);
- public static native String getDisplayVariantNative(String variantCode, String locale);
+ private static native String getDisplayCountryNative(String targetLanguageTag, String languageTag);
+
+ public static String getDisplayLanguage(Locale targetLocale, Locale locale) {
+ return getDisplayLanguageNative(targetLocale.toLanguageTag(), locale.toLanguageTag());
+ }
+
+ private static native String getDisplayLanguageNative(String targetLanguageTag, String languageTag);
+
+ public static String getDisplayVariant(Locale targetLocale, Locale locale) {
+ return getDisplayVariantNative(targetLocale.toLanguageTag(), locale.toLanguageTag());
+ }
+
+ private static native String getDisplayVariantNative(String targetLanguageTag, String languageTag);
+
+ public static String getDisplayScript(Locale targetLocale, Locale locale) {
+ return getDisplayScriptNative(targetLocale.toLanguageTag(), locale.toLanguageTag());
+ }
- public static native String getISO3CountryNative(String locale);
- public static native String getISO3LanguageNative(String locale);
+ private static native String getDisplayScriptNative(String targetLanguageTag, String languageTag);
+ public static native String getISO3Country(String languageTag);
+
+ public static native String getISO3Language(String languageTag);
+
+ public static Locale addLikelySubtags(Locale locale) {
+ return Locale.forLanguageTag(addLikelySubtags(locale.toLanguageTag()).replace('_', '-'));
+ }
+
+ /**
+ * @deprecated use {@link #addLikelySubtags(java.util.Locale)} instead.
+ */
+ @Deprecated
public static native String addLikelySubtags(String locale);
+
+ /**
+ * @deprecated use {@link java.util.Locale#getScript()} instead. This has been kept
+ * around only for the support library.
+ */
+ @Deprecated
public static native String getScript(String locale);
private static native String[] getISOLanguagesNative();
private static native String[] getISOCountriesNative();
- static native boolean initLocaleDataNative(String locale, LocaleData result);
+ static native boolean initLocaleDataNative(String languageTag, LocaleData result);
+
+ /**
+ * Takes a BCP-47 language tag (Locale.toLanguageTag()). e.g. en-US, not en_US
+ */
+ public static native void setDefaultLocale(String languageTag);
+
+ /**
+ * Returns a locale name, not a BCP-47 language tag. e.g. en_US not en-US.
+ */
+ public static native String getDefaultLocale();
}
diff --git a/luni/src/main/java/libcore/icu/LocaleData.java b/luni/src/main/java/libcore/icu/LocaleData.java
index f00c30f..9e07244 100644
--- a/luni/src/main/java/libcore/icu/LocaleData.java
+++ b/luni/src/main/java/libcore/icu/LocaleData.java
@@ -79,6 +79,10 @@ public final class LocaleData {
public String mediumDateFormat;
public String shortDateFormat;
+ // Used by TimePicker. Not currently used by UTS#35.
+ public String narrowAm; // "a".
+ public String narrowPm; // "p".
+
// shortDateFormat, but guaranteed to have 4-digit years.
// Used by android.text.format.DateFormat.getDateFormatStringForSetting.
public String shortDateFormat4;
@@ -95,7 +99,7 @@ public final class LocaleData {
public char percent;
public char perMill;
public char monetarySeparator;
- public char minusSign;
+ public String minusSign;
public String exponentSeparator;
public String infinity;
public String NaN;
@@ -112,27 +116,40 @@ public final class LocaleData {
private LocaleData() {
}
+ public static Locale mapInvalidAndNullLocales(Locale locale) {
+ if (locale == null) {
+ return Locale.getDefault();
+ }
+
+ if ("und".equals(locale.toLanguageTag())) {
+ return Locale.ROOT;
+ }
+
+ return locale;
+ }
+
/**
* Returns a shared LocaleData for the given locale.
*/
public static LocaleData get(Locale locale) {
if (locale == null) {
- locale = Locale.getDefault();
+ throw new NullPointerException("locale == null");
}
- String localeName = locale.toString();
+
+ final String languageTag = locale.toLanguageTag();
synchronized (localeDataCache) {
- LocaleData localeData = localeDataCache.get(localeName);
+ LocaleData localeData = localeDataCache.get(languageTag);
if (localeData != null) {
return localeData;
}
}
LocaleData newLocaleData = initLocaleData(locale);
synchronized (localeDataCache) {
- LocaleData localeData = localeDataCache.get(localeName);
+ LocaleData localeData = localeDataCache.get(languageTag);
if (localeData != null) {
return localeData;
}
- localeDataCache.put(localeName, newLocaleData);
+ localeDataCache.put(languageTag, newLocaleData);
return newLocaleData;
}
}
@@ -171,13 +188,13 @@ public final class LocaleData {
private static LocaleData initLocaleData(Locale locale) {
LocaleData localeData = new LocaleData();
- if (!ICU.initLocaleDataNative(locale.toString(), localeData)) {
+ if (!ICU.initLocaleDataNative(locale.toLanguageTag(), localeData)) {
throw new AssertionError("couldn't initialize LocaleData for locale " + locale);
}
// Get the "h:mm a" and "HH:mm" 12- and 24-hour time format strings.
- localeData.timeFormat12 = ICU.getBestDateTimePattern("hm", locale.toString());
- localeData.timeFormat24 = ICU.getBestDateTimePattern("Hm", locale.toString());
+ localeData.timeFormat12 = ICU.getBestDateTimePattern("hm", locale);
+ localeData.timeFormat24 = ICU.getBestDateTimePattern("Hm", locale);
// Fix up a couple of patterns.
if (localeData.fullTimeFormat != null) {
diff --git a/luni/src/main/java/libcore/icu/NativeBreakIterator.java b/luni/src/main/java/libcore/icu/NativeBreakIterator.java
index 7168d96..992aac2 100644
--- a/luni/src/main/java/libcore/icu/NativeBreakIterator.java
+++ b/luni/src/main/java/libcore/icu/NativeBreakIterator.java
@@ -138,23 +138,23 @@ public final class NativeBreakIterator implements Cloneable {
}
public int preceding(int offset) {
- return precedingImpl(this.address, this.string, offset);
+ return precedingImpl(this.address, this.string, offset);
}
- public static NativeBreakIterator getCharacterInstance(Locale where) {
- return new NativeBreakIterator(getCharacterInstanceImpl(where.toString()), BI_CHAR_INSTANCE);
+ public static NativeBreakIterator getCharacterInstance(Locale locale) {
+ return new NativeBreakIterator(getCharacterInstanceImpl(locale.toLanguageTag()), BI_CHAR_INSTANCE);
}
- public static NativeBreakIterator getLineInstance(Locale where) {
- return new NativeBreakIterator(getLineInstanceImpl(where.toString()), BI_LINE_INSTANCE);
+ public static NativeBreakIterator getLineInstance(Locale locale) {
+ return new NativeBreakIterator(getLineInstanceImpl(locale.toLanguageTag()), BI_LINE_INSTANCE);
}
- public static NativeBreakIterator getSentenceInstance(Locale where) {
- return new NativeBreakIterator(getSentenceInstanceImpl(where.toString()), BI_SENT_INSTANCE);
+ public static NativeBreakIterator getSentenceInstance(Locale locale) {
+ return new NativeBreakIterator(getSentenceInstanceImpl(locale.toLanguageTag()), BI_SENT_INSTANCE);
}
- public static NativeBreakIterator getWordInstance(Locale where) {
- return new NativeBreakIterator(getWordInstanceImpl(where.toString()), BI_WORD_INSTANCE);
+ public static NativeBreakIterator getWordInstance(Locale locale) {
+ return new NativeBreakIterator(getWordInstanceImpl(locale.toLanguageTag()), BI_WORD_INSTANCE);
}
private static native long getCharacterInstanceImpl(String locale);
diff --git a/luni/src/main/java/libcore/icu/NativeCollation.java b/luni/src/main/java/libcore/icu/NativeCollation.java
index 0373fef..b4b4f46 100644
--- a/luni/src/main/java/libcore/icu/NativeCollation.java
+++ b/luni/src/main/java/libcore/icu/NativeCollation.java
@@ -10,6 +10,8 @@
package libcore.icu;
+import java.util.Locale;
+
/**
* Package static class for declaring all native methods for collation use.
* @author syn wee quek
@@ -23,10 +25,13 @@ public final class NativeCollation {
public static native void closeCollator(long address);
public static native int compare(long address, String source, String target);
public static native int getAttribute(long address, int type);
- public static native int getCollationElementIterator(long address, String source);
+ public static native long getCollationElementIterator(long address, String source);
public static native String getRules(long address);
public static native byte[] getSortKey(long address, String source);
- public static native long openCollator(String locale);
+ public static long openCollator(Locale locale) {
+ return openCollator(locale.toLanguageTag());
+ }
+ private static native long openCollator(String languageTag);
public static native long openCollatorFromRules(String rules, int normalizationMode, int collationStrength);
public static native long safeClone(long address);
public static native void setAttribute(long address, int type, int value);
diff --git a/luni/src/main/java/libcore/icu/NativeDecimalFormat.java b/luni/src/main/java/libcore/icu/NativeDecimalFormat.java
index 0e9ffc4..fd179c1 100644
--- a/luni/src/main/java/libcore/icu/NativeDecimalFormat.java
+++ b/luni/src/main/java/libcore/icu/NativeDecimalFormat.java
@@ -27,7 +27,6 @@ import java.text.Format;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Currency;
-import java.util.NoSuchElementException;
public final class NativeDecimalFormat implements Cloneable {
/**
@@ -92,6 +91,47 @@ public final class NativeDecimalFormat implements Cloneable {
private static final int UNUM_PUBLIC_RULESETS = 7;
/**
+ * A table for translating between NumberFormat.Field instances
+ * and icu4c UNUM_x_FIELD constants.
+ */
+ private static final Format.Field[] ICU4C_FIELD_IDS = {
+ // The old java field values were 0 for integer and 1 for fraction.
+ // The new java field attributes are all objects. ICU assigns the values
+ // starting from 0 in the following order; note that integer and
+ // fraction positions match the old field values.
+ NumberFormat.Field.INTEGER, // 0 UNUM_INTEGER_FIELD
+ NumberFormat.Field.FRACTION, // 1 UNUM_FRACTION_FIELD
+ NumberFormat.Field.DECIMAL_SEPARATOR, // 2 UNUM_DECIMAL_SEPARATOR_FIELD
+ NumberFormat.Field.EXPONENT_SYMBOL, // 3 UNUM_EXPONENT_SYMBOL_FIELD
+ NumberFormat.Field.EXPONENT_SIGN, // 4 UNUM_EXPONENT_SIGN_FIELD
+ NumberFormat.Field.EXPONENT, // 5 UNUM_EXPONENT_FIELD
+ NumberFormat.Field.GROUPING_SEPARATOR, // 6 UNUM_GROUPING_SEPARATOR_FIELD
+ NumberFormat.Field.CURRENCY, // 7 UNUM_CURRENCY_FIELD
+ NumberFormat.Field.PERCENT, // 8 UNUM_PERCENT_FIELD
+ NumberFormat.Field.PERMILLE, // 9 UNUM_PERMILL_FIELD
+ NumberFormat.Field.SIGN, // 10 UNUM_SIGN_FIELD
+ };
+
+ private static int translateFieldId(FieldPosition fp) {
+ int id = fp.getField();
+ if (id < -1 || id > 1) {
+ id = -1;
+ }
+ if (id == -1) {
+ Format.Field attr = fp.getFieldAttribute();
+ if (attr != null) {
+ for (int i = 0; i < ICU4C_FIELD_IDS.length; ++i) {
+ if (ICU4C_FIELD_IDS[i].equals(attr)) {
+ id = i;
+ break;
+ }
+ }
+ }
+ }
+ return id;
+ }
+
+ /**
* The address of the ICU DecimalFormat* on the native heap.
*/
private long address;
@@ -111,19 +151,12 @@ public final class NativeDecimalFormat implements Cloneable {
private transient boolean parseBigDecimal;
- /**
- * Cache the BigDecimal form of the multiplier. This is null until we've
- * formatted a BigDecimal (with a multiplier that is not 1), or the user has
- * explicitly called {@link #setMultiplier(int)} with any multiplier.
- */
- private BigDecimal multiplierBigDecimal = null;
-
public NativeDecimalFormat(String pattern, DecimalFormatSymbols dfs) {
try {
this.address = open(pattern, dfs.getCurrencySymbol(),
dfs.getDecimalSeparator(), dfs.getDigit(), dfs.getExponentSeparator(),
dfs.getGroupingSeparator(), dfs.getInfinity(),
- dfs.getInternationalCurrencySymbol(), dfs.getMinusSign(),
+ dfs.getInternationalCurrencySymbol(), dfs.getMinusSignString(),
dfs.getMonetaryDecimalSeparator(), dfs.getNaN(), dfs.getPatternSeparator(),
dfs.getPercent(), dfs.getPerMill(), dfs.getZeroDigit());
this.lastPattern = pattern;
@@ -211,13 +244,30 @@ public final class NativeDecimalFormat implements Cloneable {
obj.isGroupingUsed() == this.isGroupingUsed();
}
+ public String toString() {
+ return getClass().getName() + "[\"" + toPattern() + "\"" +
+ ",isDecimalSeparatorAlwaysShown=" + isDecimalSeparatorAlwaysShown() +
+ ",groupingSize=" + getGroupingSize() +
+ ",multiplier=" + getMultiplier() +
+ ",negativePrefix=" + getNegativePrefix() +
+ ",negativeSuffix=" + getNegativeSuffix() +
+ ",positivePrefix=" + getPositivePrefix() +
+ ",positiveSuffix=" + getPositiveSuffix() +
+ ",maxIntegerDigits=" + getMaximumIntegerDigits() +
+ ",maxFractionDigits=" + getMaximumFractionDigits() +
+ ",minIntegerDigits=" + getMinimumIntegerDigits() +
+ ",minFractionDigits=" + getMinimumFractionDigits() +
+ ",grouping=" + isGroupingUsed() +
+ "]";
+ }
+
/**
* Copies the DecimalFormatSymbols settings into our native peer in bulk.
*/
public void setDecimalFormatSymbols(final DecimalFormatSymbols dfs) {
setDecimalFormatSymbols(this.address, dfs.getCurrencySymbol(), dfs.getDecimalSeparator(),
dfs.getDigit(), dfs.getExponentSeparator(), dfs.getGroupingSeparator(),
- dfs.getInfinity(), dfs.getInternationalCurrencySymbol(), dfs.getMinusSign(),
+ dfs.getInfinity(), dfs.getInternationalCurrencySymbol(), dfs.getMinusSignString(),
dfs.getMonetaryDecimalSeparator(), dfs.getNaN(), dfs.getPatternSeparator(),
dfs.getPercent(), dfs.getPerMill(), dfs.getZeroDigit());
}
@@ -233,8 +283,8 @@ public final class NativeDecimalFormat implements Cloneable {
public char[] formatBigDecimal(BigDecimal value, FieldPosition field) {
FieldPositionIterator fpi = FieldPositionIterator.forFieldPosition(field);
char[] result = formatDigitList(this.address, value.toString(), fpi);
- if (fpi != null) {
- FieldPositionIterator.setFieldPosition(fpi, field);
+ if (fpi != null && field != null) {
+ updateFieldPosition(field, fpi);
}
return result;
}
@@ -242,8 +292,8 @@ public final class NativeDecimalFormat implements Cloneable {
public char[] formatBigInteger(BigInteger value, FieldPosition field) {
FieldPositionIterator fpi = FieldPositionIterator.forFieldPosition(field);
char[] result = formatDigitList(this.address, value.toString(10), fpi);
- if (fpi != null) {
- FieldPositionIterator.setFieldPosition(fpi, field);
+ if (fpi != null && field != null) {
+ updateFieldPosition(field, fpi);
}
return result;
}
@@ -251,8 +301,8 @@ public final class NativeDecimalFormat implements Cloneable {
public char[] formatLong(long value, FieldPosition field) {
FieldPositionIterator fpi = FieldPositionIterator.forFieldPosition(field);
char[] result = formatLong(this.address, value, fpi);
- if (fpi != null) {
- FieldPositionIterator.setFieldPosition(fpi, field);
+ if (fpi != null && field != null) {
+ updateFieldPosition(field, fpi);
}
return result;
}
@@ -260,12 +310,25 @@ public final class NativeDecimalFormat implements Cloneable {
public char[] formatDouble(double value, FieldPosition field) {
FieldPositionIterator fpi = FieldPositionIterator.forFieldPosition(field);
char[] result = formatDouble(this.address, value, fpi);
- if (fpi != null) {
- FieldPositionIterator.setFieldPosition(fpi, field);
+ if (fpi != null && field != null) {
+ updateFieldPosition(field, fpi);
}
return result;
}
+ private static void updateFieldPosition(FieldPosition fp, FieldPositionIterator fpi) {
+ int field = translateFieldId(fp);
+ if (field != -1) {
+ while (fpi.next()) {
+ if (fpi.fieldId() == field) {
+ fp.setBeginIndex(fpi.start());
+ fp.setEndIndex(fpi.limit());
+ return;
+ }
+ }
+ }
+ }
+
public void applyLocalizedPattern(String pattern) {
applyPattern(this.address, true, pattern);
lastPattern = null;
@@ -352,6 +415,10 @@ public final class NativeDecimalFormat implements Cloneable {
}
public int getGroupingSize() {
+ // Work around http://bugs.icu-project.org/trac/ticket/10864 in icu4c 53.
+ if (!isGroupingUsed()) {
+ return 0;
+ }
return getAttribute(this.address, UNUM_GROUPING_SIZE);
}
@@ -408,9 +475,9 @@ public final class NativeDecimalFormat implements Cloneable {
setAttribute(this.address, UNUM_DECIMAL_ALWAYS_SHOWN, i);
}
- public void setCurrency(Currency currency) {
- setSymbol(this.address, UNUM_CURRENCY_SYMBOL, currency.getSymbol());
- setSymbol(this.address, UNUM_INTL_CURRENCY_SYMBOL, currency.getCurrencyCode());
+ public void setCurrency(String currencySymbol, String currencyCode) {
+ setSymbol(this.address, UNUM_CURRENCY_SYMBOL, currencySymbol);
+ setSymbol(this.address, UNUM_INTL_CURRENCY_SYMBOL, currencyCode);
}
public void setGroupingSize(int value) {
@@ -440,8 +507,6 @@ public final class NativeDecimalFormat implements Cloneable {
public void setMultiplier(int value) {
setAttribute(this.address, UNUM_MULTIPLIER, value);
- // Update the cached BigDecimal for multiplier.
- multiplierBigDecimal = BigDecimal.valueOf(value);
}
public void setNegativePrefix(String value) {
@@ -501,6 +566,7 @@ public final class NativeDecimalFormat implements Cloneable {
case HALF_EVEN: nativeRoundingMode = 4; break;
case HALF_DOWN: nativeRoundingMode = 5; break;
case HALF_UP: nativeRoundingMode = 6; break;
+ case UNNECESSARY: nativeRoundingMode = 7; break;
default: throw new AssertionError();
}
setRoundingMode(address, nativeRoundingMode, roundingIncrement);
@@ -515,104 +581,33 @@ public final class NativeDecimalFormat implements Cloneable {
}
public static FieldPositionIterator forFieldPosition(FieldPosition fp) {
- if (fp != null && fp.getField() != -1) {
- return new FieldPositionIterator();
- }
- return null;
- }
-
- private static int getNativeFieldPositionId(FieldPosition fp) {
- // NOTE: -1, 0, and 1 were the only valid original java field values
- // for NumberFormat. They take precedence. This assumes any other
- // value is a mistake and the actual value is in the attribute.
- // Clients can construct FieldPosition combining any attribute with any field
- // value, which is just wrong, but there you go.
-
- int id = fp.getField();
- if (id < -1 || id > 1) {
- id = -1;
- }
- if (id == -1) {
- Format.Field attr = fp.getFieldAttribute();
- if (attr != null) {
- for (int i = 0; i < fields.length; ++i) {
- if (fields[i].equals(attr)) {
- id = i;
- break;
- }
- }
- }
- }
- return id;
- }
-
- private static void setFieldPosition(FieldPositionIterator fpi, FieldPosition fp) {
- if (fpi != null && fp != null) {
- int field = getNativeFieldPositionId(fp);
- if (field != -1) {
- while (fpi.next()) {
- if (fpi.fieldId() == field) {
- fp.setBeginIndex(fpi.start());
- fp.setEndIndex(fpi.limit());
- break;
- }
- }
- }
- }
+ return (fp != null) ? new FieldPositionIterator() : null;
}
public boolean next() {
- // if pos == data.length, we've already returned false once
- if (data == null || pos == data.length) {
- throw new NoSuchElementException();
+ if (data == null) {
+ return false;
}
pos += 3;
return pos < data.length;
}
- private void checkValid() {
- if (data == null || pos < 0 || pos == data.length) {
- throw new NoSuchElementException();
- }
- }
-
public int fieldId() {
return data[pos];
}
public Format.Field field() {
- checkValid();
- return fields[data[pos]];
+ return ICU4C_FIELD_IDS[data[pos]];
}
public int start() {
- checkValid();
return data[pos + 1];
}
public int limit() {
- checkValid();
return data[pos + 2];
}
- private static Format.Field fields[] = {
- // The old java field values were 0 for integer and 1 for fraction.
- // The new java field attributes are all objects. ICU assigns the values
- // starting from 0 in the following order; note that integer and
- // fraction positions match the old field values.
- NumberFormat.Field.INTEGER,
- NumberFormat.Field.FRACTION,
- NumberFormat.Field.DECIMAL_SEPARATOR,
- NumberFormat.Field.EXPONENT_SYMBOL,
- NumberFormat.Field.EXPONENT_SIGN,
- NumberFormat.Field.EXPONENT,
- NumberFormat.Field.GROUPING_SEPARATOR,
- NumberFormat.Field.CURRENCY,
- NumberFormat.Field.PERCENT,
- NumberFormat.Field.PERMILLE,
- NumberFormat.Field.SIGN,
- };
-
// called by native
private void setData(int[] data) {
this.data = data;
@@ -630,13 +625,13 @@ public final class NativeDecimalFormat implements Cloneable {
private static native String getTextAttribute(long addr, int symbol);
private static native long open(String pattern, String currencySymbol,
char decimalSeparator, char digit, String exponentSeparator, char groupingSeparator,
- String infinity, String internationalCurrencySymbol, char minusSign,
+ String infinity, String internationalCurrencySymbol, String minusSign,
char monetaryDecimalSeparator, String nan, char patternSeparator, char percent,
char perMill, char zeroDigit);
private static native Number parse(long addr, String string, ParsePosition position, boolean parseBigDecimal);
private static native void setDecimalFormatSymbols(long addr, String currencySymbol,
char decimalSeparator, char digit, String exponentSeparator, char groupingSeparator,
- String infinity, String internationalCurrencySymbol, char minusSign,
+ String infinity, String internationalCurrencySymbol, String minusSign,
char monetaryDecimalSeparator, String nan, char patternSeparator, char percent,
char perMill, char zeroDigit);
private static native void setSymbol(long addr, int symbol, String str);
diff --git a/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java b/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java
index 3ea942d..b23013b 100644
--- a/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java
+++ b/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java
@@ -52,7 +52,7 @@ public final class RuleBasedCollatorICU implements Cloneable {
}
public RuleBasedCollatorICU(Locale locale) {
- address = NativeCollation.openCollator(locale.toString());
+ address = NativeCollation.openCollator(locale);
}
private RuleBasedCollatorICU(long address) {
diff --git a/luni/src/main/java/libcore/icu/TimeZoneNames.java b/luni/src/main/java/libcore/icu/TimeZoneNames.java
index 5bb54a1..3413a5d 100644
--- a/luni/src/main/java/libcore/icu/TimeZoneNames.java
+++ b/luni/src/main/java/libcore/icu/TimeZoneNames.java
@@ -53,15 +53,8 @@ public final class TimeZoneNames {
}
public static class ZoneStringsCache extends BasicLruCache<Locale, String[][]> {
- // De-duplicate the strings (http://b/2672057).
- private final HashMap<String, String> internTable = new HashMap<String, String>();
-
public ZoneStringsCache() {
- // We make room for all the time zones known to the system, since each set of strings
- // isn't particularly large (and we remove duplicates), but is currently (Honeycomb)
- // really expensive to compute.
- // If you change this, you might want to change the scope of the intern table too.
- super(availableTimeZoneIds.length);
+ super(5); // Room for a handful of locales.
}
@Override protected String[][] create(Locale locale) {
@@ -85,11 +78,13 @@ public final class TimeZoneNames {
long nativeDuration = nativeEnd - nativeStart;
long duration = end - start;
System.logI("Loaded time zone names for \"" + locale + "\" in " + duration + "ms" +
- " (" + nativeDuration + "ms in ICU)");
+ " (" + nativeDuration + "ms in ICU)");
return result;
}
+ // De-duplicate the strings (http://b/2672057).
private synchronized void internStrings(String[][] result) {
+ HashMap<String, String> internTable = new HashMap<String, String>();
for (int i = 0; i < result.length; ++i) {
for (int j = 1; j < NAME_COUNT; ++j) {
String original = result[i][j];
@@ -162,5 +157,7 @@ public final class TimeZoneNames {
return ids.toArray(new String[ids.size()]);
}
+ public static native String getExemplarLocation(String locale, String tz);
+
private static native void fillZoneStrings(String locale, String[][] result);
}
diff --git a/luni/src/main/java/libcore/io/BlockGuardOs.java b/luni/src/main/java/libcore/io/BlockGuardOs.java
index c61a3cf..b3dc74b 100644
--- a/luni/src/main/java/libcore/io/BlockGuardOs.java
+++ b/luni/src/main/java/libcore/io/BlockGuardOs.java
@@ -16,14 +16,22 @@
package libcore.io;
+import android.system.ErrnoException;
+import android.system.StructLinger;
+import android.system.StructPollfd;
+import android.system.StructStat;
+import android.system.StructStatVfs;
+import android.util.MutableLong;
import dalvik.system.BlockGuard;
import dalvik.system.SocketTagger;
import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
+import static dalvik.system.BlockGuard.DISALLOW_NETWORK;
/**
* Informs BlockGuard of any activity it should be aware of.
@@ -55,9 +63,27 @@ public class BlockGuardOs extends ForwardingOs {
return tagSocket(os.accept(fd, peerAddress));
}
+ @Override public boolean access(String path, int mode) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.access(path, mode);
+ }
+
+ @Override public void chmod(String path, int mode) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.chmod(path, mode);
+ }
+
+ @Override public void chown(String path, int uid, int gid) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.chown(path, uid, gid);
+ }
+
@Override public void close(FileDescriptor fd) throws ErrnoException {
try {
- if (S_ISSOCK(Libcore.os.fstat(fd).st_mode)) {
+ // The usual case is that this _isn't_ a socket, so the getsockopt(2) call in
+ // isLingerSocket will throw, and that's really expensive. Try to avoid asking
+ // if we don't care.
+ if (fd.isSocket()) {
if (isLingerSocket(fd)) {
// If the fd is a socket with SO_LINGER set, we might block indefinitely.
// We allow non-linger sockets so that apps can close their network
@@ -85,6 +111,16 @@ public class BlockGuardOs extends ForwardingOs {
os.connect(fd, address, port);
}
+ @Override public void fchmod(FileDescriptor fd, int mode) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.fchmod(fd, mode);
+ }
+
+ @Override public void fchown(FileDescriptor fd, int uid, int gid) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.fchown(fd, uid, gid);
+ }
+
// TODO: Untag newFd when needed for dup2(FileDescriptor oldFd, int newFd)
@Override public void fdatasync(FileDescriptor fd) throws ErrnoException {
@@ -92,6 +128,16 @@ public class BlockGuardOs extends ForwardingOs {
os.fdatasync(fd);
}
+ @Override public StructStat fstat(FileDescriptor fd) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.fstat(fd);
+ }
+
+ @Override public StructStatVfs fstatvfs(FileDescriptor fd) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.fstatvfs(fd);
+ }
+
@Override public void fsync(FileDescriptor fd) throws ErrnoException {
BlockGuard.getThreadPolicy().onWriteToDisk();
os.fsync(fd);
@@ -102,6 +148,36 @@ public class BlockGuardOs extends ForwardingOs {
os.ftruncate(fd, length);
}
+ @Override public void lchown(String path, int uid, int gid) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.lchown(path, uid, gid);
+ }
+
+ @Override public void link(String oldPath, String newPath) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.link(oldPath, newPath);
+ }
+
+ @Override public long lseek(FileDescriptor fd, long offset, int whence) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.lseek(fd, offset, whence);
+ }
+
+ @Override public StructStat lstat(String path) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.lstat(path);
+ }
+
+ @Override public void mkdir(String path, int mode) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.mkdir(path, mode);
+ }
+
+ @Override public void mkfifo(String path, int mode) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.mkfifo(path, mode);
+ }
+
@Override public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
BlockGuard.getThreadPolicy().onReadFromDisk();
if ((mode & O_ACCMODE) != O_RDONLY) {
@@ -119,37 +195,47 @@ public class BlockGuardOs extends ForwardingOs {
return os.poll(fds, timeoutMs);
}
- @Override public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException {
+ @Override public void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.posix_fallocate(fd, offset, length);
+ }
+
+ @Override public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.pread(fd, buffer, offset);
}
- @Override public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException {
+ @Override public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.pread(fd, bytes, byteOffset, byteCount, offset);
}
- @Override public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException {
+ @Override public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return os.pwrite(fd, buffer, offset);
}
- @Override public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException {
+ @Override public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return os.pwrite(fd, bytes, byteOffset, byteCount, offset);
}
- @Override public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException {
+ @Override public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.read(fd, buffer);
}
- @Override public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException {
+ @Override public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.read(fd, bytes, byteOffset, byteCount);
}
- @Override public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException {
+ @Override public String readlink(String path) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.readlink(path);
+ }
+
+ @Override public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onReadFromDisk();
return os.readv(fd, buffers, offsets, byteCounts);
}
@@ -164,6 +250,21 @@ public class BlockGuardOs extends ForwardingOs {
return os.recvfrom(fd, bytes, byteOffset, byteCount, flags, srcAddress);
}
+ @Override public void remove(String path) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.remove(path);
+ }
+
+ @Override public void rename(String oldPath, String newPath) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.rename(oldPath, newPath);
+ }
+
+ @Override public long sendfile(FileDescriptor outFd, FileDescriptor inFd, MutableLong inOffset, long byteCount) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ return os.sendfile(outFd, inFd, inOffset, byteCount);
+ }
+
@Override public int sendto(FileDescriptor fd, ByteBuffer buffer, int flags, InetAddress inetAddress, int port) throws ErrnoException, SocketException {
BlockGuard.getThreadPolicy().onNetwork();
return os.sendto(fd, buffer, flags, inetAddress, port);
@@ -187,17 +288,32 @@ public class BlockGuardOs extends ForwardingOs {
tagSocket(fd2);
}
- @Override public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException {
+ @Override public StructStat stat(String path) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.stat(path);
+ }
+
+ @Override public StructStatVfs statvfs(String path) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onReadFromDisk();
+ return os.statvfs(path);
+ }
+
+ @Override public void symlink(String oldPath, String newPath) throws ErrnoException {
+ BlockGuard.getThreadPolicy().onWriteToDisk();
+ os.symlink(oldPath, newPath);
+ }
+
+ @Override public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return os.write(fd, buffer);
}
- @Override public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException {
+ @Override public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return os.write(fd, bytes, byteOffset, byteCount);
}
- @Override public int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException {
+ @Override public int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return os.writev(fd, buffers, offsets, byteCounts);
}
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java b/luni/src/main/java/libcore/io/DeleteOnExit.java
index 8fa04fd..36d7948 100644
--- a/luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java
+++ b/luni/src/main/java/libcore/io/DeleteOnExit.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.luni.util;
+package libcore.io;
import java.io.File;
@@ -34,11 +34,6 @@ public class DeleteOnExit extends Thread {
private static DeleteOnExit instance;
/**
- * Our list of files scheduled for deletion.
- */
- private ArrayList<String> files = new ArrayList<String>();
-
- /**
* Returns our singleton instance, creating it if necessary.
*/
public static synchronized DeleteOnExit getInstance() {
@@ -51,12 +46,21 @@ public class DeleteOnExit extends Thread {
}
/**
+ * Our list of files scheduled for deletion.
+ */
+ private final ArrayList<String> files = new ArrayList<String>();
+
+
+ private DeleteOnExit() {
+ }
+
+ /**
* Schedules a file for deletion.
*
* @param filename The file to delete.
*/
public void addFile(String filename) {
- synchronized(files) {
+ synchronized (files) {
if (!files.contains(filename)) {
files.add(filename);
}
diff --git a/luni/src/main/java/libcore/io/ErrnoException.java b/luni/src/main/java/libcore/io/ErrnoException.java
deleted file mode 100644
index f484ce9..0000000
--- a/luni/src/main/java/libcore/io/ErrnoException.java
+++ /dev/null
@@ -1,65 +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 libcore.io;
-
-import java.io.IOException;
-import java.net.SocketException;
-
-/**
- * A checked exception thrown when {@link Os} methods fail. This exception contains the native
- * errno value, for comparison against the constants in {@link OsConstants}, should sophisticated
- * callers need to adjust their behavior based on the exact failure.
- */
-public final class ErrnoException extends Exception {
- private final String functionName;
- public final int errno;
-
- public ErrnoException(String functionName, int errno) {
- this.functionName = functionName;
- this.errno = errno;
- }
-
- public ErrnoException(String functionName, int errno, Throwable cause) {
- super(cause);
- this.functionName = functionName;
- this.errno = errno;
- }
-
- /**
- * Converts the stashed function name and errno value to a human-readable string.
- * We do this here rather than in the constructor so that callers only pay for
- * this if they need it.
- */
- @Override public String getMessage() {
- String errnoName = OsConstants.errnoName(errno);
- if (errnoName == null) {
- errnoName = "errno " + errno;
- }
- String description = Libcore.os.strerror(errno);
- return functionName + " failed: " + errnoName + " (" + description + ")";
- }
-
- public IOException rethrowAsIOException() throws IOException {
- IOException newException = new IOException(getMessage());
- newException.initCause(this);
- throw newException;
- }
-
- public SocketException rethrowAsSocketException() throws SocketException {
- throw new SocketException(getMessage(), this);
- }
-}
diff --git a/luni/src/main/java/libcore/io/ForwardingOs.java b/luni/src/main/java/libcore/io/ForwardingOs.java
index 3800416..bf4b448 100644
--- a/luni/src/main/java/libcore/io/ForwardingOs.java
+++ b/luni/src/main/java/libcore/io/ForwardingOs.java
@@ -16,14 +16,29 @@
package libcore.io;
+import android.system.ErrnoException;
+import android.system.GaiException;
+import android.system.StructAddrinfo;
+import android.system.StructFlock;
+import android.system.StructGroupReq;
+import android.system.StructGroupSourceReq;
+import android.system.StructLinger;
+import android.system.StructPasswd;
+import android.system.StructPollfd;
+import android.system.StructStat;
+import android.system.StructStatVfs;
+import android.system.StructTimeval;
+import android.system.StructUcred;
+import android.system.StructUtsname;
+import android.util.MutableInt;
+import android.util.MutableLong;
import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
-import libcore.util.MutableInt;
-import libcore.util.MutableLong;
/**
* Subclass this if you want to override some {@link Os} methods but otherwise delegate.
@@ -37,6 +52,7 @@ public class ForwardingOs implements Os {
public FileDescriptor accept(FileDescriptor fd, InetSocketAddress peerAddress) throws ErrnoException, SocketException { return os.accept(fd, peerAddress); }
public boolean access(String path, int mode) throws ErrnoException { return os.access(path, mode); }
+ public InetAddress[] android_getaddrinfo(String node, StructAddrinfo hints, int netId) throws GaiException { return os.android_getaddrinfo(node, hints, netId); }
public void bind(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException { os.bind(fd, address, port); }
public void chmod(String path, int mode) throws ErrnoException { os.chmod(path, mode); }
public void chown(String path, int uid, int gid) throws ErrnoException { os.chown(path, uid, gid); }
@@ -58,7 +74,6 @@ public class ForwardingOs implements Os {
public void fsync(FileDescriptor fd) throws ErrnoException { os.fsync(fd); }
public void ftruncate(FileDescriptor fd, long length) throws ErrnoException { os.ftruncate(fd, length); }
public String gai_strerror(int error) { return os.gai_strerror(error); }
- public InetAddress[] getaddrinfo(String node, StructAddrinfo hints) throws GaiException { return os.getaddrinfo(node, hints); }
public int getegid() { return os.getegid(); }
public int geteuid() { return os.geteuid(); }
public int getgid() { return os.getgid(); }
@@ -85,11 +100,13 @@ public class ForwardingOs implements Os {
public boolean isatty(FileDescriptor fd) { return os.isatty(fd); }
public void kill(int pid, int signal) throws ErrnoException { os.kill(pid, signal); }
public void lchown(String path, int uid, int gid) throws ErrnoException { os.lchown(path, uid, gid); }
+ public void link(String oldPath, String newPath) throws ErrnoException { os.link(oldPath, newPath); }
public void listen(FileDescriptor fd, int backlog) throws ErrnoException { os.listen(fd, backlog); }
public long lseek(FileDescriptor fd, long offset, int whence) throws ErrnoException { return os.lseek(fd, offset, whence); }
public StructStat lstat(String path) throws ErrnoException { return os.lstat(path); }
public void mincore(long address, long byteCount, byte[] vector) throws ErrnoException { os.mincore(address, byteCount, vector); }
public void mkdir(String path, int mode) throws ErrnoException { os.mkdir(path, mode); }
+ public void mkfifo(String path, int mode) throws ErrnoException { os.mkfifo(path, mode); }
public void mlock(long address, long byteCount) throws ErrnoException { os.mlock(address, byteCount); }
public long mmap(long address, long byteCount, int prot, int flags, FileDescriptor fd, long offset) throws ErrnoException { return os.mmap(address, byteCount, prot, flags, fd, offset); }
public void msync(long address, long byteCount, int flags) throws ErrnoException { os.msync(address, byteCount, flags); }
@@ -98,13 +115,16 @@ public class ForwardingOs implements Os {
public FileDescriptor open(String path, int flags, int mode) throws ErrnoException { return os.open(path, flags, mode); }
public FileDescriptor[] pipe() throws ErrnoException { return os.pipe(); }
public int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException { return os.poll(fds, timeoutMs); }
- public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException { return os.pread(fd, buffer, offset); }
- public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException { return os.pread(fd, bytes, byteOffset, byteCount, offset); }
- public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException { return os.pwrite(fd, buffer, offset); }
- public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException { return os.pwrite(fd, bytes, byteOffset, byteCount, offset); }
- public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException { return os.read(fd, buffer); }
- public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException { return os.read(fd, bytes, byteOffset, byteCount); }
- public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException { return os.readv(fd, buffers, offsets, byteCounts); }
+ public void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException { os.posix_fallocate(fd, offset, length); }
+ public int prctl(int option, long arg2, long arg3, long arg4, long arg5) throws ErrnoException { return os.prctl(option, arg2, arg3, arg4, arg5); };
+ public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException { return os.pread(fd, buffer, offset); }
+ public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException { return os.pread(fd, bytes, byteOffset, byteCount, offset); }
+ public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException { return os.pwrite(fd, buffer, offset); }
+ public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException { return os.pwrite(fd, bytes, byteOffset, byteCount, offset); }
+ public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException { return os.read(fd, buffer); }
+ public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException { return os.read(fd, bytes, byteOffset, byteCount); }
+ public String readlink(String path) throws ErrnoException { return os.readlink(path); }
+ public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException { return os.readv(fd, buffers, offsets, byteCounts); }
public int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException { return os.recvfrom(fd, buffer, flags, srcAddress); }
public int recvfrom(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException { return os.recvfrom(fd, bytes, byteOffset, byteCount, flags, srcAddress); }
public void remove(String path) throws ErrnoException { os.remove(path); }
@@ -122,6 +142,7 @@ public class ForwardingOs implements Os {
public void setsockoptInt(FileDescriptor fd, int level, int option, int value) throws ErrnoException { os.setsockoptInt(fd, level, option, value); }
public void setsockoptIpMreqn(FileDescriptor fd, int level, int option, int value) throws ErrnoException { os.setsockoptIpMreqn(fd, level, option, value); }
public void setsockoptGroupReq(FileDescriptor fd, int level, int option, StructGroupReq value) throws ErrnoException { os.setsockoptGroupReq(fd, level, option, value); }
+ public void setsockoptGroupSourceReq(FileDescriptor fd, int level, int option, StructGroupSourceReq value) throws ErrnoException { os.setsockoptGroupSourceReq(fd, level, option, value); }
public void setsockoptLinger(FileDescriptor fd, int level, int option, StructLinger value) throws ErrnoException { os.setsockoptLinger(fd, level, option, value); }
public void setsockoptTimeval(FileDescriptor fd, int level, int option, StructTimeval value) throws ErrnoException { os.setsockoptTimeval(fd, level, option, value); }
public void setuid(int uid) throws ErrnoException { os.setuid(uid); }
@@ -140,7 +161,7 @@ public class ForwardingOs implements Os {
public StructUtsname uname() { return os.uname(); }
public void unsetenv(String name) throws ErrnoException { os.unsetenv(name); }
public int waitpid(int pid, MutableInt status, int options) throws ErrnoException { return os.waitpid(pid, status, options); }
- public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException { return os.write(fd, buffer); }
- public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException { return os.write(fd, bytes, byteOffset, byteCount); }
- public int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException { return os.writev(fd, buffers, offsets, byteCounts); }
+ public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException { return os.write(fd, buffer); }
+ public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException { return os.write(fd, bytes, byteOffset, byteCount); }
+ public int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException { return os.writev(fd, buffers, offsets, byteCounts); }
}
diff --git a/luni/src/main/java/libcore/io/GaiException.java b/luni/src/main/java/libcore/io/GaiException.java
deleted file mode 100644
index 08143dc..0000000
--- a/luni/src/main/java/libcore/io/GaiException.java
+++ /dev/null
@@ -1,66 +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 libcore.io;
-
-import java.net.UnknownHostException;
-import libcore.io.OsConstants;
-
-/**
- * An unchecked exception thrown when the {@link Os} {@code getaddrinfo} or {@code getnameinfo}
- * methods fail. This exception contains the native error value, for comparison against the
- * {@code GAI_} constants in {@link OsConstants}, should sophisticated
- * callers need to adjust their behavior based on the exact failure.
- */
-public final class GaiException extends RuntimeException {
- private final String functionName;
- public final int error;
-
- public GaiException(String functionName, int error) {
- this.functionName = functionName;
- this.error = error;
- }
-
- public GaiException(String functionName, int error, Throwable cause) {
- super(cause);
- this.functionName = functionName;
- this.error = error;
- }
-
- /**
- * Converts the stashed function name and error value to a human-readable string.
- * We do this here rather than in the constructor so that callers only pay for
- * this if they need it.
- */
- @Override public String getMessage() {
- String gaiName = OsConstants.gaiName(error);
- if (gaiName == null) {
- gaiName = "GAI_ error " + error;
- }
- String description = Libcore.os.gai_strerror(error);
- return functionName + " failed: " + gaiName + " (" + description + ")";
- }
-
- public UnknownHostException rethrowAsUnknownHostException(String detailMessage) throws UnknownHostException {
- UnknownHostException newException = new UnknownHostException(detailMessage);
- newException.initCause(this);
- throw newException;
- }
-
- public UnknownHostException rethrowAsUnknownHostException() throws UnknownHostException {
- throw rethrowAsUnknownHostException(getMessage());
- }
-}
diff --git a/luni/src/main/java/libcore/io/IoBridge.java b/luni/src/main/java/libcore/io/IoBridge.java
index 28adba1..acc8d4f 100644
--- a/luni/src/main/java/libcore/io/IoBridge.java
+++ b/luni/src/main/java/libcore/io/IoBridge.java
@@ -16,6 +16,13 @@
package libcore.io;
+import android.system.ErrnoException;
+import android.system.StructGroupReq;
+import android.system.StructGroupSourceReq;
+import android.system.StructLinger;
+import android.system.StructPollfd;
+import android.system.StructTimeval;
+import android.util.MutableInt;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -35,8 +42,7 @@ import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
-import static libcore.io.OsConstants.*;
-import libcore.util.MutableInt;
+import static android.system.OsConstants.*;
/**
* Implements java.io/java.net/java.nio semantics in terms of the underlying POSIX system calls.
@@ -71,16 +77,20 @@ public final class IoBridge {
public static void bind(FileDescriptor fd, InetAddress address, int port) throws SocketException {
- if (address instanceof Inet6Address && ((Inet6Address) address).getScopeId() == 0) {
- // Linux won't let you bind a link-local address without a scope id. Find one.
- NetworkInterface nif = NetworkInterface.getByInetAddress(address);
- if (nif == null) {
- throw new SocketException("Can't bind to a link-local address without a scope id: " + address);
- }
- try {
- address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex());
- } catch (UnknownHostException ex) {
- throw new AssertionError(ex); // Can't happen.
+ if (address instanceof Inet6Address) {
+ Inet6Address inet6Address = (Inet6Address) address;
+ if (inet6Address.getScopeId() == 0 && inet6Address.isLinkLocalAddress()) {
+ // Linux won't let you bind a link-local address without a scope id.
+ // Find one.
+ NetworkInterface nif = NetworkInterface.getByInetAddress(address);
+ if (nif == null) {
+ throw new SocketException("Can't bind to a link-local address without a scope id: " + address);
+ }
+ try {
+ address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex());
+ } catch (UnknownHostException ex) {
+ throw new AssertionError(ex); // Can't happen.
+ }
}
}
try {
@@ -95,9 +105,9 @@ public final class IoBridge {
* Connects socket 'fd' to 'inetAddress' on 'port', with no timeout. The lack of a timeout
* means this method won't throw SocketTimeoutException.
*/
- public static boolean connect(FileDescriptor fd, InetAddress inetAddress, int port) throws SocketException {
+ public static void connect(FileDescriptor fd, InetAddress inetAddress, int port) throws SocketException {
try {
- return IoBridge.connect(fd, inetAddress, port, 0);
+ IoBridge.connect(fd, inetAddress, port, 0);
} catch (SocketTimeoutException ex) {
throw new AssertionError(ex); // Can't happen for a connect without a timeout.
}
@@ -107,9 +117,9 @@ public final class IoBridge {
* Connects socket 'fd' to 'inetAddress' on 'port', with a the given 'timeoutMs'.
* Use timeoutMs == 0 for a blocking connect with no timeout.
*/
- public static boolean connect(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws SocketException, SocketTimeoutException {
+ public static void connect(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws SocketException, SocketTimeoutException {
try {
- return connectErrno(fd, inetAddress, port, timeoutMs);
+ connectErrno(fd, inetAddress, port, timeoutMs);
} catch (ErrnoException errnoException) {
throw new ConnectException(connectDetail(inetAddress, port, timeoutMs, errnoException), errnoException);
} catch (SocketException ex) {
@@ -121,11 +131,11 @@ public final class IoBridge {
}
}
- private static boolean connectErrno(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws ErrnoException, IOException {
+ private static void connectErrno(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws ErrnoException, IOException {
// With no timeout, just call connect(2) directly.
if (timeoutMs == 0) {
Libcore.os.connect(fd, inetAddress, port);
- return true;
+ return;
}
// For connect with a timeout, we:
@@ -143,7 +153,7 @@ public final class IoBridge {
try {
Libcore.os.connect(fd, inetAddress, port);
IoUtils.setBlocking(fd, true); // 4. set the socket back to blocking.
- return true; // We connected immediately.
+ return; // We connected immediately.
} catch (ErrnoException errnoException) {
if (errnoException.errno != EINPROGRESS) {
throw errnoException;
@@ -160,7 +170,6 @@ public final class IoBridge {
}
} while (!IoBridge.isConnected(fd, inetAddress, port, timeoutMs, remainingTimeoutMs));
IoUtils.setBlocking(fd, true); // 4. set the socket back to blocking.
- return true; // Or we'd have thrown.
}
private static String connectDetail(InetAddress inetAddress, int port, int timeoutMs, ErrnoException cause) {
@@ -174,9 +183,15 @@ public final class IoBridge {
return detail;
}
- public static void closeSocket(FileDescriptor fd) throws IOException {
- if (!fd.valid()) {
- // Socket.close doesn't throw if you try to close an already-closed socket.
+ /**
+ * Closes the supplied file descriptor and sends a signal to any threads are currently blocking.
+ * In order for the signal to be sent the blocked threads must have registered with
+ * the AsynchronousCloseMonitor before they entered the blocking operation.
+ *
+ * <p>This method is a no-op if passed a {@code null} or already-closed file descriptor.
+ */
+ public static void closeAndSignalBlockedThreads(FileDescriptor fd) throws IOException {
+ if (fd == null || !fd.valid()) {
return;
}
int intFd = fd.getInt$();
@@ -226,6 +241,10 @@ public final class IoBridge {
// Socket options used by java.net but not exposed in SocketOptions.
public static final int JAVA_MCAST_JOIN_GROUP = 19;
public static final int JAVA_MCAST_LEAVE_GROUP = 20;
+ public static final int JAVA_MCAST_JOIN_SOURCE_GROUP = 21;
+ public static final int JAVA_MCAST_LEAVE_SOURCE_GROUP = 22;
+ public static final int JAVA_MCAST_BLOCK_SOURCE = 23;
+ public static final int JAVA_MCAST_UNBLOCK_SOURCE = 24;
public static final int JAVA_IP_MULTICAST_TTL = 17;
/**
@@ -369,16 +388,46 @@ public final class IoBridge {
return;
case IoBridge.JAVA_MCAST_JOIN_GROUP:
case IoBridge.JAVA_MCAST_LEAVE_GROUP:
+ {
StructGroupReq groupReq = (StructGroupReq) value;
int level = (groupReq.gr_group instanceof Inet4Address) ? IPPROTO_IP : IPPROTO_IPV6;
int op = (option == JAVA_MCAST_JOIN_GROUP) ? MCAST_JOIN_GROUP : MCAST_LEAVE_GROUP;
Libcore.os.setsockoptGroupReq(fd, level, op, groupReq);
return;
+ }
+ case IoBridge.JAVA_MCAST_JOIN_SOURCE_GROUP:
+ case IoBridge.JAVA_MCAST_LEAVE_SOURCE_GROUP:
+ case IoBridge.JAVA_MCAST_BLOCK_SOURCE:
+ case IoBridge.JAVA_MCAST_UNBLOCK_SOURCE:
+ {
+ StructGroupSourceReq groupSourceReq = (StructGroupSourceReq) value;
+ int level = (groupSourceReq.gsr_group instanceof Inet4Address)
+ ? IPPROTO_IP : IPPROTO_IPV6;
+ int op = getGroupSourceReqOp(option);
+ Libcore.os.setsockoptGroupSourceReq(fd, level, op, groupSourceReq);
+ return;
+ }
default:
throw new SocketException("Unknown socket option: " + option);
}
}
+ private static int getGroupSourceReqOp(int javaValue) {
+ switch (javaValue) {
+ case IoBridge.JAVA_MCAST_JOIN_SOURCE_GROUP:
+ return MCAST_JOIN_SOURCE_GROUP;
+ case IoBridge.JAVA_MCAST_LEAVE_SOURCE_GROUP:
+ return MCAST_LEAVE_SOURCE_GROUP;
+ case IoBridge.JAVA_MCAST_BLOCK_SOURCE:
+ return MCAST_BLOCK_SOURCE;
+ case IoBridge.JAVA_MCAST_UNBLOCK_SOURCE:
+ return MCAST_UNBLOCK_SOURCE;
+ default:
+ throw new AssertionError(
+ "Unknown java value for setsocketopt op lookup: " + javaValue);
+ }
+ }
+
/**
* java.io only throws FileNotFoundException when opening files, regardless of what actually
* went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
@@ -391,12 +440,10 @@ public final class IoBridge {
// On Android, we don't want default permissions to allow global access.
int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
fd = Libcore.os.open(path, flags, mode);
- if (fd.valid()) {
- // Posix open(2) fails with EISDIR only if you ask for write permission.
- // Java disallows reading directories too.
- if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
- throw new ErrnoException("open", EISDIR);
- }
+ // Posix open(2) fails with EISDIR only if you ask for write permission.
+ // Java disallows reading directories too.
+ if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
+ throw new ErrnoException("open", EISDIR);
}
return fd;
} catch (ErrnoException errnoException) {
diff --git a/luni/src/main/java/libcore/io/IoUtils.java b/luni/src/main/java/libcore/io/IoUtils.java
index 10ef671..5a19f17 100644
--- a/luni/src/main/java/libcore/io/IoUtils.java
+++ b/luni/src/main/java/libcore/io/IoUtils.java
@@ -16,6 +16,8 @@
package libcore.io;
+import android.system.ErrnoException;
+import android.system.StructStat;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
@@ -25,7 +27,7 @@ import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Random;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
public final class IoUtils {
private static final Random TEMPORARY_DIRECTORY_PRNG = new Random();
diff --git a/luni/src/main/java/libcore/io/Memory.java b/luni/src/main/java/libcore/io/Memory.java
index 5743949..e148457 100644
--- a/luni/src/main/java/libcore/io/Memory.java
+++ b/luni/src/main/java/libcore/io/Memory.java
@@ -151,9 +151,33 @@ public final class Memory {
public static native void memmove(Object dstObject, int dstOffset, Object srcObject, int srcOffset, long byteCount);
public static native byte peekByte(long address);
- public static native int peekInt(long address, boolean swap);
- public static native long peekLong(long address, boolean swap);
- public static native short peekShort(long address, boolean swap);
+
+ public static int peekInt(long address, boolean swap) {
+ int result = peekIntNative(address);
+ if (swap) {
+ result = Integer.reverseBytes(result);
+ }
+ return result;
+ }
+ private static native int peekIntNative(long address);
+
+ public static long peekLong(long address, boolean swap) {
+ long result = peekLongNative(address);
+ if (swap) {
+ result = Long.reverseBytes(result);
+ }
+ return result;
+ }
+ private static native long peekLongNative(long address);
+
+ public static short peekShort(long address, boolean swap) {
+ short result = peekShortNative(address);
+ if (swap) {
+ result = Short.reverseBytes(result);
+ }
+ return result;
+ }
+ private static native short peekShortNative(long address);
public static native void peekByteArray(long address, byte[] dst, int dstOffset, int byteCount);
public static native void peekCharArray(long address, char[] dst, int dstOffset, int charCount, boolean swap);
@@ -164,9 +188,30 @@ public final class Memory {
public static native void peekShortArray(long address, short[] dst, int dstOffset, int shortCount, boolean swap);
public static native void pokeByte(long address, byte value);
- public static native void pokeInt(long address, int value, boolean swap);
- public static native void pokeLong(long address, long value, boolean swap);
- public static native void pokeShort(long address, short value, boolean swap);
+
+ public static void pokeInt(long address, int value, boolean swap) {
+ if (swap) {
+ value = Integer.reverseBytes(value);
+ }
+ pokeIntNative(address, value);
+ }
+ private static native void pokeIntNative(long address, int value);
+
+ public static void pokeLong(long address, long value, boolean swap) {
+ if (swap) {
+ value = Long.reverseBytes(value);
+ }
+ pokeLongNative(address, value);
+ }
+ private static native void pokeLongNative(long address, long value);
+
+ public static void pokeShort(long address, short value, boolean swap) {
+ if (swap) {
+ value = Short.reverseBytes(value);
+ }
+ pokeShortNative(address, value);
+ }
+ private static native void pokeShortNative(long address, short value);
public static native void pokeByteArray(long address, byte[] src, int offset, int count);
public static native void pokeCharArray(long address, char[] src, int offset, int count, boolean swap);
diff --git a/luni/src/main/java/libcore/io/MemoryMappedFile.java b/luni/src/main/java/libcore/io/MemoryMappedFile.java
index 2d8aa2b..b4cd8fc 100644
--- a/luni/src/main/java/libcore/io/MemoryMappedFile.java
+++ b/luni/src/main/java/libcore/io/MemoryMappedFile.java
@@ -16,16 +16,16 @@
package libcore.io;
+import android.system.ErrnoException;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
-import java.nio.NioUtils;
import java.nio.channels.FileChannel;
-import libcore.io.ErrnoException;
+import java.nio.NioUtils;
import libcore.io.Libcore;
import libcore.io.Memory;
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
/**
* A memory-mapped file. Use {@link #mmap} to map a file, {@link #close} to unmap a file,
diff --git a/luni/src/main/java/libcore/io/Os.java b/luni/src/main/java/libcore/io/Os.java
index 2b68027..511bb27 100644
--- a/luni/src/main/java/libcore/io/Os.java
+++ b/luni/src/main/java/libcore/io/Os.java
@@ -16,18 +16,34 @@
package libcore.io;
+import android.system.ErrnoException;
+import android.system.GaiException;
+import android.system.StructAddrinfo;
+import android.system.StructFlock;
+import android.system.StructGroupReq;
+import android.system.StructGroupSourceReq;
+import android.system.StructLinger;
+import android.system.StructPasswd;
+import android.system.StructPollfd;
+import android.system.StructStat;
+import android.system.StructStatVfs;
+import android.system.StructTimeval;
+import android.system.StructUcred;
+import android.system.StructUtsname;
+import android.util.MutableInt;
+import android.util.MutableLong;
import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
-import libcore.util.MutableInt;
-import libcore.util.MutableLong;
public interface Os {
public FileDescriptor accept(FileDescriptor fd, InetSocketAddress peerAddress) throws ErrnoException, SocketException;
public boolean access(String path, int mode) throws ErrnoException;
+ public InetAddress[] android_getaddrinfo(String node, StructAddrinfo hints, int netId) throws GaiException;
public void bind(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException;
public void chmod(String path, int mode) throws ErrnoException;
public void chown(String path, int uid, int gid) throws ErrnoException;
@@ -49,7 +65,6 @@ public interface Os {
public void fsync(FileDescriptor fd) throws ErrnoException;
public void ftruncate(FileDescriptor fd, long length) throws ErrnoException;
public String gai_strerror(int error);
- public InetAddress[] getaddrinfo(String node, StructAddrinfo hints) throws GaiException;
public int getegid();
public int geteuid();
public int getgid();
@@ -77,11 +92,13 @@ public interface Os {
public boolean isatty(FileDescriptor fd);
public void kill(int pid, int signal) throws ErrnoException;
public void lchown(String path, int uid, int gid) throws ErrnoException;
+ public void link(String oldPath, String newPath) throws ErrnoException;
public void listen(FileDescriptor fd, int backlog) throws ErrnoException;
public long lseek(FileDescriptor fd, long offset, int whence) throws ErrnoException;
public StructStat lstat(String path) throws ErrnoException;
public void mincore(long address, long byteCount, byte[] vector) throws ErrnoException;
public void mkdir(String path, int mode) throws ErrnoException;
+ public void mkfifo(String path, int mode) throws ErrnoException;
public void mlock(long address, long byteCount) throws ErrnoException;
public long mmap(long address, long byteCount, int prot, int flags, FileDescriptor fd, long offset) throws ErrnoException;
public void msync(long address, long byteCount, int flags) throws ErrnoException;
@@ -91,13 +108,16 @@ public interface Os {
public FileDescriptor[] pipe() throws ErrnoException;
/* TODO: if we used the non-standard ppoll(2) behind the scenes, we could take a long timeout. */
public int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException;
- public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException;
- public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException;
- public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException;
- public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException;
- public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException;
- public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException;
- public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException;
+ public void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException;
+ public int prctl(int option, long arg2, long arg3, long arg4, long arg5) throws ErrnoException;
+ public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException;
+ public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException;
+ public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException;
+ public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException;
+ public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException;
+ public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException;
+ public String readlink(String path) throws ErrnoException;
+ public int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException;
public int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException;
public int recvfrom(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException;
public void remove(String path) throws ErrnoException;
@@ -115,6 +135,7 @@ public interface Os {
public void setsockoptInt(FileDescriptor fd, int level, int option, int value) throws ErrnoException;
public void setsockoptIpMreqn(FileDescriptor fd, int level, int option, int value) throws ErrnoException;
public void setsockoptGroupReq(FileDescriptor fd, int level, int option, StructGroupReq value) throws ErrnoException;
+ public void setsockoptGroupSourceReq(FileDescriptor fd, int level, int option, StructGroupSourceReq value) throws ErrnoException;
public void setsockoptLinger(FileDescriptor fd, int level, int option, StructLinger value) throws ErrnoException;
public void setsockoptTimeval(FileDescriptor fd, int level, int option, StructTimeval value) throws ErrnoException;
public void setuid(int uid) throws ErrnoException;
@@ -133,7 +154,7 @@ public interface Os {
public StructUtsname uname();
public void unsetenv(String name) throws ErrnoException;
public int waitpid(int pid, MutableInt status, int options) throws ErrnoException;
- public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException;
- public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException;
- public int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException;
+ public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException;
+ public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException;
+ public int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException;
}
diff --git a/luni/src/main/java/libcore/io/Posix.java b/luni/src/main/java/libcore/io/Posix.java
index b99941c..f5eaaa3 100644
--- a/luni/src/main/java/libcore/io/Posix.java
+++ b/luni/src/main/java/libcore/io/Posix.java
@@ -16,21 +16,37 @@
package libcore.io;
+import android.system.ErrnoException;
+import android.system.GaiException;
+import android.system.StructAddrinfo;
+import android.system.StructFlock;
+import android.system.StructGroupReq;
+import android.system.StructGroupSourceReq;
+import android.system.StructLinger;
+import android.system.StructPasswd;
+import android.system.StructPollfd;
+import android.system.StructStat;
+import android.system.StructStatVfs;
+import android.system.StructTimeval;
+import android.system.StructUcred;
+import android.system.StructUtsname;
+import android.util.MutableInt;
+import android.util.MutableLong;
import java.io.FileDescriptor;
+import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.NioUtils;
-import libcore.util.MutableInt;
-import libcore.util.MutableLong;
public final class Posix implements Os {
Posix() { }
public native FileDescriptor accept(FileDescriptor fd, InetSocketAddress peerAddress) throws ErrnoException, SocketException;
public native boolean access(String path, int mode) throws ErrnoException;
+ public native InetAddress[] android_getaddrinfo(String node, StructAddrinfo hints, int netId) throws GaiException;
public native void bind(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException;
public native void chmod(String path, int mode) throws ErrnoException;
public native void chown(String path, int uid, int gid) throws ErrnoException;
@@ -52,7 +68,6 @@ public final class Posix implements Os {
public native void fsync(FileDescriptor fd) throws ErrnoException;
public native void ftruncate(FileDescriptor fd, long length) throws ErrnoException;
public native String gai_strerror(int error);
- public native InetAddress[] getaddrinfo(String node, StructAddrinfo hints) throws GaiException;
public native int getegid();
public native int geteuid();
public native int getgid();
@@ -79,11 +94,13 @@ public final class Posix implements Os {
public native boolean isatty(FileDescriptor fd);
public native void kill(int pid, int signal) throws ErrnoException;
public native void lchown(String path, int uid, int gid) throws ErrnoException;
+ public native void link(String oldPath, String newPath) throws ErrnoException;
public native void listen(FileDescriptor fd, int backlog) throws ErrnoException;
public native long lseek(FileDescriptor fd, long offset, int whence) throws ErrnoException;
public native StructStat lstat(String path) throws ErrnoException;
public native void mincore(long address, long byteCount, byte[] vector) throws ErrnoException;
public native void mkdir(String path, int mode) throws ErrnoException;
+ public native void mkfifo(String path, int mode) throws ErrnoException;
public native void mlock(long address, long byteCount) throws ErrnoException;
public native long mmap(long address, long byteCount, int prot, int flags, FileDescriptor fd, long offset) throws ErrnoException;
public native void msync(long address, long byteCount, int flags) throws ErrnoException;
@@ -92,43 +109,46 @@ public final class Posix implements Os {
public native FileDescriptor open(String path, int flags, int mode) throws ErrnoException;
public native FileDescriptor[] pipe() throws ErrnoException;
public native int poll(StructPollfd[] fds, int timeoutMs) throws ErrnoException;
- public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException {
+ public native void posix_fallocate(FileDescriptor fd, long offset, long length) throws ErrnoException;
+ public native int prctl(int option, long arg2, long arg3, long arg4, long arg5) throws ErrnoException;
+ public int pread(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException {
if (buffer.isDirect()) {
return preadBytes(fd, buffer, buffer.position(), buffer.remaining(), offset);
} else {
return preadBytes(fd, NioUtils.unsafeArray(buffer), NioUtils.unsafeArrayOffset(buffer) + buffer.position(), buffer.remaining(), offset);
}
}
- public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException {
+ public int pread(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException {
// This indirection isn't strictly necessary, but ensures that our public interface is type safe.
return preadBytes(fd, bytes, byteOffset, byteCount, offset);
}
- private native int preadBytes(FileDescriptor fd, Object buffer, int bufferOffset, int byteCount, long offset) throws ErrnoException;
- public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException {
+ private native int preadBytes(FileDescriptor fd, Object buffer, int bufferOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException;
+ public int pwrite(FileDescriptor fd, ByteBuffer buffer, long offset) throws ErrnoException, InterruptedIOException {
if (buffer.isDirect()) {
return pwriteBytes(fd, buffer, buffer.position(), buffer.remaining(), offset);
} else {
return pwriteBytes(fd, NioUtils.unsafeArray(buffer), NioUtils.unsafeArrayOffset(buffer) + buffer.position(), buffer.remaining(), offset);
}
}
- public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException {
+ public int pwrite(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException {
// This indirection isn't strictly necessary, but ensures that our public interface is type safe.
return pwriteBytes(fd, bytes, byteOffset, byteCount, offset);
}
- private native int pwriteBytes(FileDescriptor fd, Object buffer, int bufferOffset, int byteCount, long offset) throws ErrnoException;
- public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException {
+ private native int pwriteBytes(FileDescriptor fd, Object buffer, int bufferOffset, int byteCount, long offset) throws ErrnoException, InterruptedIOException;
+ public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException {
if (buffer.isDirect()) {
return readBytes(fd, buffer, buffer.position(), buffer.remaining());
} else {
return readBytes(fd, NioUtils.unsafeArray(buffer), NioUtils.unsafeArrayOffset(buffer) + buffer.position(), buffer.remaining());
}
}
- public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException {
+ public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException {
// This indirection isn't strictly necessary, but ensures that our public interface is type safe.
return readBytes(fd, bytes, byteOffset, byteCount);
}
- private native int readBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException;
- public native int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException;
+ private native int readBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException, InterruptedIOException;
+ public native String readlink(String path) throws ErrnoException;
+ public native int readv(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException;
public int recvfrom(FileDescriptor fd, ByteBuffer buffer, int flags, InetSocketAddress srcAddress) throws ErrnoException, SocketException {
if (buffer.isDirect()) {
return recvfromBytes(fd, buffer, buffer.position(), buffer.remaining(), flags, srcAddress);
@@ -166,6 +186,7 @@ public final class Posix implements Os {
public native void setsockoptInt(FileDescriptor fd, int level, int option, int value) throws ErrnoException;
public native void setsockoptIpMreqn(FileDescriptor fd, int level, int option, int value) throws ErrnoException;
public native void setsockoptGroupReq(FileDescriptor fd, int level, int option, StructGroupReq value) throws ErrnoException;
+ public native void setsockoptGroupSourceReq(FileDescriptor fd, int level, int option, StructGroupSourceReq value) throws ErrnoException;
public native void setsockoptLinger(FileDescriptor fd, int level, int option, StructLinger value) throws ErrnoException;
public native void setsockoptTimeval(FileDescriptor fd, int level, int option, StructTimeval value) throws ErrnoException;
public native void setuid(int uid) throws ErrnoException;
@@ -190,17 +211,17 @@ public final class Posix implements Os {
public native StructUtsname uname();
public native void unsetenv(String name) throws ErrnoException;
public native int waitpid(int pid, MutableInt status, int options) throws ErrnoException;
- public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException {
+ public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException, InterruptedIOException {
if (buffer.isDirect()) {
return writeBytes(fd, buffer, buffer.position(), buffer.remaining());
} else {
return writeBytes(fd, NioUtils.unsafeArray(buffer), NioUtils.unsafeArrayOffset(buffer) + buffer.position(), buffer.remaining());
}
}
- public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException {
+ public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException, InterruptedIOException {
// This indirection isn't strictly necessary, but ensures that our public interface is type safe.
return writeBytes(fd, bytes, byteOffset, byteCount);
}
- private native int writeBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException;
- public native int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException;
+ private native int writeBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException, InterruptedIOException;
+ public native int writev(FileDescriptor fd, Object[] buffers, int[] offsets, int[] byteCounts) throws ErrnoException, InterruptedIOException;
}
diff --git a/luni/src/main/java/libcore/io/Streams.java b/luni/src/main/java/libcore/io/Streams.java
index cbad4a4..1f78edd 100644
--- a/luni/src/main/java/libcore/io/Streams.java
+++ b/luni/src/main/java/libcore/io/Streams.java
@@ -135,8 +135,9 @@ public final class Streams {
}
/**
- * Call {@code in.read()} repeatedly until either the stream is exhausted or
- * {@code byteCount} bytes have been read.
+ * Skip <b>at most</b> {@code byteCount} bytes from {@code in} by calling read
+ * repeatedly until either the stream is exhausted or we read fewer bytes than
+ * we ask for.
*
* <p>This method reuses the skip buffer but is careful to never use it at
* the same time that another stream is using it. Otherwise streams that use
diff --git a/luni/src/main/java/libcore/io/StructPasswd.java b/luni/src/main/java/libcore/io/StructPasswd.java
deleted file mode 100644
index 6f5e058..0000000
--- a/luni/src/main/java/libcore/io/StructPasswd.java
+++ /dev/null
@@ -1,38 +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 libcore.io;
-
-/**
- * Information returned by getpwnam(3) and getpwuid(3). Corresponds to C's
- * {@code struct passwd} from
- * <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/pwd.h.html">&lt;pwd.h&gt;</a>
- */
-public final class StructPasswd {
- public String pw_name;
- public int pw_uid; /* uid_t */
- public int pw_gid; /* gid_t */
- public String pw_dir;
- public String pw_shell;
-
- public StructPasswd(String pw_name, int pw_uid, int pw_gid, String pw_dir, String pw_shell) {
- this.pw_name = pw_name;
- this.pw_uid = pw_uid;
- this.pw_gid = pw_gid;
- this.pw_dir = pw_dir;
- this.pw_shell = pw_shell;
- }
-}
diff --git a/luni/src/main/java/libcore/io/StructPollfd.java b/luni/src/main/java/libcore/io/StructPollfd.java
deleted file mode 100644
index c659d6e..0000000
--- a/luni/src/main/java/libcore/io/StructPollfd.java
+++ /dev/null
@@ -1,48 +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 libcore.io;
-
-import java.io.FileDescriptor;
-
-/**
- * Corresponds to C's {@code struct pollfd} from
- * <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/poll.h.html">&lt;poll.h&gt;</a>
- */
-public final class StructPollfd {
- /** The file descriptor to poll. */
- public FileDescriptor fd;
-
- /**
- * The events we're interested in. POLLIN corresponds to being in select(2)'s read fd set,
- * POLLOUT to the write fd set.
- */
- public short events;
-
- /** The events that actually happened. */
- public short revents;
-
- /**
- * A non-standard extension that lets callers conveniently map back to the object
- * their fd belongs to. This is used by Selector, for example, to associate each
- * FileDescriptor with the corresponding SelectionKey.
- */
- public Object userData;
-
- @Override public String toString() {
- return "StructPollfd[fd=" + fd + ",events=" + events + ",revents=" + revents + "]";
- }
-}
diff --git a/luni/src/main/java/libcore/io/StructStat.java b/luni/src/main/java/libcore/io/StructStat.java
deleted file mode 100644
index 05ecca7..0000000
--- a/luni/src/main/java/libcore/io/StructStat.java
+++ /dev/null
@@ -1,90 +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 libcore.io;
-
-/**
- * File information returned by fstat(2), lstat(2), and stat(2). Corresponds to C's
- * {@code struct stat} from
- * <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/sys/stat.h.html">&lt;stat.h&gt;</a>
- */
-public final class StructStat {
- /** Device ID of device containing file. */
- public final long st_dev; /*dev_t*/
-
- /** File serial number (inode). */
- public final long st_ino; /*ino_t*/
-
- /** Mode (permissions) of file. */
- public final int st_mode; /*mode_t*/
-
- /** Number of hard links to the file. */
- public final long st_nlink; /*nlink_t*/
-
- /** User ID of file. */
- public final int st_uid; /*uid_t*/
-
- /** Group ID of file. */
- public final int st_gid; /*gid_t*/
-
- /** Device ID (if file is character or block special). */
- public final long st_rdev; /*dev_t*/
-
- /**
- * For regular files, the file size in bytes.
- * For symbolic links, the length in bytes of the pathname contained in the symbolic link.
- * For a shared memory object, the length in bytes.
- * For a typed memory object, the length in bytes.
- * For other file types, the use of this field is unspecified.
- */
- public final long st_size; /*off_t*/
-
- /** Time of last access. */
- public final long st_atime; /*time_t*/
-
- /** Time of last data modification. */
- public final long st_mtime; /*time_t*/
-
- /** Time of last status change. */
- public final long st_ctime; /*time_t*/
-
- /**
- * A file system-specific preferred I/O block size for this object.
- * For some file system types, this may vary from file to file.
- */
- public final long st_blksize; /*blksize_t*/
-
- /** Number of blocks allocated for this object. */
- public final long st_blocks; /*blkcnt_t*/
-
- StructStat(long st_dev, long st_ino, int st_mode, long st_nlink, int st_uid, int st_gid,
- long st_rdev, long st_size, long st_atime, long st_mtime, long st_ctime,
- long st_blksize, long st_blocks) {
- this.st_dev = st_dev;
- this.st_ino = st_ino;
- this.st_mode = st_mode;
- this.st_nlink = st_nlink;
- this.st_uid = st_uid;
- this.st_gid = st_gid;
- this.st_rdev = st_rdev;
- this.st_size = st_size;
- this.st_atime = st_atime;
- this.st_mtime = st_mtime;
- this.st_ctime = st_ctime;
- this.st_blksize = st_blksize;
- this.st_blocks = st_blocks;
- }
-}
diff --git a/luni/src/main/java/libcore/io/StructUtsname.java b/luni/src/main/java/libcore/io/StructUtsname.java
deleted file mode 100644
index e6a8e42..0000000
--- a/luni/src/main/java/libcore/io/StructUtsname.java
+++ /dev/null
@@ -1,47 +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 libcore.io;
-
-/**
- * Information returned by uname(2). Corresponds to C's
- * {@code struct utsname} from
- * <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_utsname.h.html">&lt;sys/utsname.h&gt;</a>
- */
-public final class StructUtsname {
- /** The OS name, such as "Linux". */
- public final String sysname;
-
- /** The machine's unqualified name on some implementation-defined network. */
- public final String nodename;
-
- /** The OS release, such as "2.6.35-27-generic". */
- public final String release;
-
- /** The OS version, such as "#48-Ubuntu SMP Tue Feb 22 20:25:29 UTC 2011". */
- public final String version;
-
- /** The machine architecture, such as "armv7l" or "x86_64". */
- public final String machine;
-
- StructUtsname(String sysname, String nodename, String release, String version, String machine) {
- this.sysname = sysname;
- this.nodename = nodename;
- this.release = release;
- this.version = version;
- this.machine = machine;
- }
-}
diff --git a/luni/src/main/java/libcore/net/MimeUtils.java b/luni/src/main/java/libcore/net/MimeUtils.java
index aaa5670..a5a1469 100644
--- a/luni/src/main/java/libcore/net/MimeUtils.java
+++ b/luni/src/main/java/libcore/net/MimeUtils.java
@@ -49,14 +49,13 @@ public final class MimeUtils {
add("application/andrew-inset", "ez");
add("application/dsptype", "tsp");
- add("application/futuresplash", "spl");
add("application/hta", "hta");
add("application/mac-binhex40", "hqx");
- add("application/mac-compactpro", "cpt");
add("application/mathematica", "nb");
add("application/msaccess", "mdb");
add("application/oda", "oda");
add("application/ogg", "ogg");
+ add("application/ogg", "oga");
add("application/pdf", "pdf");
add("application/pgp-keys", "key");
add("application/pgp-signature", "pgp");
@@ -133,14 +132,15 @@ public final class MimeUtils {
add("application/x-dms", "dms");
add("application/x-doom", "wad");
add("application/x-dvi", "dvi");
- add("application/x-flac", "flac");
add("application/x-font", "pfa");
add("application/x-font", "pfb");
add("application/x-font", "gsf");
add("application/x-font", "pcf");
add("application/x-font", "pcf.Z");
add("application/x-freemind", "mm");
+ // application/futuresplash isn't IANA, so application/x-futuresplash should come first.
add("application/x-futuresplash", "spl");
+ add("application/futuresplash", "spl");
add("application/x-gnumeric", "gnumeric");
add("application/x-go-sgf", "sgf");
add("application/x-graphing-calculator", "gcf");
@@ -212,11 +212,19 @@ public final class MimeUtils {
add("application/x-xfig", "fig");
add("application/xhtml+xml", "xhtml");
add("audio/3gpp", "3gpp");
+ add("audio/aac", "aac");
+ add("audio/aac-adts", "aac");
add("audio/amr", "amr");
+ add("audio/amr-wb", "awb");
add("audio/basic", "snd");
+ add("audio/flac", "flac");
+ add("application/x-flac", "flac");
+ add("audio/imelody", "imy");
add("audio/midi", "mid");
add("audio/midi", "midi");
+ add("audio/midi", "ota");
add("audio/midi", "kar");
+ add("audio/midi", "rtttl");
add("audio/midi", "xmf");
add("audio/mobile-xmf", "mxmf");
// add ".mp3" first so it will be the default for guessExtensionFromMimeType
@@ -231,6 +239,7 @@ public final class MimeUtils {
add("audio/x-aiff", "aiff");
add("audio/x-aiff", "aifc");
add("audio/x-gsm", "gsm");
+ add("audio/x-matroska", "mka");
add("audio/x-mpegurl", "m3u");
add("audio/x-ms-wma", "wma");
add("audio/x-ms-wax", "wax");
@@ -241,8 +250,12 @@ public final class MimeUtils {
add("audio/x-scpls", "pls");
add("audio/x-sd2", "sd2");
add("audio/x-wav", "wav");
+ // image/bmp isn't IANA, so image/x-ms-bmp should come first.
+ add("image/x-ms-bmp", "bmp");
add("image/bmp", "bmp");
add("image/gif", "gif");
+ // image/ico isn't IANA, so image/x-icon should come first.
+ add("image/x-icon", "ico");
add("image/ico", "cur");
add("image/ico", "ico");
add("image/ief", "ief");
@@ -258,15 +271,14 @@ public final class MimeUtils {
add("image/vnd.djvu", "djvu");
add("image/vnd.djvu", "djv");
add("image/vnd.wap.wbmp", "wbmp");
+ add("image/webp", "webp");
add("image/x-cmu-raster", "ras");
add("image/x-coreldraw", "cdr");
add("image/x-coreldrawpattern", "pat");
add("image/x-coreldrawtemplate", "cdt");
add("image/x-corelphotopaint", "cpt");
- add("image/x-icon", "ico");
add("image/x-jg", "art");
add("image/x-jng", "jng");
- add("image/x-ms-bmp", "bmp");
add("image/x-photoshop", "psd");
add("image/x-portable-anymap", "pnm");
add("image/x-portable-bitmap", "pbm");
@@ -298,7 +310,6 @@ public final class MimeUtils {
add("text/plain", "po"); // reserve "pot" for vnd.ms-powerpoint
add("text/richtext", "rtx");
add("text/rtf", "rtf");
- add("text/texmacs", "ts");
add("text/text", "phps");
add("text/tab-separated-values", "tsv");
add("text/xml", "xml");
@@ -334,12 +345,15 @@ public final class MimeUtils {
add("text/x-vcard", "vcf");
add("video/3gpp", "3gpp");
add("video/3gpp", "3gp");
- add("video/3gpp", "3g2");
+ add("video/3gpp2", "3gpp2");
+ add("video/3gpp2", "3g2");
+ add("video/avi", "avi");
add("video/dl", "dl");
add("video/dv", "dif");
add("video/dv", "dv");
add("video/fli", "fli");
add("video/m4v", "m4v");
+ add("video/mp2ts", "ts");
add("video/mpeg", "mpeg");
add("video/mpeg", "mpg");
add("video/mpeg", "mpe");
@@ -348,8 +362,10 @@ public final class MimeUtils {
add("video/quicktime", "qt");
add("video/quicktime", "mov");
add("video/vnd.mpegurl", "mxu");
+ add("video/webm", "webm");
add("video/x-la-asf", "lsf");
add("video/x-la-asf", "lsx");
+ add("video/x-matroska", "mkv");
add("video/x-mng", "mng");
add("video/x-ms-asf", "asf");
add("video/x-ms-asf", "asx");
@@ -357,7 +373,6 @@ public final class MimeUtils {
add("video/x-ms-wmv", "wmv");
add("video/x-ms-wmx", "wmx");
add("video/x-ms-wvx", "wvx");
- add("video/x-msvideo", "avi");
add("video/x-sgi-movie", "movie");
add("video/x-webex", "wrf");
add("x-conference/x-cooltalk", "ice");
@@ -366,18 +381,17 @@ public final class MimeUtils {
}
private static void add(String mimeType, String extension) {
- //
- // if we have an existing x --> y mapping, we do not want to
- // override it with another mapping x --> ?
- // this is mostly because of the way the mime-type map below
- // is constructed (if a mime type maps to several extensions
- // the first extension is considered the most popular and is
- // added first; we do not want to overwrite it later).
- //
+ // If we have an existing x -> y mapping, we do not want to
+ // override it with another mapping x -> y2.
+ // If a mime type maps to several extensions
+ // the first extension added is considered the most popular
+ // so we do not want to overwrite it later.
if (!mimeTypeToExtensionMap.containsKey(mimeType)) {
mimeTypeToExtensionMap.put(mimeType, extension);
}
- extensionToMimeTypeMap.put(extension, mimeType);
+ if (!extensionToMimeTypeMap.containsKey(extension)) {
+ extensionToMimeTypeMap.put(extension, mimeType);
+ }
}
private static InputStream getContentTypesPropertiesStream() {
diff --git a/luni/src/main/java/libcore/net/RawSocket.java b/luni/src/main/java/libcore/net/RawSocket.java
deleted file mode 100644
index 08a7d09..0000000
--- a/luni/src/main/java/libcore/net/RawSocket.java
+++ /dev/null
@@ -1,142 +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 libcore.net;
-
-import dalvik.system.CloseGuard;
-import java.io.Closeable;
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.net.SocketException;
-import java.util.Arrays;
-import libcore.io.IoBridge;
-
-/**
- * This class allows raw L2 packets to be sent and received via the
- * specified network interface. The receive-side implementation is
- * restricted to UDP packets for efficiency.
- *
- * @hide
- */
-public class RawSocket implements Closeable {
- /**
- * Ethernet IP protocol type, part of the L2 header of IP packets.
- */
- public static final short ETH_P_IP = (short) 0x0800;
-
- /**
- * Ethernet ARP protocol type, part of the L2 header of ARP packets.
- */
- public static final short ETH_P_ARP = (short) 0x0806;
-
- private static native void create(FileDescriptor fd, short
- protocolType, String interfaceName)
- throws SocketException;
- private static native int sendPacket(FileDescriptor fd,
- String interfaceName, short protocolType, byte[] destMac, byte[] packet,
- int offset, int byteCount);
- private static native int recvPacket(FileDescriptor fd, byte[] packet,
- int offset, int byteCount, int destPort, int timeoutMillis);
-
- private final FileDescriptor fd;
- private final String mInterfaceName;
- private final short mProtocolType;
- private final CloseGuard guard = CloseGuard.get();
-
- /**
- * Creates a socket on the specified interface.
- */
- public RawSocket(String interfaceName, short protocolType)
- throws SocketException {
- mInterfaceName = interfaceName;
- mProtocolType = protocolType;
- fd = new FileDescriptor();
- create(fd, mProtocolType, mInterfaceName);
- guard.open("close");
- }
-
- /**
- * Reads a raw packet into the specified buffer, with the
- * specified timeout. If the destPort is -1, then the IP
- * destination port is not verified, otherwise only packets
- * destined for the specified UDP port are returned. Returns the
- * length actually read. No indication of overflow is signaled.
- * The packet data will start at the IP header (EthernetII
- * dest/source/type headers are removed).
- */
- public int read(byte[] packet, int offset, int byteCount, int destPort,
- int timeoutMillis) {
- if (packet == null) {
- throw new NullPointerException("packet == null");
- }
-
- Arrays.checkOffsetAndCount(packet.length, offset, byteCount);
-
- if (destPort > 65535) {
- throw new IllegalArgumentException("Port out of range: "
- + destPort);
- }
-
- return recvPacket(fd, packet, offset, byteCount, destPort,
- timeoutMillis);
- }
-
- /**
- * Writes a raw packet to the desired interface. A L2 header will
- * be added which includes the specified destination address, our
- * source MAC, and the specified protocol type. The caller is responsible
- * for computing correct IP-header and payload checksums.
- */
- public int write(byte[] destMac, byte[] packet, int offset, int byteCount) {
- if (destMac == null) {
- throw new NullPointerException("destMac == null");
- }
-
- if (packet == null) {
- throw new NullPointerException("packet == null");
- }
-
- Arrays.checkOffsetAndCount(packet.length, offset, byteCount);
-
- if (destMac.length != 6) {
- throw new IllegalArgumentException("MAC length must be 6: "
- + destMac.length);
- }
-
- return sendPacket(fd, mInterfaceName, mProtocolType, destMac, packet,
- offset, byteCount);
- }
-
- /**
- * Closes the socket. After this method is invoked, subsequent
- * read/write operations will fail.
- */
- public void close() throws IOException {
- guard.close();
- IoBridge.closeSocket(fd);
- }
-
- @Override protected void finalize() throws Throwable {
- try {
- if (guard != null) {
- guard.warnIfOpen();
- }
- close();
- } finally {
- super.finalize();
- }
- }
-}
diff --git a/luni/src/main/java/libcore/net/event/NetworkEventDispatcher.java b/luni/src/main/java/libcore/net/event/NetworkEventDispatcher.java
new file mode 100644
index 0000000..d1c7c21
--- /dev/null
+++ b/luni/src/main/java/libcore/net/event/NetworkEventDispatcher.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2014 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 libcore.net.event;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * A singleton used to dispatch network events to registered listeners.
+ */
+public class NetworkEventDispatcher {
+
+ private static final NetworkEventDispatcher instance = new NetworkEventDispatcher();
+
+ private final List<NetworkEventListener> listeners =
+ new CopyOnWriteArrayList<NetworkEventListener>();
+
+ /**
+ * Returns the shared {@link NetworkEventDispatcher} instance.
+ */
+ public static NetworkEventDispatcher getInstance() {
+ return instance;
+ }
+
+ /** Visible for testing. Use {@link #getInstance()} instead. */
+ protected NetworkEventDispatcher() {
+ }
+
+ /**
+ * Registers a listener to be notified when network events occur.
+ * It can be deregistered using {@link #removeListener(NetworkEventListener)}
+ */
+ public void addListener(NetworkEventListener toAdd) {
+ if (toAdd == null) {
+ throw new NullPointerException("toAdd == null");
+ }
+ listeners.add(toAdd);
+ }
+
+ /**
+ * De-registers a listener previously added with {@link #addListener(NetworkEventListener)}. If
+ * the listener was not previously registered this is a no-op.
+ */
+ public void removeListener(NetworkEventListener toRemove) {
+ for (NetworkEventListener listener : listeners) {
+ if (listener == toRemove) {
+ listeners.remove(listener);
+ return;
+ }
+ }
+ }
+
+ /**
+ * Notifies registered listeners of a network configuration change.
+ */
+ public void onNetworkConfigurationChanged() {
+ for (NetworkEventListener listener : listeners) {
+ try {
+ listener.onNetworkConfigurationChanged();
+ } catch (RuntimeException e) {
+ System.logI("Exception thrown during network event propagation", e);
+ }
+ }
+ }
+}
diff --git a/luni/src/main/java/libcore/net/event/NetworkEventListener.java b/luni/src/main/java/libcore/net/event/NetworkEventListener.java
new file mode 100644
index 0000000..73b9f88
--- /dev/null
+++ b/luni/src/main/java/libcore/net/event/NetworkEventListener.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2014 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 libcore.net.event;
+
+/**
+ * A base class for objects interested in network events.
+ */
+public class NetworkEventListener {
+
+ public void onNetworkConfigurationChanged() {
+ // no-op
+ }
+}
diff --git a/luni/src/main/java/libcore/net/url/FileURLConnection.java b/luni/src/main/java/libcore/net/url/FileURLConnection.java
index b4654cd..43eaa7d 100644
--- a/luni/src/main/java/libcore/net/url/FileURLConnection.java
+++ b/luni/src/main/java/libcore/net/url/FileURLConnection.java
@@ -28,6 +28,11 @@ import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
import libcore.net.UriCodec;
/**
@@ -38,17 +43,45 @@ import libcore.net.UriCodec;
*/
public class FileURLConnection extends URLConnection {
+ private static final Comparator<String> HEADER_COMPARATOR = new Comparator<String>() {
+ @Override
+ public int compare(String a, String b) {
+ if (a == b) {
+ return 0;
+ } else if (a == null) {
+ return -1;
+ } else if (b == null) {
+ return 1;
+ } else {
+ return String.CASE_INSENSITIVE_ORDER.compare(a, b);
+ }
+ }
+ };
+
private String filename;
private InputStream is;
- private int length = -1;
+ private long length = -1;
+
+ private long lastModified = -1;
private boolean isDir;
private FilePermission permission;
/**
+ * A set of three key value pairs representing the headers we support.
+ */
+ private final String[] headerKeysAndValues;
+
+ private static final int CONTENT_TYPE_VALUE_IDX = 1;
+ private static final int CONTENT_LENGTH_VALUE_IDX = 3;
+ private static final int LAST_MODIFIED_VALUE_IDX = 5;
+
+ private Map<String, List<String>> headerFields;
+
+ /**
* Creates an instance of <code>FileURLConnection</code> for establishing
* a connection to the file pointed by this <code>URL<code>
*
@@ -61,6 +94,10 @@ public class FileURLConnection extends URLConnection {
filename = "";
}
filename = UriCodec.decode(filename);
+ headerKeysAndValues = new String[] {
+ "content-type", null,
+ "content-length", null,
+ "last-modified", null };
}
/**
@@ -74,27 +111,122 @@ public class FileURLConnection extends URLConnection {
@Override
public void connect() throws IOException {
File f = new File(filename);
+ IOException error = null;
if (f.isDirectory()) {
isDir = true;
is = getDirectoryListing(f);
// use -1 for the contentLength
+ lastModified = f.lastModified();
+ headerKeysAndValues[CONTENT_TYPE_VALUE_IDX] = "text/html";
} else {
- is = new BufferedInputStream(new FileInputStream(f));
- long lengthAsLong = f.length();
- length = lengthAsLong <= Integer.MAX_VALUE ? (int) lengthAsLong : Integer.MAX_VALUE;
+ try {
+ is = new BufferedInputStream(new FileInputStream(f));
+ } catch (IOException ioe) {
+ error = ioe;
+ }
+
+ if (error == null) {
+ length = f.length();
+ lastModified = f.lastModified();
+ headerKeysAndValues[CONTENT_TYPE_VALUE_IDX] = getContentTypeForPlainFiles();
+ } else {
+ headerKeysAndValues[CONTENT_TYPE_VALUE_IDX] = "content/unknown";
+ }
}
+
+ headerKeysAndValues[CONTENT_LENGTH_VALUE_IDX] = String.valueOf(length);
+ headerKeysAndValues[LAST_MODIFIED_VALUE_IDX] = String.valueOf(lastModified);
+
connected = true;
+ if (error != null) {
+ throw error;
+ }
+ }
+
+ @Override
+ public String getHeaderField(String key) {
+ if (!connected) {
+ try {
+ connect();
+ } catch (IOException ioe) {
+ return null;
+ }
+ }
+
+ for (int i = 0; i < headerKeysAndValues.length; i += 2) {
+ if (headerKeysAndValues[i].equalsIgnoreCase(key)) {
+ return headerKeysAndValues[i + 1];
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public String getHeaderFieldKey(int position) {
+ if (!connected) {
+ try {
+ connect();
+ } catch (IOException ioe) {
+ return null;
+ }
+ }
+
+ if (position < 0 || position > headerKeysAndValues.length / 2) {
+ return null;
+ }
+
+ return headerKeysAndValues[position * 2];
+ }
+
+ @Override
+ public String getHeaderField(int position) {
+ if (!connected) {
+ try {
+ connect();
+ } catch (IOException ioe) {
+ return null;
+ }
+ }
+
+ if (position < 0 || position > headerKeysAndValues.length / 2) {
+ return null;
+ }
+
+ return headerKeysAndValues[(position * 2) + 1];
+ }
+
+ @Override
+ public Map<String, List<String>> getHeaderFields() {
+ if (headerFields == null) {
+ final TreeMap<String, List<String>> headerFieldsMap = new TreeMap<>(HEADER_COMPARATOR);
+
+ for (int i = 0; i < headerKeysAndValues.length; i+=2) {
+ headerFieldsMap.put(headerKeysAndValues[i],
+ Collections.singletonList(headerKeysAndValues[i + 1]));
+ }
+
+ headerFields = Collections.unmodifiableMap(headerFieldsMap);
+ }
+
+ return headerFields;
}
/**
- * Returns the length of the file in bytes.
- *
- * @return the length of the file
- *
- * @see #getContentType()
+ * Returns the length of the file in bytes, or {@code -1} if the length cannot be
+ * represented as an {@code int}. See {@link #getContentLengthLong()} for a method that can
+ * handle larger files.
*/
@Override
public int getContentLength() {
+ long length = getContentLengthLong();
+ return length <= Integer.MAX_VALUE ? (int) length : -1;
+ }
+
+ /**
+ * Returns the length of the file in bytes.
+ */
+ private long getContentLengthLong() {
try {
if (!connected) {
connect();
@@ -113,16 +245,11 @@ public class FileURLConnection extends URLConnection {
*/
@Override
public String getContentType() {
- try {
- if (!connected) {
- connect();
- }
- } catch (IOException e) {
- return "content/unknown";
- }
- if (isDir) {
- return "text/plain";
- }
+ // The content-type header field is always at position 0.
+ return getHeaderField(0);
+ }
+
+ private String getContentTypeForPlainFiles() {
String result = guessContentTypeFromName(url.getFile());
if (result != null) {
return result;
diff --git a/luni/src/main/java/libcore/net/url/JarURLConnectionImpl.java b/luni/src/main/java/libcore/net/url/JarURLConnectionImpl.java
index 762f0e2..b01a20a 100644
--- a/luni/src/main/java/libcore/net/url/JarURLConnectionImpl.java
+++ b/luni/src/main/java/libcore/net/url/JarURLConnectionImpl.java
@@ -258,12 +258,10 @@ public class JarURLConnectionImpl extends JarURLConnection {
}
/**
- * Returns the content length of the resource. Test cases reveal that if the
- * URL is referring to a Jar file, this method answers a content-length
- * returned by URLConnection. For jar entry it should return it's size.
- * Otherwise, it will return -1.
- *
- * @return the content length
+ * Returns the content length of the resource. Test cases reveal that if the URL is referring to
+ * a Jar file, this method answers a content-length returned by URLConnection. For a jar entry
+ * it returns the entry's size if it can be represented as an {@code int}. Otherwise, it will
+ * return -1.
*/
@Override
public int getContentLength() {
diff --git a/luni/src/main/java/libcore/reflect/AnnotationAccess.java b/luni/src/main/java/libcore/reflect/AnnotationAccess.java
index 4e34284..2a72c18 100644
--- a/luni/src/main/java/libcore/reflect/AnnotationAccess.java
+++ b/luni/src/main/java/libcore/reflect/AnnotationAccess.java
@@ -16,7 +16,6 @@
package libcore.reflect;
-import com.android.dex.ClassDef;
import com.android.dex.Dex;
import com.android.dex.EncodedValueReader;
import com.android.dex.FieldId;
@@ -167,7 +166,7 @@ public final class AnnotationAccess {
*/
public static <A extends Annotation> A getDeclaredAnnotation(
AnnotatedElement element, Class<A> annotationClass) {
- com.android.dex.Annotation a = getMethodAnnotation(element, annotationClass);
+ com.android.dex.Annotation a = getAnnotation(element, annotationClass);
return a != null
? toAnnotationInstance(getDexClass(element), annotationClass, a)
: null;
@@ -178,29 +177,29 @@ public final class AnnotationAccess {
*/
public static boolean isDeclaredAnnotationPresent(
AnnotatedElement element, Class<? extends Annotation> annotationClass) {
- return getMethodAnnotation(element, annotationClass) != null;
+ return getAnnotation(element, annotationClass) != null;
}
- private static com.android.dex.Annotation getMethodAnnotation(
+ private static com.android.dex.Annotation getAnnotation(
AnnotatedElement element, Class<? extends Annotation> annotationClass) {
- Class<?> dexClass = getDexClass(element);
- Dex dex = dexClass.getDex();
- int annotationTypeIndex = getTypeIndex(dex, annotationClass);
- if (annotationTypeIndex == -1) {
- return null; // The dex file doesn't use this annotation.
- }
-
int annotationSetOffset = getAnnotationSetOffset(element);
if (annotationSetOffset == 0) {
return null; // no annotation
}
+ Class<?> dexClass = getDexClass(element);
+ Dex dex = dexClass.getDex();
Dex.Section setIn = dex.open(annotationSetOffset); // annotation_set_item
+ String annotationInternalName = InternalNames.getInternalName(annotationClass);
for (int i = 0, size = setIn.readInt(); i < size; i++) {
int annotationOffset = setIn.readInt();
Dex.Section annotationIn = dex.open(annotationOffset); // annotation_item
+ // The internal string name of the annotation is compared here and deliberately not
+ // the value of annotationClass.getTypeIndex(). The annotationClass may have been
+ // defined by a different dex file, which would make the indexes incomparable.
com.android.dex.Annotation candidate = annotationIn.readAnnotation();
- if (candidate.getTypeIndex() == annotationTypeIndex) {
+ String candidateInternalName = dex.typeNames().get(candidate.getTypeIndex());
+ if (candidateInternalName.equals(annotationInternalName)) {
return candidate;
}
}
@@ -228,19 +227,22 @@ public final class AnnotationAccess {
int methodsSize = directoryIn.readInt();
directoryIn.readInt(); // parameters size
- int fieldIndex = element instanceof Field ? ((Field) element).getDexFieldIndex() : -1;
- for (int i = 0; i < fieldsSize; i++) {
- int candidateFieldIndex = directoryIn.readInt();
- int annotationSetOffset = directoryIn.readInt();
- if (candidateFieldIndex == fieldIndex) {
- return annotationSetOffset;
- }
- }
- // we must read all fields prior to methods, if we were searching for a field then we missed
if (element instanceof Field) {
+ int fieldIndex = ((Field) element).getDexFieldIndex();
+ for (int i = 0; i < fieldsSize; i++) {
+ int candidateFieldIndex = directoryIn.readInt();
+ int annotationSetOffset = directoryIn.readInt();
+ if (candidateFieldIndex == fieldIndex) {
+ return annotationSetOffset;
+ }
+ }
+ // if we were searching for a field then we missed
return 0;
}
+ // Skip through the fields without reading them and look for constructors or methods.
+ directoryIn.skip(8 * fieldsSize);
+
int methodIndex= element instanceof Method ? ((Method) element).getDexMethodIndex()
: ((Constructor<?>) element).getDexMethodIndex();
for (int i = 0; i < methodsSize; i++) {
@@ -265,23 +267,6 @@ public final class AnnotationAccess {
: ((Member) element).getDeclaringClass();
}
- public static int getFieldIndex(Class<?> declaringClass, Class<?> type, String name) {
- Dex dex = declaringClass.getDex();
- int declaringClassIndex = getTypeIndex(dex, declaringClass);
- int typeIndex = getTypeIndex(dex, type);
- int nameIndex = dex.findStringIndex(name);
- FieldId fieldId = new FieldId(dex, declaringClassIndex, typeIndex, nameIndex);
- return dex.findFieldIndex(fieldId);
- }
-
- public static int getMethodIndex(Class<?> declaringClass, String name, int protoIndex) {
- Dex dex = declaringClass.getDex();
- int declaringClassIndex = getTypeIndex(dex, declaringClass);
- int nameIndex = dex.findStringIndex(name);
- MethodId methodId = new MethodId(dex, declaringClassIndex, protoIndex, nameIndex);
- return dex.findMethodIndex(methodId);
- }
-
/**
* Returns the parameter annotations on {@code member}.
*/
@@ -354,6 +339,8 @@ public final class AnnotationAccess {
*/
Class<?> annotationClass = method.getDeclaringClass();
+ // All lookups of type and string indexes are within the Dex that declares the annotation so
+ // the indexes can be compared directly.
Dex dex = annotationClass.getDex();
EncodedValueReader reader = getOnlyAnnotationValue(
dex, annotationClass, "Ldalvik/annotation/AnnotationDefault;");
@@ -362,7 +349,7 @@ public final class AnnotationAccess {
}
int fieldCount = reader.readAnnotation();
- if (reader.getAnnotationType() != getTypeIndex(dex, annotationClass)) {
+ if (reader.getAnnotationType() != annotationClass.getDexTypeIndex()) {
throw new AssertionError("annotation value type != annotation class");
}
@@ -384,7 +371,7 @@ public final class AnnotationAccess {
* Returns the class of which {@code c} is a direct member. If {@code c} is
* defined in a method or constructor, this is not transitive.
*/
- public static Class<?> getDeclaringClass(Class<?> c) {
+ public static Class<?> getEnclosingClass(Class<?> c) {
/*
* public class Bar {
* @EnclosingClass(value=Bar)
@@ -537,22 +524,6 @@ public final class AnnotationAccess {
* was derived.
*/
- /** Find dex's type index for the class c */
- private static int getTypeIndex(Dex dex, Class<?> c) {
- if (dex == c.getDex()) {
- return c.getDexTypeIndex();
- }
- if (dex == null) {
- return -1;
- }
- int typeIndex = dex.findTypeIndex(InternalNames.getInternalName(c));
- if (typeIndex < 0) {
- typeIndex = -1;
- }
- return typeIndex;
- }
-
-
private static EncodedValueReader getAnnotationReader(
Dex dex, AnnotatedElement element, String annotationName, int expectedFieldCount) {
int annotationSetOffset = getAnnotationSetOffset(element);
diff --git a/luni/src/main/java/libcore/reflect/GenericArrayTypeImpl.java b/luni/src/main/java/libcore/reflect/GenericArrayTypeImpl.java
index ef22576..5919a19 100644
--- a/luni/src/main/java/libcore/reflect/GenericArrayTypeImpl.java
+++ b/luni/src/main/java/libcore/reflect/GenericArrayTypeImpl.java
@@ -18,6 +18,7 @@ package libcore.reflect;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
+import java.util.Objects;
public final class GenericArrayTypeImpl implements GenericArrayType {
private final Type componentType;
@@ -34,6 +35,20 @@ public final class GenericArrayTypeImpl implements GenericArrayType {
}
}
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof GenericArrayType)) {
+ return false;
+ }
+ GenericArrayType that = (GenericArrayType) o;
+ return Objects.equals(getGenericComponentType(), that.getGenericComponentType());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(getGenericComponentType());
+ }
+
public String toString() {
return componentType.toString() + "[]";
}
diff --git a/luni/src/main/java/libcore/reflect/ParameterizedTypeImpl.java b/luni/src/main/java/libcore/reflect/ParameterizedTypeImpl.java
index 99dfe8b..2cd5ac3 100644
--- a/luni/src/main/java/libcore/reflect/ParameterizedTypeImpl.java
+++ b/luni/src/main/java/libcore/reflect/ParameterizedTypeImpl.java
@@ -18,17 +18,22 @@ package libcore.reflect;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import java.util.Arrays;
+import java.util.Objects;
public final class ParameterizedTypeImpl implements ParameterizedType {
private final ListOfTypes args;
private final ParameterizedTypeImpl ownerType0; // Potentially unresolved.
- private Type ownerTypeRes;
- private Class rawType; // Already resolved.
+ private Type ownerTypeRes; // Potentially unresolved.
+ private Class rawType; // Potentially unresolved.
private final String rawTypeName;
- private ClassLoader loader;
+ private final ClassLoader loader;
public ParameterizedTypeImpl(ParameterizedTypeImpl ownerType, String rawTypeName,
ListOfTypes args, ClassLoader loader) {
+ if (args == null) {
+ throw new NullPointerException();
+ }
this.ownerType0 = ownerType;
this.rawTypeName = rawTypeName;
this.args = args;
@@ -37,7 +42,6 @@ public final class ParameterizedTypeImpl implements ParameterizedType {
public Type[] getActualTypeArguments() {
- // ASSUMPTION: args is never null!!!
return args.getResolvedTypes().clone();
}
@@ -76,6 +80,23 @@ public final class ParameterizedTypeImpl implements ParameterizedType {
}
@Override
+ public boolean equals(Object o) {
+ if (!(o instanceof ParameterizedType)) {
+ return false;
+ }
+ ParameterizedType that = (ParameterizedType) o;
+ return Objects.equals(getRawType(), that.getRawType()) &&
+ Objects.equals(getOwnerType(), that.getOwnerType()) &&
+ Arrays.equals(args.getResolvedTypes(), that.getActualTypeArguments());
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * (31 * Objects.hashCode(getRawType()) + Objects.hashCode(getOwnerType())) +
+ Arrays.hashCode(args.getResolvedTypes());
+ }
+
+ @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(rawTypeName);
diff --git a/luni/src/main/java/libcore/util/EmptyArray.java b/luni/src/main/java/libcore/util/EmptyArray.java
index 1713bfc..eac06f2 100644
--- a/luni/src/main/java/libcore/util/EmptyArray.java
+++ b/luni/src/main/java/libcore/util/EmptyArray.java
@@ -23,7 +23,9 @@ public final class EmptyArray {
public static final byte[] BYTE = new byte[0];
public static final char[] CHAR = new char[0];
public static final double[] DOUBLE = new double[0];
+ public static final float[] FLOAT = new float[0];
public static final int[] INT = new int[0];
+ public static final long[] LONG = new long[0];
public static final Class<?>[] CLASS = new Class[0];
public static final Object[] OBJECT = new Object[0];
diff --git a/luni/src/main/java/libcore/util/ZoneInfo.java b/luni/src/main/java/libcore/util/ZoneInfo.java
index 54ee667..4d58d93 100644
--- a/luni/src/main/java/libcore/util/ZoneInfo.java
+++ b/luni/src/main/java/libcore/util/ZoneInfo.java
@@ -13,11 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+/*
+ * Elements of the WallTime class are a port of Bionic's localtime.c to Java. That code had the
+ * following header:
+ *
+ * This file is in the public domain, so clarified as of
+ * 1996-06-05 by Arthur David Olson.
+ */
package libcore.util;
import java.util.Arrays;
+import java.util.Calendar;
import java.util.Date;
+import java.util.GregorianCalendar;
import java.util.TimeZone;
import libcore.io.BufferIterator;
@@ -51,7 +59,7 @@ public final class ZoneInfo extends TimeZone {
private final byte[] mTypes;
private final byte[] mIsDsts;
- public static TimeZone makeTimeZone(String id, BufferIterator it) {
+ public static ZoneInfo makeTimeZone(String id, BufferIterator it) {
// Variable names beginning tzh_ correspond to those in "tzfile.h".
// Check tzh_magic.
@@ -148,22 +156,21 @@ public final class ZoneInfo extends TimeZone {
mOffsets[i] -= mRawOffset;
}
- // Is this zone still observing DST?
+ // Is this zone observing DST currently or in the future?
// We don't care if they've historically used it: most places have at least once.
- // We want to know whether the last "schedule info" (the unix times in the mTransitions
- // array) is in the future. If it is, DST is still relevant.
// See http://code.google.com/p/android/issues/detail?id=877.
// This test means that for somewhere like Morocco, which tried DST in 2009 but has
// no future plans (and thus no future schedule info) will report "true" from
// useDaylightTime at the start of 2009 but "false" at the end. This seems appropriate.
boolean usesDst = false;
- long currentUnixTime = System.currentTimeMillis() / 1000;
- if (mTransitions.length > 0) {
- // (We're really dealing with uint32_t values, so long is most convenient in Java.)
- long latestScheduleTime = ((long) mTransitions[mTransitions.length - 1]) & 0xffffffff;
- if (currentUnixTime < latestScheduleTime) {
+ int currentUnixTimeSeconds = (int) (System.currentTimeMillis() / 1000);
+ int i = mTransitions.length - 1;
+ while (i >= 0 && mTransitions[i] >= currentUnixTimeSeconds) {
+ if (mIsDsts[mTypes[i]] > 0) {
usesDst = true;
+ break;
}
+ i--;
}
mUseDst = usesDst;
@@ -301,4 +308,670 @@ public final class ZoneInfo extends TimeZone {
",transitions=" + mTransitions.length +
"]";
}
+
+ @Override
+ public Object clone() {
+ // Overridden for documentation. The default clone() behavior is exactly what we want.
+ // Though mutable, the arrays of offset data are treated as immutable. Only ID and
+ // mRawOffset are mutable in this class, and those are an immutable object and a primitive
+ // respectively.
+ return super.clone();
+ }
+
+ /**
+ * A class that represents a "wall time". This class is modeled on the C tm struct and
+ * is used to support android.text.format.Time behavior. Unlike the tm struct the year is
+ * represented as the full year, not the years since 1900.
+ *
+ * <p>This class contains a rewrite of various native functions that android.text.format.Time
+ * once relied on such as mktime_tz and localtime_tz. This replacement does not support leap
+ * seconds but does try to preserve behavior around ambiguous date/times found in the BSD
+ * version of mktime that was previously used.
+ *
+ * <p>The original native code used a 32-bit value for time_t on 32-bit Android, which
+ * was the only variant of Android available at the time. To preserve old behavior this code
+ * deliberately uses {@code int} rather than {@code long} for most things and performs
+ * calculations in seconds. This creates deliberate truncation issues for date / times before
+ * 1901 and after 2038. This is intentional but might be fixed in future if all the knock-ons
+ * can be resolved: Application code may have come to rely on the range so previously values
+ * like zero for year could indicate an invalid date but if we move to long the year zero would
+ * be valid.
+ *
+ * <p>All offsets are considered to be safe for addition / subtraction / multiplication without
+ * worrying about overflow. All absolute time arithmetic is checked for overflow / underflow.
+ */
+ public static class WallTime {
+
+ // We use a GregorianCalendar (set to UTC) to handle all the date/time normalization logic
+ // and to convert from a broken-down date/time to a millis value.
+ // Unfortunately, it cannot represent an initial state with a zero day and would
+ // automatically normalize it, so we must copy values into and out of it as needed.
+ private final GregorianCalendar calendar;
+
+ private int year;
+ private int month;
+ private int monthDay;
+ private int hour;
+ private int minute;
+ private int second;
+ private int weekDay;
+ private int yearDay;
+ private int isDst;
+ private int gmtOffsetSeconds;
+
+ public WallTime() {
+ this.calendar = createGregorianCalendar();
+ calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ }
+
+ // LayoutLib replaces this method via bytecode manipulation, since the
+ // minimum-cost constructor is not available on host machines.
+ private static GregorianCalendar createGregorianCalendar() {
+ return new GregorianCalendar(false);
+ }
+
+ /**
+ * Sets the wall time to a point in time using the time zone information provided. This
+ * is a replacement for the old native localtime_tz() function.
+ *
+ * <p>When going from an instant to a wall time it is always unambiguous because there
+ * is only one offset rule acting at any given instant. We do not consider leap seconds.
+ */
+ public void localtime(int timeSeconds, ZoneInfo zoneInfo) {
+ try {
+ int offsetSeconds = zoneInfo.mRawOffset / 1000;
+
+ // Find out the timezone DST state and adjustment.
+ byte isDst;
+ if (zoneInfo.mTransitions.length == 0) {
+ isDst = 0;
+ } else {
+ // transitionIndex can be in the range -1..zoneInfo.mTransitions.length - 1
+ int transitionIndex = findTransitionIndex(zoneInfo, timeSeconds);
+ if (transitionIndex < 0) {
+ // -1 means timeSeconds is "before the first recorded transition". The first
+ // recorded transition is treated as a transition from non-DST and the raw
+ // offset.
+ isDst = 0;
+ } else {
+ byte transitionType = zoneInfo.mTypes[transitionIndex];
+ offsetSeconds += zoneInfo.mOffsets[transitionType];
+ isDst = zoneInfo.mIsDsts[transitionType];
+ }
+ }
+
+ // Perform arithmetic that might underflow before setting fields.
+ int wallTimeSeconds = checkedAdd(timeSeconds, offsetSeconds);
+
+ // Set fields.
+ calendar.setTimeInMillis(wallTimeSeconds * 1000L);
+ copyFieldsFromCalendar();
+ this.isDst = isDst;
+ this.gmtOffsetSeconds = offsetSeconds;
+ } catch (CheckedArithmeticException e) {
+ // Just stop, leaving fields untouched.
+ }
+ }
+
+ /**
+ * Returns the time in seconds since beginning of the Unix epoch for the wall time using the
+ * time zone information provided. This is a replacement for an old native mktime_tz() C
+ * function.
+ *
+ * <p>When going from a wall time to an instant the answer can be ambiguous. A wall
+ * time can map to zero, one or two instants given sane date/time transitions. Sane
+ * in this case means that transitions occur less frequently than the offset
+ * differences between them (which could cause all sorts of craziness like the
+ * skipping out of transitions).
+ *
+ * <p>For example, this is not fully supported:
+ * <ul>
+ * <li>t1 { time = 1, offset = 0 }
+ * <li>t2 { time = 2, offset = -1 }
+ * <li>t3 { time = 3, offset = -2 }
+ * </ul>
+ * A wall time in this case might map to t1, t2 or t3.
+ *
+ * <p>We do not handle leap seconds.
+ * <p>We assume that no timezone offset transition has an absolute offset > 24 hours.
+ * <p>We do not assume that adjacent transitions modify the DST state; adjustments can
+ * occur for other reasons such as when a zone changes its raw offset.
+ */
+ public int mktime(ZoneInfo zoneInfo) {
+ // Normalize isDst to -1, 0 or 1 to simplify isDst equality checks below.
+ this.isDst = this.isDst > 0 ? this.isDst = 1 : this.isDst < 0 ? this.isDst = -1 : 0;
+
+ copyFieldsToCalendar();
+ final long longWallTimeSeconds = calendar.getTimeInMillis() / 1000;
+ if (Integer.MIN_VALUE > longWallTimeSeconds
+ || longWallTimeSeconds > Integer.MAX_VALUE) {
+ // For compatibility with the old native 32-bit implementation we must treat
+ // this as an error. Note: -1 could be confused with a real time.
+ return -1;
+ }
+
+ try {
+ final int wallTimeSeconds = (int) longWallTimeSeconds;
+ final int rawOffsetSeconds = zoneInfo.mRawOffset / 1000;
+ final int rawTimeSeconds = checkedSubtract(wallTimeSeconds, rawOffsetSeconds);
+
+ if (zoneInfo.mTransitions.length == 0) {
+ // There is no transition information. There is just a raw offset for all time.
+ if (this.isDst > 0) {
+ // Caller has asserted DST, but there is no DST information available.
+ return -1;
+ }
+ copyFieldsFromCalendar();
+ this.isDst = 0;
+ this.gmtOffsetSeconds = rawOffsetSeconds;
+ return rawTimeSeconds;
+ }
+
+ // We cannot know for sure what instant the wall time will map to. Unfortunately, in
+ // order to know for sure we need the timezone information, but to get the timezone
+ // information we need an instant. To resolve this we use the raw offset to find an
+ // OffsetInterval; this will get us the OffsetInterval we need or very close.
+
+ // The initialTransition can be between -1 and (zoneInfo.mTransitions - 1). -1
+ // indicates the rawTime is before the first transition and is handled gracefully by
+ // createOffsetInterval().
+ final int initialTransitionIndex = findTransitionIndex(zoneInfo, rawTimeSeconds);
+
+ if (isDst < 0) {
+ // This is treated as a special case to get it out of the way:
+ // When a caller has set isDst == -1 it means we can return the first match for
+ // the wall time we find. If the caller has specified a wall time that cannot
+ // exist this always returns -1.
+
+ Integer result = doWallTimeSearch(zoneInfo, initialTransitionIndex,
+ wallTimeSeconds, true /* mustMatchDst */);
+ return result == null ? -1 : result;
+ }
+
+ // If the wall time asserts a DST (isDst == 0 or 1) the search is performed twice:
+ // 1) The first attempts to find a DST offset that matches isDst exactly.
+ // 2) If it fails, isDst is assumed to be incorrect and adjustments are made to see
+ // if a valid wall time can be created. The result can be somewhat arbitrary.
+
+ Integer result = doWallTimeSearch(zoneInfo, initialTransitionIndex, wallTimeSeconds,
+ true /* mustMatchDst */);
+ if (result == null) {
+ result = doWallTimeSearch(zoneInfo, initialTransitionIndex, wallTimeSeconds,
+ false /* mustMatchDst */);
+ }
+ if (result == null) {
+ result = -1;
+ }
+ return result;
+ } catch (CheckedArithmeticException e) {
+ return -1;
+ }
+ }
+
+ /**
+ * Attempt to apply DST adjustments to {@code oldWallTimeSeconds} to create a wall time in
+ * {@code targetInterval}.
+ *
+ * <p>This is used when a caller has made an assertion about standard time / DST that cannot
+ * be matched to any offset interval that exists. We must therefore assume that the isDst
+ * assertion is incorrect and the invalid wall time is the result of some modification the
+ * caller made to a valid wall time that pushed them outside of the offset interval they
+ * were in. We must correct for any DST change that should have been applied when they did
+ * so.
+ *
+ * <p>Unfortunately, we have no information about what adjustment they made and so cannot
+ * know which offset interval they were previously in. For example, they may have added a
+ * second or a year to a valid time to arrive at what they have.
+ *
+ * <p>We try all offset types that are not the same as the isDst the caller asserted. For
+ * each possible offset we work out the offset difference between that and
+ * {@code targetInterval}, apply it, and see if we are still in {@code targetInterval}. If
+ * we are, then we have found an adjustment.
+ */
+ private Integer tryOffsetAdjustments(ZoneInfo zoneInfo, int oldWallTimeSeconds,
+ OffsetInterval targetInterval, int transitionIndex, int isDstToFind)
+ throws CheckedArithmeticException {
+
+ int[] offsetsToTry = getOffsetsOfType(zoneInfo, transitionIndex, isDstToFind);
+ for (int j = 0; j < offsetsToTry.length; j++) {
+ int rawOffsetSeconds = zoneInfo.mRawOffset / 1000;
+ int jOffsetSeconds = rawOffsetSeconds + offsetsToTry[j];
+ int targetIntervalOffsetSeconds = targetInterval.getTotalOffsetSeconds();
+ int adjustmentSeconds = targetIntervalOffsetSeconds - jOffsetSeconds;
+ int adjustedWallTimeSeconds = checkedAdd(oldWallTimeSeconds, adjustmentSeconds);
+ if (targetInterval.containsWallTime(adjustedWallTimeSeconds)) {
+ // Perform any arithmetic that might overflow.
+ int returnValue = checkedSubtract(adjustedWallTimeSeconds,
+ targetIntervalOffsetSeconds);
+
+ // Modify field state and return the result.
+ calendar.setTimeInMillis(adjustedWallTimeSeconds * 1000L);
+ copyFieldsFromCalendar();
+ this.isDst = targetInterval.getIsDst();
+ this.gmtOffsetSeconds = targetIntervalOffsetSeconds;
+ return returnValue;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Return an array of offsets that have the requested {@code isDst} value.
+ * The {@code startIndex} is used as a starting point so transitions nearest
+ * to that index are returned first.
+ */
+ private static int[] getOffsetsOfType(ZoneInfo zoneInfo, int startIndex, int isDst) {
+ // +1 to account for the synthetic transition we invent before the first recorded one.
+ int[] offsets = new int[zoneInfo.mOffsets.length + 1];
+ boolean[] seen = new boolean[zoneInfo.mOffsets.length];
+ int numFound = 0;
+
+ int delta = 0;
+ boolean clampTop = false;
+ boolean clampBottom = false;
+ do {
+ // delta = { 1, -1, 2, -2, 3, -3...}
+ delta *= -1;
+ if (delta >= 0) {
+ delta++;
+ }
+
+ int transitionIndex = startIndex + delta;
+ if (delta < 0 && transitionIndex < -1) {
+ clampBottom = true;
+ continue;
+ } else if (delta > 0 && transitionIndex >= zoneInfo.mTypes.length) {
+ clampTop = true;
+ continue;
+ }
+
+ if (transitionIndex == -1) {
+ if (isDst == 0) {
+ // Synthesize a non-DST transition before the first transition we have
+ // data for.
+ offsets[numFound++] = 0; // offset of 0 from raw offset
+ }
+ continue;
+ }
+ byte type = zoneInfo.mTypes[transitionIndex];
+ if (!seen[type]) {
+ if (zoneInfo.mIsDsts[type] == isDst) {
+ offsets[numFound++] = zoneInfo.mOffsets[type];
+ }
+ seen[type] = true;
+ }
+ } while (!(clampTop && clampBottom));
+
+ int[] toReturn = new int[numFound];
+ System.arraycopy(offsets, 0, toReturn, 0, numFound);
+ return toReturn;
+ }
+
+ /**
+ * Find a time <em>in seconds</em> the same or close to {@code wallTimeSeconds} that
+ * satisfies {@code mustMatchDst}. The search begins around the timezone offset transition
+ * with {@code initialTransitionIndex}.
+ *
+ * <p>If {@code mustMatchDst} is {@code true} the method can only return times that
+ * use timezone offsets that satisfy the {@code this.isDst} requirements.
+ * If {@code this.isDst == -1} it means that any offset can be used.
+ *
+ * <p>If {@code mustMatchDst} is {@code false} any offset that covers the
+ * currently set time is acceptable. That is: if {@code this.isDst} == -1, any offset
+ * transition can be used, if it is 0 or 1 the offset used must match {@code this.isDst}.
+ *
+ * <p>Note: This method both uses and can modify field state. It returns the matching time
+ * in seconds if a match has been found and modifies fields, or it returns {@code null} and
+ * leaves the field state unmodified.
+ */
+ private Integer doWallTimeSearch(ZoneInfo zoneInfo, int initialTransitionIndex,
+ int wallTimeSeconds, boolean mustMatchDst) throws CheckedArithmeticException {
+
+ // The loop below starts at the initialTransitionIndex and radiates out from that point
+ // up to 24 hours in either direction by applying transitionIndexDelta to inspect
+ // adjacent transitions (0, -1, +1, -2, +2). 24 hours is used because we assume that no
+ // total offset from UTC is ever > 24 hours. clampTop and clampBottom are used to
+ // indicate whether the search has either searched > 24 hours or exhausted the
+ // transition data in that direction. The search stops when a match is found or if
+ // clampTop and clampBottom are both true.
+ // The match logic employed is determined by the mustMatchDst parameter.
+ final int MAX_SEARCH_SECONDS = 24 * 60 * 60;
+ boolean clampTop = false, clampBottom = false;
+ int loop = 0;
+ do {
+ // transitionIndexDelta = { 0, -1, 1, -2, 2,..}
+ int transitionIndexDelta = (loop + 1) / 2;
+ if (loop % 2 == 1) {
+ transitionIndexDelta *= -1;
+ }
+ loop++;
+
+ // Only do any work in this iteration if we need to.
+ if (transitionIndexDelta > 0 && clampTop
+ || transitionIndexDelta < 0 && clampBottom) {
+ continue;
+ }
+
+ // Obtain the OffsetInterval to use.
+ int currentTransitionIndex = initialTransitionIndex + transitionIndexDelta;
+ OffsetInterval offsetInterval =
+ OffsetInterval.create(zoneInfo, currentTransitionIndex);
+ if (offsetInterval == null) {
+ // No transition exists with the index we tried: Stop searching in the
+ // current direction.
+ clampTop |= (transitionIndexDelta > 0);
+ clampBottom |= (transitionIndexDelta < 0);
+ continue;
+ }
+
+ // Match the wallTimeSeconds against the OffsetInterval.
+ if (mustMatchDst) {
+ // Work out if the interval contains the wall time the caller specified and
+ // matches their isDst value.
+ if (offsetInterval.containsWallTime(wallTimeSeconds)) {
+ if (this.isDst == -1 || offsetInterval.getIsDst() == this.isDst) {
+ // This always returns the first OffsetInterval it finds that matches
+ // the wall time and isDst requirements. If this.isDst == -1 this means
+ // the result might be a DST or a non-DST answer for wall times that can
+ // exist in two OffsetIntervals.
+ int totalOffsetSeconds = offsetInterval.getTotalOffsetSeconds();
+ int returnValue = checkedSubtract(wallTimeSeconds,
+ totalOffsetSeconds);
+
+ copyFieldsFromCalendar();
+ this.isDst = offsetInterval.getIsDst();
+ this.gmtOffsetSeconds = totalOffsetSeconds;
+ return returnValue;
+ }
+ }
+ } else {
+ // To retain similar behavior to the old native implementation: if the caller is
+ // asserting the same isDst value as the OffsetInterval we are looking at we do
+ // not try to find an adjustment from another OffsetInterval of the same isDst
+ // type. If you remove this you get different results in situations like a
+ // DST -> DST transition or STD -> STD transition that results in an interval of
+ // "skipped" wall time. For example: if 01:30 (DST) is invalid and between two
+ // DST intervals, and the caller has passed isDst == 1, this results in a -1
+ // being returned.
+ if (isDst != offsetInterval.getIsDst()) {
+ final int isDstToFind = isDst;
+ Integer returnValue = tryOffsetAdjustments(zoneInfo, wallTimeSeconds,
+ offsetInterval, currentTransitionIndex, isDstToFind);
+ if (returnValue != null) {
+ return returnValue;
+ }
+ }
+ }
+
+ // See if we can avoid another loop in the current direction.
+ if (transitionIndexDelta > 0) {
+ // If we are searching forward and the OffsetInterval we have ends
+ // > MAX_SEARCH_SECONDS after the wall time, we don't need to look any further
+ // forward.
+ boolean endSearch = offsetInterval.getEndWallTimeSeconds() - wallTimeSeconds
+ > MAX_SEARCH_SECONDS;
+ if (endSearch) {
+ clampTop = true;
+ }
+ } else if (transitionIndexDelta < 0) {
+ boolean endSearch = wallTimeSeconds - offsetInterval.getStartWallTimeSeconds()
+ >= MAX_SEARCH_SECONDS;
+ if (endSearch) {
+ // If we are searching backward and the OffsetInterval starts
+ // > MAX_SEARCH_SECONDS before the wall time, we don't need to look any
+ // further backwards.
+ clampBottom = true;
+ }
+ }
+ } while (!(clampTop && clampBottom));
+ return null;
+ }
+
+ public void setYear(int year) {
+ this.year = year;
+ }
+
+ public void setMonth(int month) {
+ this.month = month;
+ }
+
+ public void setMonthDay(int monthDay) {
+ this.monthDay = monthDay;
+ }
+
+ public void setHour(int hour) {
+ this.hour = hour;
+ }
+
+ public void setMinute(int minute) {
+ this.minute = minute;
+ }
+
+ public void setSecond(int second) {
+ this.second = second;
+ }
+
+ public void setWeekDay(int weekDay) {
+ this.weekDay = weekDay;
+ }
+
+ public void setYearDay(int yearDay) {
+ this.yearDay = yearDay;
+ }
+
+ public void setIsDst(int isDst) {
+ this.isDst = isDst;
+ }
+
+ public void setGmtOffset(int gmtoff) {
+ this.gmtOffsetSeconds = gmtoff;
+ }
+
+ public int getYear() {
+ return year;
+ }
+
+ public int getMonth() {
+ return month;
+ }
+
+ public int getMonthDay() {
+ return monthDay;
+ }
+
+ public int getHour() {
+ return hour;
+ }
+
+ public int getMinute() {
+ return minute;
+ }
+
+ public int getSecond() {
+ return second;
+ }
+
+ public int getWeekDay() {
+ return weekDay;
+ }
+
+ public int getYearDay() {
+ return yearDay;
+ }
+
+ public int getGmtOffset() {
+ return gmtOffsetSeconds;
+ }
+
+ public int getIsDst() {
+ return isDst;
+ }
+
+ private void copyFieldsToCalendar() {
+ calendar.set(Calendar.YEAR, year);
+ calendar.set(Calendar.MONTH, month);
+ calendar.set(Calendar.DAY_OF_MONTH, monthDay);
+ calendar.set(Calendar.HOUR_OF_DAY, hour);
+ calendar.set(Calendar.MINUTE, minute);
+ calendar.set(Calendar.SECOND, second);
+ }
+
+ private void copyFieldsFromCalendar() {
+ year = calendar.get(Calendar.YEAR);
+ month = calendar.get(Calendar.MONTH);
+ monthDay = calendar.get(Calendar.DAY_OF_MONTH);
+ hour = calendar.get(Calendar.HOUR_OF_DAY);
+ minute = calendar.get(Calendar.MINUTE);
+ second = calendar.get(Calendar.SECOND);
+
+ // Calendar uses Sunday == 1. Android Time uses Sunday = 0.
+ weekDay = calendar.get(Calendar.DAY_OF_WEEK) - 1;
+ // Calendar enumerates from 1, Android Time enumerates from 0.
+ yearDay = calendar.get(Calendar.DAY_OF_YEAR) - 1;
+ }
+
+ /**
+ * Find the transition in the {@code timezone} in effect at {@code timeSeconds}.
+ *
+ * <p>Returns an index in the range -1..timeZone.mTransitions.length - 1. -1 is used to
+ * indicate the time is before the first transition. Other values are an index into
+ * timeZone.mTransitions.
+ */
+ private static int findTransitionIndex(ZoneInfo timeZone, int timeSeconds) {
+ int matchingRawTransition = Arrays.binarySearch(timeZone.mTransitions, timeSeconds);
+ if (matchingRawTransition < 0) {
+ matchingRawTransition = ~matchingRawTransition - 1;
+ }
+ return matchingRawTransition;
+ }
+ }
+
+ /**
+ * A wall-time representation of a timezone offset interval.
+ *
+ * <p>Wall-time means "as it would appear locally in the timezone in which it applies".
+ * For example in 2007:
+ * PST was a -8:00 offset that ran until Mar 11, 2:00 AM.
+ * PDT was a -7:00 offset and ran from Mar 11, 3:00 AM to Nov 4, 2:00 AM.
+ * PST was a -8:00 offset and ran from Nov 4, 1:00 AM.
+ * Crucially this means that there was a "gap" after PST when PDT started, and an overlap when
+ * PDT ended and PST began.
+ *
+ * <p>For convenience all wall-time values are represented as the number of seconds since the
+ * beginning of the Unix epoch <em>in UTC</em>. To convert from a wall-time to the actual time
+ * in the offset it is necessary to <em>subtract</em> the {@code totalOffsetSeconds}.
+ * For example: If the offset in PST is -07:00 hours, then:
+ * timeInPstSeconds = wallTimeUtcSeconds - offsetSeconds
+ * i.e. 13:00 UTC - (-07:00) = 20:00 UTC = 13:00 PST
+ */
+ static class OffsetInterval {
+
+ private final int startWallTimeSeconds;
+ private final int endWallTimeSeconds;
+ private final int isDst;
+ private final int totalOffsetSeconds;
+
+ /**
+ * Creates an {@link OffsetInterval}.
+ *
+ * <p>If {@code transitionIndex} is -1, the transition is synthesized to be a non-DST offset
+ * that runs from the beginning of time until the first transition in {@code timeZone} and
+ * has an offset of {@code timezone.mRawOffset}. If {@code transitionIndex} is the last
+ * transition that transition is considered to run until the end of representable time.
+ * Otherwise, the information is extracted from {@code timeZone.mTransitions},
+ * {@code timeZone.mOffsets} an {@code timeZone.mIsDsts}.
+ */
+ public static OffsetInterval create(ZoneInfo timeZone, int transitionIndex)
+ throws CheckedArithmeticException {
+
+ if (transitionIndex < -1 || transitionIndex >= timeZone.mTransitions.length) {
+ return null;
+ }
+
+ int rawOffsetSeconds = timeZone.mRawOffset / 1000;
+ if (transitionIndex == -1) {
+ int endWallTimeSeconds = checkedAdd(timeZone.mTransitions[0], rawOffsetSeconds);
+ return new OffsetInterval(Integer.MIN_VALUE, endWallTimeSeconds, 0 /* isDst */,
+ rawOffsetSeconds);
+ }
+
+ byte type = timeZone.mTypes[transitionIndex];
+ int totalOffsetSeconds = timeZone.mOffsets[type] + rawOffsetSeconds;
+ int endWallTimeSeconds;
+ if (transitionIndex == timeZone.mTransitions.length - 1) {
+ // If this is the last transition, make up the end time.
+ endWallTimeSeconds = Integer.MAX_VALUE;
+ } else {
+ endWallTimeSeconds = checkedAdd(timeZone.mTransitions[transitionIndex + 1],
+ totalOffsetSeconds);
+ }
+ int isDst = timeZone.mIsDsts[type];
+ int startWallTimeSeconds =
+ checkedAdd(timeZone.mTransitions[transitionIndex], totalOffsetSeconds);
+ return new OffsetInterval(
+ startWallTimeSeconds, endWallTimeSeconds, isDst, totalOffsetSeconds);
+ }
+
+ private OffsetInterval(int startWallTimeSeconds, int endWallTimeSeconds, int isDst,
+ int totalOffsetSeconds) {
+ this.startWallTimeSeconds = startWallTimeSeconds;
+ this.endWallTimeSeconds = endWallTimeSeconds;
+ this.isDst = isDst;
+ this.totalOffsetSeconds = totalOffsetSeconds;
+ }
+
+ public boolean containsWallTime(long wallTimeSeconds) {
+ return wallTimeSeconds >= startWallTimeSeconds && wallTimeSeconds < endWallTimeSeconds;
+ }
+
+ public int getIsDst() {
+ return isDst;
+ }
+
+ public int getTotalOffsetSeconds() {
+ return totalOffsetSeconds;
+ }
+
+ public long getEndWallTimeSeconds() {
+ return endWallTimeSeconds;
+ }
+
+ public long getStartWallTimeSeconds() {
+ return startWallTimeSeconds;
+ }
+ }
+
+ /**
+ * An exception used to indicate an arithmetic overflow or underflow.
+ */
+ private static class CheckedArithmeticException extends Exception {
+ }
+
+ /**
+ * Calculate (a + b).
+ *
+ * @throws CheckedArithmeticException if overflow or underflow occurs
+ */
+ private static int checkedAdd(int a, int b) throws CheckedArithmeticException {
+ // Adapted from Guava IntMath.checkedAdd();
+ long result = (long) a + b;
+ if (result != (int) result) {
+ throw new CheckedArithmeticException();
+ }
+ return (int) result;
+ }
+
+ /**
+ * Calculate (a - b).
+ *
+ * @throws CheckedArithmeticException if overflow or underflow occurs
+ */
+ private static int checkedSubtract(int a, int b) throws CheckedArithmeticException {
+ // Adapted from Guava IntMath.checkedSubtract();
+ long result = (long) a - b;
+ if (result != (int) result) {
+ throw new CheckedArithmeticException();
+ }
+ return (int) result;
+ }
}
diff --git a/luni/src/main/java/libcore/util/ZoneInfoDB.java b/luni/src/main/java/libcore/util/ZoneInfoDB.java
index 10e3900..a9d06a4 100644
--- a/luni/src/main/java/libcore/util/ZoneInfoDB.java
+++ b/luni/src/main/java/libcore/util/ZoneInfoDB.java
@@ -16,6 +16,7 @@
package libcore.util;
+import android.system.ErrnoException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
@@ -27,7 +28,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
import libcore.io.BufferIterator;
-import libcore.io.ErrnoException;
import libcore.io.IoUtils;
import libcore.io.MemoryMappedFile;
@@ -62,11 +62,33 @@ public final class ZoneInfoDB {
/**
* The 'ids' array contains time zone ids sorted alphabetically, for binary searching.
* The other two arrays are in the same order. 'byteOffsets' gives the byte offset
- * of each time zone, and 'rawUtcOffsets' gives the time zone's raw UTC offset.
+ * of each time zone, and 'rawUtcOffsetsCache' gives the time zone's raw UTC offset.
*/
private String[] ids;
private int[] byteOffsets;
- private int[] rawUtcOffsets;
+ private int[] rawUtcOffsetsCache; // Access this via getRawUtcOffsets instead.
+
+ /**
+ * ZoneInfo objects are worth caching because they are expensive to create.
+ * See http://b/8270865 for context.
+ */
+ private final static int CACHE_SIZE = 1;
+ private final BasicLruCache<String, ZoneInfo> cache =
+ new BasicLruCache<String, ZoneInfo>(CACHE_SIZE) {
+ @Override
+ protected ZoneInfo create(String id) {
+ // Work out where in the big data file this time zone is.
+ int index = Arrays.binarySearch(ids, id);
+ if (index < 0) {
+ return null;
+ }
+
+ BufferIterator it = mappedFile.bigEndianIterator();
+ it.skip(byteOffsets[index]);
+
+ return ZoneInfo.makeTimeZone(id, it);
+ }
+ };
public TzData(String... paths) {
for (String path : paths) {
@@ -82,7 +104,7 @@ public final class ZoneInfoDB {
version = "missing";
zoneTab = "# Emergency fallback data.\n";
ids = new String[] { "GMT" };
- byteOffsets = rawUtcOffsets = new int[1];
+ byteOffsets = rawUtcOffsetsCache = new int[1];
}
private boolean loadData(String path) {
@@ -149,7 +171,6 @@ public final class ZoneInfoDB {
int idOffset = 0;
byteOffsets = new int[entryCount];
- rawUtcOffsets = new int[entryCount];
for (int i = 0; i < entryCount; i++) {
it.readByteArray(idBytes, 0, idBytes.length);
@@ -161,7 +182,7 @@ public final class ZoneInfoDB {
if (length < 44) {
throw new AssertionError("length in index file < sizeof(tzhead)");
}
- rawUtcOffsets[i] = it.readInt();
+ it.skip(4); // Skip the unused 4 bytes that used to be the raw offset.
// Don't include null chars in the String
int len = idBytes.length;
@@ -188,16 +209,33 @@ public final class ZoneInfoDB {
return ids.clone();
}
- public String[] getAvailableIDs(int rawOffset) {
+ public String[] getAvailableIDs(int rawUtcOffset) {
List<String> matches = new ArrayList<String>();
- for (int i = 0, end = rawUtcOffsets.length; i < end; ++i) {
- if (rawUtcOffsets[i] == rawOffset) {
+ int[] rawUtcOffsets = getRawUtcOffsets();
+ for (int i = 0; i < rawUtcOffsets.length; ++i) {
+ if (rawUtcOffsets[i] == rawUtcOffset) {
matches.add(ids[i]);
}
}
return matches.toArray(new String[matches.size()]);
}
+ private synchronized int[] getRawUtcOffsets() {
+ if (rawUtcOffsetsCache != null) {
+ return rawUtcOffsetsCache;
+ }
+ rawUtcOffsetsCache = new int[ids.length];
+ for (int i = 0; i < ids.length; ++i) {
+ // This creates a TimeZone, which is quite expensive. Hence the cache.
+ // Note that icu4c does the same (without the cache), so if you're
+ // switching this code over to icu4j you should check its performance.
+ // Telephony shouldn't care, but someone converting a bunch of calendar
+ // events might.
+ rawUtcOffsetsCache[i] = cache.get(ids[i]).getRawOffset();
+ }
+ return rawUtcOffsetsCache;
+ }
+
public String getVersion() {
return version;
}
@@ -206,17 +244,10 @@ public final class ZoneInfoDB {
return zoneTab;
}
- public TimeZone makeTimeZone(String id) throws IOException {
- // Work out where in the big data file this time zone is.
- int index = Arrays.binarySearch(ids, id);
- if (index < 0) {
- return null;
- }
-
- BufferIterator it = mappedFile.bigEndianIterator();
- it.skip(byteOffsets[index]);
-
- return ZoneInfo.makeTimeZone(id, it);
+ public ZoneInfo makeTimeZone(String id) throws IOException {
+ ZoneInfo zoneInfo = cache.get(id);
+ // The object from the cache is cloned because TimeZone / ZoneInfo are mutable.
+ return zoneInfo == null ? null : (ZoneInfo) zoneInfo.clone();
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java b/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java
index f1dd43c..855a8c7 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java
@@ -24,15 +24,15 @@ package org.apache.harmony.security.fortress;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
+import java.util.ArrayList;
import java.util.Locale;
-
/**
* This class implements common functionality for Provider supplied
* classes. The usage pattern is to allocate static Engine instance
* per service type and synchronize on that instance during calls to
- * {@code getInstance} and retreival of the selected {@code Provider}
- * and Service Provider Interface (SPI) results. Retreiving the
+ * {@code getInstance} and retrieval of the selected {@code Provider}
+ * and Service Provider Interface (SPI) results. Retrieving the
* results with {@code getProvider} and {@code getSpi} sets the
* internal {@code Engine} values to null to prevent memory leaks.
*
@@ -69,7 +69,7 @@ import java.util.Locale;
*
* }</pre>
*/
-public class Engine {
+public final class Engine {
/**
* Access to package visible api in java.security
@@ -95,14 +95,14 @@ public class Engine {
/** used to test for cache validity */
private final int cacheVersion;
/** cached result */
- private final Provider.Service service;
+ private final ArrayList<Provider.Service> services;
private ServiceCacheEntry(String algorithm,
int cacheVersion,
- Provider.Service service) {
+ ArrayList<Provider.Service> services) {
this.algorithm = algorithm;
this.cacheVersion = cacheVersion;
- this.service = service;
+ this.services = services;
}
}
@@ -118,47 +118,60 @@ public class Engine {
/**
* Creates a Engine object
*
- * @param service
+ * @param serviceName
*/
- public Engine(String service) {
- this.serviceName = service;
+ public Engine(String serviceName) {
+ this.serviceName = serviceName;
}
/**
* Finds the appropriate service implementation and returns an
- * {@code SpiAndProvider} instance containing a reference to SPI
- * and its {@code Provider}
+ * {@code SpiAndProvider} instance containing a reference to the first
+ * matching SPI and its {@code Provider}
*/
public SpiAndProvider getInstance(String algorithm, Object param)
throws NoSuchAlgorithmException {
if (algorithm == null) {
throw new NoSuchAlgorithmException("Null algorithm name");
}
+ ArrayList<Provider.Service> services = getServices(algorithm);
+ if (services == null) {
+ throw notFound(this.serviceName, algorithm);
+ }
+ return new SpiAndProvider(services.get(0).newInstance(param), services.get(0).getProvider());
+ }
+
+ /**
+ * Finds the appropriate service implementation and returns an
+ * {@code SpiAndProvider} instance containing a reference to SPI
+ * and its {@code Provider}
+ */
+ public SpiAndProvider getInstance(Provider.Service service, String param)
+ throws NoSuchAlgorithmException {
+ return new SpiAndProvider(service.newInstance(param), service.getProvider());
+ }
+
+ /**
+ * Returns a list of all possible matches for a given algorithm.
+ */
+ public ArrayList<Provider.Service> getServices(String algorithm) {
int newCacheVersion = Services.getCacheVersion();
- Provider.Service service;
ServiceCacheEntry cacheEntry = this.serviceCache;
+ final String algoUC = algorithm.toUpperCase(Locale.US);
if (cacheEntry != null
- && cacheEntry.algorithm.equalsIgnoreCase(algorithm)
+ && cacheEntry.algorithm.equalsIgnoreCase(algoUC)
&& newCacheVersion == cacheEntry.cacheVersion) {
- service = cacheEntry.service;
- } else {
- if (Services.isEmpty()) {
- throw notFound(serviceName, algorithm);
- }
- String name = this.serviceName + "." + algorithm.toUpperCase(Locale.US);
- service = Services.getService(name);
- if (service == null) {
- throw notFound(serviceName, algorithm);
- }
- this.serviceCache = new ServiceCacheEntry(algorithm, newCacheVersion, service);
+ return cacheEntry.services;
}
- return new SpiAndProvider(service.newInstance(param), service.getProvider());
+ String name = this.serviceName + "." + algoUC;
+ ArrayList<Provider.Service> services = Services.getServices(name);
+ this.serviceCache = new ServiceCacheEntry(algoUC, newCacheVersion, services);
+ return services;
}
/**
- * Finds the appropriate service implementation and returns and
- * instance of the class that implements corresponding Service
- * Provider Interface.
+ * Finds the appropriate service implementation and returns and instance of
+ * the class that implements corresponding Service Provider Interface.
*/
public Object getInstance(String algorithm, Provider provider, Object param)
throws NoSuchAlgorithmException {
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/Services.java b/luni/src/main/java/org/apache/harmony/security/fortress/Services.java
index 4fe0d44..30f4839 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/Services.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/Services.java
@@ -21,9 +21,7 @@ import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.Locale;
-import java.util.Map;
/**
@@ -38,8 +36,8 @@ public class Services {
* Set the initial size to 600 so we don't grow to 1024 by default because
* initialization adds a few entries more than the growth threshold.
*/
- private static final Map<String, Provider.Service> services
- = new HashMap<String, Provider.Service>(600);
+ private static final HashMap<String, ArrayList<Provider.Service>> services
+ = new HashMap<String, ArrayList<Provider.Service>>(600);
/**
* Save default SecureRandom service as well.
@@ -62,12 +60,13 @@ public class Services {
/**
* Registered providers.
*/
- private static final List<Provider> providers = new ArrayList<Provider>(20);
+ private static final ArrayList<Provider> providers = new ArrayList<Provider>(20);
/**
* Hash for quick provider access by name.
*/
- private static final Map<String, Provider> providersNames = new HashMap<String, Provider>(20);
+ private static final HashMap<String, Provider> providersNames
+ = new HashMap<String, Provider>(20);
static {
String providerClassName = null;
int i = 1;
@@ -75,7 +74,7 @@ public class Services {
while ((providerClassName = Security.getProperty("security.provider." + i++)) != null) {
try {
- Class providerClass = Class.forName(providerClassName.trim(), true, cl);
+ Class<?> providerClass = Class.forName(providerClassName.trim(), true, cl);
Provider p = (Provider) providerClass.newInstance();
providers.add(p);
providersNames.put(p.getName(), p);
@@ -91,15 +90,8 @@ public class Services {
/**
* Returns a copy of the registered providers as an array.
*/
- public static synchronized Provider[] getProviders() {
- return providers.toArray(new Provider[providers.size()]);
- }
-
- /**
- * Returns a copy of the registered providers as a list.
- */
- public static synchronized List<Provider> getProvidersList() {
- return new ArrayList<Provider>(providers);
+ public static synchronized ArrayList<Provider> getProviders() {
+ return providers;
}
/**
@@ -145,20 +137,28 @@ public class Services {
cachedSecureRandomService = service;
}
String key = type + "." + service.getAlgorithm().toUpperCase(Locale.US);
- if (!services.containsKey(key)) {
- services.put(key, service);
- }
+ appendServiceLocked(key, service);
for (String alias : Engine.door.getAliases(service)) {
key = type + "." + alias.toUpperCase(Locale.US);
- if (!services.containsKey(key)) {
- services.put(key, service);
- }
+ appendServiceLocked(key, service);
}
}
}
/**
- * Returns true if services contain any provider information.
+ * Add or append the service to the key.
+ */
+ private static void appendServiceLocked(String key, Provider.Service service) {
+ ArrayList<Provider.Service> serviceList = services.get(key);
+ if (serviceList == null) {
+ serviceList = new ArrayList<Provider.Service>(1);
+ services.put(key, serviceList);
+ }
+ serviceList.add(service);
+ }
+
+ /**
+ * Returns true if services does not contain any provider information.
*/
public static synchronized boolean isEmpty() {
return services.isEmpty();
@@ -174,7 +174,7 @@ public class Services {
* caches should be validated against the result of
* Service.getCacheVersion() before use.
*/
- public static synchronized Provider.Service getService(String key) {
+ public static synchronized ArrayList<Provider.Service> getServices(String key) {
return services.get(key);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java
deleted file mode 100644
index a2c5b4c..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.util.Arrays;
-
-/**
- * The caching mechanism designed to speed up the process
- * of Certificates/CRLs generation in the case of their repeated
- * generation.
- *
- * It keeps correspondences between Objects (Certificates or CLRs)
- * and arrays of bytes on the base of which the Objects have been generated,
- * and provides the means to determine whether it contains the object built on
- * the base of particular encoded form or not. If there are such
- * objects they are returned from the cache, if not - newly generated
- * objects can be saved in the cache.<br>
- *
- * The process of Certificate/CRL generation
- * (implemented in <code>X509CertFactoryImpl</code>) is accompanied with
- * prereading of the beginning of encoded form. This prefix is used to determine
- * whether provided form is PEM encoding or not.<br>
- *
- * So the use of the prefix is the first point to (approximately)
- * determine whether object to be generated is in the cache or not.
- *
- * The failure of the predetermination process tells us that there were not
- * object generated from the encoded form with such prefix and we should
- * generate (decode) the object. If predetermination is successful,
- * we conduct the accurate search on the base of whole encoded form. <br>
- *
- * So to speed up the object generation process this caching mechanism provides
- * the following functionality:<br>
- *
- * 1. With having of the beginning of the encoded form (prefix)
- * it is possible to predetermine whether object has already been
- * generated on the base of the encoding with the SIMILAR prefix or not.
- * This process is not computationally expensive and takes a little time.
- * But it prevents us from use of expensive full encoding
- * search in the case of its failure.<br>
- *
- * 2. If predetermination ends with success, the whole encoding
- * form should be provided to make the final answer: whether object has
- * already been generated on the base of this PARTICULAR encoded form or not.
- * If it is so - the cached object is returned from the cache,
- * if not - new object should be generated and saved in the cache.<br>
- *
- * Note: The length of the prefixes of the encoded forms should not be
- * less than correspondence (default value is 28).
- */
-public class Cache {
-
- // Hash code consist of 6 bytes: AABB00
- // where:
- // AA - 2 bytes for prefix hash
- // value generated on the base of the prefix of encoding
- // BB - 2 bytes for tail hash
- // value generated on the base of the tail of encoding
- // 00 - 2 reserved bytes equals to 0
- //
- // Note, that it is possible for 2 different arrays to have
- // the similar hash codes.
-
- // The masks to work with hash codes:
- // the hash code without the reserved bytes
- private static final long HASH_MASK = 0xFFFFFFFFFFFF0000L;
- // the hash code of the prefix
- private static final long PREFIX_HASH_MASK = 0xFFFFFFFF00000000L;
- // the index value contained in reserved bytes
- private static final int INDEX_MASK = 0x00FFFF;
-
- // size of the cache
- private final int cache_size;
- // the number of bytes which will be used for array hash generation.
- private final int prefix_size;
-
- // The following 3 arrays contain the information about cached objects.
- // This information includes: hash of the array, encoded form of the object,
- // and the object itself.
- // The hash-encoding-object correspondence is made by means of index
- // in the particular array. I.e. for index N hash contained in hashes[N]
- // corresponds to the encoding contained in encodings[N] which corresponds
- // to the object cached at cache[N]
-
- // array containing the hash codes of encodings
- private final long[] hashes;
- // array containing the encodings of the cached objects
- private final byte[][] encodings;
- // array containing the cached objects
- private final Object[] cache;
-
- // This array is used to speed up the process of the search in the cache.
- // This is an ordered array of the hash codes from 'hashes' array (described
- // above) with last 2 (reserved) bytes equals to the index of
- // the hash in the 'hashes' array. I.e. hash code ABCD00 with index 10 in
- // the hashes array will be represented in this array as ABCD0A (10==0x0A)
- // So this array contains ordered <hash to index> correspondences.
- // Note, that every item in this array is unique.
- private final long[] hashes_idx;
-
- // the index of the last cached object
- private int last_cached = 0;
- // cache population indicator
- private boolean cache_is_full = false;
-
- /**
- * Creates the Cache object.
- * @param pref_size specifies how many leading/trailing bytes of object's
- * encoded form will be used for hash computation
- * @param size capacity of the cache to be created.
- */
- public Cache(int pref_size, int size) {
- cache_size = size;
- prefix_size = pref_size;
- hashes = new long[cache_size];
- hashes_idx = new long[cache_size];
- encodings = new byte[cache_size][];
- cache = new Object[cache_size];
- }
-
- /**
- * Creates the Cache object of size of 9.
- * @param pref_size specifies how many leading/trailing bytes of object's
- * encoded form will be used for hash computation
- */
- public Cache(int pref_size) {
- this(pref_size, 9);
- }
-
- /**
- * Creates the Cache object of size of 9.
- */
- public Cache() {
- this(28, 9);
- }
-
- /**
- * Returns the hash code for the array. This code is used to
- * predetermine whether the object was built on the base of the
- * similar encoding or not (by means of <code>contains(long)</code> method),
- * to exactly determine whether object is contained in the cache or not,
- * and to put the object in the cache.
- * Note: parameter array should be of length not less than
- * specified by <code>prefix_size</code> (default 28)
- * @param arr the byte array containing at least prefix_size leading bytes
- * of the encoding.
- * @return hash code for specified encoding prefix
- */
- public long getHash(byte[] arr) {
- long hash = 0;
- for (int i=1; i<prefix_size; i++) {
- hash += (arr[i] & 0xFF);
- } // it takes about 2 bytes for prefix_size == 28
-
- // shift to the correct place
- hash = hash << 32;
- return hash;
- }
-
- /**
- * Checks if there are any object in the cache generated
- * on the base of encoding with prefix corresponding
- * to the specified hash code.
- * @param prefix_hash the hash code for the prefix
- * of the encoding (retrieved by method <code>getHash(byte[]))</code>
- * @return false if there were not any object generated
- * on the base of encoding with specified hash code, true
- * otherwise.
- */
- public boolean contains(long prefix_hash) {
- if (prefix_hash == 0) {
- return false;
- }
- int idx = -1*Arrays.binarySearch(hashes_idx, prefix_hash)-1;
- if (idx == cache_size) {
- return false;
- } else {
- return (hashes_idx[idx] & PREFIX_HASH_MASK) == prefix_hash;
- }
- }
-
- /**
- * Returns the object built on the base on the specified encoded
- * form if it is contained in the cache and null otherwise.
- * This method is computationally expensive and should be called only if
- * the method <code>contains(long)</code> for the hash code returned true.
- * @param hash the hash code for the prefix of the encoding
- * (retrieved by method <code>getHash(byte[])</code>)
- * @param encoding encoded form of the required object.
- * @return the object corresponding to specified encoding or null if
- * there is no such correspondence.
- */
- public Object get(long hash, byte[] encoding) {
- hash |= getSuffHash(encoding);
- if (hash == 0) {
- return null;
- }
- int idx = -1*Arrays.binarySearch(hashes_idx, hash)-1;
- if (idx == cache_size) {
- return null;
- }
- while ((hashes_idx[idx] & HASH_MASK) == hash) {
- int i = (int) (hashes_idx[idx] & INDEX_MASK) - 1;
- if (Arrays.equals(encoding, encodings[i])) {
- return cache[i];
- }
- idx++;
- if (idx == cache_size) {
- return null;
- }
- }
- return null;
- }
-
- /**
- * Puts the object into the cache.
- * @param hash hash code for the prefix of the encoding
- * @param encoding the encoded form of the object
- * @param object the object to be saved in the cache
- */
- public void put(long hash, byte[] encoding, Object object) {
- // check for empty space in the cache
- if (last_cached == cache_size) {
- // so cache is full, will erase the first entry in the
- // cache (oldest entry). it could be better to throw out
- // rarely used value instead of oldest one..
- last_cached = 0;
- cache_is_full = true;
- }
- // index pointing to the item of the table to be overwritten
- int index = last_cached++;
-
- // improve the hash value with info from the tail of encoding
- hash |= getSuffHash(encoding);
-
- if (cache_is_full) {
- // indexing hash value to be overwritten:
- long idx_hash = (hashes[index] | (index+1));
- int idx = Arrays.binarySearch(hashes_idx, idx_hash);
- if (idx < 0) {
- // it will never happen because we use saved hash value
- // (hashes[index])
- System.out.println("WARNING! "+idx);
- idx = -(idx + 1);
- }
- long new_hash_idx = (hash | (index + 1));
- int new_idx = Arrays.binarySearch(hashes_idx, new_hash_idx);
- if (new_idx >= 0) {
- // it's possible when we write the same hash in the same cell
- if (idx != new_idx) {
- // it will never happen because we use the same
- // hash and the same index in hash table
- System.out.println("WARNING: ");
- System.out.println(">> idx: "+idx+" new_idx: "+new_idx);
- }
- } else {
- new_idx = -(new_idx + 1);
- // replace in sorted array
- if (new_idx > idx) {
- System.arraycopy(hashes_idx, idx+1, hashes_idx, idx,
- new_idx - idx - 1);
- hashes_idx[new_idx-1] = new_hash_idx;
- } else if (idx > new_idx) {
- System.arraycopy(hashes_idx, new_idx, hashes_idx, new_idx+1,
- idx - new_idx);
- hashes_idx[new_idx] = new_hash_idx;
- } else { // idx == new_idx
- hashes_idx[new_idx] = new_hash_idx;
- }
- }
- } else {
- long idx_hash = (hash | (index + 1));
- int idx = Arrays.binarySearch(hashes_idx, idx_hash);
- if (idx < 0) {
- // it will always be true because idx_hash depends on index
- idx = -(idx + 1);
- }
- idx = idx - 1;
- if (idx != cache_size - index - 1) {
- // if not in the cell containing 0 (free cell), do copy:
- System.arraycopy(hashes_idx, cache_size - index,
- hashes_idx, cache_size - index - 1,
- idx - (cache_size - index) + 1);
- }
- hashes_idx[idx] = idx_hash;
- }
- // overwrite the values in the tables:
- hashes[index] = hash;
- encodings[index] = encoding;
- cache[index] = object;
- }
-
- // Returns the hash code built on the base of the tail of the encoded form
- // @param arr - the array containing at least prefix_size trailing bytes
- // of encoded form
- private long getSuffHash(byte[] arr) {
- long hash_addon = 0;
- for (int i=arr.length-1; i>arr.length - prefix_size; i--) {
- hash_addon += (arr[i] & 0xFF);
- }
- return hash_addon << 16;
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
deleted file mode 100644
index 790be67..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
+++ /dev/null
@@ -1,44 +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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.security.Provider;
-
-public final class DRLCertFactory extends Provider {
- /**
- * @serial
- */
- private static final long serialVersionUID = -7269650779605195879L;
-
- /**
- * Constructs the instance of the certificate factory provider.
- */
- public DRLCertFactory() {
- // specification of the provider name, version, and description.
- super("DRLCertFactory", 1.0, "ASN.1, DER, PkiPath, PKCS7");
- // register the service
- put("CertificateFactory.X509", "org.apache.harmony.security.provider.cert.X509CertFactoryImpl");
- // mapping the alias
- put("Alg.Alias.CertificateFactory.X.509", "X509");
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java
deleted file mode 100644
index 38500e5..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLEntryImpl.java
+++ /dev/null
@@ -1,179 +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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.math.BigInteger;
-import java.security.cert.CRLException;
-import java.security.cert.X509CRLEntry;
-import java.util.Date;
-import java.util.Set;
-import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.x509.Extension;
-import org.apache.harmony.security.x509.Extensions;
-import org.apache.harmony.security.x509.TBSCertList;
-
-/**
- * Implementation of X509CRLEntry. It wraps the instance
- * of org.apache.harmony.security.x509.TBSCertList.RevokedCertificate
- * obtained during the decoding of TBSCertList substructure
- * of the CertificateList structure which is an X.509 form of CRL.
- * (see RFC 3280 at http://www.ietf.org/rfc/rfc3280.txt)
- * Normally the instances of this class are constructed by involving
- * X509CRLImpl object.
- * @see org.apache.harmony.security.x509.TBSCertList
- * @see org.apache.harmony.security.provider.cert.X509CRLImpl
- * @see java.security.cert.X509CRLEntry
- */
-public class X509CRLEntryImpl extends X509CRLEntry {
-
- // the crl entry object to be wrapped in X509CRLEntry
- private final TBSCertList.RevokedCertificate rcert;
- // the extensions of the entry
- private final Extensions extensions;
- // issuer of the revoked certificate described by this crl entry
- private final X500Principal issuer;
-
- // encoded form of this revoked certificate entry
- private byte[] encoding;
-
- /**
- * Creates an instance on the base of existing
- * <code>TBSCertList.RevokedCertificate</code> object and
- * information about the issuer of revoked certificate.
- * If specified issuer is null, it is supposed that issuer
- * of the revoked certificate is the same as for involving CRL.
- */
- public X509CRLEntryImpl(TBSCertList.RevokedCertificate rcert,
- X500Principal issuer) {
- this.rcert = rcert;
- this.extensions = rcert.getCrlEntryExtensions();
- this.issuer = issuer;
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.X509CRLEntry method implementations -------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509CRLEntry#getEncoded()
- * method documentation for more info
- */
- public byte[] getEncoded() throws CRLException {
- if (encoding == null) {
- encoding = rcert.getEncoded();
- }
- byte[] result = new byte[encoding.length];
- System.arraycopy(encoding, 0, result, 0, encoding.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#getSerialNumber()
- * method documentation for more info
- */
- public BigInteger getSerialNumber() {
- return rcert.getUserCertificate();
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#getCertificateIssuer()
- * method documentation for more info
- */
- public X500Principal getCertificateIssuer() {
- return issuer;
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#getRevocationDate()
- * method documentation for more info
- */
- public Date getRevocationDate() {
- return rcert.getRevocationDate();
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#hasExtensions()
- * method documentation for more info
- */
- public boolean hasExtensions() {
- return (extensions != null) && (extensions.size() != 0);
- }
-
- /**
- * @see java.security.cert.X509CRLEntry#toString()
- * method documentation for more info
- */
- public String toString() {
- return "X509CRLEntryImpl: "+rcert.toString();
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.X509Extension method implementations ------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509Extension#getNonCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getNonCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getNonCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getExtensionValue(String)
- * method documentation for more info
- */
- public byte[] getExtensionValue(String oid) {
- if (extensions == null) {
- return null;
- }
- Extension ext = extensions.getExtensionByOID(oid);
- return (ext == null) ? null : ext.getRawExtnValue();
- }
-
- /**
- * @see java.security.cert.X509Extension#hasUnsupportedCriticalExtension()
- * method documentation for more info
- */
- public boolean hasUnsupportedCriticalExtension() {
- if (extensions == null) {
- return false;
- }
- return extensions.hasUnsupportedCritical();
- }
-}
-
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java
deleted file mode 100644
index 68ec38a..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CRLImpl.java
+++ /dev/null
@@ -1,504 +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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Principal;
-import java.security.PublicKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.CRLException;
-import java.security.cert.Certificate;
-import java.security.cert.X509CRL;
-import java.security.cert.X509CRLEntry;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.CertificateList;
-import org.apache.harmony.security.x509.Extension;
-import org.apache.harmony.security.x509.Extensions;
-import org.apache.harmony.security.x509.TBSCertList;
-
-/**
- * This class is an implementation of X509CRL. It wraps
- * the instance of org.apache.harmony.security.x509.CertificateList
- * built on the base of provided ASN.1 DER encoded form of
- * CertificateList structure (as specified in RFC 3280
- * http://www.ietf.org/rfc/rfc3280.txt).
- * Implementation supports work with indirect CRLs.
- * @see org.apache.harmony.security.x509.CertificateList
- * @see java.security.cert.X509CRL
- */
-public class X509CRLImpl extends X509CRL {
-
- // the core object to be wrapped in X509CRL
- private final CertificateList crl;
-
- // To speed up access to the info, the following fields
- // cache values retrieved from the CertificateList object
- private final TBSCertList tbsCertList;
- private byte[] tbsCertListEncoding;
- private final Extensions extensions;
- private X500Principal issuer;
- private ArrayList entries;
- private int entriesSize;
- private byte[] signature;
- private String sigAlgOID;
- private String sigAlgName;
- private byte[] sigAlgParams;
-
- // encoded form of crl
- private byte[] encoding;
-
- // indicates whether the signature algorithm parameters are null
- private boolean nullSigAlgParams;
- // indicates whether the crl entries have already been retrieved
- // from CertificateList object (crl)
- private boolean entriesRetrieved;
-
- // indicates whether this X.509 CRL is direct or indirect
- // (see rfc 3280 http://www.ietf.org/rfc/rfc3280.txt, p 5.)
- private boolean isIndirectCRL;
- // if crl is indirect, this field holds an info about how
- // many of the leading certificates in the list are issued
- // by the same issuer as CRL.
- private int nonIndirectEntriesSize;
-
- /**
- * Creates X.509 CRL by wrapping of the specified CertificateList object.
- */
- public X509CRLImpl(CertificateList crl) {
- this.crl = crl;
- this.tbsCertList = crl.getTbsCertList();
- this.extensions = tbsCertList.getCrlExtensions();
- }
-
- /**
- * Creates X.509 CRL on the base of ASN.1 DER encoded form of
- * the CRL (CertificateList structure described in RFC 3280)
- * provided via input stream.
- * @throws CRLException if decoding errors occur.
- */
- public X509CRLImpl(InputStream in) throws CRLException {
- try {
- // decode CertificateList structure
- this.crl = (CertificateList) CertificateList.ASN1.decode(in);
- this.tbsCertList = crl.getTbsCertList();
- this.extensions = tbsCertList.getCrlExtensions();
- } catch (IOException e) {
- throw new CRLException(e);
- }
- }
-
- /**
- * Creates X.509 CRL on the base of ASN.1 DER encoded form of
- * the CRL (CertificateList structure described in RFC 3280)
- * provided via array of bytes.
- * @throws IOException if decoding errors occur.
- */
- public X509CRLImpl(byte[] encoding) throws IOException {
- this((CertificateList) CertificateList.ASN1.decode(encoding));
- }
-
- // ---------------------------------------------------------------------
- // ----- java.security.cert.X509CRL abstract method implementations ----
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509CRL#getEncoded()
- * method documentation for more info
- */
- public byte[] getEncoded() throws CRLException {
- if (encoding == null) {
- encoding = crl.getEncoded();
- }
- byte[] result = new byte[encoding.length];
- System.arraycopy(encoding, 0, result, 0, encoding.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRL#getVersion()
- * method documentation for more info
- */
- public int getVersion() {
- return tbsCertList.getVersion();
- }
-
- /**
- * @see java.security.cert.X509CRL#getIssuerDN()
- * method documentation for more info
- */
- public Principal getIssuerDN() {
- if (issuer == null) {
- issuer = tbsCertList.getIssuer().getX500Principal();
- }
- return issuer;
- }
-
- /**
- * @see java.security.cert.X509CRL#getIssuerX500Principal()
- * method documentation for more info
- */
- public X500Principal getIssuerX500Principal() {
- if (issuer == null) {
- issuer = tbsCertList.getIssuer().getX500Principal();
- }
- return issuer;
- }
-
- /**
- * @see java.security.cert.X509CRL#getThisUpdate()
- * method documentation for more info
- */
- public Date getThisUpdate() {
- return tbsCertList.getThisUpdate();
- }
-
- /**
- * @see java.security.cert.X509CRL#getNextUpdate()
- * method documentation for more info
- */
- public Date getNextUpdate() {
- return tbsCertList.getNextUpdate();
- }
-
- /*
- * Retrieves the crl entries (TBSCertList.RevokedCertificate objects)
- * from the TBSCertList structure and converts them to the
- * X509CRLEntryImpl objects
- */
- private void retrieveEntries() {
- entriesRetrieved = true;
- List rcerts = tbsCertList.getRevokedCertificates();
- if (rcerts == null) {
- return;
- }
- entriesSize = rcerts.size();
- entries = new ArrayList(entriesSize);
- // null means that revoked certificate issuer is the same as CRL issuer
- X500Principal rcertIssuer = null;
- for (int i=0; i<entriesSize; i++) {
- TBSCertList.RevokedCertificate rcert =
- (TBSCertList.RevokedCertificate) rcerts.get(i);
- X500Principal iss = rcert.getIssuer();
- if (iss != null) {
- // certificate issuer differs from CRL issuer
- // and CRL is indirect.
- rcertIssuer = iss;
- isIndirectCRL = true;
- // remember how many leading revoked certificates in the
- // list are issued by the same issuer as issuer of CRL
- // (these certificates are first in the list)
- nonIndirectEntriesSize = i;
- }
- entries.add(new X509CRLEntryImpl(rcert, rcertIssuer));
- }
- }
-
- /**
- * Searches for certificate in CRL.
- * This method supports indirect CRLs: if CRL is indirect method takes
- * into account serial number and issuer of the certificate,
- * if CRL issued by CA (i.e. it is not indirect) search is done only
- * by serial number of the specified certificate.
- * @see java.security.cert.X509CRL#getRevokedCertificate(X509Certificate)
- * method documentation for more info
- */
- public X509CRLEntry getRevokedCertificate(X509Certificate certificate) {
- if (certificate == null) {
- throw new NullPointerException("certificate == null");
- }
- if (!entriesRetrieved) {
- retrieveEntries();
- }
- if (entries == null) {
- return null;
- }
- BigInteger serialN = certificate.getSerialNumber();
- if (isIndirectCRL) {
- // search in indirect crl
- X500Principal certIssuer = certificate.getIssuerX500Principal();
- if (certIssuer.equals(getIssuerX500Principal())) {
- // certificate issuer is CRL issuer
- certIssuer = null;
- }
- for (int i=0; i<entriesSize; i++) {
- X509CRLEntry entry = (X509CRLEntry) entries.get(i);
- // check the serial number of revoked certificate
- if (serialN.equals(entry.getSerialNumber())) {
- // revoked certificate issuer
- X500Principal iss = entry.getCertificateIssuer();
- // check the issuer of revoked certificate
- if (certIssuer != null) {
- // certificate issuer is not a CRL issuer, so
- // check issuers for equality
- if (certIssuer.equals(iss)) {
- return entry;
- }
- } else if (iss == null) {
- // both certificates was issued by CRL issuer
- return entry;
- }
- }
- }
- } else {
- // search in CA's (non indirect) crl: just look up the serial number
- for (int i=0; i<entriesSize; i++) {
- X509CRLEntry entry = (X509CRLEntry) entries.get(i);
- if (serialN.equals(entry.getSerialNumber())) {
- return entry;
- }
- }
- }
- return null;
- }
-
- /**
- * Method searches for CRL entry with specified serial number.
- * The method will search only certificate issued by CRL's issuer.
- * @see java.security.cert.X509CRL#getRevokedCertificate(BigInteger)
- * method documentation for more info
- */
- public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) {
- if (!entriesRetrieved) {
- retrieveEntries();
- }
- if (entries == null) {
- return null;
- }
- for (int i=0; i<nonIndirectEntriesSize; i++) {
- X509CRLEntry entry = (X509CRLEntry) entries.get(i);
- if (serialNumber.equals(entry.getSerialNumber())) {
- return entry;
- }
- }
- return null;
- }
-
- /**
- * @see java.security.cert.X509CRL#getRevokedCertificates()
- * method documentation for more info
- */
- public Set<? extends X509CRLEntry> getRevokedCertificates() {
- if (!entriesRetrieved) {
- retrieveEntries();
- }
- if (entries == null) {
- return null;
- }
- return new HashSet(entries);
- }
-
- /**
- * @see java.security.cert.X509CRL#getTBSCertList()
- * method documentation for more info
- */
- public byte[] getTBSCertList() throws CRLException {
- if (tbsCertListEncoding == null) {
- tbsCertListEncoding = tbsCertList.getEncoded();
- }
- byte[] result = new byte[tbsCertListEncoding.length];
- System.arraycopy(tbsCertListEncoding, 0,
- result, 0, tbsCertListEncoding.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSignature()
- * method documentation for more info
- */
- public byte[] getSignature() {
- if (signature == null) {
- signature = crl.getSignatureValue();
- }
- byte[] result = new byte[signature.length];
- System.arraycopy(signature, 0, result, 0, signature.length);
- return result;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSigAlgName()
- * method documentation for more info
- */
- public String getSigAlgName() {
- if (sigAlgOID == null) {
- sigAlgOID = tbsCertList.getSignature().getAlgorithm();
- sigAlgName = AlgNameMapper.map2AlgName(sigAlgOID);
- if (sigAlgName == null) {
- sigAlgName = sigAlgOID;
- }
- }
- return sigAlgName;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSigAlgOID()
- * method documentation for more info
- */
- public String getSigAlgOID() {
- if (sigAlgOID == null) {
- sigAlgOID = tbsCertList.getSignature().getAlgorithm();
- sigAlgName = AlgNameMapper.map2AlgName(sigAlgOID);
- if (sigAlgName == null) {
- sigAlgName = sigAlgOID;
- }
- }
- return sigAlgOID;
- }
-
- /**
- * @see java.security.cert.X509CRL#getSigAlgParams()
- * method documentation for more info
- */
- public byte[] getSigAlgParams() {
- if (nullSigAlgParams) {
- return null;
- }
- if (sigAlgParams == null) {
- sigAlgParams = tbsCertList.getSignature().getParameters();
- if (sigAlgParams == null) {
- nullSigAlgParams = true;
- return null;
- }
- }
- return sigAlgParams;
- }
-
- /**
- * @see java.security.cert.X509CRL#verify(PublicKey key)
- * method documentation for more info
- */
- public void verify(PublicKey key)
- throws CRLException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
- Signature signature = Signature.getInstance(getSigAlgName());
- signature.initVerify(key);
- byte[] tbsEncoding = tbsCertList.getEncoded();
- signature.update(tbsEncoding, 0, tbsEncoding.length);
- if (!signature.verify(crl.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- /**
- * @see java.security.cert.X509CRL#verify(PublicKey key, String sigProvider)
- * method documentation for more info
- */
- public void verify(PublicKey key, String sigProvider)
- throws CRLException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
- Signature signature = Signature.getInstance(
- getSigAlgName(), sigProvider);
- signature.initVerify(key);
- byte[] tbsEncoding = tbsCertList.getEncoded();
- signature.update(tbsEncoding, 0, tbsEncoding.length);
- if (!signature.verify(crl.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.CRL abstract method implementations -------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.CRL#isRevoked(Certificate)
- * method documentation for more info
- */
- public boolean isRevoked(Certificate cert) {
- if (!(cert instanceof X509Certificate)) {
- return false;
- }
- return getRevokedCertificate((X509Certificate) cert) != null;
- }
-
- /**
- * @see java.security.cert.CRL#toString()
- * method documentation for more info
- */
- public String toString() {
- return crl.toString();
- }
-
- // ---------------------------------------------------------------------
- // ------ java.security.cert.X509Extension method implementations ------
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.X509Extension#getNonCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getNonCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getNonCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getCriticalExtensionOIDs()
- * method documentation for more info
- */
- public Set getCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- return extensions.getCriticalExtensions();
- }
-
- /**
- * @see java.security.cert.X509Extension#getExtensionValue(String)
- * method documentation for more info
- */
- public byte[] getExtensionValue(String oid) {
- if (extensions == null) {
- return null;
- }
- Extension ext = extensions.getExtensionByOID(oid);
- return (ext == null) ? null : ext.getRawExtnValue();
- }
-
- /**
- * @see java.security.cert.X509Extension#hasUnsupportedCriticalExtension()
- * method documentation for more info
- */
- public boolean hasUnsupportedCriticalExtension() {
- if (extensions == null) {
- return false;
- }
- return extensions.hasUnsupportedCritical();
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
deleted file mode 100644
index 9129ec2..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
+++ /dev/null
@@ -1,858 +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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.security.cert.CRL;
-import java.security.cert.CRLException;
-import java.security.cert.CertPath;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactorySpi;
-import java.security.cert.X509CRL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import libcore.io.Base64;
-import libcore.io.Streams;
-import org.apache.harmony.security.asn1.ASN1Constants;
-import org.apache.harmony.security.asn1.BerInputStream;
-import org.apache.harmony.security.pkcs7.ContentInfo;
-import org.apache.harmony.security.pkcs7.SignedData;
-import org.apache.harmony.security.x509.CertificateList;
-
-/**
- * X509 Certificate Factory Service Provider Interface Implementation.
- * It supports CRLs and Certificates in (PEM) ASN.1 DER encoded form,
- * and Certification Paths in PkiPath and PKCS7 formats.
- * For Certificates and CRLs factory maintains the caching
- * mechanisms allowing to speed up repeated Certificate/CRL
- * generation.
- * @see Cache
- */
-public class X509CertFactoryImpl extends CertificateFactorySpi {
-
- // number of leading/trailing bytes used for cert hash computation
- private static final int CERT_CACHE_SEED_LENGTH = 28;
- // certificate cache
- private static final Cache CERT_CACHE = new Cache(CERT_CACHE_SEED_LENGTH);
- // number of leading/trailing bytes used for crl hash computation
- private static final int CRL_CACHE_SEED_LENGTH = 24;
- // crl cache
- private static final Cache CRL_CACHE = new Cache(CRL_CACHE_SEED_LENGTH);
-
- /**
- * Default constructor.
- * Creates the instance of Certificate Factory SPI ready for use.
- */
- public X509CertFactoryImpl() { }
-
- /**
- * Generates the X.509 certificate from the data in the stream.
- * The data in the stream can be either in ASN.1 DER encoded X.509
- * certificate, or PEM (Base64 encoding bounded by
- * <code>"-----BEGIN CERTIFICATE-----"</code> at the beginning and
- * <code>"-----END CERTIFICATE-----"</code> at the end) representation
- * of the former encoded form.
- *
- * Before the generation the encoded form is looked up in
- * the cache. If the cache contains the certificate with requested encoded
- * form it is returned from it, otherwise it is generated by ASN.1
- * decoder.
- *
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertificate(InputStream)
- * method documentation for more info
- */
- public Certificate engineGenerateCertificate(InputStream inStream)
- throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- try {
- if (!inStream.markSupported()) {
- // create the mark supporting wrapper
- inStream = new RestoringInputStream(inStream);
- }
- // mark is needed to recognize the format of the provided encoding
- // (ASN.1 or PEM)
- inStream.mark(1);
- // check whether the provided certificate is in PEM encoded form
- if (inStream.read() == '-') {
- // decode PEM, retrieve CRL
- return getCertificate(decodePEM(inStream, CERT_BOUND_SUFFIX));
- } else {
- inStream.reset();
- // retrieve CRL
- return getCertificate(inStream);
- }
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * Generates the collection of the certificates on the base of provided
- * via input stream encodings.
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertificates(InputStream)
- * method documentation for more info
- */
- public Collection<? extends Certificate>
- engineGenerateCertificates(InputStream inStream)
- throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- ArrayList<Certificate> result = new ArrayList<Certificate>();
- try {
- if (!inStream.markSupported()) {
- // create the mark supporting wrapper
- inStream = new RestoringInputStream(inStream);
- }
- // if it is PEM encoded form this array will contain the encoding
- // so ((it is PEM) <-> (encoding != null))
- byte[] encoding = null;
- // The following by SEQUENCE ASN.1 tag, used for
- // recognizing the data format
- // (is it PKCS7 ContentInfo structure, X.509 Certificate, or
- // unsupported encoding)
- int second_asn1_tag = -1;
- inStream.mark(1);
- int ch;
- while ((ch = inStream.read()) != -1) {
- // check if it is PEM encoded form
- if (ch == '-') { // beginning of PEM encoding ('-' char)
- // decode PEM chunk and store its content (ASN.1 encoding)
- encoding = decodePEM(inStream, FREE_BOUND_SUFFIX);
- } else if (ch == 0x30) { // beginning of ASN.1 sequence (0x30)
- encoding = null;
- inStream.reset();
- // prepare for data format determination
- inStream.mark(CERT_CACHE_SEED_LENGTH);
- } else { // unsupported data
- if (result.size() == 0) {
- throw new CertificateException("Unsupported encoding");
- } else {
- // it can be trailing user data,
- // so keep it in the stream
- inStream.reset();
- return result;
- }
- }
- // Check the data format
- BerInputStream in = (encoding == null)
- ? new BerInputStream(inStream)
- : new BerInputStream(encoding);
- // read the next ASN.1 tag
- second_asn1_tag = in.next(); // inStream position changed
- if (encoding == null) {
- // keep whole structure in the stream
- inStream.reset();
- }
- // check if it is a TBSCertificate structure
- if (second_asn1_tag != ASN1Constants.TAG_C_SEQUENCE) {
- if (result.size() == 0) {
- // there were not read X.509 Certificates, so
- // break the cycle and check
- // whether it is PKCS7 structure
- break;
- } else {
- // it can be trailing user data,
- // so return what we already read
- return result;
- }
- } else {
- if (encoding == null) {
- result.add(getCertificate(inStream));
- } else {
- result.add(getCertificate(encoding));
- }
- }
- // mark for the next iteration
- inStream.mark(1);
- }
- if (result.size() != 0) {
- // some Certificates have been read
- return result;
- } else if (ch == -1) {
- /* No data in the stream, so return the empty collection. */
- return result;
- }
- // else: check if it is PKCS7
- if (second_asn1_tag == ASN1Constants.TAG_OID) {
- // it is PKCS7 ContentInfo structure, so decode it
- ContentInfo info = (ContentInfo)
- ((encoding != null)
- ? ContentInfo.ASN1.decode(encoding)
- : ContentInfo.ASN1.decode(inStream));
- // retrieve SignedData
- SignedData data = info.getSignedData();
- if (data == null) {
- throw new CertificateException("Invalid PKCS7 data provided");
- }
- List<org.apache.harmony.security.x509.Certificate> certs = data.getCertificates();
- if (certs != null) {
- for (org.apache.harmony.security.x509.Certificate cert : certs) {
- result.add(new X509CertImpl(cert));
- }
- }
- return result;
- }
- // else: Unknown data format
- throw new CertificateException("Unsupported encoding");
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCRL(InputStream)
- * method documentation for more info
- */
- public CRL engineGenerateCRL(InputStream inStream)
- throws CRLException {
- if (inStream == null) {
- throw new CRLException("inStream == null");
- }
- try {
- if (!inStream.markSupported()) {
- // Create the mark supporting wrapper
- // Mark is needed to recognize the format
- // of provided encoding form (ASN.1 or PEM)
- inStream = new RestoringInputStream(inStream);
- }
- inStream.mark(1);
- // check whether the provided crl is in PEM encoded form
- if (inStream.read() == '-') {
- // decode PEM, retrieve CRL
- return getCRL(decodePEM(inStream, FREE_BOUND_SUFFIX));
- } else {
- inStream.reset();
- // retrieve CRL
- return getCRL(inStream);
- }
- } catch (IOException e) {
- throw new CRLException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCRLs(InputStream)
- * method documentation for more info
- */
- public Collection<? extends CRL> engineGenerateCRLs(InputStream inStream)
- throws CRLException {
- if (inStream == null) {
- throw new CRLException("inStream == null");
- }
- ArrayList<CRL> result = new ArrayList<CRL>();
- try {
- if (!inStream.markSupported()) {
- inStream = new RestoringInputStream(inStream);
- }
- // if it is PEM encoded form this array will contain the encoding
- // so ((it is PEM) <-> (encoding != null))
- byte[] encoding = null;
- // The following by SEQUENCE ASN.1 tag, used for
- // recognizing the data format
- // (is it PKCS7 ContentInfo structure, X.509 CRL, or
- // unsupported encoding)
- int second_asn1_tag = -1;
- inStream.mark(1);
- int ch;
- while ((ch = inStream.read()) != -1) {
- // check if it is PEM encoded form
- if (ch == '-') { // beginning of PEM encoding ('-' char)
- // decode PEM chunk and store its content (ASN.1 encoding)
- encoding = decodePEM(inStream, FREE_BOUND_SUFFIX);
- } else if (ch == 0x30) { // beginning of ASN.1 sequence (0x30)
- encoding = null;
- inStream.reset();
- // prepare for data format determination
- inStream.mark(CRL_CACHE_SEED_LENGTH);
- } else { // unsupported data
- if (result.size() == 0) {
- throw new CRLException("Unsupported encoding");
- } else {
- // it can be trailing user data,
- // so keep it in the stream
- inStream.reset();
- return result;
- }
- }
- // Check the data format
- BerInputStream in = (encoding == null)
- ? new BerInputStream(inStream)
- : new BerInputStream(encoding);
- // read the next ASN.1 tag
- second_asn1_tag = in.next();
- if (encoding == null) {
- // keep whole structure in the stream
- inStream.reset();
- }
- // check if it is a TBSCertList structure
- if (second_asn1_tag != ASN1Constants.TAG_C_SEQUENCE) {
- if (result.size() == 0) {
- // there were not read X.509 CRLs, so
- // break the cycle and check
- // whether it is PKCS7 structure
- break;
- } else {
- // it can be trailing user data,
- // so return what we already read
- return result;
- }
- } else {
- if (encoding == null) {
- result.add(getCRL(inStream));
- } else {
- result.add(getCRL(encoding));
- }
- }
- inStream.mark(1);
- }
- if (result.size() != 0) {
- // the stream was read out
- return result;
- } else if (ch == -1) {
- throw new CRLException("There is no data in the stream");
- }
- // else: check if it is PKCS7
- if (second_asn1_tag == ASN1Constants.TAG_OID) {
- // it is PKCS7 ContentInfo structure, so decode it
- ContentInfo info = (ContentInfo)
- ((encoding != null)
- ? ContentInfo.ASN1.decode(encoding)
- : ContentInfo.ASN1.decode(inStream));
- // retrieve SignedData
- SignedData data = info.getSignedData();
- if (data == null) {
- throw new CRLException("Invalid PKCS7 data provided");
- }
- List<CertificateList> crls = data.getCRLs();
- if (crls != null) {
- for (CertificateList crl : crls) {
- result.add(new X509CRLImpl(crl));
- }
- }
- return result;
- }
- // else: Unknown data format
- throw new CRLException("Unsupported encoding");
- } catch (IOException e) {
- throw new CRLException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertPath(InputStream)
- * method documentation for more info
- */
- public CertPath engineGenerateCertPath(InputStream inStream)
- throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- return engineGenerateCertPath(inStream, "PkiPath");
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertPath(InputStream,String)
- * method documentation for more info
- */
- public CertPath engineGenerateCertPath(
- InputStream inStream, String encoding) throws CertificateException {
- if (inStream == null) {
- throw new CertificateException("inStream == null");
- }
- if (!inStream.markSupported()) {
- inStream = new RestoringInputStream(inStream);
- }
- try {
- inStream.mark(1);
- int ch;
-
- // check if it is PEM encoded form
- if ((ch = inStream.read()) == '-') {
- // decode PEM chunk into ASN.1 form and decode CertPath object
- return X509CertPathImpl.getInstance(
- decodePEM(inStream, FREE_BOUND_SUFFIX), encoding);
- } else if (ch == 0x30) { // ASN.1 Sequence
- inStream.reset();
- // decode ASN.1 form
- return X509CertPathImpl.getInstance(inStream, encoding);
- } else {
- throw new CertificateException("Unsupported encoding");
- }
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGenerateCertPath(List)
- * method documentation for more info
- */
- public CertPath engineGenerateCertPath(List<? extends Certificate> certificates)
- throws CertificateException {
- return new X509CertPathImpl(certificates);
- }
-
- /**
- * @see java.security.cert.CertificateFactorySpi#engineGetCertPathEncodings()
- * method documentation for more info
- */
- public Iterator<String> engineGetCertPathEncodings() {
- return X509CertPathImpl.encodings.iterator();
- }
-
- // ---------------------------------------------------------------------
- // ------------------------ Staff methods ------------------------------
- // ---------------------------------------------------------------------
-
- private static final byte[] PEM_BEGIN = "-----BEGIN".getBytes(StandardCharsets.UTF_8);
- private static final byte[] PEM_END = "-----END".getBytes(StandardCharsets.UTF_8);
- /**
- * Code describing free format for PEM boundary suffix:
- * "^-----BEGIN.*\n" at the beginning, and<br>
- * "\n-----END.*(EOF|\n)$" at the end.
- */
- private static final byte[] FREE_BOUND_SUFFIX = null;
- /**
- * Code describing PEM boundary suffix for X.509 certificate:
- * "^-----BEGIN CERTIFICATE-----\n" at the beginning, and<br>
- * "\n-----END CERTIFICATE-----" at the end.
- */
- private static final byte[] CERT_BOUND_SUFFIX = " CERTIFICATE-----".getBytes(StandardCharsets.UTF_8);
-
- /**
- * Method retrieves the PEM encoded data from the stream
- * and returns its decoded representation.
- * Method checks correctness of PEM boundaries. It supposes that
- * the first '-' of the opening boundary has already been read from
- * the stream. So first of all it checks that the leading bytes
- * are equal to "-----BEGIN" boundary prefix. Than if boundary_suffix
- * is not null, it checks that next bytes equal to boundary_suffix
- * + new line char[s] ([CR]LF).
- * If boundary_suffix parameter is null, method supposes free suffix
- * format and skips any bytes until the new line.<br>
- * After the opening boundary has been read and checked, the method
- * read Base64 encoded data until closing PEM boundary is not reached.<br>
- * Than it checks closing boundary - it should start with new line +
- * "-----END" + boundary_suffix. If boundary_suffix is null,
- * any characters are skipped until the new line.<br>
- * After this any trailing new line characters are skipped from the stream,
- * Base64 encoding is decoded and returned.
- * @param inStream the stream containing the PEM encoding.
- * @param boundary_suffix the suffix of expected PEM multipart
- * boundary delimiter.<br>
- * If it is null, that any character sequences are accepted.
- * @throws IOException If PEM boundary delimiter does not comply
- * with expected or some I/O or decoding problems occur.
- */
- private byte[] decodePEM(InputStream inStream, byte[] boundary_suffix)
- throws IOException {
- int ch; // the char to be read
- // check and skip opening boundary delimiter
- // (first '-' is supposed as already read)
- for (int i = 1; i < PEM_BEGIN.length; ++i) {
- if (PEM_BEGIN[i] != (ch = inStream.read())) {
- throw new IOException(
- "Incorrect PEM encoding: '-----BEGIN"
- + ((boundary_suffix == null)
- ? "" : new String(boundary_suffix))
- + "' is expected as opening delimiter boundary.");
- }
- }
- if (boundary_suffix == null) {
- // read (skip) the trailing characters of
- // the beginning PEM boundary delimiter
- while ((ch = inStream.read()) != '\n') {
- if (ch == -1) {
- throw new IOException("Incorrect PEM encoding: EOF before content");
- }
- }
- } else {
- for (int i=0; i<boundary_suffix.length; i++) {
- if (boundary_suffix[i] != inStream.read()) {
- throw new IOException("Incorrect PEM encoding: '-----BEGIN" +
- new String(boundary_suffix) + "' is expected as opening delimiter boundary.");
- }
- }
- // read new line characters
- if ((ch = inStream.read()) == '\r') {
- // CR has been read, now read LF character
- ch = inStream.read();
- }
- if (ch != '\n') {
- throw new IOException("Incorrect PEM encoding: newline expected after " +
- "opening delimiter boundary");
- }
- }
- int size = 1024; // the size of the buffer containing Base64 data
- byte[] buff = new byte[size];
- int index = 0;
- // read bytes while ending boundary delimiter is not reached
- while ((ch = inStream.read()) != '-') {
- if (ch == -1) {
- throw new IOException("Incorrect Base64 encoding: EOF without closing delimiter");
- }
- buff[index++] = (byte) ch;
- if (index == size) {
- // enlarge the buffer
- byte[] newbuff = new byte[size+1024];
- System.arraycopy(buff, 0, newbuff, 0, size);
- buff = newbuff;
- size += 1024;
- }
- }
- if (buff[index-1] != '\n') {
- throw new IOException("Incorrect Base64 encoding: newline expected before " +
- "closing boundary delimiter");
- }
- // check and skip closing boundary delimiter prefix
- // (first '-' was read)
- for (int i = 1; i < PEM_END.length; ++i) {
- if (PEM_END[i] != inStream.read()) {
- throw badEnd(boundary_suffix);
- }
- }
- if (boundary_suffix == null) {
- // read (skip) the trailing characters of
- // the closing PEM boundary delimiter
- while (((ch = inStream.read()) != -1) && (ch != '\n') && (ch != '\r')) {
- }
- } else {
- for (int i=0; i<boundary_suffix.length; i++) {
- if (boundary_suffix[i] != inStream.read()) {
- throw badEnd(boundary_suffix);
- }
- }
- }
- // skip trailing line breaks
- inStream.mark(1);
- while (((ch = inStream.read()) != -1) && (ch == '\n' || ch == '\r')) {
- inStream.mark(1);
- }
- inStream.reset();
- buff = Base64.decode(buff, index);
- if (buff == null) {
- throw new IOException("Incorrect Base64 encoding");
- }
- return buff;
- }
-
- private IOException badEnd(byte[] boundary_suffix) throws IOException {
- String s = (boundary_suffix == null) ? "" : new String(boundary_suffix);
- throw new IOException("Incorrect PEM encoding: '-----END" + s + "' is expected as closing delimiter boundary.");
- }
-
- /**
- * Reads the data of specified length from source
- * and returns it as an array.
- * @return the byte array contained read data or
- * null if the stream contains not enough data
- * @throws IOException if some I/O error has been occurred.
- */
- private static byte[] readBytes(InputStream source, int length)
- throws IOException {
- byte[] result = new byte[length];
- for (int i=0; i<length; i++) {
- int bytik = source.read();
- if (bytik == -1) {
- return null;
- }
- result[i] = (byte) bytik;
- }
- return result;
- }
-
- /**
- * Returns the Certificate object corresponding to the provided encoding.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static Certificate getCertificate(byte[] encoding)
- throws CertificateException, IOException {
- if (encoding.length < CERT_CACHE_SEED_LENGTH) {
- throw new CertificateException("encoding.length < CERT_CACHE_SEED_LENGTH");
- }
- synchronized (CERT_CACHE) {
- long hash = CERT_CACHE.getHash(encoding);
- if (CERT_CACHE.contains(hash)) {
- Certificate res =
- (Certificate) CERT_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- }
- Certificate res = new X509CertImpl(encoding);
- CERT_CACHE.put(hash, encoding, res);
- return res;
- }
- }
-
- /**
- * Returns the Certificate object corresponding to the encoding provided
- * by the stream.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static Certificate getCertificate(InputStream inStream)
- throws CertificateException, IOException {
- synchronized (CERT_CACHE) {
- inStream.mark(CERT_CACHE_SEED_LENGTH);
- // read the prefix of the encoding
- byte[] buff = readBytes(inStream, CERT_CACHE_SEED_LENGTH);
- inStream.reset();
- if (buff == null) {
- throw new CertificateException("InputStream doesn't contain enough data");
- }
- long hash = CERT_CACHE.getHash(buff);
- if (CERT_CACHE.contains(hash)) {
- byte[] encoding = new byte[BerInputStream.getLength(buff)];
- if (encoding.length < CERT_CACHE_SEED_LENGTH) {
- throw new CertificateException("Bad Certificate encoding");
- }
- Streams.readFully(inStream, encoding);
- Certificate res = (Certificate) CERT_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- res = new X509CertImpl(encoding);
- CERT_CACHE.put(hash, encoding, res);
- return res;
- } else {
- inStream.reset();
- Certificate res = new X509CertImpl(inStream);
- CERT_CACHE.put(hash, res.getEncoded(), res);
- return res;
- }
- }
- }
-
- /**
- * Returns the CRL object corresponding to the provided encoding.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static CRL getCRL(byte[] encoding)
- throws CRLException, IOException {
- if (encoding.length < CRL_CACHE_SEED_LENGTH) {
- throw new CRLException("encoding.length < CRL_CACHE_SEED_LENGTH");
- }
- synchronized (CRL_CACHE) {
- long hash = CRL_CACHE.getHash(encoding);
- if (CRL_CACHE.contains(hash)) {
- X509CRL res = (X509CRL) CRL_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- }
- X509CRL res = new X509CRLImpl(encoding);
- CRL_CACHE.put(hash, encoding, res);
- return res;
- }
- }
-
- /**
- * Returns the CRL object corresponding to the encoding provided
- * by the stream.
- * Resulting object is retrieved from the cache
- * if it contains such correspondence
- * and is constructed on the base of encoding
- * and stored in the cache otherwise.
- * @throws IOException if some decoding errors occur
- * (in the case of cache miss).
- */
- private static CRL getCRL(InputStream inStream)
- throws CRLException, IOException {
- synchronized (CRL_CACHE) {
- inStream.mark(CRL_CACHE_SEED_LENGTH);
- byte[] buff = readBytes(inStream, CRL_CACHE_SEED_LENGTH);
- // read the prefix of the encoding
- inStream.reset();
- if (buff == null) {
- throw new CRLException("InputStream doesn't contain enough data");
- }
- long hash = CRL_CACHE.getHash(buff);
- if (CRL_CACHE.contains(hash)) {
- byte[] encoding = new byte[BerInputStream.getLength(buff)];
- if (encoding.length < CRL_CACHE_SEED_LENGTH) {
- throw new CRLException("Bad CRL encoding");
- }
- Streams.readFully(inStream, encoding);
- CRL res = (CRL) CRL_CACHE.get(hash, encoding);
- if (res != null) {
- return res;
- }
- res = new X509CRLImpl(encoding);
- CRL_CACHE.put(hash, encoding, res);
- return res;
- } else {
- X509CRL res = new X509CRLImpl(inStream);
- CRL_CACHE.put(hash, res.getEncoded(), res);
- return res;
- }
- }
- }
-
- /*
- * This class extends any existing input stream with
- * mark functionality. It acts as a wrapper over the
- * stream and supports reset to the
- * marked state with readlimit no more than BUFF_SIZE.
- */
- private static class RestoringInputStream extends InputStream {
-
- // wrapped input stream
- private final InputStream inStream;
- // specifies how much of the read data is buffered
- // after the mark has been set up
- private static final int BUFF_SIZE = 32;
- // buffer to keep the bytes read after the mark has been set up
- private final int[] buff = new int[BUFF_SIZE*2];
- // position of the next byte to read,
- // the value of -1 indicates that the buffer is not used
- // (mark was not set up or was invalidated, or reset to the marked
- // position has been done and all the buffered data was read out)
- private int pos = -1;
- // position of the last buffered byte
- private int bar = 0;
- // position in the buffer where the mark becomes invalidated
- private int end = 0;
-
- /**
- * Creates the mark supporting wrapper over the stream.
- */
- public RestoringInputStream(InputStream inStream) {
- this.inStream = inStream;
- }
-
- @Override
- public int available() throws IOException {
- return (bar - pos) + inStream.available();
- }
-
- @Override
- public void close() throws IOException {
- inStream.close();
- }
-
- @Override
- public void mark(int readlimit) {
- if (pos < 0) {
- pos = 0;
- bar = 0;
- end = BUFF_SIZE - 1;
- } else {
- end = (pos + BUFF_SIZE - 1) % BUFF_SIZE;
- }
- }
-
- @Override
- public boolean markSupported() {
- return true;
- }
-
- /**
- * Reads the byte from the stream. If mark has been set up
- * and was not invalidated byte is read from the underlying
- * stream and saved into the buffer. If the current read position
- * has been reset to the marked position and there are remaining
- * bytes in the buffer, the byte is taken from it. In the other cases
- * (if mark has been invalidated, or there are no buffered bytes)
- * the byte is taken directly from the underlying stream and it is
- * returned without saving to the buffer.
- *
- * @see java.io.InputStream#read()
- * method documentation for more info
- */
- public int read() throws IOException {
- // if buffer is currently used
- if (pos >= 0) {
- // current position in the buffer
- int cur = pos % BUFF_SIZE;
- // check whether the buffer contains the data to be read
- if (cur < bar) {
- // return the data from the buffer
- pos++;
- return buff[cur];
- }
- // check whether buffer has free space
- if (cur != end) {
- // it has, so read the data from the wrapped stream
- // and place it in the buffer
- buff[cur] = inStream.read();
- bar = cur+1;
- pos++;
- return buff[cur];
- } else {
- // buffer if full and can not operate
- // any more, so invalidate the mark position
- // and turn off the using of buffer
- pos = -1;
- }
- }
- // buffer is not used, so return the data from the wrapped stream
- return inStream.read();
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- int read_b;
- int i;
- for (i=0; i<len; i++) {
- if ((read_b = read()) == -1) {
- return (i == 0) ? -1 : i;
- }
- b[off+i] = (byte) read_b;
- }
- return i;
- }
-
- @Override
- public void reset() throws IOException {
- if (pos >= 0) {
- pos = (end + 1) % BUFF_SIZE;
- } else {
- throw new IOException("Could not reset the stream: " +
- "position became invalid or stream has not been marked");
- }
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
deleted file mode 100644
index 4600bdc..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
+++ /dev/null
@@ -1,430 +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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Principal;
-import java.security.PublicKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateExpiredException;
-import java.security.cert.CertificateNotYetValidException;
-import java.security.cert.CertificateParsingException;
-import java.security.cert.X509Certificate;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.Certificate;
-import org.apache.harmony.security.x509.Extension;
-import org.apache.harmony.security.x509.Extensions;
-import org.apache.harmony.security.x509.TBSCertificate;
-
-/**
- * This class is an implementation of X509Certificate. It wraps
- * the instance of org.apache.harmony.security.x509.Certificate
- * built on the base of provided ASN.1 DER encoded form of
- * Certificate structure (as specified in RFC 3280
- * http://www.ietf.org/rfc/rfc3280.txt).
- * @see org.apache.harmony.security.x509.Certificate
- * @see java.security.cert.X509Certificate
- */
-public final class X509CertImpl extends X509Certificate {
-
- /** @serial */
- private static final long serialVersionUID = 2972248729446736154L;
-
- /** the core object to be wrapped in X509Certificate */
- private final Certificate certificate;
-
- private final TBSCertificate tbsCert;
- private final Extensions extensions;
- // to speed up access to the info, the following fields
- // cache values retrieved from the certificate object,
- // initialized using the "single-check idiom".
- private volatile long notBefore = -1;
- private volatile long notAfter = -1;
- private volatile BigInteger serialNumber;
- private volatile X500Principal issuer;
- private volatile X500Principal subject;
- private volatile byte[] tbsCertificate;
- private volatile byte[] signature;
- private volatile String sigAlgName;
- private volatile String sigAlgOID;
- private volatile byte[] sigAlgParams;
- // indicates whether the signature algorithm parameters are null
- private volatile boolean nullSigAlgParams;
- private volatile PublicKey publicKey;
-
- // encoding of the certificate
- private volatile byte[] encoding;
-
- /**
- * Constructs the instance on the base of ASN.1 encoded
- * form of X.509 certificate provided via stream parameter.
- * @param in input stream containing ASN.1 encoded form of certificate.
- * @throws CertificateException if some decoding problems occur.
- */
- public X509CertImpl(InputStream in) throws CertificateException {
- try {
- // decode the Certificate object
- this.certificate = (Certificate) Certificate.ASN1.decode(in);
- // cache the values of TBSCertificate and Extensions
- this.tbsCert = certificate.getTbsCertificate();
- this.extensions = tbsCert.getExtensions();
- } catch (IOException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * Constructs the instance on the base of existing Certificate object to
- * be wrapped.
- */
- public X509CertImpl(Certificate certificate) {
- this.certificate = certificate;
- // cache the values of TBSCertificate and Extensions
- this.tbsCert = certificate.getTbsCertificate();
- this.extensions = tbsCert.getExtensions();
- }
-
- /**
- * Constructs the instance on the base of ASN.1 encoded
- * form of X.509 certificate provided via array of bytes.
- * @param encoding byte array containing ASN.1 encoded form of certificate.
- * @throws IOException if some decoding problems occur.
- */
- public X509CertImpl(byte[] encoding) throws IOException {
- this((Certificate) Certificate.ASN1.decode(encoding));
- }
-
- public void checkValidity()
- throws CertificateExpiredException, CertificateNotYetValidException {
- checkValidity(System.currentTimeMillis());
- }
-
- public void checkValidity(Date date)
- throws CertificateExpiredException, CertificateNotYetValidException {
- checkValidity(date.getTime());
- }
-
- private void checkValidity(long time)
- throws CertificateExpiredException, CertificateNotYetValidException {
- if (time < getNotBeforeInternal()) {
- throw new CertificateNotYetValidException("current time: " + new Date(time)
- + ", validation time: " + new Date(getNotBeforeInternal()));
- }
- if (time > getNotAfterInternal()) {
- throw new CertificateExpiredException("current time: " + new Date(time)
- + ", expiration time: " + new Date(getNotAfterInternal()));
- }
- }
-
- public int getVersion() {
- return tbsCert.getVersion() + 1;
- }
-
- public BigInteger getSerialNumber() {
- BigInteger result = serialNumber;
- if (result == null) {
- serialNumber = result = tbsCert.getSerialNumber();
- }
- return result;
- }
-
- public Principal getIssuerDN() {
- return getIssuerX500Principal();
- }
-
- public X500Principal getIssuerX500Principal() {
- X500Principal result = issuer;
- if (result == null) {
- // retrieve the issuer's principal
- issuer = result = tbsCert.getIssuer().getX500Principal();
- }
- return result;
- }
-
- public Principal getSubjectDN() {
- return getSubjectX500Principal();
- }
-
- public X500Principal getSubjectX500Principal() {
- X500Principal result = subject;
- if (result == null) {
- // retrieve the subject's principal
- subject = result = tbsCert.getSubject().getX500Principal();
- }
- return result;
- }
-
- public Date getNotBefore() {
- return new Date(getNotBeforeInternal());
- }
-
- private long getNotBeforeInternal() {
- long result = notBefore;
- if (result == -1) {
- notBefore = result = tbsCert.getValidity().getNotBefore().getTime();
- }
- return result;
- }
-
- public Date getNotAfter() {
- return new Date(getNotAfterInternal());
- }
-
- private long getNotAfterInternal() {
- long result = notAfter;
- if (result == -1) {
- notAfter = result = tbsCert.getValidity().getNotAfter().getTime();
- }
- return result;
- }
-
- public byte[] getTBSCertificate() throws CertificateEncodingException {
- return getTbsCertificateInternal().clone();
- }
-
- private byte[] getTbsCertificateInternal() {
- byte[] result = tbsCertificate;
- if (result == null) {
- tbsCertificate = result = tbsCert.getEncoded();
- }
- return result;
- }
-
- public byte[] getSignature() {
- return getSignatureInternal().clone();
- }
-
- private byte[] getSignatureInternal() {
- byte[] result = signature;
- if (result == null) {
- signature = result = certificate.getSignatureValue();
- }
- return result;
- }
-
- public String getSigAlgName() {
- String result = sigAlgName;
- if (result == null) {
- String sigAlgOIDLocal = getSigAlgOID();
- // retrieve the name of the signing algorithm
- result = AlgNameMapper.map2AlgName(sigAlgOIDLocal);
- if (result == null) {
- // if could not be found, use OID as a name
- result = sigAlgOIDLocal;
- }
- sigAlgName = result;
- }
- return result;
- }
-
- public String getSigAlgOID() {
- String result = sigAlgOID;
- if (result == null) {
- // if info was not retrieved (and cached), do it:
- sigAlgOID = result = tbsCert.getSignature().getAlgorithm();
- }
- return result;
- }
-
- public byte[] getSigAlgParams() {
- if (nullSigAlgParams) {
- return null;
- }
- byte[] result = sigAlgParams;
- if (result == null) {
- result = tbsCert.getSignature().getParameters();
- if (result == null) {
- nullSigAlgParams = true;
- return null;
- }
- sigAlgParams = result;
- }
- return result;
- }
-
- public boolean[] getIssuerUniqueID() {
- return tbsCert.getIssuerUniqueID();
- }
-
- public boolean[] getSubjectUniqueID() {
- return tbsCert.getSubjectUniqueID();
- }
-
- public boolean[] getKeyUsage() {
- if (extensions == null) {
- return null;
- }
- return extensions.valueOfKeyUsage();
- }
-
- public List<String> getExtendedKeyUsage()
- throws CertificateParsingException {
- if (extensions == null) {
- return null;
- }
- try {
- return extensions.valueOfExtendedKeyUsage();
- } catch (IOException e) {
- throw new CertificateParsingException(e);
- }
- }
-
- public int getBasicConstraints() {
- if (extensions == null) {
- return -1;
- }
- return extensions.valueOfBasicConstraints();
- }
-
- public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException {
- if (extensions == null) {
- return null;
- }
- try {
- // Retrieve the extension value from the cached extensions object
- // This extension is not checked for correctness during
- // certificate generation, so now it can throw exception
- return extensions.valueOfSubjectAlternativeName();
- } catch (IOException e) {
- throw new CertificateParsingException(e);
- }
- }
-
- /**
- * @see java.security.cert.X509Certificate#getIssuerAlternativeNames()
- * method documentation for more information.
- */
- public Collection<List<?>> getIssuerAlternativeNames() throws CertificateParsingException {
- if (extensions == null) {
- return null;
- }
- try {
- // Retrieve the extension value from the cached extensions object
- // This extension is not checked for correctness during
- // certificate generation, so now it can throw exception
- return extensions.valueOfIssuerAlternativeName();
- } catch (IOException e) {
- throw new CertificateParsingException(e);
- }
- }
-
- @Override public byte[] getEncoded() throws CertificateEncodingException {
- return getEncodedInternal().clone();
- }
- private byte[] getEncodedInternal() throws CertificateEncodingException {
- byte[] result = encoding;
- if (encoding == null) {
- encoding = result = certificate.getEncoded();
- }
- return result;
- }
-
- @Override public PublicKey getPublicKey() {
- PublicKey result = publicKey;
- if (result == null) {
- publicKey = result = tbsCert.getSubjectPublicKeyInfo().getPublicKey();
- }
- return result;
- }
-
- @Override public String toString() {
- return certificate.toString();
- }
-
- @Override public void verify(PublicKey key)
- throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
-
- Signature signature = Signature.getInstance(getSigAlgName());
- signature.initVerify(key);
- // retrieve the encoding of the TBSCertificate structure
- byte[] tbsCertificateLocal = getTbsCertificateInternal();
- // compute and verify the signature
- signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
- if (!signature.verify(certificate.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- @Override public void verify(PublicKey key, String sigProvider)
- throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
-
- Signature signature = Signature.getInstance(getSigAlgName(), sigProvider);
- signature.initVerify(key);
- // retrieve the encoding of the TBSCertificate structure
- byte[] tbsCertificateLocal = getTbsCertificateInternal();
- // compute and verify the signature
- signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
- if (!signature.verify(certificate.getSignatureValue())) {
- throw new SignatureException("Signature was not verified");
- }
- }
-
- @Override public Set<String> getNonCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- // retrieve the info from the cached extensions object
- return extensions.getNonCriticalExtensions();
- }
-
- @Override public Set<String> getCriticalExtensionOIDs() {
- if (extensions == null) {
- return null;
- }
- // retrieve the info from the cached extensions object
- return extensions.getCriticalExtensions();
- }
-
- @Override public byte[] getExtensionValue(String oid) {
- if (extensions == null) {
- return null;
- }
- // retrieve the info from the cached extensions object
- Extension ext = extensions.getExtensionByOID(oid);
- return (ext == null) ? null : ext.getRawExtnValue();
- }
-
- @Override public boolean hasUnsupportedCriticalExtension() {
- if (extensions == null) {
- return false;
- }
- // retrieve the info from the cached extensions object
- return extensions.hasUnsupportedCritical();
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
deleted file mode 100644
index 3699700..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
+++ /dev/null
@@ -1,451 +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.
- */
-
-/**
-* @author Alexander Y. Kleymenov
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.provider.cert;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.cert.CertPath;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.harmony.security.asn1.ASN1Any;
-import org.apache.harmony.security.asn1.ASN1Explicit;
-import org.apache.harmony.security.asn1.ASN1Implicit;
-import org.apache.harmony.security.asn1.ASN1Oid;
-import org.apache.harmony.security.asn1.ASN1Sequence;
-import org.apache.harmony.security.asn1.ASN1SequenceOf;
-import org.apache.harmony.security.asn1.ASN1Type;
-import org.apache.harmony.security.asn1.BerInputStream;
-import org.apache.harmony.security.pkcs7.ContentInfo;
-import org.apache.harmony.security.pkcs7.SignedData;
-import org.apache.harmony.security.x509.Certificate;
-
-/**
- * This class is an implementation of X.509 CertPath. This implementation
- * provides ability to create the instance of X.509 Certification Path
- * by several means:<br>
- *
- * &nbsp; 1. It can be created over the list of X.509 certificates
- * (implementations of X509Certificate class) provided in constructor.<br>
- *
- * &nbsp; 2. It can be created by means of <code>getInstance</code> methods
- * on the base of the following ASN.1 DER encoded forms:<br>
- *
- * &nbsp;&nbsp; - PkiPath as defined in
- * ITU-T Recommendation X.509(2000) Corrigendum 1(2001)
- * (can be seen at
- * ftp://ftp.bull.com/pub/OSIdirectory/DefectResolution/TechnicalCorrigenda/ApprovedTechnicalCorrigendaToX.509/8%7CX.509-TC1(4th).pdf)
- * <br>
- * &nbsp;&nbsp; - PKCS #7 SignedData object provided in the form of
- * ContentInfo structure. CertPath object is generated on the base of
- * certificates presented in <code>certificates</code> field of the SignedData
- * object which in its turn is retrieved from ContentInfo structure.
- * (see http://www.ietf.org/rfc/rfc2315.txt
- * for more info on PKCS #7)
- * <br>
- * &nbsp;
- */
-public class X509CertPathImpl extends CertPath {
- /**
- * @serial
- */
- private static final long serialVersionUID = 7989755106209515436L;
-
- /**
- * Supported encoding types for CerthPath. Used by the various APIs that
- * encode this into bytes such as {@link #getEncoded()}.
- */
- private enum Encoding {
- PKI_PATH("PkiPath"),
- PKCS7("PKCS7");
-
- private final String apiName;
-
- Encoding(String apiName) {
- this.apiName = apiName;
- }
-
- static Encoding findByApiName(String apiName) throws CertificateEncodingException {
- for (Encoding element : values()) {
- if (element.apiName.equals(apiName)) {
- return element;
- }
- }
-
- return null;
- }
- }
-
- /** Unmodifiable list of encodings for the API. */
- static final List<String> encodings = Collections.unmodifiableList(Arrays.asList(new String[] {
- Encoding.PKI_PATH.apiName,
- Encoding.PKCS7.apiName,
- }));
-
- /** The list of certificates in the order of target toward trust anchor. */
- private final List<X509Certificate> certificates;
-
- /** PkiPath encoding of the certification path. */
- private byte[] pkiPathEncoding;
-
- /** PKCS7 encoding of the certification path. */
- private byte[] pkcs7Encoding;
-
- /**
- * Creates an instance of X.509 CertPath over the specified list of
- * certificates.
- *
- * @throws CertificateException if some of the object in the list is not an
- * instance of subclass of X509Certificate.
- */
- public X509CertPathImpl(List<? extends java.security.cert.Certificate> certs)
- throws CertificateException {
- super("X.509");
-
- final int size = certs.size();
- certificates = new ArrayList<X509Certificate>(size);
-
- for (int i = 0; i < size; i++) {
- final java.security.cert.Certificate cert = certs.get(i);
- if (!(cert instanceof X509Certificate)) {
- throw new CertificateException("Certificate " + i + " is not an X.509 certificate");
- }
-
- certificates.add((X509Certificate) cert);
- }
- }
-
- /**
- * Creates an X.509 CertPath over the specified {@code certs}. The
- * {@code certs} should be sorted correctly when calling into the
- * constructor. Additionally, the {@code encodedPath} should match the
- * expected output for the {@code type} of encoding.
- */
- private X509CertPathImpl(List<X509Certificate> certs, Encoding type) {
- super("X.509");
-
- certificates = certs;
- }
-
- /**
- * Extract a CertPath from a PKCS#7 {@code contentInfo} object.
- */
- private static X509CertPathImpl getCertPathFromContentInfo(ContentInfo contentInfo)
- throws CertificateException {
- final SignedData sd = contentInfo.getSignedData();
- if (sd == null) {
- throw new CertificateException("Incorrect PKCS7 encoded form: missing signed data");
- }
-
- List<Certificate> certs = sd.getCertificates();
- if (certs == null) {
- certs = Collections.emptyList();
- }
-
- final List<X509Certificate> result = new ArrayList<X509Certificate>(certs.size());
- for (Certificate cert : certs) {
- result.add(new X509CertImpl(cert));
- }
-
- return new X509CertPathImpl(result, Encoding.PKCS7);
- }
-
- /**
- * Generates certification path object on the base of PkiPath encoded form
- * provided via input stream.
- *
- * @throws CertificateException if some problems occurred during the
- * decoding.
- */
- public static X509CertPathImpl getInstance(InputStream in) throws CertificateException {
- try {
- return (X509CertPathImpl) ASN1.decode(in);
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- /**
- * Generates certification path object on the basis of encoding provided via
- * input stream. The format of provided encoded form is specified by
- * parameter <code>encoding</code>.
- *
- * @throws CertificateException if specified encoding form is not supported,
- * or some problems occurred during the decoding.
- */
- public static X509CertPathImpl getInstance(InputStream in, String encoding)
- throws CertificateException {
- try {
- final Encoding encType = Encoding.findByApiName(encoding);
- if (encType == null) {
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
-
- switch (encType) {
- case PKI_PATH:
- return (X509CertPathImpl) ASN1.decode(in);
- case PKCS7:
- return getCertPathFromContentInfo((ContentInfo) ContentInfo.ASN1.decode(in));
- default:
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- /**
- * Generates certification path object on the base of PkiPath
- * encoded form provided via array of bytes.
- * @throws CertificateException if some problems occurred during
- * the decoding.
- */
- public static X509CertPathImpl getInstance(byte[] in) throws CertificateException {
- try {
- return (X509CertPathImpl) ASN1.decode(in);
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- /**
- * Generates certification path object on the base of encoding provided via
- * array of bytes. The format of provided encoded form is specified by
- * parameter {@code encoding}.
- *
- * @throws CertificateException if specified encoding form is not supported,
- * or some problems occurred during the decoding.
- */
- public static X509CertPathImpl getInstance(byte[] in, String encoding)
- throws CertificateException {
- try {
- final Encoding encType = Encoding.findByApiName(encoding);
- if (encType == null) {
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
-
- switch (encType) {
- case PKI_PATH:
- return (X509CertPathImpl) ASN1.decode(in);
- case PKCS7:
- return getCertPathFromContentInfo((ContentInfo) ContentInfo.ASN1.decode(in));
- default:
- throw new CertificateException("Unsupported encoding: " + encoding);
- }
- } catch (IOException e) {
- throw new CertificateException("Failed to decode CertPath", e);
- }
- }
-
- // ---------------------------------------------------------------------
- // ---- java.security.cert.CertPath abstract method implementations ----
- // ---------------------------------------------------------------------
-
- /**
- * @see java.security.cert.CertPath#getCertificates()
- * method documentation for more info
- */
- @Override
- public List<X509Certificate> getCertificates() {
- return Collections.unmodifiableList(certificates);
- }
-
- /**
- * Returns in PkiPath format which is our default encoding.
- *
- * @see java.security.cert.CertPath#getEncoded()
- */
- @Override
- public byte[] getEncoded() throws CertificateEncodingException {
- return getEncoded(Encoding.PKI_PATH);
- }
-
- /**
- * @see #getEncoded(String)
- */
- private byte[] getEncoded(Encoding encoding) throws CertificateEncodingException {
- switch (encoding) {
- case PKI_PATH:
- if (pkiPathEncoding == null) {
- pkiPathEncoding = ASN1.encode(this);
- }
-
- return pkiPathEncoding.clone();
- case PKCS7:
- if (pkcs7Encoding == null) {
- pkcs7Encoding = PKCS7_SIGNED_DATA_OBJECT.encode(this);
- }
-
- return pkcs7Encoding.clone();
- default:
- throw new CertificateEncodingException("Unsupported encoding: " + encoding);
- }
- }
-
- /**
- * @see java.security.cert.CertPath#getEncoded(String)
- */
- @Override
- public byte[] getEncoded(String encoding) throws CertificateEncodingException {
- final Encoding encType = Encoding.findByApiName(encoding);
- if (encType == null) {
- throw new CertificateEncodingException("Unsupported encoding: " + encoding);
- }
-
- return getEncoded(encType);
- }
-
- /**
- * @see java.security.cert.CertPath#getEncodings()
- * method documentation for more info
- */
- @Override
- public Iterator<String> getEncodings() {
- return encodings.iterator();
- }
-
- /**
- * ASN.1 DER Encoder/Decoder for PkiPath structure.
- */
- public static final ASN1SequenceOf ASN1 = new ASN1SequenceOf(ASN1Any.getInstance()) {
- /**
- * Builds the instance of X509CertPathImpl on the base of the list of
- * ASN.1 encodings of X.509 certificates provided via PkiPath structure.
- * This method participates in decoding process.
- */
- public Object getDecodedObject(BerInputStream in) throws IOException {
- // retrieve the decoded content
- final List<byte[]> encodedCerts = (List<byte[]>) in.content;
-
- final int size = encodedCerts.size();
- final List<X509Certificate> certificates = new ArrayList<X509Certificate>(size);
-
- for (int i = size - 1; i >= 0; i--) {
- // create the X.509 certificate on the base of its encoded form
- // and add it to the list.
- certificates.add(new X509CertImpl((Certificate) Certificate.ASN1
- .decode(encodedCerts.get(i))));
- }
-
- // create and return the resulting object
- return new X509CertPathImpl(certificates, Encoding.PKI_PATH);
- }
-
- /**
- * Returns the Collection of the encoded form of certificates contained
- * in the X509CertPathImpl object to be encoded.
- * This method participates in encoding process.
- */
- public Collection<byte[]> getValues(Object object) {
- // object to be encoded
- final X509CertPathImpl cp = (X509CertPathImpl) object;
-
- // if it has no certificates in it - create the sequence of size 0
- if (cp.certificates == null) {
- return Collections.emptyList();
- }
-
- final int size = cp.certificates.size();
- final List<byte[]> encodings = new ArrayList<byte[]>(size);
-
- try {
- for (int i = size - 1; i >= 0; i--) {
- // get the encoded form of certificate and place it into the
- // list to be encoded in PkiPath format
- encodings.add(cp.certificates.get(i).getEncoded());
- }
- } catch (CertificateEncodingException e) {
- throw new IllegalArgumentException("Encoding error occurred", e);
- }
-
- return encodings;
- }
- };
-
-
- /**
- * Encoder for PKCS#7 SignedData. It is assumed that only certificate field
- * is important all other fields contain pre-calculated encodings.
- */
- private static final ASN1Sequence ASN1_SIGNED_DATA = new ASN1Sequence(
- new ASN1Type[] {
- // version ,digestAlgorithms, content info
- ASN1Any.getInstance(),
- // certificates
- new ASN1Implicit(0, ASN1),
- // set of crls is optional and is missed here
- ASN1Any.getInstance(),// signers info
- }) {
-
- // precalculated ASN.1 encodings for
- // version ,digestAlgorithms, content info field of SignedData
- private final byte[] PRECALCULATED_HEAD = new byte[] { 0x02, 0x01,
- 0x01,// version (v1)
- 0x31, 0x00,// empty set of DigestAlgorithms
- 0x30, 0x03, 0x06, 0x01, 0x00 // empty ContentInfo with oid=0
- };
-
- // precalculated empty set of SignerInfos
- private final byte[] SIGNERS_INFO = new byte[] { 0x31, 0x00 };
-
- protected void getValues(Object object, Object[] values) {
- values[0] = PRECALCULATED_HEAD;
- values[1] = object; // pass X509CertPathImpl object
- values[2] = SIGNERS_INFO;
- }
-
- // stub to prevent using the instance as decoder
- public Object decode(BerInputStream in) throws IOException {
- throw new RuntimeException(
- "Invalid use of encoder for PKCS#7 SignedData object");
- }
- };
-
- private static final ASN1Sequence PKCS7_SIGNED_DATA_OBJECT = new ASN1Sequence(
- new ASN1Type[] { ASN1Any.getInstance(), // contentType
- new ASN1Explicit(0, ASN1_SIGNED_DATA) // SignedData
- }) {
-
- // precalculated ASN.1 encoding for SignedData object oid
- private final byte[] SIGNED_DATA_OID = ASN1Oid.getInstance().encode(
- ContentInfo.SIGNED_DATA);
-
- protected void getValues(Object object, Object[] values) {
- values[0] = SIGNED_DATA_OID;
- values[1] = object; // pass X509CertPathImpl object
- }
-
- // stub to prevent using the instance as decoder
- public Object decode(BerInputStream in) throws IOException {
- throw new RuntimeException(
- "Invalid use of encoder for PKCS#7 SignedData object");
- }
- };
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
index 7c2785a..ad5ac7d 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
@@ -20,12 +20,9 @@ package org.apache.harmony.security.provider.crypto;
import java.security.Provider;
/**
- * Implementation of Provider for SecureRandom, MessageDigest and Signature
- * using a Secure Hash Algorithm, SHA-1;
- * see SECURE HASH STANDARD, FIPS PUB 180-1 (http://www.itl.nist.gov/fipspubs/fip180-1.htm) <BR>
- * <BR>
- * The implementation supports "SHA1PRNG", "SHA-1" and "SHA1withDSA" algorithms described in
- * JavaTM Cryptography Architecture, API Specification & Reference
+ * Implementation of Provider for SecureRandom. The implementation supports the
+ * "SHA1PRNG" algorithm described in JavaTM Cryptography Architecture, API
+ * Specification & Reference
*/
public final class CryptoProvider extends Provider {
@@ -36,46 +33,10 @@ public final class CryptoProvider extends Provider {
* Creates a Provider and puts parameters
*/
public CryptoProvider() {
-
super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
- // names of classes implementing services
- final String MD_NAME = "org.apache.harmony.security.provider.crypto.SHA1_MessageDigestImpl";
- final String SR_NAME = "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl";
-
- final String SIGN_NAME = "org.apache.harmony.security.provider.crypto.SHA1withDSA_SignatureImpl";
-
- final String SIGN_ALIAS = "SHA1withDSA";
-
-
- final String KEYF_NAME = "org.apache.harmony.security.provider.crypto.DSAKeyFactoryImpl";
-
- put("MessageDigest.SHA-1", MD_NAME);
- put("MessageDigest.SHA-1 ImplementedIn", "Software");
- put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
- put("Alg.Alias.MessageDigest.SHA", "SHA-1");
-
- put("SecureRandom.SHA1PRNG", SR_NAME);
+ put("SecureRandom.SHA1PRNG",
+ "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl");
put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
-
- put("Signature.SHA1withDSA", SIGN_NAME);
- put("Signature.SHA1withDSA ImplementedIn", "Software");
- put("Alg.Alias.Signature.SHAwithDSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSAwithSHA1", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA1/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA-1/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSS", SIGN_ALIAS);
-
- put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.2.840.10040.4.3", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.3.14.3.2.13", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.3.14.3.2.27", SIGN_ALIAS);
-
- put("KeyFactory.DSA", KEYF_NAME);
- put("KeyFactory.DSA ImplementedIn", "Software");
- put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA");
- put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA");
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java
deleted file mode 100644
index 690d16e..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java
+++ /dev/null
@@ -1,217 +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.harmony.security.provider.crypto;
-
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.Key;
-import java.security.KeyFactorySpi;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPrivateKey;
-import java.security.interfaces.DSAPublicKey;
-import java.security.spec.DSAPrivateKeySpec;
-import java.security.spec.DSAPublicKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.KeySpec;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-
-public class DSAKeyFactoryImpl extends KeyFactorySpi {
-
- /**
- * This method generates a DSAPrivateKey object from the provided key specification.
- *
- * @param
- * keySpec - the specification (key material) for the DSAPrivateKey.
- *
- * @return
- * a DSAPrivateKey object
- *
- * @throws InvalidKeySpecException
- * if "keySpec" is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec
- */
- protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
- throws InvalidKeySpecException {
-
- if (keySpec != null) {
- if (keySpec instanceof DSAPrivateKeySpec) {
-
- return new DSAPrivateKeyImpl((DSAPrivateKeySpec) keySpec);
- }
- if (keySpec instanceof PKCS8EncodedKeySpec) {
-
- return new DSAPrivateKeyImpl((PKCS8EncodedKeySpec) keySpec);
- }
- }
- throw new InvalidKeySpecException("'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
- }
-
- /**
- * This method generates a DSAPublicKey object from the provided key specification.
- *
- * @param
- * keySpec - the specification (key material) for the DSAPublicKey.
- *
- * @return
- * a DSAPublicKey object
- *
- * @throws InvalidKeySpecException
- * if "keySpec" is neither DSAPublicKeySpec nor X509EncodedKeySpec
- */
- protected PublicKey engineGeneratePublic(KeySpec keySpec)
- throws InvalidKeySpecException {
-
- if (keySpec != null) {
- if (keySpec instanceof DSAPublicKeySpec) {
-
- return new DSAPublicKeyImpl((DSAPublicKeySpec) keySpec);
- }
- if (keySpec instanceof X509EncodedKeySpec) {
-
- return new DSAPublicKeyImpl((X509EncodedKeySpec) keySpec);
- }
- }
- throw new InvalidKeySpecException("'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
- }
-
- /**
- * This method returns a specification for the supplied key.
- *
- * The specification will be returned in the form of an object of the type
- * specified by keySpec.
- *
- * @param key -
- * either DSAPrivateKey or DSAPublicKey
- * @param keySpec -
- * either DSAPrivateKeySpec.class or DSAPublicKeySpec.class
- *
- * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec
- *
- * @throws InvalidKeySpecException
- * if "keySpec" is not a specification for DSAPublicKey or
- * DSAPrivateKey
- */
- protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
- throws InvalidKeySpecException {
-
- BigInteger p, q, g, x, y;
-
- if (key != null) {
- if (keySpec == null) {
- throw new NullPointerException("keySpec == null");
- }
- if (key instanceof DSAPrivateKey) {
- DSAPrivateKey privateKey = (DSAPrivateKey) key;
-
- if (keySpec.equals(DSAPrivateKeySpec.class)) {
-
- x = privateKey.getX();
-
- DSAParams params = privateKey.getParams();
-
- p = params.getP();
- q = params.getQ();
- g = params.getG();
-
- return (T) (new DSAPrivateKeySpec(x, p, q, g));
- }
-
- if (keySpec.equals(PKCS8EncodedKeySpec.class)) {
- return (T) (new PKCS8EncodedKeySpec(key.getEncoded()));
- }
-
- throw new InvalidKeySpecException("'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
- }
-
- if (key instanceof DSAPublicKey) {
- DSAPublicKey publicKey = (DSAPublicKey) key;
-
- if (keySpec.equals(DSAPublicKeySpec.class)) {
-
- y = publicKey.getY();
-
- DSAParams params = publicKey.getParams();
-
- p = params.getP();
- q = params.getQ();
- g = params.getG();
-
- return (T) (new DSAPublicKeySpec(y, p, q, g));
- }
-
- if (keySpec.equals(X509EncodedKeySpec.class)) {
- return (T) (new X509EncodedKeySpec(key.getEncoded()));
- }
-
- throw new InvalidKeySpecException("'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
- }
- }
- throw new InvalidKeySpecException("'key' is neither DSAPublicKey nor DSAPrivateKey");
- }
-
- /**
- * The method generates a DSAPublicKey object from the provided key.
- *
- * @param
- * key - a DSAPublicKey object or DSAPrivateKey object.
- *
- * @return
- * object of the same type as the "key" argument
- *
- * @throws InvalidKeyException
- * if "key" is neither DSAPublicKey nor DSAPrivateKey
- */
- protected Key engineTranslateKey(Key key) throws InvalidKeyException {
-
- if (key != null) {
- if (key instanceof DSAPrivateKey) {
-
- DSAPrivateKey privateKey = (DSAPrivateKey) key;
- DSAParams params = privateKey.getParams();
-
- try {
- return engineGeneratePrivate(new DSAPrivateKeySpec(
- privateKey.getX(), params.getP(), params.getQ(),
- params.getG()));
- } catch (InvalidKeySpecException e) {
- // Actually this exception shouldn't be thrown
- throw new InvalidKeyException("ATTENTION: InvalidKeySpecException: " + e);
- }
- }
-
- if (key instanceof DSAPublicKey) {
-
- DSAPublicKey publicKey = (DSAPublicKey) key;
- DSAParams params = publicKey.getParams();
-
- try {
- return engineGeneratePublic(new DSAPublicKeySpec(publicKey
- .getY(), params.getP(), params.getQ(), params
- .getG()));
- } catch (InvalidKeySpecException e) {
- // Actually this exception shouldn't be thrown
- throw new InvalidKeyException("ATTENTION: InvalidKeySpecException: " + e);
- }
- }
- }
- throw new InvalidKeyException("'key' is neither DSAPublicKey nor DSAPrivateKey");
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
deleted file mode 100644
index c0fc766..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
+++ /dev/null
@@ -1,159 +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.
- */
-
- /*
- * TODO
- * 1. The class extends the PrivateKeyImpl class in "org.apache.harmony.security" package.
- *
- * 2. See a compatibility with RI comments
- * in the below "DSAPrivateKeyImpl(PKCS8EncodedKeySpec keySpec)" constructor.
- */
-
-
-package org.apache.harmony.security.provider.crypto;
-
-import java.io.IOException;
-import java.io.NotActiveException;
-import java.math.BigInteger;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPrivateKey;
-import java.security.spec.DSAParameterSpec;
-import java.security.spec.DSAPrivateKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-import org.apache.harmony.security.PrivateKeyImpl;
-import org.apache.harmony.security.asn1.ASN1Integer;
-import org.apache.harmony.security.pkcs8.PrivateKeyInfo;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.AlgorithmIdentifier;
-
-/**
- * The class provides DSAPrivateKey functionality by extending a class implementing PrivateKey
- * and implementing methods defined in both interfaces, DSAKey and DSAPrivateKey
- */
-public class DSAPrivateKeyImpl extends PrivateKeyImpl implements DSAPrivateKey {
-
- /**
- * @serial
- */
- private static final long serialVersionUID = -4716227614104950081L;
-
- private BigInteger x, g, p, q;
-
- private transient DSAParams params;
-
- /**
- * Creates object from DSAPrivateKeySpec.
- *
- * @param keySpec - a DSAPrivateKeySpec object
- */
- public DSAPrivateKeyImpl(DSAPrivateKeySpec keySpec) {
-
- super("DSA");
-
- PrivateKeyInfo pki;
-
- g = keySpec.getG();
- p = keySpec.getP();
- q = keySpec.getQ();
-
- ThreeIntegerSequence threeInts = new ThreeIntegerSequence(p
- .toByteArray(), q.toByteArray(), g.toByteArray());
-
- AlgorithmIdentifier ai = new AlgorithmIdentifier(AlgNameMapper
- .map2OID("DSA"),
- threeInts.getEncoded());
- x = keySpec.getX();
-
- pki = new PrivateKeyInfo(0, ai, ASN1Integer.getInstance().encode(
- x.toByteArray()), null);
-
- setEncoding(pki.getEncoded());
-
- params = new DSAParameterSpec(p, q, g);
- }
-
- /**
- * Creates object from PKCS8EncodedKeySpec.
- *
- * @param keySpec - a XPKCS8EncodedKeySpec object
- *
- * @throws InvalidKeySpecException - if key data cannot be obtain from encoded format
- */
- public DSAPrivateKeyImpl(PKCS8EncodedKeySpec keySpec)
- throws InvalidKeySpecException {
-
- super("DSA");
-
- AlgorithmIdentifier ai;
- ThreeIntegerSequence threeInts = null;
-
- String alg, algName;
-
- byte[] encoding = keySpec.getEncoded();
-
- PrivateKeyInfo privateKeyInfo = null;
-
- try {
- privateKeyInfo = (PrivateKeyInfo) PrivateKeyInfo.ASN1
- .decode(encoding);
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode keySpec encoding: " + e);
- }
-
- try {
- x = new BigInteger((byte[]) ASN1Integer.getInstance().decode(
- privateKeyInfo.getPrivateKey()));
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
-
- ai = privateKeyInfo.getAlgorithmIdentifier();
- try {
- threeInts = (ThreeIntegerSequence) ThreeIntegerSequence.ASN1
- .decode(ai.getParameters());
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
- p = new BigInteger(threeInts.p);
- q = new BigInteger(threeInts.q);
- g = new BigInteger(threeInts.g);
- params = new DSAParameterSpec(p, q, g);
- setEncoding(encoding);
-
- /*
- * the following code implements RI behavior
- */
- alg = ai.getAlgorithm();
- algName = AlgNameMapper.map2AlgName(alg);
- setAlgorithm(algName == null ? alg : algName);
- }
-
- public BigInteger getX() {
- return x;
- }
-
- public DSAParams getParams() {
- return params;
- }
-
- private void readObject(java.io.ObjectInputStream in) throws NotActiveException, IOException, ClassNotFoundException {
- in.defaultReadObject();
- params = new DSAParameterSpec(p, q, g);
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java
deleted file mode 100644
index 6b35970..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.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.
- */
-
- /*
- * TODO
- * 1. The class extends the PublicKeyImpl class in "org.apache.harmony.security" package.
- *
- * 2. The class uses methods in the auxiliary non-public "ThreeIntegerSequence" class
- * defined along with the "DSAPrivateKeyImpl" class.
- *
- * 3. See a compatibility with RI comments
- * in the below "DSAPublicKeyImpl(X509EncodedKeySpec keySpec)" constructor.
- */
-
-package org.apache.harmony.security.provider.crypto;
-
-import java.io.IOException;
-import java.io.NotActiveException;
-import java.math.BigInteger;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPublicKey;
-import java.security.spec.DSAParameterSpec;
-import java.security.spec.DSAPublicKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.X509EncodedKeySpec;
-import org.apache.harmony.security.PublicKeyImpl;
-import org.apache.harmony.security.asn1.ASN1Integer;
-import org.apache.harmony.security.utils.AlgNameMapper;
-import org.apache.harmony.security.x509.AlgorithmIdentifier;
-import org.apache.harmony.security.x509.SubjectPublicKeyInfo;
-
-/**
- * The class provides DSAPublicKey functionality by extending a class implementing PublicKey
- * and implementing methods defined in both interfaces, DSAKey and DSAPublicKey
- */
-public class DSAPublicKeyImpl extends PublicKeyImpl implements DSAPublicKey {
-
- /**
- * @serial
- */
- private static final long serialVersionUID = -2279672131310978336L;
-
- private BigInteger y, g, p, q;
-
- private transient DSAParams params;
-
- /**
- * Creates object from DSAPublicKeySpec.
- *
- * @param keySpec - a DSAPublicKeySpec object
- */
- public DSAPublicKeyImpl(DSAPublicKeySpec keySpec) {
-
- super("DSA");
-
- SubjectPublicKeyInfo spki;
-
- p = keySpec.getP();
- q = keySpec.getQ();
- g = keySpec.getG();
-
- ThreeIntegerSequence threeInts = new ThreeIntegerSequence(p
- .toByteArray(), q.toByteArray(), g.toByteArray());
-
- AlgorithmIdentifier ai = new AlgorithmIdentifier(AlgNameMapper
- .map2OID("DSA"),
- threeInts.getEncoded());
-
- y = keySpec.getY();
-
- spki = new SubjectPublicKeyInfo(ai, ASN1Integer.getInstance().encode(
- y.toByteArray()));
- setEncoding(spki.getEncoded());
-
- params = (DSAParams) (new DSAParameterSpec(p, q, g));
- }
-
- /**
- * Creates object from X509EncodedKeySpec.
- *
- * @param keySpec - a X509EncodedKeySpec object
- *
- * @throws InvalidKeySpecException - if key data cannot be obtain from encoded format
- */
- public DSAPublicKeyImpl(X509EncodedKeySpec keySpec)
- throws InvalidKeySpecException {
-
- super("DSA");
-
- AlgorithmIdentifier ai;
- ThreeIntegerSequence threeInts = null;
-
- SubjectPublicKeyInfo subjectPublicKeyInfo = null;
-
- byte[] encoding = keySpec.getEncoded();
-
- String alg, algName;
-
- try {
- subjectPublicKeyInfo = (SubjectPublicKeyInfo) SubjectPublicKeyInfo.ASN1
- .decode(encoding);
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode keySpec encoding: " + e);
- }
-
- try {
- y = new BigInteger((byte[]) ASN1Integer.getInstance().decode(
- subjectPublicKeyInfo.getSubjectPublicKey()));
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
-
- ai = subjectPublicKeyInfo.getAlgorithmIdentifier();
-
- try {
- threeInts = (ThreeIntegerSequence) ThreeIntegerSequence.ASN1
- .decode(ai.getParameters());
- } catch (IOException e) {
- throw new InvalidKeySpecException("Failed to decode parameters: " + e);
- }
- p = new BigInteger(threeInts.p);
- q = new BigInteger(threeInts.q);
- g = new BigInteger(threeInts.g);
- params = (DSAParams) (new DSAParameterSpec(p, q, g));
-
- setEncoding(encoding);
-
- /*
- * the following code implements RI behavior
- */
- alg = ai.getAlgorithm();
- algName = AlgNameMapper.map2AlgName(alg);
- setAlgorithm(algName == null ? alg : algName);
- }
-
- /**
- * @return
- * a value of a public key (y).
- */
- public BigInteger getY() {
- return y;
- }
-
- /**
- * @return
- * DSA key parameters (p, q, g).
- */
- public DSAParams getParams() {
- return params;
- }
-
- private void readObject(java.io.ObjectInputStream in) throws NotActiveException, IOException, ClassNotFoundException {
- in.defaultReadObject();
- params = new DSAParameterSpec(p, q, g);
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java
deleted file mode 100644
index 3f41f18..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java
+++ /dev/null
@@ -1,306 +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.harmony.security.provider.crypto;
-
-import java.security.DigestException;
-import java.security.MessageDigestSpi;
-import java.util.Arrays;
-
-import static org.apache.harmony.security.provider.crypto.SHA1Constants.*;
-
-/**
- * This class extends the MessageDigestSpi class implementing all its abstract methods;
- * it overrides the "Object clone()" and "int engineGetDigestLength()" methods. <BR>
- * The class implements the Cloneable interface.
- */
-public class SHA1_MessageDigestImpl extends MessageDigestSpi implements Cloneable {
- private int[] buffer; // buffer has the following structure:
- // - 0-16 - frame for accumulating a message
- // - 17-79 - for SHA1Impl methods
- // - 80 - unused
- // - 81 - to store length of the message
- // - 82-86 - frame for current message digest
-
- private byte[] oneByte; // one byte buffer needed to use in engineUpdate(byte)
- // having buffer as private field is just optimization
-
- private long messageLength; // total length of bytes supplied by user
-
-
- /**
- * The constructor creates needed buffers and sets the engine at initial state
- */
- public SHA1_MessageDigestImpl() {
-
- // BYTES_OFFSET +6 is minimal length required by methods in SHA1Impl
- buffer = new int[BYTES_OFFSET +6];
-
- oneByte = new byte[1];
-
- engineReset();
- }
-
-
- /**
- * The method performs final actions and invokes the "computeHash(int[])" method.
- * In case if there is no enough words in current frame
- * after processing its data, extra frame is prepared and
- * the "computeHash(int[])" method is invoked second time. <BR>
- *
- * After processing, the method resets engine's state
- *
- * @param
- * digest - byte array
- * @param
- * offset - offset in digest
- */
- private void processDigest(byte[] digest, int offset) {
-
- int i, j; // implementation variables
- int lastWord; //
-
- long nBits = messageLength <<3 ; // length has to be calculated before padding
-
- engineUpdate( (byte) 0x80 ); // beginning byte in padding
-
- i = 0; // i contains number of beginning word for following loop
-
- lastWord = (buffer[BYTES_OFFSET] + 3)>>2 ; // computing of # of full words by shifting
- // # of bytes
-
- // possible cases:
- //
- // - buffer[BYTES_OFFSET] == 0 - buffer frame is empty,
- // padding byte was 64th in previous frame
- // current frame should contain only message's length
- //
- // - lastWord < 14 - two last, these are 14 & 15, words in 16 word frame are free;
- // no extra frame needed
- // - lastWord = 14 - only one last, namely 15-th, word in frame doesn't contain bytes;
- // extra frame is needed
- // - lastWord > 14 - last word in frame is not full;
- // extra frame is needed
-
- if ( buffer[BYTES_OFFSET] != 0 ) {
-
- if ( lastWord < 15 ) {
- i = lastWord;
- } else {
- if ( lastWord == 15 ) {
- buffer[15] = 0; // last word in frame is set to "0"
- }
- SHA1Impl.computeHash(buffer);
- i = 0;
- }
- }
- Arrays.fill(buffer, i, 14, 0);
-
- buffer[14] = (int)( nBits >>>32 );
- buffer[15] = (int)( nBits & 0xFFFFFFFF );
- SHA1Impl.computeHash(buffer);
-
- // converting 5-word frame into 20 bytes
- j = offset;
- for ( i = HASH_OFFSET; i < HASH_OFFSET +5; i++ ) {
- int k = buffer[i];
- digest[j ] = (byte) ( k >>>24 ); // getting first byte from left
- digest[j+1] = (byte) ( k >>>16 ); // getting second byte from left
- digest[j+2] = (byte) ( k >>> 8 ); // getting third byte from left
- digest[j+3] = (byte) ( k ); // getting fourth byte from left
- j += 4;
- }
-
- engineReset();
- }
-
- // methods specified in java.security.MessageDigestSpi
-
- /**
- * Returns a "deep" copy of this SHA1MDImpl object. <BR>
- *
- * The method overrides "clone()" in class Object. <BR>
- *
- * @return
- * a clone of this object
- */
- public Object clone() throws CloneNotSupportedException {
- SHA1_MessageDigestImpl cloneObj = (SHA1_MessageDigestImpl) super.clone();
- cloneObj.buffer = buffer.clone();
- cloneObj.oneByte = oneByte.clone();
- return cloneObj;
- }
-
-
- /**
- * Computes a message digest value. <BR>
- *
- * The method resets the engine. <BR>
- *
- * The method overrides "engineDigest()" in class MessageDigestSpi. <BR>
- *
- * @return
- * byte array containing message digest value
- */
- protected byte[] engineDigest() {
- byte[] hash = new byte[DIGEST_LENGTH];
- processDigest(hash, 0);
- return hash;
- }
-
-
- /**
- * Computes message digest value.
- * Upon return, the value is stored in "buf" buffer beginning "offset" byte. <BR>
- *
- * The method resets the engine. <BR>
- *
- * The method overrides "engineDigest(byte[],int,int) in class MessageDigestSpi.
- *
- * @param
- * buf byte array to store a message digest returned
- * @param
- * offset a position in the array for first byte of the message digest
- * @param
- * len number of bytes within buffer allotted for the message digest;
- * as this implementation doesn't provide partial digests,
- * len should be >= 20, DigestException is thrown otherwise
- * @return
- * the length of the message digest stored in the "buf" buffer;
- * in this implementation the length=20
- *
- * @throws IllegalArgumentException
- * if null is passed to the "buf" argument <BR>
- * if offset + len > buf.length <BR>
- * if offset > buf.length or len > buf.length
- *
- * @throws DigestException
- * if len < 20
- *
- * @throws ArrayIndexOutOfBoundsException
- * if offset < 0
- */
- protected int engineDigest(byte[] buf, int offset, int len) throws DigestException {
- if (buf == null) {
- throw new IllegalArgumentException("buf == null");
- }
- if (offset > buf.length || len > buf.length || (len + offset) > buf.length) {
- throw new IllegalArgumentException();
- }
- if (len < DIGEST_LENGTH) {
- throw new DigestException("len < DIGEST_LENGTH");
- }
- if (offset < 0) {
- throw new ArrayIndexOutOfBoundsException(offset);
- }
-
- processDigest(buf, offset);
-
- return DIGEST_LENGTH;
- }
-
-
- /**
- * Returns a message digest length. <BR>
- *
- * The method overrides "engineGetDigestLength()" in class MessageDigestSpi. <BR>
- *
- * @return
- * total length of current message digest as an int value
- */
- protected int engineGetDigestLength() {
- return DIGEST_LENGTH;
- }
-
-
- /**
- * Resets the engine. <BR>
- *
- * The method overrides "engineReset()" in class MessageDigestSpi. <BR>
- */
- protected void engineReset() {
-
- messageLength = 0;
-
- buffer[BYTES_OFFSET] = 0;
- buffer[HASH_OFFSET ] = H0;
- buffer[HASH_OFFSET +1] = H1;
- buffer[HASH_OFFSET +2] = H2;
- buffer[HASH_OFFSET +3] = H3;
- buffer[HASH_OFFSET +4] = H4;
- }
-
-
- /**
- * Supplements a byte to current message. <BR>
- *
- * The method overrides "engineUpdate(byte)" in class MessageDigestSpi. <BR>
- *
- * @param
- * input byte to add to current message
- */
- protected void engineUpdate(byte input) {
-
- oneByte[0] = input;
- SHA1Impl.updateHash( buffer, oneByte, 0, 0 );
- messageLength++;
- }
-
-
- /**
- * Updates current message. <BR>
- *
- * The method overrides "engineUpdate(byte[],int,int)" in class MessageDigestSpi. <BR>
- *
- * The method silently returns if "len" <= 0.
- *
- * @param
- * input a byte array
- * @param
- * offset a number of first byte in the "input" array to use for updating
- * @param
- * len a number of bytes to use
- *
- * @throws NullPointerException
- * if null is passed to the "buf" argument
- *
- * @throws IllegalArgumentException
- * if offset > buf.length or len > buf.length or
- * (len + offset) > buf.length
- * @throws ArrayIndexOutOfBoundsException
- * offset < 0
- */
- protected void engineUpdate(byte[] input, int offset, int len) {
- if (input == null) {
- throw new IllegalArgumentException("input == null");
- }
- if (len <= 0) {
- return;
- }
- if (offset < 0) {
- throw new ArrayIndexOutOfBoundsException(offset);
- }
- if (offset > input.length || len > input.length || (len + offset) > input.length) {
- throw new IllegalArgumentException();
- }
-
- SHA1Impl.updateHash(buffer, input, offset, offset + len -1 );
- messageLength += len;
- }
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java
deleted file mode 100644
index 2958e00..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java
+++ /dev/null
@@ -1,423 +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.harmony.security.provider.crypto;
-
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.InvalidParameterException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.interfaces.DSAKey;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPrivateKey;
-import java.security.interfaces.DSAPublicKey;
-
-public class SHA1withDSA_SignatureImpl extends Signature {
-
- private MessageDigest msgDigest;
-
- private DSAKey dsaKey;
-
- /**
- * The solo constructor.
- */
- public SHA1withDSA_SignatureImpl() throws NoSuchAlgorithmException {
-
- super("SHA1withDSA");
-
- msgDigest = MessageDigest.getInstance("SHA1");
- }
-
- /**
- * Deprecated method.
- *
- * @return
- * null
- */
- protected Object engineGetParameter(String param)
- throws InvalidParameterException {
- if (param == null) {
- throw new NullPointerException("param == null");
- }
- return null;
- }
-
- /**
- * Initializes this signature object with PrivateKey object
- * passed as argument to the method.
- *
- * @params
- * privateKey DSAPrivateKey object
- * @throws
- * InvalidKeyException if privateKey is not DSAPrivateKey object
- */
- protected void engineInitSign(PrivateKey privateKey)
- throws InvalidKeyException {
-
- DSAParams params;
-
- // parameters and private key
- BigInteger p, q, x;
-
- int n;
-
- if (privateKey == null || !(privateKey instanceof DSAPrivateKey)) {
- throw new InvalidKeyException();
- }
-
- params = ((DSAPrivateKey) privateKey).getParams();
- p = params.getP();
- q = params.getQ();
- x = ((DSAPrivateKey) privateKey).getX();
-
- // checks described in DSA standard
- n = p.bitLength();
- if (p.compareTo(BigInteger.valueOf(1)) != 1 || n < 512 || n > 1024 || (n & 077) != 0) {
- throw new InvalidKeyException("bad p");
- }
- if (q.signum() != 1 && q.bitLength() != 160) {
- throw new InvalidKeyException("bad q");
- }
- if (x.signum() != 1 || x.compareTo(q) != -1) {
- throw new InvalidKeyException("x <= 0 || x >= q");
- }
-
- dsaKey = (DSAKey) privateKey;
-
- msgDigest.reset();
- }
-
- /**
- * Initializes this signature object with PublicKey object
- * passed as argument to the method.
- *
- * @params
- * publicKey DSAPublicKey object
- * @throws
- * InvalidKeyException if publicKey is not DSAPublicKey object
- */
- protected void engineInitVerify(PublicKey publicKey)
- throws InvalidKeyException {
-
- // parameters and public key
- BigInteger p, q, y;
-
- int n1;
-
- if (publicKey == null || !(publicKey instanceof DSAPublicKey)) {
- throw new InvalidKeyException("publicKey is not an instance of DSAPublicKey");
- }
-
- DSAParams params = ((DSAPublicKey) publicKey).getParams();
- p = params.getP();
- q = params.getQ();
- y = ((DSAPublicKey) publicKey).getY();
-
- // checks described in DSA standard
- n1 = p.bitLength();
- if (p.compareTo(BigInteger.valueOf(1)) != 1 || n1 < 512 || n1 > 1024 || (n1 & 077) != 0) {
- throw new InvalidKeyException("bad p");
- }
- if (q.signum() != 1 || q.bitLength() != 160) {
- throw new InvalidKeyException("bad q");
- }
- if (y.signum() != 1) {
- throw new InvalidKeyException("y <= 0");
- }
-
- dsaKey = (DSAKey) publicKey;
-
- msgDigest.reset();
- }
-
- /*
- * Deprecated method.
- *
- * @throws
- * InvalidParameterException
- */
- protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
- if (param == null) {
- throw new NullPointerException("param == null");
- }
- throw new InvalidParameterException("invalid parameter for this engine");
- }
-
- /**
- * Returns signature bytes as byte array containing
- * ASN1 representation for two BigInteger objects
- * which is SEQUENCE of two INTEGERS.
- * Length of sequence varies from less than 46 to 48.
- *
- * Resets object to the state it was in
- * when previous call to either "initSign" method was called.
- *
- * @return
- * byte array containing signature in ASN1 representation
- * @throws
- * SignatureException if object's state is not SIGN or
- * signature algorithm cannot process data
- */
-
- protected byte[] engineSign() throws SignatureException {
-
- // names of below BigIntegers are the same as they are defined in DSA standard
- BigInteger r = null;
- BigInteger s = null;
- BigInteger k = null;
-
- // parameters and private key
- BigInteger p, q, g, x;
-
- // BigInteger for message digest
- BigInteger digestBI;
-
- // various byte array being used in computing signature
- byte[] randomBytes;
- byte[] rBytes;
- byte[] sBytes;
- byte[] signature;
-
- int n, n1, n2;
-
- DSAParams params;
-
- if (appRandom == null) {
- appRandom = new SecureRandom();
- }
-
- params = dsaKey.getParams();
- p = params.getP();
- q = params.getQ();
- g = params.getG();
- x = ((DSAPrivateKey) dsaKey).getX();
-
- // forming signature according algorithm described in chapter 5 of DSA standard
-
- digestBI = new BigInteger(1, msgDigest.digest());
-
- randomBytes = new byte[20];
-
- for (;;) {
-
- appRandom.nextBytes(randomBytes);
-
- k = new BigInteger(1, randomBytes);
- if (k.compareTo(q) != -1) {
- continue;
- }
- r = g.modPow(k, p).mod(q);
- if (r.signum() == 0) {
- continue;
- }
-
- s = k.modInverse(q).multiply(digestBI.add(x.multiply(r)).mod(q))
- .mod(q);
-
- if (s.signum() != 0) {
- break;
- }
- }
-
- // forming signature's ASN1 representation which is SEQUENCE of two INTEGERs
- //
- rBytes = r.toByteArray();
- n1 = rBytes.length;
- if ((rBytes[0] & 0x80) != 0) {
- n1++;
- }
- sBytes = s.toByteArray();
- n2 = sBytes.length;
- if ((sBytes[0] & 0x80) != 0) {
- n2++;
- }
-
- signature = new byte[6 + n1 + n2]; // 48 is max. possible length of signature
- signature[0] = (byte) 0x30; // ASN1 SEQUENCE tag
- signature[1] = (byte) (4 + n1 + n2); // total length of two INTEGERs
- signature[2] = (byte) 0x02; // ASN1 INTEGER tag
- signature[3] = (byte) n1; // length of r
- signature[4 + n1] = (byte) 0x02; // ASN1 INTEGER tag
- signature[5 + n1] = (byte) n2; // length of s
-
- if (n1 == rBytes.length) {
- n = 4;
- } else {
- n = 5;
- }
- System.arraycopy(rBytes, 0, signature, n, rBytes.length);
-
- if (n2 == sBytes.length) {
- n = 6 + n1;
- } else {
- n = 7 + n1;
- }
- System.arraycopy(sBytes, 0, signature, n, sBytes.length);
-
- return signature;
- }
-
- /**
- * Updates data to sign or to verify.
- *
- * @params
- * b byte to update
- * @throws
- * SignatureException if object was not initialized for signing or verifying
- */
- protected void engineUpdate(byte b) throws SignatureException {
-
- msgDigest.update(b);
- }
-
- /**
- * Updates data to sign or to verify.
- *
- * @params
- * b byte array containing bytes to update
- * @params
- * off offset in byte array to start from
- * @params
- * len number of bytes to use for updating
- * @throws
- * SignatureException if object was not initialized for signing or verifying
- */
- protected void engineUpdate(byte[] b, int off, int len)
- throws SignatureException {
-
- msgDigest.update(b, off, len);
- }
-
- private boolean checkSignature(byte[] sigBytes, int offset, int length)
- throws SignatureException {
-
- // names of below BigIntegers are the same as they are defined in DSA standard
- BigInteger r, s, w;
- BigInteger u1, u2, v;
-
- // parameters and public key
- BigInteger p, q, g, y;
-
- DSAParams params;
-
- int n1, n2;
-
- byte[] bytes;
- byte[] digest;
-
- // checking up on signature's ASN1
- try {
- byte dummy;
- n1 = sigBytes[offset + 3];
- n2 = sigBytes[offset + n1 + 5];
-
- if (sigBytes[offset + 0] != 0x30 || sigBytes[offset + 2] != 2
- || sigBytes[offset + n1 + 4] != 2
- || sigBytes[offset + 1] != (n1 + n2 + 4) || n1 > 21
- || n2 > 21
- || (length != 0 && (sigBytes[offset + 1] + 2) > length)) {
- throw new SignatureException("signature bytes have invalid encoding");
- }
-
- dummy = sigBytes[5 + n1 + n2]; // to check length of sigBytes
- } catch (ArrayIndexOutOfBoundsException e) {
- throw new SignatureException("bad argument: byte[] is too small");
- }
-
- digest = msgDigest.digest();
-
- bytes = new byte[n1];
- System.arraycopy(sigBytes, offset + 4, bytes, 0, n1);
- r = new BigInteger(bytes);
-
- bytes = new byte[n2];
- System.arraycopy(sigBytes, offset + 6 + n1, bytes, 0, n2);
- s = new BigInteger(bytes);
-
- params = dsaKey.getParams();
- p = params.getP();
- q = params.getQ();
- g = params.getG();
- y = ((DSAPublicKey) dsaKey).getY();
-
- // forming signature according algorithm described in chapter 6 of DSA standard
-
- if (r.signum() != 1 || r.compareTo(q) != -1 || s.signum() != 1
- || s.compareTo(q) != -1) {
- return false;
- }
-
- w = s.modInverse(q);
-
- u1 = (new BigInteger(1, digest)).multiply(w).mod(q);
- u2 = r.multiply(w).mod(q);
-
- v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);
-
- if (v.compareTo(r) != 0) {
- return false;
- }
- return true;
- }
-
- /**
- * Verifies the signature bytes.
- *
- * @params
- * sigBytes byte array with signature bytes to verify.
- * @return
- * true if signature bytes were verified, false otherwise
- * @throws
- * SignatureException if object's state is not VERIFY or
- * signature format is not ASN1 representation or
- * signature algorithm cannot process data
- */
- protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
- if (sigBytes == null) {
- throw new NullPointerException("sigBytes == null");
- }
-
- return checkSignature(sigBytes, 0, 0);
- }
-
- /**
- * Verifies the signature bytes.
- *
- * @params
- * sigBytes byte array with signature bytes to verify.
- * @params
- * offset index in sigBytes to start from
- * @params
- * length number of bytes allotted for signature
- * @return
- * true if signature bytes were verified, false otherwise
- * @throws
- * SignatureException if object's state is not VERIFY or
- * signature format is not ASN1 representation or
- * signature algorithm cannot process data
- */
- protected boolean engineVerify(byte[] sigBytes, int offset, int length)
- throws SignatureException {
- return checkSignature(sigBytes, offset, length);
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.java
deleted file mode 100644
index 4f4232a..0000000
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/ThreeIntegerSequence.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.harmony.security.provider.crypto;
-
-import org.apache.harmony.security.asn1.ASN1Integer;
-import org.apache.harmony.security.asn1.ASN1Sequence;
-import org.apache.harmony.security.asn1.ASN1Type;
-import org.apache.harmony.security.asn1.BerInputStream;
-
-
-/**
- * The auxiliary class providing means to process ASN1Sequence of three Integers.
- * Such sequences are parts of ASN1 encoded formats for DSA private and public keys.
- */
-class ThreeIntegerSequence {
-
- byte[] p, q, g;
-
- private byte[] encoding;
-
- ThreeIntegerSequence(byte[] p, byte[] q, byte[] g) {
-
- this.p = p;
- this.q = q;
- this.g = g;
- encoding = null;
- }
-
- public byte[] getEncoded() {
- if (encoding == null) {
- encoding = ASN1.encode(this);
- }
- return encoding;
- }
-
- public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
- ASN1Integer.getInstance(), ASN1Integer.getInstance(),
- ASN1Integer.getInstance() }) {
-
- protected Object getDecodedObject(BerInputStream in) {
-
- Object[] values = (Object[]) in.content;
-
- return new ThreeIntegerSequence((byte[]) values[0],
- (byte[]) values[1], (byte[]) values[2]);
- }
-
- protected void getValues(Object object, Object[] values) {
-
- ThreeIntegerSequence mySeq = (ThreeIntegerSequence) object;
-
- values[0] = mySeq.p;
- values[1] = mySeq.q;
- values[2] = mySeq.g;
- }
- };
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java b/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
index 135394d..e7f3596 100644
--- a/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
+++ b/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
@@ -21,6 +21,7 @@
*/
package org.apache.harmony.security.utils;
+import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
@@ -30,10 +31,12 @@ import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.Signature;
import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.LinkedList;
import java.util.List;
import javax.security.auth.x500.X500Principal;
@@ -42,7 +45,6 @@ import org.apache.harmony.security.asn1.BerInputStream;
import org.apache.harmony.security.pkcs7.ContentInfo;
import org.apache.harmony.security.pkcs7.SignedData;
import org.apache.harmony.security.pkcs7.SignerInfo;
-import org.apache.harmony.security.provider.cert.X509CertImpl;
import org.apache.harmony.security.x501.AttributeTypeAndValue;
public class JarUtils {
@@ -53,27 +55,18 @@ public class JarUtils {
new int[] {1, 2, 840, 113549, 1, 9, 4};
/**
- * @see #verifySignature(InputStream, InputStream, boolean)
- */
- public static Certificate[] verifySignature(InputStream signature, InputStream signatureBlock)
- throws IOException, GeneralSecurityException {
- return verifySignature(signature, signatureBlock, false);
- }
-
- /**
* This method handle all the work with PKCS7, ASN1 encoding, signature verifying,
* and certification path building.
* See also PKCS #7: Cryptographic Message Syntax Standard:
* http://www.ietf.org/rfc/rfc2315.txt
* @param signature - the input stream of signature file to be verified
* @param signatureBlock - the input stream of corresponding signature block file
- * @param chainCheck - whether to validate certificate chain signatures
* @return array of certificates used to verify the signature file
* @throws IOException - if some errors occurs during reading from the stream
* @throws GeneralSecurityException - if signature verification process fails
*/
public static Certificate[] verifySignature(InputStream signature, InputStream
- signatureBlock, boolean chainCheck) throws IOException, GeneralSecurityException {
+ signatureBlock) throws IOException, GeneralSecurityException {
BerInputStream bis = new BerInputStream(signatureBlock);
ContentInfo info = (ContentInfo)ContentInfo.ASN1.decode(bis);
@@ -87,9 +80,13 @@ public class JarUtils {
return null;
}
X509Certificate[] certs = new X509Certificate[encCerts.size()];
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
int i = 0;
for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
- certs[i++] = new X509CertImpl(encCert);
+ final byte[] encoded = encCert.getEncoded();
+ final InputStream is = new ByteArrayInputStream(encoded);
+ certs[i++] = new VerbatimX509Certificate((X509Certificate) cf.generateCertificate(is),
+ encoded);
}
List<SignerInfo> sigInfos = signedData.getSignerInfos();
@@ -131,17 +128,16 @@ public class JarUtils {
String alg = null;
Signature sig = null;
- if (daOid != null && deaOid != null) {
- alg = daOid + "with" + deaOid;
+ if (deaOid != null) {
+ alg = deaOid;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
}
- // Try to convert to names instead of OID.
- if (sig == null) {
- final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
- alg = daName + "with" + deaName;
+ final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
+ if (sig == null && deaName != null) {
+ alg = deaName;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
@@ -149,19 +145,17 @@ public class JarUtils {
}
}
- /*
- * TODO figure out the case in which we'd only use digestAlgorithm and
- * add a test for it.
- */
- if (sig == null && daOid != null) {
- alg = daOid;
+ if (sig == null && daOid != null && deaOid != null) {
+ alg = daOid + "with" + deaOid;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
}
- if (sig == null && daName != null) {
- alg = daName;
+ // Try to convert to names instead of OID.
+ if (sig == null) {
+ final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
+ alg = daName + "with" + deaName;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
@@ -232,54 +226,63 @@ public class JarUtils {
throw new SecurityException("Incorrect signature");
}
- return createChain(certs[issuerSertIndex], certs, chainCheck);
+ return createChain(certs[issuerSertIndex], certs);
}
- private static X509Certificate[] createChain(X509Certificate signer,
- X509Certificate[] candidates, boolean chainCheck) {
- LinkedList chain = new LinkedList();
- chain.add(0, signer);
+ private static X509Certificate[] createChain(X509Certificate signer,
+ X509Certificate[] candidates) {
+ Principal issuer = signer.getIssuerDN();
// Signer is self-signed
- if (signer.getSubjectDN().equals(signer.getIssuerDN())){
- return (X509Certificate[])chain.toArray(new X509Certificate[1]);
+ if (signer.getSubjectDN().equals(issuer)) {
+ return new X509Certificate[] { signer };
}
- Principal issuer = signer.getIssuerDN();
+ ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>(candidates.length + 1);
+ chain.add(0, signer);
+
X509Certificate issuerCert;
- X509Certificate subjectCert = signer;
int count = 1;
while (true) {
- issuerCert = findCert(issuer, candidates, subjectCert, chainCheck);
- if( issuerCert == null) {
+ issuerCert = findCert(issuer, candidates);
+ if (issuerCert == null) {
break;
}
chain.add(issuerCert);
count++;
- if (issuerCert.getSubjectDN().equals(issuerCert.getIssuerDN())) {
+ issuer = issuerCert.getIssuerDN();
+ if (issuerCert.getSubjectDN().equals(issuer)) {
break;
}
- issuer = issuerCert.getIssuerDN();
- subjectCert = issuerCert;
}
- return (X509Certificate[])chain.toArray(new X509Certificate[count]);
+ return chain.toArray(new X509Certificate[count]);
}
- private static X509Certificate findCert(Principal issuer, X509Certificate[] candidates,
- X509Certificate subjectCert, boolean chainCheck) {
+ private static X509Certificate findCert(Principal issuer, X509Certificate[] candidates) {
for (int i = 0; i < candidates.length; i++) {
if (issuer.equals(candidates[i].getSubjectDN())) {
- if (chainCheck) {
- try {
- subjectCert.verify(candidates[i].getPublicKey());
- } catch (Exception e) {
- continue;
- }
- }
return candidates[i];
}
}
return null;
}
+ /**
+ * For legacy reasons we need to return exactly the original encoded
+ * certificate bytes, instead of letting the underlying implementation have
+ * a shot at re-encoding the data.
+ */
+ private static class VerbatimX509Certificate extends WrappedX509Certificate {
+ private byte[] encodedVerbatim;
+
+ public VerbatimX509Certificate(X509Certificate wrapped, byte[] encodedVerbatim) {
+ super(wrapped);
+ this.encodedVerbatim = encodedVerbatim;
+ }
+
+ @Override
+ public byte[] getEncoded() throws CertificateEncodingException {
+ return encodedVerbatim;
+ }
+ }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/utils/WrappedX509Certificate.java b/luni/src/main/java/org/apache/harmony/security/utils/WrappedX509Certificate.java
new file mode 100644
index 0000000..2b09309
--- /dev/null
+++ b/luni/src/main/java/org/apache/harmony/security/utils/WrappedX509Certificate.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2014 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.harmony.security.utils;
+
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Principal;
+import java.security.PublicKey;
+import java.security.SignatureException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+import java.util.Set;
+
+public class WrappedX509Certificate extends X509Certificate {
+ private final X509Certificate wrapped;
+
+ public WrappedX509Certificate(X509Certificate wrapped) {
+ this.wrapped = wrapped;
+ }
+
+ @Override
+ public Set<String> getCriticalExtensionOIDs() {
+ return wrapped.getCriticalExtensionOIDs();
+ }
+
+ @Override
+ public byte[] getExtensionValue(String oid) {
+ return wrapped.getExtensionValue(oid);
+ }
+
+ @Override
+ public Set<String> getNonCriticalExtensionOIDs() {
+ return wrapped.getNonCriticalExtensionOIDs();
+ }
+
+ @Override
+ public boolean hasUnsupportedCriticalExtension() {
+ return wrapped.hasUnsupportedCriticalExtension();
+ }
+
+ @Override
+ public void checkValidity() throws CertificateExpiredException,
+ CertificateNotYetValidException {
+ wrapped.checkValidity();
+ }
+
+ @Override
+ public void checkValidity(Date date) throws CertificateExpiredException,
+ CertificateNotYetValidException {
+ wrapped.checkValidity(date);
+ }
+
+ @Override
+ public int getVersion() {
+ return wrapped.getVersion();
+ }
+
+ @Override
+ public BigInteger getSerialNumber() {
+ return wrapped.getSerialNumber();
+ }
+
+ @Override
+ public Principal getIssuerDN() {
+ return wrapped.getIssuerDN();
+ }
+
+ @Override
+ public Principal getSubjectDN() {
+ return wrapped.getSubjectDN();
+ }
+
+ @Override
+ public Date getNotBefore() {
+ return wrapped.getNotBefore();
+ }
+
+ @Override
+ public Date getNotAfter() {
+ return wrapped.getNotAfter();
+ }
+
+ @Override
+ public byte[] getTBSCertificate() throws CertificateEncodingException {
+ return wrapped.getTBSCertificate();
+ }
+
+ @Override
+ public byte[] getSignature() {
+ return wrapped.getSignature();
+ }
+
+ @Override
+ public String getSigAlgName() {
+ return wrapped.getSigAlgName();
+ }
+
+ @Override
+ public String getSigAlgOID() {
+ return wrapped.getSigAlgOID();
+ }
+
+ @Override
+ public byte[] getSigAlgParams() {
+ return wrapped.getSigAlgParams();
+ }
+
+ @Override
+ public boolean[] getIssuerUniqueID() {
+ return wrapped.getIssuerUniqueID();
+ }
+
+ @Override
+ public boolean[] getSubjectUniqueID() {
+ return wrapped.getSubjectUniqueID();
+ }
+
+ @Override
+ public boolean[] getKeyUsage() {
+ return wrapped.getKeyUsage();
+ }
+
+ @Override
+ public int getBasicConstraints() {
+ return wrapped.getBasicConstraints();
+ }
+
+ @Override
+ public byte[] getEncoded() throws CertificateEncodingException {
+ return wrapped.getEncoded();
+ }
+
+ @Override
+ public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException {
+ wrapped.verify(key);
+ }
+
+ @Override
+ public void verify(PublicKey key, String sigProvider) throws CertificateException,
+ NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
+ SignatureException {
+ verify(key, sigProvider);
+ }
+
+ @Override
+ public String toString() {
+ return wrapped.toString();
+ }
+
+ @Override
+ public PublicKey getPublicKey() {
+ return wrapped.getPublicKey();
+ }
+}
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java
index 3b5f622..171d9c2 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java
@@ -287,6 +287,8 @@ public final class AttributeTypeAndValue {
} else {
if (X500Principal.CANONICAL.equals(attrFormat)) {
sb.append(value.makeCanonical());
+ } else if (X500Principal.RFC2253.equals(attrFormat)) {
+ sb.append(value.getRFC2253String());
} else {
sb.append(value.escapedString);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java
index 160c62d..bdc3c84 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java
@@ -30,27 +30,26 @@ import org.apache.harmony.security.utils.ObjectIdentifier;
* AttributeTypeAndValue comparator
*
*/
-public class AttributeTypeAndValueComparator implements Comparator, Serializable {
+public class AttributeTypeAndValueComparator implements Comparator<AttributeTypeAndValue>,
+ Serializable {
private static final long serialVersionUID = -1286471842007103132L;
/**
* compares two AttributeTypeAndValues
*
- * @param obj1
+ * @param atav1
* first AttributeTypeAndValue
- * @param obj2
+ * @param atav2
* second AttributeTypeAndValue
* @return -1 of first AttributeTypeAndValue "less" than second
* AttributeTypeAndValue 1 otherwise, 0 if they are equal
*/
- public int compare(Object obj1, Object obj2) {
- if (obj1 == obj2) {
+ public int compare(AttributeTypeAndValue atav1, AttributeTypeAndValue atav2) {
+ if (atav1 == atav2) {
return 0;
}
- AttributeTypeAndValue atav1 = (AttributeTypeAndValue) obj1;
- AttributeTypeAndValue atav2 = (AttributeTypeAndValue) obj2;
String kw1 = atav1.getType().getName();
String kw2 = atav2.getType().getName();
if (kw1 != null && kw2 == null) {
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
index 63be3f1..b3eb200 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
@@ -37,8 +37,12 @@ public final class AttributeValue {
public boolean wasEncoded;
+ private boolean hasConsecutiveSpaces;
+
public final String escapedString;
+ private String rfc2253String;
+
private String hexString;
private final int tag;
@@ -197,8 +201,9 @@ public final class AttributeValue {
* Escapes:
* 1) chars ",", "+", """, "\", "<", ">", ";" (RFC 2253)
* 2) chars "#", "=" (required by RFC 1779)
- * 3) a space char at the beginning or end
- * 4) according to the requirement to be RFC 1779 compatible:
+ * 3) leading or trailing spaces
+ * 4) consecutive spaces (RFC 1779)
+ * 5) according to the requirement to be RFC 1779 compatible:
* '#' char is escaped in any position
*/
private String makeEscaped(String name) {
@@ -208,14 +213,35 @@ public final class AttributeValue {
}
StringBuilder buf = new StringBuilder(length * 2);
+ // Keeps track of whether we are escaping spaces.
+ boolean escapeSpaces = false;
+
for (int index = 0; index < length; index++) {
char ch = name.charAt(index);
switch (ch) {
case ' ':
- if (index == 0 || index == (length - 1)) {
- // escape first or last space
+ /*
+ * We should escape spaces in the following cases:
+ * 1) at the beginning
+ * 2) at the end
+ * 3) consecutive spaces
+ * Since multiple spaces at the beginning or end will be covered by
+ * 3, we don't need a special case to check for that. Note that RFC 2253
+ * doesn't escape consecutive spaces, so they are removed in
+ * getRFC2253String instead of making two different strings here.
+ */
+ if (index < (length - 1)) {
+ boolean nextIsSpace = name.charAt(index + 1) == ' ';
+ escapeSpaces = escapeSpaces || nextIsSpace || index == 0;
+ hasConsecutiveSpaces |= nextIsSpace;
+ } else {
+ escapeSpaces = true;
+ }
+
+ if (escapeSpaces) {
buf.append('\\');
}
+
buf.append(' ');
break;
@@ -241,6 +267,10 @@ public final class AttributeValue {
buf.append(ch);
break;
}
+
+ if (escapeSpaces && ch != ' ') {
+ escapeSpaces = false;
+ }
}
return buf.toString();
@@ -295,4 +325,50 @@ public final class AttributeValue {
return buf.toString();
}
+
+ /**
+ * Removes escape sequences used in RFC1779 escaping but not in RFC2253 and
+ * returns the RFC2253 string to the caller..
+ */
+ public String getRFC2253String() {
+ if (!hasConsecutiveSpaces) {
+ return escapedString;
+ }
+
+ if (rfc2253String == null) {
+ // Scan backwards first since runs of spaces at the end are escaped.
+ int lastIndex = escapedString.length() - 2;
+ for (int i = lastIndex; i > 0; i -= 2) {
+ if (escapedString.charAt(i) == '\\' && escapedString.charAt(i + 1) == ' ') {
+ lastIndex = i - 1;
+ }
+ }
+
+ boolean beginning = true;
+ StringBuilder sb = new StringBuilder(escapedString.length());
+ for (int i = 0; i < escapedString.length(); i++) {
+ char ch = escapedString.charAt(i);
+ if (ch != '\\') {
+ sb.append(ch);
+ beginning = false;
+ } else {
+ char nextCh = escapedString.charAt(i + 1);
+ if (nextCh == ' ') {
+ if (beginning || i > lastIndex) {
+ sb.append(ch);
+ }
+ sb.append(nextCh);
+ } else {
+ sb.append(ch);
+ sb.append(nextCh);
+ beginning = false;
+ }
+
+ i++;
+ }
+ }
+ rfc2253String = sb.toString();
+ }
+ return rfc2253String;
+ }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Extension.java b/luni/src/main/java/org/apache/harmony/security/x509/Extension.java
index d9b02f9..d5d8015 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Extension.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Extension.java
@@ -23,6 +23,7 @@
package org.apache.harmony.security.x509;
import java.io.IOException;
+import java.io.OutputStream;
import java.util.Arrays;
import org.apache.harmony.security.asn1.ASN1Boolean;
import org.apache.harmony.security.asn1.ASN1OctetString;
@@ -49,7 +50,7 @@ import org.apache.harmony.security.utils.Array;
* }
* </pre>
*/
-public final class Extension {
+public final class Extension implements java.security.cert.Extension {
// critical constants
public static final boolean CRITICAL = true;
public static final boolean NON_CRITICAL = false;
@@ -145,7 +146,8 @@ public final class Extension {
/**
* Returns the value of extnID field of the structure.
*/
- public String getExtnID() {
+ @Override
+ public String getId() {
if (extnID_str == null) {
extnID_str = ObjectIdentifier.toString(extnID);
}
@@ -155,14 +157,16 @@ public final class Extension {
/**
* Returns the value of critical field of the structure.
*/
- public boolean getCritical() {
+ @Override
+ public boolean isCritical() {
return critical;
}
/**
* Returns the value of extnValue field of the structure.
*/
- public byte[] getExtnValue() {
+ @Override
+ public byte[] getValue() {
return extnValue;
}
@@ -187,6 +191,11 @@ public final class Extension {
return encoding;
}
+ @Override
+ public void encode(OutputStream out) throws IOException {
+ out.write(getEncoded());
+ }
+
@Override public boolean equals(Object ext) {
if (!(ext instanceof Extension)) {
return false;
@@ -287,7 +296,7 @@ public final class Extension {
}
public void dumpValue(StringBuilder sb, String prefix) {
- sb.append("OID: ").append(getExtnID()).append(", Critical: ").append(critical).append('\n');
+ sb.append("OID: ").append(getId()).append(", Critical: ").append(critical).append('\n');
if (!valueDecoded) {
try {
decodeExtensionValue();
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java b/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java
index 92ff3a9..7a10ebc 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java
@@ -136,8 +136,8 @@ public final class Extensions {
Set<String> localNoncritical = new HashSet<String>(size);
Boolean localHasUnsupported = Boolean.FALSE;
for (Extension extension : extensions) {
- String oid = extension.getExtnID();
- if (extension.getCritical()) {
+ String oid = extension.getId();
+ if (extension.isCritical()) {
if (!SUPPORTED_CRITICAL.contains(oid)) {
localHasUnsupported = Boolean.TRUE;
}
@@ -162,7 +162,7 @@ public final class Extensions {
if (localOidMap == null) {
localOidMap = new HashMap<String, Extension>();
for (Extension extension : extensions) {
- localOidMap.put(extension.getExtnID(), extension);
+ localOidMap.put(extension.getId(), extension);
}
this.oidMap = localOidMap;
}
@@ -311,7 +311,7 @@ public final class Extensions {
}
Collection<List<?>> collection = ((GeneralNames) GeneralNames.ASN1.decode(extension
- .getExtnValue())).getPairsList();
+ .getValue())).getPairsList();
/*
* If the extension had any invalid entries, we may have an empty
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java b/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java
index b7c1847..533c79c 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java
@@ -44,6 +44,13 @@ public final class InvalidityDate extends ExtensionValue {
}
/**
+ * Constructs the object from a date instance.
+ */
+ public InvalidityDate(Date date) {
+ this.date = (Date) date.clone();
+ }
+
+ /**
* Returns the invalidity date.
*/
public Date getDate() {
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java b/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java
index 183ecde..2c9d6aa 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java
@@ -18,6 +18,7 @@
package org.apache.harmony.security.x509;
import java.io.IOException;
+import java.security.cert.CRLReason;
import org.apache.harmony.security.asn1.ASN1Enumerated;
import org.apache.harmony.security.asn1.ASN1Type;
@@ -71,6 +72,14 @@ public final class ReasonCode extends ExtensionValue {
return encoding;
}
+ public CRLReason getReason() {
+ CRLReason[] values = CRLReason.values();
+ if (code < 0 || code > values.length) {
+ return null;
+ }
+ return values[code];
+ }
+
@Override public void dumpValue(StringBuilder sb, String prefix) {
sb.append(prefix).append("Reason Code: [ ");
switch (code) {
diff --git a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
index db6f4ef..fa6308e 100644
--- a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
+++ b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
@@ -48,7 +48,7 @@ class ExpatParser {
private boolean inStartElement = false;
private int attributeCount = -1;
- private int attributePointer = 0;
+ private long attributePointer = 0;
private final Locator locator = new ExpatLocator();
@@ -129,7 +129,7 @@ class ExpatParser {
* @param attributeCount number of attributes
*/
/*package*/ void startElement(String uri, String localName, String qName,
- int attributePointer, int attributeCount) throws SAXException {
+ long attributePointer, int attributeCount) throws SAXException {
ContentHandler contentHandler = xmlReader.contentHandler;
if (contentHandler == null) {
return;
@@ -772,7 +772,7 @@ class ExpatParser {
@Override
void startElement(String uri, String localName, String qName,
- int attributePointer, int attributeCount) throws SAXException {
+ long attributePointer, int attributeCount) throws SAXException {
/*
* Skip topmost element generated by our workaround in
* {@link #handleExternalEntity}.
diff --git a/luni/src/main/native/AsynchronousSocketCloseMonitor.cpp b/luni/src/main/native/AsynchronousCloseMonitor.cpp
index 9617e9d..31cde00 100644
--- a/luni/src/main/native/AsynchronousSocketCloseMonitor.cpp
+++ b/luni/src/main/native/AsynchronousCloseMonitor.cpp
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-#define LOG_TAG "AsynchronousSocketCloseMonitor"
+#define LOG_TAG "AsynchronousCloseMonitor"
-#include "AsynchronousSocketCloseMonitor.h"
+#include "AsynchronousCloseMonitor.h"
#include "cutils/log.h"
#include <errno.h>
@@ -27,27 +27,28 @@
* We use an intrusive doubly-linked list to keep track of blocked threads.
* This gives us O(1) insertion and removal, and means we don't need to do any allocation.
* (The objects themselves are stack-allocated.)
- * Waking potentially-blocked threads when a socket is closed is O(n) in the total number of
- * blocked threads (not the number of threads actually blocked on the socket in question).
- * For now at least, this seems like a good compromise for Android.
+ * Waking potentially-blocked threads when a file descriptor is closed is O(n) in the total number
+ * of blocked threads (not the number of threads actually blocked on the file descriptor in
+ * question). For now at least, this seems like a good compromise for Android.
*/
static pthread_mutex_t blockedThreadListMutex = PTHREAD_MUTEX_INITIALIZER;
-static AsynchronousSocketCloseMonitor* blockedThreadList = NULL;
+static AsynchronousCloseMonitor* blockedThreadList = NULL;
/**
- * The specific signal chosen here is arbitrary.
+ * The specific signal chosen here is arbitrary, but bionic needs to know so that SIGRTMIN
+ * starts at a higher value.
*/
#if defined(__APPLE__)
static const int BLOCKED_THREAD_SIGNAL = SIGUSR2;
#else
-static const int BLOCKED_THREAD_SIGNAL = SIGRTMIN + 2;
+static const int BLOCKED_THREAD_SIGNAL = __SIGRTMIN + 2;
#endif
static void blockedThreadSignalHandler(int /*signal*/) {
// Do nothing. We only sent this signal for its side-effect of interrupting syscalls.
}
-void AsynchronousSocketCloseMonitor::init() {
+void AsynchronousCloseMonitor::init() {
// Ensure that the signal we send interrupts system calls but doesn't kill threads.
// Using sigaction(2) lets us ensure that the SA_RESTART flag is not set.
// (The whole reason we're sending this signal is to unblock system calls!)
@@ -61,21 +62,27 @@ void AsynchronousSocketCloseMonitor::init() {
}
}
-void AsynchronousSocketCloseMonitor::signalBlockedThreads(int fd) {
+void AsynchronousCloseMonitor::signalBlockedThreads(int fd) {
ScopedPthreadMutexLock lock(&blockedThreadListMutex);
- for (AsynchronousSocketCloseMonitor* it = blockedThreadList; it != NULL; it = it->mNext) {
+ for (AsynchronousCloseMonitor* it = blockedThreadList; it != NULL; it = it->mNext) {
if (it->mFd == fd) {
+ it->mSignaled = true;
pthread_kill(it->mThread, BLOCKED_THREAD_SIGNAL);
// Keep going, because there may be more than one thread...
}
}
}
-AsynchronousSocketCloseMonitor::AsynchronousSocketCloseMonitor(int fd) {
+bool AsynchronousCloseMonitor::wasSignaled() const {
+ return mSignaled;
+}
+
+AsynchronousCloseMonitor::AsynchronousCloseMonitor(int fd) {
ScopedPthreadMutexLock lock(&blockedThreadListMutex);
// Who are we, and what are we waiting for?
mThread = pthread_self();
mFd = fd;
+ mSignaled = false;
// Insert ourselves at the head of the intrusive doubly-linked list...
mPrev = NULL;
mNext = blockedThreadList;
@@ -85,7 +92,7 @@ AsynchronousSocketCloseMonitor::AsynchronousSocketCloseMonitor(int fd) {
blockedThreadList = this;
}
-AsynchronousSocketCloseMonitor::~AsynchronousSocketCloseMonitor() {
+AsynchronousCloseMonitor::~AsynchronousCloseMonitor() {
ScopedPthreadMutexLock lock(&blockedThreadListMutex);
// Unlink ourselves from the intrusive doubly-linked list...
if (mNext != NULL) {
diff --git a/luni/src/main/native/AsynchronousSocketCloseMonitor.h b/luni/src/main/native/AsynchronousCloseMonitor.h
index 3370e22..eefbbdf 100644
--- a/luni/src/main/native/AsynchronousSocketCloseMonitor.h
+++ b/luni/src/main/native/AsynchronousCloseMonitor.h
@@ -14,47 +14,53 @@
* limitations under the License.
*/
-#ifndef ASYNCHRONOUS_SOCKET_CLOSE_MONITOR_H_included
-#define ASYNCHRONOUS_SOCKET_CLOSE_MONITOR_H_included
+#ifndef ASYNCHRONOUS_CLOSE_MONITOR_H_included
+#define ASYNCHRONOUS_CLOSE_MONITOR_H_included
#include "ScopedPthreadMutexLock.h"
#include <pthread.h>
/**
- * AsynchronousSocketCloseMonitor helps implement Java's asynchronous Socket.close semantics.
+ * AsynchronousCloseMonitor helps implement Java's asynchronous close semantics.
*
- * AsynchronousSocketCloseMonitor::init must be called before anything else.
+ * AsynchronousCloseMonitor::init must be called before anything else.
*
- * Every blocking network I/O operation must be surrounded by an AsynchronousSocketCloseMonitor
+ * Every blocking I/O operation must be surrounded by an AsynchronousCloseMonitor
* instance. For example:
*
* {
- * AsynchronousSocketCloseMonitor monitor(fd);
+ * AsynchronousCloseMonitor monitor(fd);
* byteCount = ::read(fd, buf, sizeof(buf));
* }
*
* To interrupt all threads currently blocked on file descriptor 'fd', call signalBlockedThreads:
*
- * AsynchronousSocketCloseMonitor::signalBlockedThreads(fd);
+ * AsynchronousCloseMonitor::signalBlockedThreads(fd);
+ *
+ * To test to see if the interruption was due to the signalBlockedThreads call:
+ *
+ * monitor.wasSignaled();
*/
-class AsynchronousSocketCloseMonitor {
+class AsynchronousCloseMonitor {
public:
- AsynchronousSocketCloseMonitor(int fd);
- ~AsynchronousSocketCloseMonitor();
+ AsynchronousCloseMonitor(int fd);
+ ~AsynchronousCloseMonitor();
+ bool wasSignaled() const;
static void init();
static void signalBlockedThreads(int fd);
private:
- AsynchronousSocketCloseMonitor* mPrev;
- AsynchronousSocketCloseMonitor* mNext;
+ AsynchronousCloseMonitor* mPrev;
+ AsynchronousCloseMonitor* mNext;
pthread_t mThread;
int mFd;
+ bool mSignaled;
// Disallow copy and assignment.
- AsynchronousSocketCloseMonitor(const AsynchronousSocketCloseMonitor&);
- void operator=(const AsynchronousSocketCloseMonitor&);
+ AsynchronousCloseMonitor(const AsynchronousCloseMonitor&);
+ void operator=(const AsynchronousCloseMonitor&);
};
-#endif // ASYNCHRONOUS_SOCKET_CLOSE_MONITOR_H_included
+#endif // ASYNCHRONOUS_CLOSE_MONITOR_H_included
diff --git a/luni/src/main/native/IcuUtilities.cpp b/luni/src/main/native/IcuUtilities.cpp
index c1bdd0f..7ce2168 100644
--- a/luni/src/main/native/IcuUtilities.cpp
+++ b/luni/src/main/native/IcuUtilities.cpp
@@ -28,10 +28,6 @@
#include "unicode/uloc.h"
#include "unicode/ustring.h"
-Locale getLocale(JNIEnv* env, jstring localeName) {
- return Locale::createFromName(ScopedUtfChars(env, localeName).c_str());
-}
-
jobjectArray fromStringEnumeration(JNIEnv* env, UErrorCode& status, const char* provider, StringEnumeration* se) {
if (maybeThrowIcuException(env, provider, status)) {
return NULL;
@@ -65,6 +61,8 @@ bool maybeThrowIcuException(JNIEnv* env, const char* function, UErrorCode error)
exceptionClass = "java/lang/ArrayIndexOutOfBoundsException";
} else if (error == U_UNSUPPORTED_ERROR) {
exceptionClass = "java/lang/UnsupportedOperationException";
+ } else if (error == U_FORMAT_INEXACT_ERROR) {
+ exceptionClass = "java/lang/ArithmeticException";
}
jniThrowExceptionFmt(env, exceptionClass, "%s failed: %s", function, u_errorName(error));
return true;
diff --git a/luni/src/main/native/IcuUtilities.h b/luni/src/main/native/IcuUtilities.h
index cff1e0d..737379e 100644
--- a/luni/src/main/native/IcuUtilities.h
+++ b/luni/src/main/native/IcuUtilities.h
@@ -17,14 +17,13 @@
#ifndef ICU_UTILITIES_H_included
#define ICU_UTILITIES_H_included
+#undef U_HAVE_STD_STRING
#define U_HAVE_STD_STRING 1 // For UnicodeString::toUTF8String(std::string&).
#include "jni.h"
#include "ustrenum.h" // For UStringEnumeration.
#include "unicode/utypes.h" // For UErrorCode.
-#include "unicode/locid.h" // For Locale.
-extern Locale getLocale(JNIEnv* env, jstring localeName);
extern jobjectArray fromStringEnumeration(JNIEnv* env, UErrorCode& status, const char* provider, StringEnumeration*);
bool maybeThrowIcuException(JNIEnv* env, const char* function, UErrorCode error);
diff --git a/luni/src/main/native/NetworkUtilities.h b/luni/src/main/native/NetworkUtilities.h
index 28e9fa5..6b720d4 100644
--- a/luni/src/main/native/NetworkUtilities.h
+++ b/luni/src/main/native/NetworkUtilities.h
@@ -35,7 +35,7 @@ bool inetAddressToSockaddr(JNIEnv* env, jobject inetAddress, int port,
// An Inet4Address will be converted to a sockaddr_in. This is probably only useful for
// getnameinfo(2), where we'll be presenting the result to the user and the user may actually
// care whether the original address was pure IPv4 or an IPv4-mapped IPv6 address, and
-// for the MCAST_JOIN_GROUP socket option.
+// for the MCAST_JOIN_GROUP, MCAST_LEAVE_GROUP, and other multicast socket options.
bool inetAddressToSockaddrVerbatim(JNIEnv* env, jobject inetAddress, int port,
sockaddr_storage& ss, socklen_t& sa_len);
diff --git a/luni/src/main/native/Portability.h b/luni/src/main/native/Portability.h
index 60b7062..1520311 100644
--- a/luni/src/main/native/Portability.h
+++ b/luni/src/main/native/Portability.h
@@ -64,9 +64,8 @@ static inline int mincore(void* addr, size_t length, unsigned char* vec) {
// For statfs(3).
#include <sys/param.h>
#include <sys/mount.h>
-#define f_frsize f_bsize // TODO: close enough?
-#else
+#else // defined(__APPLE__)
// Bionic or glibc.
@@ -74,6 +73,15 @@ static inline int mincore(void* addr, size_t length, unsigned char* vec) {
#include <sys/sendfile.h>
#include <sys/statvfs.h>
-#endif
+#endif // defined(__APPLE__)
+
+#if !defined(__BIONIC__)
+#include <netdb.h>
+#include "../../bionic/libc/dns/include/resolv_netid.h"
+inline int android_getaddrinfofornet(const char *hostname, const char *servname,
+ const struct addrinfo *hints, unsigned /*netid*/, unsigned /*mark*/, struct addrinfo **res) {
+ return getaddrinfo(hostname, servname, hints, res);
+}
+#endif // !defined(__BIONIC__)
#endif // PORTABILITY_H_included
diff --git a/luni/src/main/native/Register.cpp b/luni/src/main/native/Register.cpp
index 6b24a36..6a2c939 100644
--- a/luni/src/main/native/Register.cpp
+++ b/luni/src/main/native/Register.cpp
@@ -23,7 +23,7 @@
#include <stdlib.h>
// DalvikVM calls this on startup, so we can statically register all our native methods.
-int JNI_OnLoad(JavaVM* vm, void*) {
+jint JNI_OnLoad(JavaVM* vm, void*) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
ALOGE("JavaVM::GetEnv() failed");
@@ -33,8 +33,9 @@ int JNI_OnLoad(JavaVM* vm, void*) {
ScopedLocalFrame localFrame(env);
#define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
- REGISTER(register_java_io_Console);
+ REGISTER(register_android_system_OsConstants);
REGISTER(register_java_io_File);
+ REGISTER(register_java_io_FileDescriptor);
REGISTER(register_java_io_ObjectStreamClass);
REGISTER(register_java_lang_Character);
REGISTER(register_java_lang_Double);
@@ -49,6 +50,7 @@ int JNI_OnLoad(JavaVM* vm, void*) {
REGISTER(register_java_nio_ByteOrder);
REGISTER(register_java_nio_charset_Charsets);
REGISTER(register_java_text_Bidi);
+ REGISTER(register_java_util_jar_StrictJarFile);
REGISTER(register_java_util_regex_Matcher);
REGISTER(register_java_util_regex_Pattern);
REGISTER(register_java_util_zip_Adler32);
@@ -69,12 +71,11 @@ int JNI_OnLoad(JavaVM* vm, void*) {
REGISTER(register_libcore_icu_Transliterator);
REGISTER(register_libcore_io_AsynchronousCloseMonitor);
REGISTER(register_libcore_io_Memory);
- REGISTER(register_libcore_io_OsConstants);
REGISTER(register_libcore_io_Posix);
- REGISTER(register_libcore_net_RawSocket);
REGISTER(register_org_apache_harmony_dalvik_NativeTestTarget);
REGISTER(register_org_apache_harmony_xml_ExpatParser);
REGISTER(register_sun_misc_Unsafe);
#undef REGISTER
+
return JNI_VERSION_1_6;
}
diff --git a/luni/src/main/native/libcore_io_OsConstants.cpp b/luni/src/main/native/android_system_OsConstants.cpp
index 8f1f506..92212b9 100644
--- a/luni/src/main/native/libcore_io_OsConstants.cpp
+++ b/luni/src/main/native/android_system_OsConstants.cpp
@@ -18,6 +18,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "Portability.h"
#include <errno.h>
#include <fcntl.h>
@@ -27,16 +28,28 @@
#include <poll.h>
#include <signal.h>
#include <stdlib.h>
-#include <sys/capability.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
+#ifndef __APPLE__
+#include <sys/prctl.h>
+#endif
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
+// After the others because these are not necessarily self-contained in glibc.
+#ifndef __APPLE__
+#include <linux/if_addr.h>
+#include <linux/rtnetlink.h>
+#endif
+
#include <net/if.h> // After <sys/socket.h> to work around a Mac header file bug.
+#if defined(__BIONIC__)
+#include <linux/capability.h>
+#endif
+
static void initConstant(JNIEnv* env, jclass c, const char* fieldName, int value) {
jfieldID field = env->GetStaticFieldID(c, fieldName, "I");
env->SetStaticIntField(c, field, value);
@@ -56,8 +69,10 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
#endif
initConstant(env, c, "AI_PASSIVE", AI_PASSIVE);
initConstant(env, c, "AI_V4MAPPED", AI_V4MAPPED);
+#if defined(CAP_LAST_CAP)
initConstant(env, c, "CAP_AUDIT_CONTROL", CAP_AUDIT_CONTROL);
initConstant(env, c, "CAP_AUDIT_WRITE", CAP_AUDIT_WRITE);
+ initConstant(env, c, "CAP_BLOCK_SUSPEND", CAP_BLOCK_SUSPEND);
initConstant(env, c, "CAP_CHOWN", CAP_CHOWN);
initConstant(env, c, "CAP_DAC_OVERRIDE", CAP_DAC_OVERRIDE);
initConstant(env, c, "CAP_DAC_READ_SEARCH", CAP_DAC_READ_SEARCH);
@@ -93,6 +108,7 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
initConstant(env, c, "CAP_SYS_TIME", CAP_SYS_TIME);
initConstant(env, c, "CAP_SYS_TTY_CONFIG", CAP_SYS_TTY_CONFIG);
initConstant(env, c, "CAP_WAKE_ALARM", CAP_WAKE_ALARM);
+#endif
initConstant(env, c, "E2BIG", E2BIG);
initConstant(env, c, "EACCES", EACCES);
initConstant(env, c, "EADDRINUSE", EADDRINUSE);
@@ -214,6 +230,33 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
initConstant(env, c, "F_SETOWN", F_SETOWN);
initConstant(env, c, "F_UNLCK", F_UNLCK);
initConstant(env, c, "F_WRLCK", F_WRLCK);
+#if defined(IFA_F_DADFAILED)
+ initConstant(env, c, "IFA_F_DADFAILED", IFA_F_DADFAILED);
+#endif
+#if defined(IFA_F_DEPRECATED)
+ initConstant(env, c, "IFA_F_DEPRECATED", IFA_F_DEPRECATED);
+#endif
+#if defined(IFA_F_HOMEADDRESS)
+ initConstant(env, c, "IFA_F_HOMEADDRESS", IFA_F_HOMEADDRESS);
+#endif
+#if defined(IFA_F_NODAD)
+ initConstant(env, c, "IFA_F_NODAD", IFA_F_NODAD);
+#endif
+#if defined(IFA_F_OPTIMISTIC)
+ initConstant(env, c, "IFA_F_OPTIMISTIC", IFA_F_OPTIMISTIC);
+#endif
+#if defined(IFA_F_PERMANENT)
+ initConstant(env, c, "IFA_F_PERMANENT", IFA_F_PERMANENT);
+#endif
+#if defined(IFA_F_SECONDARY)
+ initConstant(env, c, "IFA_F_SECONDARY", IFA_F_SECONDARY);
+#endif
+#if defined(IFA_F_TEMPORARY)
+ initConstant(env, c, "IFA_F_TEMPORARY", IFA_F_TEMPORARY);
+#endif
+#if defined(IFA_F_TENTATIVE)
+ initConstant(env, c, "IFA_F_TENTATIVE", IFA_F_TENTATIVE);
+#endif
initConstant(env, c, "IFF_ALLMULTI", IFF_ALLMULTI);
#if defined(IFF_AUTOMEDIA)
initConstant(env, c, "IFF_AUTOMEDIA", IFF_AUTOMEDIA);
@@ -288,6 +331,18 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
#if defined(MCAST_LEAVE_GROUP)
initConstant(env, c, "MCAST_LEAVE_GROUP", MCAST_LEAVE_GROUP);
#endif
+#if defined(MCAST_JOIN_SOURCE_GROUP)
+ initConstant(env, c, "MCAST_JOIN_SOURCE_GROUP", MCAST_JOIN_SOURCE_GROUP);
+#endif
+#if defined(MCAST_LEAVE_SOURCE_GROUP)
+ initConstant(env, c, "MCAST_LEAVE_SOURCE_GROUP", MCAST_LEAVE_SOURCE_GROUP);
+#endif
+#if defined(MCAST_BLOCK_SOURCE)
+ initConstant(env, c, "MCAST_BLOCK_SOURCE", MCAST_BLOCK_SOURCE);
+#endif
+#if defined(MCAST_UNBLOCK_SOURCE)
+ initConstant(env, c, "MCAST_UNBLOCK_SOURCE", MCAST_UNBLOCK_SOURCE);
+#endif
initConstant(env, c, "MCL_CURRENT", MCL_CURRENT);
initConstant(env, c, "MCL_FUTURE", MCL_FUTURE);
initConstant(env, c, "MSG_CTRUNC", MSG_CTRUNC);
@@ -327,11 +382,31 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
initConstant(env, c, "POLLRDNORM", POLLRDNORM);
initConstant(env, c, "POLLWRBAND", POLLWRBAND);
initConstant(env, c, "POLLWRNORM", POLLWRNORM);
+#if defined(PR_GET_DUMPABLE)
+ initConstant(env, c, "PR_GET_DUMPABLE", PR_GET_DUMPABLE);
+#endif
+#if defined(PR_SET_DUMPABLE)
+ initConstant(env, c, "PR_SET_DUMPABLE", PR_SET_DUMPABLE);
+#endif
+#if defined(PR_SET_NO_NEW_PRIVS)
+ initConstant(env, c, "PR_SET_NO_NEW_PRIVS", PR_SET_NO_NEW_PRIVS);
+#endif
initConstant(env, c, "PROT_EXEC", PROT_EXEC);
initConstant(env, c, "PROT_NONE", PROT_NONE);
initConstant(env, c, "PROT_READ", PROT_READ);
initConstant(env, c, "PROT_WRITE", PROT_WRITE);
initConstant(env, c, "R_OK", R_OK);
+// NOTE: The RT_* constants are not preprocessor defines, they're enum
+// members. The best we can do (barring UAPI / kernel version checks) is
+// to hope they exist on all host linuxes we're building on. These
+// constants have been around since 2.6.35 at least, so we should be ok.
+#if !defined(__APPLE__)
+ initConstant(env, c, "RT_SCOPE_HOST", RT_SCOPE_HOST);
+ initConstant(env, c, "RT_SCOPE_LINK", RT_SCOPE_LINK);
+ initConstant(env, c, "RT_SCOPE_NOWHERE", RT_SCOPE_NOWHERE);
+ initConstant(env, c, "RT_SCOPE_SITE", RT_SCOPE_SITE);
+ initConstant(env, c, "RT_SCOPE_UNIVERSE", RT_SCOPE_UNIVERSE);
+#endif
initConstant(env, c, "SEEK_CUR", SEEK_CUR);
initConstant(env, c, "SEEK_END", SEEK_END);
initConstant(env, c, "SEEK_SET", SEEK_SET);
@@ -398,8 +473,12 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
initConstant(env, c, "SO_KEEPALIVE", SO_KEEPALIVE);
initConstant(env, c, "SO_LINGER", SO_LINGER);
initConstant(env, c, "SO_OOBINLINE", SO_OOBINLINE);
+#if defined(SO_PASSCRED)
initConstant(env, c, "SO_PASSCRED", SO_PASSCRED);
+#endif
+#if defined(SO_PEERCRED)
initConstant(env, c, "SO_PEERCRED", SO_PEERCRED);
+#endif
initConstant(env, c, "SO_RCVBUF", SO_RCVBUF);
initConstant(env, c, "SO_RCVLOWAT", SO_RCVLOWAT);
initConstant(env, c, "SO_RCVTIMEO", SO_RCVTIMEO);
@@ -544,6 +623,6 @@ static void OsConstants_initConstants(JNIEnv* env, jclass c) {
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(OsConstants, initConstants, "()V"),
};
-void register_libcore_io_OsConstants(JNIEnv* env) {
- jniRegisterNativeMethods(env, "libcore/io/OsConstants", gMethods, NELEM(gMethods));
+void register_android_system_OsConstants(JNIEnv* env) {
+ jniRegisterNativeMethods(env, "android/system/OsConstants", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/realpath.cpp b/luni/src/main/native/canonicalize_path.cpp
index d1960a4..b2a2a01 100644
--- a/luni/src/main/native/realpath.cpp
+++ b/luni/src/main/native/canonicalize_path.cpp
@@ -45,7 +45,7 @@
*
* This implementation also removes all the fixed-length buffers of the C original.
*/
-bool realpath(const char* path, std::string& resolved) {
+bool canonicalize_path(const char* path, std::string& resolved) {
// 'path' must be an absolute path.
if (path[0] != '/') {
errno = EINVAL;
diff --git a/luni/src/main/native/java_io_Console.cpp b/luni/src/main/native/java_io_Console.cpp
deleted file mode 100644
index 512bc72..0000000
--- a/luni/src/main/native/java_io_Console.cpp
+++ /dev/null
@@ -1,51 +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.
- */
-
-#define LOG_TAG "Console"
-
-#include "JNIHelp.h"
-#include "JniConstants.h"
-
-#include <errno.h>
-#include <termios.h>
-#include <unistd.h>
-
-static jint Console_setEchoImpl(JNIEnv* env, jclass, jboolean on, jint previousState) {
- termios state;
- if (TEMP_FAILURE_RETRY(tcgetattr(STDIN_FILENO, &state)) == -1) {
- jniThrowIOException(env, errno);
- return 0;
- }
- if (on) {
- state.c_lflag = previousState;
- } else {
- previousState = state.c_lflag;
- state.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
- }
- if (TEMP_FAILURE_RETRY(tcsetattr(STDIN_FILENO, TCSAFLUSH, &state)) == -1){
- jniThrowIOException(env, errno);
- return 0;
- }
- return previousState;
-}
-
-static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(Console, setEchoImpl, "(ZI)I"),
-};
-void register_java_io_Console(JNIEnv* env) {
- jniRegisterNativeMethods(env, "java/io/Console", gMethods, NELEM(gMethods));
-}
diff --git a/luni/src/main/native/java_io_File.cpp b/luni/src/main/native/java_io_File.cpp
index c217ea2..046fc4f 100644
--- a/luni/src/main/native/java_io_File.cpp
+++ b/luni/src/main/native/java_io_File.cpp
@@ -22,7 +22,6 @@
#include "JniException.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
-#include "readlink.h"
#include "toStringArray.h"
#include <string>
@@ -39,96 +38,82 @@
#include <unistd.h>
#include <utime.h>
-static jstring File_readlink(JNIEnv* env, jclass, jstring javaPath) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return NULL;
- }
-
- std::string result;
- if (!readlink(path.c_str(), result)) {
- jniThrowIOException(env, errno);
- return NULL;
- }
- return env->NewStringUTF(result.c_str());
-}
-
-static jstring File_realpath(JNIEnv* env, jclass, jstring javaPath) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return NULL;
- }
-
- extern bool realpath(const char* path, std::string& resolved);
- std::string result;
- if (!realpath(path.c_str(), result)) {
- jniThrowIOException(env, errno);
- return NULL;
- }
- return env->NewStringUTF(result.c_str());
+static jstring File_canonicalizePath(JNIEnv* env, jclass, jstring javaPath) {
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return NULL;
+ }
+
+ extern bool canonicalize_path(const char* path, std::string& resolved);
+ std::string result;
+ if (!canonicalize_path(path.c_str(), result)) {
+ jniThrowIOException(env, errno);
+ return NULL;
+ }
+ return env->NewStringUTF(result.c_str());
}
static jboolean File_setLastModifiedImpl(JNIEnv* env, jclass, jstring javaPath, jlong ms) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return JNI_FALSE;
- }
-
- // We want to preserve the access time.
- struct stat sb;
- if (stat(path.c_str(), &sb) == -1) {
- return JNI_FALSE;
- }
-
- // TODO: we could get microsecond resolution with utimes(3), "legacy" though it is.
- utimbuf times;
- times.actime = sb.st_atime;
- times.modtime = static_cast<time_t>(ms / 1000);
- return (utime(path.c_str(), &times) == 0);
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return JNI_FALSE;
+ }
+
+ // We want to preserve the access time.
+ struct stat sb;
+ if (stat(path.c_str(), &sb) == -1) {
+ return JNI_FALSE;
+ }
+
+ // TODO: we could get microsecond resolution with utimes(3), "legacy" though it is.
+ utimbuf times;
+ times.actime = sb.st_atime;
+ times.modtime = static_cast<time_t>(ms / 1000);
+ return (utime(path.c_str(), &times) == 0);
}
// Iterates over the filenames in the given directory.
class ScopedReaddir {
-public:
- ScopedReaddir(const char* path) {
- mDirStream = opendir(path);
- mIsBad = (mDirStream == NULL);
+ public:
+ ScopedReaddir(const char* path) {
+ mDirStream = opendir(path);
+ mIsBad = (mDirStream == NULL);
+ }
+
+ ~ScopedReaddir() {
+ if (mDirStream != NULL) {
+ closedir(mDirStream);
}
+ }
- ~ScopedReaddir() {
- if (mDirStream != NULL) {
- closedir(mDirStream);
- }
+ // Returns the next filename, or NULL.
+ const char* next() {
+ if (mIsBad) {
+ return NULL;
}
-
- // Returns the next filename, or NULL.
- const char* next() {
- if (mIsBad) {
- return NULL;
- }
- errno = 0;
- dirent* result = readdir(mDirStream);
- if (result != NULL) {
- return result->d_name;
- }
- if (errno != 0) {
- mIsBad = true;
- }
- return NULL;
+ errno = 0;
+ dirent* result = readdir(mDirStream);
+ if (result != NULL) {
+ return result->d_name;
}
-
- // Has an error occurred on this stream?
- bool isBad() const {
- return mIsBad;
+ if (errno != 0) {
+ mIsBad = true;
}
+ return NULL;
+ }
-private:
- DIR* mDirStream;
- bool mIsBad;
+ // Has an error occurred on this stream?
+ bool isBad() const {
+ return mIsBad;
+ }
- // Disallow copy and assignment.
- ScopedReaddir(const ScopedReaddir&);
- void operator=(const ScopedReaddir&);
+ private:
+ DIR* mDirStream;
+ bool mIsBad;
+
+ // Disallow copy and assignment.
+ ScopedReaddir(const ScopedReaddir&);
+ void operator=(const ScopedReaddir&);
};
typedef std::vector<std::string> DirEntries;
@@ -136,38 +121,37 @@ typedef std::vector<std::string> DirEntries;
// Reads the directory referred to by 'pathBytes', adding each directory entry
// to 'entries'.
static bool readDirectory(JNIEnv* env, jstring javaPath, DirEntries& entries) {
- ScopedUtfChars path(env, javaPath);
- if (path.c_str() == NULL) {
- return false;
- }
-
- ScopedReaddir dir(path.c_str());
- const char* filename;
- while ((filename = dir.next()) != NULL) {
- if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) {
- // TODO: this hides allocation failures from us. Push directory iteration up into Java?
- entries.push_back(filename);
- }
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return false;
+ }
+
+ ScopedReaddir dir(path.c_str());
+ const char* filename;
+ while ((filename = dir.next()) != NULL) {
+ if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) {
+ // TODO: this hides allocation failures from us. Push directory iteration up into Java?
+ entries.push_back(filename);
}
- return !dir.isBad();
+ }
+ return !dir.isBad();
}
static jobjectArray File_listImpl(JNIEnv* env, jclass, jstring javaPath) {
- // Read the directory entries into an intermediate form.
- DirEntries entries;
- if (!readDirectory(env, javaPath, entries)) {
- return NULL;
- }
- // Translate the intermediate form into a Java String[].
- return toStringArray(env, entries);
+ // Read the directory entries into an intermediate form.
+ DirEntries entries;
+ if (!readDirectory(env, javaPath, entries)) {
+ return NULL;
+ }
+ // Translate the intermediate form into a Java String[].
+ return toStringArray(env, entries);
}
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(File, listImpl, "(Ljava/lang/String;)[Ljava/lang/String;"),
- NATIVE_METHOD(File, readlink, "(Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(File, realpath, "(Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(File, setLastModifiedImpl, "(Ljava/lang/String;J)Z"),
+ NATIVE_METHOD(File, canonicalizePath, "(Ljava/lang/String;)Ljava/lang/String;"),
+ NATIVE_METHOD(File, listImpl, "(Ljava/lang/String;)[Ljava/lang/String;"),
+ NATIVE_METHOD(File, setLastModifiedImpl, "(Ljava/lang/String;J)Z"),
};
void register_java_io_File(JNIEnv* env) {
- jniRegisterNativeMethods(env, "java/io/File", gMethods, NELEM(gMethods));
+ jniRegisterNativeMethods(env, "java/io/File", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/java_io_FileDescriptor.cpp b/luni/src/main/native/java_io_FileDescriptor.cpp
new file mode 100644
index 0000000..fe7e07e
--- /dev/null
+++ b/luni/src/main/native/java_io_FileDescriptor.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2014 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.
+ */
+
+#define LOG_TAG "FileDescriptor"
+
+#include "JniConstants.h"
+
+#include <sys/socket.h>
+#include <sys/types.h>
+
+static jboolean FileDescriptor_isSocket(JNIEnv*, jclass, jint fd) {
+ int error;
+ socklen_t error_length = sizeof(error);
+ return TEMP_FAILURE_RETRY(getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &error_length));
+}
+
+static JNINativeMethod gMethods[] = {
+ NATIVE_METHOD(FileDescriptor, isSocket, "(I)Z"),
+};
+void register_java_io_FileDescriptor(JNIEnv* env) {
+ jniRegisterNativeMethods(env, "java/io/FileDescriptor", gMethods, NELEM(gMethods));
+}
diff --git a/luni/src/main/native/java_lang_Character.cpp b/luni/src/main/native/java_lang_Character.cpp
index 14eef64..4022f4b 100644
--- a/luni/src/main/native/java_lang_Character.cpp
+++ b/luni/src/main/native/java_lang_Character.cpp
@@ -20,6 +20,7 @@
#include "JniConstants.h"
#include "ScopedUtfChars.h"
#include "unicode/uchar.h"
+#include "unicode/uscript.h"
#include <math.h>
#include <stdio.h> // For BUFSIZ
#include <stdlib.h>
@@ -32,7 +33,7 @@ static jint Character_getTypeImpl(JNIEnv*, jclass, jint codePoint) {
return u_charType(codePoint);
}
-static jbyte Character_getDirectionalityImpl(JNIEnv*, jclass, jint codePoint) {
+static jbyte Character_getIcuDirectionality(JNIEnv*, jclass, jint codePoint) {
return u_charDirection(codePoint);
}
@@ -124,7 +125,7 @@ static jboolean Character_isLowerCaseImpl(JNIEnv*, jclass, jint codePoint) {
return u_islower(codePoint);
}
-static int Character_forNameImpl(JNIEnv* env, jclass, jstring javaBlockName) {
+static int Character_unicodeBlockForName(JNIEnv* env, jclass, jstring javaBlockName) {
ScopedUtfChars blockName(env, javaBlockName);
if (blockName.c_str() == NULL) {
return 0;
@@ -132,10 +133,29 @@ static int Character_forNameImpl(JNIEnv* env, jclass, jstring javaBlockName) {
return u_getPropertyValueEnum(UCHAR_BLOCK, blockName.c_str());
}
-static int Character_ofImpl(JNIEnv*, jclass, jint codePoint) {
+static int Character_unicodeBlockForCodePoint(JNIEnv*, jclass, jint codePoint) {
return ublock_getCode(codePoint);
}
+static int Character_unicodeScriptForName(JNIEnv* env, jclass, jstring javaScriptName) {
+ ScopedUtfChars scriptName(env, javaScriptName);
+ if (scriptName.c_str() == NULL) {
+ return -1;
+ }
+
+ return u_getPropertyValueEnum(UCHAR_SCRIPT, scriptName.c_str());
+}
+
+static int Character_unicodeScriptForCodePoint(JNIEnv*, jclass, jint codePoint) {
+ UErrorCode status = U_ZERO_ERROR;
+ const UScriptCode script = uscript_getScript(codePoint, &status);
+ if (status != U_ZERO_ERROR) {
+ return -1;
+ }
+
+ return script;
+}
+
static jboolean Character_isAlphabetic(JNIEnv*, jclass, jint codePoint) {
return u_hasBinaryProperty(codePoint, UCHAR_ALPHABETIC);
}
@@ -146,8 +166,7 @@ static jboolean Character_isIdeographic(JNIEnv*, jclass, jint codePoint) {
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Character, digitImpl, "!(II)I"),
- NATIVE_METHOD(Character, forNameImpl, "(Ljava/lang/String;)I"),
- NATIVE_METHOD(Character, getDirectionalityImpl, "!(I)B"),
+ NATIVE_METHOD(Character, getIcuDirectionality, "!(I)B"),
NATIVE_METHOD(Character, getNameImpl, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Character, getNumericValueImpl, "!(I)I"),
NATIVE_METHOD(Character, getTypeImpl, "!(I)I"),
@@ -166,10 +185,13 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Character, isUnicodeIdentifierStartImpl, "!(I)Z"),
NATIVE_METHOD(Character, isUpperCaseImpl, "!(I)Z"),
NATIVE_METHOD(Character, isWhitespaceImpl, "!(I)Z"),
- NATIVE_METHOD(Character, ofImpl, "!(I)I"),
NATIVE_METHOD(Character, toLowerCaseImpl, "!(I)I"),
NATIVE_METHOD(Character, toTitleCaseImpl, "!(I)I"),
NATIVE_METHOD(Character, toUpperCaseImpl, "!(I)I"),
+ NATIVE_METHOD(Character, unicodeBlockForName, "(Ljava/lang/String;)I"),
+ NATIVE_METHOD(Character, unicodeBlockForCodePoint, "!(I)I"),
+ NATIVE_METHOD(Character, unicodeScriptForName, "(Ljava/lang/String;)I"),
+ NATIVE_METHOD(Character, unicodeScriptForCodePoint, "!(I)I"),
};
void register_java_lang_Character(JNIEnv* env) {
jniRegisterNativeMethods(env, "java/lang/Character", gMethods, NELEM(gMethods));
diff --git a/luni/src/main/native/java_lang_Double.cpp b/luni/src/main/native/java_lang_Double.cpp
index 259be30..186bd26 100644
--- a/luni/src/main/native/java_lang_Double.cpp
+++ b/luni/src/main/native/java_lang_Double.cpp
@@ -29,15 +29,6 @@ union Double {
double d;
};
-static const jlong NaN = 0x7ff8000000000000ULL;
-
-static jlong Double_doubleToLongBits(JNIEnv*, jclass, jdouble val) {
- Double d;
- d.d = val;
- // For this method all values in the NaN range are normalized to the canonical NaN value.
- return isnan(d.d) ? NaN : d.bits;
-}
-
static jlong Double_doubleToRawLongBits(JNIEnv*, jclass, jdouble val) {
Double d;
d.d = val;
@@ -51,10 +42,9 @@ static jdouble Double_longBitsToDouble(JNIEnv*, jclass, jlong val) {
}
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(Double, doubleToLongBits, "(D)J"),
NATIVE_METHOD(Double, doubleToRawLongBits, "(D)J"),
NATIVE_METHOD(Double, longBitsToDouble, "(J)D"),
};
-int register_java_lang_Double(JNIEnv* env) {
- return jniRegisterNativeMethods(env, "java/lang/Double", gMethods, NELEM(gMethods));
+void register_java_lang_Double(JNIEnv* env) {
+ jniRegisterNativeMethods(env, "java/lang/Double", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/java_lang_Float.cpp b/luni/src/main/native/java_lang_Float.cpp
index 59544db..3852516 100644
--- a/luni/src/main/native/java_lang_Float.cpp
+++ b/luni/src/main/native/java_lang_Float.cpp
@@ -18,6 +18,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "Portability.h"
#include <math.h>
#include <stdlib.h>
@@ -28,15 +29,6 @@ union Float {
float f;
};
-static const jint NaN = 0x7fc00000;
-
-static jint Float_floatToIntBits(JNIEnv*, jclass, jfloat val) {
- Float f;
- f.f = val;
- // For this method all values in the NaN range are normalized to the canonical NaN value.
- return isnanf(f.f) ? NaN : f.bits;
-}
-
jint Float_floatToRawIntBits(JNIEnv*, jclass, jfloat val) {
Float f;
f.f = val;
@@ -50,10 +42,9 @@ jfloat Float_intBitsToFloat(JNIEnv*, jclass, jint val) {
}
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(Float, floatToIntBits, "(F)I"),
NATIVE_METHOD(Float, floatToRawIntBits, "(F)I"),
NATIVE_METHOD(Float, intBitsToFloat, "(I)F"),
};
-int register_java_lang_Float(JNIEnv* env) {
- return jniRegisterNativeMethods(env, "java/lang/Float", gMethods, NELEM(gMethods));
+void register_java_lang_Float(JNIEnv* env) {
+ jniRegisterNativeMethods(env, "java/lang/Float", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/java_lang_Math.cpp b/luni/src/main/native/java_lang_Math.cpp
index 784b84d..83c39bd 100644
--- a/luni/src/main/native/java_lang_Math.cpp
+++ b/luni/src/main/native/java_lang_Math.cpp
@@ -145,7 +145,6 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Math, tan, "!(D)D"),
NATIVE_METHOD(Math, tanh, "!(D)D"),
};
-
void register_java_lang_Math(JNIEnv* env) {
jniRegisterNativeMethods(env, "java/lang/Math", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/java_lang_ProcessManager.cpp b/luni/src/main/native/java_lang_ProcessManager.cpp
index a74ba8b..3a97ac6 100644
--- a/luni/src/main/native/java_lang_ProcessManager.cpp
+++ b/luni/src/main/native/java_lang_ProcessManager.cpp
@@ -38,7 +38,7 @@
static void CloseNonStandardFds(int status_pipe_fd) {
// On Cygwin, Linux, and Solaris, the best way to close iterates over "/proc/self/fd/".
const char* fd_path = "/proc/self/fd";
-#ifdef __APPLE__
+#if defined(__APPLE__)
// On Mac OS, there's "/dev/fd/" which Linux seems to link to "/proc/self/fd/",
// but which on Solaris appears to be something quite different.
fd_path = "/dev/fd";
diff --git a/luni/src/main/native/java_lang_System.cpp b/luni/src/main/native/java_lang_System.cpp
index 0686310..944c0c3 100644
--- a/luni/src/main/native/java_lang_System.cpp
+++ b/luni/src/main/native/java_lang_System.cpp
@@ -34,6 +34,10 @@
#include <time.h>
#include <unistd.h>
+#if defined(HAVE_ANDROID_OS)
+extern "C" void android_get_LD_LIBRARY_PATH(char*, size_t);
+#endif
+
static void System_log(JNIEnv* env, jclass, jchar type, jstring javaMessage, jthrowable exception) {
ScopedUtfChars message(env, javaMessage);
if (message.c_str() == NULL) {
@@ -82,6 +86,18 @@ static jobjectArray System_specialProperties(JNIEnv* env, jclass) {
properties.push_back("android.zlib.version=" ZLIB_VERSION);
properties.push_back("android.openssl.version=" OPENSSL_VERSION_TEXT);
+ const char* library_path = getenv("LD_LIBRARY_PATH");
+#if defined(HAVE_ANDROID_OS)
+ if (library_path == NULL) {
+ android_get_LD_LIBRARY_PATH(path, sizeof(path));
+ library_path = path;
+ }
+#endif
+ if (library_path == NULL) {
+ library_path = "";
+ }
+ properties.push_back(std::string("java.library.path=") + library_path);
+
return toStringArray(env, properties);
}
@@ -93,9 +109,15 @@ static jlong System_currentTimeMillis(JNIEnv*, jclass) {
}
static jlong System_nanoTime(JNIEnv*, jclass) {
+#if defined(HAVE_POSIX_CLOCKS)
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return now.tv_sec * 1000000000LL + now.tv_nsec;
+#else
+ timeval now;
+ gettimeofday(&now, NULL);
+ return static_cast<jlong>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
+#endif
}
static jstring System_mapLibraryName(JNIEnv* env, jclass, jstring javaName) {
@@ -111,10 +133,10 @@ static jstring System_mapLibraryName(JNIEnv* env, jclass, jstring javaName) {
}
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(System, currentTimeMillis, "()J"),
+ NATIVE_METHOD(System, currentTimeMillis, "!()J"),
NATIVE_METHOD(System, log, "(CLjava/lang/String;Ljava/lang/Throwable;)V"),
NATIVE_METHOD(System, mapLibraryName, "(Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(System, nanoTime, "()J"),
+ NATIVE_METHOD(System, nanoTime, "!()J"),
NATIVE_METHOD(System, setFieldImpl, "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V"),
NATIVE_METHOD(System, specialProperties, "()[Ljava/lang/String;"),
};
diff --git a/luni/src/main/native/java_math_NativeBN.cpp b/luni/src/main/native/java_math_NativeBN.cpp
index 158dfac..be87ea6 100644
--- a/luni/src/main/native/java_math_NativeBN.cpp
+++ b/luni/src/main/native/java_math_NativeBN.cpp
@@ -21,7 +21,6 @@
#include "JniException.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
-#include "StaticAssert.h"
#include "UniquePtr.h"
#include "jni.h"
#include <openssl/bn.h>
@@ -109,18 +108,24 @@ static void NativeBN_BN_copy(JNIEnv* env, jclass, jlong to, jlong from) {
throwExceptionIfNecessary(env);
}
-static void NativeBN_putULongInt(JNIEnv* env, jclass, jlong a0, unsigned long long dw, jboolean neg) {
+static void NativeBN_putULongInt(JNIEnv* env, jclass, jlong a0, jlong java_dw, jboolean neg) {
if (!oneValidHandle(env, a0)) return;
- unsigned int hi = dw >> 32; // This shifts without sign extension.
- int lo = (int)dw; // This truncates implicitly.
+
+ uint64_t dw = java_dw;
// cf. litEndInts2bn:
BIGNUM* a = toBigNum(a0);
bn_check_top(a);
- if (bn_wexpand(a, 2) != NULL) {
+ if (bn_wexpand(a, 8/BN_BYTES) != NULL) {
+#ifdef __LP64__
+ a->d[0] = dw;
+#else
+ unsigned int hi = dw >> 32; // This shifts without sign extension.
+ int lo = (int)dw; // This truncates implicitly.
a->d[0] = lo;
a->d[1] = hi;
- a->top = 2;
+#endif
+ a->top = 8 / BN_BYTES;
a->neg = neg;
bn_correct_top(a);
} else {
@@ -128,7 +133,7 @@ static void NativeBN_putULongInt(JNIEnv* env, jclass, jlong a0, unsigned long lo
}
}
-static void NativeBN_putLongInt(JNIEnv* env, jclass cls, jlong a, long long dw) {
+static void NativeBN_putLongInt(JNIEnv* env, jclass cls, jlong a, jlong dw) {
if (dw >= 0) {
NativeBN_putULongInt(env, cls, a, dw, JNI_FALSE);
} else {
@@ -188,12 +193,26 @@ static void NativeBN_litEndInts2bn(JNIEnv* env, jclass, jintArray arr, int len,
if (scopedArray.get() == NULL) {
return;
}
-
- STATIC_ASSERT(sizeof(BN_ULONG) == sizeof(jint), BN_ULONG_not_32_bit);
- const BN_ULONG* tmpInts = reinterpret_cast<const BN_ULONG*>(scopedArray.get());
- if ((tmpInts != NULL) && (bn_wexpand(ret, len) != NULL)) {
+#ifdef __LP64__
+ const int wlen = (len + 1) / 2;
+#else
+ const int wlen = len;
+#endif
+ const unsigned int* tmpInts = reinterpret_cast<const unsigned int*>(scopedArray.get());
+ if ((tmpInts != NULL) && (bn_wexpand(ret, wlen) != NULL)) {
+#ifdef __LP64__
+ if (len % 2) {
+ ret->d[wlen - 1] = tmpInts[--len];
+ }
+ if (len > 0) {
+ for (int i = len - 2; i >= 0; i -= 2) {
+ ret->d[i/2] = ((unsigned long long)tmpInts[i+1] << 32) | tmpInts[i];
+ }
+ }
+#else
int i = len; do { i--; ret->d[i] = tmpInts[i]; } while (i > 0);
- ret->top = len;
+#endif
+ ret->top = wlen;
ret->neg = neg;
// need to call this due to clear byte at top if avoiding
// having the top bit set (-ve number)
@@ -208,35 +227,39 @@ static void NativeBN_litEndInts2bn(JNIEnv* env, jclass, jintArray arr, int len,
}
-#define BYTES2INT(bytes, k) \
+#ifdef __LP64__
+#define BYTES2ULONG(bytes, k) \
+ ((bytes[k + 7] & 0xffULL) | (bytes[k + 6] & 0xffULL) << 8 | (bytes[k + 5] & 0xffULL) << 16 | (bytes[k + 4] & 0xffULL) << 24 | \
+ (bytes[k + 3] & 0xffULL) << 32 | (bytes[k + 2] & 0xffULL) << 40 | (bytes[k + 1] & 0xffULL) << 48 | (bytes[k + 0] & 0xffULL) << 56)
+#else
+#define BYTES2ULONG(bytes, k) \
((bytes[k + 3] & 0xff) | (bytes[k + 2] & 0xff) << 8 | (bytes[k + 1] & 0xff) << 16 | (bytes[k + 0] & 0xff) << 24)
-
+#endif
static void negBigEndianBytes2bn(JNIEnv*, jclass, const unsigned char* bytes, int bytesLen, jlong ret0) {
BIGNUM* ret = toBigNum(ret0);
- // We rely on: (BN_BITS2 == 32), i.e. BN_ULONG is unsigned int and has 4 bytes:
bn_check_top(ret);
// FIXME: assert bytesLen > 0
- int intLen = (bytesLen + 3) / 4;
+ int wLen = (bytesLen + BN_BYTES - 1) / BN_BYTES;
int firstNonzeroDigit = -2;
- if (bn_wexpand(ret, intLen) != NULL) {
+ if (bn_wexpand(ret, wLen) != NULL) {
BN_ULONG* d = ret->d;
BN_ULONG di;
- ret->top = intLen;
- int highBytes = bytesLen % 4;
+ ret->top = wLen;
+ int highBytes = bytesLen % BN_BYTES;
int k = bytesLen;
// Put bytes to the int array starting from the end of the byte array
int i = 0;
while (k > highBytes) {
- k -= 4;
- di = BYTES2INT(bytes, k);
+ k -= BN_BYTES;
+ di = BYTES2ULONG(bytes, k);
if (di != 0) {
d[i] = -di;
firstNonzeroDigit = i;
i++;
while (k > highBytes) {
- k -= 4;
- d[i] = ~BYTES2INT(bytes, k);
+ k -= BN_BYTES;
+ d[i] = ~BYTES2ULONG(bytes, k);
i++;
}
break;
@@ -260,6 +283,8 @@ static void negBigEndianBytes2bn(JNIEnv*, jclass, const unsigned char* bytes, in
d[i] = -di;
}
}
+ // The top may have superfluous zeros, so fix it.
+ bn_correct_top(ret);
}
}
@@ -288,28 +313,25 @@ static void NativeBN_twosComp2bn(JNIEnv* env, jclass cls, jbyteArray arr, int by
throwExceptionIfNecessary(env);
}
-static long long NativeBN_longInt(JNIEnv* env, jclass, jlong a0) {
+static jlong NativeBN_longInt(JNIEnv* env, jclass, jlong a0) {
if (!oneValidHandle(env, a0)) return -1;
+
BIGNUM* a = toBigNum(a0);
bn_check_top(a);
- int intLen = a->top;
- BN_ULONG* d = a->d;
- switch (intLen) {
- case 0:
- return 0;
- case 1:
- if (!a->neg) {
- return d[0] & 0X00000000FFFFFFFFLL;
- } else {
- return -(d[0] & 0X00000000FFFFFFFFLL);
- }
- default:
- if (!a->neg) {
- return ((long long)d[1] << 32) | (d[0] & 0XFFFFFFFFLL);
- } else {
- return -(((long long)d[1] << 32) | (d[0] & 0XFFFFFFFFLL));
- }
+ int wLen = a->top;
+ if (wLen == 0) {
+ return 0;
+ }
+
+#ifdef __LP64__
+ jlong result = a->d[0];
+#else
+ jlong result = static_cast<jlong>(a->d[0]) & 0xffffffff;
+ if (wLen > 1) {
+ result |= static_cast<jlong>(a->d[1]) << 32;
}
+#endif
+ return a->neg ? -result : result;
}
static char* leadingZerosTrimmed(char* s) {
@@ -368,11 +390,11 @@ static jintArray NativeBN_bn2litEndInts(JNIEnv* env, jclass, jlong a0) {
if (!oneValidHandle(env, a0)) return NULL;
BIGNUM* a = toBigNum(a0);
bn_check_top(a);
- int len = a->top;
- if (len == 0) {
+ int wLen = a->top;
+ if (wLen == 0) {
return NULL;
}
- jintArray result = env->NewIntArray(len);
+ jintArray result = env->NewIntArray(wLen * BN_BYTES/sizeof(unsigned int));
if (result == NULL) {
return NULL;
}
@@ -380,11 +402,15 @@ static jintArray NativeBN_bn2litEndInts(JNIEnv* env, jclass, jlong a0) {
if (ints.get() == NULL) {
return NULL;
}
- BN_ULONG* ulongs = reinterpret_cast<BN_ULONG*>(ints.get());
- if (ulongs == NULL) {
+ unsigned int* uints = reinterpret_cast<unsigned int*>(ints.get());
+ if (uints == NULL) {
return NULL;
}
- int i = len; do { i--; ulongs[i] = a->d[i]; } while (i > 0);
+#ifdef __LP64__
+ int i = wLen; do { i--; uints[i*2+1] = a->d[i] >> 32; uints[i*2] = a->d[i]; } while (i > 0);
+#else
+ int i = wLen; do { i--; uints[i] = a->d[i]; } while (i > 0);
+#endif
return result;
}
@@ -404,15 +430,13 @@ static void NativeBN_BN_set_negative(JNIEnv* env, jclass, jlong b, int n) {
}
static int NativeBN_bitLength(JNIEnv* env, jclass, jlong a0) {
-// We rely on: (BN_BITS2 == 32), i.e. BN_ULONG is unsigned int and has 4 bytes:
-//
if (!oneValidHandle(env, a0)) return JNI_FALSE;
BIGNUM* a = toBigNum(a0);
bn_check_top(a);
- int intLen = a->top;
- if (intLen == 0) return 0;
+ int wLen = a->top;
+ if (wLen == 0) return 0;
BN_ULONG* d = a->d;
- int i = intLen - 1;
+ int i = wLen - 1;
BN_ULONG msd = d[i]; // most significant digit
if (a->neg) {
// Handle negative values correctly:
@@ -421,7 +445,7 @@ static int NativeBN_bitLength(JNIEnv* env, jclass, jlong a0) {
do { i--; } while (!((i < 0) || (d[i] != 0)));
if (i < 0) msd--; // Only if all lower significant digits are 0 we decrement the most significant one.
}
- return (intLen - 1) * 32 + BN_num_bits_word(msd);
+ return (wLen - 1) * BN_BYTES * 8 + BN_num_bits_word(msd);
}
static jboolean NativeBN_BN_is_bit_set(JNIEnv* env, jclass, jlong a, int n) {
diff --git a/luni/src/main/native/java_util_jar_StrictJarFile.cpp b/luni/src/main/native/java_util_jar_StrictJarFile.cpp
new file mode 100644
index 0000000..7611749
--- /dev/null
+++ b/luni/src/main/native/java_util_jar_StrictJarFile.cpp
@@ -0,0 +1,173 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "StrictJarFile"
+
+#include <string>
+
+#include "JNIHelp.h"
+#include "JniConstants.h"
+#include "ScopedLocalRef.h"
+#include "ScopedUtfChars.h"
+#include "UniquePtr.h"
+#include "jni.h"
+#include "ziparchive/zip_archive.h"
+#include "cutils/log.h"
+
+static void throwIoException(JNIEnv* env, const int32_t errorCode) {
+ jniThrowException(env, "java/io/IOException", ErrorCodeString(errorCode));
+}
+
+static jobject newZipEntry(JNIEnv* env, const ZipEntry& entry, jstring entryName,
+ const uint16_t nameLength) {
+ ScopedLocalRef<jclass> zipEntryClass(env, env->FindClass("java/util/zip/ZipEntry"));
+ const jmethodID zipEntryCtor = env->GetMethodID(zipEntryClass.get(), "<init>",
+ "(Ljava/lang/String;Ljava/lang/String;JJJIII[BIJJ)V");
+
+ return env->NewObject(zipEntryClass.get(),
+ zipEntryCtor,
+ entryName,
+ NULL, // comment
+ static_cast<jlong>(entry.crc32),
+ static_cast<jlong>(entry.compressed_length),
+ static_cast<jlong>(entry.uncompressed_length),
+ static_cast<jint>(entry.method),
+ static_cast<jint>(0), // time
+ static_cast<jint>(0), // modData
+ NULL, // byte[] extra
+ static_cast<jint>(nameLength),
+ static_cast<jlong>(-1), // local header offset
+ static_cast<jlong>(entry.offset));
+}
+
+static jlong StrictJarFile_nativeOpenJarFile(JNIEnv* env, jobject, jstring fileName) {
+ ScopedUtfChars fileChars(env, fileName);
+ if (fileChars.c_str() == NULL) {
+ return static_cast<jlong>(-1);
+ }
+
+ ZipArchiveHandle handle;
+ int32_t error = OpenArchive(fileChars.c_str(), &handle);
+ if (error) {
+ throwIoException(env, error);
+ return static_cast<jlong>(-1);
+ }
+
+ return reinterpret_cast<jlong>(handle);
+}
+
+class IterationHandle {
+ public:
+ IterationHandle(const char* prefix) :
+ cookie_(NULL), prefix_(strdup(prefix)) {
+ }
+
+ void** CookieAddress() {
+ return &cookie_;
+ }
+
+ const char* Prefix() const {
+ return prefix_;
+ }
+
+ ~IterationHandle() {
+ free(prefix_);
+ }
+
+ private:
+ void* cookie_;
+ char* prefix_;
+};
+
+
+static jlong StrictJarFile_nativeStartIteration(JNIEnv* env, jobject, jlong nativeHandle,
+ jstring prefix) {
+ ScopedUtfChars prefixChars(env, prefix);
+ if (prefixChars.c_str() == NULL) {
+ return static_cast<jlong>(-1);
+ }
+
+ IterationHandle* handle = new IterationHandle(prefixChars.c_str());
+ int32_t error = 0;
+ if (prefixChars.size() == 0) {
+ error = StartIteration(reinterpret_cast<ZipArchiveHandle>(nativeHandle),
+ handle->CookieAddress(), NULL);
+ } else {
+ error = StartIteration(reinterpret_cast<ZipArchiveHandle>(nativeHandle),
+ handle->CookieAddress(), handle->Prefix());
+ }
+
+ if (error) {
+ throwIoException(env, error);
+ return static_cast<jlong>(-1);
+ }
+
+ return reinterpret_cast<jlong>(handle);
+}
+
+static jobject StrictJarFile_nativeNextEntry(JNIEnv* env, jobject, jlong iterationHandle) {
+ ZipEntry data;
+ ZipEntryName entryName;
+
+ IterationHandle* handle = reinterpret_cast<IterationHandle*>(iterationHandle);
+ const int32_t error = Next(*handle->CookieAddress(), &data, &entryName);
+ if (error) {
+ delete handle;
+ return NULL;
+ }
+
+ UniquePtr<char[]> entryNameCString(new char[entryName.name_length + 1]);
+ memcpy(entryNameCString.get(), entryName.name, entryName.name_length);
+ entryNameCString[entryName.name_length] = '\0';
+ ScopedLocalRef<jstring> entryNameString(env, env->NewStringUTF(entryNameCString.get()));
+
+ return newZipEntry(env, data, entryNameString.get(), entryName.name_length);
+}
+
+static jobject StrictJarFile_nativeFindEntry(JNIEnv* env, jobject, jlong nativeHandle,
+ jstring entryName) {
+ ScopedUtfChars entryNameChars(env, entryName);
+ if (entryNameChars.c_str() == NULL) {
+ return NULL;
+ }
+
+ ZipEntry data;
+ const int32_t error = FindEntry(reinterpret_cast<ZipArchiveHandle>(nativeHandle),
+ entryNameChars.c_str(), &data);
+ if (error) {
+ return NULL;
+ }
+
+ return newZipEntry(env, data, entryName, entryNameChars.size());
+}
+
+static void StrictJarFile_nativeClose(JNIEnv*, jobject, jlong nativeHandle) {
+ CloseArchive(reinterpret_cast<ZipArchiveHandle>(nativeHandle));
+}
+
+static JNINativeMethod gMethods[] = {
+ NATIVE_METHOD(StrictJarFile, nativeOpenJarFile, "(Ljava/lang/String;)J"),
+ NATIVE_METHOD(StrictJarFile, nativeStartIteration, "(JLjava/lang/String;)J"),
+ NATIVE_METHOD(StrictJarFile, nativeNextEntry, "(J)Ljava/util/zip/ZipEntry;"),
+ NATIVE_METHOD(StrictJarFile, nativeFindEntry, "(JLjava/lang/String;)Ljava/util/zip/ZipEntry;"),
+ NATIVE_METHOD(StrictJarFile, nativeClose, "(J)V"),
+};
+
+void register_java_util_jar_StrictJarFile(JNIEnv* env) {
+ jniRegisterNativeMethods(env, "java/util/jar/StrictJarFile", gMethods, NELEM(gMethods));
+
+}
diff --git a/luni/src/main/native/libcore_icu_AlphabeticIndex.cpp b/luni/src/main/native/libcore_icu_AlphabeticIndex.cpp
index bb05193..e0638bd 100644
--- a/luni/src/main/native/libcore_icu_AlphabeticIndex.cpp
+++ b/luni/src/main/native/libcore_icu_AlphabeticIndex.cpp
@@ -20,6 +20,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
+#include "ScopedIcuLocale.h"
#include "ScopedJavaUnicodeString.h"
#include "unicode/alphaindex.h"
#include "unicode/uniset.h"
@@ -28,9 +29,13 @@ static AlphabeticIndex* fromPeer(jlong peer) {
return reinterpret_cast<AlphabeticIndex*>(static_cast<uintptr_t>(peer));
}
-static jlong AlphabeticIndex_create(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong AlphabeticIndex_create(JNIEnv* env, jclass, jstring javaLocaleName) {
UErrorCode status = U_ZERO_ERROR;
- AlphabeticIndex* ai = new AlphabeticIndex(getLocale(env, javaLocale), status);
+ ScopedIcuLocale icuLocale(env, javaLocaleName);
+ if (!icuLocale.valid()) {
+ return 0;
+ }
+ AlphabeticIndex* ai = new AlphabeticIndex(icuLocale.locale(), status);
if (maybeThrowIcuException(env, "AlphabeticIndex", status)) {
return 0;
}
@@ -53,10 +58,14 @@ static void AlphabeticIndex_setMaxLabelCount(JNIEnv* env, jclass, jlong peer, ji
maybeThrowIcuException(env, "AlphabeticIndex::setMaxLabelCount", status);
}
-static void AlphabeticIndex_addLabels(JNIEnv* env, jclass, jlong peer, jstring javaLocale) {
+static void AlphabeticIndex_addLabels(JNIEnv* env, jclass, jlong peer, jstring javaLocaleName) {
AlphabeticIndex* ai = fromPeer(peer);
+ ScopedIcuLocale icuLocale(env, javaLocaleName);
+ if (!icuLocale.valid()) {
+ return;
+ }
UErrorCode status = U_ZERO_ERROR;
- ai->addLabels(getLocale(env, javaLocale), status);
+ ai->addLabels(icuLocale.locale(), status);
maybeThrowIcuException(env, "AlphabeticIndex::addLabels", status);
}
diff --git a/luni/src/main/native/libcore_icu_DateIntervalFormat.cpp b/luni/src/main/native/libcore_icu_DateIntervalFormat.cpp
index 72bc631..a3258c1 100644
--- a/luni/src/main/native/libcore_icu_DateIntervalFormat.cpp
+++ b/luni/src/main/native/libcore_icu_DateIntervalFormat.cpp
@@ -18,13 +18,17 @@
#include "IcuUtilities.h"
#include "JniConstants.h"
+#include "ScopedIcuLocale.h"
#include "ScopedJavaUnicodeString.h"
#include "UniquePtr.h"
#include "cutils/log.h"
#include "unicode/dtitvfmt.h"
static jlong DateIntervalFormat_createDateIntervalFormat(JNIEnv* env, jclass, jstring javaSkeleton, jstring javaLocaleName, jstring javaTzName) {
- Locale locale = getLocale(env, javaLocaleName);
+ ScopedIcuLocale icuLocale(env, javaLocaleName);
+ if (!icuLocale.valid()) {
+ return 0;
+ }
ScopedJavaUnicodeString skeletonHolder(env, javaSkeleton);
if (!skeletonHolder.valid()) {
@@ -32,7 +36,7 @@ static jlong DateIntervalFormat_createDateIntervalFormat(JNIEnv* env, jclass, js
}
UErrorCode status = U_ZERO_ERROR;
- DateIntervalFormat* formatter(DateIntervalFormat::createInstance(skeletonHolder.unicodeString(), locale, status));
+ DateIntervalFormat* formatter(DateIntervalFormat::createInstance(skeletonHolder.unicodeString(), icuLocale.locale(), status));
if (maybeThrowIcuException(env, "DateIntervalFormat::createInstance", status)) {
return 0;
}
diff --git a/luni/src/main/native/libcore_icu_ICU.cpp b/luni/src/main/native/libcore_icu_ICU.cpp
index 5bbb506..1528a2d 100644
--- a/luni/src/main/native/libcore_icu_ICU.cpp
+++ b/luni/src/main/native/libcore_icu_ICU.cpp
@@ -21,12 +21,14 @@
#include "JniConstants.h"
#include "JniException.h"
#include "ScopedFd.h"
+#include "ScopedIcuLocale.h"
#include "ScopedJavaUnicodeString.h"
#include "ScopedLocalRef.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#include "cutils/log.h"
#include "toStringArray.h"
+#include "unicode/brkiter.h"
#include "unicode/calendar.h"
#include "unicode/datefmt.h"
#include "unicode/dcfmtsym.h"
@@ -60,6 +62,7 @@
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
+#include <vector>
// TODO: put this in a header file and use it everywhere!
// DISALLOW_COPY_AND_ASSIGN disallows the copy and operator= functions.
@@ -94,26 +97,23 @@ class ScopedResourceBundle {
DISALLOW_COPY_AND_ASSIGN(ScopedResourceBundle);
};
-static jstring ICU_addLikelySubtags(JNIEnv* env, jclass, jstring javaLocale) {
+static jstring ICU_addLikelySubtags(JNIEnv* env, jclass, jstring javaLocaleName) {
UErrorCode status = U_ZERO_ERROR;
- ScopedUtfChars localeID(env, javaLocale);
+ ScopedUtfChars localeID(env, javaLocaleName);
char maximizedLocaleID[ULOC_FULLNAME_CAPACITY];
uloc_addLikelySubtags(localeID.c_str(), maximizedLocaleID, sizeof(maximizedLocaleID), &status);
if (U_FAILURE(status)) {
- return javaLocale;
+ return javaLocaleName;
}
return env->NewStringUTF(maximizedLocaleID);
}
-static jstring ICU_getScript(JNIEnv* env, jclass, jstring javaLocale) {
- UErrorCode status = U_ZERO_ERROR;
- ScopedUtfChars localeID(env, javaLocale);
- char script[ULOC_SCRIPT_CAPACITY];
- uloc_getScript(localeID.c_str(), script, sizeof(script), &status);
- if (U_FAILURE(status)) {
- return NULL;
- }
- return env->NewStringUTF(script);
+static jstring ICU_getScript(JNIEnv* env, jclass, jstring javaLocaleName) {
+ ScopedIcuLocale icuLocale(env, javaLocaleName);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ return env->NewStringUTF(icuLocale.locale().getScript());
}
static jint ICU_getCurrencyFractionDigits(JNIEnv* env, jclass, jstring javaCurrencyCode) {
@@ -126,6 +126,15 @@ static jint ICU_getCurrencyFractionDigits(JNIEnv* env, jclass, jstring javaCurre
return ucurr_getDefaultFractionDigits(icuCurrencyCode.getTerminatedBuffer(), &status);
}
+static jint ICU_getCurrencyNumericCode(JNIEnv* env, jclass, jstring javaCurrencyCode) {
+ ScopedJavaUnicodeString currencyCode(env, javaCurrencyCode);
+ if (!currencyCode.valid()) {
+ return 0;
+ }
+ UnicodeString icuCurrencyCode(currencyCode.unicodeString());
+ return ucurr_getNumericCode(icuCurrencyCode.getTerminatedBuffer());
+}
+
// TODO: rewrite this with int32_t ucurr_forLocale(const char* locale, UChar* buff, int32_t buffCapacity, UErrorCode* ec)...
static jstring ICU_getCurrencyCode(JNIEnv* env, jclass, jstring javaCountryCode) {
UErrorCode status = U_ZERO_ERROR;
@@ -169,9 +178,9 @@ static jstring ICU_getCurrencyCode(JNIEnv* env, jclass, jstring javaCountryCode)
return (charCount == 0) ? env->NewStringUTF("XXX") : env->NewString(chars, charCount);
}
-static jstring getCurrencyName(JNIEnv* env, jstring javaLocaleName, jstring javaCurrencyCode, UCurrNameStyle nameStyle) {
- ScopedUtfChars localeName(env, javaLocaleName);
- if (localeName.c_str() == NULL) {
+static jstring getCurrencyName(JNIEnv* env, jstring javaLanguageTag, jstring javaCurrencyCode, UCurrNameStyle nameStyle) {
+ ScopedUtfChars languageTag(env, javaLanguageTag);
+ if (languageTag.c_str() == NULL) {
return NULL;
}
ScopedJavaUnicodeString currencyCode(env, javaCurrencyCode);
@@ -182,7 +191,7 @@ static jstring getCurrencyName(JNIEnv* env, jstring javaLocaleName, jstring java
UErrorCode status = U_ZERO_ERROR;
UBool isChoiceFormat = false;
int32_t charCount;
- const UChar* chars = ucurr_getName(icuCurrencyCode.getTerminatedBuffer(), localeName.c_str(),
+ const UChar* chars = ucurr_getName(icuCurrencyCode.getTerminatedBuffer(), languageTag.c_str(),
nameStyle, &isChoiceFormat, &charCount, &status);
if (status == U_USING_DEFAULT_WARNING) {
if (nameStyle == UCURR_SYMBOL_NAME) {
@@ -201,46 +210,88 @@ static jstring getCurrencyName(JNIEnv* env, jstring javaLocaleName, jstring java
return (charCount == 0) ? NULL : env->NewString(chars, charCount);
}
-static jstring ICU_getCurrencyDisplayName(JNIEnv* env, jclass, jstring javaLocaleName, jstring javaCurrencyCode) {
- return getCurrencyName(env, javaLocaleName, javaCurrencyCode, UCURR_LONG_NAME);
+static jstring ICU_getCurrencyDisplayName(JNIEnv* env, jclass, jstring javaLanguageTag, jstring javaCurrencyCode) {
+ return getCurrencyName(env, javaLanguageTag, javaCurrencyCode, UCURR_LONG_NAME);
}
-static jstring ICU_getCurrencySymbol(JNIEnv* env, jclass, jstring javaLocaleName, jstring javaCurrencyCode) {
- return getCurrencyName(env, javaLocaleName, javaCurrencyCode, UCURR_SYMBOL_NAME);
+static jstring ICU_getCurrencySymbol(JNIEnv* env, jclass, jstring javaLanguageTag, jstring javaCurrencyCode) {
+ return getCurrencyName(env, javaLanguageTag, javaCurrencyCode, UCURR_SYMBOL_NAME);
}
-static jstring ICU_getDisplayCountryNative(JNIEnv* env, jclass, jstring targetLocale, jstring locale) {
- Locale loc = getLocale(env, locale);
- Locale targetLoc = getLocale(env, targetLocale);
- UnicodeString str;
- targetLoc.getDisplayCountry(loc, str);
- return env->NewString(str.getBuffer(), str.length());
+static jstring ICU_getDisplayCountryNative(JNIEnv* env, jclass, jstring javaTargetLanguageTag, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ ScopedIcuLocale icuTargetLocale(env, javaTargetLanguageTag);
+ if (!icuTargetLocale.valid()) {
+ return NULL;
+ }
+
+ UnicodeString str;
+ icuTargetLocale.locale().getDisplayCountry(icuLocale.locale(), str);
+ return env->NewString(str.getBuffer(), str.length());
}
-static jstring ICU_getDisplayLanguageNative(JNIEnv* env, jclass, jstring targetLocale, jstring locale) {
- Locale loc = getLocale(env, locale);
- Locale targetLoc = getLocale(env, targetLocale);
- UnicodeString str;
- targetLoc.getDisplayLanguage(loc, str);
- return env->NewString(str.getBuffer(), str.length());
+static jstring ICU_getDisplayLanguageNative(JNIEnv* env, jclass, jstring javaTargetLanguageTag, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ ScopedIcuLocale icuTargetLocale(env, javaTargetLanguageTag);
+ if (!icuTargetLocale.valid()) {
+ return NULL;
+ }
+
+ UnicodeString str;
+ icuTargetLocale.locale().getDisplayLanguage(icuLocale.locale(), str);
+ return env->NewString(str.getBuffer(), str.length());
}
-static jstring ICU_getDisplayVariantNative(JNIEnv* env, jclass, jstring targetLocale, jstring locale) {
- Locale loc = getLocale(env, locale);
- Locale targetLoc = getLocale(env, targetLocale);
- UnicodeString str;
- targetLoc.getDisplayVariant(loc, str);
- return env->NewString(str.getBuffer(), str.length());
+static jstring ICU_getDisplayScriptNative(JNIEnv* env, jclass, jstring javaTargetLanguageTag, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ ScopedIcuLocale icuTargetLocale(env, javaTargetLanguageTag);
+ if (!icuTargetLocale.valid()) {
+ return NULL;
+ }
+
+ UnicodeString str;
+ icuTargetLocale.locale().getDisplayScript(icuLocale.locale(), str);
+ return env->NewString(str.getBuffer(), str.length());
}
-static jstring ICU_getISO3CountryNative(JNIEnv* env, jclass, jstring locale) {
- Locale loc = getLocale(env, locale);
- return env->NewStringUTF(loc.getISO3Country());
+static jstring ICU_getDisplayVariantNative(JNIEnv* env, jclass, jstring javaTargetLanguageTag, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ ScopedIcuLocale icuTargetLocale(env, javaTargetLanguageTag);
+ if (!icuTargetLocale.valid()) {
+ return NULL;
+ }
+
+ UnicodeString str;
+ icuTargetLocale.locale().getDisplayVariant(icuLocale.locale(), str);
+ return env->NewString(str.getBuffer(), str.length());
}
-static jstring ICU_getISO3LanguageNative(JNIEnv* env, jclass, jstring locale) {
- Locale loc = getLocale(env, locale);
- return env->NewStringUTF(loc.getISO3Language());
+static jstring ICU_getISO3Country(JNIEnv* env, jclass, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ return env->NewStringUTF(icuLocale.locale().getISO3Country());
+}
+
+static jstring ICU_getISO3Language(JNIEnv* env, jclass, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+ return env->NewStringUTF(icuLocale.locale().getISO3Language());
}
static jobjectArray ICU_getISOCountriesNative(JNIEnv* env, jclass) {
@@ -318,17 +369,6 @@ static void setStringField(JNIEnv* env, jobject obj, const char* fieldName, URes
}
}
-static void setStringField(JNIEnv* env, jobject obj, const char* fieldName, UResourceBundle* bundle, const char* key) {
- UErrorCode status = U_ZERO_ERROR;
- int charCount;
- const UChar* chars = ures_getStringByKey(bundle, key, &charCount, &status);
- if (U_SUCCESS(status)) {
- setStringField(env, obj, fieldName, env->NewString(chars, charCount));
- } else {
- ALOGE("Error setting String field %s from ICU resource (key %s): %s", fieldName, key, u_errorName(status));
- }
-}
-
static void setCharField(JNIEnv* env, jobject obj, const char* fieldName, const UnicodeString& value) {
if (value.length() == 0) {
return;
@@ -369,7 +409,7 @@ static void setDecimalFormatSymbolsData(JNIEnv* env, jobject obj, Locale& locale
setCharField(env, obj, "percent", dfs.getSymbol(DecimalFormatSymbols::kPercentSymbol));
setCharField(env, obj, "perMill", dfs.getSymbol(DecimalFormatSymbols::kPerMillSymbol));
setCharField(env, obj, "monetarySeparator", dfs.getSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol));
- setCharField(env, obj, "minusSign", dfs.getSymbol(DecimalFormatSymbols:: kMinusSignSymbol));
+ setStringField(env, obj, "minusSign", dfs.getSymbol(DecimalFormatSymbols:: kMinusSignSymbol));
setStringField(env, obj, "exponentSeparator", dfs.getSymbol(DecimalFormatSymbols::kExponentialSymbol));
setStringField(env, obj, "infinity", dfs.getSymbol(DecimalFormatSymbols::kInfinitySymbol));
setStringField(env, obj, "NaN", dfs.getSymbol(DecimalFormatSymbols::kNaNSymbol));
@@ -410,6 +450,29 @@ class LocaleNameIterator {
DISALLOW_COPY_AND_ASSIGN(LocaleNameIterator);
};
+static bool getAmPmMarkersNarrow(JNIEnv* env, jobject localeData, const char* locale_name) {
+ UErrorCode status = U_ZERO_ERROR;
+ ScopedResourceBundle root(ures_open(NULL, locale_name, &status));
+ if (U_FAILURE(status)) {
+ return false;
+ }
+ ScopedResourceBundle calendar(ures_getByKey(root.get(), "calendar", NULL, &status));
+ if (U_FAILURE(status)) {
+ return false;
+ }
+ ScopedResourceBundle gregorian(ures_getByKey(calendar.get(), "gregorian", NULL, &status));
+ if (U_FAILURE(status)) {
+ return false;
+ }
+ ScopedResourceBundle amPmMarkersNarrow(ures_getByKey(gregorian.get(), "AmPmMarkersNarrow", NULL, &status));
+ if (U_FAILURE(status)) {
+ return false;
+ }
+ setStringField(env, localeData, "narrowAm", amPmMarkersNarrow.get(), 0);
+ setStringField(env, localeData, "narrowPm", amPmMarkersNarrow.get(), 1);
+ return true;
+}
+
static bool getDateTimePatterns(JNIEnv* env, jobject localeData, const char* locale_name) {
UErrorCode status = U_ZERO_ERROR;
ScopedResourceBundle root(ures_open(NULL, locale_name, &status));
@@ -439,73 +502,96 @@ static bool getDateTimePatterns(JNIEnv* env, jobject localeData, const char* loc
return true;
}
-static bool getYesterdayTodayAndTomorrow(JNIEnv* env, jobject localeData, const char* locale_name) {
+static bool getYesterdayTodayAndTomorrow(JNIEnv* env, jobject localeData, const Locale& locale, const char* locale_name) {
UErrorCode status = U_ZERO_ERROR;
ScopedResourceBundle root(ures_open(NULL, locale_name, &status));
- if (U_FAILURE(status)) {
- return false;
- }
ScopedResourceBundle fields(ures_getByKey(root.get(), "fields", NULL, &status));
+ ScopedResourceBundle day(ures_getByKey(fields.get(), "day", NULL, &status));
+ ScopedResourceBundle relative(ures_getByKey(day.get(), "relative", NULL, &status));
if (U_FAILURE(status)) {
return false;
}
- ScopedResourceBundle day(ures_getByKey(fields.get(), "day", NULL, &status));
+
+ UnicodeString yesterday(ures_getUnicodeStringByKey(relative.get(), "-1", &status));
+ UnicodeString today(ures_getUnicodeStringByKey(relative.get(), "0", &status));
+ UnicodeString tomorrow(ures_getUnicodeStringByKey(relative.get(), "1", &status));
if (U_FAILURE(status)) {
+ ALOGE("Error getting yesterday/today/tomorrow for %s: %s", locale_name, u_errorName(status));
return false;
}
- ScopedResourceBundle relative(ures_getByKey(day.get(), "relative", NULL, &status));
+
+ // We title-case the strings so they have consistent capitalization (http://b/14493853).
+ UniquePtr<BreakIterator> brk(BreakIterator::createSentenceInstance(locale, status));
if (U_FAILURE(status)) {
+ ALOGE("Error getting yesterday/today/tomorrow break iterator for %s: %s", locale_name, u_errorName(status));
return false;
}
- // bn_BD only has a "-2" entry.
- if (relative.hasKey("-1") && relative.hasKey("0") && relative.hasKey("1")) {
- setStringField(env, localeData, "yesterday", relative.get(), "-1");
- setStringField(env, localeData, "today", relative.get(), "0");
- setStringField(env, localeData, "tomorrow", relative.get(), "1");
- return true;
- }
- return false;
+ yesterday.toTitle(brk.get(), locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
+ today.toTitle(brk.get(), locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
+ tomorrow.toTitle(brk.get(), locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
+
+ setStringField(env, localeData, "yesterday", yesterday);
+ setStringField(env, localeData, "today", today);
+ setStringField(env, localeData, "tomorrow", tomorrow);
+ return true;
}
-static jboolean ICU_initLocaleDataNative(JNIEnv* env, jclass, jstring javaLocaleName, jobject localeData) {
- ScopedUtfChars localeName(env, javaLocaleName);
- if (localeName.c_str() == NULL) {
+static jboolean ICU_initLocaleDataNative(JNIEnv* env, jclass, jstring javaLanguageTag, jobject localeData) {
+ ScopedUtfChars languageTag(env, javaLanguageTag);
+ if (languageTag.c_str() == NULL) {
return JNI_FALSE;
}
- if (localeName.size() >= ULOC_FULLNAME_CAPACITY) {
+ if (languageTag.size() >= ULOC_FULLNAME_CAPACITY) {
return JNI_FALSE; // ICU has a fixed-length limit.
}
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return JNI_FALSE;
+ }
+
// Get the DateTimePatterns.
UErrorCode status = U_ZERO_ERROR;
bool foundDateTimePatterns = false;
- for (LocaleNameIterator it(localeName.c_str(), status); it.HasNext(); it.Up()) {
+ for (LocaleNameIterator it(icuLocale.locale().getBaseName(), status); it.HasNext(); it.Up()) {
if (getDateTimePatterns(env, localeData, it.Get())) {
foundDateTimePatterns = true;
break;
}
}
if (!foundDateTimePatterns) {
- ALOGE("Couldn't find ICU DateTimePatterns for %s", localeName.c_str());
+ ALOGE("Couldn't find ICU DateTimePatterns for %s", languageTag.c_str());
return JNI_FALSE;
}
// Get the "Yesterday", "Today", and "Tomorrow" strings.
bool foundYesterdayTodayAndTomorrow = false;
- for (LocaleNameIterator it(localeName.c_str(), status); it.HasNext(); it.Up()) {
- if (getYesterdayTodayAndTomorrow(env, localeData, it.Get())) {
+ for (LocaleNameIterator it(icuLocale.locale().getBaseName(), status); it.HasNext(); it.Up()) {
+ if (getYesterdayTodayAndTomorrow(env, localeData, icuLocale.locale(), it.Get())) {
foundYesterdayTodayAndTomorrow = true;
break;
}
}
if (!foundYesterdayTodayAndTomorrow) {
- ALOGE("Couldn't find ICU yesterday/today/tomorrow for %s", localeName.c_str());
+ ALOGE("Couldn't find ICU yesterday/today/tomorrow for %s", languageTag.c_str());
+ return JNI_FALSE;
+ }
+
+ // Get the narrow "AM" and "PM" strings.
+ bool foundAmPmMarkersNarrow = false;
+ for (LocaleNameIterator it(icuLocale.locale().getBaseName(), status); it.HasNext(); it.Up()) {
+ if (getAmPmMarkersNarrow(env, localeData, it.Get())) {
+ foundAmPmMarkersNarrow = true;
+ break;
+ }
+ }
+ if (!foundAmPmMarkersNarrow) {
+ ALOGE("Couldn't find ICU AmPmMarkersNarrow for %s", languageTag.c_str());
return JNI_FALSE;
}
status = U_ZERO_ERROR;
- Locale locale = getLocale(env, javaLocaleName);
- UniquePtr<Calendar> cal(Calendar::createInstance(locale, status));
+ UniquePtr<Calendar> cal(Calendar::createInstance(icuLocale.locale(), status));
if (U_FAILURE(status)) {
return JNI_FALSE;
}
@@ -515,7 +601,7 @@ static jboolean ICU_initLocaleDataNative(JNIEnv* env, jclass, jstring javaLocale
// Get DateFormatSymbols.
status = U_ZERO_ERROR;
- DateFormatSymbols dateFormatSym(locale, status);
+ DateFormatSymbols dateFormatSym(icuLocale.locale(), status);
if (U_FAILURE(status)) {
return JNI_FALSE;
}
@@ -568,17 +654,17 @@ static jboolean ICU_initLocaleDataNative(JNIEnv* env, jclass, jstring javaLocale
status = U_ZERO_ERROR;
// For numberPatterns and symbols.
- setNumberPatterns(env, localeData, locale);
- setDecimalFormatSymbolsData(env, localeData, locale);
+ setNumberPatterns(env, localeData, icuLocale.locale());
+ setDecimalFormatSymbolsData(env, localeData, icuLocale.locale());
- jstring countryCode = env->NewStringUTF(Locale::createFromName(localeName.c_str()).getCountry());
+ jstring countryCode = env->NewStringUTF(icuLocale.locale().getCountry());
jstring internationalCurrencySymbol = ICU_getCurrencyCode(env, NULL, countryCode);
env->DeleteLocalRef(countryCode);
countryCode = NULL;
jstring currencySymbol = NULL;
if (internationalCurrencySymbol != NULL) {
- currencySymbol = ICU_getCurrencySymbol(env, NULL, javaLocaleName, internationalCurrencySymbol);
+ currencySymbol = ICU_getCurrencySymbol(env, NULL, javaLanguageTag, internationalCurrencySymbol);
} else {
internationalCurrencySymbol = env->NewStringUTF("XXX");
}
@@ -592,25 +678,33 @@ static jboolean ICU_initLocaleDataNative(JNIEnv* env, jclass, jstring javaLocale
return JNI_TRUE;
}
-static jstring ICU_toLowerCase(JNIEnv* env, jclass, jstring javaString, jstring localeName) {
+static jstring ICU_toLowerCase(JNIEnv* env, jclass, jstring javaString, jstring javaLanguageTag) {
ScopedJavaUnicodeString scopedString(env, javaString);
if (!scopedString.valid()) {
return NULL;
}
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
UnicodeString& s(scopedString.unicodeString());
UnicodeString original(s);
- s.toLower(Locale::createFromName(ScopedUtfChars(env, localeName).c_str()));
+ s.toLower(icuLocale.locale());
return s == original ? javaString : env->NewString(s.getBuffer(), s.length());
}
-static jstring ICU_toUpperCase(JNIEnv* env, jclass, jstring javaString, jstring localeName) {
+static jstring ICU_toUpperCase(JNIEnv* env, jclass, jstring javaString, jstring javaLanguageTag) {
ScopedJavaUnicodeString scopedString(env, javaString);
if (!scopedString.valid()) {
return NULL;
}
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
UnicodeString& s(scopedString.unicodeString());
UnicodeString original(s);
- s.toUpper(Locale::createFromName(ScopedUtfChars(env, localeName).c_str()));
+ s.toUpper(icuLocale.locale());
return s == original ? javaString : env->NewString(s.getBuffer(), s.length());
}
@@ -645,10 +739,14 @@ static jobject ICU_getAvailableCurrencyCodes(JNIEnv* env, jclass) {
return fromStringEnumeration(env, status, "ucurr_openISOCurrencies", &e);
}
-static jstring ICU_getBestDateTimePatternNative(JNIEnv* env, jclass, jstring javaSkeleton, jstring javaLocaleName) {
- Locale locale = getLocale(env, javaLocaleName);
+static jstring ICU_getBestDateTimePatternNative(JNIEnv* env, jclass, jstring javaSkeleton, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return NULL;
+ }
+
UErrorCode status = U_ZERO_ERROR;
- UniquePtr<DateTimePatternGenerator> generator(DateTimePatternGenerator::createInstance(locale, status));
+ UniquePtr<DateTimePatternGenerator> generator(DateTimePatternGenerator::createInstance(icuLocale.locale(), status));
if (maybeThrowIcuException(env, "DateTimePatternGenerator::createInstance", status)) {
return NULL;
}
@@ -665,6 +763,21 @@ static jstring ICU_getBestDateTimePatternNative(JNIEnv* env, jclass, jstring jav
return env->NewString(result.getBuffer(), result.length());
}
+static void ICU_setDefaultLocale(JNIEnv* env, jclass, jstring javaLanguageTag) {
+ ScopedIcuLocale icuLocale(env, javaLanguageTag);
+ if (!icuLocale.valid()) {
+ return;
+ }
+
+ UErrorCode status = U_ZERO_ERROR;
+ Locale::setDefault(icuLocale.locale(), status);
+ maybeThrowIcuException(env, "Locale::setDefault", status);
+}
+
+static jstring ICU_getDefaultLocale(JNIEnv* env, jclass) {
+ return env->NewStringUTF(Locale::getDefault().getName());
+}
+
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(ICU, addLikelySubtags, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getAvailableBreakIteratorLocalesNative, "()[Ljava/lang/String;"),
@@ -679,18 +792,22 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(ICU, getCurrencyCode, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getCurrencyDisplayName, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getCurrencyFractionDigits, "(Ljava/lang/String;)I"),
+ NATIVE_METHOD(ICU, getCurrencyNumericCode, "(Ljava/lang/String;)I"),
NATIVE_METHOD(ICU, getCurrencySymbol, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
+ NATIVE_METHOD(ICU, getDefaultLocale, "()Ljava/lang/String;"),
NATIVE_METHOD(ICU, getDisplayCountryNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getDisplayLanguageNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
+ NATIVE_METHOD(ICU, getDisplayScriptNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getDisplayVariantNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(ICU, getISO3CountryNative, "(Ljava/lang/String;)Ljava/lang/String;"),
- NATIVE_METHOD(ICU, getISO3LanguageNative, "(Ljava/lang/String;)Ljava/lang/String;"),
+ NATIVE_METHOD(ICU, getISO3Country, "(Ljava/lang/String;)Ljava/lang/String;"),
+ NATIVE_METHOD(ICU, getISO3Language, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getISOCountriesNative, "()[Ljava/lang/String;"),
NATIVE_METHOD(ICU, getISOLanguagesNative, "()[Ljava/lang/String;"),
NATIVE_METHOD(ICU, getIcuVersion, "()Ljava/lang/String;"),
NATIVE_METHOD(ICU, getScript, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, getUnicodeVersion, "()Ljava/lang/String;"),
NATIVE_METHOD(ICU, initLocaleDataNative, "(Ljava/lang/String;Llibcore/icu/LocaleData;)Z"),
+ NATIVE_METHOD(ICU, setDefaultLocale, "(Ljava/lang/String;)V"),
NATIVE_METHOD(ICU, toLowerCase, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(ICU, toUpperCase, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
};
diff --git a/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp b/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp
index 5d715c9..ef0c2a9 100644
--- a/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp
+++ b/luni/src/main/native/libcore_icu_NativeBreakIterator.cpp
@@ -20,6 +20,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
+#include "ScopedIcuLocale.h"
#include "ScopedUtfChars.h"
#include "unicode/brkiter.h"
#include "unicode/putil.h"
@@ -107,19 +108,18 @@ class BreakIteratorAccessor {
};
#define MAKE_BREAK_ITERATOR_INSTANCE(F) \
- UErrorCode status = U_ZERO_ERROR; \
- const ScopedUtfChars localeChars(env, javaLocale); \
- if (localeChars.c_str() == NULL) { \
+ ScopedIcuLocale icuLocale(env, javaLocaleName); \
+ if (!icuLocale.valid()) { \
return 0; \
} \
- Locale locale(Locale::createFromName(localeChars.c_str())); \
- BreakIterator* it = F(locale, status); \
+ UErrorCode status = U_ZERO_ERROR; \
+ BreakIterator* it = F(icuLocale.locale(), status); \
if (maybeThrowIcuException(env, "ubrk_open", status)) { \
return 0; \
} \
return reinterpret_cast<uintptr_t>(it)
-static jint NativeBreakIterator_cloneImpl(JNIEnv* env, jclass, jlong address) {
+static jlong NativeBreakIterator_cloneImpl(JNIEnv* env, jclass, jlong address) {
BreakIteratorAccessor it(env, address);
return reinterpret_cast<uintptr_t>(it->clone());
}
@@ -143,19 +143,19 @@ static jint NativeBreakIterator_followingImpl(JNIEnv* env, jclass, jlong address
return it->following(offset);
}
-static jint NativeBreakIterator_getCharacterInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getCharacterInstanceImpl(JNIEnv* env, jclass, jstring javaLocaleName) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createCharacterInstance);
}
-static jint NativeBreakIterator_getLineInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getLineInstanceImpl(JNIEnv* env, jclass, jstring javaLocaleName) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createLineInstance);
}
-static jint NativeBreakIterator_getSentenceInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getSentenceInstanceImpl(JNIEnv* env, jclass, jstring javaLocaleName) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createSentenceInstance);
}
-static jint NativeBreakIterator_getWordInstanceImpl(JNIEnv* env, jclass, jstring javaLocale) {
+static jlong NativeBreakIterator_getWordInstanceImpl(JNIEnv* env, jclass, jstring javaLocaleName) {
MAKE_BREAK_ITERATOR_INSTANCE(BreakIterator::createWordInstance);
}
diff --git a/luni/src/main/native/libcore_icu_NativeCollation.cpp b/luni/src/main/native/libcore_icu_NativeCollation.cpp
index 9ac7745..4ce42ec 100644
--- a/luni/src/main/native/libcore_icu_NativeCollation.cpp
+++ b/luni/src/main/native/libcore_icu_NativeCollation.cpp
@@ -16,24 +16,87 @@
#include "ScopedStringChars.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
-#include "ucol_imp.h"
#include "unicode/ucol.h"
#include "unicode/ucoleitr.h"
+#include <cutils/log.h>
+
+// Manages a UCollationElements instance along with the jchar
+// array it is iterating over. The associated array can be unpinned
+// only after a call to ucol_closeElements. This means we have to
+// keep a reference to the string (so that it isn't collected) and
+// make a call to GetStringChars to ensure the underlying array is
+// pinned.
+class CollationElements {
+public:
+ CollationElements()
+ : mElements(NULL), mString(NULL), mChars(NULL) {
+ }
+
+ UCollationElements* get() const {
+ return mElements;
+ }
+
+ // Starts a new iteration sequence over the string |string|. If
+ // we have a valid UCollationElements object, we call ucol_setText
+ // on it. Otherwise, we create a new object with the specified
+ // collator.
+ UErrorCode start(JNIEnv* env, jstring string, UCollator* collator) {
+ release(env, false /* don't close the collator */);
+ mChars = env->GetStringChars(string, NULL);
+ if (mChars != NULL) {
+ mString = static_cast<jstring>(env->NewGlobalRef(string));
+ const size_t size = env->GetStringLength(string);
+
+ UErrorCode status = U_ZERO_ERROR;
+ // If we don't have a UCollationElements object yet, create
+ // a new one. If we do, reset it.
+ if (mElements == NULL) {
+ mElements = ucol_openElements(collator, mChars, size, &status);
+ } else {
+ ucol_setText(mElements, mChars, size, &status);
+ }
+
+ return status;
+ }
+
+ return U_ILLEGAL_ARGUMENT_ERROR;
+ }
+
+ void release(JNIEnv* env, bool closeCollator) {
+ if (mElements != NULL && closeCollator) {
+ ucol_closeElements(mElements);
+ }
+
+ if (mChars != NULL) {
+ env->ReleaseStringChars(mString, mChars);
+ env->DeleteGlobalRef(mString);
+ mChars = NULL;
+ mString = NULL;
+ }
+ }
+
+private:
+ UCollationElements* mElements;
+ jstring mString;
+ const jchar* mChars;
+};
static UCollator* toCollator(jlong address) {
return reinterpret_cast<UCollator*>(static_cast<uintptr_t>(address));
}
-static UCollationElements* toCollationElements(jlong address) {
- return reinterpret_cast<UCollationElements*>(static_cast<uintptr_t>(address));
+static CollationElements* toCollationElements(jlong address) {
+ return reinterpret_cast<CollationElements*>(static_cast<uintptr_t>(address));
}
static void NativeCollation_closeCollator(JNIEnv*, jclass, jlong address) {
ucol_close(toCollator(address));
}
-static void NativeCollation_closeElements(JNIEnv*, jclass, jlong address) {
- ucol_closeElements(toCollationElements(address));
+static void NativeCollation_closeElements(JNIEnv* env, jclass, jlong address) {
+ CollationElements* elements = toCollationElements(address);
+ elements->release(env, true /* close collator */);
+ delete elements;
}
static jint NativeCollation_compare(JNIEnv* env, jclass, jlong address, jstring javaLhs, jstring javaRhs) {
@@ -60,18 +123,23 @@ static jlong NativeCollation_getCollationElementIterator(JNIEnv* env, jclass, jl
if (source.get() == NULL) {
return -1;
}
- UErrorCode status = U_ZERO_ERROR;
- UCollationElements* result = ucol_openElements(toCollator(address), source.get(), source.size(), &status);
+
+ UniquePtr<CollationElements> ce(new CollationElements);
+ UErrorCode status = ce->start(env, javaSource, toCollator(address));
maybeThrowIcuException(env, "ucol_openElements", status);
- return static_cast<jlong>(reinterpret_cast<uintptr_t>(result));
+ if (status == U_ZERO_ERROR) {
+ return static_cast<jlong>(reinterpret_cast<uintptr_t>(ce.release()));
+ }
+
+ return 0L;
}
static jint NativeCollation_getMaxExpansion(JNIEnv*, jclass, jlong address, jint order) {
- return ucol_getMaxExpansion(toCollationElements(address), order);
+ return ucol_getMaxExpansion(toCollationElements(address)->get(), order);
}
static jint NativeCollation_getOffset(JNIEnv*, jclass, jlong address) {
- return ucol_getOffset(toCollationElements(address));
+ return ucol_getOffset(toCollationElements(address)->get());
}
static jstring NativeCollation_getRules(JNIEnv* env, jclass, jlong address) {
@@ -86,7 +154,8 @@ static jbyteArray NativeCollation_getSortKey(JNIEnv* env, jclass, jlong address,
return NULL;
}
const UCollator* collator = toCollator(address);
- uint8_t byteArray[UCOL_MAX_BUFFER * 2];
+ // The buffer size prevents reallocation for most strings.
+ uint8_t byteArray[128];
UniquePtr<uint8_t[]> largerByteArray;
uint8_t* usedByteArray = byteArray;
size_t byteArraySize = ucol_getSortKey(collator, source.get(), source.size(), usedByteArray, sizeof(byteArray) - 1);
@@ -106,16 +175,17 @@ static jbyteArray NativeCollation_getSortKey(JNIEnv* env, jclass, jlong address,
static jint NativeCollation_next(JNIEnv* env, jclass, jlong address) {
UErrorCode status = U_ZERO_ERROR;
- jint result = ucol_next(toCollationElements(address), &status);
+ jint result = ucol_next(toCollationElements(address)->get(), &status);
maybeThrowIcuException(env, "ucol_next", status);
return result;
}
-static jlong NativeCollation_openCollator(JNIEnv* env, jclass, jstring localeName) {
- ScopedUtfChars localeChars(env, localeName);
+static jlong NativeCollation_openCollator(JNIEnv* env, jclass, jstring javaLocaleName) {
+ ScopedUtfChars localeChars(env, javaLocaleName);
if (localeChars.c_str() == NULL) {
return 0;
}
+
UErrorCode status = U_ZERO_ERROR;
UCollator* c = ucol_open(localeChars.c_str(), &status);
maybeThrowIcuException(env, "ucol_open", status);
@@ -136,19 +206,18 @@ static jlong NativeCollation_openCollatorFromRules(JNIEnv* env, jclass, jstring
static jint NativeCollation_previous(JNIEnv* env, jclass, jlong address) {
UErrorCode status = U_ZERO_ERROR;
- jint result = ucol_previous(toCollationElements(address), &status);
+ jint result = ucol_previous(toCollationElements(address)->get(), &status);
maybeThrowIcuException(env, "ucol_previous", status);
return result;
}
static void NativeCollation_reset(JNIEnv*, jclass, jlong address) {
- ucol_reset(toCollationElements(address));
+ ucol_reset(toCollationElements(address)->get());
}
static jlong NativeCollation_safeClone(JNIEnv* env, jclass, jlong address) {
UErrorCode status = U_ZERO_ERROR;
- jint bufferSize = U_COL_SAFECLONE_BUFFERSIZE;
- UCollator* c = ucol_safeClone(toCollator(address), NULL, &bufferSize, &status);
+ UCollator* c = ucol_safeClone(toCollator(address), NULL, NULL, &status);
maybeThrowIcuException(env, "ucol_safeClone", status);
return static_cast<jlong>(reinterpret_cast<uintptr_t>(c));
}
@@ -161,7 +230,7 @@ static void NativeCollation_setAttribute(JNIEnv* env, jclass, jlong address, jin
static void NativeCollation_setOffset(JNIEnv* env, jclass, jlong address, jint offset) {
UErrorCode status = U_ZERO_ERROR;
- ucol_setOffset(toCollationElements(address), offset, &status);
+ ucol_setOffset(toCollationElements(address)->get(), offset, &status);
maybeThrowIcuException(env, "ucol_setOffset", status);
}
@@ -170,8 +239,7 @@ static void NativeCollation_setText(JNIEnv* env, jclass, jlong address, jstring
if (source.get() == NULL) {
return;
}
- UErrorCode status = U_ZERO_ERROR;
- ucol_setText(toCollationElements(address), source.get(), source.size(), &status);
+ UErrorCode status = toCollationElements(address)->start(env, javaSource, NULL);
maybeThrowIcuException(env, "ucol_setText", status);
}
@@ -180,7 +248,7 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(NativeCollation, closeElements, "(J)V"),
NATIVE_METHOD(NativeCollation, compare, "(JLjava/lang/String;Ljava/lang/String;)I"),
NATIVE_METHOD(NativeCollation, getAttribute, "(JI)I"),
- NATIVE_METHOD(NativeCollation, getCollationElementIterator, "(JLjava/lang/String;)I"),
+ NATIVE_METHOD(NativeCollation, getCollationElementIterator, "(JLjava/lang/String;)J"),
NATIVE_METHOD(NativeCollation, getMaxExpansion, "(JI)I"),
NATIVE_METHOD(NativeCollation, getOffset, "(J)I"),
NATIVE_METHOD(NativeCollation, getRules, "(J)Ljava/lang/String;"),
diff --git a/luni/src/main/native/libcore_icu_NativeConverter.cpp b/luni/src/main/native/libcore_icu_NativeConverter.cpp
index 137e172..8dd439a 100644
--- a/luni/src/main/native/libcore_icu_NativeConverter.cpp
+++ b/luni/src/main/native/libcore_icu_NativeConverter.cpp
@@ -214,10 +214,11 @@ static jint NativeConverter_encode(JNIEnv* env, jclass, jlong address,
UErrorCode errorCode = U_ZERO_ERROR;
ucnv_fromUnicode(cnv , &cTarget, cTargetLimit, &mySource, mySourceLimit, NULL, (UBool) flush, &errorCode);
*sourceOffset = (mySource - uSource.get()) - *sourceOffset;
- *targetOffset = (reinterpret_cast<jbyte*>(cTarget) - uTarget.get()) - *targetOffset;
+ *targetOffset = (reinterpret_cast<jbyte*>(cTarget) - uTarget.get());
// If there was an error, count the problematic characters.
- if (errorCode == U_ILLEGAL_CHAR_FOUND || errorCode == U_INVALID_CHAR_FOUND) {
+ if (errorCode == U_ILLEGAL_CHAR_FOUND || errorCode == U_INVALID_CHAR_FOUND ||
+ errorCode == U_TRUNCATED_CHAR_FOUND) {
int8_t invalidUCharCount = 32;
UChar invalidUChars[32];
UErrorCode minorErrorCode = U_ZERO_ERROR;
@@ -272,7 +273,8 @@ static jint NativeConverter_decode(JNIEnv* env, jclass, jlong address,
*targetOffset = cTarget - uTarget.get() - *targetOffset;
// If there was an error, count the problematic bytes.
- if (errorCode == U_ILLEGAL_CHAR_FOUND || errorCode == U_INVALID_CHAR_FOUND) {
+ if (errorCode == U_ILLEGAL_CHAR_FOUND || errorCode == U_INVALID_CHAR_FOUND ||
+ errorCode == U_TRUNCATED_CHAR_FOUND) {
int8_t invalidByteCount = 32;
char invalidBytes[32] = {'\0'};
UErrorCode minorErrorCode = U_ZERO_ERROR;
diff --git a/luni/src/main/native/libcore_icu_NativeDecimalFormat.cpp b/luni/src/main/native/libcore_icu_NativeDecimalFormat.cpp
index 88e6780..c0fd42b 100644
--- a/luni/src/main/native/libcore_icu_NativeDecimalFormat.cpp
+++ b/luni/src/main/native/libcore_icu_NativeDecimalFormat.cpp
@@ -16,25 +16,28 @@
#define LOG_TAG "NativeDecimalFormat"
+#include <stdlib.h>
+#include <string.h>
+
+#include <vector>
+
+#include "cutils/log.h"
+#include "digitlst.h"
#include "IcuUtilities.h"
-#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
+#include "JNIHelp.h"
#include "ScopedJavaUnicodeString.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedStringChars.h"
#include "ScopedUtfChars.h"
-#include "UniquePtr.h"
-#include "cutils/log.h"
-#include "digitlst.h"
#include "unicode/decimfmt.h"
#include "unicode/fmtable.h"
#include "unicode/numfmt.h"
#include "unicode/unum.h"
#include "unicode/ustring.h"
+#include "UniquePtr.h"
#include "valueOf.h"
-#include <stdlib.h>
-#include <string.h>
static DecimalFormat* toDecimalFormat(jlong addr) {
return reinterpret_cast<DecimalFormat*>(static_cast<uintptr_t>(addr));
@@ -47,7 +50,7 @@ static UNumberFormat* toUNumberFormat(jlong addr) {
static DecimalFormatSymbols* makeDecimalFormatSymbols(JNIEnv* env,
jstring currencySymbol0, jchar decimalSeparator, jchar digit, jstring exponentSeparator0,
jchar groupingSeparator0, jstring infinity0,
- jstring internationalCurrencySymbol0, jchar minusSign,
+ jstring internationalCurrencySymbol0, jstring minusSign0,
jchar monetaryDecimalSeparator, jstring nan0, jchar patternSeparator,
jchar percent, jchar perMill, jchar zeroDigit) {
ScopedJavaUnicodeString currencySymbol(env, currencySymbol0);
@@ -55,6 +58,7 @@ static DecimalFormatSymbols* makeDecimalFormatSymbols(JNIEnv* env,
ScopedJavaUnicodeString infinity(env, infinity0);
ScopedJavaUnicodeString internationalCurrencySymbol(env, internationalCurrencySymbol0);
ScopedJavaUnicodeString nan(env, nan0);
+ ScopedJavaUnicodeString minusSign(env, minusSign0);
UnicodeString groupingSeparator(groupingSeparator0);
DecimalFormatSymbols* result = new DecimalFormatSymbols;
@@ -66,7 +70,7 @@ static DecimalFormatSymbols* makeDecimalFormatSymbols(JNIEnv* env,
result->setSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol, groupingSeparator);
result->setSymbol(DecimalFormatSymbols::kInfinitySymbol, infinity.unicodeString());
result->setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, internationalCurrencySymbol.unicodeString());
- result->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, UnicodeString(minusSign));
+ result->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, minusSign.unicodeString());
result->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, UnicodeString(monetaryDecimalSeparator));
result->setSymbol(DecimalFormatSymbols::kNaNSymbol, nan.unicodeString());
result->setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, UnicodeString(patternSeparator));
@@ -90,7 +94,7 @@ static DecimalFormatSymbols* makeDecimalFormatSymbols(JNIEnv* env,
static void NativeDecimalFormat_setDecimalFormatSymbols(JNIEnv* env, jclass, jlong addr,
jstring currencySymbol, jchar decimalSeparator, jchar digit, jstring exponentSeparator,
jchar groupingSeparator, jstring infinity,
- jstring internationalCurrencySymbol, jchar minusSign,
+ jstring internationalCurrencySymbol, jstring minusSign,
jchar monetaryDecimalSeparator, jstring nan, jchar patternSeparator,
jchar percent, jchar perMill, jchar zeroDigit) {
DecimalFormatSymbols* symbols = makeDecimalFormatSymbols(env,
@@ -104,7 +108,7 @@ static void NativeDecimalFormat_setDecimalFormatSymbols(JNIEnv* env, jclass, jlo
static jlong NativeDecimalFormat_open(JNIEnv* env, jclass, jstring pattern0,
jstring currencySymbol, jchar decimalSeparator, jchar digit, jstring exponentSeparator,
jchar groupingSeparator, jstring infinity,
- jstring internationalCurrencySymbol, jchar minusSign,
+ jstring internationalCurrencySymbol, jstring minusSign,
jchar monetaryDecimalSeparator, jstring nan, jchar patternSeparator,
jchar percent, jchar perMill, jchar zeroDigit) {
UErrorCode status = U_ZERO_ERROR;
@@ -216,56 +220,69 @@ static jstring NativeDecimalFormat_toPatternImpl(JNIEnv* env, jclass, jlong addr
return env->NewString(pattern.getBuffer(), pattern.length());
}
-static jcharArray formatResult(JNIEnv* env, const UnicodeString &str, FieldPositionIterator* fpi, jobject fpIter) {
+static jcharArray formatResult(JNIEnv* env, const UnicodeString& s, FieldPositionIterator* fpi, jobject javaFieldPositionIterator) {
static jmethodID gFPI_setData = env->GetMethodID(JniConstants::fieldPositionIteratorClass, "setData", "([I)V");
if (fpi != NULL) {
- int len = fpi->getData(NULL, 0);
- jintArray data = NULL;
- if (len) {
- data = env->NewIntArray(len);
- ScopedIntArrayRW ints(env, data);
+ std::vector<int32_t> data;
+ FieldPosition fp;
+ while (fpi->next(fp)) {
+ data.push_back(fp.getField());
+ data.push_back(fp.getBeginIndex());
+ data.push_back(fp.getEndIndex());
+ }
+
+ jintArray javaData = NULL;
+ if (!data.empty()) {
+ javaData = env->NewIntArray(data.size());
+ if (javaData == NULL) {
+ return NULL;
+ }
+ ScopedIntArrayRW ints(env, javaData);
if (ints.get() == NULL) {
return NULL;
}
- fpi->getData(ints.get(), len);
+ memcpy(ints.get(), &data[0], data.size() * sizeof(int32_t));
}
- env->CallVoidMethod(fpIter, gFPI_setData, data);
+ env->CallVoidMethod(javaFieldPositionIterator, gFPI_setData, javaData);
}
- jcharArray result = env->NewCharArray(str.length());
+ jcharArray result = env->NewCharArray(s.length());
if (result != NULL) {
- env->SetCharArrayRegion(result, 0, str.length(), str.getBuffer());
+ env->SetCharArrayRegion(result, 0, s.length(), s.getBuffer());
}
return result;
}
template <typename T>
-static jcharArray format(JNIEnv* env, jlong addr, jobject fpIter, T val) {
+static jcharArray format(JNIEnv* env, jlong addr, jobject javaFieldPositionIterator, T value) {
UErrorCode status = U_ZERO_ERROR;
- UnicodeString str;
+ UnicodeString s;
DecimalFormat* fmt = toDecimalFormat(addr);
- FieldPositionIterator fpi;
- FieldPositionIterator* pfpi = fpIter ? &fpi : NULL;
- fmt->format(val, str, pfpi, status);
- return formatResult(env, str, pfpi, fpIter);
+ FieldPositionIterator nativeFieldPositionIterator;
+ FieldPositionIterator* fpi = javaFieldPositionIterator ? &nativeFieldPositionIterator : NULL;
+ fmt->format(value, s, fpi, status);
+ if (maybeThrowIcuException(env, "DecimalFormat::format", status)) {
+ return NULL;
+ }
+ return formatResult(env, s, fpi, javaFieldPositionIterator);
}
-static jcharArray NativeDecimalFormat_formatLong(JNIEnv* env, jclass, jlong addr, jlong value, jobject fpIter) {
- return format(env, addr, fpIter, value);
+static jcharArray NativeDecimalFormat_formatLong(JNIEnv* env, jclass, jlong addr, jlong value, jobject javaFieldPositionIterator) {
+ return format<int64_t>(env, addr, javaFieldPositionIterator, value);
}
-static jcharArray NativeDecimalFormat_formatDouble(JNIEnv* env, jclass, jlong addr, jdouble value, jobject fpIter) {
- return format(env, addr, fpIter, value);
+static jcharArray NativeDecimalFormat_formatDouble(JNIEnv* env, jclass, jlong addr, jdouble value, jobject javaFieldPositionIterator) {
+ return format<double>(env, addr, javaFieldPositionIterator, value);
}
-static jcharArray NativeDecimalFormat_formatDigitList(JNIEnv* env, jclass, jlong addr, jstring value, jobject fpIter) {
+static jcharArray NativeDecimalFormat_formatDigitList(JNIEnv* env, jclass, jlong addr, jstring value, jobject javaFieldPositionIterator) {
ScopedUtfChars chars(env, value);
if (chars.c_str() == NULL) {
return NULL;
}
StringPiece sp(chars.c_str());
- return format(env, addr, fpIter, sp);
+ return format(env, addr, javaFieldPositionIterator, sp);
}
static jobject newBigDecimal(JNIEnv* env, const char* value, jsize len) {
@@ -287,6 +304,11 @@ static jobject NativeDecimalFormat_parse(JNIEnv* env, jclass, jlong addr, jstrin
static jmethodID gPP_setIndex = env->GetMethodID(JniConstants::parsePositionClass, "setIndex", "(I)V");
static jmethodID gPP_setErrorIndex = env->GetMethodID(JniConstants::parsePositionClass, "setErrorIndex", "(I)V");
+ ScopedJavaUnicodeString src(env, text);
+ if (!src.valid()) {
+ return NULL;
+ }
+
// make sure the ParsePosition is valid. Actually icu4c would parse a number
// correctly even if the parsePosition is set to -1, but since the RI fails
// for that case we have to fail too
@@ -297,10 +319,6 @@ static jobject NativeDecimalFormat_parse(JNIEnv* env, jclass, jlong addr, jstrin
Formattable res;
ParsePosition pp(parsePos);
- ScopedJavaUnicodeString src(env, text);
- if (!src.valid()) {
- return NULL;
- }
DecimalFormat* fmt = toDecimalFormat(addr);
fmt->parse(src.unicodeString(), res, pp);
@@ -350,10 +368,10 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(NativeDecimalFormat, formatDigitList, "(JLjava/lang/String;Llibcore/icu/NativeDecimalFormat$FieldPositionIterator;)[C"),
NATIVE_METHOD(NativeDecimalFormat, getAttribute, "(JI)I"),
NATIVE_METHOD(NativeDecimalFormat, getTextAttribute, "(JI)Ljava/lang/String;"),
- NATIVE_METHOD(NativeDecimalFormat, open, "(Ljava/lang/String;Ljava/lang/String;CCLjava/lang/String;CLjava/lang/String;Ljava/lang/String;CCLjava/lang/String;CCCC)J"),
+ NATIVE_METHOD(NativeDecimalFormat, open, "(Ljava/lang/String;Ljava/lang/String;CCLjava/lang/String;CLjava/lang/String;Ljava/lang/String;Ljava/lang/String;CLjava/lang/String;CCCC)J"),
NATIVE_METHOD(NativeDecimalFormat, parse, "(JLjava/lang/String;Ljava/text/ParsePosition;Z)Ljava/lang/Number;"),
NATIVE_METHOD(NativeDecimalFormat, setAttribute, "(JII)V"),
- NATIVE_METHOD(NativeDecimalFormat, setDecimalFormatSymbols, "(JLjava/lang/String;CCLjava/lang/String;CLjava/lang/String;Ljava/lang/String;CCLjava/lang/String;CCCC)V"),
+ NATIVE_METHOD(NativeDecimalFormat, setDecimalFormatSymbols, "(JLjava/lang/String;CCLjava/lang/String;CLjava/lang/String;Ljava/lang/String;Ljava/lang/String;CLjava/lang/String;CCCC)V"),
NATIVE_METHOD(NativeDecimalFormat, setRoundingMode, "(JID)V"),
NATIVE_METHOD(NativeDecimalFormat, setSymbol, "(JILjava/lang/String;)V"),
NATIVE_METHOD(NativeDecimalFormat, setTextAttribute, "(JILjava/lang/String;)V"),
diff --git a/luni/src/main/native/libcore_icu_TimeZoneNames.cpp b/luni/src/main/native/libcore_icu_TimeZoneNames.cpp
index 8c8682a..a7c9098 100644
--- a/luni/src/main/native/libcore_icu_TimeZoneNames.cpp
+++ b/luni/src/main/native/libcore_icu_TimeZoneNames.cpp
@@ -20,6 +20,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
+#include "ScopedIcuLocale.h"
#include "ScopedJavaUnicodeString.h"
#include "ScopedLocalRef.h"
#include "ScopedUtfChars.h"
@@ -43,7 +44,7 @@ static bool isUtc(const UnicodeString& id) {
id == kUct || id == kUtc || id == kUniversal || id == kZulu;
}
-static void setStringArrayElement(JNIEnv* env, jobjectArray array, int i, const UnicodeString& s) {
+static bool setStringArrayElement(JNIEnv* env, jobjectArray array, int i, const UnicodeString& s) {
// Fill in whatever we got. We don't use the display names if they're "GMT[+-]xx:xx"
// because icu4c doesn't use the up-to-date time zone transition data, so it gets these
// wrong. TimeZone.getDisplayName creates accurate names on demand.
@@ -51,15 +52,22 @@ static void setStringArrayElement(JNIEnv* env, jobjectArray array, int i, const
static const UnicodeString kGmt("GMT", 3, US_INV);
if (!s.isBogus() && !s.startsWith(kGmt)) {
ScopedLocalRef<jstring> javaString(env, env->NewString(s.getBuffer(), s.length()));
+ if (javaString.get() == NULL) {
+ return false;
+ }
env->SetObjectArrayElement(array, i, javaString.get());
}
+ return true;
}
-static void TimeZoneNames_fillZoneStrings(JNIEnv* env, jclass, jstring localeName, jobjectArray result) {
- Locale locale = getLocale(env, localeName);
+static void TimeZoneNames_fillZoneStrings(JNIEnv* env, jclass, jstring javaLocaleName, jobjectArray result) {
+ ScopedIcuLocale icuLocale(env, javaLocaleName);
+ if (!icuLocale.valid()) {
+ return;
+ }
UErrorCode status = U_ZERO_ERROR;
- UniquePtr<TimeZoneNames> names(TimeZoneNames::createInstance(locale, status));
+ UniquePtr<TimeZoneNames> names(TimeZoneNames::createInstance(icuLocale.locale(), status));
if (maybeThrowIcuException(env, "TimeZoneNames::createInstance", status)) {
return;
}
@@ -67,7 +75,6 @@ static void TimeZoneNames_fillZoneStrings(JNIEnv* env, jclass, jstring localeNam
const UDate now(Calendar::getNow());
static const UnicodeString kUtc("UTC", 3, US_INV);
- static const UnicodeString pacific_apia("Pacific/Apia", 12, US_INV);
size_t id_count = env->GetArrayLength(result);
for (size_t i = 0; i < id_count; ++i) {
@@ -96,22 +103,45 @@ static void TimeZoneNames_fillZoneStrings(JNIEnv* env, jclass, jstring localeNam
// every language).
// TODO: check CLDR doesn't actually have this somewhere.
long_std = short_std = long_dst = short_dst = kUtc;
- } else if (zone_id.unicodeString() == pacific_apia) {
- // icu4c 50 doesn't know Samoa has DST yet. http://b/7955614
- if (long_dst.isBogus()) {
- long_dst = "Samoa Daylight Time";
- }
}
- setStringArrayElement(env, java_row.get(), 1, long_std);
- setStringArrayElement(env, java_row.get(), 2, short_std);
- setStringArrayElement(env, java_row.get(), 3, long_dst);
- setStringArrayElement(env, java_row.get(), 4, short_dst);
+ bool okay =
+ setStringArrayElement(env, java_row.get(), 1, long_std) &&
+ setStringArrayElement(env, java_row.get(), 2, short_std) &&
+ setStringArrayElement(env, java_row.get(), 3, long_dst) &&
+ setStringArrayElement(env, java_row.get(), 4, short_dst);
+ if (!okay) {
+ return;
+ }
+ }
+}
+
+static jstring TimeZoneNames_getExemplarLocation(JNIEnv* env, jclass, jstring javaLocaleName, jstring javaTz) {
+ ScopedIcuLocale icuLocale(env, javaLocaleName);
+ if (!icuLocale.valid()) {
+ return NULL;
}
+
+ UErrorCode status = U_ZERO_ERROR;
+ UniquePtr<TimeZoneNames> names(TimeZoneNames::createInstance(icuLocale.locale(), status));
+ if (maybeThrowIcuException(env, "TimeZoneNames::createInstance", status)) {
+ return NULL;
+ }
+
+ ScopedJavaUnicodeString tz(env, javaTz);
+ if (!tz.valid()) {
+ return NULL;
+ }
+
+ UnicodeString s;
+ const UDate now(Calendar::getNow());
+ names->getDisplayName(tz.unicodeString(), UTZNM_EXEMPLAR_LOCATION, now, s);
+ return env->NewString(s.getBuffer(), s.length());
}
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(TimeZoneNames, fillZoneStrings, "(Ljava/lang/String;[[Ljava/lang/String;)V"),
+ NATIVE_METHOD(TimeZoneNames, getExemplarLocation, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
};
void register_libcore_icu_TimeZoneNames(JNIEnv* env) {
jniRegisterNativeMethods(env, "libcore/icu/TimeZoneNames", gMethods, NELEM(gMethods));
diff --git a/luni/src/main/native/libcore_io_AsynchronousCloseMonitor.cpp b/luni/src/main/native/libcore_io_AsynchronousCloseMonitor.cpp
index 4f50ce5..a27e7b8 100644
--- a/luni/src/main/native/libcore_io_AsynchronousCloseMonitor.cpp
+++ b/luni/src/main/native/libcore_io_AsynchronousCloseMonitor.cpp
@@ -16,20 +16,20 @@
#define LOG_TAG "AsynchronousCloseMonitor"
-#include "AsynchronousSocketCloseMonitor.h"
+#include "AsynchronousCloseMonitor.h"
#include "JNIHelp.h"
#include "JniConstants.h"
#include "jni.h"
static void AsynchronousCloseMonitor_signalBlockedThreads(JNIEnv* env, jclass, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
- AsynchronousSocketCloseMonitor::signalBlockedThreads(fd);
+ AsynchronousCloseMonitor::signalBlockedThreads(fd);
}
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(AsynchronousCloseMonitor, signalBlockedThreads, "(Ljava/io/FileDescriptor;)V"),
};
void register_libcore_io_AsynchronousCloseMonitor(JNIEnv* env) {
- AsynchronousSocketCloseMonitor::init();
+ AsynchronousCloseMonitor::init();
jniRegisterNativeMethods(env, "libcore/io/AsynchronousCloseMonitor", gMethods, NELEM(gMethods));
}
diff --git a/luni/src/main/native/libcore_io_Memory.cpp b/luni/src/main/native/libcore_io_Memory.cpp
index 77aef5b..9edbfb8 100644
--- a/luni/src/main/native/libcore_io_Memory.cpp
+++ b/luni/src/main/native/libcore_io_Memory.cpp
@@ -38,8 +38,8 @@
#define LONG_ALIGNMENT_MASK 0x7
#define INT_ALIGNMENT_MASK 0x3
#define SHORT_ALIGNMENT_MASK 0x1
-#elif defined(__i386__) || defined(__x86_64__)
-// x86 can load anything at any alignment.
+#elif defined(__aarch64__) || defined(__i386__) || defined(__x86_64__)
+// These architectures can load anything at any alignment.
#define LONG_ALIGNMENT_MASK 0x0
#define INT_ALIGNMENT_MASK 0x0
#define SHORT_ALIGNMENT_MASK 0x0
@@ -259,37 +259,23 @@ static void Memory_pokeShortArray(JNIEnv* env, jclass, jlong dstAddress, jshortA
POKER(jshort, Short, jshort, swapShorts);
}
-static jshort Memory_peekShort(JNIEnv*, jclass, jlong srcAddress, jboolean swap) {
- jshort result = *cast<const jshort*>(srcAddress);
- if (swap) {
- result = bswap_16(result);
- }
- return result;
+static jshort Memory_peekShortNative(JNIEnv*, jclass, jlong srcAddress) {
+ return *cast<const jshort*>(srcAddress);
}
-static void Memory_pokeShort(JNIEnv*, jclass, jlong dstAddress, jshort value, jboolean swap) {
- if (swap) {
- value = bswap_16(value);
- }
+static void Memory_pokeShortNative(JNIEnv*, jclass, jlong dstAddress, jshort value) {
*cast<jshort*>(dstAddress) = value;
}
-static jint Memory_peekInt(JNIEnv*, jclass, jlong srcAddress, jboolean swap) {
- jint result = *cast<const jint*>(srcAddress);
- if (swap) {
- result = bswap_32(result);
- }
- return result;
+static jint Memory_peekIntNative(JNIEnv*, jclass, jlong srcAddress) {
+ return *cast<const jint*>(srcAddress);
}
-static void Memory_pokeInt(JNIEnv*, jclass, jlong dstAddress, jint value, jboolean swap) {
- if (swap) {
- value = bswap_32(value);
- }
+static void Memory_pokeIntNative(JNIEnv*, jclass, jlong dstAddress, jint value) {
*cast<jint*>(dstAddress) = value;
}
-static jlong Memory_peekLong(JNIEnv*, jclass, jlong srcAddress, jboolean swap) {
+static jlong Memory_peekLongNative(JNIEnv*, jclass, jlong srcAddress) {
jlong result;
const jlong* src = cast<const jlong*>(srcAddress);
if ((srcAddress & LONG_ALIGNMENT_MASK) == 0) {
@@ -297,17 +283,11 @@ static jlong Memory_peekLong(JNIEnv*, jclass, jlong srcAddress, jboolean swap) {
} else {
result = get_unaligned<jlong>(src);
}
- if (swap) {
- result = bswap_64(result);
- }
return result;
}
-static void Memory_pokeLong(JNIEnv*, jclass, jlong dstAddress, jlong value, jboolean swap) {
+static void Memory_pokeLongNative(JNIEnv*, jclass, jlong dstAddress, jlong value) {
jlong* dst = cast<jlong*>(dstAddress);
- if (swap) {
- value = bswap_64(value);
- }
if ((dstAddress & LONG_ALIGNMENT_MASK) == 0) {
*dst = value;
} else {
@@ -378,22 +358,22 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Memory, peekCharArray, "(J[CIIZ)V"),
NATIVE_METHOD(Memory, peekDoubleArray, "(J[DIIZ)V"),
NATIVE_METHOD(Memory, peekFloatArray, "(J[FIIZ)V"),
- NATIVE_METHOD(Memory, peekInt, "!(JZ)I"),
+ NATIVE_METHOD(Memory, peekIntNative, "!(J)I"),
NATIVE_METHOD(Memory, peekIntArray, "(J[IIIZ)V"),
- NATIVE_METHOD(Memory, peekLong, "!(JZ)J"),
+ NATIVE_METHOD(Memory, peekLongNative, "!(J)J"),
NATIVE_METHOD(Memory, peekLongArray, "(J[JIIZ)V"),
- NATIVE_METHOD(Memory, peekShort, "!(JZ)S"),
+ NATIVE_METHOD(Memory, peekShortNative, "!(J)S"),
NATIVE_METHOD(Memory, peekShortArray, "(J[SIIZ)V"),
NATIVE_METHOD(Memory, pokeByte, "!(JB)V"),
NATIVE_METHOD(Memory, pokeByteArray, "(J[BII)V"),
NATIVE_METHOD(Memory, pokeCharArray, "(J[CIIZ)V"),
NATIVE_METHOD(Memory, pokeDoubleArray, "(J[DIIZ)V"),
NATIVE_METHOD(Memory, pokeFloatArray, "(J[FIIZ)V"),
- NATIVE_METHOD(Memory, pokeInt, "!(JIZ)V"),
+ NATIVE_METHOD(Memory, pokeIntNative, "!(JI)V"),
NATIVE_METHOD(Memory, pokeIntArray, "(J[IIIZ)V"),
- NATIVE_METHOD(Memory, pokeLong, "!(JJZ)V"),
+ NATIVE_METHOD(Memory, pokeLongNative, "!(JJ)V"),
NATIVE_METHOD(Memory, pokeLongArray, "(J[JIIZ)V"),
- NATIVE_METHOD(Memory, pokeShort, "!(JSZ)V"),
+ NATIVE_METHOD(Memory, pokeShortNative, "!(JS)V"),
NATIVE_METHOD(Memory, pokeShortArray, "(J[SIIZ)V"),
NATIVE_METHOD(Memory, unsafeBulkGet, "(Ljava/lang/Object;II[BIIZ)V"),
NATIVE_METHOD(Memory, unsafeBulkPut, "([BIILjava/lang/Object;IIZ)V"),
diff --git a/luni/src/main/native/libcore_io_Posix.cpp b/luni/src/main/native/libcore_io_Posix.cpp
index cf1b714..e8e8efb 100644
--- a/luni/src/main/native/libcore_io_Posix.cpp
+++ b/luni/src/main/native/libcore_io_Posix.cpp
@@ -16,7 +16,7 @@
#define LOG_TAG "Posix"
-#include "AsynchronousSocketCloseMonitor.h"
+#include "AsynchronousCloseMonitor.h"
#include "cutils/log.h"
#include "ExecStrings.h"
#include "JNIHelp.h"
@@ -24,13 +24,14 @@
#include "JniException.h"
#include "NetworkUtilities.h"
#include "Portability.h"
+#include "readlink.h"
+#include "../../bionic/libc/dns/include/resolv_netid.h" // For android_getaddrinfofornet.
#include "ScopedBytes.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
-#include "StaticAssert.h"
-#include "UniquePtr.h"
#include "toStringArray.h"
+#include "UniquePtr.h"
#include <arpa/inet.h>
#include <errno.h>
@@ -44,8 +45,14 @@
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
+#ifndef __APPLE__
+#include <sys/prctl.h>
+#endif
#include <sys/socket.h>
#include <sys/stat.h>
+#ifdef __APPLE__
+#include <sys/statvfs.h>
+#endif
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
@@ -55,6 +62,11 @@
#include <termios.h>
#include <unistd.h>
+
+#ifndef __unused
+#define __unused __attribute__((__unused__))
+#endif
+
#define TO_JAVA_STRING(NAME, EXP) \
jstring NAME = env->NewStringUTF(EXP); \
if (NAME == NULL) return NULL;
@@ -68,31 +80,79 @@ struct addrinfo_deleter {
};
/**
- * Used to retry networking system calls that can return EINTR. Unlike TEMP_FAILURE_RETRY,
- * this also handles the case where the reason for failure is that another thread called
- * Socket.close. This macro also throws exceptions on failure.
+ * Used to retry networking system calls that can be interrupted with a signal. Unlike
+ * TEMP_FAILURE_RETRY, this also handles the case where
+ * AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal a close() or
+ * Thread.interrupt(). Other signals that result in an EINTR result are ignored and the system call
+ * is retried.
*
- * Returns the result of 'exp', though a Java exception will be pending if the result is -1.
+ * Returns the result of the system call though a Java exception will be pending if the result is
+ * -1: a SocketException if signaled via AsynchronousCloseMonitor, or ErrnoException for other
+ * failures.
*/
#define NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \
return_type _rc = -1; \
do { \
+ bool _wasSignaled; \
+ int _syscallErrno; \
{ \
int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
- AsynchronousSocketCloseMonitor _monitor(_fd); \
+ AsynchronousCloseMonitor _monitor(_fd); \
_rc = syscall_name(_fd, __VA_ARGS__); \
+ _syscallErrno = errno; \
+ _wasSignaled = _monitor.wasSignaled(); \
+ } \
+ if (_wasSignaled) { \
+ jniThrowException(jni_env, "java/net/SocketException", "Socket closed"); \
+ _rc = -1; \
+ break; \
+ } \
+ if (_rc == -1 && _syscallErrno != EINTR) { \
+ /* TODO: with a format string we could show the arguments too, like strace(1). */ \
+ throwErrnoException(jni_env, # syscall_name); \
+ break; \
} \
- if (_rc == -1) { \
- if (jniGetFDFromFileDescriptor(jni_env, java_fd) == -1) { \
- jniThrowException(jni_env, "java/net/SocketException", "Socket closed"); \
+ } while (_rc == -1); /* _syscallErrno == EINTR && !_wasSignaled */ \
+ _rc; })
+
+/**
+ * Used to retry system calls that can be interrupted with a signal. Unlike TEMP_FAILURE_RETRY, this
+ * also handles the case where AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal
+ * a close() or Thread.interrupt(). Other signals that result in an EINTR result are ignored and the
+ * system call is retried.
+ *
+ * Returns the result of the system call though a Java exception will be pending if the result is
+ * -1: an IOException if the file descriptor is already closed, a InterruptedIOException if signaled
+ * via AsynchronousCloseMonitor, or ErrnoException for other failures.
+ */
+#define IO_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \
+ return_type _rc = -1; \
+ int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
+ if (_fd == -1) { \
+ jniThrowException(jni_env, "java/io/IOException", "File descriptor closed"); \
+ } else { \
+ do { \
+ bool _wasSignaled; \
+ int _syscallErrno; \
+ { \
+ int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
+ AsynchronousCloseMonitor _monitor(_fd); \
+ _rc = syscall_name(_fd, __VA_ARGS__); \
+ _syscallErrno = errno; \
+ _wasSignaled = _monitor.wasSignaled(); \
+ } \
+ if (_wasSignaled) { \
+ jniThrowException(jni_env, "java/io/InterruptedIOException", # syscall_name " interrupted"); \
+ _rc = -1; \
break; \
- } else if (errno != EINTR) { \
+ } \
+ if (_rc == -1 && _syscallErrno != EINTR) { \
/* TODO: with a format string we could show the arguments too, like strace(1). */ \
throwErrnoException(jni_env, # syscall_name); \
break; \
} \
- } \
- } while (_rc == -1); \
+ } while (_rc == -1); /* && _syscallErrno == EINTR && !_wasSignaled */ \
+ } \
_rc; })
static void throwException(JNIEnv* env, jclass exceptionClass, jmethodID ctor3, jmethodID ctor2,
@@ -281,9 +341,14 @@ static jobject makeStructTimeval(JNIEnv* env, const struct timeval& tv) {
static_cast<jlong>(tv.tv_sec), static_cast<jlong>(tv.tv_usec));
}
-static jobject makeStructUcred(JNIEnv* env, const struct ucred& u) {
+static jobject makeStructUcred(JNIEnv* env, const struct ucred& u __unused) {
+#ifdef __APPLE__
+ jniThrowException(env, "java/lang/UnsupportedOperationException", "unimplemented support for ucred on a Mac");
+ return NULL;
+#else
static jmethodID ctor = env->GetMethodID(JniConstants::structUcredClass, "<init>", "(III)V");
return env->NewObject(JniConstants::structUcredClass, ctor, u.pid, u.uid, u.gid);
+#endif
}
static jobject makeStructUtsname(JNIEnv* env, const struct utsname& buf) {
@@ -545,8 +610,7 @@ static jint Posix_fcntlFlock(JNIEnv* env, jobject, jobject javaFd, jint cmd, job
lock.l_len = env->GetLongField(javaFlock, lenFid);
lock.l_pid = env->GetIntField(javaFlock, pidFid);
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- int rc = throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd, &lock)));
+ int rc = IO_FAILURE_RETRY(env, int, fcntl, javaFd, cmd, &lock);
if (rc != -1) {
env->SetShortField(javaFlock, typeFid, lock.l_type);
env->SetShortField(javaFlock, whenceFid, lock.l_whence);
@@ -598,7 +662,8 @@ static jstring Posix_gai_strerror(JNIEnv* env, jobject, jint error) {
return env->NewStringUTF(gai_strerror(error));
}
-static jobjectArray Posix_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jobject javaHints) {
+static jobjectArray Posix_android_getaddrinfo(JNIEnv* env, jobject, jstring javaNode,
+ jobject javaHints, jint netId) {
ScopedUtfChars node(env, javaNode);
if (node.c_str() == NULL) {
return NULL;
@@ -618,10 +683,10 @@ static jobjectArray Posix_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jo
addrinfo* addressList = NULL;
errno = 0;
- int rc = getaddrinfo(node.c_str(), NULL, &hints, &addressList);
+ int rc = android_getaddrinfofornet(node.c_str(), NULL, &hints, netId, 0, &addressList);
UniquePtr<addrinfo, addrinfo_deleter> addressListDeleter(addressList);
if (rc != 0) {
- throwGaiException(env, "getaddrinfo", rc);
+ throwGaiException(env, "android_getaddrinfo", rc);
return NULL;
}
@@ -631,7 +696,7 @@ static jobjectArray Posix_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jo
if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
++addressCount;
} else {
- ALOGE("getaddrinfo unexpected ai_family %i", ai->ai_family);
+ ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family);
}
}
if (addressCount == 0) {
@@ -649,7 +714,7 @@ static jobjectArray Posix_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jo
for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) {
// Unknown address family. Skip this address.
- ALOGE("getaddrinfo unexpected ai_family %i", ai->ai_family);
+ ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family);
continue;
}
@@ -799,9 +864,19 @@ static jobject Posix_getsockoptUcred(JNIEnv* env, jobject, jobject javaFd, jint
return makeStructUcred(env, u);
}
-static jint Posix_gettid(JNIEnv*, jobject) {
+static jint Posix_gettid(JNIEnv* env __unused, jobject) {
+#if defined(__APPLE__)
+ uint64_t owner;
+ int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6
+ if (rc != 0) {
+ throwErrnoException(env, "gettid");
+ return 0;
+ }
+ return static_cast<jint>(owner);
+#else
// Neither bionic nor glibc exposes gettid(2).
return syscall(__NR_gettid);
+#endif
}
static jint Posix_getuid(JNIEnv*, jobject) {
@@ -875,6 +950,18 @@ static void Posix_lchown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint
throwIfMinusOne(env, "lchown", TEMP_FAILURE_RETRY(lchown(path.c_str(), uid, gid)));
}
+static void Posix_link(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
+ ScopedUtfChars oldPath(env, javaOldPath);
+ if (oldPath.c_str() == NULL) {
+ return;
+ }
+ ScopedUtfChars newPath(env, javaNewPath);
+ if (newPath.c_str() == NULL) {
+ return;
+ }
+ throwIfMinusOne(env, "link", TEMP_FAILURE_RETRY(link(oldPath.c_str(), newPath.c_str())));
+}
+
static void Posix_listen(JNIEnv* env, jobject, jobject javaFd, jint backlog) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "listen", TEMP_FAILURE_RETRY(listen(fd, backlog)));
@@ -907,6 +994,14 @@ static void Posix_mkdir(JNIEnv* env, jobject, jstring javaPath, jint mode) {
throwIfMinusOne(env, "mkdir", TEMP_FAILURE_RETRY(mkdir(path.c_str(), mode)));
}
+static void Posix_mkfifo(JNIEnv* env, jobject, jstring javaPath, jint mode) {
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return;
+ }
+ throwIfMinusOne(env, "mkfifo", TEMP_FAILURE_RETRY(mkfifo(path.c_str(), mode)));
+}
+
static void Posix_mlock(JNIEnv* env, jobject, jlong address, jlong byteCount) {
void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
throwIfMinusOne(env, "mlock", TEMP_FAILURE_RETRY(mlock(ptr, byteCount)));
@@ -971,7 +1066,7 @@ static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint time
static jfieldID eventsFid = env->GetFieldID(JniConstants::structPollfdClass, "events", "S");
static jfieldID reventsFid = env->GetFieldID(JniConstants::structPollfdClass, "revents", "S");
- // Turn the Java libcore.io.StructPollfd[] into a C++ struct pollfd[].
+ // Turn the Java android.system.StructPollfd[] into a C++ struct pollfd[].
size_t arrayLength = env->GetArrayLength(javaStructs);
UniquePtr<struct pollfd[]> fds(new struct pollfd[arrayLength]);
memset(fds.get(), 0, sizeof(struct pollfd) * arrayLength);
@@ -990,11 +1085,9 @@ static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint time
++count;
}
- // Since we don't know which fds -- if any -- are sockets, be conservative and register
- // all fds for asynchronous socket close monitoring.
- std::vector<AsynchronousSocketCloseMonitor*> monitors;
+ std::vector<AsynchronousCloseMonitor*> monitors;
for (size_t i = 0; i < count; ++i) {
- monitors.push_back(new AsynchronousSocketCloseMonitor(fds[i].fd));
+ monitors.push_back(new AsynchronousCloseMonitor(fds[i].fd));
}
int rc = poll(fds.get(), count, timeoutMs);
for (size_t i = 0; i < monitors.size(); ++i) {
@@ -1005,7 +1098,7 @@ static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint time
return -1;
}
- // Update the revents fields in the Java libcore.io.StructPollfd[].
+ // Update the revents fields in the Java android.system.StructPollfd[].
for (size_t i = 0; i < count; ++i) {
ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i));
if (javaStruct.get() == NULL) {
@@ -1016,13 +1109,39 @@ static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint time
return rc;
}
+static void Posix_posix_fallocate(JNIEnv* env, jobject, jobject javaFd __unused,
+ jlong offset __unused, jlong length __unused) {
+#ifdef __APPLE__
+ jniThrowException(env, "java/lang/UnsupportedOperationException",
+ "fallocate doesn't exist on a Mac");
+#else
+ int fd = jniGetFDFromFileDescriptor(env, javaFd);
+ errno = TEMP_FAILURE_RETRY(posix_fallocate64(fd, offset, length));
+ if (errno != 0) {
+ throwErrnoException(env, "posix_fallocate");
+ }
+#endif
+}
+
+static jint Posix_prctl(JNIEnv* env, jobject, jint option __unused, jlong arg2 __unused,
+ jlong arg3 __unused, jlong arg4 __unused, jlong arg5 __unused) {
+#ifdef __APPLE__
+ jniThrowException(env, "java/lang/UnsupportedOperationException", "prctl doesn't exist on a Mac");
+ return 0;
+#else
+ int result = prctl(static_cast<int>(option),
+ static_cast<unsigned long>(arg2), static_cast<unsigned long>(arg3),
+ static_cast<unsigned long>(arg4), static_cast<unsigned long>(arg5));
+ return throwIfMinusOne(env, "prctl", result);
+#endif
+}
+
static jint Posix_preadBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) {
ScopedBytesRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- return throwIfMinusOne(env, "pread", TEMP_FAILURE_RETRY(pread64(fd, bytes.get() + byteOffset, byteCount, offset)));
+ return IO_FAILURE_RETRY(env, ssize_t, pread64, javaFd, bytes.get() + byteOffset, byteCount, offset);
}
static jint Posix_pwriteBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount, jlong offset) {
@@ -1030,8 +1149,7 @@ static jint Posix_pwriteBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray j
if (bytes.get() == NULL) {
return -1;
}
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- return throwIfMinusOne(env, "pwrite", TEMP_FAILURE_RETRY(pwrite64(fd, bytes.get() + byteOffset, byteCount, offset)));
+ return IO_FAILURE_RETRY(env, ssize_t, pwrite64, javaFd, bytes.get() + byteOffset, byteCount, offset);
}
static jint Posix_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) {
@@ -1039,8 +1157,21 @@ static jint Posix_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBy
if (bytes.get() == NULL) {
return -1;
}
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- return throwIfMinusOne(env, "read", TEMP_FAILURE_RETRY(read(fd, bytes.get() + byteOffset, byteCount)));
+ return IO_FAILURE_RETRY(env, ssize_t, read, javaFd, bytes.get() + byteOffset, byteCount);
+}
+
+static jstring Posix_readlink(JNIEnv* env, jobject, jstring javaPath) {
+ ScopedUtfChars path(env, javaPath);
+ if (path.c_str() == NULL) {
+ return NULL;
+ }
+
+ std::string result;
+ if (!readlink(path.c_str(), result)) {
+ throwErrnoException(env, "readlink");
+ return NULL;
+ }
+ return env->NewStringUTF(result.c_str());
}
static jint Posix_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
@@ -1048,8 +1179,7 @@ static jint Posix_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffe
if (!ioVec.init(buffers, offsets, byteCounts)) {
return -1;
}
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- return throwIfMinusOne(env, "readv", TEMP_FAILURE_RETRY(readv(fd, ioVec.get(), ioVec.size())));
+ return IO_FAILURE_RETRY(env, ssize_t, readv, javaFd, ioVec.get(), ioVec.size());
}
static jint Posix_recvfromBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetSocketAddress) {
@@ -1171,6 +1301,7 @@ static void Posix_setsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level
// Mac OS didn't support modern multicast APIs until 10.7.
static void Posix_setsockoptIpMreqn(JNIEnv*, jobject, jobject, jint, jint, jint) { abort(); }
static void Posix_setsockoptGroupReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); }
+static void Posix_setsockoptGroupSourceReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); }
#else
static void Posix_setsockoptIpMreqn(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
ip_mreqn req;
@@ -1199,6 +1330,7 @@ static void Posix_setsockoptGroupReq(JNIEnv* env, jobject, jobject javaFd, jint
if (rc == -1 && errno == EINVAL) {
// Maybe we're a 32-bit binary talking to a 64-bit kernel?
// glibc doesn't automatically handle this.
+ // http://sourceware.org/bugzilla/show_bug.cgi?id=12080
struct group_req64 {
uint32_t gr_interface;
uint32_t my_padding;
@@ -1211,6 +1343,48 @@ static void Posix_setsockoptGroupReq(JNIEnv* env, jobject, jobject javaFd, jint
}
throwIfMinusOne(env, "setsockopt", rc);
}
+
+static void Posix_setsockoptGroupSourceReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupSourceReq) {
+ socklen_t sa_len;
+ struct group_source_req req;
+ memset(&req, 0, sizeof(req));
+
+ static jfieldID gsrInterfaceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_interface", "I");
+ req.gsr_interface = env->GetIntField(javaGroupSourceReq, gsrInterfaceFid);
+ // Get the IPv4 or IPv6 multicast address to join or leave.
+ static jfieldID gsrGroupFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_group", "Ljava/net/InetAddress;");
+ ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupSourceReq, gsrGroupFid));
+ if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gsr_group, sa_len)) {
+ return;
+ }
+
+ // Get the IPv4 or IPv6 multicast address to add to the filter.
+ static jfieldID gsrSourceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_source", "Ljava/net/InetAddress;");
+ ScopedLocalRef<jobject> javaSource(env, env->GetObjectField(javaGroupSourceReq, gsrSourceFid));
+ if (!inetAddressToSockaddrVerbatim(env, javaSource.get(), 0, req.gsr_source, sa_len)) {
+ return;
+ }
+
+ int fd = jniGetFDFromFileDescriptor(env, javaFd);
+ int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)));
+ if (rc == -1 && errno == EINVAL) {
+ // Maybe we're a 32-bit binary talking to a 64-bit kernel?
+ // glibc doesn't automatically handle this.
+ // http://sourceware.org/bugzilla/show_bug.cgi?id=12080
+ struct group_source_req64 {
+ uint32_t gsr_interface;
+ uint32_t my_padding;
+ sockaddr_storage gsr_group;
+ sockaddr_storage gsr_source;
+ };
+ group_source_req64 req64;
+ req64.gsr_interface = req.gsr_interface;
+ memcpy(&req64.gsr_group, &req.gsr_group, sizeof(req.gsr_group));
+ memcpy(&req64.gsr_source, &req.gsr_source, sizeof(req.gsr_source));
+ rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64)));
+ }
+ throwIfMinusOne(env, "setsockopt", rc);
+}
#endif
static void Posix_setsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaLinger) {
@@ -1351,8 +1525,7 @@ static jint Posix_writeBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray ja
if (bytes.get() == NULL) {
return -1;
}
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- return throwIfMinusOne(env, "write", TEMP_FAILURE_RETRY(write(fd, bytes.get() + byteOffset, byteCount)));
+ return IO_FAILURE_RETRY(env, ssize_t, write, javaFd, bytes.get() + byteOffset, byteCount);
}
static jint Posix_writev(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
@@ -1360,13 +1533,13 @@ static jint Posix_writev(JNIEnv* env, jobject, jobject javaFd, jobjectArray buff
if (!ioVec.init(buffers, offsets, byteCounts)) {
return -1;
}
- int fd = jniGetFDFromFileDescriptor(env, javaFd);
- return throwIfMinusOne(env, "writev", TEMP_FAILURE_RETRY(writev(fd, ioVec.get(), ioVec.size())));
+ return IO_FAILURE_RETRY(env, ssize_t, writev, javaFd, ioVec.get(), ioVec.size());
}
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, accept, "(Ljava/io/FileDescriptor;Ljava/net/InetSocketAddress;)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, access, "(Ljava/lang/String;I)Z"),
+ NATIVE_METHOD(Posix, android_getaddrinfo, "(Ljava/lang/String;Landroid/system/StructAddrinfo;I)[Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"),
NATIVE_METHOD(Posix, chmod, "(Ljava/lang/String;I)V"),
NATIVE_METHOD(Posix, chown, "(Ljava/lang/String;II)V"),
@@ -1381,14 +1554,13 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, fchown, "(Ljava/io/FileDescriptor;II)V"),
NATIVE_METHOD(Posix, fcntlVoid, "(Ljava/io/FileDescriptor;I)I"),
NATIVE_METHOD(Posix, fcntlLong, "(Ljava/io/FileDescriptor;IJ)I"),
- NATIVE_METHOD(Posix, fcntlFlock, "(Ljava/io/FileDescriptor;ILlibcore/io/StructFlock;)I"),
+ NATIVE_METHOD(Posix, fcntlFlock, "(Ljava/io/FileDescriptor;ILandroid/system/StructFlock;)I"),
NATIVE_METHOD(Posix, fdatasync, "(Ljava/io/FileDescriptor;)V"),
- NATIVE_METHOD(Posix, fstat, "(Ljava/io/FileDescriptor;)Llibcore/io/StructStat;"),
- NATIVE_METHOD(Posix, fstatvfs, "(Ljava/io/FileDescriptor;)Llibcore/io/StructStatVfs;"),
+ NATIVE_METHOD(Posix, fstat, "(Ljava/io/FileDescriptor;)Landroid/system/StructStat;"),
+ NATIVE_METHOD(Posix, fstatvfs, "(Ljava/io/FileDescriptor;)Landroid/system/StructStatVfs;"),
NATIVE_METHOD(Posix, fsync, "(Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, ftruncate, "(Ljava/io/FileDescriptor;J)V"),
NATIVE_METHOD(Posix, gai_strerror, "(I)Ljava/lang/String;"),
- NATIVE_METHOD(Posix, getaddrinfo, "(Ljava/lang/String;Llibcore/io/StructAddrinfo;)[Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, getegid, "()I"),
NATIVE_METHOD(Posix, geteuid, "()I"),
NATIVE_METHOD(Posix, getgid, "()I"),
@@ -1397,29 +1569,31 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, getpeername, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"),
NATIVE_METHOD(Posix, getpid, "()I"),
NATIVE_METHOD(Posix, getppid, "()I"),
- NATIVE_METHOD(Posix, getpwnam, "(Ljava/lang/String;)Llibcore/io/StructPasswd;"),
- NATIVE_METHOD(Posix, getpwuid, "(I)Llibcore/io/StructPasswd;"),
+ NATIVE_METHOD(Posix, getpwnam, "(Ljava/lang/String;)Landroid/system/StructPasswd;"),
+ NATIVE_METHOD(Posix, getpwuid, "(I)Landroid/system/StructPasswd;"),
NATIVE_METHOD(Posix, getsockname, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"),
NATIVE_METHOD(Posix, getsockoptByte, "(Ljava/io/FileDescriptor;II)I"),
NATIVE_METHOD(Posix, getsockoptInAddr, "(Ljava/io/FileDescriptor;II)Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, getsockoptInt, "(Ljava/io/FileDescriptor;II)I"),
- NATIVE_METHOD(Posix, getsockoptLinger, "(Ljava/io/FileDescriptor;II)Llibcore/io/StructLinger;"),
- NATIVE_METHOD(Posix, getsockoptTimeval, "(Ljava/io/FileDescriptor;II)Llibcore/io/StructTimeval;"),
- NATIVE_METHOD(Posix, getsockoptUcred, "(Ljava/io/FileDescriptor;II)Llibcore/io/StructUcred;"),
+ NATIVE_METHOD(Posix, getsockoptLinger, "(Ljava/io/FileDescriptor;II)Landroid/system/StructLinger;"),
+ NATIVE_METHOD(Posix, getsockoptTimeval, "(Ljava/io/FileDescriptor;II)Landroid/system/StructTimeval;"),
+ NATIVE_METHOD(Posix, getsockoptUcred, "(Ljava/io/FileDescriptor;II)Landroid/system/StructUcred;"),
NATIVE_METHOD(Posix, gettid, "()I"),
NATIVE_METHOD(Posix, getuid, "()I"),
NATIVE_METHOD(Posix, if_indextoname, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, inet_pton, "(ILjava/lang/String;)Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, ioctlInetAddress, "(Ljava/io/FileDescriptor;ILjava/lang/String;)Ljava/net/InetAddress;"),
- NATIVE_METHOD(Posix, ioctlInt, "(Ljava/io/FileDescriptor;ILlibcore/util/MutableInt;)I"),
+ NATIVE_METHOD(Posix, ioctlInt, "(Ljava/io/FileDescriptor;ILandroid/util/MutableInt;)I"),
NATIVE_METHOD(Posix, isatty, "(Ljava/io/FileDescriptor;)Z"),
NATIVE_METHOD(Posix, kill, "(II)V"),
NATIVE_METHOD(Posix, lchown, "(Ljava/lang/String;II)V"),
+ NATIVE_METHOD(Posix, link, "(Ljava/lang/String;Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, listen, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, lseek, "(Ljava/io/FileDescriptor;JI)J"),
- NATIVE_METHOD(Posix, lstat, "(Ljava/lang/String;)Llibcore/io/StructStat;"),
+ NATIVE_METHOD(Posix, lstat, "(Ljava/lang/String;)Landroid/system/StructStat;"),
NATIVE_METHOD(Posix, mincore, "(JJ[B)V"),
NATIVE_METHOD(Posix, mkdir, "(Ljava/lang/String;I)V"),
+ NATIVE_METHOD(Posix, mkfifo, "(Ljava/lang/String;I)V"),
NATIVE_METHOD(Posix, mlock, "(JJ)V"),
NATIVE_METHOD(Posix, mmap, "(JJIILjava/io/FileDescriptor;J)J"),
NATIVE_METHOD(Posix, msync, "(JJI)V"),
@@ -1427,15 +1601,18 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, munmap, "(JJ)V"),
NATIVE_METHOD(Posix, open, "(Ljava/lang/String;II)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, pipe, "()[Ljava/io/FileDescriptor;"),
- NATIVE_METHOD(Posix, poll, "([Llibcore/io/StructPollfd;I)I"),
+ NATIVE_METHOD(Posix, poll, "([Landroid/system/StructPollfd;I)I"),
+ NATIVE_METHOD(Posix, posix_fallocate, "(Ljava/io/FileDescriptor;JJ)V"),
+ NATIVE_METHOD(Posix, prctl, "(IJJJJ)I"),
NATIVE_METHOD(Posix, preadBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
NATIVE_METHOD(Posix, pwriteBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
NATIVE_METHOD(Posix, readBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
+ NATIVE_METHOD(Posix, readlink, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(Posix, readv, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
NATIVE_METHOD(Posix, recvfromBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetSocketAddress;)I"),
NATIVE_METHOD(Posix, remove, "(Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, rename, "(Ljava/lang/String;Ljava/lang/String;)V"),
- NATIVE_METHOD(Posix, sendfile, "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;Llibcore/util/MutableLong;J)J"),
+ NATIVE_METHOD(Posix, sendfile, "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;Landroid/util/MutableLong;J)J"),
NATIVE_METHOD(Posix, sendtoBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetAddress;I)I"),
NATIVE_METHOD(Posix, setegid, "(I)V"),
NATIVE_METHOD(Posix, setenv, "(Ljava/lang/String;Ljava/lang/String;Z)V"),
@@ -1446,15 +1623,16 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, setsockoptIfreq, "(Ljava/io/FileDescriptor;IILjava/lang/String;)V"),
NATIVE_METHOD(Posix, setsockoptInt, "(Ljava/io/FileDescriptor;III)V"),
NATIVE_METHOD(Posix, setsockoptIpMreqn, "(Ljava/io/FileDescriptor;III)V"),
- NATIVE_METHOD(Posix, setsockoptGroupReq, "(Ljava/io/FileDescriptor;IILlibcore/io/StructGroupReq;)V"),
- NATIVE_METHOD(Posix, setsockoptLinger, "(Ljava/io/FileDescriptor;IILlibcore/io/StructLinger;)V"),
- NATIVE_METHOD(Posix, setsockoptTimeval, "(Ljava/io/FileDescriptor;IILlibcore/io/StructTimeval;)V"),
+ NATIVE_METHOD(Posix, setsockoptGroupReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupReq;)V"),
+ NATIVE_METHOD(Posix, setsockoptGroupSourceReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupSourceReq;)V"),
+ NATIVE_METHOD(Posix, setsockoptLinger, "(Ljava/io/FileDescriptor;IILandroid/system/StructLinger;)V"),
+ NATIVE_METHOD(Posix, setsockoptTimeval, "(Ljava/io/FileDescriptor;IILandroid/system/StructTimeval;)V"),
NATIVE_METHOD(Posix, setuid, "(I)V"),
NATIVE_METHOD(Posix, shutdown, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, socket, "(III)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, socketpair, "(IIILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V"),
- NATIVE_METHOD(Posix, stat, "(Ljava/lang/String;)Llibcore/io/StructStat;"),
- NATIVE_METHOD(Posix, statvfs, "(Ljava/lang/String;)Llibcore/io/StructStatVfs;"),
+ NATIVE_METHOD(Posix, stat, "(Ljava/lang/String;)Landroid/system/StructStat;"),
+ NATIVE_METHOD(Posix, statvfs, "(Ljava/lang/String;)Landroid/system/StructStatVfs;"),
NATIVE_METHOD(Posix, strerror, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, strsignal, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, symlink, "(Ljava/lang/String;Ljava/lang/String;)V"),
@@ -1462,9 +1640,9 @@ static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, tcdrain, "(Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, tcsendbreak, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, umaskImpl, "(I)I"),
- NATIVE_METHOD(Posix, uname, "()Llibcore/io/StructUtsname;"),
+ NATIVE_METHOD(Posix, uname, "()Landroid/system/StructUtsname;"),
NATIVE_METHOD(Posix, unsetenv, "(Ljava/lang/String;)V"),
- NATIVE_METHOD(Posix, waitpid, "(ILlibcore/util/MutableInt;I)I"),
+ NATIVE_METHOD(Posix, waitpid, "(ILandroid/util/MutableInt;I)I"),
NATIVE_METHOD(Posix, writeBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
NATIVE_METHOD(Posix, writev, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
};
diff --git a/luni/src/main/native/libcore_net_RawSocket.cpp b/luni/src/main/native/libcore_net_RawSocket.cpp
deleted file mode 100644
index f8a8506..0000000
--- a/luni/src/main/native/libcore_net_RawSocket.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright 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.
- */
-
-#define LOG_TAG "RawSocket"
-
-#include "AsynchronousSocketCloseMonitor.h"
-#include "cutils/log.h"
-#include "JNIHelp.h"
-#include "JniException.h"
-#include "JniConstants.h"
-#include "NetFd.h"
-#include "NetworkUtilities.h"
-#include "ScopedUtfChars.h"
-#include "ScopedPrimitiveArray.h"
-
-#include "jni.h"
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <linux/rtnetlink.h>
-#include <net/if.h>
-#include <linux/if_ether.h>
-#include <linux/if_packet.h>
-#include <arpa/inet.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <netinet/ip.h>
-#include <linux/udp.h>
-
-union sockunion {
- sockaddr sa;
- sockaddr_ll sll;
-};
-
-/*
- * Creates a socket suitable for raw socket operations. The socket is
- * bound to the interface specified by the supplied name. The socket
- * value is placed into the supplied FileDescriptor instance.
- *
- * TODO(chesnutt): consider breaking this into pieces: create a
- * variety of constructors for different socket types, then a generic
- * setBlocking() method followed by polymorphic bind().
- */
-static void RawSocket_create(JNIEnv* env, jclass, jobject fileDescriptor,
- jshort protocolType, jstring interfaceName)
-{
-
- ScopedUtfChars ifname(env, interfaceName);
- if (ifname.c_str() == NULL) {
- return;
- }
-
- sockunion su;
- memset(&su, 0, sizeof(su));
- su.sll.sll_family = PF_PACKET;
- su.sll.sll_protocol = htons(protocolType);
- su.sll.sll_ifindex = if_nametoindex(ifname.c_str());
- int sock = socket(PF_PACKET, SOCK_DGRAM, htons(protocolType));
-
- if (sock == -1) {
- ALOGE("Can't create socket %s", strerror(errno));
- jniThrowSocketException(env, errno);
- return;
- }
-
- jniSetFileDescriptorOfFD(env, fileDescriptor, sock);
- if (!setBlocking(sock, false)) {
- ALOGE("Can't set non-blocking mode on socket %s", strerror(errno));
- jniThrowSocketException(env, errno);
- return;
- }
-
- int err = bind(sock, &su.sa, sizeof(su));
- if (err != 0) {
- ALOGE("Socket bind error %s", strerror(errno));
- jniThrowSocketException(env, errno);
- return;
- }
-}
-
-/*
- * Writes the L3 (IP) packet to the raw socket supplied in the
- * FileDescriptor instance.
- *
- * Assumes that the caller has validated the offset & byteCount values.
- */
-static int RawSocket_sendPacket(JNIEnv* env, jclass, jobject fileDescriptor,
- jstring interfaceName, jshort protocolType, jbyteArray destMac,
- jbyteArray packet, jint offset, jint byteCount)
-{
- NetFd fd(env, fileDescriptor);
-
- if (fd.isClosed()) {
- return 0;
- }
-
- ScopedUtfChars ifname(env, interfaceName);
- if (ifname.c_str() == NULL) {
- return 0;
- }
-
- ScopedByteArrayRO byteArray(env, packet);
- if (byteArray.get() == NULL) {
- return 0;
- }
-
- ScopedByteArrayRO mac(env, destMac);
- if (mac.get() == NULL) {
- return 0;
- }
-
- sockunion su;
- memset(&su, 0, sizeof(su));
- su.sll.sll_hatype = htons(1); // ARPHRD_ETHER
- su.sll.sll_halen = mac.size();
- memcpy(&su.sll.sll_addr, mac.get(), mac.size());
- su.sll.sll_family = AF_PACKET;
- su.sll.sll_protocol = htons(protocolType);
- su.sll.sll_ifindex = if_nametoindex(ifname.c_str());
-
- int err;
- {
- int intFd = fd.get();
- AsynchronousSocketCloseMonitor monitor(intFd);
- err = NET_FAILURE_RETRY(fd, sendto(intFd, byteArray.get() + offset,
- byteCount, 0, &su.sa, sizeof(su)));
- }
-
- return err;
-}
-
-/*
- * Reads a network packet into the user-supplied buffer. Return the
- * length of the packet, or a 0 if there was a timeout or an
- * unacceptable packet was acquired.
- *
- * Assumes that the caller has validated the offset & byteCount values.
- */
-static jint RawSocket_recvPacket(JNIEnv* env, jclass, jobject fileDescriptor,
- jbyteArray packet, jint offset, jint byteCount, jint port,
- jint timeout_millis)
-{
- NetFd fd(env, fileDescriptor);
- if (fd.isClosed()) {
- return 0;
- }
-
- ScopedByteArrayRW body(env, packet);
- jbyte* packetData = body.get();
- if (packetData == NULL) {
- return 0;
- }
-
- packetData += offset;
-
- pollfd fds[1];
- fds[0].fd = fd.get();
- fds[0].events = POLLIN;
- int retval = poll(fds, 1, timeout_millis);
- if (retval <= 0) {
- return 0;
- }
-
- unsigned int size = 0;
- {
- int packetSize = byteCount;
- int intFd = fd.get();
- AsynchronousSocketCloseMonitor monitor(intFd);
- size = NET_FAILURE_RETRY(fd, read(intFd, packetData, packetSize));
- }
-
- if (env->ExceptionOccurred()) {
- return 0;
- }
-
- if (port != -1) {
- // quick check for UDP type & UDP port
- // the packet is an IP header, UDP header, and UDP payload
- if ((size < (sizeof(struct iphdr) + sizeof(struct udphdr)))) {
- return 0; // runt packet
- }
-
- u_int8_t ip_proto = ((iphdr *) packetData)->protocol;
- if (ip_proto != IPPROTO_UDP) {
- return 0; // something other than UDP
- }
-
- __be16 destPort = htons((reinterpret_cast<udphdr*>(packetData + sizeof(iphdr)))->dest);
- if (destPort != port) {
- return 0; // something other than requested port
- }
- }
-
- return size;
-}
-
-static JNINativeMethod gRawMethods[] = {
- NATIVE_METHOD(RawSocket, create, "(Ljava/io/FileDescriptor;SLjava/lang/String;)V"),
- NATIVE_METHOD(RawSocket, sendPacket, "(Ljava/io/FileDescriptor;Ljava/lang/String;S[B[BII)I"),
- NATIVE_METHOD(RawSocket, recvPacket, "(Ljava/io/FileDescriptor;[BIIII)I"),
-};
-
-void register_libcore_net_RawSocket(JNIEnv* env) {
- jniRegisterNativeMethods(env, "libcore/net/RawSocket", gRawMethods, NELEM(gRawMethods));
-}
diff --git a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
index 6ba055a..2ea8806 100644
--- a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
+++ b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
@@ -632,7 +632,8 @@ static void startElement(void* data, const char* elementName, const char** attri
parsingContext->stringStack.push(env, uri);
parsingContext->stringStack.push(env, localName);
- env->CallVoidMethod(javaParser, startElementMethod, uri, localName, qName, attributes, count);
+ jlong attributesAddress = reinterpret_cast<jlong>(attributes);
+ env->CallVoidMethod(javaParser, startElementMethod, uri, localName, qName, attributesAddress, count);
parsingContext->attributes = NULL;
parsingContext->attributeCount = -1;
@@ -1291,7 +1292,7 @@ static void ExpatAttributes_freeAttributes(JNIEnv*, jobject, jlong pointer) {
static void ExpatParser_staticInitialize(JNIEnv* env, jobject classObject, jstring empty) {
jclass clazz = reinterpret_cast<jclass>(classObject);
startElementMethod = env->GetMethodID(clazz, "startElement",
- "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V");
+ "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JI)V");
if (startElementMethod == NULL) return;
endElementMethod = env->GetMethodID(clazz, "endElement",
diff --git a/luni/src/main/native/sub.mk b/luni/src/main/native/sub.mk
index 8a1d7c5..079ecd2 100644
--- a/luni/src/main/native/sub.mk
+++ b/luni/src/main/native/sub.mk
@@ -4,68 +4,69 @@
# or BUILD_*_LIBRARY.
LOCAL_SRC_FILES := \
- AsynchronousSocketCloseMonitor.cpp \
- ExecStrings.cpp \
- IcuUtilities.cpp \
- JniException.cpp \
- NetworkUtilities.cpp \
- Register.cpp \
- ZipUtilities.cpp \
- cbigint.cpp \
- java_io_Console.cpp \
- java_io_File.cpp \
- java_io_ObjectStreamClass.cpp \
- java_lang_Character.cpp \
- java_lang_Double.cpp \
- java_lang_Float.cpp \
- java_lang_Math.cpp \
- java_lang_ProcessManager.cpp \
- java_lang_RealToString.cpp \
- java_lang_StrictMath.cpp \
- java_lang_StringToReal.cpp \
- java_lang_System.cpp \
- java_math_NativeBN.cpp \
- java_nio_ByteOrder.cpp \
- java_nio_charset_Charsets.cpp \
- java_text_Bidi.cpp \
- java_util_regex_Matcher.cpp \
- java_util_regex_Pattern.cpp \
- java_util_zip_Adler32.cpp \
- java_util_zip_CRC32.cpp \
- java_util_zip_Deflater.cpp \
- java_util_zip_Inflater.cpp \
- libcore_icu_AlphabeticIndex.cpp \
- libcore_icu_DateIntervalFormat.cpp \
- libcore_icu_ICU.cpp \
- libcore_icu_NativeBreakIterator.cpp \
- libcore_icu_NativeCollation.cpp \
- libcore_icu_NativeConverter.cpp \
- libcore_icu_NativeDecimalFormat.cpp \
- libcore_icu_NativeIDN.cpp \
- libcore_icu_NativeNormalizer.cpp \
- libcore_icu_NativePluralRules.cpp \
- libcore_icu_TimeZoneNames.cpp \
- libcore_icu_Transliterator.cpp \
- libcore_io_AsynchronousCloseMonitor.cpp \
- libcore_io_Memory.cpp \
- libcore_io_OsConstants.cpp \
- libcore_io_Posix.cpp \
- libcore_net_RawSocket.cpp \
- org_apache_harmony_xml_ExpatParser.cpp \
- readlink.cpp \
- realpath.cpp \
- sun_misc_Unsafe.cpp \
- valueOf.cpp
+ AsynchronousCloseMonitor.cpp \
+ ExecStrings.cpp \
+ IcuUtilities.cpp \
+ JniException.cpp \
+ NetworkUtilities.cpp \
+ Register.cpp \
+ ZipUtilities.cpp \
+ android_system_OsConstants.cpp \
+ canonicalize_path.cpp \
+ cbigint.cpp \
+ java_io_File.cpp \
+ java_io_FileDescriptor.cpp \
+ java_io_ObjectStreamClass.cpp \
+ java_lang_Character.cpp \
+ java_lang_Double.cpp \
+ java_lang_Float.cpp \
+ java_lang_Math.cpp \
+ java_lang_ProcessManager.cpp \
+ java_lang_RealToString.cpp \
+ java_lang_StrictMath.cpp \
+ java_lang_StringToReal.cpp \
+ java_lang_System.cpp \
+ java_math_NativeBN.cpp \
+ java_nio_ByteOrder.cpp \
+ java_nio_charset_Charsets.cpp \
+ java_text_Bidi.cpp \
+ java_util_jar_StrictJarFile.cpp \
+ java_util_regex_Matcher.cpp \
+ java_util_regex_Pattern.cpp \
+ java_util_zip_Adler32.cpp \
+ java_util_zip_CRC32.cpp \
+ java_util_zip_Deflater.cpp \
+ java_util_zip_Inflater.cpp \
+ libcore_icu_AlphabeticIndex.cpp \
+ libcore_icu_DateIntervalFormat.cpp \
+ libcore_icu_ICU.cpp \
+ libcore_icu_NativeBreakIterator.cpp \
+ libcore_icu_NativeCollation.cpp \
+ libcore_icu_NativeConverter.cpp \
+ libcore_icu_NativeDecimalFormat.cpp \
+ libcore_icu_NativeIDN.cpp \
+ libcore_icu_NativeNormalizer.cpp \
+ libcore_icu_NativePluralRules.cpp \
+ libcore_icu_TimeZoneNames.cpp \
+ libcore_icu_Transliterator.cpp \
+ libcore_io_AsynchronousCloseMonitor.cpp \
+ libcore_io_Memory.cpp \
+ libcore_io_Posix.cpp \
+ org_apache_harmony_xml_ExpatParser.cpp \
+ readlink.cpp \
+ sun_misc_Unsafe.cpp \
+ valueOf.cpp \
LOCAL_C_INCLUDES += \
- external/icu4c/common \
- external/icu4c/i18n \
- external/openssl/include \
- external/zlib
-
-LOCAL_SHARED_LIBRARIES += \
- liblog \
- libnativehelper
+ external/icu/icu4c/source/common \
+ external/icu/icu4c/source/i18n \
+ external/openssl/include \
+ external/zlib \
+ system/core/include \
LOCAL_STATIC_LIBRARIES += \
- libfdlibm
+ libfdlibm \
+
+LOCAL_SHARED_LIBRARIES += \
+ liblog \
+ libnativehelper \
diff --git a/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java b/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java
index d2247cf..8708214 100644
--- a/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java
+++ b/luni/src/test/java/com/android/org/bouncycastle/crypto/digests/DigestTest.java
@@ -36,7 +36,7 @@ public class DigestTest extends TestCase {
* @param newDigest The new digest implementation, provided by OpenSSL
*/
public void doTestMessageDigest(Digest oldDigest, Digest newDigest) {
- final int ITERATIONS = 10;
+ final int ITERATIONS = 100;
byte[] data = new byte[1024];
diff --git a/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java b/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java
index 6d033d3..1475a63 100644
--- a/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java
+++ b/luni/src/test/java/com/android/org/bouncycastle/jce/provider/CertBlacklistTest.java
@@ -109,6 +109,24 @@ public class CertBlacklistTest extends TestCase {
"3xQAyMuOHm72exJljYFqIsiNvGE0KufCqCuH1PD97IXMrLlwGmKKg5jP349lySBpJjm6RDqCTT+6" +
"dUl2jkVbeNmco99Y7AOdtLsOdXBMCo5x8lK8zwQWFrzEms0joHXCpWfGWA==";
+ public static final String ANSSI = "" +
+ "MIIDbDCCAlSgAwIBAgIDAx2nMA0GCSqGSIb3DQEBBQUAMEsxCzAJBgNVBAYTAkZSMQ4wDAYDVQQK" +
+ "EwVER1RQRTEsMCoGA1UEAxMjQUMgREdUUEUgU2lnbmF0dXJlIEF1dGhlbnRpZmljYXRpb24wHhcN" +
+ "MTMwNzE4MTAwNTI4WhcNMTQwNzE4MTAwNTI4WjA+MQswCQYDVQQGEwJGUjETMBEGA1UECgwKREcg" +
+ "VHLDqXNvcjEaMBgGA1UEAwwRQUMgREcgVHLDqXNvciBTU0wwggEiMA0GCSqGSIb3DQEBAQUAA4IB" +
+ "DwAwggEKAoIBAQDI0WFSUyY+MmtFkqFjTefoFyDgh9b1C/2YvSIvT8oCH62JWT5rpeTCZwaXbqWc" +
+ "jaNfzggqaFsokqfhBif43HNHNtNJmvKE32VcuLB0SpsLR/1VeTd9F99C1JeHVa+nelumOHEfouX8" +
+ "rRFrxNXNIYTVeiENT8Y2YqRb/XAril9g7i674uFzLiNR/t/N/F8Exujv9U8m8rmgud/+tG9WDRaD" +
+ "Jwoj3ZFCOnL5qLnSUEcS6TzWpozLmC2JVO5GZKGGd7qC9FjdBkVilkbVIEGSrYvz2Uz2v5IGqMBI" +
+ "QaFL/kSYWxGTaedTOk2drFEApp9AEPTfv1NwCWBfegsGQrHUROM3AgMBAAGjZjBkMBIGA1UdEwEB" +
+ "/wQIMAYBAf8CAQQwHQYDVR0OBBYEFAAMW8lJqJW0DtAv5p3Mjogxvh9lMB8GA1UdIwQYMBaAFOnb" +
+ "kI/9W5nkFTvwYlyn5A1Y6IeZMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAtDfG" +
+ "HkHOLW2d9fiMtwtkEwDauISJLJyCjoRmawzmQbIZXq7HaLliVfE0sdfKUm0iQ0im1/CpnJLPoTeK" +
+ "yBHvNu1ubLc2m+9dabAYhF3pVdKC+gNaAzBXZ9Gt0p1CLk1lf8Hg+R10HN2IPCv7V/crz2Ga+c23" +
+ "4P3pfwYW8+Nd7alGCuvqot6UYXOlheF7zWUkHn6z6tvY+9oMDHKSUAthhA/FB50JgJU89zyTv1eg" +
+ "Y3ldKwvYBW3W3yNZdTHbPyNsPJdhqA55mDNsteE5YTp1PyySDb1MSVrbxDEruoH6ZE99Hob4Ih8A" +
+ "mn7MHZatGClECgjXWFZ2Gxa7OUCaQpcH8g==";
+
public CertBlacklistTest() throws IOException {
tmpFile = File.createTempFile("test", "");
DEFAULT_PUBKEYS = getDefaultPubkeys();
@@ -415,6 +433,20 @@ public class CertBlacklistTest extends TestCase {
assertEquals(bl.isPublicKeyBlackListed(pk), true);
}
+ public void testANSSISerialBlacklist() throws Exception {
+ CertBlacklist bl = new CertBlacklist();
+ assertEquals(bl.isSerialNumberBlackListed(createSerialNumber(ANSSI)), true);
+ }
+
+ public void testANSSIIntermediatePubkeyBlacklist() throws Exception {
+ // build the public key
+ PublicKey pk = createPublicKey(ANSSI);
+ // set our blacklist path
+ CertBlacklist bl = new CertBlacklist();
+ // check to make sure it isn't blacklisted
+ assertEquals(bl.isPublicKeyBlackListed(pk), true);
+ }
+
private static void printHash(String cert) throws Exception {
System.out.println("CERTIFICATE PUBLIC KEY HASH: " + getHash(createPublicKey(cert)));
}
diff --git a/luni/src/test/java/dalvik/system/DexClassLoaderTest.java b/luni/src/test/java/dalvik/system/DexClassLoaderTest.java
index 5133ea0..c57db71 100644
--- a/luni/src/test/java/dalvik/system/DexClassLoaderTest.java
+++ b/luni/src/test/java/dalvik/system/DexClassLoaderTest.java
@@ -16,6 +16,7 @@
package dalvik.system;
+import java.io.FilenameFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.io.File;
@@ -29,121 +30,131 @@ import junit.framework.TestCase;
* Tests for the class {@link DexClassLoader}.
*/
public class DexClassLoaderTest extends TestCase {
- private static final File TMP_DIR =
- new File(System.getProperty("java.io.tmpdir"), "loading-test");
private static final String PACKAGE_PATH = "dalvik/system/";
- private static final String JAR_NAME = "loading-test.jar";
- private static final String DEX_NAME = "loading-test.dex";
- private static final String JAR2_NAME = "loading-test2.jar";
- private static final String DEX2_NAME = "loading-test2.dex";
- private static final File JAR_FILE = new File(TMP_DIR, JAR_NAME);
- private static final File DEX_FILE = new File(TMP_DIR, DEX_NAME);
- private static final File JAR2_FILE = new File(TMP_DIR, JAR2_NAME);
- private static final File DEX2_FILE = new File(TMP_DIR, DEX2_NAME);
- private static final File OPTIMIZED_DIR = new File(TMP_DIR, "optimized");
- private static enum Configuration {
- /** just one classpath element, a raw dex file */
- ONE_DEX(1),
+ private File srcDir;
+ private File dex1;
+ private File dex2;
+ private File jar1;
+ private File jar2;
+ private File optimizedDir;
- /** just one classpath element, a jar file */
- ONE_JAR(1),
+ protected void setUp() throws Exception {
+ srcDir = File.createTempFile("src", "");
+ assertTrue(srcDir.delete());
+ assertTrue(srcDir.mkdirs());
- /** two classpath elements, both raw dex files */
- TWO_DEX(2),
+ dex1 = new File(srcDir, "loading-test.dex");
+ dex2 = new File(srcDir, "loading-test2.dex");
+ jar1 = new File(srcDir, "loading-test.jar");
+ jar2 = new File(srcDir, "loading-test2.jar");
- /** two classpath elements, both jar files */
- TWO_JAR(2);
+ copyResource("loading-test.dex", dex1);
+ copyResource("loading-test2.dex", dex2);
+ copyResource("loading-test.jar", jar1);
+ copyResource("loading-test2.jar", jar2);
- public final int expectedFiles;
-
- Configuration(int expectedFiles) {
- this.expectedFiles = expectedFiles;
- }
+ optimizedDir = File.createTempFile("optimized", "");
+ assertTrue(optimizedDir.delete());
+ assertTrue(optimizedDir.mkdirs());
}
- protected void setUp() throws IOException {
- TMP_DIR.mkdirs();
-
- ClassLoader cl = DexClassLoaderTest.class.getClassLoader();
- copyResource(cl, JAR_NAME, JAR_FILE);
- copyResource(cl, DEX_NAME, DEX_FILE);
- copyResource(cl, JAR2_NAME, JAR2_FILE);
- copyResource(cl, DEX2_NAME, DEX2_FILE);
+ protected void tearDown() {
+ cleanUpDir(srcDir);
+ cleanUpDir(optimizedDir);
+ }
- OPTIMIZED_DIR.mkdirs();
- File[] files = OPTIMIZED_DIR.listFiles();
+ private static void cleanUpDir(File dir) {
+ if (!dir.isDirectory()) {
+ return;
+ }
+ File[] files = dir.listFiles();
for (File file : files) {
- file.delete();
+ assertTrue(file.delete());
}
}
/**
* Copy a resource in the package directory to the indicated
- * target file, but only if the target file doesn't exist.
+ * target file.
*/
- private static void copyResource(ClassLoader loader, String resourceName,
+ private static void copyResource(String resourceName,
File destination) throws IOException {
- if (destination.exists()) {
- return;
+ ClassLoader loader = DexClassLoaderTest.class.getClassLoader();
+ assertFalse(destination.exists());
+ InputStream in = loader.getResourceAsStream(PACKAGE_PATH + resourceName);
+ if (in == null) {
+ throw new IllegalStateException("Resource not found: " + PACKAGE_PATH + resourceName);
}
- InputStream in =
- loader.getResourceAsStream(PACKAGE_PATH + resourceName);
- FileOutputStream out = new FileOutputStream(destination);
- Streams.copy(in, out);
- in.close();
- out.close();
+ try (FileOutputStream out = new FileOutputStream(destination)) {
+ Streams.copy(in, out);
+ } finally {
+ in.close();
+ }
}
+ static final FilenameFilter DEX_FILE_NAME_FILTER = new FilenameFilter() {
+ @Override
+ public boolean accept(File file, String s) {
+ return s.endsWith(".dex");
+ }
+ };
+
/**
- * Helper to construct an instance to test.
+ * Helper to construct a DexClassLoader instance to test.
*
- * @param config how to configure the classpath
+ * @param files The .dex or .jar files to use for the class path.
*/
- private static DexClassLoader createInstance(Configuration config) {
- File file1;
- File file2;
-
- switch (config) {
- case ONE_DEX: file1 = DEX_FILE; file2 = null; break;
- case ONE_JAR: file1 = JAR_FILE; file2 = null; break;
- case TWO_DEX: file1 = DEX_FILE; file2 = DEX2_FILE; break;
- case TWO_JAR: file1 = JAR_FILE; file2 = JAR2_FILE; break;
- default: throw new AssertionError("shouldn't happen");
+ private ClassLoader createLoader(File... files) {
+ assertNotNull(files);
+ assertTrue(files.length > 0);
+ String path = files[0].getAbsolutePath();
+ for (int i = 1; i < files.length; i++) {
+ path += File.pathSeparator + files[i].getAbsolutePath();
}
-
- String path = file1.getAbsolutePath();
- if (file2 != null) {
- path += File.pathSeparator + file2.getAbsolutePath();
- }
-
- return new DexClassLoader(
- path, OPTIMIZED_DIR.getAbsolutePath(), null,
+ return new DexClassLoader(path, optimizedDir.getAbsolutePath(), null,
ClassLoader.getSystemClassLoader());
}
/**
- * Helper to construct an instance to test, using the jar file as
- * the source, and call a named no-argument static method on a
- * named class.
+ * Helper to construct a new DexClassLoader instance to test, using the
+ * given files as the class path, and call a named no-argument static
+ * method on a named class.
*
- * @param config how to configure the classpath
+ * @param className The name of the class of the method to call.
+ * @param methodName The name of the method to call.
+ * @param files The .dex or .jar files to use for the class path.
*/
- public static Object createInstanceAndCallStaticMethod(
- Configuration config, String className, String methodName)
- throws ClassNotFoundException, NoSuchMethodException,
- IllegalAccessException, InvocationTargetException {
- DexClassLoader dcl = createInstance(config);
- Class c = dcl.loadClass(className);
+ public Object createLoaderAndCallMethod(
+ String className, String methodName, File... files)
+ throws ReflectiveOperationException {
+ ClassLoader cl = createLoader(files);
+ Class c = cl.loadClass(className);
Method m = c.getMethod(methodName, (Class[]) null);
return m.invoke(null, (Object[]) null);
}
- /*
- * Tests that are parametric with respect to whether to use a jar
- * file or a dex file as the source of the code
+ /**
+ * Helper to construct a new DexClassLoader instance to test, using the
+ * given files as the class path, and read the contents of the named
+ * resource as a String.
+ *
+ * @param resourceName The name of the resource to get.
+ * @param files The .dex or .jar files to use for the class path.
*/
+ private String createLoaderAndGetResource(String resourceName, File... files) throws Exception {
+ ClassLoader cl = createLoader(files);
+ InputStream in = cl.getResourceAsStream(resourceName);
+ if (in == null) {
+ throw new IllegalStateException("Resource not found: " + resourceName);
+ }
+
+ byte[] contents = Streams.readFully(in);
+ return new String(contents, "UTF-8");
+ }
+
+ // ONE_JAR
/**
* Just a trivial test of construction. This one merely makes
@@ -151,23 +162,19 @@ public class DexClassLoaderTest extends TestCase {
* to verify anything about the constructed instance, other than
* checking for the existence of optimized dex files.
*/
- private static void test_init(Configuration config) {
- createInstance(config);
-
- int expectedFiles = config.expectedFiles;
- int actualFiles = OPTIMIZED_DIR.listFiles().length;
-
- assertEquals(expectedFiles, actualFiles);
+ public void test_oneJar_init() throws Exception {
+ ClassLoader cl = createLoader(jar1);
+ File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER);
+ assertNotNull(files);
+ assertEquals(1, files.length);
}
/**
* Check that a class in the jar/dex file may be used successfully. In this
* case, a trivial static method is called.
*/
- private static void test_simpleUse(Configuration config) throws Exception {
- String result = (String)
- createInstanceAndCallStaticMethod(config, "test.Test1", "test");
-
+ public void test_oneJar_simpleUse() throws Exception {
+ String result = (String) createLoaderAndCallMethod("test.Test1", "test", jar1);
assertSame("blort", result);
}
@@ -176,312 +183,214 @@ public class DexClassLoaderTest extends TestCase {
* that lives inside the loading-test dex/jar file.
*/
- private static void test_constructor(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_constructor");
- }
-
- private static void test_callStaticMethod(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_callStaticMethod");
- }
-
- private static void test_getStaticVariable(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_getStaticVariable");
- }
-
- private static void test_callInstanceMethod(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_callInstanceMethod");
- }
-
- private static void test_getInstanceVariable(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_getInstanceVariable");
- }
-
- private static void test_diff_constructor(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_diff_constructor");
- }
-
- private static void test_diff_callStaticMethod(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_diff_callStaticMethod");
- }
-
- private static void test_diff_getStaticVariable(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_diff_getStaticVariable");
- }
-
- private static void test_diff_callInstanceMethod(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_diff_callInstanceMethod");
- }
-
- private static void test_diff_getInstanceVariable(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_diff_getInstanceVariable");
- }
-
- /*
- * These methods are all essentially just calls to the
- * parametrically-defined tests above.
- */
-
- // ONE_JAR
-
- public void test_oneJar_init() throws Exception {
- test_init(Configuration.ONE_JAR);
- }
-
- public void test_oneJar_simpleUse() throws Exception {
- test_simpleUse(Configuration.ONE_JAR);
- }
-
public void test_oneJar_constructor() throws Exception {
- test_constructor(Configuration.ONE_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_constructor", jar1);
}
public void test_oneJar_callStaticMethod() throws Exception {
- test_callStaticMethod(Configuration.ONE_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", jar1);
}
public void test_oneJar_getStaticVariable() throws Exception {
- test_getStaticVariable(Configuration.ONE_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", jar1);
}
public void test_oneJar_callInstanceMethod() throws Exception {
- test_callInstanceMethod(Configuration.ONE_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", jar1);
}
public void test_oneJar_getInstanceVariable() throws Exception {
- test_getInstanceVariable(Configuration.ONE_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", jar1);
}
// ONE_DEX
public void test_oneDex_init() throws Exception {
- test_init(Configuration.ONE_DEX);
+ ClassLoader cl = createLoader(dex1);
+ File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER);
+ assertNotNull(files);
+ assertEquals(1, files.length);
}
public void test_oneDex_simpleUse() throws Exception {
- test_simpleUse(Configuration.ONE_DEX);
+ String result = (String) createLoaderAndCallMethod("test.Test1", "test", dex1);
+ assertSame("blort", result);
}
public void test_oneDex_constructor() throws Exception {
- test_constructor(Configuration.ONE_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_constructor", dex1);
}
public void test_oneDex_callStaticMethod() throws Exception {
- test_callStaticMethod(Configuration.ONE_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", dex1);
}
public void test_oneDex_getStaticVariable() throws Exception {
- test_getStaticVariable(Configuration.ONE_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", dex1);
}
public void test_oneDex_callInstanceMethod() throws Exception {
- test_callInstanceMethod(Configuration.ONE_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", dex1);
}
public void test_oneDex_getInstanceVariable() throws Exception {
- test_getInstanceVariable(Configuration.ONE_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", dex1);
}
// TWO_JAR
public void test_twoJar_init() throws Exception {
- test_init(Configuration.TWO_JAR);
+ ClassLoader cl = createLoader(jar1, jar2);
+ File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER);
+ assertNotNull(files);
+ assertEquals(2, files.length);
}
public void test_twoJar_simpleUse() throws Exception {
- test_simpleUse(Configuration.TWO_JAR);
+ String result = (String) createLoaderAndCallMethod("test.Test1", "test", jar1, jar2);
+ assertSame("blort", result);
}
public void test_twoJar_constructor() throws Exception {
- test_constructor(Configuration.TWO_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_constructor", jar1, jar2);
}
public void test_twoJar_callStaticMethod() throws Exception {
- test_callStaticMethod(Configuration.TWO_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", jar1, jar2);
}
public void test_twoJar_getStaticVariable() throws Exception {
- test_getStaticVariable(Configuration.TWO_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", jar1, jar2);
}
public void test_twoJar_callInstanceMethod() throws Exception {
- test_callInstanceMethod(Configuration.TWO_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", jar1, jar2);
}
public void test_twoJar_getInstanceVariable() throws Exception {
- test_getInstanceVariable(Configuration.TWO_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", jar1, jar2);
}
- public static void test_twoJar_diff_constructor() throws Exception {
- test_diff_constructor(Configuration.TWO_JAR);
+ public void test_twoJar_diff_constructor() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_constructor", jar1, jar2);
}
- public static void test_twoJar_diff_callStaticMethod() throws Exception {
- test_diff_callStaticMethod(Configuration.TWO_JAR);
+ public void test_twoJar_diff_callStaticMethod() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_callStaticMethod", jar1, jar2);
}
- public static void test_twoJar_diff_getStaticVariable() throws Exception {
- test_diff_getStaticVariable(Configuration.TWO_JAR);
+ public void test_twoJar_diff_getStaticVariable() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_getStaticVariable", jar1, jar2);
}
- public static void test_twoJar_diff_callInstanceMethod()
- throws Exception {
- test_diff_callInstanceMethod(Configuration.TWO_JAR);
+ public void test_twoJar_diff_callInstanceMethod() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_callInstanceMethod", jar1, jar2);
}
- public static void test_twoJar_diff_getInstanceVariable()
- throws Exception {
- test_diff_getInstanceVariable(Configuration.TWO_JAR);
+ public void test_twoJar_diff_getInstanceVariable() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_getInstanceVariable", jar1, jar2);
}
// TWO_DEX
public void test_twoDex_init() throws Exception {
- test_init(Configuration.TWO_DEX);
+ ClassLoader cl = createLoader(dex1, dex2);
+ File[] files = optimizedDir.listFiles(DEX_FILE_NAME_FILTER);
+ assertNotNull(files);
+ assertEquals(2, files.length);
}
public void test_twoDex_simpleUse() throws Exception {
- test_simpleUse(Configuration.TWO_DEX);
+ String result = (String) createLoaderAndCallMethod("test.Test1", "test", dex1, dex2);
+ assertSame("blort", result);
}
public void test_twoDex_constructor() throws Exception {
- test_constructor(Configuration.TWO_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_constructor", dex1, dex2);
}
public void test_twoDex_callStaticMethod() throws Exception {
- test_callStaticMethod(Configuration.TWO_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_callStaticMethod", dex1, dex2);
}
public void test_twoDex_getStaticVariable() throws Exception {
- test_getStaticVariable(Configuration.TWO_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_getStaticVariable", dex1, dex2);
}
public void test_twoDex_callInstanceMethod() throws Exception {
- test_callInstanceMethod(Configuration.TWO_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_callInstanceMethod", dex1, dex2);
}
public void test_twoDex_getInstanceVariable() throws Exception {
- test_getInstanceVariable(Configuration.TWO_DEX);
+ createLoaderAndCallMethod("test.TestMethods", "test_getInstanceVariable", dex1, dex2);
}
- public static void test_twoDex_diff_constructor() throws Exception {
- test_diff_constructor(Configuration.TWO_DEX);
+ public void test_twoDex_diff_constructor() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_constructor", dex1, dex2);
}
- public static void test_twoDex_diff_callStaticMethod() throws Exception {
- test_diff_callStaticMethod(Configuration.TWO_DEX);
+ public void test_twoDex_diff_callStaticMethod() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_callStaticMethod", dex1, dex2);
}
- public static void test_twoDex_diff_getStaticVariable() throws Exception {
- test_diff_getStaticVariable(Configuration.TWO_DEX);
+ public void test_twoDex_diff_getStaticVariable() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_getStaticVariable", dex1, dex2);
}
- public static void test_twoDex_diff_callInstanceMethod()
- throws Exception {
- test_diff_callInstanceMethod(Configuration.TWO_DEX);
+ public void test_twoDex_diff_callInstanceMethod() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_callInstanceMethod", dex1, dex2);
}
- public static void test_twoDex_diff_getInstanceVariable()
- throws Exception {
- test_diff_getInstanceVariable(Configuration.TWO_DEX);
+ public void test_twoDex_diff_getInstanceVariable() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_getInstanceVariable", dex1, dex2);
}
/*
* Tests specifically for resource-related functionality. Since
* raw dex files don't contain resources, these test only work
- * with jar files. The first couple methods here are helpers,
- * and they are followed by the tests per se.
- */
-
- /**
- * Check that a given resource (by name) is retrievable and contains
- * the given expected contents.
+ * with jar files.
*/
- private static void test_directGetResourceAsStream(Configuration config,
- String resourceName, String expectedContents)
- throws Exception {
- DexClassLoader dcl = createInstance(config);
- InputStream in = dcl.getResourceAsStream(resourceName);
- byte[] contents = Streams.readFully(in);
- String s = new String(contents, "UTF-8");
-
- assertEquals(expectedContents, s);
- }
/**
* Check that a resource in the jar file is retrievable and contains
* the expected contents.
*/
- private static void test_directGetResourceAsStream(Configuration config)
- throws Exception {
- test_directGetResourceAsStream(
- config, "test/Resource1.txt", "Muffins are tasty!\n");
+ public void test_oneJar_directGetResourceAsStream() throws Exception {
+ String result = createLoaderAndGetResource("test/Resource1.txt", jar1);
+ assertEquals("Muffins are tasty!\n", result);
}
/**
* Check that a resource in the jar file can be retrieved from
* a class within that jar file.
*/
- private static void test_getResourceAsStream(Configuration config)
- throws Exception {
- createInstanceAndCallStaticMethod(
- config, "test.TestMethods", "test_getResourceAsStream");
- }
-
- public void test_oneJar_directGetResourceAsStream() throws Exception {
- test_directGetResourceAsStream(Configuration.ONE_JAR);
- }
-
public void test_oneJar_getResourceAsStream() throws Exception {
- test_getResourceAsStream(Configuration.ONE_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_getResourceAsStream", jar1);
}
public void test_twoJar_directGetResourceAsStream() throws Exception {
- test_directGetResourceAsStream(Configuration.TWO_JAR);
+ String result = createLoaderAndGetResource("test/Resource1.txt", jar1, jar2);
+ assertEquals("Muffins are tasty!\n", result);
}
public void test_twoJar_getResourceAsStream() throws Exception {
- test_getResourceAsStream(Configuration.TWO_JAR);
+ createLoaderAndCallMethod("test.TestMethods", "test_getResourceAsStream", jar1, jar2);
}
/**
* Check that a resource in the second jar file is retrievable and
* contains the expected contents.
*/
- public void test_twoJar_diff_directGetResourceAsStream()
- throws Exception {
- test_directGetResourceAsStream(
- Configuration.TWO_JAR, "test2/Resource2.txt",
- "Who doesn't like a good biscuit?\n");
+ public void test_twoJar_diff_directGetResourceAsStream() throws Exception {
+ String result = createLoaderAndGetResource("test2/Resource2.txt", jar1, jar2);
+ assertEquals("Who doesn't like a good biscuit?\n", result);
}
/**
* Check that a resource in a jar file can be retrieved from
* a class within the other jar file.
*/
- public void test_twoJar_diff_getResourceAsStream()
- throws Exception {
- createInstanceAndCallStaticMethod(
- Configuration.TWO_JAR, "test.TestMethods",
- "test_diff_getResourceAsStream");
+ public void test_twoJar_diff_getResourceAsStream() throws Exception {
+ createLoaderAndCallMethod("test.TestMethods", "test_diff_getResourceAsStream", jar1, jar2);
}
}
diff --git a/luni/src/test/java/dalvik/system/JniTest.java b/luni/src/test/java/dalvik/system/JniTest.java
new file mode 100644
index 0000000..37e687d
--- /dev/null
+++ b/luni/src/test/java/dalvik/system/JniTest.java
@@ -0,0 +1,368 @@
+/*
+ * 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 dalvik.system;
+
+import junit.framework.TestCase;
+
+/**
+ * Test JNI behavior
+ */
+public final class JniTest extends TestCase {
+
+ static {
+ System.loadLibrary("javacoretests");
+ }
+
+ /** @return this argument of method */
+ private native JniTest returnThis();
+ /** @return class argument of method */
+ private static native Class<JniTest> returnClass();
+
+ private native Object returnObjectArgFrom16(int arg_no,
+ Object o1, Object o2, Object o3, Object o4, Object o5,
+ Object o6, Object o7, Object o8, Object o9, Object o10,
+ Object o11, Object o12, Object o13, Object o14, Object o15,
+ Object o16);
+ private native boolean returnBooleanArgFrom16(int arg_no,
+ boolean o1, boolean o2, boolean o3, boolean o4, boolean o5,
+ boolean o6, boolean o7, boolean o8, boolean o9, boolean o10,
+ boolean o11, boolean o12, boolean o13, boolean o14, boolean o15,
+ boolean o16);
+ private native char returnCharArgFrom16(int arg_no,
+ char o1, char o2, char o3, char o4, char o5,
+ char o6, char o7, char o8, char o9, char o10,
+ char o11, char o12, char o13, char o14, char o15,
+ char o16);
+ private native byte returnByteArgFrom16(int arg_no,
+ byte o1, byte o2, byte o3, byte o4, byte o5,
+ byte o6, byte o7, byte o8, byte o9, byte o10,
+ byte o11, byte o12, byte o13, byte o14, byte o15,
+ byte o16);
+ private native short returnShortArgFrom16(int arg_no,
+ short o1, short o2, short o3, short o4, short o5,
+ short o6, short o7, short o8, short o9, short o10,
+ short o11, short o12, short o13, short o14, short o15,
+ short o16);
+ private native int returnIntArgFrom16(int arg_no,
+ int o1, int o2, int o3, int o4, int o5,
+ int o6, int o7, int o8, int o9, int o10,
+ int o11, int o12, int o13, int o14, int o15,
+ int o16);
+ private native long returnLongArgFrom16(int arg_no,
+ long o1, long o2, long o3, long o4, long o5,
+ long o6, long o7, long o8, long o9, long o10,
+ long o11, long o12, long o13, long o14, long o15,
+ long o16);
+ private native float returnFloatArgFrom16(int arg_no,
+ float o1, float o2, float o3, float o4, float o5,
+ float o6, float o7, float o8, float o9, float o10,
+ float o11, float o12, float o13, float o14, float o15,
+ float o16);
+ private native double returnDoubleArgFrom16(int arg_no,
+ double o1, double o2, double o3, double o4, double o5,
+ double o6, double o7, double o8, double o9, double o10,
+ double o11, double o12, double o13, double o14, double o15,
+ double o16);
+
+ /** Test cases for implicit this argument */
+ public void testPassingThis() {
+ assertEquals(this, returnThis());
+ }
+
+ /** Test cases for implicit class argument */
+ public void testPassingClass() {
+ assertEquals(JniTest.class, returnClass());
+ }
+
+ /** Test passing object references as arguments to a native method */
+ public void testPassingObjectReferences() {
+ final Object[] literals = {"Bradshaw", "Isherwood", "Oldknow", "Mallet",
+ JniTest.class, null, Integer.valueOf(0)};
+ final Object[] a = new Object[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(Object literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnObjectArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnObjectArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing booleans as arguments to a native method */
+ public void testPassingBooleans() {
+ final boolean[] literals = {true, false, false, true};
+ final boolean[] a = new boolean[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(boolean literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnBooleanArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnBooleanArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing characters as arguments to a native method */
+ public void testPassingChars() {
+ final char[] literals = {Character.MAX_VALUE, Character.MIN_VALUE,
+ Character.MAX_HIGH_SURROGATE, Character.MAX_LOW_SURROGATE,
+ Character.MIN_HIGH_SURROGATE, Character.MIN_LOW_SURROGATE,
+ 'a', 'z', 'A', 'Z', '0', '9'};
+ final char[] a = new char[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(char literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnCharArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnCharArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing bytes as arguments to a native method */
+ public void testPassingBytes() {
+ final byte[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, 0, -1};
+ final byte[] a = new byte[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(byte literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnByteArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnByteArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing shorts as arguments to a native method */
+ public void testPassingShorts() {
+ final short[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE, 0, -1};
+ final short[] a = new short[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(short literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnShortArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnShortArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing ints as arguments to a native method */
+ public void testPassingInts() {
+ final int[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE,
+ Integer.MAX_VALUE, Integer.MIN_VALUE, 0, -1};
+ final int[] a = new int[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(int literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnIntArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnIntArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing longs as arguments to a native method */
+ public void testPassingLongs() {
+ final long[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE,
+ Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, 0, -1};
+ final long[] a = new long[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(long literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnLongArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnLongArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing floats as arguments to a native method */
+ public void testPassingFloats() {
+ final float[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE,
+ Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE,
+ Float.MAX_VALUE, Float.MIN_VALUE, Float.MIN_NORMAL, Float.NaN,
+ Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, (float)Math.E, (float)Math.PI, 0, -1};
+ final float[] a = new float[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(float literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnFloatArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnFloatArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ /** Test passing doubles as arguments to a native method */
+ public void testPassingDoubles() {
+ final double[] literals = {Byte.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE,
+ Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE,
+ Float.MAX_VALUE, Float.MIN_VALUE, Float.MIN_NORMAL, Float.NaN,
+ Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY,
+ Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL, Double.NaN,
+ Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY,
+ Math.E, Math.PI, 0, -1};
+ final double[] a = new double[16];
+ // test selection from a list of object literals where the literals are all the same
+ for(double literal : literals) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literal;
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnDoubleArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ // test selection from a list of object literals where the literals are shuffled
+ for(int j = 0; j < literals.length; j++) {
+ for(int i = 0; i < 16; i++) {
+ a[i] = literals[(i + j) % literals.length];
+ }
+ for(int i = 0; i < 16; i++) {
+ assertEquals(a[i], returnDoubleArgFrom16(i, a[0], a[1], a[2], a[3], a[4],
+ a[5], a[6], a[7], a[8], a[9], a[10],
+ a[11], a[12], a[13], a[14], a[15]));
+ }
+ }
+ }
+
+ private static native Class<?> envGetSuperclass(Class<?> clazz);
+
+ public void testGetSuperclass() {
+ assertEquals(Object.class, envGetSuperclass(String.class));
+ assertEquals(null, envGetSuperclass(Object.class));
+ assertEquals(null, envGetSuperclass(int.class));
+
+ // incorrect! the spec says this should be null. http://b/5652725
+ assertEquals(Object.class, envGetSuperclass(Runnable.class));
+ }
+}
diff --git a/luni/src/test/java/dalvik/system/VMRuntimeTest.java b/luni/src/test/java/dalvik/system/VMRuntimeTest.java
new file mode 100644
index 0000000..251ecd8
--- /dev/null
+++ b/luni/src/test/java/dalvik/system/VMRuntimeTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2014 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 dalvik.system;
+
+import java.lang.reflect.Array;
+import junit.framework.TestCase;
+
+/**
+ * Test VMRuntime behavior.
+ */
+public final class VMRuntimeTest extends TestCase {
+
+ private void doTestNewNonMovableArray(Class<?> componentType, int step, int maxLength) {
+ // Can't create negative sized arrays.
+ try {
+ Object array = VMRuntime.getRuntime().newNonMovableArray(componentType, -1);
+ assertTrue(false);
+ } catch (NegativeArraySizeException expected) {
+ }
+
+ try {
+ Object array = VMRuntime.getRuntime().newNonMovableArray(componentType, Integer.MIN_VALUE);
+ assertTrue(false);
+ } catch (NegativeArraySizeException expected) {
+ }
+
+ // Allocate arrays in a loop and check their properties.
+ for (int i = 0; i <= maxLength; i += step) {
+ Object array = VMRuntime.getRuntime().newNonMovableArray(componentType, i);
+ assertTrue(array.getClass().isArray());
+ assertEquals(array.getClass().getComponentType(), componentType);
+ assertEquals(Array.getLength(array), i);
+ }
+ }
+
+ public void testNewNonMovableArray() {
+ // Can't create arrays with no component type.
+ try {
+ Object array = VMRuntime.getRuntime().newNonMovableArray(null, 0);
+ assertTrue(false);
+ } catch (NullPointerException expected) {
+ }
+
+ // Can't create arrays of void.
+ try {
+ Object array = VMRuntime.getRuntime().newNonMovableArray(void.class, 0);
+ assertTrue(false);
+ } catch (NoClassDefFoundError expected) {
+ }
+
+ int maxLengthForLoop = 16 * 1024;
+ int step = 67;
+ doTestNewNonMovableArray(boolean.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(byte.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(char.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(short.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(int.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(long.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(float.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(double.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(Object.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(Number.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(String.class, step, maxLengthForLoop);
+ doTestNewNonMovableArray(Runnable.class, step, maxLengthForLoop);
+ }
+
+ private void doTestNewUnpaddedArray(Class<?> componentType, int step, int maxLength) {
+ // Can't create negative sized arrays.
+ try {
+ Object array = VMRuntime.getRuntime().newUnpaddedArray(componentType, -1);
+ assertTrue(false);
+ } catch (NegativeArraySizeException expected) {
+ }
+
+ try {
+ Object array = VMRuntime.getRuntime().newUnpaddedArray(componentType, Integer.MIN_VALUE);
+ assertTrue(false);
+ } catch (NegativeArraySizeException expected) {
+ }
+
+ // Allocate arrays in a loop and check their properties.
+ for (int i = 0; i <= maxLength; i += step) {
+ Object array = VMRuntime.getRuntime().newUnpaddedArray(componentType, i);
+ assertTrue(array.getClass().isArray());
+ assertEquals(array.getClass().getComponentType(), componentType);
+ assertTrue(Array.getLength(array) >= i);
+ }
+ }
+
+ public void testNewUnpaddedArray() {
+ // Can't create arrays with no component type.
+ try {
+ Object array = VMRuntime.getRuntime().newUnpaddedArray(null, 0);
+ assertTrue(false);
+ } catch (NullPointerException expected) {
+ }
+
+ // Can't create arrays of void.
+ try {
+ Object array = VMRuntime.getRuntime().newUnpaddedArray(void.class, 0);
+ assertTrue(false);
+ } catch (NoClassDefFoundError expected) {
+ }
+
+ int maxLengthForLoop = 16 * 1024;
+ int step = 67;
+ doTestNewUnpaddedArray(boolean.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(byte.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(char.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(short.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(int.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(long.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(float.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(double.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(Object.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(Number.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(String.class, step, maxLengthForLoop);
+ doTestNewUnpaddedArray(Runnable.class, step, maxLengthForLoop);
+ }
+}
+
diff --git a/luni/src/test/java/libcore/android/system/OsConstantsTest.java b/luni/src/test/java/libcore/android/system/OsConstantsTest.java
new file mode 100644
index 0000000..681d68c
--- /dev/null
+++ b/luni/src/test/java/libcore/android/system/OsConstantsTest.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2014 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 android.system;
+
+import junit.framework.TestCase;
+
+public class OsConstantsTest extends TestCase {
+
+ // http://b/15602893
+ public void testBug15602893() {
+ assertTrue(OsConstants.RT_SCOPE_HOST > 0);
+ assertTrue(OsConstants.RT_SCOPE_LINK > 0);
+ assertTrue(OsConstants.RT_SCOPE_SITE > 0);
+
+ assertTrue(OsConstants.IFA_F_TENTATIVE > 0);
+ }
+}
diff --git a/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java b/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java
index 801db4b..6c7452d 100644
--- a/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java
+++ b/luni/src/test/java/libcore/icu/AlphabeticIndexTest.java
@@ -20,8 +20,7 @@ import java.util.Locale;
public class AlphabeticIndexTest extends junit.framework.TestCase {
private static AlphabeticIndex.ImmutableIndex createIndex(Locale locale) {
- return new AlphabeticIndex(locale).addLabels(Locale.US)
- .getImmutableIndex();
+ return new AlphabeticIndex(locale).addLabels(Locale.US).getImmutableIndex();
}
private static void assertHasLabel(AlphabeticIndex.ImmutableIndex ii, String string, String expectedLabel) {
@@ -51,8 +50,10 @@ public class AlphabeticIndexTest extends junit.framework.TestCase {
// Kanji (sorts to inflow section)
assertHasLabel(ja, "\u65e5", "");
+
// http://bugs.icu-project.org/trac/ticket/10423 / http://b/10809397
assertHasLabel(ja, "\u95c7", "");
+ assertHasLabel(ja, "\u308f", "ã‚");
// English
assertHasLabel(ja, "Smith", "S");
@@ -106,12 +107,13 @@ public class AlphabeticIndexTest extends junit.framework.TestCase {
}
public void test_de() throws Exception {
- // German: [A-S,Sch,St,T-Z] (no ß or umlauted characters in standard alphabet)
+ // German: [A-Z] (no ß or umlauted characters in standard alphabet)
AlphabeticIndex.ImmutableIndex de = createIndex(Locale.GERMAN);
assertHasLabel(de, "ßind", "S");
+ // We no longer split out "S", "Sch", and "St".
assertHasLabel(de, "Sacher", "S");
- assertHasLabel(de, "Schiller", "Sch");
- assertHasLabel(de, "Steiff", "St");
+ assertHasLabel(de, "Schiller", "S");
+ assertHasLabel(de, "Steiff", "S");
}
public void test_th() throws Exception {
@@ -138,14 +140,19 @@ public class AlphabeticIndexTest extends junit.framework.TestCase {
public void test_zh_CN() throws Exception {
// Simplified Chinese (default collator Pinyin): [A-Z]
- // Shen/Chen (simplified): should be, usually, 'S' for name collator and 'C' for apps/other
AlphabeticIndex.ImmutableIndex zh_CN = createIndex(new Locale("zh", "CN"));
// Jia/Gu: should be, usually, 'J' for name collator and 'G' for apps/other
assertHasLabel(zh_CN, "\u8d3e", "J");
- // Shen/Chen
- assertHasLabel(zh_CN, "\u6c88", "C"); // icu4c 50 does not specialize for names.
+ // Shen/Chen (simplified): should usually be 'S' for names and 'C' for apps/other.
+ // icu4c does not specialize for names and defaults to 'C'.
+ // Some OEMs prefer to default to 'S'.
+ // We allow either to pass CTS since neither choice is right all the time.
+ // assertHasLabel(zh_CN, "\u6c88", "C");
+ String shenChenLabel = zh_CN.getBucketLabel(zh_CN.getBucketIndex("\u6c88"));
+ assertTrue(shenChenLabel.equals("C") || shenChenLabel.equals("S"));
+
// Shen/Chen (traditional)
assertHasLabel(zh_CN, "\u700b", "S");
}
diff --git a/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java b/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java
index c8cf572..bac8138 100644
--- a/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java
+++ b/luni/src/test/java/libcore/icu/DateIntervalFormatTest.java
@@ -16,13 +16,9 @@
package libcore.icu;
-import java.util.Arrays;
-import java.util.Locale;
-
import java.util.Calendar;
-import java.util.Date;
+import java.util.Locale;
import java.util.TimeZone;
-
import static libcore.icu.DateIntervalFormat.*;
public class DateIntervalFormatTest extends junit.framework.TestCase {
@@ -42,6 +38,7 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
c.set(Calendar.HOUR_OF_DAY, 3);
c.set(Calendar.MINUTE, 30);
c.set(Calendar.SECOND, 15);
+ c.set(Calendar.MILLISECOND, 0);
long timeWithCurrentYear = c.getTimeInMillis();
c.set(Calendar.YEAR, 2009);
@@ -89,26 +86,26 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
assertEquals("19.01.2009 - 09.02.2012", formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
assertEquals("1/19/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + HOUR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 22/1/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 22/4/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 9/2/2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
+ assertEquals("19/1/2009–22/1/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
+ assertEquals("19/1/2009–22/4/2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
+ assertEquals("19/1/2009–9/2/2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
assertEquals("19/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + HOUR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 22/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 22/4/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 9/2/2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
+ assertEquals("19/1/2009–22/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
+ assertEquals("19/1/2009–22/4/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
+ assertEquals("19/1/2009–9/2/2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
// These are some random other test cases I came up with.
- assertEquals("January 19–22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, 0));
- assertEquals("Jan 19–22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("January 19 – 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, 0));
+ assertEquals("Jan 19 – 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
assertEquals("Mon, Jan 19 – Thu, Jan 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
assertEquals("Monday, January 19 – Thursday, January 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
assertEquals("January 19 – April 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, 0));
assertEquals("Jan 19 – Apr 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
assertEquals("Mon, Jan 19 – Wed, Apr 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("January–April 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
+ assertEquals("January – April 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
assertEquals("Jan 19, 2009 – Feb 9, 2012", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
assertEquals("Jan 2009 – Feb 2012", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
@@ -135,36 +132,36 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
// The same tests but for es_US.
assertEquals("19–22 enero 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, 0));
- assertEquals("19–22 ene 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun 19 ene – jue 22 ene 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("lunes 19 enero – jueves 22 enero 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
+ assertEquals("19–22 ene. 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("lun., 19 ene.–jue., 22 ene. de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
+ assertEquals("lunes, 19 enero–jueves, 22 enero de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
- assertEquals("19 enero – 22 abril 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, 0));
- assertEquals("19 ene – 22 abr 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun 19 ene – mié 22 abr 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("enero–abril 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
+ assertEquals("19 enero–22 abril de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, 0));
+ assertEquals("19 ene.–22 abr. de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("lun., 19 ene.–mié., 22 abr. de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
+ assertEquals("enero–abril de 2009", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
- assertEquals("19 ene 2009 – 9 feb 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("ene 2009 – feb 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
- assertEquals("19 enero 2009 – 9 febrero 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, 0));
- assertEquals("lunes 19 enero 2009 – jueves 9 febrero 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
+ assertEquals("19 ene. de 2009–9 feb. de 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("ene. 2009–feb. 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
+ assertEquals("19 enero de 2009–9 febrero de 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, 0));
+ assertEquals("lunes, 19 enero de 2009–jueves, 9 febrero de 2012", formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
// The same tests but for es_ES.
assertEquals("19–22 enero 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, 0));
- assertEquals("19–22 ene 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun 19 ene – jue 22 ene 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("lunes 19 enero – jueves 22 enero 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
-
- assertEquals("19 enero – 22 abril 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, 0));
- assertEquals("19 ene – 22 abr 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun 19 ene – mié 22 abr 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("enero–abril 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
-
- assertEquals("19 ene 2009 – 9 feb 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("ene 2009 – feb 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
- assertEquals("19 enero 2009 – 9 febrero 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, 0));
- assertEquals("lunes 19 enero 2009 – jueves 9 febrero 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
+ assertEquals("19–22 ene. 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("lun., 19 ene.–jue., 22 ene. de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
+ assertEquals("lunes, 19 enero–jueves, 22 enero de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
+
+ assertEquals("19 enero–22 abril de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, 0));
+ assertEquals("19 ene.–22 abr. de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("lun., 19 ene.–mié., 22 abr. de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
+ assertEquals("enero–abril de 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
+
+ assertEquals("19 ene. de 2009–9 feb. de 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("ene. 2009–feb. 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
+ assertEquals("19 enero de 2009–9 febrero de 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, 0));
+ assertEquals("lunes, 19 enero de 2009–jueves, 9 febrero de 2012", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
}
// http://b/8862241 - we should be able to format dates past 2038.
@@ -173,6 +170,7 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
Locale l = Locale.US;
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar c = Calendar.getInstance(tz, l);
+ c.clear();
c.set(2042, Calendar.JANUARY, 19, 3, 30);
long jan_19_2042 = c.getTimeInMillis();
c.set(2046, Calendar.OCTOBER, 4, 3, 30);
@@ -221,11 +219,11 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
assertEquals("4 PM", formatDateRange(l, utc, teaTime, teaTime, abbr12));
// Abbreviated on-the-hour ranges.
- assertEquals("00:00–16:00", formatDateRange(l, utc, midnight, teaTime, abbr24));
+ assertEquals("00:00 – 16:00", formatDateRange(l, utc, midnight, teaTime, abbr24));
assertEquals("12 AM – 4 PM", formatDateRange(l, utc, midnight, teaTime, abbr12));
// Abbreviated mixed ranges.
- assertEquals("00:00–16:01", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr24));
+ assertEquals("00:00 – 16:01", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr24));
assertEquals("12:00 AM – 4:01 PM", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr12));
}
@@ -261,10 +259,49 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE;
- assertEquals("January 1, 1970, 22:00–00:00", formatDateRange(l, utc, 22 * HOUR, 24 * HOUR, flags));
+ assertEquals("January 1, 1970, 22:00 – 00:00", formatDateRange(l, utc, 22 * HOUR, 24 * HOUR, flags));
assertEquals("January 1, 1970, 22:00 – January 2, 1970, 00:30", formatDateRange(l, utc, 22 * HOUR, 24 * HOUR + 30 * MINUTE, flags));
}
+ // The fix for http://b/10560853 didn't work except for the day around the epoch, which was
+ // all the unit test checked!
+ public void test_single_day_events_later_than_epoch() throws Exception {
+ Locale l = Locale.US;
+ TimeZone utc = TimeZone.getTimeZone("UTC");
+
+ int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE;
+
+ Calendar c = Calendar.getInstance(utc, l);
+ c.clear();
+ c.set(1980, Calendar.JANUARY, 1, 0, 0);
+ long jan_1_1980 = c.getTimeInMillis();
+ assertEquals("January 1, 1980, 22:00 – 00:00",
+ formatDateRange(l, utc, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR, flags));
+ assertEquals("January 1, 1980, 22:00 – January 2, 1980, 00:30",
+ formatDateRange(l, utc, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR + 30 * MINUTE, flags));
+ }
+
+ // The fix for http://b/10560853 didn't work except for UTC, which was
+ // all the unit test checked!
+ public void test_single_day_events_not_in_UTC() throws Exception {
+ Locale l = Locale.US;
+ TimeZone pacific = TimeZone.getTimeZone("America/Los_Angeles");
+
+ int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE;
+
+ Calendar c = Calendar.getInstance(pacific, l);
+ c.clear();
+ c.set(1980, Calendar.JANUARY, 1, 0, 0);
+ long jan_1_1980 = c.getTimeInMillis();
+ assertEquals("January 1, 1980, 22:00 – 00:00",
+ formatDateRange(l, pacific, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR, flags));
+
+ c.set(1980, Calendar.JULY, 1, 0, 0);
+ long jul_1_1980 = c.getTimeInMillis();
+ assertEquals("July 1, 1980, 22:00 – 00:00",
+ formatDateRange(l, pacific, jul_1_1980 + 22 * HOUR, jul_1_1980 + 24 * HOUR, flags));
+ }
+
// http://b/10209343 - even if the caller didn't explicitly ask us to include the year,
// we should do so for years other than the current year.
public void test10209343_when_not_this_year() {
@@ -347,6 +384,7 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
public void test12004664() throws Exception {
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar c = Calendar.getInstance(utc, Locale.US);
+ c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.FEBRUARY);
c.set(Calendar.DAY_OF_MONTH, 10);
@@ -361,9 +399,9 @@ public class DateIntervalFormatTest extends junit.framework.TestCase {
// the Gregorian calendar, we want to deliberately force icu4c to agree, otherwise we'd have
// a mix of calendars throughout an app's UI depending on whether Java or native code formatted
// the date.
- //assertEquals("یکشنبه Û²Û± بهمن Û±Û³ÛµÛ¸ Ù‡â€.Ø´.", formatDateRange(new Locale("fa"), utc, thisYear, thisYear, flags));
- //assertEquals("AP ۱۳۵۸ سلواغه ۲۱, یکشنبه", formatDateRange(new Locale("ps"), utc, thisYear, thisYear, flags));
- //assertEquals("วันอาทิตย์ 10 à¸à¸¸à¸¡à¸ à¸²à¸žà¸±à¸™à¸˜à¹Œ 2523", formatDateRange(new Locale("th"), utc, thisYear, thisYear, flags));
+ // assertEquals("یکشنبه Û²Û± بهمن Û±Û³ÛµÛ¸ Ù‡â€.Ø´.", formatDateRange(new Locale("fa"), utc, thisYear, thisYear, flags));
+ // assertEquals("AP ۱۳۵۸ سلواغه ۲۱, یکشنبه", formatDateRange(new Locale("ps"), utc, thisYear, thisYear, flags));
+ // assertEquals("วันอาทิตย์ 10 à¸à¸¸à¸¡à¸ à¸²à¸žà¸±à¸™à¸˜à¹Œ 2523", formatDateRange(new Locale("th"), utc, thisYear, thisYear, flags));
// For now, here are the localized Gregorian strings instead...
assertEquals("یکشنبه Û±Û° Ùوریهٔ Û±Û¹Û¸Û°", formatDateRange(new Locale("fa"), utc, thisYear, thisYear, flags));
diff --git a/luni/src/test/java/libcore/icu/ICUTest.java b/luni/src/test/java/libcore/icu/ICUTest.java
index b3d16f9..a7cc7a0 100644
--- a/luni/src/test/java/libcore/icu/ICUTest.java
+++ b/luni/src/test/java/libcore/icu/ICUTest.java
@@ -16,6 +16,8 @@
package libcore.icu;
+import java.text.BreakIterator;
+import java.text.Collator;
import java.util.Arrays;
import java.util.Locale;
@@ -42,26 +44,26 @@ public class ICUTest extends junit.framework.TestCase {
}
public void test_getBestDateTimePattern() throws Exception {
- assertEquals("d MMMM", ICU.getBestDateTimePattern("MMMMd", "ca_ES"));
- assertEquals("d 'de' MMMM", ICU.getBestDateTimePattern("MMMMd", "es_ES"));
- assertEquals("d. MMMM", ICU.getBestDateTimePattern("MMMMd", "de_CH"));
- assertEquals("MMMM d", ICU.getBestDateTimePattern("MMMMd", "en_US"));
- assertEquals("d LLLL", ICU.getBestDateTimePattern("MMMMd", "fa_IR"));
- assertEquals("M月d日", ICU.getBestDateTimePattern("MMMMd", "ja_JP"));
+ assertEquals("d MMMM", ICU.getBestDateTimePattern("MMMMd", new Locale("ca", "ES")));
+ assertEquals("d 'de' MMMM", ICU.getBestDateTimePattern("MMMMd", new Locale("es", "ES")));
+ assertEquals("d. MMMM", ICU.getBestDateTimePattern("MMMMd", new Locale("de", "CH")));
+ assertEquals("MMMM d", ICU.getBestDateTimePattern("MMMMd", new Locale("en", "US")));
+ assertEquals("d LLLL", ICU.getBestDateTimePattern("MMMMd", new Locale("fa", "IR")));
+ assertEquals("M月d日", ICU.getBestDateTimePattern("MMMMd", new Locale("ja", "JP")));
}
public void test_localeFromString() throws Exception {
// localeFromString is pretty lenient. Some of these can't be round-tripped
// through Locale.toString.
- assertEquals(Locale.ENGLISH, ICU.localeFromString("en"));
- assertEquals(Locale.ENGLISH, ICU.localeFromString("en_"));
- assertEquals(Locale.ENGLISH, ICU.localeFromString("en__"));
- assertEquals(Locale.US, ICU.localeFromString("en_US"));
- assertEquals(Locale.US, ICU.localeFromString("en_US_"));
- assertEquals(new Locale("", "US", ""), ICU.localeFromString("_US"));
- assertEquals(new Locale("", "US", ""), ICU.localeFromString("_US_"));
- assertEquals(new Locale("", "", "POSIX"), ICU.localeFromString("__POSIX"));
- assertEquals(new Locale("aa", "BB", "CC"), ICU.localeFromString("aa_BB_CC"));
+ assertEquals(Locale.ENGLISH, ICU.localeFromIcuLocaleId("en"));
+ assertEquals(Locale.ENGLISH, ICU.localeFromIcuLocaleId("en_"));
+ assertEquals(Locale.ENGLISH, ICU.localeFromIcuLocaleId("en__"));
+ assertEquals(Locale.US, ICU.localeFromIcuLocaleId("en_US"));
+ assertEquals(Locale.US, ICU.localeFromIcuLocaleId("en_US_"));
+ assertEquals(new Locale("", "US", ""), ICU.localeFromIcuLocaleId("_US"));
+ assertEquals(new Locale("", "US", ""), ICU.localeFromIcuLocaleId("_US_"));
+ assertEquals(new Locale("", "", "POSIX"), ICU.localeFromIcuLocaleId("__POSIX"));
+ assertEquals(new Locale("aa", "BB", "CC"), ICU.localeFromIcuLocaleId("aa_BB_CC"));
}
public void test_getScript_addLikelySubtags() throws Exception {
@@ -72,8 +74,16 @@ public class ICUTest extends junit.framework.TestCase {
assertEquals("Hebr", ICU.getScript(ICU.addLikelySubtags("iw_IL")));
}
+ public void test_addLikelySubtags() throws Exception {
+ assertEquals("Latn", ICU.addLikelySubtags(new Locale("en", "US")).getScript());
+ assertEquals("Hebr", ICU.addLikelySubtags(new Locale("he")).getScript());
+ assertEquals("Hebr", ICU.addLikelySubtags(new Locale("he", "IL")).getScript());
+ assertEquals("Hebr", ICU.addLikelySubtags(new Locale("iw")).getScript());
+ assertEquals("Hebr", ICU.addLikelySubtags(new Locale("iw", "IL")).getScript());
+ }
+
private String best(Locale l, String skeleton) {
- return ICU.getBestDateTimePattern(skeleton, l.toString());
+ return ICU.getBestDateTimePattern(skeleton, l);
}
public void test_getDateFormatOrder() throws Exception {
@@ -123,4 +133,124 @@ public class ICUTest extends junit.framework.TestCase {
} catch (IllegalArgumentException expected) {
}
}
+
+ public void testScriptsPassedToIcu() throws Exception {
+ Locale sr_Cyrl_BA = Locale.forLanguageTag("sr-Cyrl-BA");
+ Locale sr_Cyrl_ME = Locale.forLanguageTag("sr-Cyrl-ME");
+ Locale sr_Latn_BA = Locale.forLanguageTag("sr-Latn-BA");
+ Locale sr_Latn_ME = Locale.forLanguageTag("sr-Latn-ME");
+
+ assertEquals("sr_BA_#Cyrl", sr_Cyrl_BA.toString());
+ assertEquals("Cyrl", sr_Cyrl_BA.getScript());
+
+ assertEquals("sr_ME_#Cyrl", sr_Cyrl_ME.toString());
+ assertEquals("Cyrl", sr_Cyrl_ME.getScript());
+
+ assertEquals("sr_BA_#Latn", sr_Latn_BA.toString());
+ assertEquals("Latn", sr_Latn_BA.getScript());
+
+ assertEquals("sr_ME_#Latn", sr_Latn_ME.toString());
+ assertEquals("Latn", sr_Latn_ME.getScript());
+
+ assertEquals("СрпÑки", sr_Cyrl_BA.getDisplayLanguage(sr_Cyrl_BA));
+ assertEquals("БоÑна и Херцеговина", sr_Cyrl_BA.getDisplayCountry(sr_Cyrl_BA));
+ assertEquals("Ћирилица", sr_Cyrl_BA.getDisplayScript(sr_Cyrl_BA));
+ assertEquals("", sr_Cyrl_BA.getDisplayVariant(sr_Cyrl_BA));
+
+ assertEquals("СрпÑки", sr_Cyrl_ME.getDisplayLanguage(sr_Cyrl_ME));
+ assertEquals("Црна Гора", sr_Cyrl_ME.getDisplayCountry(sr_Cyrl_ME));
+ assertEquals("Ћирилица", sr_Cyrl_ME.getDisplayScript(sr_Cyrl_ME));
+ assertEquals("", sr_Cyrl_ME.getDisplayVariant(sr_Cyrl_ME));
+
+ assertEquals("Srpski", sr_Latn_BA.getDisplayLanguage(sr_Latn_BA));
+ assertEquals("Bosna i Hercegovina", sr_Latn_BA.getDisplayCountry(sr_Latn_BA));
+ assertEquals("Latinica", sr_Latn_BA.getDisplayScript(sr_Latn_BA));
+ assertEquals("", sr_Latn_BA.getDisplayVariant(sr_Latn_BA));
+
+ assertEquals("Srpski", sr_Latn_ME.getDisplayLanguage(sr_Latn_ME));
+ assertEquals("Crna Gora", sr_Latn_ME.getDisplayCountry(sr_Latn_ME));
+ assertEquals("Latinica", sr_Latn_ME.getDisplayScript(sr_Latn_ME));
+ assertEquals("", sr_Latn_ME.getDisplayVariant(sr_Latn_ME));
+
+ assertEquals("BIH", sr_Cyrl_BA.getISO3Country());
+ assertEquals("srp", sr_Cyrl_BA.getISO3Language());
+ assertEquals("MNE", sr_Cyrl_ME.getISO3Country());
+ assertEquals("srp", sr_Cyrl_ME.getISO3Language());
+ assertEquals("BIH", sr_Latn_BA.getISO3Country());
+ assertEquals("srp", sr_Latn_BA.getISO3Language());
+ assertEquals("MNE", sr_Latn_ME.getISO3Country());
+ assertEquals("srp", sr_Latn_ME.getISO3Language());
+
+ BreakIterator.getCharacterInstance(sr_Cyrl_BA);
+ BreakIterator.getCharacterInstance(sr_Cyrl_ME);
+ BreakIterator.getCharacterInstance(sr_Latn_BA);
+ BreakIterator.getCharacterInstance(sr_Latn_ME);
+
+ BreakIterator.getLineInstance(sr_Cyrl_BA);
+ BreakIterator.getLineInstance(sr_Cyrl_ME);
+ BreakIterator.getLineInstance(sr_Latn_BA);
+ BreakIterator.getLineInstance(sr_Latn_ME);
+
+ BreakIterator.getSentenceInstance(sr_Cyrl_BA);
+ BreakIterator.getSentenceInstance(sr_Cyrl_ME);
+ BreakIterator.getSentenceInstance(sr_Latn_BA);
+ BreakIterator.getSentenceInstance(sr_Latn_ME);
+
+ BreakIterator.getWordInstance(sr_Cyrl_BA);
+ BreakIterator.getWordInstance(sr_Cyrl_ME);
+ BreakIterator.getWordInstance(sr_Latn_BA);
+ BreakIterator.getWordInstance(sr_Latn_ME);
+
+ Collator.getInstance(sr_Cyrl_BA);
+ Collator.getInstance(sr_Cyrl_ME);
+ Collator.getInstance(sr_Latn_BA);
+ Collator.getInstance(sr_Latn_ME);
+
+ Locale l = Locale.forLanguageTag("de-u-co-phonebk-kf-upper-kn");
+ assertEquals("de__#u-co-phonebk-kf-upper-kn", l.toString());
+ assertEquals("de-u-co-phonebk-kf-upper-kn", l.toLanguageTag());
+
+ Collator c = Collator.getInstance(l);
+ assertTrue(c.compare("2", "11") < 0);
+ assertTrue(c.compare("11", "ae") < 0);
+ assertTrue(c.compare("ae", "Ä") < 0);
+ assertTrue(c.compare("Ä", "ä") < 0);
+ assertTrue(c.compare("ä", "AF") < 0);
+ assertTrue(c.compare("AF", "af") < 0);
+ }
+
+ // Test for the behavior of currency symbol lookup when an unrecognized locale has been set as the
+ // default.
+ public void testIcuDefaultAffectsCurrencySymbol() {
+ // A locale that is not going to be recognized by ICU and should fallback to "root" for the
+ // currency symbol.
+ final Locale unrecognizedLocale = new Locale("xy", "KR");
+
+ // A known locale with a relatively stable representation for its currency symbol.
+ final Locale enUsLocale = new Locale("en", "US");
+ final String usDollar = "USD";
+
+ String initialDefaultLocale = ICU.getDefaultLocale();
+ try {
+ // Confirm the "$" symbol for USD in en-US.
+ assertEquals("$", ICU.getCurrencySymbol(enUsLocale, usDollar));
+
+ // Set the default so this will be used as fallback for the unrecognized locale symbol lookup.
+ ICU.setDefaultLocale(enUsLocale.toLanguageTag());
+
+ // Demonstrate the USD symbol is reported as "$" for the unrecognized locale (which is using
+ // the default).
+ assertEquals("$", ICU.getCurrencySymbol(unrecognizedLocale, usDollar));
+
+ // Change the default.
+ ICU.setDefaultLocale(unrecognizedLocale.toLanguageTag());
+
+ String currencySymbolAfterDefaultChange = ICU.getCurrencySymbol(unrecognizedLocale, usDollar);
+ // "$US" is the value from root. With an unrecognized locale argument, and an unrecognized
+ // locale as the default, ICU has returns the value in root.
+ assertEquals("US$", currencySymbolAfterDefaultChange);
+ } finally {
+ ICU.setDefaultLocale(initialDefaultLocale);
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/icu/LocaleDataTest.java b/luni/src/test/java/libcore/icu/LocaleDataTest.java
index 27eda86..0a83c53 100644
--- a/luni/src/test/java/libcore/icu/LocaleDataTest.java
+++ b/luni/src/test/java/libcore/icu/LocaleDataTest.java
@@ -19,104 +19,116 @@ package libcore.icu;
import java.util.Locale;
public class LocaleDataTest extends junit.framework.TestCase {
- public void testAll() throws Exception {
- // Test that we can get the locale data for all known locales.
- for (Locale l : Locale.getAvailableLocales()) {
- LocaleData d = LocaleData.get(l);
- // System.err.format("%10s %10s %10s\n", l, d.timeFormat12, d.timeFormat24);
- }
- }
-
- public void test_en_US() throws Exception {
- LocaleData l = LocaleData.get(Locale.US);
- assertEquals("AM", l.amPm[0]);
- assertEquals("BC", l.eras[0]);
-
- assertEquals("January", l.longMonthNames[0]);
- assertEquals("Jan", l.shortMonthNames[0]);
- assertEquals("J", l.tinyMonthNames[0]);
-
- assertEquals("January", l.longStandAloneMonthNames[0]);
- assertEquals("Jan", l.shortStandAloneMonthNames[0]);
- assertEquals("J", l.tinyStandAloneMonthNames[0]);
-
- assertEquals("Sunday", l.longWeekdayNames[1]);
- assertEquals("Sun", l.shortWeekdayNames[1]);
- assertEquals("S", l.tinyWeekdayNames[1]);
-
- assertEquals("Sunday", l.longStandAloneWeekdayNames[1]);
- assertEquals("Sun", l.shortStandAloneWeekdayNames[1]);
- assertEquals("S", l.tinyStandAloneWeekdayNames[1]);
-
- assertEquals("Yesterday", l.yesterday);
- assertEquals("Today", l.today);
- assertEquals("Tomorrow", l.tomorrow);
- }
-
- public void test_de_DE() throws Exception {
- LocaleData l = LocaleData.get(new Locale("de", "DE"));
-
- assertEquals("Gestern", l.yesterday);
- assertEquals("Heute", l.today);
- assertEquals("Morgen", l.tomorrow);
- }
-
- public void test_cs_CZ() throws Exception {
- LocaleData l = LocaleData.get(new Locale("cs", "CZ"));
-
- assertEquals("ledna", l.longMonthNames[0]);
- assertEquals("led", l.shortMonthNames[0]);
- assertEquals("1", l.tinyMonthNames[0]);
-
- assertEquals("leden", l.longStandAloneMonthNames[0]);
- assertEquals("led", l.shortStandAloneMonthNames[0]);
- assertEquals("l", l.tinyStandAloneMonthNames[0]);
- }
-
- public void test_ru_RU() throws Exception {
- LocaleData l = LocaleData.get(new Locale("ru", "RU"));
-
- assertEquals("воÑкреÑенье", l.longWeekdayNames[1]);
- assertEquals("вÑ", l.shortWeekdayNames[1]);
- assertEquals("вÑ", l.tinyWeekdayNames[1]);
-
- // Russian stand-alone weekday names get an initial capital.
- assertEquals("ВоÑкреÑенье", l.longStandAloneWeekdayNames[1]);
- assertEquals("Ð’Ñ", l.shortStandAloneWeekdayNames[1]);
- assertEquals("Ð’", l.tinyStandAloneWeekdayNames[1]);
- }
-
- // http://code.google.com/p/android/issues/detail?id=38844
- public void testDecimalFormatSymbols_es() throws Exception {
- LocaleData es = LocaleData.get(new Locale("es"));
- assertEquals(',', es.decimalSeparator);
- assertEquals('.', es.groupingSeparator);
-
- LocaleData es_419 = LocaleData.get(new Locale("es", "419"));
- assertEquals('.', es_419.decimalSeparator);
- assertEquals(',', es_419.groupingSeparator);
-
- LocaleData es_US = LocaleData.get(new Locale("es", "US"));
- assertEquals('.', es_US.decimalSeparator);
- assertEquals(',', es_US.groupingSeparator);
-
- LocaleData es_MX = LocaleData.get(new Locale("es", "MX"));
- assertEquals('.', es_MX.decimalSeparator);
- assertEquals(',', es_MX.groupingSeparator);
-
- LocaleData es_AR = LocaleData.get(new Locale("es", "AR"));
- assertEquals(',', es_AR.decimalSeparator);
- assertEquals('.', es_AR.groupingSeparator);
- }
-
- // http://b/7924970
- public void testTimeFormat12And24() throws Exception {
- LocaleData en_US = LocaleData.get(Locale.US);
- assertEquals("h:mm a", en_US.timeFormat12);
- assertEquals("HH:mm", en_US.timeFormat24);
-
- LocaleData ja_JP = LocaleData.get(Locale.JAPAN);
- assertEquals("aK:mm", ja_JP.timeFormat12);
- assertEquals("H:mm", ja_JP.timeFormat24);
+ public void testAll() throws Exception {
+ // Test that we can get the locale data for all known locales.
+ for (Locale l : Locale.getAvailableLocales()) {
+ LocaleData d = LocaleData.get(l);
+ // System.err.format("%20s %s %s %s\n", l, d.yesterday, d.today, d.tomorrow);
+ // System.err.format("%20s %10s %10s\n", l, d.timeFormat12, d.timeFormat24);
}
+ }
+
+ public void test_en_US() throws Exception {
+ LocaleData l = LocaleData.get(Locale.US);
+ assertEquals("AM", l.amPm[0]);
+ assertEquals("a", l.narrowAm);
+
+ assertEquals("BC", l.eras[0]);
+
+ assertEquals("January", l.longMonthNames[0]);
+ assertEquals("Jan", l.shortMonthNames[0]);
+ assertEquals("J", l.tinyMonthNames[0]);
+
+ assertEquals("January", l.longStandAloneMonthNames[0]);
+ assertEquals("Jan", l.shortStandAloneMonthNames[0]);
+ assertEquals("J", l.tinyStandAloneMonthNames[0]);
+
+ assertEquals("Sunday", l.longWeekdayNames[1]);
+ assertEquals("Sun", l.shortWeekdayNames[1]);
+ assertEquals("S", l.tinyWeekdayNames[1]);
+
+ assertEquals("Sunday", l.longStandAloneWeekdayNames[1]);
+ assertEquals("Sun", l.shortStandAloneWeekdayNames[1]);
+ assertEquals("S", l.tinyStandAloneWeekdayNames[1]);
+
+ assertEquals("Yesterday", l.yesterday);
+ assertEquals("Today", l.today);
+ assertEquals("Tomorrow", l.tomorrow);
+ }
+
+ public void test_de_DE() throws Exception {
+ LocaleData l = LocaleData.get(new Locale("de", "DE"));
+
+ assertEquals("Gestern", l.yesterday);
+ assertEquals("Heute", l.today);
+ assertEquals("Morgen", l.tomorrow);
+ }
+
+ public void test_cs_CZ() throws Exception {
+ LocaleData l = LocaleData.get(new Locale("cs", "CZ"));
+
+ assertEquals("ledna", l.longMonthNames[0]);
+ assertEquals("led", l.shortMonthNames[0]);
+ assertEquals("1", l.tinyMonthNames[0]);
+
+ assertEquals("leden", l.longStandAloneMonthNames[0]);
+ assertEquals("led", l.shortStandAloneMonthNames[0]);
+ assertEquals("l", l.tinyStandAloneMonthNames[0]);
+ }
+
+ public void test_ko_KR() throws Exception {
+ LocaleData l = LocaleData.get(new Locale("ko", "KR"));
+
+ // Ensure the fix for http://b/14493853 doesn't mangle Hangul.
+ assertEquals("어제", l.yesterday);
+ assertEquals("오늘", l.today);
+ assertEquals("ë‚´ì¼", l.tomorrow);
+ }
+
+ public void test_ru_RU() throws Exception {
+ LocaleData l = LocaleData.get(new Locale("ru", "RU"));
+
+ assertEquals("воÑкреÑенье", l.longWeekdayNames[1]);
+ assertEquals("вÑ", l.shortWeekdayNames[1]);
+ assertEquals("вÑ", l.tinyWeekdayNames[1]);
+
+ // Russian stand-alone weekday names get an initial capital.
+ assertEquals("ВоÑкреÑенье", l.longStandAloneWeekdayNames[1]);
+ assertEquals("Ð’Ñ", l.shortStandAloneWeekdayNames[1]);
+ assertEquals("Ð’", l.tinyStandAloneWeekdayNames[1]);
+ }
+
+ // http://code.google.com/p/android/issues/detail?id=38844
+ public void testDecimalFormatSymbols_es() throws Exception {
+ LocaleData es = LocaleData.get(new Locale("es"));
+ assertEquals(',', es.decimalSeparator);
+ assertEquals('.', es.groupingSeparator);
+
+ LocaleData es_419 = LocaleData.get(new Locale("es", "419"));
+ assertEquals('.', es_419.decimalSeparator);
+ assertEquals(',', es_419.groupingSeparator);
+
+ LocaleData es_US = LocaleData.get(new Locale("es", "US"));
+ assertEquals('.', es_US.decimalSeparator);
+ assertEquals(',', es_US.groupingSeparator);
+
+ LocaleData es_MX = LocaleData.get(new Locale("es", "MX"));
+ assertEquals('.', es_MX.decimalSeparator);
+ assertEquals(',', es_MX.groupingSeparator);
+
+ LocaleData es_AR = LocaleData.get(new Locale("es", "AR"));
+ assertEquals(',', es_AR.decimalSeparator);
+ assertEquals('.', es_AR.groupingSeparator);
+ }
+
+ // http://b/7924970
+ public void testTimeFormat12And24() throws Exception {
+ LocaleData en_US = LocaleData.get(Locale.US);
+ assertEquals("h:mm a", en_US.timeFormat12);
+ assertEquals("HH:mm", en_US.timeFormat24);
+
+ LocaleData ja_JP = LocaleData.get(Locale.JAPAN);
+ assertEquals("aK:mm", ja_JP.timeFormat12);
+ assertEquals("H:mm", ja_JP.timeFormat24);
+ }
}
diff --git a/luni/src/test/java/libcore/icu/NativePluralRulesTest.java b/luni/src/test/java/libcore/icu/NativePluralRulesTest.java
index 73699ff..703a94a 100644
--- a/luni/src/test/java/libcore/icu/NativePluralRulesTest.java
+++ b/luni/src/test/java/libcore/icu/NativePluralRulesTest.java
@@ -21,7 +21,6 @@ import java.util.Locale;
public class NativePluralRulesTest extends junit.framework.TestCase {
public void testEnglish() throws Exception {
NativePluralRules npr = NativePluralRules.forLocale(new Locale("en", "US"));
- assertEquals(NativePluralRules.OTHER, npr.quantityForInt(-1));
assertEquals(NativePluralRules.OTHER, npr.quantityForInt(0));
assertEquals(NativePluralRules.ONE, npr.quantityForInt(1));
assertEquals(NativePluralRules.OTHER, npr.quantityForInt(2));
@@ -29,7 +28,6 @@ public class NativePluralRulesTest extends junit.framework.TestCase {
public void testCzech() throws Exception {
NativePluralRules npr = NativePluralRules.forLocale(new Locale("cs", "CZ"));
- assertEquals(NativePluralRules.OTHER, npr.quantityForInt(-1));
assertEquals(NativePluralRules.OTHER, npr.quantityForInt(0));
assertEquals(NativePluralRules.ONE, npr.quantityForInt(1));
assertEquals(NativePluralRules.FEW, npr.quantityForInt(2));
@@ -40,7 +38,6 @@ public class NativePluralRulesTest extends junit.framework.TestCase {
public void testArabic() throws Exception {
NativePluralRules npr = NativePluralRules.forLocale(new Locale("ar"));
- assertEquals(NativePluralRules.OTHER, npr.quantityForInt(-1));
assertEquals(NativePluralRules.ZERO, npr.quantityForInt(0));
assertEquals(NativePluralRules.ONE, npr.quantityForInt(1));
assertEquals(NativePluralRules.TWO, npr.quantityForInt(2));
@@ -62,6 +59,7 @@ public class NativePluralRulesTest extends junit.framework.TestCase {
assertEquals(NativePluralRules.ONE, he.quantityForInt(1));
assertEquals(NativePluralRules.TWO, he.quantityForInt(2));
assertEquals(NativePluralRules.OTHER, he.quantityForInt(3));
- assertEquals(NativePluralRules.MANY, he.quantityForInt(10));
+ assertEquals(NativePluralRules.OTHER, he.quantityForInt(10));
}
}
+
diff --git a/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java b/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java
index c2f8312..57943b0 100644
--- a/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java
+++ b/luni/src/test/java/libcore/icu/TimeZoneNamesTest.java
@@ -59,4 +59,11 @@ public class TimeZoneNamesTest extends junit.framework.TestCase {
assertTrue(TimeZoneNames.forLocale(l) != null);
}
}
+
+ public void test_getExemplarLocation() throws Exception {
+ assertEquals("Moscow", TimeZoneNames.getExemplarLocation("en_US", "Europe/Moscow"));
+ assertEquals("Moskau", TimeZoneNames.getExemplarLocation("de_DE", "Europe/Moscow"));
+ assertEquals("Seoul", TimeZoneNames.getExemplarLocation("en_US", "Asia/Seoul"));
+ assertEquals("서울", TimeZoneNames.getExemplarLocation("ko_KR", "Asia/Seoul"));
+ }
}
diff --git a/luni/src/test/java/libcore/io/MemoryTest.java b/luni/src/test/java/libcore/io/MemoryTest.java
index 9a596fb..c817b20 100644
--- a/luni/src/test/java/libcore/io/MemoryTest.java
+++ b/luni/src/test/java/libcore/io/MemoryTest.java
@@ -32,10 +32,10 @@ public class MemoryTest extends TestCase {
int scale = SizeOf.INT;
VMRuntime runtime = VMRuntime.getRuntime();
byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1);
- int base_ptr = (int) runtime.addressOf(array);
+ long base_ptr = runtime.addressOf(array);
for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) {
- int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
+ long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
Arrays.fill(array, (byte) 0);
// Regular copy.
@@ -57,7 +57,7 @@ public class MemoryTest extends TestCase {
}
}
- private void assertIntsEqual(int[] expectedValues, int ptr, boolean swap) {
+ private void assertIntsEqual(int[] expectedValues, long ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
assertEquals(expectedValues[i], Memory.peekInt(ptr + SizeOf.INT * i, swap));
}
@@ -73,10 +73,10 @@ public class MemoryTest extends TestCase {
int scale = SizeOf.LONG;
VMRuntime runtime = VMRuntime.getRuntime();
byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1);
- int base_ptr = (int) runtime.addressOf(array);
+ long base_ptr = runtime.addressOf(array);
for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) {
- int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
+ long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
Arrays.fill(array, (byte) 0);
// Regular copy.
@@ -98,7 +98,7 @@ public class MemoryTest extends TestCase {
}
}
- private void assertLongsEqual(long[] expectedValues, int ptr, boolean swap) {
+ private void assertLongsEqual(long[] expectedValues, long ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
assertEquals(expectedValues[i], Memory.peekLong(ptr + SizeOf.LONG * i, swap));
}
@@ -111,10 +111,10 @@ public class MemoryTest extends TestCase {
int scale = SizeOf.SHORT;
VMRuntime runtime = VMRuntime.getRuntime();
byte[] array = (byte[]) runtime.newNonMovableArray(byte.class, scale * values.length + 1);
- int base_ptr = (int) runtime.addressOf(array);
+ long base_ptr = runtime.addressOf(array);
for (int ptr_offset = 0; ptr_offset < 2; ++ptr_offset) {
- int ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
+ long ptr = base_ptr + ptr_offset; // To test aligned and unaligned accesses.
Arrays.fill(array, (byte) 0);
// Regular copy.
@@ -136,7 +136,7 @@ public class MemoryTest extends TestCase {
}
}
- private void assertShortsEqual(short[] expectedValues, int ptr, boolean swap) {
+ private void assertShortsEqual(short[] expectedValues, long ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
assertEquals(expectedValues[i], Memory.peekShort(ptr + SizeOf.SHORT * i, swap));
}
diff --git a/luni/src/test/java/libcore/io/OsTest.java b/luni/src/test/java/libcore/io/OsTest.java
index 624c119..cf28122 100644
--- a/luni/src/test/java/libcore/io/OsTest.java
+++ b/luni/src/test/java/libcore/io/OsTest.java
@@ -16,6 +16,7 @@
package libcore.io;
+import android.system.StructUcred;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
@@ -26,8 +27,7 @@ import java.net.ServerSocket;
import java.net.SocketAddress;
import java.util.Locale;
import junit.framework.TestCase;
-
-import static libcore.io.OsConstants.*;
+import static android.system.OsConstants.*;
public class OsTest extends TestCase {
public void testIsSocket() throws Exception {
diff --git a/luni/src/test/java/libcore/java/io/FileTest.java b/luni/src/test/java/libcore/java/io/FileTest.java
index b2391ac..b4101f9 100644
--- a/luni/src/test/java/libcore/java/io/FileTest.java
+++ b/luni/src/test/java/libcore/java/io/FileTest.java
@@ -16,11 +16,9 @@
package libcore.java.io;
-import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
-import java.io.InputStreamReader;
import java.io.IOException;
import java.util.UUID;
import libcore.io.Libcore;
@@ -62,7 +60,13 @@ public class FileTest extends junit.framework.TestCase {
assertTrue(createDeepStructure(base).exists());
}
- // readlink(2) is a special case,.
+ /*
+ * readlink(2) is a special case,.
+ *
+ * This test assumes you can create symbolic links in the temporary directory. This
+ * isn't true on Android if you're using /sdcard (which is used if this test is
+ * run using vogar). It will work in /data/data/ though.
+ */
public void test_longReadlink() throws Exception {
File base = createTemporaryDirectory();
File target = createDeepStructure(base);
@@ -144,10 +148,14 @@ public class FileTest extends junit.framework.TestCase {
new MyFile("");
}
- // http://b/3047893 - getCanonicalPath wasn't actually resolving symbolic links.
+ /*
+ * http://b/3047893 - getCanonicalPath wasn't actually resolving symbolic links.
+ *
+ * This test assumes you can create symbolic links in the temporary directory. This
+ * isn't true on Android if you're using /sdcard (which is used if this test is
+ * run using vogar). It will work in /data/data/ though.
+ */
public void test_getCanonicalPath() throws Exception {
- // This assumes you can create symbolic links in the temporary directory. This isn't
- // true on Android if you're using /sdcard. It will work in /data/local though.
File base = createTemporaryDirectory();
File target = new File(base, "target");
target.createNewFile(); // The RI won't follow a dangling symlink, which seems like a bug!
@@ -208,16 +216,13 @@ public class FileTest extends junit.framework.TestCase {
}
public void test_getAbsolutePath() throws Exception {
- String originalUserDir = System.getProperty("user.dir");
- try {
- File f = new File("poop");
- System.setProperty("user.dir", "/a");
- assertEquals("/a/poop", f.getAbsolutePath());
- System.setProperty("user.dir", "/b");
- assertEquals("/b/poop", f.getAbsolutePath());
- } finally {
- System.setProperty("user.dir", originalUserDir);
+ String userDir = System.getProperty("user.dir");
+ if (!userDir.endsWith(File.separator)) {
+ userDir = userDir + File.separator;
}
+
+ File f = new File("poop");
+ assertEquals(userDir + "poop", f.getAbsolutePath());
}
public void test_getSpace() throws Exception {
diff --git a/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java b/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java
index e5fd39f..30ae7eb 100755
--- a/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java
+++ b/luni/src/test/java/libcore/java/io/InterruptedStreamTest.java
@@ -207,7 +207,10 @@ public final class InterruptedStreamTest extends TestCase {
private static void confirmInterrupted(Thread thread) throws InterruptedException {
// validate and clear interrupted bit before join
- assertTrue(Thread.interrupted());
- thread.join();
+ try {
+ assertTrue(Thread.interrupted());
+ } finally {
+ thread.join();
+ }
}
}
diff --git a/luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java b/luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java
deleted file mode 100644
index a3ef4e4..0000000
--- a/luni/src/test/java/libcore/java/io/OldBufferedInputStreamTest.java
+++ /dev/null
@@ -1,228 +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 libcore.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-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 junit.framework.TestCase;
-import tests.support.Support_ASimpleInputStream;
-import tests.support.Support_PlatformFile;
-
-public class OldBufferedInputStreamTest extends TestCase {
-
- public String fileName;
- private BufferedInputStream is;
- private FileInputStream isFile;
- public String fileString = "Test_All_Tests\nTest_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- public void test_ConstructorLjava_io_InputStream() {
- is = new BufferedInputStream(isFile);
-
- try {
- is.read();
- } catch (Exception e) {
- fail("Test 1: Read failed on a freshly constructed buffer.");
- }
- }
-
- public void test_ConstructorLjava_io_InputStreamI() throws IOException {
- // regression test for harmony-2407
- new testBufferedInputStream(null);
- assertNotNull(testBufferedInputStream.buf);
- testBufferedInputStream.buf = null;
- new testBufferedInputStream(null, 100);
- assertNotNull(testBufferedInputStream.buf);
- }
-
- static class testBufferedInputStream extends BufferedInputStream {
- static byte[] buf;
- testBufferedInputStream(InputStream is) throws IOException {
- super(is);
- buf = super.buf;
- }
-
- testBufferedInputStream(InputStream is, int size) throws IOException {
- super(is, size);
- buf = super.buf;
- }
- }
-
- public void test_available() {
- // Test for method int java.io.BufferedInputStream.available()
- try {
- assertTrue("Returned incorrect number of available bytes", is
- .available() == fileString.length());
- } catch (IOException e) {
- fail("Exception during available test");
- }
-
- // Test that a closed stream throws an IOE for available()
- BufferedInputStream bis = new BufferedInputStream(
- new ByteArrayInputStream(new byte[] { 'h', 'e', 'l', 'l', 'o',
- ' ', 't', 'i', 'm' }));
- int available = 0;
- try {
- available = bis.available();
- bis.close();
- } catch (IOException ex) {
- fail();
- }
- assertTrue(available != 0);
-
- try {
- bis.available();
- fail("Expected test to throw IOE.");
- } catch (IOException ex) {
- // expected
- } catch (Throwable ex) {
- fail("Expected test to throw IOE not "
- + ex.getClass().getName());
- }
- }
-
- public void test_close() throws IOException {
- is.close();
-
- try {
- is.read();
- fail("Test 1: IOException expected when reading after closing " +
- "the stream.");
- } catch (IOException e) {
- // Expected.
- }
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(true);
- is = new BufferedInputStream(sis);
- try {
- is.close();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- }
-
- public void test_markI_reset() throws IOException {
- byte[] buf1 = new byte[100];
- byte[] buf2 = new byte[100];
-
- // Test 1: Check that reset fails if no mark has been set.
- try {
- is.reset();
- fail("Test 1: IOException expected if no mark has been set.");
- } catch (IOException e) {
- // Expected.
- }
-
- // Test 2: Check that mark / reset works when the mark is not invalidated.
- is.skip(10);
- is.mark(100);
- is.read(buf1, 0, buf1.length);
- is.reset();
- is.read(buf2, 0, buf2.length);
- is.reset();
- assertTrue("Test 2: Failed to mark correct position or reset failed.",
- new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length)));
-
- // Tests 3 and 4: Check that skipping less than readlimit bytes does
- // not invalidate the mark.
- is.skip(10);
- try {
- is.reset();
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException " + e.getMessage());
- }
- is.read(buf2, 0, buf2.length);
- is.reset();
- assertTrue("Test 4: Failed to mark correct position, or reset failed.",
- new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length)));
-
- // Test 8: Check that reset fails for a closed input stream.
- is.close();
- try {
- is.reset();
- fail("Test 8: IOException expected because the input stream is closed.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- public void test_read() throws IOException {
- int c = is.read();
- assertTrue("Test 1: Incorrect character read.",
- c == fileString.charAt(0));
-
- byte[] bytes = new byte[256];
- for (int i = 0; i < 256; i++) {
- bytes[i] = (byte) i;
- }
-
- BufferedInputStream in = new BufferedInputStream(
- new ByteArrayInputStream(bytes), 5);
-
- // Read more bytes than are buffered.
- for (int i = 0; i < 10; i++) {
- assertEquals("Test 2: Incorrect byte read;", bytes[i], in.read());
- }
-
- in.close();
- try {
- in.read();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- @Override
- protected void setUp() throws IOException {
- fileName = System.getProperty("user.dir");
- String separator = System.getProperty("file.separator");
- if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) {
- fileName = Support_PlatformFile.getNewPlatformFile(fileName,
- "input.tst");
- } else {
- fileName = Support_PlatformFile.getNewPlatformFile(fileName
- + separator, "input.tst");
- }
- OutputStream fos = new FileOutputStream(fileName);
- fos.write(fileString.getBytes());
- fos.close();
- isFile = new FileInputStream(fileName);
- is = new BufferedInputStream(isFile);
- }
-
- @Override
- protected void tearDown() {
- try {
- is.close();
- } catch (Exception e) {
- }
- try {
- File f = new File(fileName);
- f.delete();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java b/luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java
deleted file mode 100644
index 894849a..0000000
--- a/luni/src/test/java/libcore/java/io/OldFileInputStreamTest.java
+++ /dev/null
@@ -1,209 +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 libcore.java.io;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.channels.FileChannel;
-import junit.framework.TestCase;
-import tests.support.Support_PlatformFile;
-
-public class OldFileInputStreamTest extends TestCase {
-
- public String fileName;
- private FileInputStream is;
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- public void test_ConstructorLjava_io_File() {
- // Test for method FileInputStream(File)
- try {
- File f = new File(fileName);
- is = new FileInputStream(f);
- is.close();
- } catch (Exception e) {
- fail("Failed to create FileInputStream : " + e.getMessage());
- }
- File f2 = new File("ImprobableFile.42");
- try {
- is = new FileInputStream(f2);
- is.close();
- f2.delete();
- fail("FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- }
- }
-
- public void test_ConstructorLjava_io_FileDescriptor() {
- try {
- FileInputStream fis = new FileInputStream((FileDescriptor) null);
- fis.close();
- fail("NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- }
- }
-
- public void test_ConstructorLjava_lang_String() {
- // Test for method FileInputStream(java.lang.String)
- try {
- is = new FileInputStream(fileName);
- is.close();
- } catch (Exception e) {
- fail("Failed to create FileInputStream : " + e.getMessage());
- }
- try {
- is = new FileInputStream("ImprobableFile.42");
- is.close();
- new File("ImprobableFile.42").delete();
- fail("FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- }
- }
-
- public void test_available() throws IOException {
- is = new FileInputStream(fileName);
- assertEquals("Test 1: Returned incorrect number of available bytes;",
- fileString.length(), is.available());
- is.close();
- try {
- is.available();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- public void test_getChannel() {
- // Test for method FileChannel FileInputStream.getChannel()
- FileChannel channel;
- byte[] buffer = new byte[100];
- byte[] stringBytes;
- final int offset = 5;
- boolean equal = true;
-
- try {
- FileInputStream fis = new FileInputStream(fileName);
- channel = fis.getChannel();
- assertNotNull(channel);
- assertTrue("Channel is closed.", channel.isOpen());
-
- // Check that the channel is associated with the input stream.
- channel.position(offset);
- fis.read(buffer, 0, 10);
- stringBytes = fileString.getBytes();
- for (int i = 0; i < 10; i++) {
- equal &= (buffer[i] == stringBytes[i + offset]);
- }
- assertTrue("Channel is not associated with this stream.", equal);
-
- fis.close();
- assertFalse("Channel has not been closed.", channel.isOpen());
- } catch (FileNotFoundException e) {
- fail("Could not find : " + fileName);
- }
-
- catch (IOException e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- public void test_read() throws IOException {
- is = new FileInputStream(fileName);
- int c = is.read();
- assertEquals("Test 1: Read returned incorrect char;",
- fileString.charAt(0), c);
-
- is.close();
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- public void test_read$B() throws IOException {
- byte[] buf1 = new byte[100];
- is = new FileInputStream(fileName);
- is.skip(3000);
- is.read(buf1);
- is.close();
- assertTrue("Test 1: Failed to read correct data.",
- new String(buf1, 0, buf1.length).equals(
- fileString.substring(3000, 3100)));
-
- is.close();
- try {
- is.read(buf1);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- public void test_skipJ() throws IOException {
- byte[] buf1 = new byte[10];
- is = new FileInputStream(fileName);
- is.skip(1000);
- is.read(buf1, 0, buf1.length);
- assertTrue("Test 1: Failed to skip to correct position.",
- new String(buf1, 0, buf1.length).equals(
- fileString.substring(1000, 1010)));
-
- is.close();
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- protected void setUp() throws Exception {
- fileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (fileName.charAt(fileName.length() - 1) == separator.charAt(0))
- fileName = Support_PlatformFile.getNewPlatformFile(fileName,
- "input.tst");
- else
- fileName = Support_PlatformFile.getNewPlatformFile(fileName
- + separator, "input.tst");
- java.io.OutputStream fos = new FileOutputStream(fileName);
- fos.write(fileString.getBytes());
- fos.close();
- }
-
- protected void tearDown() throws Exception {
- if (is != null) {
- is.close();
- }
- new File(fileName).delete();
- }
-}
diff --git a/luni/src/test/java/libcore/java/io/OldFileTest.java b/luni/src/test/java/libcore/java/io/OldFileTest.java
index 8265d20..07ca161 100644
--- a/luni/src/test/java/libcore/java/io/OldFileTest.java
+++ b/luni/src/test/java/libcore/java/io/OldFileTest.java
@@ -18,7 +18,6 @@
package libcore.java.io;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
@@ -27,16 +26,6 @@ import static tests.support.Support_Exec.execAndGetOutput;
import static tests.support.Support_Exec.javaProcessBuilder;
public class OldFileTest extends TestCase {
-
- /** Location to store tests in */
- private File tempDirectory;
-
- /** Temp file that does exist */
- private File tempFile;
-
- /** File separator */
- private String slash = File.separator;
-
public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
private static String platformId = "Android"
@@ -72,76 +61,66 @@ public class OldFileTest extends TestCase {
}
public void test_ConstructorLjava_io_FileLjava_lang_String() throws Exception {
- String error;
- String dirName = System.getProperty("java.io.tmpdir");
- System.setProperty("user.dir", dirName);
+ String tmpDirName = System.getProperty("java.io.tmpdir");
- File d = new File(dirName);
+ File d = new File(tmpDirName);
File f = new File(d, "input.tst");
- if (!dirName.regionMatches((dirName.length() - 1), slash, 0, 1))
- dirName += slash;
- dirName += "input.tst";
- error = String.format("Test 1: Incorrect file created: %s; %s expected.", f.getPath(), dirName);
- assertTrue(error, f.getPath().equals(dirName));
+
+ if (!tmpDirName.endsWith(File.separator)) {
+ tmpDirName += File.separator;
+ }
+ tmpDirName += "input.tst";
+
+ assertEquals(tmpDirName, f.getPath());
String fileName = null;
try {
f = new File(d, fileName);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
+ fail();
+ } catch (NullPointerException expected) {
}
- d = null;
f = new File(d, "input.tst");
- error = String.format("Test 3: Incorrect file created: %s; %s expected.",
- f.getAbsolutePath(), dirName);
- assertTrue(error, f.getAbsolutePath().equals(dirName));
+ assertEquals(tmpDirName, f.getAbsolutePath());
// Regression test for Harmony-382
File s = null;
f = new File("/abc");
d = new File(s, "/abc");
- assertEquals("Test 4: Incorrect file created;",
- f.getAbsolutePath(), d.getAbsolutePath());
+ assertEquals(f.getAbsolutePath(), d.getAbsolutePath());
}
public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException {
- String dirName = null;
- String fileName = "input.tst";
-
- String userDir = System.getProperty("java.io.tmpdir");
- System.setProperty("user.dir", userDir);
+ String tmpDir = System.getProperty("java.io.tmpdir");
+ if (!tmpDir.endsWith(File.separator)) {
+ tmpDir += File.separator;
+ }
- File f = new File(dirName, fileName);
- if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1))
- userDir += slash;
- userDir += "input.tst";
- String error = String.format("Test 1: Incorrect file created: %s; %s expected.",
- f.getAbsolutePath(), userDir);
- assertTrue(error, f.getAbsolutePath().equals(userDir));
+ String dirName = tmpDir;
+ String fileName = "input.tst";
+ File f = new File(tmpDir, fileName);
+ tmpDir += "input.tst";
+ assertEquals(tmpDir, f.getAbsolutePath());
dirName = System.getProperty("java.io.tmpdir");
fileName = null;
try {
f = new File(dirName, fileName);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
+ fail();
+ } catch (NullPointerException expected) {
// Expected.
}
fileName = "input.tst";
f = new File(dirName, fileName);
- assertTrue("Test 3: Incorrect file created.", f.getPath()
- .equals(userDir));
+ assertEquals(tmpDir, f.getPath());
// Regression test for Harmony-382
String s = null;
f = new File("/abc");
File d = new File(s, "/abc");
- assertEquals("Test 4: Incorrect file created;", d.getAbsolutePath(), f
- .getAbsolutePath());
- assertEquals("Test3: Created Incorrect File", "/abc", f
- .getAbsolutePath());
+ assertEquals(d.getAbsolutePath(), f.getAbsolutePath());
+ assertEquals("/abc", f.getAbsolutePath());
}
public void test_createTempFileLjava_lang_StringLjava_lang_String() {
@@ -170,8 +149,7 @@ public class OldFileTest extends TestCase {
public void test_toURL3() throws MalformedURLException {
File dir = new File(""); // current directory
String newDirURL = dir.toURL().toString();
- assertTrue("Test 1: URL does not end with slash.",
- newDirURL.endsWith("/"));
+ assertTrue("Test 1: URL does not end with slash.", newDirURL.endsWith(File.separator));
}
public void test_deleteOnExit() throws IOException, InterruptedException {
@@ -200,42 +178,4 @@ public class OldFileTest extends TestCase {
assertFalse(dir.exists());
assertFalse(subDir.exists());
}
-
- protected void setUp() throws Exception {
- super.setUp();
-
- // Make sure that system properties are set correctly
- String userDir = System.getProperty("java.io.tmpdir");
- if (userDir == null)
- throw new Exception("System property java.io.tmpdir not defined.");
- System.setProperty("java.io.tmpdir", userDir);
-
- /** Setup the temporary directory */
- if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1))
- userDir += slash;
- tempDirectory = new File(userDir + "tempDir"
- + String.valueOf(System.currentTimeMillis()));
- if (!tempDirectory.mkdir())
- System.out.println("Setup for OldFileTest failed (1).");
-
- /** Setup the temporary file */
- tempFile = new File(tempDirectory, "tempfile");
- FileOutputStream tempStream;
- try {
- tempStream = new FileOutputStream(tempFile.getPath(), false);
- tempStream.close();
- } catch (IOException e) {
- System.out.println("Setup for OldFileTest failed (2).");
- return;
- }
- }
-
- protected void tearDown() {
- if (tempFile.exists() && !tempFile.delete())
- System.out
- .println("OldFileTest.tearDown() failed, could not delete file!");
- if (!tempDirectory.delete())
- System.out
- .println("OldFileTest.tearDown() failed, could not delete directory!");
- }
}
diff --git a/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java b/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java
index 848b1bf..11c0279 100644
--- a/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java
+++ b/luni/src/test/java/libcore/java/io/OldFilterInputStreamTest.java
@@ -18,11 +18,11 @@
package libcore.java.io;
import java.io.BufferedInputStream;
+import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.util.Arrays;
import tests.support.Support_ASimpleInputStream;
-import tests.support.Support_PlatformFile;
public class OldFilterInputStreamTest extends junit.framework.TestCase {
@@ -36,13 +36,11 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase {
private FilterInputStream is;
- byte[] ibuf = new byte[4096];
-
- private static final String testString = "Lorem ipsum dolor sit amet,\n" +
+ private static final String INPUT = "Lorem ipsum dolor sit amet,\n" +
"consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" +
"labore et dolore magna aliqua.\n";
- private static final int testLength = testString.length();
+ private static final int INPUT_LENGTH = INPUT.length();
public void test_Constructor() {
// The FilterInputStream object has already been created in setUp().
@@ -59,7 +57,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase {
public void test_available() throws IOException {
assertEquals("Test 1: Returned incorrect number of available bytes;",
- testLength, is.available());
+ INPUT_LENGTH, is.available());
is.close();
try {
@@ -144,7 +142,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase {
public void test_read() throws IOException {
int c = is.read();
assertEquals("Test 1: Read returned incorrect char;",
- testString.charAt(0), c);
+ INPUT.charAt(0), c);
is.close();
try {
@@ -161,7 +159,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase {
is.read(buf1);
assertTrue("Test 1: Failed to read correct data.",
new String(buf1, 0, buf1.length).equals(
- testString.substring(0, 100)));
+ INPUT.substring(0, 100)));
is.close();
try {
@@ -281,7 +279,7 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase {
is.read(buf1, 0, buf1.length);
assertTrue("Test 1: Failed to skip to the correct position.",
new String(buf1, 0, buf1.length).equals(
- testString.substring(10, 20)));
+ INPUT.substring(10, 20)));
is.close();
try {
@@ -292,32 +290,19 @@ public class OldFilterInputStreamTest extends junit.framework.TestCase {
}
}
- protected void setUp() {
- try {
- fileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (fileName.charAt(fileName.length() - 1) == separator.charAt(0))
- fileName = Support_PlatformFile.getNewPlatformFile(fileName,
- "input.tst");
- else
- fileName = Support_PlatformFile.getNewPlatformFile(fileName
- + separator, "input.tst");
- java.io.OutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(testString.getBytes());
- fos.close();
- is = new MyFilterInputStream(new java.io.FileInputStream(fileName));
- } catch (java.io.IOException e) {
- System.out.println("Exception during setup");
- e.printStackTrace();
- }
+ protected void setUp() throws Exception {
+ File f = File.createTempFile("OldFilterInputStreamTest", "tst");
+ fileName = f.getAbsolutePath();
+ java.io.OutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(INPUT.getBytes());
+ fos.close();
+ is = new MyFilterInputStream(new java.io.FileInputStream(fileName));
}
protected void tearDown() {
try {
is.close();
- } catch (Exception e) {
- System.out.println("Unexpected exception in tearDown().");
+ } catch (Exception ignored) {
}
- new java.io.File(fileName).delete();
}
}
diff --git a/luni/src/test/java/libcore/java/io/SerializationTest.java b/luni/src/test/java/libcore/java/io/SerializationTest.java
index 32bc402..03e7d94 100644
--- a/luni/src/test/java/libcore/java/io/SerializationTest.java
+++ b/luni/src/test/java/libcore/java/io/SerializationTest.java
@@ -49,7 +49,9 @@ public final class SerializationTest extends TestCase {
static class FieldMadeTransient implements Serializable {
private static final long serialVersionUID = 0L;
+ @SuppressWarnings("unused")
private transient int transientInt;
+ @SuppressWarnings("unused")
private int nonTransientInt;
}
@@ -64,7 +66,7 @@ public final class SerializationTest extends TestCase {
+ "374244669656c644d6164655374617469630000000000000000020001490009737461746963496e7"
+ "47870000022b8";
FieldMadeStatic deserialized = (FieldMadeStatic) SerializationTester.deserializeHex(s);
- // The field data is simply ignored if it is static.
+ // The field data must be ignored if it is static.
assertEquals(9999, deserialized.staticInt);
}
@@ -74,73 +76,101 @@ public final class SerializationTest extends TestCase {
private static int staticInt = 9999;
}
+ public static boolean serializableContainer1InitializedFlag = false;
+ public static boolean unserializable1InitializedFlag = false;
+
+ public static class Unserializable1 {
+ static {
+ SerializationTest.unserializable1InitializedFlag = true;
+ }
+ }
+
+ static class SerializableContainer1 implements Serializable {
+ private static final long serialVersionUID = 0L;
+ private Unserializable1 unserializable = null;
+
+ static {
+ serializableContainer1InitializedFlag = true;
+ }
+ }
+
// We can serialize an object that has an unserializable field providing it is null.
public void testDeserializeNullUnserializableField() throws Exception {
// This was created by creating a new SerializableContainer and not setting the
// unserializable field. A canned serialized form is used so we can tell if the static
// initializers were executed during deserialization.
- // SerializationTester.serializeHex(new SerializableContainer());
- String s = "aced0005737200376c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657"
- + "3742453657269616c697a61626c65436f6e7461696e657200000000000000000200014c000e756e7"
- + "3657269616c697a61626c657400334c6c6962636f72652f6a6176612f696f2f53657269616c697a6"
- + "174696f6e546573742457617353657269616c697a61626c653b787070";
+ // SerializationTester.serializeHex(new SerializableContainer1());
+ String s = "aced0005737200386c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657"
+ + "3742453657269616c697a61626c65436f6e7461696e65723100000000000000000200014c000e7"
+ + "56e73657269616c697a61626c657400124c6a6176612f6c616e672f4f626a6563743b787070";
- serializableContainerInitializedFlag = false;
- wasSerializableInitializedFlag = false;
+ assertFalse(serializableContainer1InitializedFlag);
+ assertFalse(unserializable1InitializedFlag);
- SerializableContainer sc = (SerializableContainer) SerializationTester.deserializeHex(s);
+ SerializableContainer1 sc = (SerializableContainer1) SerializationTester.deserializeHex(s);
assertNull(sc.unserializable);
// Confirm the container was initialized, but the class for the null field was not.
- assertTrue(serializableContainerInitializedFlag);
- assertFalse(wasSerializableInitializedFlag);
+ assertTrue(serializableContainer1InitializedFlag);
+ assertFalse(unserializable1InitializedFlag);
}
- public static boolean serializableContainerInitializedFlag = false;
+ static class Unserializable2 {
+ }
- static class SerializableContainer implements Serializable {
+ static class HasUnserializableField implements Serializable {
private static final long serialVersionUID = 0L;
- private Object unserializable = null;
-
- static {
- serializableContainerInitializedFlag = true;
- }
+ @SuppressWarnings("unused") // Required to make objects unserializable.
+ private Unserializable2 unserializable = new Unserializable2();
}
// We must not serialize an object that has a non-null unserializable field.
public void testSerializeUnserializableField() throws Exception {
- SerializableContainer sc = new SerializableContainer();
- sc.unserializable = new WasSerializable();
+ HasUnserializableField uf = new HasUnserializableField();
try {
- SerializationTester.serializeHex(sc);
+ SerializationTester.serializeHex(uf);
fail();
} catch (NotSerializableException expected) {
}
}
+ public static boolean serializableContainer2InitializedFlag = false;
+
+ @SuppressWarnings("unused") // Required for deserialization test
+ static class SerializableContainer2 implements Serializable {
+ private static final long serialVersionUID = 0L;
+ private WasSerializable unserializable = null;
+
+ static {
+ serializableContainer2InitializedFlag = true;
+ }
+ }
+
// It must not be possible to deserialize an object if a field is no longer serializable.
public void testDeserializeUnserializableField() throws Exception {
- // This was generated by creating a SerializableContainer and setting the unserializable
+ // This was generated by creating a SerializableContainer2 and setting the unserializable
// field to a WasSerializable when it was still Serializable. A canned serialized form is
// used so we can tell if the static initializers were executed during deserialization.
- // SerializableContainer sc = new SerializableContainer();
+ // SerializableContainer2 sc = new SerializableContainer2();
// sc.unserializable = new WasSerializable();
// SerializationTester.serializeHex(sc);
- String s = "aced0005737200376c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657"
- + "3742453657269616c697a61626c65436f6e7461696e657200000000000000000200014c000e756e7"
- + "3657269616c697a61626c657400124c6a6176612f6c616e672f4f626a6563743b7870737200316c6"
- + "962636f72652e6a6176612e696f2e53657269616c697a6174696f6e5465737424576173536572696"
- + "16c697a61626c65000000000000000002000149000169787000000000";
-
- serializableContainerInitializedFlag = false;
- wasSerializableInitializedFlag = false;
+ String s = "aced0005737200386c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657"
+ + "3742453657269616c697a61626c65436f6e7461696e65723200000000000000000200014c000e7"
+ + "56e73657269616c697a61626c657400334c6c6962636f72652f6a6176612f696f2f53657269616"
+ + "c697a6174696f6e546573742457617353657269616c697a61626c653b7870737200316c6962636"
+ + "f72652e6a6176612e696f2e53657269616c697a6174696f6e546573742457617353657269616c6"
+ + "97a61626c65000000000000000002000149000169787000000000";
+
+ assertFalse(serializableContainer2InitializedFlag);
+ assertFalse(wasSerializableInitializedFlag);
try {
SerializationTester.deserializeHex(s);
fail();
} catch (InvalidClassException expected) {
}
- // Confirm neither the container nor the contained class was initialized.
- assertFalse(serializableContainerInitializedFlag);
+ // The container class will be initialized to establish the serialVersionUID.
+ assertTrue(serializableContainer2InitializedFlag);
+ // Confirm the contained class was initialized.
assertFalse(wasSerializableInitializedFlag);
}
@@ -196,7 +226,7 @@ public final class SerializationTest extends TestCase {
+ "e546573742457617353657269616c697a61626c65000000000000000002000149000169787000000"
+ "000";
- wasSerializableInitializedFlag = false;
+ assertFalse(wasSerializableInitializedFlag);
try {
SerializationTester.deserializeHex(s);
fail();
@@ -239,7 +269,7 @@ public final class SerializationTest extends TestCase {
final String s = "aced0005737200336c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6"
+ "e546573742457617345787465726e616c697a61626c6500000000000000000c0000787078";
- wasExternalizableInitializedFlag = false;
+ assertFalse(wasExternalizableInitializedFlag);
try {
SerializationTester.deserializeHex(s);
fail();
@@ -275,7 +305,7 @@ public final class SerializationTest extends TestCase {
+ "e5465737424576173456e756d00000000000000001200007872000e6a6176612e6c616e672e456e7"
+ "56d0000000000000000120000787074000556414c5545";
- wasEnumInitializedFlag = false;
+ assertFalse(wasEnumInitializedFlag);
try {
SerializationTester.deserializeHex(s);
fail();
@@ -309,7 +339,7 @@ public final class SerializationTest extends TestCase {
final String s = "aced00057372002b6c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6"
+ "e54657374245761734f626a656374000000000000000002000149000169787000000000";
- wasObjectInitializedFlag = false;
+ assertFalse(wasObjectInitializedFlag);
try {
SerializationTester.deserializeHex(s);
fail();
diff --git a/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
deleted file mode 100644
index 98e497d..0000000
--- a/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
+++ /dev/null
@@ -1,81 +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 libcore.java.lang;
-
-import junit.framework.TestCase;
-
-public final class ArrayIndexOutOfBoundsExceptionTest extends TestCase {
- public void testAput() throws Exception {
- byte[] bs = new byte[1];
- try {
- bs[2] = 0;
- fail();
- } catch (ArrayIndexOutOfBoundsException ex) {
- assertEquals("length=1; index=2", ex.getMessage());
- }
- }
-
- public void testAget() throws Exception {
- byte[] bs = new byte[1];
- try {
- byte b = bs[2];
- fail();
- } catch (ArrayIndexOutOfBoundsException ex) {
- assertEquals("length=1; index=2", ex.getMessage());
- }
- }
-
- public void testAputWide() throws Exception {
- double[] ds = new double[1];
- try {
- ds[2] = 0.0;
- fail();
- } catch (ArrayIndexOutOfBoundsException ex) {
- assertEquals("length=1; index=2", ex.getMessage());
- }
- }
-
- public void testAgetWide() throws Exception {
- double[] ds = new double[1];
- try {
- double d = ds[2];
- fail();
- } catch (ArrayIndexOutOfBoundsException ex) {
- assertEquals("length=1; index=2", ex.getMessage());
- }
- }
-
- public void testAputObject() throws Exception {
- Object[] os = new Object[1];
- try {
- os[2] = null;
- fail();
- } catch (ArrayIndexOutOfBoundsException ex) {
- assertEquals("length=1; index=2", ex.getMessage());
- }
- }
-
- public void testAgetObject() throws Exception {
- Object[] os = new Object[1];
- try {
- Object o = os[2];
- fail();
- } catch (ArrayIndexOutOfBoundsException ex) {
- assertEquals("length=1; index=2", ex.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java b/luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java
deleted file mode 100644
index c25245f..0000000
--- a/luni/src/test/java/libcore/java/lang/ArrayStoreExceptionTest.java
+++ /dev/null
@@ -1,154 +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 libcore.java.lang;
-
-import junit.framework.TestCase;
-
-public final class ArrayStoreExceptionTest extends TestCase {
- public void testArrayStoreException_store1() throws Exception {
- Object[] array = new String[10];
- Object o = new Exception();
- try {
- array[0] = o;
- fail();
- } catch (ArrayStoreException ex) {
- ex.printStackTrace();
- assertEquals("java.lang.Exception cannot be stored in an array of type "
- + "java.lang.String[]",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_store2() throws Exception {
- Object[] array = new Nonce[10][];
- Object o = new Integer(5);
- try {
- array[0] = o;
- fail();
- } catch (ArrayStoreException ex) {
- assertEquals("java.lang.Integer cannot be stored in an array of type "
- + "libcore.java.lang.ArrayStoreExceptionTest$Nonce[][]",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_store3() throws Exception {
- Object[] array = new Float[10][];
- Object o = new Nonce[1];
- try {
- array[0] = o;
- fail();
- } catch (ArrayStoreException ex) {
- assertEquals("libcore.java.lang.ArrayStoreExceptionTest$Nonce[] cannot be stored "
- + "in an array of type java.lang.Float[][]",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy1() throws Exception {
- String[] src = new String[] { null, null, null, null, "hello", "goodbye" };
- Integer[] dest = new Integer[10];
- try {
- System.arraycopy(src, 1, dest, 0, 5);
- } catch (ArrayStoreException ex) {
- ex.printStackTrace();
- assertEquals("source[4] of type java.lang.String cannot be stored in destination "
- + "array of type java.lang.Integer[]",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy2() throws Exception {
- String[] src = new String[1];
- int[] dest = new int[1];
- try {
- System.arraycopy(src, 0, dest, 0, 1);
- } catch (ArrayStoreException ex) {
- assertEquals("java.lang.String[] and int[] are incompatible array types",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy3() throws Exception {
- float[] src = new float[1];
- Runnable[] dest = new Runnable[1];
- try {
- System.arraycopy(src, 0, dest, 0, 1);
- } catch (ArrayStoreException ex) {
- assertEquals("float[] and java.lang.Runnable[] are incompatible array types",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy4() throws Exception {
- boolean[] src = new boolean[1];
- double[][] dest = new double[1][];
- try {
- System.arraycopy(src, 0, dest, 0, 1);
- } catch (ArrayStoreException ex) {
- assertEquals("boolean[] and double[][] are incompatible array types",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy5() throws Exception {
- String src = "blort";
- Object[] dest = new Object[1];
- try {
- System.arraycopy(src, 0, dest, 0, 1);
- } catch (ArrayStoreException ex) {
- assertEquals("source of type java.lang.String is not an array",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy6() throws Exception {
- Object[] src = new Object[1];
- Integer dest = new Integer(5);
- try {
- System.arraycopy(src, 0, dest, 0, 1);
- } catch (ArrayStoreException ex) {
- assertEquals("destination of type java.lang.Integer is not an array",
- ex.getMessage());
- }
- }
-
- public void testArrayStoreException_arraycopy7() throws Exception {
- /*
- * This test demonstrates that the exception message complains
- * about the source in cases where neither source nor
- * destination is an array.
- */
- Nonce src = new Nonce();
- String dest = "blort";
- try {
- System.arraycopy(src, 0, dest, 0, 1);
- } catch (ArrayStoreException ex) {
- assertEquals("source of type libcore.java.lang.ArrayStoreExceptionTest$Nonce "
- + "is not an array",
- ex.getMessage());
- }
- }
-
- /**
- * This class is just used so that we have an example of getting a
- * message that includes an inner class.
- */
- private static class Nonce {
- // This space intentionally left blank.
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/CharacterTest.java b/luni/src/test/java/libcore/java/lang/CharacterTest.java
index 48284d6..8c6f06f 100644
--- a/luni/src/test/java/libcore/java/lang/CharacterTest.java
+++ b/luni/src/test/java/libcore/java/lang/CharacterTest.java
@@ -242,7 +242,14 @@ public class CharacterTest extends junit.framework.TestCase {
Method m = Character.class.getDeclaredMethod("isSpaceChar" + "Impl", int.class);
m.setAccessible(true);
for (int i = 0; i <= 0xffff; ++i) {
- if((Boolean) m.invoke(null, i) != Character.isSpaceChar(i)) System.out.println(i);
+ // ICU and the RI disagree about character 0x180e. Remove this special case if this changes
+ // or Android decides to follow ICU exactly.
+ if (i == 0x180e) {
+ assertTrue(Character.isSpaceChar(i));
+ assertFalse((Boolean) m.invoke(null, i));
+ } else {
+ assertEquals("Failed for character " + i, m.invoke(null, i), Character.isSpaceChar(i));
+ }
}
}
@@ -260,7 +267,26 @@ public class CharacterTest extends junit.framework.TestCase {
Method m = Character.class.getDeclaredMethod("isWhitespace" + "Impl", int.class);
m.setAccessible(true);
for (int i = 0; i <= 0xffff; ++i) {
- assertEquals(m.invoke(null, i), Character.isWhitespace(i));
+ // ICU and the RI disagree about character 0x180e. Remove this special case if this changes
+ // or Android decides to follow ICU exactly.
+ if (i == 0x180e) {
+ assertTrue(Character.isWhitespace(i));
+ assertFalse((Boolean) m.invoke(null, i));
+ } else {
+ assertEquals("Failed for character " + i, m.invoke(null, i), Character.isWhitespace(i));
+ }
}
}
+
+ // http://b/15492712
+ public void test_getDirectionality() throws Exception {
+ // We shouldn't throw an exception for any code point.
+ for (int c = '\u0000'; c <= Character.MAX_VALUE; ++c) {
+ Character.getDirectionality(c);
+ }
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2066));
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2067));
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2068));
+ assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character.getDirectionality(0x2069));
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java b/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java
index ec3aa46..3c10aa8 100644
--- a/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java
+++ b/luni/src/test/java/libcore/java/lang/ClassCastExceptionTest.java
@@ -23,16 +23,6 @@ import java.util.EnumSet;
import junit.framework.TestCase;
public final class ClassCastExceptionTest extends TestCase {
- public void testCast() throws Exception {
- Object o = new Exception();
- try {
- String s = (String) o;
- fail();
- } catch (ClassCastException ex) {
- assertEquals("java.lang.Exception cannot be cast to java.lang.String", ex.getMessage());
- }
- }
-
public void testClassCast() throws Exception {
Object o = new Exception();
try {
@@ -53,69 +43,6 @@ public final class ClassCastExceptionTest extends TestCase {
}
}
- public void testCastOperator() throws Exception {
- try {
- Object o = (InputStream) makeInteger();
- fail();
- } catch (ClassCastException ex) {
- assertEquals("java.lang.Integer cannot be cast to java.io.InputStream",
- ex.getMessage());
- }
- }
-
- public void testCastOperatorWithArrays() throws Exception {
- try {
- Object o = (E) makeArray(String.class);
- fail();
- } catch (ClassCastException ex) {
- assertEquals("java.lang.String[] cannot be cast to "
- + "libcore.java.lang.ClassCastExceptionTest$E",
- ex.getMessage());
- }
-
- try {
- Object o = (E) makeArray(float.class);
- fail();
- } catch (ClassCastException ex) {
- assertEquals("float[] cannot be cast to libcore.java.lang.ClassCastExceptionTest$E",
- ex.getMessage());
- }
-
- try {
- Object o = (E) makeArray(char[].class);
- fail();
- } catch (ClassCastException ex) {
- assertEquals("char[][] cannot be cast to libcore.java.lang.ClassCastExceptionTest$E",
- ex.getMessage());
- }
-
- try {
- Object o = (Object[][][]) makeInteger();
- fail();
- } catch (ClassCastException ex) {
- assertEquals("java.lang.Integer cannot be cast to java.lang.Object[][][]",
- ex.getMessage());
- }
- }
-
- /**
- * Helper for {@link #testCastOperator} and {@link
- * #testCastOperatorWithArrays}, above. It's important that the
- * return type is {@code Object}, since otherwise the compiler
- * will just reject the code.
- */
- private static Object makeInteger() {
- return new Integer(5);
- }
-
- /**
- * Helper for {@link #testCastOperatorWithArrays} above. It's important that
- * the return type is {@code Object}.
- */
- private static Object makeArray(Class clazz) {
- return Array.newInstance(clazz, 1);
- }
-
enum E { A, B, C };
enum F { A, B, C };
@@ -125,7 +52,6 @@ public final class ClassCastExceptionTest extends TestCase {
m.put(F.A, "world");
fail();
} catch (ClassCastException ex) {
- ex.printStackTrace();
assertNotNull(ex.getMessage());
}
}
@@ -136,7 +62,6 @@ public final class ClassCastExceptionTest extends TestCase {
m.add(F.A);
fail();
} catch (ClassCastException ex) {
- ex.printStackTrace();
assertNotNull(ex.getMessage());
}
}
@@ -148,7 +73,6 @@ public final class ClassCastExceptionTest extends TestCase {
m.addAll(n);
fail();
} catch (ClassCastException ex) {
- ex.printStackTrace();
assertNotNull(ex.getMessage());
}
}
@@ -170,7 +94,6 @@ public final class ClassCastExceptionTest extends TestCase {
m.add(HugeF.A0);
fail();
} catch (ClassCastException ex) {
- ex.printStackTrace();
assertNotNull(ex.getMessage());
}
}
@@ -182,7 +105,6 @@ public final class ClassCastExceptionTest extends TestCase {
m.addAll(n);
fail();
} catch (ClassCastException ex) {
- ex.printStackTrace();
assertNotNull(ex.getMessage());
}
}
diff --git a/luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java b/luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java
deleted file mode 100644
index 6eb97c2..0000000
--- a/luni/src/test/java/libcore/java/lang/ClassNotFoundExceptionTest.java
+++ /dev/null
@@ -1,49 +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 libcore.java.lang;
-
-import junit.framework.TestCase;
-
-public final class ClassNotFoundExceptionTest extends TestCase {
- public void testIllegalName() throws Exception {
- try {
- // There is no such thing as an array of void.
- Class.forName("[V");
- fail();
- } catch (ClassNotFoundException ex) {
- assertEquals("[V", ex.getMessage());
- }
- }
-
- public void testValidName() throws Exception {
- try {
- Class.forName("blort.Zorch");
- fail();
- } catch (ClassNotFoundException ex) {
- assertEquals("blort.Zorch", ex.getMessage());
- }
- }
-
- public void testValidArrayName() throws Exception {
- try {
- Class.forName("[[Lblort.Zorch;");
- fail();
- } catch (ClassNotFoundException ex) {
- assertEquals("[[Lblort.Zorch;", ex.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/ClassTest.java b/luni/src/test/java/libcore/java/lang/ClassTest.java
new file mode 100644
index 0000000..15298ea
--- /dev/null
+++ b/luni/src/test/java/libcore/java/lang/ClassTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2013 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 libcore.java.lang;
+
+import junit.framework.TestCase;
+
+public class ClassTest extends TestCase {
+
+ interface Foo {
+ public void foo();
+ }
+
+ interface ParameterizedFoo<T> {
+ public void foo(T param);
+ }
+
+ interface ParameterizedBar<T> extends ParameterizedFoo<T> {
+ public void bar(T param);
+ }
+
+ interface ParameterizedBaz extends ParameterizedFoo<String> {
+
+ }
+
+ public void test_getGenericSuperclass_nullReturnCases() {
+ // Should always return null for interfaces.
+ assertNull(Foo.class.getGenericSuperclass());
+ assertNull(ParameterizedFoo.class.getGenericSuperclass());
+ assertNull(ParameterizedBar.class.getGenericSuperclass());
+ assertNull(ParameterizedBaz.class.getGenericSuperclass());
+
+ assertNull(Object.class.getGenericSuperclass());
+ assertNull(void.class.getGenericSuperclass());
+ assertNull(int.class.getGenericSuperclass());
+ }
+
+ public void test_getGenericSuperclass_returnsObjectForArrays() {
+ assertSame(Object.class, (new Integer[0]).getClass().getGenericSuperclass());
+ }
+}
diff --git a/luni/src/test/java/libcore/java/lang/DoubleTest.java b/luni/src/test/java/libcore/java/lang/DoubleTest.java
index 687d3e3..85281ba 100644
--- a/luni/src/test/java/libcore/java/lang/DoubleTest.java
+++ b/luni/src/test/java/libcore/java/lang/DoubleTest.java
@@ -127,4 +127,19 @@ public class DoubleTest extends TestCase {
assertEquals(2.2250738585072014E-308, Double.parseDouble("2.22507385850720129978001e-308"));
assertEquals(-2.2250738585072014E-308, Double.parseDouble("-2.2250738585072012e-308"));
}
+
+ // https://code.google.com/p/android/issues/detail?id=71216
+ public void testParse_bug71216() {
+ try {
+ Double.parseDouble("73706943-9580-4406-a02f-0304e4324844");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+
+ try {
+ Double.parseDouble("bade999999999999999999999999999999");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/IntegerTest.java b/luni/src/test/java/libcore/java/lang/IntegerTest.java
index 2d8c082..b54b322 100644
--- a/luni/src/test/java/libcore/java/lang/IntegerTest.java
+++ b/luni/src/test/java/libcore/java/lang/IntegerTest.java
@@ -16,19 +16,118 @@
package libcore.java.lang;
+import java.util.Properties;
+
public class IntegerTest extends junit.framework.TestCase {
- public void test_compare() throws Exception {
- final int min = Integer.MIN_VALUE;
- final int zero = 0;
- final int max = Integer.MAX_VALUE;
- assertTrue(Integer.compare(max, max) == 0);
- assertTrue(Integer.compare(min, min) == 0);
- assertTrue(Integer.compare(zero, zero) == 0);
- assertTrue(Integer.compare(max, zero) > 0);
- assertTrue(Integer.compare(max, min) > 0);
- assertTrue(Integer.compare(zero, max) < 0);
- assertTrue(Integer.compare(zero, min) > 0);
- assertTrue(Integer.compare(min, zero) < 0);
- assertTrue(Integer.compare(min, max) < 0);
+
+ public void testSystemProperties() {
+ Properties originalProperties = System.getProperties();
+ try {
+ Properties testProperties = new Properties();
+ testProperties.put("testIncInt", "notInt");
+ System.setProperties(testProperties);
+ assertNull("returned incorrect default Integer",
+ Integer.getInteger("testIncInt"));
+ assertEquals(new Integer(4), Integer.getInteger("testIncInt", 4));
+ assertEquals(new Integer(4),
+ Integer.getInteger("testIncInt", new Integer(4)));
+ } finally {
+ System.setProperties(originalProperties);
}
+ }
+
+ public void testCompare() throws Exception {
+ final int min = Integer.MIN_VALUE;
+ final int zero = 0;
+ final int max = Integer.MAX_VALUE;
+ assertTrue(Integer.compare(max, max) == 0);
+ assertTrue(Integer.compare(min, min) == 0);
+ assertTrue(Integer.compare(zero, zero) == 0);
+ assertTrue(Integer.compare(max, zero) > 0);
+ assertTrue(Integer.compare(max, min) > 0);
+ assertTrue(Integer.compare(zero, max) < 0);
+ assertTrue(Integer.compare(zero, min) > 0);
+ assertTrue(Integer.compare(min, zero) < 0);
+ assertTrue(Integer.compare(min, max) < 0);
+ }
+
+ public void testParseInt() throws Exception {
+ assertEquals(0, Integer.parseInt("+0", 10));
+ assertEquals(473, Integer.parseInt("+473", 10));
+ assertEquals(255, Integer.parseInt("+FF", 16));
+ assertEquals(102, Integer.parseInt("+1100110", 2));
+ assertEquals(2147483647, Integer.parseInt("+2147483647", 10));
+ assertEquals(411787, Integer.parseInt("Kona", 27));
+ assertEquals(411787, Integer.parseInt("+Kona", 27));
+ assertEquals(-145, Integer.parseInt("-145", 10));
+
+ try {
+ Integer.parseInt("--1", 10); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Integer.parseInt("++1", 10); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Integer.parseInt("Kona", 10); // base too small
+ fail();
+ } catch (NumberFormatException expected) {}
+ }
+
+ public void testDecodeInt() throws Exception {
+ assertEquals(0, Integer.decode("+0").intValue());
+ assertEquals(473, Integer.decode("+473").intValue());
+ assertEquals(255, Integer.decode("+0xFF").intValue());
+ assertEquals(16, Integer.decode("+020").intValue());
+ assertEquals(2147483647, Integer.decode("+2147483647").intValue());
+ assertEquals(-73, Integer.decode("-73").intValue());
+ assertEquals(-255, Integer.decode("-0xFF").intValue());
+ assertEquals(255, Integer.decode("+#FF").intValue());
+ assertEquals(-255, Integer.decode("-#FF").intValue());
+
+ try {
+ Integer.decode("--1"); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Integer.decode("++1"); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Integer.decode("-+1"); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Integer.decode("Kona"); // invalid number
+ fail();
+ } catch (NumberFormatException expected) {}
+ }
+
+ public void testParsePositiveInt() throws Exception {
+ assertEquals(0, Integer.parsePositiveInt("0", 10));
+ assertEquals(473, Integer.parsePositiveInt("473", 10));
+ assertEquals(255, Integer.parsePositiveInt("FF", 16));
+
+ try {
+ Integer.parsePositiveInt("-1", 10);
+ fail();
+ } catch (NumberFormatException e) {}
+
+ try {
+ Integer.parsePositiveInt("+1", 10);
+ fail();
+ } catch (NumberFormatException e) {}
+
+ try {
+ Integer.parsePositiveInt("+0", 16);
+ fail();
+ } catch (NumberFormatException e) {}
+ }
+
}
diff --git a/luni/src/test/java/libcore/java/lang/LongTest.java b/luni/src/test/java/libcore/java/lang/LongTest.java
index 9e143da..0d1741a 100644
--- a/luni/src/test/java/libcore/java/lang/LongTest.java
+++ b/luni/src/test/java/libcore/java/lang/LongTest.java
@@ -16,8 +16,25 @@
package libcore.java.lang;
+import java.util.Properties;
+
public class LongTest extends junit.framework.TestCase {
- public void test_compare() throws Exception {
+
+ public void testSystemProperties() {
+ Properties originalProperties = System.getProperties();
+ try {
+ Properties testProperties = new Properties();
+ testProperties.put("testIncLong", "string");
+ System.setProperties(testProperties);
+ assertNull(Long.getLong("testIncLong"));
+ assertEquals(new Long(4), Long.getLong("testIncLong", 4L));
+ assertEquals(new Long(4), Long.getLong("testIncLong", new Long(4)));
+ } finally {
+ System.setProperties(originalProperties);
+ }
+ }
+
+ public void testCompare() throws Exception {
final long min = Long.MIN_VALUE;
final long zero = 0L;
final long max = Long.MAX_VALUE;
@@ -32,11 +49,91 @@ public class LongTest extends junit.framework.TestCase {
assertTrue(Long.compare(min, max) < 0);
}
- public void test_signum() throws Exception {
+ public void testSignum() throws Exception {
assertEquals(0, Long.signum(0));
assertEquals(1, Long.signum(1));
assertEquals(-1, Long.signum(-1));
assertEquals(1, Long.signum(Long.MAX_VALUE));
assertEquals(-1, Long.signum(Long.MIN_VALUE));
}
+
+ public void testParsePositiveLong() throws Exception {
+ assertEquals(0, Long.parsePositiveLong("0", 10));
+ assertEquals(473, Long.parsePositiveLong("473", 10));
+ assertEquals(255, Long.parsePositiveLong("FF", 16));
+
+ try {
+ Long.parsePositiveLong("-1", 10);
+ fail();
+ } catch (NumberFormatException e) {}
+
+ try {
+ Long.parsePositiveLong("+1", 10);
+ fail();
+ } catch (NumberFormatException e) {}
+
+ try {
+ Long.parsePositiveLong("+0", 16);
+ fail();
+ } catch (NumberFormatException e) {}
+ }
+
+ public void testParseLong() throws Exception {
+ assertEquals(0, Long.parseLong("+0", 10));
+ assertEquals(473, Long.parseLong("+473", 10));
+ assertEquals(255, Long.parseLong("+FF", 16));
+ assertEquals(102, Long.parseLong("+1100110", 2));
+ assertEquals(Long.MAX_VALUE, Long.parseLong("+" + Long.MAX_VALUE, 10));
+ assertEquals(411787, Long.parseLong("Kona", 27));
+ assertEquals(411787, Long.parseLong("+Kona", 27));
+ assertEquals(-145, Long.parseLong("-145", 10));
+
+ try {
+ Long.parseLong("--1", 10); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Long.parseLong("++1", 10); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Long.parseLong("Kona", 10); // base to small
+ fail();
+ } catch (NumberFormatException expected) {}
+ }
+
+ public void testDecodeLong() throws Exception {
+ assertEquals(0, Long.decode("+0").longValue());
+ assertEquals(473, Long.decode("+473").longValue());
+ assertEquals(255, Long.decode("+0xFF").longValue());
+ assertEquals(16, Long.decode("+020").longValue());
+ assertEquals(Long.MAX_VALUE, Long.decode("+" + Long.MAX_VALUE).longValue());
+ assertEquals(-73, Long.decode("-73").longValue());
+ assertEquals(-255, Long.decode("-0xFF").longValue());
+ assertEquals(255, Long.decode("+#FF").longValue());
+ assertEquals(-255, Long.decode("-#FF").longValue());
+
+ try {
+ Long.decode("--1"); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Long.decode("++1"); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Long.decode("+-1"); // multiple sign chars
+ fail();
+ } catch (NumberFormatException expected) {}
+
+ try {
+ Long.decode("Kona"); // invalid number
+ fail();
+ } catch (NumberFormatException expected) {}
+ }
+
}
diff --git a/luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java b/luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java
deleted file mode 100644
index 08351d6..0000000
--- a/luni/src/test/java/libcore/java/lang/OldAndroidParseIntTest.java
+++ /dev/null
@@ -1,108 +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 libcore.java.lang;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for functionality of class Integer to parse integers.
- */
-public class OldAndroidParseIntTest extends TestCase {
-
- public void testParseInt() throws Exception {
- assertEquals(0, Integer.parseInt("0", 10));
- assertEquals(473, Integer.parseInt("473", 10));
- assertEquals(0, Integer.parseInt("-0", 10));
- assertEquals(-255, Integer.parseInt("-FF", 16));
- assertEquals(102, Integer.parseInt("1100110", 2));
- assertEquals(2147483647, Integer.parseInt("2147483647", 10));
- assertEquals(-2147483648, Integer.parseInt("-2147483648", 10));
-
- try {
- Integer.parseInt("2147483648", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("-2147483649", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- // One digit too many
- try {
- Integer.parseInt("21474836470", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("-21474836480", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("21474836471", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("-21474836481", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("214748364710", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("-214748364811", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("99", 8);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- try {
- Integer.parseInt("Kona", 10);
- fail();
- } catch (NumberFormatException e) {
- // ok
- }
-
- assertEquals(411787, Integer.parseInt("Kona", 27));
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/OldClassTest.java b/luni/src/test/java/libcore/java/lang/OldClassTest.java
index 0f7ce42..23a42bd 100644
--- a/luni/src/test/java/libcore/java/lang/OldClassTest.java
+++ b/luni/src/test/java/libcore/java/lang/OldClassTest.java
@@ -720,8 +720,20 @@ public class OldClassTest extends junit.framework.TestCase {
}
public void test_getDeclaringClass() {
- assertNull(OldClassTest.class.getDeclaringClass());
- assertNotNull(PublicTestClass.class.getDeclaringClass());
+ assertEquals(OldClassTest.class, Intf1.class.getDeclaringClass());
+ assertEquals(null, Serializable.class.getDeclaringClass());
+ assertEquals(null, OldClassTest.class.getDeclaringClass());
+
+ assertEquals(OldClassTest.class, PublicTestClass.class.getDeclaringClass());
+
+ // https://code.google.com/p/android/issues/detail?id=61003
+ assertEquals(null, new Object() {}.getClass().getDeclaringClass());
+ assertEquals(null, new AnonymousMemberFixture().instanceOfAnonymousClass.getClass().getDeclaringClass());
+
+ // Arrays, primitive types, and void all return null.
+ assertEquals(null, char[].class.getDeclaringClass());
+ assertEquals(null, int.class.getDeclaringClass());
+ assertEquals(null, void.class.getDeclaringClass());
}
public void test_getFieldLjava_lang_String() throws Exception {
@@ -1022,3 +1034,7 @@ public class OldClassTest extends junit.framework.TestCase {
assertNull(clazz.getResourceAsStream("libcore/java/lang/HelloWorld.txt"));
}
}
+
+class AnonymousMemberFixture {
+ Object instanceOfAnonymousClass = new Object() {};
+}
diff --git a/luni/src/test/java/libcore/java/lang/OldIntegerTest.java b/luni/src/test/java/libcore/java/lang/OldIntegerTest.java
deleted file mode 100644
index 462ee19..0000000
--- a/luni/src/test/java/libcore/java/lang/OldIntegerTest.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 libcore.java.lang;
-
-import java.util.Properties;
-import junit.framework.TestCase;
-
-public class OldIntegerTest extends TestCase {
- private Properties orgProps;
-
- @Override
- protected void setUp() {
- orgProps = System.getProperties();
- }
-
- @Override
- protected void tearDown() {
- System.setProperties(orgProps);
- }
-
- public void test_getIntegerLjava_lang_StringI() {
- // Test for method java.lang.Integer
- // java.lang.Integer.getInteger(java.lang.String, int)
- Properties tProps = new Properties();
- tProps.put("testIncInt", "notInt");
- System.setProperties(tProps);
- assertTrue("returned incorrect default Integer", Integer.getInteger(
- "testIncInt", 4).equals(new Integer(4)));
- }
-
- public void test_getIntegerLjava_lang_StringLjava_lang_Integer() {
- // Test for method java.lang.Integer
- // java.lang.Integer.getInteger(java.lang.String, java.lang.Integer)
- Properties tProps = new Properties();
- tProps.put("testIncInt", "notInt");
- System.setProperties(tProps);
- assertTrue("returned incorrect default Integer", Integer.getInteger(
- "testIncInt", new Integer(4)).equals(new Integer(4)));
- }
-
- public void test_intValue() {
- assertEquals(Integer.MAX_VALUE, new Integer(Integer.MAX_VALUE).intValue());
- assertEquals(Integer.MIN_VALUE, new Integer(Integer.MIN_VALUE).intValue());
- }
-
- public void test_longValue() {
- assertEquals(Integer.MAX_VALUE, new Integer(Integer.MAX_VALUE).longValue());
- assertEquals(Integer.MIN_VALUE, new Integer(Integer.MIN_VALUE).longValue());
- }
-
- public void test_shortValue() {
- assertEquals(-1, new Integer(Integer.MAX_VALUE).shortValue());
- assertEquals(0, new Integer(Integer.MIN_VALUE).shortValue());
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/OldLongTest.java b/luni/src/test/java/libcore/java/lang/OldLongTest.java
deleted file mode 100644
index 6fb7d49..0000000
--- a/luni/src/test/java/libcore/java/lang/OldLongTest.java
+++ /dev/null
@@ -1,83 +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 libcore.java.lang;
-
-import java.util.Properties;
-import junit.framework.TestCase;
-
-public class OldLongTest extends TestCase {
- private Properties orgProps;
-
- @Override
- protected void setUp() {
- orgProps = System.getProperties();
- }
-
- @Override
- protected void tearDown() {
- System.setProperties(orgProps);
- }
-
- public void test_getLongLjava_lang_String() {
- Properties tProps = new Properties();
- tProps.put("testLong", "99");
- tProps.put("testIncLong", "string");
- System.setProperties(tProps);
- assertNull("returned incorrect default Long",
- Long.getLong("testIncLong"));
- }
-
- public void test_getLongLjava_lang_StringJ() {
- // Test for method java.lang.Long
- // java.lang.Long.getLong(java.lang.String, long)
- Properties tProps = new Properties();
- tProps.put("testIncLong", "string");
- System.setProperties(tProps);
- assertTrue("returned incorrect default Long", Long.getLong("testIncLong", 4L)
- .equals(new Long(4)));
- }
-
- public void test_getLongLjava_lang_StringLjava_lang_Long() {
- // Test for method java.lang.Long
- // java.lang.Long.getLong(java.lang.String, java.lang.Long)
- Properties tProps = new Properties();
- tProps.put("testIncLong", "string");
- System.setProperties(tProps);
- assertTrue("returned incorrect default Long", Long.getLong("testIncLong",
- new Long(4)).equals(new Long(4)));
- }
-
- public void test_floatValue() {
- assertEquals(Long.MAX_VALUE, new Long(Long.MAX_VALUE).floatValue(), 0F);
- assertEquals(Long.MIN_VALUE, new Long(Long.MIN_VALUE).floatValue(), 0F);
- }
-
- public void test_intValue() {
- assertEquals(-1, new Long(Long.MAX_VALUE).intValue());
- assertEquals(0, new Long(Long.MIN_VALUE).intValue());
- }
-
- public void test_longValue() {
- assertEquals(Long.MAX_VALUE, new Long(Long.MAX_VALUE).longValue());
- assertEquals(Long.MIN_VALUE, new Long(Long.MIN_VALUE).longValue());
- }
-
- public void test_shortValue() {
- assertEquals(-1, new Long(Long.MAX_VALUE).shortValue());
- assertEquals(0, new Long(Long.MIN_VALUE).shortValue());
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/OldObjectTest.java b/luni/src/test/java/libcore/java/lang/OldObjectTest.java
index 3ab0327..f7a3781 100644
--- a/luni/src/test/java/libcore/java/lang/OldObjectTest.java
+++ b/luni/src/test/java/libcore/java/lang/OldObjectTest.java
@@ -36,6 +36,16 @@ public class OldObjectTest extends TestCase {
TestThread1 thr1;
TestThread2 thr2;
+ public void test_hashCode() {
+ Object o1 = new Object();
+ Object o2 = new Object();
+ int h1 = System.identityHashCode(o1);
+ int h2 = System.identityHashCode(o2);
+ assertEquals(h1, o1.hashCode());
+ assertEquals(h2, o2.hashCode());
+ assertTrue(h1 != h2);
+ }
+
public void test_clone() {
MockCloneableObject mco = new MockCloneableObject();
try {
diff --git a/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java b/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java
index 0926569..294cea2 100644
--- a/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java
+++ b/luni/src/test/java/libcore/java/lang/OldRuntimeTest.java
@@ -34,28 +34,6 @@ public class OldRuntimeTest extends junit.framework.TestCase {
InputStream is;
- public void test_freeMemory() {
- // Heap might grow or do GC at any time,
- // so we can't really test a lot. Hence
- // we are just doing some basic sanity
- // checks here.
- assertTrue("must have some free memory",
- r.freeMemory() > 0);
-
- assertTrue("must not exceed total memory",
- r.freeMemory() < r.totalMemory());
-
- long before = r.totalMemory() - r.freeMemory();
- Vector<byte[]> v = new Vector<byte[]>();
- for (int i = 1; i < 10; i++) {
- v.addElement(new byte[10000]);
- }
- long after = r.totalMemory() - r.freeMemory();
-
- assertTrue("free memory must change with allocations",
- after != before);
- }
-
public void test_getRuntime() {
// Test for method java.lang.Runtime java.lang.Runtime.getRuntime()
assertNotNull(Runtime.getRuntime());
@@ -451,10 +429,6 @@ public class OldRuntimeTest extends junit.framework.TestCase {
}
}
- public void test_maxMemory() {
- assertTrue(Runtime.getRuntime().maxMemory() < Long.MAX_VALUE);
- }
-
public void test_traceInstructions() {
Runtime.getRuntime().traceInstructions(false);
Runtime.getRuntime().traceInstructions(true);
diff --git a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
index d03ae65..9766cef 100644
--- a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
+++ b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
@@ -22,10 +22,10 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
-import libcore.dalvik.system.CloseGuardTester;
+import libcore.java.util.AbstractResourceLeakageDetectorTestCase;
import static tests.support.Support_Exec.execAndCheckOutput;
-public class ProcessBuilderTest extends junit.framework.TestCase {
+public class ProcessBuilderTest extends AbstractResourceLeakageDetectorTestCase {
private static String shell() {
String deviceSh = "/system/bin/sh";
@@ -84,14 +84,8 @@ public class ProcessBuilderTest extends junit.framework.TestCase {
}
public void testDestroyDoesNotLeak() throws IOException {
- CloseGuardTester closeGuardTester = new CloseGuardTester();
- try {
- Process process = new ProcessBuilder(shell(), "-c", "echo out; echo err 1>&2").start();
- process.destroy();
- closeGuardTester.assertEverythingWasClosed();
- } finally {
- closeGuardTester.close();
- }
+ Process process = new ProcessBuilder(shell(), "-c", "echo out; echo err 1>&2").start();
+ process.destroy();
}
public void testEnvironmentMapForbidsNulls() throws Exception {
diff --git a/luni/src/test/java/libcore/java/lang/StringBuilderTest.java b/luni/src/test/java/libcore/java/lang/StringBuilderTest.java
new file mode 100644
index 0000000..1f9abbf
--- /dev/null
+++ b/luni/src/test/java/libcore/java/lang/StringBuilderTest.java
@@ -0,0 +1,132 @@
+/*
+ * 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 libcore.java.lang;
+
+public class StringBuilderTest extends junit.framework.TestCase {
+ // See https://code.google.com/p/android/issues/detail?id=60639
+ public void test_deleteChatAt_lastRange() {
+ StringBuilder sb = new StringBuilder("oarFish_");
+ sb.append('a');
+ String oarFishA = sb.toString();
+
+ sb.deleteCharAt(sb.length() - 1);
+ sb.append('b');
+ String oarFishB = sb.toString();
+
+ assertEquals("oarFish_a", oarFishA);
+ assertEquals("oarFish_b", oarFishB);
+ }
+
+ // See https://code.google.com/p/android/issues/detail?id=60639
+ public void test_deleteCharAt_lastChar() {
+ StringBuilder sb = new StringBuilder();
+ sb.append('a');
+ String a = sb.toString();
+
+ sb.deleteCharAt(0);
+ sb.append('b');
+ String b = sb.toString();
+
+ assertEquals("a", a);
+ assertEquals("b", b);
+ }
+
+ // See https://code.google.com/p/android/issues/detail?id=60639
+ public void test_delete_endsAtLastChar() {
+ StringBuilder sb = new StringBuilder("newGuineaSinging");
+ sb.append("Dog");
+ String dog = sb.toString();
+
+ sb.delete(sb.length() - 3, sb.length());
+ sb.append("Cat");
+ String cat = sb.toString();
+
+ // NOTE: It's important that these asserts stay at the end of this test.
+ // We're trying to make sure that replacing chars in the builder does not
+ // change strings that have already been returned from it.
+ assertEquals("newGuineaSingingDog", dog);
+ assertEquals("newGuineaSingingCat", cat);
+ }
+
+ public void test_deleteCharAt_boundsChecks() {
+ StringBuilder sb = new StringBuilder("yeti");
+
+ try {
+ sb.deleteCharAt(sb.length());
+ fail();
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+
+ try {
+ sb.deleteCharAt(-1);
+ fail();
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void test_delete_boundsChecks() throws Exception {
+ StringBuilder sb = new StringBuilder("yeti");
+
+ // The cases below ahould not throw (even though they are clearly invalid
+ // ranges), because we promise not to throw if start == count as long as
+ // end >= start.
+ sb.delete(sb.length(), sb.length() + 2);
+ sb.delete(sb.length(), sb.length());
+
+ sb.delete(2, 2);
+ assertEquals("yeti", sb.toString());
+
+ // We must throw if start > count....
+ try {
+ sb.delete(sb.length() + 2, sb.length() + 3);
+ fail();
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+
+ // ... even if the length of the range is 0.
+ try {
+ sb.delete(sb.length() + 2, sb.length() + 2);
+ fail();
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+
+ // Must throw if start < 0.
+ try {
+ sb.delete(-1, sb.length() -1);
+ fail();
+ } catch (StringIndexOutOfBoundsException expected) {
+ }
+
+ // A few commonly used specializations: sb.delete(0, 0) on an empty
+ // builder is a particularly common pattern.
+ StringBuilder sb2 = new StringBuilder();
+ sb2.delete(0, sb2.length());
+ sb2.delete(0, 12);
+ }
+
+ // We shouldn't throw if the end index is > count, we should clamp it
+ // instead.
+ public void test_delete_clampsEnd() throws Exception {
+ StringBuilder sb = new StringBuilder("mogwai");
+
+ sb.delete(sb.length() - 1 , sb.length() + 2);
+ assertEquals("mogwa", sb.toString());
+
+ sb.delete(sb.length() - 1, sb.length());
+ assertEquals("mogw", sb.toString());
+ }
+}
diff --git a/luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java
deleted file mode 100644
index 822e37f..0000000
--- a/luni/src/test/java/libcore/java/lang/StringIndexOutOfBoundsExceptionTest.java
+++ /dev/null
@@ -1,47 +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 libcore.java.lang;
-
-import junit.framework.TestCase;
-
-public final class StringIndexOutOfBoundsExceptionTest extends TestCase {
- public void testCharAt() throws Exception {
- try {
- "hello".charAt(-1);
- fail();
- } catch (StringIndexOutOfBoundsException ex) {
- assertEquals("length=5; index=-1", ex.getMessage());
- }
-
- try {
- "hello".charAt(7);
- fail();
- } catch (StringIndexOutOfBoundsException ex) {
- assertEquals("length=5; index=7", ex.getMessage());
- }
- }
-
- public void testSubstring() throws Exception {
- try {
- "hello there".substring(9,14);
- fail();
- } catch (StringIndexOutOfBoundsException ex) {
- assertEquals("length=11; regionStart=9; regionLength=5",
- ex.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/lang/StringTest.java b/luni/src/test/java/libcore/java/lang/StringTest.java
index e16496b..bf162e5 100644
--- a/luni/src/test/java/libcore/java/lang/StringTest.java
+++ b/luni/src/test/java/libcore/java/lang/StringTest.java
@@ -174,7 +174,7 @@ public class StringTest extends TestCase {
/**
* Tests a widely assumed performance characteristic of String.substring():
- * that it reuses the original's backing array. Although behaviour should be
+ * that it reuses the original's backing array. Although behavior should be
* correct even if this test fails, many applications may suffer
* significant performance degradation.
*/
@@ -187,7 +187,7 @@ public class StringTest extends TestCase {
/**
* Tests a widely assumed performance characteristic of string's copy
* constructor: that it ensures the backing array is the same length as the
- * string. Although behaviour should be correct even if this test fails,
+ * string. Although behavior should be correct even if this test fails,
* many applications may suffer significant performance degradation.
*/
public void testStringCopiesAvoidHeapRetention() throws IllegalAccessException {
@@ -243,33 +243,43 @@ public class StringTest extends TestCase {
};
public void testCaseMapping_tr_TR() {
- Locale trTR = new Locale("tr", "TR");
- assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(trTR));
- assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(trTR));
- assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(trTR));
+ Locale tr_TR = new Locale("tr", "TR");
+ assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(tr_TR));
+ assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(tr_TR));
+ assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(tr_TR));
- assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(trTR));
- assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(trTR));
- assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_SMALL_I.toUpperCase(trTR));
+ assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(tr_TR));
+ assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(tr_TR));
+ assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_SMALL_I.toUpperCase(tr_TR));
- assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(trTR));
- assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_CAPITAL_I.toLowerCase(trTR));
+ assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(tr_TR));
+ assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_CAPITAL_I.toLowerCase(tr_TR));
}
public void testCaseMapping_en_US() {
- Locale enUs = new Locale("en", "US");
- assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_I.toUpperCase(enUs));
- assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(enUs));
- assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(enUs));
+ Locale en_US = new Locale("en", "US");
+ assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_I.toUpperCase(en_US));
+ assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(en_US));
+ assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(en_US));
- assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(enUs));
- assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I.toLowerCase(enUs));
- assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(enUs));
+ assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(en_US));
+ assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I.toLowerCase(en_US));
+ assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(en_US));
- assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(enUs));
+ assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(en_US));
// http://b/3325799: the RI fails this because it's using an obsolete version of the Unicode rules.
// Android correctly preserves canonical equivalence. (See the separate test for tr_TR.)
- assertEquals(LATIN_SMALL_I + COMBINING_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(enUs));
+ assertEquals(LATIN_SMALL_I + COMBINING_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(en_US));
+ }
+
+ public void testCaseMapping_el() {
+ Locale el_GR = new Locale("el", "GR");
+ assertEquals("ΟΔΟΣ ΟΔΟΣ ΣΟ ΣΟ OΣ ΟΣ Σ ΕΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(el_GR));
+ assertEquals("ΟΔΟΣ ΟΔΟΣ ΣΟ ΣΟ OΣ ΟΣ Σ ΕΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(el_GR));
+ assertEquals("ΟΔΟΣ ΟΔΟΣ ΣΟ ΣΟ OΣ ΟΣ Σ ΕΞ", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(el_GR));
+
+ Locale en_US = new Locale("en", "US");
+ assertEquals("ΟΔΌΣ ΟΔΌΣ ΣΟ ΣΟ OΣ ΟΣ Σ á¼Îž", "ΟΔΌΣ Οδός Σο ΣΟ oΣ ΟΣ σ ἕξ".toUpperCase(en_US));
}
public void testEqualsIgnoreCase_tr_TR() {
@@ -349,12 +359,88 @@ public class StringTest extends TestCase {
assertEquals("-*-w-*-o-*-r-*-l-*-d-*-", "hello world".substring(6).replace("", "-*-"));
}
- // http://b/11571917
public void test_String_getBytes() throws Exception {
+ // http://b/11571917
assertEquals("[-126, -96]", Arrays.toString("ã‚".getBytes("Shift_JIS")));
assertEquals("[-126, -87]", Arrays.toString("ã‹".getBytes("Shift_JIS")));
assertEquals("[-105, 67]", Arrays.toString("佑".getBytes("Shift_JIS")));
assertEquals("[36]", Arrays.toString("$".getBytes("Shift_JIS")));
assertEquals("[-29, -127, -117]", Arrays.toString("ã‹".getBytes("UTF-8")));
+
+ // http://b/11639117
+ assertEquals("[-79, -72, -70, -48]", Arrays.toString("구분".getBytes("EUC-KR")));
+
+
+ // https://code.google.com/p/android/issues/detail?id=63188
+ assertEquals("[-77, -10, -64, -76, -63, -53]", Arrays.toString("出æ¥äº†".getBytes("gbk")));
+ assertEquals("[-77, -10, -64, -76]", Arrays.toString("出æ¥".getBytes("gbk")));
+ assertEquals("[-77, -10]", Arrays.toString("出".getBytes("gbk")));
+ }
+
+ public void test_compareTo() throws Exception {
+ // For strings where a character differs, the result is
+ // the difference between the characters.
+ assertEquals(-1, "a".compareTo("b"));
+ assertEquals(-2, "a".compareTo("c"));
+ assertEquals(1, "b".compareTo("a"));
+ assertEquals(2, "c".compareTo("a"));
+
+ // For strings where the characters match up to the length of the shorter,
+ // the result is the difference between the strings' lengths.
+ assertEquals(0, "a".compareTo("a"));
+ assertEquals(-1, "a".compareTo("aa"));
+ assertEquals(-1, "a".compareTo("az"));
+ assertEquals(-2, "a".compareTo("aaa"));
+ assertEquals(-2, "a".compareTo("azz"));
+ assertEquals(-3, "a".compareTo("aaaa"));
+ assertEquals(-3, "a".compareTo("azzz"));
+ assertEquals(0, "a".compareTo("a"));
+ assertEquals(1, "aa".compareTo("a"));
+ assertEquals(1, "az".compareTo("a"));
+ assertEquals(2, "aaa".compareTo("a"));
+ assertEquals(2, "azz".compareTo("a"));
+ assertEquals(3, "aaaa".compareTo("a"));
+ assertEquals(3, "azzz".compareTo("a"));
+ }
+
+ public void test_compareToIgnoreCase() throws Exception {
+ // For strings where a character differs, the result is
+ // the difference between the characters.
+ assertEquals(-1, "a".compareToIgnoreCase("b"));
+ assertEquals(-1, "a".compareToIgnoreCase("B"));
+ assertEquals(-2, "a".compareToIgnoreCase("c"));
+ assertEquals(-2, "a".compareToIgnoreCase("C"));
+ assertEquals(1, "b".compareToIgnoreCase("a"));
+ assertEquals(1, "B".compareToIgnoreCase("a"));
+ assertEquals(2, "c".compareToIgnoreCase("a"));
+ assertEquals(2, "C".compareToIgnoreCase("a"));
+
+ // For strings where the characters match up to the length of the shorter,
+ // the result is the difference between the strings' lengths.
+ assertEquals(0, "a".compareToIgnoreCase("a"));
+ assertEquals(0, "a".compareToIgnoreCase("A"));
+ assertEquals(0, "A".compareToIgnoreCase("a"));
+ assertEquals(0, "A".compareToIgnoreCase("A"));
+ assertEquals(-1, "a".compareToIgnoreCase("aa"));
+ assertEquals(-1, "a".compareToIgnoreCase("aA"));
+ assertEquals(-1, "a".compareToIgnoreCase("Aa"));
+ assertEquals(-1, "a".compareToIgnoreCase("az"));
+ assertEquals(-1, "a".compareToIgnoreCase("aZ"));
+ assertEquals(-2, "a".compareToIgnoreCase("aaa"));
+ assertEquals(-2, "a".compareToIgnoreCase("AAA"));
+ assertEquals(-2, "a".compareToIgnoreCase("azz"));
+ assertEquals(-2, "a".compareToIgnoreCase("AZZ"));
+ assertEquals(-3, "a".compareToIgnoreCase("aaaa"));
+ assertEquals(-3, "a".compareToIgnoreCase("AAAA"));
+ assertEquals(-3, "a".compareToIgnoreCase("azzz"));
+ assertEquals(-3, "a".compareToIgnoreCase("AZZZ"));
+ assertEquals(1, "aa".compareToIgnoreCase("a"));
+ assertEquals(1, "aA".compareToIgnoreCase("a"));
+ assertEquals(1, "Aa".compareToIgnoreCase("a"));
+ assertEquals(1, "az".compareToIgnoreCase("a"));
+ assertEquals(2, "aaa".compareToIgnoreCase("a"));
+ assertEquals(2, "azz".compareToIgnoreCase("a"));
+ assertEquals(3, "aaaa".compareToIgnoreCase("a"));
+ assertEquals(3, "azzz".compareToIgnoreCase("a"));
}
}
diff --git a/luni/src/test/java/libcore/java/lang/SystemTest.java b/luni/src/test/java/libcore/java/lang/SystemTest.java
index f995954..ff155d3 100644
--- a/luni/src/test/java/libcore/java/lang/SystemTest.java
+++ b/luni/src/test/java/libcore/java/lang/SystemTest.java
@@ -16,14 +16,15 @@
package libcore.java.lang;
-import junit.framework.TestCase;
-
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Formatter;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicBoolean;
+import junit.framework.TestCase;
public class SystemTest extends TestCase {
@@ -33,11 +34,11 @@ public class SystemTest extends TestCase {
// use System.getProperty. Now they should use System.lineSeparator instead, and the
// "line.separator" property has no effect after the VM has started.
- // Test System.lineSeparator directly.
+ // Test that System.lineSeparator is not changed when the corresponding
+ // system property is changed.
assertEquals("\n", System.lineSeparator());
System.setProperty("line.separator", "poop");
assertEquals("\n", System.lineSeparator());
- assertFalse(System.lineSeparator().equals(System.getProperty("line.separator")));
// java.io.BufferedWriter --- uses System.lineSeparator on Android but not on RI.
StringWriter sw = new StringWriter();
@@ -45,23 +46,19 @@ public class SystemTest extends TestCase {
bw.newLine();
bw.flush();
assertEquals(System.lineSeparator(), sw.toString());
- assertFalse(System.lineSeparator().equals(System.getProperty("line.separator")));
// java.io.PrintStream --- uses System.lineSeparator on Android but not on RI.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new PrintStream(baos).println();
assertEquals(System.lineSeparator(), new String(baos.toByteArray(), "UTF-8"));
- assertFalse(System.lineSeparator().equals(System.getProperty("line.separator")));
// java.io.PrintWriter --- uses System.lineSeparator on Android but not on RI.
sw = new StringWriter();
new PrintWriter(sw).println();
assertEquals(System.lineSeparator(), sw.toString());
- assertFalse(System.lineSeparator().equals(System.getProperty("line.separator")));
// java.util.Formatter --- uses System.lineSeparator on both.
assertEquals(System.lineSeparator(), new Formatter().format("%n").toString());
- assertFalse(System.lineSeparator().equals(System.getProperty("line.separator")));
} finally {
System.setProperty("line.separator", "\n");
}
@@ -90,7 +87,7 @@ public class SystemTest extends TestCase {
System.arraycopy(new char[5], 0, new Object[5], 0, 3);
fail();
} catch (ArrayStoreException e) {
- assertEquals("char[] and java.lang.Object[] are incompatible array types", e.getMessage());
+ assertEquals("Incompatible types: src=char[], dst=java.lang.Object[]", e.getMessage());
}
}
@@ -118,4 +115,125 @@ public class SystemTest extends TestCase {
assertEquals("dst == null", e.getMessage());
}
}
+
+ /**
+ * System.arraycopy() must never copy objects into arrays that can't store
+ * them. We've had bugs where type checks and copying were done separately
+ * and racy code could defeat the type checks. http://b/5247258
+ */
+ public void testArrayCopyConcurrentModification() {
+ final AtomicBoolean done = new AtomicBoolean();
+
+ final Object[] source = new Object[1024 * 1024];
+ String[] target = new String[1024 * 1024];
+
+ new Thread() {
+ @Override public void run() {
+ // the last array element alternates between being a Thread and being null. When
+ // it's a Thread it isn't safe for arrayCopy; when its null it is!
+ while (!done.get()) {
+ source[source.length - 1] = this;
+ source[source.length - 1] = null;
+ }
+ }
+ }.start();
+
+ for (int i = 0; i < 8192; i++) {
+ try {
+ System.arraycopy(source, 0, target, 0, source.length);
+ assertNull(target[source.length - 1]); // make sure the wrong type didn't sneak in
+ } catch (ArrayStoreException ignored) {
+ }
+ }
+
+ done.set(true);
+ }
+
+ public void testSystemProperties_immutable() {
+ // Android-specific: The RI does not have a concept of immutable properties.
+
+ // user.dir is an immutable property
+ String userDir = System.getProperty("user.dir");
+ assertNotNull(userDir);
+ System.setProperty("user.dir", "not poop");
+ assertEquals(userDir, System.getProperty("user.dir"));
+
+ System.getProperties().setProperty("user.dir", "hmmph");
+ assertEquals(userDir, System.getProperty("user.dir"));
+
+ System.getProperties().clear();
+ assertEquals(userDir, System.getProperty("user.dir"));
+
+ Properties p = new Properties();
+ p.setProperty("user.dir", "meh");
+ System.setProperties(p);
+
+ assertEquals(userDir, System.getProperty("user.dir"));
+ }
+
+ public void testSystemProperties_mutable() {
+ // We allow "java.io.tmpdir" and "user.home" to be changed however
+ // we can't test for "java.io.tmpdir" consistently across test runners because
+ // it will be immutable if set on the dalvikvm command line "-Djava.io.tmpdir="
+ // like vogar does.
+ String oldUserHome = System.getProperty("user.home");
+ try {
+ System.setProperty("user.home", "/user/home");
+ assertEquals("/user/home", System.getProperty("user.home"));
+ } finally {
+ System.setProperty("user.home", oldUserHome);
+ }
+ }
+
+ public void testSystemProperties_setProperties_null() {
+ // user.dir is an immutable property
+ String userDir = System.getProperty("user.dir");
+ assertNotNull(userDir);
+
+ // Add a non-standard property
+ System.setProperty("p1", "v1");
+
+ // Reset using setProperties(null)
+ System.setProperties(null);
+
+ // All the immutable properties should be reset.
+ assertEquals(userDir, System.getProperty("user.dir"));
+ // Non-standard properties are cleared.
+ assertNull(System.getProperty("p1"));
+ }
+
+ public void testSystemProperties_setProperties_nonNull() {
+ String userDir = System.getProperty("user.dir");
+
+ Properties newProperties = new Properties();
+ // Immutable property
+ newProperties.setProperty("user.dir", "v1");
+ // Non-standard property
+ newProperties.setProperty("p1", "v2");
+
+ System.setProperties(newProperties);
+
+ // Android-specific: The RI makes the setProperties() argument the system properties object,
+ // Android makes a new Properties object and copies the properties.
+ assertNotSame(newProperties, System.getProperties());
+ // Android-specific: The RI does not have a concept of immutable properties.
+ assertEquals(userDir, System.getProperty("user.dir"));
+
+ assertEquals("v2", System.getProperty("p1"));
+ }
+
+ public void testSystemProperties_getProperties_clear() {
+ String userDir = System.getProperty("user.dir");
+ assertNotNull(userDir);
+ System.setProperty("p1", "v1");
+
+ Properties properties = System.getProperties();
+ assertEquals("v1", properties.getProperty("p1"));
+
+ properties.clear();
+
+ // Android-specific: The RI clears everything, Android resets to immutable defaults.
+ assertEquals(userDir, System.getProperty("user.dir"));
+ assertNull(System.getProperty("p1"));
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/ThreadTest.java b/luni/src/test/java/libcore/java/lang/ThreadTest.java
index 998afdb..8545a20 100644
--- a/luni/src/test/java/libcore/java/lang/ThreadTest.java
+++ b/luni/src/test/java/libcore/java/lang/ThreadTest.java
@@ -58,14 +58,71 @@ public final class ThreadTest extends TestCase {
assertTrue("Unstarted threads were never finalized!", finalizedThreadsCount.get() > 0);
}
- private Thread newThread(final AtomicInteger finalizedThreadsCount, final int size) {
- return new Thread() {
- byte[] memoryPressure = new byte[size];
- @Override protected void finalize() throws Throwable {
- super.finalize();
- finalizedThreadsCount.incrementAndGet();
- }
- };
+ public void testThreadSleep() throws Exception {
+ int millis = 1000;
+ long start = System.currentTimeMillis();
+
+ Thread.sleep(millis);
+
+ long elapsed = System.currentTimeMillis() - start;
+ long offBy = Math.abs(elapsed - millis);
+
+ assertTrue("Actual sleep off by " + offBy + " ms", offBy <= 250);
+ }
+
+ public void testThreadInterrupted() throws Exception {
+ Thread.currentThread().interrupt();
+ try {
+ Thread.sleep(0);
+ fail();
+ } catch (InterruptedException e) {
+ assertFalse(Thread.currentThread().isInterrupted());
+ }
+ }
+
+ public void testThreadSleepIllegalArguments() throws Exception {
+
+ try {
+ Thread.sleep(-1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ Thread.sleep(0, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ Thread.sleep(0, 1000000);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testThreadWakeup() throws Exception {
+ WakeupTestThread t1 = new WakeupTestThread();
+ WakeupTestThread t2 = new WakeupTestThread();
+
+ t1.start();
+ t2.start();
+ assertTrue("Threads already finished", !t1.done && !t2.done);
+
+ t1.interrupt();
+ t2.interrupt();
+
+ Thread.sleep(1000);
+ assertTrue("Threads did not finish", t1.done && t2.done);
+ }
+
+ public void testContextClassLoaderIsNotNull() {
+ assertNotNull(Thread.currentThread().getContextClassLoader());
+ }
+
+ public void testContextClassLoaderIsInherited() {
+ Thread other = new Thread();
+ assertSame(Thread.currentThread().getContextClassLoader(), other.getContextClassLoader());
}
/**
@@ -109,4 +166,30 @@ public final class ThreadTest extends TestCase {
// Expect to see the traces of all threads (not just t2)
assertTrue("Must have traces for all threads", visibleTraces.get() > 1);
}
+
+ private Thread newThread(final AtomicInteger finalizedThreadsCount, final int size) {
+ return new Thread() {
+ long[] memoryPressure = new long[size];
+ @Override protected void finalize() throws Throwable {
+ super.finalize();
+ finalizedThreadsCount.incrementAndGet();
+ }
+ };
+ }
+
+ private class WakeupTestThread extends Thread {
+ public boolean done;
+
+ public void run() {
+ done = false;
+
+ // Sleep for a while (1 min)
+ try {
+ Thread.sleep(60000);
+ } catch (InterruptedException ignored) {
+ }
+
+ done = true;
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java b/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java
index c23775e..4cc69ba 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/AnnotationsTest.java
@@ -16,6 +16,7 @@
package libcore.java.lang.reflect;
+import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
@@ -23,7 +24,11 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@@ -56,7 +61,13 @@ public final class AnnotationsTest extends TestCase {
public void testParameterAnnotations() throws Exception {
Method method = Type.class.getMethod("method", String.class, String.class);
- Annotation[][] parameterAnnotations = method.getParameterAnnotations();
+ Annotation[][] noParameterAnnotations = method.getParameterAnnotations();
+ assertEquals(2, noParameterAnnotations.length);
+ assertEquals(set(), annotationsToTypes(noParameterAnnotations[0]));
+ assertEquals(set(), annotationsToTypes(noParameterAnnotations[1]));
+
+ Method parameters = Type.class.getMethod("parameters", String.class, String.class);
+ Annotation[][] parameterAnnotations = parameters.getParameterAnnotations();
assertEquals(2, parameterAnnotations.length);
assertEquals(set(AnnotationB.class, AnnotationD.class),
annotationsToTypes(parameterAnnotations[0]));
@@ -64,6 +75,206 @@ public final class AnnotationsTest extends TestCase {
annotationsToTypes(parameterAnnotations[1]));
}
+ public void testAnnotationDefaults() throws Exception {
+ assertEquals((byte) 5, defaultValue("a"));
+ assertEquals((short) 6, defaultValue("b"));
+ assertEquals(7, defaultValue("c"));
+ assertEquals(8L, defaultValue("d"));
+ assertEquals(9.0f, defaultValue("e"));
+ assertEquals(10.0, defaultValue("f"));
+ assertEquals('k', defaultValue("g"));
+ assertEquals(true, defaultValue("h"));
+ assertEquals(Breakfast.WAFFLES, defaultValue("i"));
+ assertEquals("@" + AnnotationA.class.getName() + "()", defaultValue("j").toString());
+ assertEquals("maple", defaultValue("k"));
+ assertEquals(AnnotationB.class, defaultValue("l"));
+ assertEquals("[1, 2, 3]", Arrays.toString((int[]) defaultValue("m")));
+ assertEquals("[WAFFLES, PANCAKES]", Arrays.toString((Breakfast[]) defaultValue("n")));
+ assertEquals(null, defaultValue("o"));
+ assertEquals(null, defaultValue("p"));
+ }
+
+ private Object defaultValue(String name) throws NoSuchMethodException {
+ return HasDefaultsAnnotation.class.getMethod(name).getDefaultValue();
+ }
+
+ public void testGetEnclosingClass() {
+ assertNull(AnnotationsTest.class.getEnclosingClass());
+ assertEquals(AnnotationsTest.class, Foo.class.getEnclosingClass());
+ assertEquals(AnnotationsTest.class, HasMemberClassesInterface.class.getEnclosingClass());
+ assertEquals(HasMemberClassesInterface.class,
+ HasMemberClassesInterface.D.class.getEnclosingClass());
+ assertEquals(AnnotationsTest.class, Foo.class.getEnclosingClass());
+ }
+
+ public void testGetDeclaringClass() {
+ assertNull(AnnotationsTest.class.getDeclaringClass());
+ assertEquals(AnnotationsTest.class, Foo.class.getDeclaringClass());
+ assertEquals(AnnotationsTest.class, HasMemberClassesInterface.class.getDeclaringClass());
+ assertEquals(HasMemberClassesInterface.class,
+ HasMemberClassesInterface.D.class.getDeclaringClass());
+ }
+
+ public void testGetEnclosingClassIsTransitiveForClassesDefinedInAMethod() {
+ class C {}
+ assertEquals(AnnotationsTest.class, C.class.getEnclosingClass());
+ }
+
+ public void testGetDeclaringClassIsNotTransitiveForClassesDefinedInAMethod() {
+ class C {}
+ assertEquals(null, C.class.getDeclaringClass());
+ }
+
+ public void testGetEnclosingMethodIsNotTransitive() {
+ class C {
+ class D {}
+ }
+ assertEquals(null, C.D.class.getEnclosingMethod());
+ }
+
+ public void testStaticFieldAnonymousClass() {
+ // The class declared in the <clinit> is enclosed by the <clinit>'s class.
+ // http://b/11245138
+ assertEquals(AnnotationsTest.class, staticAnonymous.getClass().getEnclosingClass());
+ // However, because it is anonymous, it has no declaring class.
+ // https://code.google.com/p/android/issues/detail?id=61003
+ assertNull(staticAnonymous.getClass().getDeclaringClass());
+ // Because the class is declared in <clinit> which is not exposed through reflection,
+ // it has no enclosing method or constructor.
+ assertNull(staticAnonymous.getClass().getEnclosingMethod());
+ assertNull(staticAnonymous.getClass().getEnclosingConstructor());
+ }
+
+ public void testGetEnclosingMethodOfTopLevelClass() {
+ assertNull(AnnotationsTest.class.getEnclosingMethod());
+ }
+
+ public void testGetEnclosingConstructorOfTopLevelClass() {
+ assertNull(AnnotationsTest.class.getEnclosingConstructor());
+ }
+
+ public void testClassEnclosedByConstructor() throws Exception {
+ Foo foo = new Foo("string");
+ assertEquals(Foo.class, foo.c.getEnclosingClass());
+ assertEquals(Foo.class.getDeclaredConstructor(String.class),
+ foo.c.getEnclosingConstructor());
+ assertNull(foo.c.getEnclosingMethod());
+ assertNull(foo.c.getDeclaringClass());
+ }
+
+ public void testClassEnclosedByMethod() throws Exception {
+ Foo foo = new Foo();
+ foo.foo("string");
+ assertEquals(Foo.class, foo.c.getEnclosingClass());
+ assertNull(foo.c.getEnclosingConstructor());
+ assertEquals(Foo.class.getDeclaredMethod("foo", String.class),
+ foo.c.getEnclosingMethod());
+ assertNull(foo.c.getDeclaringClass());
+ }
+
+ public void testGetClasses() throws Exception {
+ // getClasses() doesn't include classes inherited from interfaces!
+ assertSetEquals(HasMemberClasses.class.getClasses(),
+ HasMemberClassesSuperclass.B.class, HasMemberClasses.H.class);
+ }
+
+ public void testGetDeclaredClasses() throws Exception {
+ assertSetEquals(HasMemberClasses.class.getDeclaredClasses(),
+ HasMemberClasses.G.class, HasMemberClasses.H.class, HasMemberClasses.I.class,
+ HasMemberClasses.J.class, HasMemberClasses.K.class, HasMemberClasses.L.class);
+ }
+
+ public void testConstructorGetExceptions() throws Exception {
+ assertSetEquals(HasThrows.class.getConstructor().getExceptionTypes(),
+ IOException.class, InvocationTargetException.class, IllegalStateException.class);
+ assertSetEquals(HasThrows.class.getConstructor(Void.class).getExceptionTypes());
+ }
+
+ public void testClassMethodGetExceptions() throws Exception {
+ assertSetEquals(HasThrows.class.getMethod("foo").getExceptionTypes(),
+ IOException.class, InvocationTargetException.class, IllegalStateException.class);
+ assertSetEquals(HasThrows.class.getMethod("foo", Void.class).getExceptionTypes());
+ }
+
+ public void testProxyMethodGetExceptions() throws Exception {
+ InvocationHandler emptyInvocationHandler = new InvocationHandler() {
+ @Override public Object invoke(Object proxy, Method method, Object[] args) {
+ return null;
+ }
+ };
+
+ Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class[] { ThrowsInterface.class }, emptyInvocationHandler);
+ assertSetEquals(proxy.getClass().getMethod("foo").getExceptionTypes(),
+ IOException.class, InvocationTargetException.class, IllegalStateException.class);
+ assertSetEquals(proxy.getClass().getMethod("foo", Void.class).getExceptionTypes());
+ }
+
+ public void testClassModifiers() {
+ int modifiers = AnnotationsTest.class.getModifiers();
+ assertTrue(Modifier.isPublic(modifiers));
+ assertFalse(Modifier.isProtected(modifiers));
+ assertFalse(Modifier.isPrivate(modifiers));
+ assertFalse(Modifier.isAbstract(modifiers));
+ assertFalse(Modifier.isStatic(modifiers));
+ assertTrue(Modifier.isFinal(modifiers));
+ assertFalse(Modifier.isStrict(modifiers));
+ }
+
+ public void testInnerClassModifiers() {
+ int modifiers = Foo.class.getModifiers();
+ assertFalse(Modifier.isPublic(modifiers));
+ assertFalse(Modifier.isProtected(modifiers));
+ assertTrue(Modifier.isPrivate(modifiers));
+ assertFalse(Modifier.isAbstract(modifiers));
+ assertTrue(Modifier.isStatic(modifiers));
+ assertFalse(Modifier.isFinal(modifiers));
+ assertFalse(Modifier.isStrict(modifiers));
+ }
+
+ public void testAnonymousClassModifiers() {
+ int modifiers = staticAnonymous.getClass().getModifiers();
+ assertFalse(Modifier.isPublic(modifiers));
+ assertFalse(Modifier.isProtected(modifiers));
+ assertFalse(Modifier.isPrivate(modifiers));
+ assertFalse(Modifier.isAbstract(modifiers));
+ assertTrue(Modifier.isStatic(modifiers));
+ assertFalse(Modifier.isFinal(modifiers));
+ assertFalse(Modifier.isStrict(modifiers));
+ }
+
+ public void testInnerClassName() {
+ assertEquals("AnnotationsTest", AnnotationsTest.class.getSimpleName());
+ assertEquals("Foo", Foo.class.getSimpleName());
+ assertEquals("", staticAnonymous.getClass().getSimpleName());
+ }
+
+ public void testIsAnonymousClass() {
+ assertFalse(AnnotationsTest.class.isAnonymousClass());
+ assertFalse(Foo.class.isAnonymousClass());
+ assertTrue(staticAnonymous.getClass().isAnonymousClass());
+ }
+
+ private static final Object staticAnonymous = new Object() {};
+
+ private static class Foo {
+ Class<?> c;
+ private Foo() {
+ }
+ private Foo(String s) {
+ c = new Object() {}.getClass();
+ }
+ private Foo(int i) {
+ c = new Object() {}.getClass();
+ }
+ private void foo(String s) {
+ c = new Object() {}.getClass();
+ }
+ private void foo(int i) {
+ c = new Object() {}.getClass();
+ }
+ }
+
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationA {}
@@ -81,12 +292,68 @@ public final class AnnotationsTest extends TestCase {
public static class Type {
@AnnotationA @AnnotationC public Type() {}
@AnnotationA @AnnotationD public String field;
- @AnnotationB @AnnotationC public void method(@AnnotationB @AnnotationD String parameter1,
+ @AnnotationB @AnnotationC public void method(String parameter1, String parameter2) {}
+ @AnnotationB @AnnotationC public void parameters(@AnnotationB @AnnotationD String parameter1,
@AnnotationC @AnnotationD String parameter2) {}
}
public static class ExtendsType extends Type {}
+ static enum Breakfast { WAFFLES, PANCAKES }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface HasDefaultsAnnotation {
+ byte a() default 5;
+ short b() default 6;
+ int c() default 7;
+ long d() default 8;
+ float e() default 9.0f;
+ double f() default 10.0;
+ char g() default 'k';
+ boolean h() default true;
+ Breakfast i() default Breakfast.WAFFLES;
+ AnnotationA j() default @AnnotationA();
+ String k() default "maple";
+ Class l() default AnnotationB.class;
+ int[] m() default { 1, 2, 3 };
+ Breakfast[] n() default { Breakfast.WAFFLES, Breakfast.PANCAKES };
+ Breakfast o();
+ int p();
+ }
+
+ static class HasMemberClassesSuperclass {
+ class A {}
+ public class B {}
+ static class C {}
+ }
+
+ public interface HasMemberClassesInterface {
+ class D {}
+ public class E {}
+ static class F {}
+ }
+
+ public static class HasMemberClasses extends HasMemberClassesSuperclass
+ implements HasMemberClassesInterface {
+ class G {}
+ public class H {}
+ static class I {}
+ enum J {}
+ interface K {}
+ @interface L {}
+ }
+
+ public static class HasThrows {
+ public HasThrows() throws IOException, InvocationTargetException, IllegalStateException {}
+ public HasThrows(Void v) {}
+ public void foo() throws IOException, InvocationTargetException, IllegalStateException {}
+ public void foo(Void v) {}
+ }
+
+ public static interface ThrowsInterface {
+ void foo() throws IOException, InvocationTargetException, IllegalStateException;
+ void foo(Void v);
+ }
private void assertAnnotatedElement(
AnnotatedElement element, Class<? extends Annotation>... expectedAnnotations) {
@@ -134,4 +401,10 @@ public final class AnnotationsTest extends TestCase {
private <T> Set<T> set(T... instances) {
return new HashSet<T>(Arrays.asList(instances));
}
+
+ private void assertSetEquals(Object[] actual, Object... expected) {
+ Set<Object> actualSet = new HashSet<Object>(Arrays.asList(actual));
+ Set<Object> expectedSet = new HashSet<Object>(Arrays.asList(expected));
+ assertEquals(expectedSet, actualSet);
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java b/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java
index 2e15de2..28fd7e9 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java
@@ -124,6 +124,28 @@ public final class ClassLoaderReflectionTest extends TestCase {
assertParameterizedType(types[1], List.class, aClass);
}
+ public void testClassesOfDifferentClassLoadersAreNotEqual() throws Exception {
+ assertFalse(A.class.equals(aClass));
+ }
+
+ public void testConstructorsOfDifferentClassLoadersAreNotEqual() throws Exception {
+ Constructor<?> c1 = A.class.getDeclaredConstructor();
+ Constructor<?> c2 = aClass.getDeclaredConstructor();
+ assertFalse(c1.equals(c2));
+ }
+
+ public void testMethodsOfDifferentClassLoadersAreNotEqual() throws Exception {
+ Method m1 = E.class.getMethod("call");
+ Method m2 = eClass.getMethod("call");
+ assertFalse(m1.equals(m2));
+ }
+
+ public void testFieldsOfDifferentClassLoadersAreNotEqual() throws Exception {
+ Field f1 = B.class.getDeclaredField("field");
+ Field f2 = bClass.getDeclaredField("field");
+ assertFalse(f1.equals(f2));
+ }
+
static class A {}
static class B<T> {
T field;
diff --git a/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java b/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java
index ed98794..51ddfc0 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/ConstructorTest.java
@@ -72,6 +72,24 @@ public final class ConstructorTest extends TestCase {
assertEquals(2, constructor.getParameterTypes().length);
}
+ public void testEqualConstructorEqualsAndHashCode() throws Exception {
+ Constructor<?> c1 = ConstructorTestHelper.class.getConstructor();
+ Constructor<?> c2 = ConstructorTestHelper.class.getConstructor();
+ assertEquals(c1, c2);
+ assertEquals(c1.hashCode(), c2.hashCode());
+ }
+
+ public void testHashCodeSpec() throws Exception {
+ Constructor<?> c1 = ConstructorTestHelper.class.getConstructor();
+ assertEquals(ConstructorTestHelper.class.getName().hashCode(), c1.hashCode());
+ }
+
+ public void testDifferentConstructorEqualsAndHashCode() throws Exception {
+ Constructor<?> c1 = ConstructorTestHelper.class.getConstructor();
+ Constructor<?> c2 = ConstructorTestHelper.class.getConstructor(Object.class);
+ assertFalse(c1.equals(c2));
+ }
+
static class ConstructorTestHelper {
public ConstructorTestHelper() throws IndexOutOfBoundsException { }
public ConstructorTestHelper(Object o) { }
diff --git a/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java b/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java
index eb3d034..b60d984 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/FieldTest.java
@@ -27,4 +27,27 @@ public final class FieldTest extends TestCase {
Field field = getClass().getDeclaredField("MY_LONG");
assertEquals(5073258162644648461L, field.getLong(null));
}
+
+ public void testEqualConstructorEqualsAndHashCode() throws Exception {
+ Field f1 = FieldTestHelper.class.getField("a");
+ Field f2 = FieldTestHelper.class.getField("a");
+ assertEquals(f1, f2);
+ assertEquals(f1.hashCode(), f2.hashCode());
+ }
+
+ public void testHashCodeSpec() throws Exception {
+ Field f1 = FieldTestHelper.class.getField("a");
+ assertEquals(FieldTestHelper.class.getName().hashCode() ^ "a".hashCode(), f1.hashCode());
+ }
+
+ public void testDifferentConstructorEqualsAndHashCode() throws Exception {
+ Field f1 = FieldTestHelper.class.getField("a");
+ Field f2 = FieldTestHelper.class.getField("b");
+ assertFalse(f1.equals(f2));
+ }
+
+ static class FieldTestHelper {
+ public String a;
+ public Object b;
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java b/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java
index ef30eb8..c3a436c 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java
@@ -20,42 +20,6 @@ import java.lang.reflect.Method;
import junit.framework.TestCase;
public final class MethodTest extends TestCase {
- // Check that the VM gives useful detail messages.
- public void test_invokeExceptions() throws Exception {
- Method m = String.class.getMethod("charAt", int.class);
- try {
- m.invoke("hello"); // Wrong number of arguments.
- fail();
- } catch (IllegalArgumentException iae) {
- assertEquals("wrong number of arguments; expected 1, got 0", iae.getMessage());
- }
- try {
- m.invoke("hello", "world"); // Wrong type.
- fail();
- } catch (IllegalArgumentException iae) {
- assertEquals("argument 1 should have type int, got java.lang.String", iae.getMessage());
- }
- try {
- m.invoke("hello", (Object) null); // Null for a primitive argument.
- fail();
- } catch (IllegalArgumentException iae) {
- assertEquals("argument 1 should have type int, got null", iae.getMessage());
- }
- try {
- m.invoke(new Integer(5)); // Wrong type for 'this'.
- fail();
- } catch (IllegalArgumentException iae) {
- assertEquals("expected receiver of type java.lang.String, but got java.lang.Integer", iae.getMessage());
- }
- try {
- m.invoke(null); // Null for 'this'.
- fail();
- } catch (NullPointerException npe) {
- assertEquals("expected receiver of type java.lang.String, but got null",
- npe.getMessage());
- }
- }
-
public void test_getExceptionTypes() throws Exception {
Method method = MethodTestHelper.class.getMethod("m1", new Class[0]);
Class[] exceptions = method.getExceptionTypes();
@@ -197,6 +161,26 @@ public final class MethodTest extends TestCase {
assertEquals(anonymous.getClass(), method.getDeclaringClass());
}
+ public void testEqualMethodEqualsAndHashCode() throws Exception {
+ Method m1 = MethodTestHelper.class.getMethod("m1");
+ Method m2 = MethodTestHelper.class.getMethod("m1");
+ assertEquals(m1, m2);
+ assertEquals(m1.hashCode(), m2.hashCode());
+ assertEquals(MethodTestHelper.class.getName().hashCode() ^ "m1".hashCode(), m1.hashCode());
+ }
+
+ public void testHashCodeSpec() throws Exception {
+ Method m1 = MethodTestHelper.class.getMethod("m1");
+ assertEquals(MethodTestHelper.class.getName().hashCode() ^ "m1".hashCode(), m1.hashCode());
+ }
+
+ public void testDifferentMethodEqualsAndHashCode() throws Exception {
+ Method m1 = MethodTestHelper.class.getMethod("m1");
+ Method m2 = MethodTestHelper.class.getMethod("m2", Object.class);
+ assertFalse(m1.equals(m2));
+ assertFalse(m1.hashCode() == m2.hashCode());
+ }
+
// http://b/1045939
public void testMethodToString() throws Exception {
assertEquals("public final native void java.lang.Object.notify()",
diff --git a/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java b/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java
index 168a00d..ad3cc06 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java
@@ -16,12 +16,12 @@
package libcore.java.lang.reflect;
+import org.apache.harmony.tests.java.lang.reflect.GenericReflectionTestsBase;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
-import tests.api.java.lang.reflect.GenericReflectionTestsBase;
/**
* Tests generic reflection in more complicated cases. In particular: Scoping of
diff --git a/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java b/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java
index 69eff4f..9dec794 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java
@@ -21,7 +21,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
-import tests.api.java.lang.reflect.GenericReflectionTestsBase;
+import org.apache.harmony.tests.java.lang.reflect.GenericReflectionTestsBase;
/**
diff --git a/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java b/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java
index 30d47fb..abd5851 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/ProxyTest.java
@@ -16,14 +16,25 @@
package libcore.java.lang.reflect;
+import java.io.EOFException;
+import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.net.SocketException;
import junit.framework.TestCase;
import tests.util.ClassLoaderBuilder;
public final class ProxyTest extends TestCase {
+ private final ClassLoader loader = getClass().getClassLoader();
+ private final InvocationHandler returnHandler = new TestInvocationHandler();
+ private final InvocationHandler throwHandler = new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ throw (Throwable) args[0];
+ }
+ };
/**
* Make sure the proxy's class loader fails if it cannot see the class
@@ -36,7 +47,7 @@ public final class ProxyTest extends TestCase {
Class[] interfacesA = { loaderA.loadClass(prefix + "$Echo") };
try {
- Proxy.newProxyInstance(loaderB, interfacesA, new TestInvocationHandler());
+ Proxy.newProxyInstance(loaderB, interfacesA, returnHandler);
fail();
} catch (IllegalArgumentException expected) {
}
@@ -55,10 +66,331 @@ public final class ProxyTest extends TestCase {
assertEquals("foo", proxy.getClass().getMethod("echo", String.class).invoke(proxy, "foo"));
}
+ public void testIncompatibleReturnTypesPrimitiveAndPrimitive() {
+ try {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsInt.class, ReturnsFloat.class},
+ returnHandler);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testIncompatibleReturnTypesPrimitiveAndWrapper() {
+ try {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsInt.class, ReturnsInteger.class},
+ returnHandler);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testIncompatibleReturnTypesPrimitiveAndVoid() {
+ try {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsInt.class, ReturnsVoid.class},
+ returnHandler);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testIncompatibleReturnTypesIncompatibleObjects() {
+ try {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsInteger.class, ReturnsString.class },
+ returnHandler);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testCompatibleReturnTypesImplementedInterface() {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsString.class, ReturnsCharSequence.class},
+ returnHandler);
+ Proxy.newProxyInstance(loader, new Class[]{ReturnsObject.class, ReturnsCharSequence.class,
+ ReturnsString.class}, returnHandler);
+ Proxy.newProxyInstance(loader, new Class[]{ReturnsObject.class, ReturnsCharSequence.class,
+ ReturnsString.class, ReturnsSerializable.class, ReturnsComparable.class},
+ returnHandler);
+ }
+
+
+ public void testCompatibleReturnTypesSuperclass() {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsString.class, ReturnsObject.class},
+ returnHandler);
+ }
+
+ public void testDeclaredExceptionIntersectionIsSubtype() throws Exception {
+ ThrowsIOException instance = (ThrowsIOException) Proxy.newProxyInstance(loader,
+ new Class[] {ThrowsIOException.class, ThrowsEOFException.class},
+ throwHandler);
+ try {
+ instance.run(new EOFException());
+ fail();
+ } catch (EOFException expected) {
+ }
+ try {
+ instance.run(new IOException());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ try {
+ instance.run(new Exception());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ }
+
+ public void testDeclaredExceptionIntersectionIsEmpty() throws Exception {
+ ThrowsEOFException instance = (ThrowsEOFException) Proxy.newProxyInstance(loader,
+ new Class[] {ThrowsSocketException.class, ThrowsEOFException.class},
+ throwHandler);
+ try {
+ instance.run(new EOFException());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ try {
+ instance.run(new SocketException());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ }
+
+ public void testDeclaredExceptionIntersectionIsSubset() throws Exception {
+ ThrowsEOFException instance = (ThrowsEOFException) Proxy.newProxyInstance(loader,
+ new Class[] {ThrowsEOFException.class, ThrowsSocketExceptionAndEOFException.class},
+ throwHandler);
+ try {
+ instance.run(new EOFException());
+ fail();
+ } catch (EOFException expected) {
+ }
+ try {
+ instance.run(new SocketException());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ try {
+ instance.run(new IOException());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ }
+
+ public void testDeclaredExceptionIntersectedByExactReturnTypes() throws Exception {
+ ThrowsIOException instance = (ThrowsIOException) Proxy.newProxyInstance(loader,
+ new Class[] {ThrowsIOException.class, ThrowsEOFExceptionReturnsString.class},
+ throwHandler);
+ try {
+ instance.run(new EOFException());
+ fail();
+ } catch (EOFException expected) {
+ }
+ try {
+ instance.run(new IOException());
+ fail();
+ } catch (IOException expected) {
+ }
+ try {
+ ((ThrowsEOFExceptionReturnsString) instance).run(new EOFException());
+ fail();
+ } catch (EOFException expected) {
+ }
+ try {
+ ((ThrowsEOFExceptionReturnsString) instance).run(new IOException());
+ fail();
+ } catch (UndeclaredThrowableException expected) {
+ }
+ }
+
+ public void test_getProxyClass_nullInterfaces() {
+ try {
+ Proxy.getProxyClass(loader, new Class<?>[] { null });
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ Proxy.getProxyClass(loader, Echo.class, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_getProxyClass_duplicateInterfaces() {
+ try {
+ Proxy.getProxyClass(loader, Echo.class, Echo.class);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_getProxyClass_caching() throws Exception {
+ Class<?> proxy1 = Proxy.getProxyClass(loader, Echo.class, ReturnsInt.class);
+ Class<?> proxy2 = Proxy.getProxyClass(loader, Echo.class, ReturnsInt.class);
+ Class<?> proxy3 = Proxy.getProxyClass(loader, ReturnsInt.class, Echo.class);
+
+ assertSame(proxy1, proxy2);
+ assertTrue(!proxy2.equals(proxy3));
+ }
+
+ public void testMethodsImplementedByFarIndirectInterface() {
+ ExtendsExtendsDeclaresFiveMethods instance = (ExtendsExtendsDeclaresFiveMethods)
+ Proxy.newProxyInstance(loader, new Class[]{ExtendsExtendsDeclaresFiveMethods.class},
+ returnHandler);
+ assertEquals("foo", instance.a("foo"));
+ assertEquals(0x12345678, instance.b(0x12345678));
+ assertEquals(Double.MIN_VALUE, instance.c(Double.MIN_VALUE));
+ assertEquals(null, instance.d(null));
+ assertEquals(0x1234567890abcdefL, instance.e(0x1234567890abcdefL));
+ }
+
+ public void testEquals() {
+ InvocationHandler handler = new InvocationHandler() {
+ @Override public Object invoke(Object proxy, Method method, Object[] args) {
+ return args[0] == ProxyTest.class; // bogus as equals(), but good for testing
+ }
+ };
+ Echo instance = (Echo) Proxy.newProxyInstance(loader, new Class[]{Echo.class}, handler);
+ assertTrue(instance.equals(ProxyTest.class));
+ assertFalse(instance.equals(new Object()));
+ assertFalse(instance.equals(instance));
+ assertFalse(instance.equals(null));
+ }
+
+ public void testHashCode() {
+ InvocationHandler handler = new InvocationHandler() {
+ @Override public Object invoke(Object proxy, Method method, Object[] args) {
+ return 0x12345678;
+ }
+ };
+ Echo instance = (Echo) Proxy.newProxyInstance(loader, new Class[]{Echo.class}, handler);
+ assertEquals(0x12345678, instance.hashCode());
+ }
+
+ public void testToString() {
+ InvocationHandler handler = new InvocationHandler() {
+ @Override public Object invoke(Object proxy, Method method, Object[] args) {
+ return "foo";
+ }
+ };
+ Echo instance = (Echo) Proxy.newProxyInstance(loader, new Class[]{Echo.class}, handler);
+ assertEquals("foo", instance.toString());
+ }
+
+ public void testReturnTypeDoesNotSatisfyAllConstraintsWithLenientCaller() {
+ InvocationHandler handler = new InvocationHandler() {
+ @Override public Object invoke(Object proxy, Method method, Object[] args) {
+ assertEquals(Object.class, method.getReturnType());
+ return Boolean.TRUE; // not the right type for 'ReturnsString' callers
+ }
+ };
+ ReturnsObject returnsObject = (ReturnsObject) Proxy.newProxyInstance(loader,
+ new Class[] {ReturnsString.class, ReturnsObject.class}, handler);
+ assertEquals(true, returnsObject.foo());
+ }
+
+ public void testReturnTypeDoesNotSatisfyAllConstraintsWithStrictCaller() {
+ InvocationHandler handler = new InvocationHandler() {
+ @Override public Object invoke(Object proxy, Method method, Object[] args) {
+ assertEquals(String.class, method.getReturnType());
+ return Boolean.TRUE; // not the right type for 'ReturnsString' callers
+ }
+ };
+ ReturnsString returnsString = (ReturnsString) Proxy.newProxyInstance(loader,
+ new Class[] {ReturnsString.class, ReturnsObject.class}, handler);
+ try {
+ returnsString.foo();
+ fail();
+ } catch (ClassCastException expected) {
+ }
+ }
+
+ public void testReturnsTypeAndInterfaceNotImplementedByThatType() {
+ try {
+ Proxy.newProxyInstance(loader, new Class[] {ReturnsString.class, ReturnsEcho.class},
+ returnHandler);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
public interface Echo {
String echo(String s);
}
+ public interface ReturnsInt {
+ int foo();
+ }
+
+ public interface ReturnsFloat {
+ float foo();
+ }
+
+ public interface ReturnsInteger {
+ Integer foo();
+ }
+
+ public interface ReturnsString {
+ String foo();
+ }
+
+ public interface ReturnsCharSequence {
+ CharSequence foo();
+ }
+
+ public interface ReturnsSerializable {
+ CharSequence foo();
+ }
+
+ public interface ReturnsComparable {
+ CharSequence foo();
+ }
+
+ public interface ReturnsObject {
+ Object foo();
+ }
+
+ public interface ReturnsVoid {
+ void foo();
+ }
+
+ public interface ReturnsEcho {
+ Echo foo();
+ }
+
+ public interface ThrowsIOException {
+ Object run(Throwable toThrow) throws IOException;
+ }
+
+ public interface ThrowsEOFException {
+ Object run(Throwable toThrow) throws EOFException;
+ }
+
+ public interface ThrowsEOFExceptionReturnsString {
+ String run(Throwable toThrow) throws EOFException;
+ }
+
+ public interface ThrowsSocketException {
+ Object run(Throwable toThrow) throws SocketException;
+
+ }
+ public interface ThrowsSocketExceptionAndEOFException {
+ Object run(Throwable toThrow) throws SocketException, EOFException;
+
+ }
+
+ public interface DeclaresFiveMethods {
+ String a(String a);
+ int b(int b);
+ double c(double c);
+ Object d(Object d);
+ long e(long e);
+ }
+ public interface ExtendsDeclaresFiveMethods extends DeclaresFiveMethods {
+ }
+ public interface ExtendsExtendsDeclaresFiveMethods extends ExtendsDeclaresFiveMethods {
+ }
+
public static class TestInvocationHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return args[0];
diff --git a/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java b/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java
index cdce405..1950bf3 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/ReflectionTest.java
@@ -24,6 +24,8 @@ import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
+import java.util.AbstractCollection;
+import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -37,6 +39,27 @@ public final class ReflectionTest extends TestCase {
String classB = "libcore.java.lang.reflect.ReflectionTest$B";
String classC = "libcore.java.lang.reflect.ReflectionTest$C";
+ public void testClassGetSuperclass() {
+ assertEquals(AbstractList.class, ArrayList.class.getSuperclass());
+ assertEquals(AbstractCollection.class, AbstractList.class.getSuperclass());
+ assertEquals(AbstractCollection.class, AbstractList.class.getSuperclass());
+ assertEquals(Object.class, AbstractCollection.class.getSuperclass());
+ assertNull(Object.class.getSuperclass());
+ }
+
+ public void testPrimitiveGetSuperclass() {
+ assertNull(boolean.class.getSuperclass());
+ assertNull(int.class.getSuperclass());
+ assertNull(double.class.getSuperclass());
+ assertNull(void.class.getSuperclass());
+ }
+
+ public void testInterfaceGetSuperclass() {
+ assertNull(Comparable.class.getSuperclass());
+ assertNull(DefinesMember.class.getSuperclass());
+ assertNull(ExtendsDefinesMember.class.getSuperclass());
+ }
+
/**
* http://code.google.com/p/android/issues/detail?id=6636
*/
@@ -277,6 +300,36 @@ public final class ReflectionTest extends TestCase {
assertEquals(1, count(names(fields), "field"));
}
+ public void testIsLocalClass() {
+ A methodLevelAnonymous = new A() {};
+ class Local {}
+ class $Local$1 {}
+ assertFalse(ReflectionTest.class.isLocalClass());
+ assertFalse(A.class.isLocalClass());
+ assertFalse($Dollar$1.class.isLocalClass());
+ assertFalse(CLASS_LEVEL_ANONYMOUS.getClass().isLocalClass());
+ assertFalse(methodLevelAnonymous.getClass().isLocalClass());
+ assertTrue(Local.class.isLocalClass());
+ assertTrue($Local$1.class.isLocalClass());
+ assertFalse(int.class.isLocalClass());
+ assertFalse(Object.class.isLocalClass());
+ }
+
+ public void testIsAnonymousClass() {
+ A methodLevelAnonymous = new A() {};
+ class Local {}
+ class $Local$1 {}
+ assertFalse(ReflectionTest.class.isAnonymousClass());
+ assertFalse(A.class.isAnonymousClass());
+ assertFalse($Dollar$1.class.isAnonymousClass());
+ assertTrue(CLASS_LEVEL_ANONYMOUS.getClass().isAnonymousClass());
+ assertTrue(methodLevelAnonymous.getClass().isAnonymousClass());
+ assertFalse(Local.class.isAnonymousClass());
+ assertFalse($Local$1.class.isAnonymousClass());
+ assertFalse(int.class.isAnonymousClass());
+ assertFalse(Object.class.isAnonymousClass());
+ }
+
/**
* Class.isEnum() erroneously returned true for indirect descendants of
* Enum. http://b/1062200.
@@ -299,8 +352,10 @@ public final class ReflectionTest extends TestCase {
assertNull(greenClass.getEnumConstants());
}
+ static class $Dollar$1 {}
static class A {}
static class AList extends ArrayList<A> {}
+ static A CLASS_LEVEL_ANONYMOUS = new A() {};
static class B extends Exception {}
diff --git a/luni/src/test/java/libcore/java/math/BigIntegerTest.java b/luni/src/test/java/libcore/java/math/BigIntegerTest.java
index 15a0dad..58c68a1 100644
--- a/luni/src/test/java/libcore/java/math/BigIntegerTest.java
+++ b/luni/src/test/java/libcore/java/math/BigIntegerTest.java
@@ -156,4 +156,32 @@ public class BigIntegerTest extends junit.framework.TestCase {
assertTrue(b.isProbablePrime(100));
}
}
+
+ public void test_negativeValues_superfluousZeros() throws Exception {
+ byte[] trimmedBytes = new byte[] {
+ (byte) 0xae, (byte) 0x0f, (byte) 0xa1, (byte) 0x93
+ };
+ byte[] extraZeroesBytes = new byte[] {
+ (byte) 0xff, (byte) 0xae, (byte) 0x0f, (byte) 0xa1, (byte) 0x93
+ };
+
+ BigInteger trimmed = new BigInteger(trimmedBytes);
+ BigInteger extraZeroes = new BigInteger(extraZeroesBytes);
+
+ assertEquals(trimmed, extraZeroes);
+ }
+
+ public void test_positiveValues_superfluousZeros() throws Exception {
+ byte[] trimmedBytes = new byte[] {
+ (byte) 0x2e, (byte) 0x0f, (byte) 0xa1, (byte) 0x93
+ };
+ byte[] extraZeroesBytes = new byte[] {
+ (byte) 0x00, (byte) 0x2e, (byte) 0x0f, (byte) 0xa1, (byte) 0x93
+ };
+
+ BigInteger trimmed = new BigInteger(trimmedBytes);
+ BigInteger extraZeroes = new BigInteger(extraZeroesBytes);
+
+ assertEquals(trimmed, extraZeroes);
+ }
}
diff --git a/luni/src/test/java/libcore/java/math/CSVTest.java b/luni/src/test/java/libcore/java/math/CSVTest.java
new file mode 100644
index 0000000..9e151c3
--- /dev/null
+++ b/luni/src/test/java/libcore/java/math/CSVTest.java
@@ -0,0 +1,88 @@
+package libcore.java.math;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Standard single-input test framework for csv math tests
+ */
+public abstract class CSVTest extends junit.framework.TestCase {
+ /*
+ * csv file should have the following format:
+ * function,expected_output,input,extra_info
+ * e.g. cos,-0x1.0000000000000p+0,0x1.921fb54442d18p+1,cos(pi)
+ * for two input: function,expected_output,input1,input2,extra
+ * vogar classpath: obj/JAVA_LIBRARIES/core-tests-support_intermediates/javalib.jar
+ */
+
+ /**
+ * This is a set of functions in java.Math/StrictMath that take two inputs.
+ * These functions will call run2InputTest; others will call runTest.
+ */
+ protected static final Set<String> twoInputFunctions;
+ static {
+ Set<String> twoInFunc = new HashSet<String>();
+ twoInFunc.add("atan2");
+ twoInFunc.add("copySign");
+ twoInFunc.add("hypot");
+ twoInFunc.add("IEEEremainder");
+ twoInFunc.add("max");
+ twoInFunc.add("min");
+ twoInFunc.add("nextAfter");
+ twoInFunc.add("pow");
+ twoInFunc.add("scalb");
+ twoInputFunctions = Collections.unmodifiableSet(twoInFunc);
+ }
+
+ void TestCSVInputs(String[] csvFileNames) throws Exception {
+ int totalTests = 0;
+ for (String csvFileName : csvFileNames) {
+ String line = "";
+ BufferedReader br = null;
+
+ try {
+ br = new BufferedReader(new InputStreamReader(
+ getClass().getResourceAsStream(csvFileName)));
+ while ((line = br.readLine()) != null) {
+ if (line.charAt(0) != '#') {
+ String[] testCase = line.split(",");
+ runTest(testCase);
+ totalTests++;
+ }
+ }
+ } finally {
+ if (br != null) {
+ br.close();
+ }
+ }
+ }
+ System.out.println("Completed running " + totalTests + " tests");
+ }
+
+ protected void runTest(String[] testCase) throws Exception {
+ String function = testCase[0];
+ double expectedOutput = Double.parseDouble(testCase[1]);
+ double input = Double.parseDouble(testCase[2]);
+ String extra = "";
+ if (twoInputFunctions.contains(function)) {
+ double input2 = Double.parseDouble(testCase[3]);
+ if (testCase.length > 4) {
+ extra = testCase[4];
+ }
+ run2InputTest(function, expectedOutput, input, input2, extra);
+ } else {
+ if (testCase.length > 3) {
+ extra = testCase[3];
+ }
+ runTest(function, expectedOutput, input, extra);
+ }
+ }
+
+ abstract void runTest(String func, double expectedOutput, double input,
+ String extra) throws Exception;
+
+ abstract void run2InputTest(String func, double expectedOutput, double input1, double input2, String extra) throws Exception;
+} \ No newline at end of file
diff --git a/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java b/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java
index 8f01a17..4823798 100644
--- a/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java
+++ b/luni/src/test/java/libcore/java/math/OldBigDecimalConvertTest.java
@@ -251,10 +251,6 @@ public class OldBigDecimalConvertTest extends TestCase {
assertTrue("incorrect byteValue", i == bNumber);
}
- /**
- * @test java.math.BigDecimal#byteValue() Convert negative BigDesimal to
- * byte type
- */
public void test_ByteValueNeg() {
String sNumber = "-127.56789";
int iNumber = -128;
diff --git a/luni/src/test/java/libcore/java/math/RunCSVTests.java b/luni/src/test/java/libcore/java/math/RunCSVTests.java
new file mode 100644
index 0000000..0c107f1
--- /dev/null
+++ b/luni/src/test/java/libcore/java/math/RunCSVTests.java
@@ -0,0 +1,109 @@
+package libcore.java.math;
+
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Tests functions in java.lang.Math
+ * Looks for the filenames in csvFileNames in tests/resources
+ * Tests functions and numbers found in those files.
+ * Run: vogar --classpath out/target/common/obj/JAVA_LIBRARIES/core-tests-support_intermediates/javalib.jar
+ * libcore/luni/src/test/java/libcore/java/math/RunCSVTests.java
+ */
+public class RunCSVTests extends CSVTest {
+ /** Stores ulps of error allowed for each function, if not 1 ulp.*/
+ private static final Map<String, Double> UlpMap;
+ static {
+ final HashMap<String, Double> funcUlps = new HashMap<String, Double>();
+ funcUlps.put("sinh", 2.5);
+ funcUlps.put("cosh", 2.5);
+ funcUlps.put("tanh", 2.5);
+ funcUlps.put("abs", 0.0);
+ funcUlps.put("signum", 0.0);
+ funcUlps.put("getExponent", 0.0);
+ funcUlps.put("toRadians", 0.0);
+ funcUlps.put("toDegrees", 0.0);
+ funcUlps.put("sqrt", 0.0);
+ funcUlps.put("ceil", 0.0);
+ funcUlps.put("floor", 0.0);
+ funcUlps.put("rint", 0.0);
+ funcUlps.put("atan2", 2.0);
+ funcUlps.put("round", 0.0);
+ funcUlps.put("max", 0.0);
+ funcUlps.put("min", 0.0);
+ funcUlps.put("copySign", 0.0);
+ funcUlps.put("nextAfter", 0.0);
+ funcUlps.put("scalb", 0.0);
+ UlpMap = Collections.unmodifiableMap(funcUlps);
+ }
+
+ public static final String[] csvFileNames = { "/math_tests.csv",
+ "/math_important_numbers.csv", "/math_java_only.csv" };
+
+ public void test_csv() throws Exception {
+ this.TestCSVInputs(csvFileNames);
+ }
+
+ /**
+ * Runs a standard single-input test using assertEquals.
+ * Allows error based on UlpMap, but defaults to 1 ulp.
+ */
+ @Override
+ void runTest(String func, double expectedOutput, double input, String extra)
+ throws Exception {
+ Class<Math> mathClass = Math.class;
+ Method m = mathClass.getMethod(func, new Class[] { Double.TYPE });
+ Object returnValue = m.invoke(null, input);
+
+ double allowedError;
+ if (UlpMap.containsKey(func)) {
+ allowedError = UlpMap.get(func)*Math.ulp(expectedOutput);
+ } else {
+ allowedError = Math.ulp(expectedOutput);
+ }
+
+ try {
+ assertEquals(extra + ": " + m + ": " + input + ": ", expectedOutput,
+ (double) returnValue, allowedError);
+ } catch (ClassCastException e) {
+ assertEquals(extra + ": " + m + ": " + input + ": ", (int) expectedOutput,
+ (int) returnValue, allowedError);
+ }
+ }
+
+ /**
+ * Runs a 2-input test using assertEquals.
+ * Allows error based on UlpMap, but defaults to 1 ulp.
+ */
+ @Override
+ void run2InputTest(String func, double expectedOutput, double input1,
+ double input2, String extra) throws Exception {
+ Class<Math> mathClass = Math.class;
+ Method m;
+ Object returnValue;
+ if (func.equals("scalb")) {
+ m = mathClass.getMethod(func, new Class[] { Double.TYPE, Integer.TYPE });
+ returnValue = m.invoke(null, input1, (int) input2);
+ } else {
+ m = mathClass.getMethod(func, new Class[] { Double.TYPE, Double.TYPE });
+ returnValue = m.invoke(null, input1, input2);
+ }
+
+ double allowedError;
+ if (UlpMap.containsKey(func)) {
+ allowedError = UlpMap.get(func)*Math.ulp(expectedOutput);
+ } else {
+ allowedError = Math.ulp(expectedOutput);
+ }
+
+ try {
+ assertEquals(extra + ": " + m + ": ", expectedOutput, (double) returnValue,
+ allowedError);
+ } catch (ClassCastException e) {
+ assertEquals(extra + ": " + m + ": ", (int) expectedOutput, (int) returnValue,
+ allowedError);
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java b/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java
new file mode 100644
index 0000000..0443eb0
--- /dev/null
+++ b/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java
@@ -0,0 +1,62 @@
+package libcore.java.math;
+
+import java.lang.reflect.Method;
+
+/**
+ * Tests java.lang.StrictMath
+ * Looks for the filenames in csvFileNames in tests/resources
+ * Tests functions and numbers found in those files.
+ * Run: vogar --classpath out/target/common/obj/JAVA_LIBRARIES/core-tests-support_intermediates/javalib.jar
+ * libcore/luni/src/test/java/libcore/java/math/RunCSVTestsStrict.java
+ */
+public class RunCSVTestsStrict extends CSVTest {
+ public static final String[] csvFileNames = { "/math_tests.csv",
+ "/math_important_numbers.csv", "/math_java_only.csv" };
+
+ public void test_csv() throws Exception {
+ this.TestCSVInputs(csvFileNames);
+ }
+
+ /**
+ * Runs single-input test using assertEquals.
+ */
+ @Override
+ void runTest(String func, double expectedOutput, double input, String extra)
+ throws Exception {
+ Class<StrictMath> mathClass = StrictMath.class;
+ Method m = mathClass.getMethod(func, new Class[] { Double.TYPE });
+ Object returnValue = m.invoke(null, input);
+
+ try {
+ assertEquals(extra + ": " + m + ": " + input + ": ", expectedOutput,
+ (double) returnValue, 0D);
+ } catch (ClassCastException e) {
+ assertEquals(extra + ": " + m + ": " + input + ": ", (int) expectedOutput,
+ (int) returnValue, 0D);
+ }
+ }
+
+ /**
+ * Runs 2-input test using assertEquals.
+ */
+ @Override
+ void run2InputTest(String func, double expectedOutput, double input1,
+ double input2, String extra) throws Exception {
+ Class<StrictMath> mathClass = StrictMath.class;
+ Method m;
+ Object returnValue;
+ if (func.equals("scalb")) {
+ m = mathClass.getMethod(func, new Class[] { Double.TYPE, Integer.TYPE });
+ returnValue = m.invoke(null, input1, (int) input2);
+ } else {
+ m = mathClass.getMethod(func, new Class[] { Double.TYPE, Double.TYPE });
+ returnValue = m.invoke(null, input1, input2);
+ }
+
+ try {
+ assertEquals(extra + ": " + m + ": " , expectedOutput, (double) returnValue, 0D);
+ } catch (ClassCastException e) {
+ assertEquals(extra + ": " + m + ": ", (int) expectedOutput, (int) returnValue, 0D);
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/net/DatagramSocketTest.java b/luni/src/test/java/libcore/java/net/DatagramSocketTest.java
new file mode 100644
index 0000000..86e47ec
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/DatagramSocketTest.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 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 libcore.java.net;
+
+import junit.framework.TestCase;
+
+import java.net.DatagramSocket;
+import java.net.InetSocketAddress;
+
+public class DatagramSocketTest extends TestCase {
+
+ public void testInitialState() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ try {
+ assertTrue(ds.isBound());
+ assertTrue(ds.getBroadcast()); // The RI starts DatagramSocket in broadcast mode.
+ assertFalse(ds.isClosed());
+ assertFalse(ds.isConnected());
+ assertTrue(ds.getLocalPort() > 0);
+ assertTrue(ds.getLocalAddress().isAnyLocalAddress());
+ InetSocketAddress socketAddress = (InetSocketAddress) ds.getLocalSocketAddress();
+ assertEquals(ds.getLocalPort(), socketAddress.getPort());
+ assertEquals(ds.getLocalAddress(), socketAddress.getAddress());
+ assertNull(ds.getInetAddress());
+ assertEquals(-1, ds.getPort());
+ assertNull(ds.getRemoteSocketAddress());
+ assertFalse(ds.getReuseAddress());
+ assertNull(ds.getChannel());
+ } finally {
+ ds.close();
+ }
+ }
+
+ public void testStateAfterClose() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
+ ds.close();
+ assertTrue(ds.isBound());
+ assertTrue(ds.isClosed());
+ assertFalse(ds.isConnected());
+ assertNull(ds.getLocalAddress());
+ assertEquals(-1, ds.getLocalPort());
+ assertNull(ds.getLocalSocketAddress());
+ }
+}
diff --git a/luni/src/test/java/libcore/java/net/InetAddressTest.java b/luni/src/test/java/libcore/java/net/InetAddressTest.java
index c7617ab..4b656cc 100644
--- a/luni/src/test/java/libcore/java/net/InetAddressTest.java
+++ b/luni/src/test/java/libcore/java/net/InetAddressTest.java
@@ -49,13 +49,16 @@ public class InetAddressTest extends junit.framework.TestCase {
"1234",
"0", // Single out the deprecated form of the ANY address.
- // Hex.
+ // Hex. Not supported by Android but supported by the RI.
"0x1.0x2.0x3.0x4",
"0x7f.0x00.0x00.0x01",
"7f.0.0.1",
- // Octal.
- "0177.00.00.01", // Historically, this would have been interpreted as 127.0.0.1.
+ // Octal. Not supported by Android but supported by the RI. In the RI, if any of the numbers
+ // cannot be treated as a decimal the entire IP is interpreted differently, leading to
+ // "0177.00.00.01" -> 177.0.0.1, but "0177.0x0.00.01" -> 127.0.0.1.
+ // Android does not do this.
+ "0256.00.00.01", // Historically, this could have been interpreted as 174.0.0.1.
// Negative numbers.
"-1.0.0.1",
@@ -89,6 +92,9 @@ public class InetAddressTest extends junit.framework.TestCase {
} catch (IllegalArgumentException expected) {
}
+ // Android does not recognize Octal (leading 0) cases: they are treated as decimal.
+ assertEquals("/177.0.0.1", InetAddress.parseNumericAddress("0177.00.00.01").toString());
+
for (String invalid : INVALID_IPv4_NUMERIC_ADDRESSES) {
try {
InetAddress.parseNumericAddress(invalid);
@@ -121,6 +127,9 @@ public class InetAddressTest extends junit.framework.TestCase {
// Negative test
assertFalse(InetAddress.isNumeric("example.com"));
+ // Android does not handle Octal (leading 0) cases: they are treated as decimal.
+ assertTrue(InetAddress.isNumeric("0177.00.00.01")); // Interpreted as 177.0.0.1
+
for (String invalid : INVALID_IPv4_NUMERIC_ADDRESSES) {
assertFalse(invalid, InetAddress.isNumeric(invalid));
}
diff --git a/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java b/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java
index 1cbcd1a..3bca8dc 100644
--- a/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java
+++ b/luni/src/test/java/libcore/java/net/InetSocketAddressTest.java
@@ -140,13 +140,14 @@ public class InetSocketAddressTest extends TestCase {
InetSocketAddress isa1 = new InetSocketAddress("localhost", 80);
assertFalse(isa1.isUnresolved());
- InetSocketAddress sockAddr = new InetSocketAddress("unknown.host", 1000);
+ InetSocketAddress sockAddr = new InetSocketAddress("unknown.host.google.com", 1000);
assertTrue(sockAddr.isUnresolved());
}
public void test_getHostString() throws Exception {
// When we have a hostname, we'll get it back because that doesn't cost a DNS lookup...
InetSocketAddress hasHostname = InetSocketAddress.createUnresolved("some host", 1234);
+ assertTrue(hasHostname.isUnresolved());
assertEquals("some host", hasHostname.getHostString());
assertEquals("some host", hasHostname.getHostName());
// When we don't have a hostname, whether or not we do the reverse lookup is the difference
diff --git a/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java b/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java
index 249c326..0e11d50 100644
--- a/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java
+++ b/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java
@@ -16,6 +16,9 @@
package libcore.java.net;
+import com.google.mockwebserver.MockResponse;
+import com.google.mockwebserver.MockWebServer;
+
import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
@@ -27,65 +30,57 @@ import tests.support.Support_Configuration;
public class OldCookieHandlerTest extends TestCase {
- URI getURI, putURI;
- String link = "http://" + Support_Configuration.SpecialInetTestAddress + "/";
- boolean isGetCalled = false;
- boolean isPutCalled = false;
- boolean completedSuccessfully = false;
-
public void test_CookieHandler() {
assertNull(CookieHandler.getDefault());
}
- public void test_get_put() {
+ public void test_get_put() throws Exception {
MockCookieHandler mch = new MockCookieHandler();
CookieHandler defaultHandler = CookieHandler.getDefault();
- CookieHandler.setDefault(mch);
-
- class TestThread extends Thread {
- public void run() {
- try {
- URL url = new URL(link);
- URLConnection conn = url.openConnection();
- conn.getContent();
- url = new URL(link);
- conn = url.openConnection();
- conn.getContent();
- completedSuccessfully = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
try {
- TestThread thread = new TestThread();
+ CookieHandler.setDefault(mch);
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
+ MockWebServer server = new MockWebServer();
+ server.play();
+ server.enqueue(new MockResponse().addHeader("Set-Cookie2: a=\"android\"; "
+ + "Comment=\"this cookie is delicious\"; "
+ + "CommentURL=\"http://google.com/\"; "
+ + "Discard; "
+ + "Domain=\"" + server.getCookieDomain() + "\"; "
+ + "Max-Age=\"60\"; "
+ + "Path=\"/path\"; "
+ + "Port=\"80,443," + server.getPort() + "\"; "
+ + "Secure; "
+ + "Version=\"1\""));
- assertTrue(isGetCalled);
- assertTrue(isPutCalled);
- assertTrue(completedSuccessfully);
+ URLConnection connection = server.getUrl("/path/foo").openConnection();
+ connection.getContent();
+
+ assertTrue(mch.wasGetCalled());
+ assertTrue(mch.wasPutCalled());
} finally {
CookieHandler.setDefault(defaultHandler);
}
}
- class MockCookieHandler extends CookieHandler {
+ private static class MockCookieHandler extends CookieHandler {
+ private boolean getCalled = false;
+ private boolean putCalled = false;
public Map get(URI uri, Map requestHeaders) throws IOException {
- getURI = uri;
- isGetCalled = true;
+ getCalled = true;
return requestHeaders;
}
public void put(URI uri, Map responseHeaders) throws IOException {
- putURI = uri;
- isPutCalled = true;
+ putCalled = true;
+ }
+
+ public boolean wasGetCalled() {
+ return getCalled;
+ }
+ public boolean wasPutCalled() {
+ return putCalled;
}
}
}
diff --git a/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java b/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java
deleted file mode 100644
index d51d461..0000000
--- a/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java
+++ /dev/null
@@ -1,2183 +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 libcore.java.net;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.BindException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.DatagramSocketImpl;
-import java.net.DatagramSocketImplFactory;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.NetworkInterface;
-import java.net.PortUnreachableException;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
-import java.nio.channels.DatagramChannel;
-import java.nio.channels.IllegalBlockingModeException;
-import java.util.Date;
-import java.util.Vector;
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-public class OldDatagramSocketTest extends junit.framework./*Socket*/TestCase {
-
- java.net.DatagramSocket ds;
-
- java.net.DatagramPacket dp;
-
- DatagramSocket sds = null;
-
- String retval;
-
- String testString = "Test String";
-
- boolean interrupted;
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
-
- boolean running = true;
-
- public volatile byte[] rbuf = new byte[512];
-
- volatile DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
- ;
- }
- ;
- } catch (java.io.IOException e) {
- System.out.println("DatagramServer server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public void stopServer() {
- running = false;
- }
-
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
- }
- }
-
- public void test_Constructor() {
- // Test for method java.net.DatagramSocket()
- try {
- ds = new java.net.DatagramSocket();
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
- }
-
- public void test_ConstructorI() {
- // Test for method java.net.DatagramSocket(int)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- assertTrue("Created socket with incorrect port",
- ds.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket(8080);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
-
- try {
- DatagramSocket ds = new java.net.DatagramSocket(1);
- if (!("root".equals(System.getProperty("user.name")))) {
- fail("SocketException was not thrown.");
- }
- } catch (SocketException e) {
- //expected
- }
-
- }
-
- public void test_ConstructorILjava_net_InetAddress() {
- // Test for method java.net.DatagramSocket(int, java.net.InetAddress)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber, InetAddress
- .getLocalHost());
- assertTrue("Created socket with incorrect port",
- ds.getLocalPort() == portNumber);
- assertTrue("Created socket with incorrect address", ds
- .getLocalAddress().equals(InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new java.net.DatagramSocket(8080, InetAddress
- .getLocalHost());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
-
- try {
- new java.net.DatagramSocket(1, InetAddress
- .getLocalHost());
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- }
-
- public void test_close() {
- // Test for method void java.net.DatagramSocket.close()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- dp = new DatagramPacket("Test String".getBytes(), 11, InetAddress
- .getLocalHost(), 0);
- ds.close();
- try {
- ds.send(dp);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- public void test_connectLjava_net_InetAddressI() throws
- UnknownHostException, SocketException {
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
- inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
- ds.disconnect();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- System.out
- .println("Running test_connectLjava_net_InetAddressI" +
- "(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
- inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
- ds.disconnect();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- try {
- // Create a connected datagram socket to test
- // PlainDatagramSocketImpl.peek()
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket();
- int port = ds.getLocalPort();
- ds.connect(localHost, port);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, port);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size: " + receive.getLength(), receive
- .getLength() == 10);
- assertTrue("Wrong receiver", receive.getAddress().equals(localHost));
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- }
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
-
- boolean running = true;
-
- public byte[] rbuf = new byte[512];
-
- DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
-
- }
-
- } catch (java.io.IOException e) {
- System.out.println("Multicast server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public void stopServer() {
- running = false;
- }
-
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
- }
- }
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail(
- "No PortUnreachableException when connected at native level on recv ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level on recv: "
- + e.toString(),
- (e instanceof PortUnreachableException));
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":"
- + localHost, receive.getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- ds.close();
- } catch (Exception e) {
- assertTrue("Unexpected exception when trying to connect at native"
- + e.toString(), (e instanceof PortUnreachableException));
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(send);
- ds.close();
- fail(
- "No Exception when trying to send to a different address on a connected socket ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to send to a different address on a connected socket: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.disconnect();
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue(
- "connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.disconnect();
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, serverPortNumber);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. Even though we
- // fail at the native level there is no way to return an exception so
- // there should be no exception
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- } catch (Exception e) {
- fail(
- "Unexcpected exception when trying to connect at native level with bad address for signature with no exception to be returned: "
- + e.toString());
- }
-
- System.out
- .println("Running test_connectLjava_net_InetAddressI(DatagramSocketTest) with IPv6 address");
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0 };
- InetAddress inetAddress = InetAddress
- .getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- } catch (Exception e) {
- fail(
- "Unexcpected exception when trying to connect at native level with bad IPv6 address for signature with no exception to be returned: "
- + e.toString());
- }
- }
-
- public void test_disconnect() {
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- assertNull("Incorrect InetAddress", ds.getInetAddress());
- assertEquals("Incorrect Port", -1, ds.getPort());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- System.out
- .println("Running test_disconnect(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- assertNull("Incorrect InetAddress", ds.getInetAddress());
- assertEquals("Incorrect Port", -1, ds.getPort());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- public void test_getInetAddress() {
- Vector<InetAddress> ias = new Vector<InetAddress>();
- try {
- ias.add(InetAddress.getLocalHost());
- ias.add(InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestAddress2));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestAddress2));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestIP));
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
-
- for(InetAddress ia:ias) {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket ds = null;
- try {
- ds = new DatagramSocket();
- ds.connect(ia, portNumber);
- assertEquals(ia, ds.getInetAddress());
- assertEquals("" + ia, ia, ds.getInetAddress());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- ds.disconnect();
- ds.close();
- }
- }
-
- try {
- assertNull(new DatagramSocket().getInetAddress());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
-
- }
-
- public void test_getLocalPort() {
- // Test for method int java.net.DatagramSocket.getLocalPort()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- assertTrue("Returned incorrect port",
- ds.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Exception during getLocalAddress : " + e.getMessage());
- }
- }
-
- public void test_getPort() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket theSocket = new DatagramSocket(portNumber);
- assertEquals("Expected -1 for remote port as not connected",
- -1, theSocket.getPort());
-
- // now connect the socket and validate that we get the right port
- theSocket.connect(InetAddress.getLocalHost(), portNumber);
- assertTrue("getPort returned wrong value:" + theSocket.getPort()
- + ":Expected:" + portNumber,
- theSocket.getPort() == portNumber);
- } catch (Exception e) {
- fail("unexpected exception during getPort test : " + e.getMessage());
- }
- }
-
- public void test_getReceiveBufferSize() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
- ds.close();
- try {
- ds.getReceiveBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getSendBufferSize() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
- ds.close();
- try {
- ds.getSendBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getSoTimeout_setSoTimeout() throws Exception {
- // TODO: a useful test would check that setSoTimeout actually causes timeouts!
- DatagramSocket s = new DatagramSocket();
- s.setSoTimeout(1500);
- int ms = s.getSoTimeout();
- if (ms < 1500-10 || ms > 1500+10) {
- fail("suspicious timeout: " + ms);
- }
- s.close();
- try {
- s.getSoTimeout();
- fail("SocketException was not thrown.");
- } catch (SocketException expected) {
- }
- try {
- s.setSoTimeout(1000);
- fail("SocketException was not thrown.");
- } catch (SocketException expected) {
- }
- }
-
- public void test_receiveLjava_net_DatagramPacket() throws Exception {
- // Test for method void
- // java.net.DatagramSocket.receive(java.net.DatagramPacket)
-
- receive_oversize_java_net_DatagramPacket();
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcv implements Runnable {
- public void run() {
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- sds.send(new DatagramPacket("Test".getBytes("UTF-8"), "Test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("Longer test".getBytes("UTF-8"), "Longer test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("3 Test".getBytes("UTF-8"), "3 Test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("4 Test".getBytes("UTF-8"), "4 Test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("5".getBytes("UTF-8"), "5".length(), localHost, portNumber));
- sds.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- try {
- new Thread(new TestDGRcv(), "datagram receiver").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte[] rbuf = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
-
- // Receive the first packet.
- ds.receive(rdp);
- assertEquals("Test", new String(rbuf, 0, rdp.getLength()));
- // Check that we can still receive a longer packet (http://code.google.com/p/android/issues/detail?id=24748).
- ds.receive(rdp);
- assertEquals("Longer test", new String(rbuf, 0, rdp.getLength()));
- // See what happens if we manually call DatagramPacket.setLength.
- rdp.setLength(4);
- ds.receive(rdp);
- assertEquals("3 Te", new String(rbuf, 0, rdp.getLength()));
- // And then another.
- ds.receive(rdp);
- assertEquals("4 Te", new String(rbuf, 0, rdp.getLength()));
- // And then a packet shorter than the user-supplied length.
- ds.receive(rdp);
- assertEquals("5", new String(rbuf, 0, rdp.getLength()));
-
- ds.close();
- } finally {
- ds.close();
- }
- DatagramSocket socket = null;
- try {
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- socket = channel.socket();
- socket.receive(rdp);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException expected) {
- } finally {
- socket.close();
- }
-
- try {
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(1000);
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ds.receive(rdp);
- fail("SocketTimeoutException was not thrown.");
- } catch(SocketTimeoutException expected) {
- } finally {
- ds.close();
- }
-
- interrupted = false;
- final DatagramSocket ds = new DatagramSocket();
- ds.setSoTimeout(12000);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- ds.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException ignored) {
- }
- }
- };
- Thread thread = new Thread(runnable, "DatagramSocket.receive1");
- thread.start();
- do {
- Thread.sleep(500);
- } while (!thread.isAlive());
- ds.close();
- int c = 0;
- do {
- Thread.sleep(500);
- if (interrupted) {
- fail("received interrupt");
- }
- if (++c > 4) {
- fail("read call did not exit");
- }
- } while (thread.isAlive());
-
- interrupted = false;
- final int portNum = ports[0];
- final DatagramSocket ds2 = new DatagramSocket(ports[1]);
- ds2.setSoTimeout(12000);
- Runnable runnable2 = new Runnable() {
- public void run() {
- try {
- ds2.receive(new DatagramPacket(new byte[1], 1,
- InetAddress.getLocalHost(), portNum));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException ignored) {
- }
- }
- };
- Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
- thread2.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread2.isAlive());
- } catch (InterruptedException ignored) {
- }
- ds2.close();
- int c2 = 0;
- do {
- Thread.sleep(500);
- if (interrupted) {
- fail("receive2 was interrupted");
- }
- if (++c2 > 4) {
- fail("read2 call did not exit");
- }
- } while (thread2.isAlive());
-
- interrupted = false;
- DatagramSocket ds3 = new DatagramSocket();
- ds3.setSoTimeout(500);
- Date start = new Date();
- try {
- ds3.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- }
- ds3.close();
- assertTrue("receive not interrupted", interrupted);
- int delay = (int) (new Date().getTime() - start.getTime());
- assertTrue("timeout too soon: " + delay, delay >= 490);
- }
-
- public void test_sendLjava_net_DatagramPacket() throws Exception {
- // Test for method void
- // java.net.DatagramSocket.send(java.net.DatagramPacket)
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGSend implements Runnable {
- Thread pThread;
-
- public TestDGSend(Thread t) {
- pThread = t;
- }
-
- public void run() {
- try {
- byte[] rbuf = new byte[1000];
-
- sds = new DatagramSocket(portNumber);
- DatagramPacket sdp = new DatagramPacket(rbuf, rbuf.length);
- sds.setSoTimeout(6000);
- sds.receive(sdp);
- retval = new String(rbuf, 0, testString.length());
- pThread.interrupt();
- } catch (java.io.InterruptedIOException e) {
- System.out.println("Recv operation timed out");
- pThread.interrupt();
- ds.close();
- } catch (Exception e) {
- System.out.println("Failed to establish Dgram server: " + e);
- }
- }
- }
- try {
- new Thread(new TestDGSend(Thread.currentThread()), "DGServer")
- .start();
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
- // Wait to allow send to occur
- try {
- Thread.sleep(500);
- ds.send(dp);
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- ds.close();
- assertTrue("Incorrect data sent: " + retval, retval
- .equals(testString));
- }
- } catch (Exception e) {
- fail("Exception during send test : " + e.getMessage());
- } finally {
- ds.close();
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkMulticast(InetAddress maddr) {
- throw new SecurityException();
- }
-
- public void checkConnect(String host,
- int port) {
- throw new SecurityException();
- }
- };
- try {
-
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ds.send(dp);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.getMessage());
- }
- */
-
- DatagramSocket socket = null;
- try {
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- socket = channel.socket();
- socket.send(rdp);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown: " + ioe.getMessage());
- } finally {
- socket.close();
- }
-
- //Regression for HARMONY-1118
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl){
- super(impl);
- }
- }
- class testDatagramSocketImpl extends DatagramSocketImpl {
- protected void create() throws SocketException {}
- protected void bind(int arg0, InetAddress arg1) throws SocketException {}
- protected void send(DatagramPacket arg0) throws IOException {}
- protected int peek(InetAddress arg0) throws IOException {
- return 0;
- }
- protected int peekData(DatagramPacket arg0) throws IOException {
- return 0;
- }
- protected void receive(DatagramPacket arg0) throws IOException {}
- protected void setTTL(byte arg0) throws IOException {}
- protected byte getTTL() throws IOException {
- return 0;
- }
- protected void setTimeToLive(int arg0) throws IOException {}
- protected int getTimeToLive() throws IOException {
- return 0;
- }
- protected void join(InetAddress arg0) throws IOException {}
- protected void leave(InetAddress arg0) throws IOException {}
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
- protected void close() {}
- public void setOption(int arg0, Object arg1) throws SocketException {}
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
- }
- InetSocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- //no exception expected for next line
- new testDatagramSocket(new testDatagramSocketImpl()).send(new DatagramPacket(new byte[272], 3, sa));
-
- // Regression test for Harmony-2938
- InetAddress i = InetAddress.getByName("127.0.0.1");
- DatagramSocket d = new DatagramSocket(0, i);
- try {
- d.send(new DatagramPacket(new byte[] { 1 }, 1));
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
- } finally {
- d.close();
- }
- }
-
- public void test_setSendBufferSizeI() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
- ds.close();
- try {
- ds.setSendBufferSize(1);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_setReceiveBufferSizeI() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
-
- try {
- ds.setReceiveBufferSize(0);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- ds.setReceiveBufferSize(-1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- ds.close();
-
- try {
- ds.setReceiveBufferSize(1);
- fail("SocketException was not thrown.");
- } catch (SocketException e) {
- //expected
- }
- }
-
- public void test_ConstructorLjava_net_DatagramSocketImpl() {
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl){
- super(impl);
- }
- }
-
- try {
- new testDatagramSocket((DatagramSocketImpl) null);
- fail("exception expected");
- } catch (NullPointerException ex) {
- //expected
- }
- }
-
- public void test_ConstructorLjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- assertTrue(ds.getBroadcast());
- assertTrue("Created socket with incorrect port", ds
- .getLocalPort() == portNumber);
- assertTrue("Created socket with incorrect address", ds
- .getLocalAddress().equals(InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(new mySocketAddress());
- fail(
- "No exception when constucting datagramSocket with unsupported SocketAddress type");
- } catch (IllegalArgumentException e) {
-
- }
- //regression for Harmony-894
- ds = new DatagramSocket((SocketAddress)null);
- assertTrue(ds.getBroadcast());
- } catch (Exception ex) {
- fail(
- "unexpected exception when datagramSocket SocketAddress constructor test");
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), 1));
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
-
- InetSocketAddress isa = null;
- try {
- isa = new InetSocketAddress(
- InetAddress.getLocalHost(), 1);
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- }
-
- public void test_bindLjava_net_SocketAddress() throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[1];
-
- // now create a socket that is not bound and then bind it
- InetAddress localHost = InetAddress.getLocalHost();
- InetSocketAddress localAddress1 = new InetSocketAddress(localHost, ports[0]);
- DatagramSocket theSocket = new DatagramSocket(localAddress1);
-
- // validate that the localSocketAddress reflects the address we bound to
- assertEquals(localAddress1, theSocket.getLocalSocketAddress());
-
- // now make sure that datagrams sent from this socket appear to come
- // from the address we bound to
- InetSocketAddress localAddress2 = new InetSocketAddress(localHost, ports[2]);
- DatagramSocket ds = new DatagramSocket((SocketAddress) null);
- ds.bind(localAddress2);
-
- DatagramServer server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
-
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
- ds.send(send);
- Thread.sleep(1000);
- ds.close();
- // Check that the address in the packet matches the bound address.
- assertEquals(localAddress2, server.rdp.getSocketAddress());
-
- if (server != null) {
- server.stopServer();
- }
- }
-
- public void test_bindLjava_net_SocketAddress_null() throws Exception {
- // validate if we pass in null that it picks an address for us.
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- theSocket.bind(null);
- assertNotNull(theSocket.getLocalSocketAddress());
- theSocket.close();
- }
-
- public void test_bindLjava_net_SocketAddress_bad_address() throws Exception {
- // Address we cannot bind to
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- try {
- InetAddress badAddress = InetAddress.getByAddress(Support_Configuration.nonLocalAddressBytes);
- theSocket.bind(new InetSocketAddress(badAddress, Support_PortManager.getNextPortForUDP()));
- fail("No exception when binding to bad address");
- } catch (SocketException expected) {
- }
- theSocket.close();
- }
-
- public void test_bindLjava_net_SocketAddress_address_in_use() throws Exception {
- // Address that we have already bound to
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- DatagramSocket theSocket1 = new DatagramSocket((SocketAddress) null);
- DatagramSocket theSocket2 = new DatagramSocket(ports[0]);
- try {
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), ports[1]);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail("No exception binding to address that is not available");
- } catch (SocketException expected) {
- }
- theSocket1.close();
- theSocket2.close();
- }
-
- public void test_bindLjava_net_SocketAddress_unsupported_address_type() throws Exception {
- class mySocketAddress extends SocketAddress {
- public mySocketAddress() {
- }
- }
-
- // unsupported SocketAddress subclass
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- try {
- theSocket.bind(new mySocketAddress());
- fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException expected) {
- }
- theSocket.close();
- }
-
- public void test_connectLjava_net_SocketAddress() {
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail(
- "No PortUnreachableException when connected at native level on recv ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level on recv: "
- + e.toString(),
- (e instanceof PortUnreachableException));
- }
-
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
-
- ds.connect(new InetSocketAddress("asdfasdf", 1));
- ds.close();
- fail("SocketException was not thrown.");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect to unknown host: "
- + e.toString(),
- (e instanceof SocketException));
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":"
- + localHost, receive.getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- ds.disconnect();
- ds.close();
- } catch (Exception e) {
- assertTrue("Unexpected exception when trying to connect at native"
- + e.toString(), (e instanceof PortUnreachableException));
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(send);
- ds.close();
- fail(
- "No Exception when trying to send to a different address on a connected socket ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to send to a different address on a connected socket: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue(
- "connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, serverPortNumber);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. It seems to
- // fail for the any address so we use this. Now to be compatible we
- // don't throw the exception but eat it and then act as if we were
- // connected at the Java level.
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- InetAddress localHost = InetAddress.getLocalHost();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- assertTrue("Is not connected after connect to inaddr any", ds
- .isConnected());
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, portNumber);
- ds.send(send);
- fail(
- "No exception when trying to connect at native level with bad address (exception from send) ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level with bad address (exception from send): "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
- }
-
- public void test_isBound() {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int port = ports[0];
-
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertTrue("Socket indicated not bound when it should be (1)",
- theSocket.isBound());
- theSocket.close();
-
- theSocket = new DatagramSocket(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (2)",
- theSocket.isBound());
- theSocket.close();
-
- theSocket = new DatagramSocket((SocketAddress) null);
- assertFalse("Socket indicated bound when it should not be (1)",
- theSocket.isBound());
- theSocket.close();
-
- // connect causes implicit bind
- theSocket = new DatagramSocket((SocketAddress) null);
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (3)",
- theSocket.isBound());
- theSocket.close();
-
- // now test when we bind explicitely
- InetSocketAddress theLocalAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), ports[2]);
- theSocket = new DatagramSocket((SocketAddress) null);
- assertFalse("Socket indicated bound when it should not be (2)",
- theSocket.isBound());
- theSocket.bind(theLocalAddress);
- assertTrue("Socket indicated not bound when it should be (4)",
- theSocket.isBound());
- theSocket.close();
- assertTrue("Socket indicated not bound when it should be (5)",
- theSocket.isBound());
- } catch (Exception e) {
- fail("Got exception during isBound tests" + e.toString());
- }
- }
-
- public void test_isConnected() {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(4);
- int port = ports[0];
-
- // base test
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
-
- // reconnect the socket and make sure we get the right answer
- theSocket.connect(new InetSocketAddress(addr, ports[2]));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
-
- // now disconnect the socket and make sure we get the right answer
- theSocket.disconnect();
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.close();
-
- // now check behavior when socket is closed when connected
- theSocket = new DatagramSocket(ports[3]);
- theSocket.connect(new InetSocketAddress(addr, port));
- theSocket.close();
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
- } catch (Exception e) {
- fail("Got exception during isConnected tests" + e.toString());
- }
- }
-
- public void test_getRemoteSocketAddress() {
- try {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int sport = ports[0];
- int portNumber = ports[1];
- DatagramSocket s = new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- s.connect(new InetSocketAddress(InetAddress.getLocalHost(), sport));
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString(), s
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- sport)));
- s.close();
-
- // now create one that is not connected and validate that we get the
- // right answer
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- portNumber = ports[2];
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
- assertNull(
- "Returned incorrect InetSocketAddress -unconnected socket:"
- + "Expected: NULL", theSocket
- .getRemoteSocketAddress());
-
- // now connect and validate we get the right answer
- theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
- sport));
- assertTrue("Returned incorrect InetSocketAddress(2):"
- + theSocket.getRemoteSocketAddress().toString(), theSocket
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- sport)));
- theSocket.close();
-
- } catch (Exception e) {
- fail("Exception during getRemoteSocketAddress test: " + e);
- }
- }
-
- public void test_setReuseAddressZ() throws Exception {
- // test case were we set it to false
- DatagramSocket theSocket1 = null;
- DatagramSocket theSocket2 = null;
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket((SocketAddress) null);
- theSocket2 = new DatagramSocket((SocketAddress) null);
- theSocket1.setReuseAddress(false);
- theSocket2.setReuseAddress(false);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do duplicate socket bind with re-useaddr set to false");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test case were we set it to true
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket((SocketAddress) null);
- theSocket2 = new DatagramSocket((SocketAddress) null);
- theSocket1.setReuseAddress(true);
- theSocket2.setReuseAddress(true);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- } catch (Exception e) {
- fail(
- "unexpected exception when trying to connect to do duplicate socket bind with re-useaddr set to true");
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test the default case which we expect to be the same on all
- // platforms
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket((SocketAddress) null);
- theSocket2 = new DatagramSocket((SocketAddress) null);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do duplicate socket bind with re-useaddr left as default");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- try {
- theSocket1.setReuseAddress(true);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getReuseAddress() throws Exception {
- DatagramSocket theSocket = new DatagramSocket();
- theSocket.setReuseAddress(true);
- assertTrue("getReuseAddress false when it should be true",
- theSocket.getReuseAddress());
- theSocket.setReuseAddress(false);
- assertFalse("getReuseAddress true when it should be false",
- theSocket.getReuseAddress());
- theSocket.close();
- try {
- theSocket.getReuseAddress();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_setBroadcastZ() throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- DatagramSocket theSocket = new DatagramSocket(ports[0]);
- theSocket.setBroadcast(false);
- byte theBytes[] = { -1, -1, -1, -1 };
-
- // validate we cannot connect to the broadcast address when
- // setBroadcast is false
- try {
- theSocket.connect(new InetSocketAddress(InetAddress
- .getByAddress(theBytes), ports[1]));
- assertFalse(
- "No exception when connecting to broadcast address with setBroadcast(false)",
- theSocket.getBroadcast());
- } catch (SocketException ex) {
- //expected
- }
-
- // now validate that we can connect to the broadcast address when
- // setBroadcast is true
- theSocket.setBroadcast(true);
- theSocket.connect(new InetSocketAddress(InetAddress
- .getByAddress(theBytes), ports[2]));
-
- theSocket.close();
- try {
- theSocket.setBroadcast(false);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getBroadcast() throws Exception {
- DatagramSocket theSocket = new DatagramSocket();
- theSocket.setBroadcast(true);
- assertTrue("getBroadcast false when it should be true", theSocket
- .getBroadcast());
- theSocket.setBroadcast(false);
- assertFalse("getBroadcast true when it should be False", theSocket
- .getBroadcast());
- theSocket.close();
- try {
- theSocket.getBroadcast();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_setTrafficClassI() throws Exception {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- // validate that value set must be between 0 and 255
- try {
- theSocket.setTrafficClass(256);
- fail("No exception when traffic class set to 256");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- theSocket.setTrafficClass(-1);
- fail("No exception when traffic class set to -1");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate that we can set it to some good values
- theSocket.setTrafficClass(IPTOS_LOWCOST);
- theSocket.setTrafficClass(IPTOS_THROUGHPUT);
-
- theSocket.close();
- try {
- theSocket.setTrafficClass(1);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getTrafficClass() throws Exception {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- /*
- * we cannot actually check that the values are set as if a platform
- * does not support the option then it may come back unset even
- * though we set it so just get the value to make sure we can get it
- */
- int trafficClass = theSocket.getTrafficClass();
-
- theSocket.close();
- try {
- theSocket.getTrafficClass();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_isClosed() {
- try {
- DatagramSocket theSocket = new DatagramSocket();
-
- // validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):",
- theSocket.isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is not closed(1):", theSocket
- .isClosed());
-
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- theSocket = new DatagramSocket(theAddress);
- assertFalse("Socket should indicate it is not closed(2):",
- theSocket.isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is not closed(2):", theSocket
- .isClosed());
- } catch (Exception e) {
- fail("Got exception during isClosed tests" + e.toString());
- }
- }
-
- public void test_getChannel() throws Exception {
- assertNull(new DatagramSocket().getChannel());
-
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket ds = null;
- try {
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- ds = new DatagramSocket();
- assertNull(ds.getChannel());
- ds.connect(ia, portNumber);
- assertNull(ds.getChannel());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- ds.disconnect();
- ds.close();
- }
- portNumber = Support_PortManager.getNextPortForUDP();
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- DatagramSocket socket = channel.socket();
- assertEquals(channel, socket.getChannel());
- socket.close();
- }
-
- class TestDatagramSocketImplFactory implements DatagramSocketImplFactory {
- public DatagramSocketImpl createDatagramSocketImpl() {
- return new TestDatagramSocketImpl();
- }
- }
-
- class TestDatagramSocketImpl extends DatagramSocketImpl {
-
- @Override
- protected void bind(int arg0, InetAddress arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void close() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void create() throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected byte getTTL() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected int getTimeToLive() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void join(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void leave(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected int peek(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected int peekData(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void receive(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void send(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void setTTL(byte arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void setTimeToLive(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public Object getOption(int arg0) throws SocketException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- retval = "Bogus retval";
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- ds.close();
- sds.close();
- } catch (Exception e) {
- }
- }
-
- protected void receive_oversize_java_net_DatagramPacket() throws Exception {
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcvOver implements Runnable {
- public void run() {
- InetAddress localHost = null;
- try {
- localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- DatagramPacket rdp = new DatagramPacket("0123456789"
- .getBytes(), 10, localHost, portNumber);
- sds.send(rdp);
- sds.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- try {
- new Thread(new TestDGRcvOver(), "DGSenderOver").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte rbuf[] = new byte[5];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ;
- ds.receive(rdp);
- ds.close();
- assertTrue("Send/Receive oversize failed to return correct data: "
- + new String(rbuf, 0, 5), new String(rbuf, 0, 5)
- .equals("01234"));
- } finally {
- ds.close();
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
index de9caa9..4fe3ef4 100644
--- a/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
+++ b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
@@ -22,19 +22,11 @@ import java.net.FileNameMap;
import java.net.URLConnection;
public class OldFileNameMapTest extends TestCase {
-
- public void test_getContentTypeFor() {
- String [] files = {"text", "txt", "htm", "html"};
-
- String [] mimeTypes = {"text/plain", "text/plain",
- "text/html", "text/html"};
-
- FileNameMap fileNameMap = URLConnection.getFileNameMap();
-
- for(int i = 0; i < files.length; i++) {
- String mimeType = fileNameMap.getContentTypeFor("test." + files[i]);
- assertEquals("getContentTypeFor returns incorrect MIME type for " +
- files[i], mimeTypes[i], mimeType);
- }
- }
+ public void test_getContentTypeFor() {
+ FileNameMap map = URLConnection.getFileNameMap();
+ assertEquals("text/plain", map.getContentTypeFor("test.text"));
+ assertEquals("text/plain", map.getContentTypeFor("test.txt"));
+ assertEquals("text/html", map.getContentTypeFor("test.htm"));
+ assertEquals("text/html", map.getContentTypeFor("test.html"));
+ }
}
diff --git a/luni/src/test/java/libcore/java/net/OldSocketTest.java b/luni/src/test/java/libcore/java/net/OldSocketTest.java
index 033a7bf..7973965 100644
--- a/luni/src/test/java/libcore/java/net/OldSocketTest.java
+++ b/luni/src/test/java/libcore/java/net/OldSocketTest.java
@@ -95,10 +95,9 @@ public class OldSocketTest extends OldSocketTestCase {
}
try {
- new Socket("unknown.host", 0);
+ new Socket("unknown.host.google.com", 0);
fail("UnknownHostException was not thrown.");
- } catch(UnknownHostException uhe) {
- //expected
+ } catch (UnknownHostException expected) {
}
Socket socket = null;
try {
@@ -120,9 +119,10 @@ public class OldSocketTest extends OldSocketTestCase {
}
public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI2() throws IOException {
- Socket s1 = new Socket("www.google.com", 80, null, 0);
+ int sport = startServer("Cons String,I,InetAddress,I");
+ Socket s1 = new Socket(InetAddress.getLocalHost(), sport, null, 0);
try {
- Socket s2 = new Socket("www.google.com", 80, null, s1.getLocalPort());
+ Socket s2 = new Socket(InetAddress.getLocalHost(), sport, null, s1.getLocalPort());
try {
s2.close();
} catch (IOException ignored) {
@@ -1251,6 +1251,12 @@ public class OldSocketTest extends OldSocketTestCase {
theSocket.connect(nonReachableAddress, 200);
theSocket.close();
fail("No interrupted exception when connecting to address nobody listening on with short timeout 200: ");
+ } catch (ConnectException ce) {
+ // some networks will quickly reset the TCP connection attempt to this fake IP
+ assertTrue(
+ "Wrong exception when connecting to address nobody listening on with short timeout 200: "
+ + ce.toString(),
+ (ce.getMessage() != null && ce.getMessage().contains("ECONNREFUSED")));
} catch (Exception e) {
assertTrue(
"Wrong exception when connecting to address nobody listening on with short timeout 200: "
@@ -1266,6 +1272,12 @@ public class OldSocketTest extends OldSocketTestCase {
theSocket.connect(nonReachableAddress, 40);
theSocket.close();
fail("No interrupted exception when connecting to address nobody listening on with short timeout 40: ");
+ } catch (ConnectException ce) {
+ // some networks will quickly reset the TCP connection attempt to this fake IP
+ assertTrue(
+ "Wrong exception when connecting to address nobody listening on with short timeout 40: "
+ + ce.toString(),
+ (ce.getMessage() != null && ce.getMessage().contains("ECONNREFUSED")));
} catch (Exception e) {
assertTrue(
"Wrong exception when connecting to address nobody listening on with short timeout 40: "
diff --git a/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java b/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java
index 3a5608c..c076f1d 100644
--- a/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java
@@ -17,7 +17,6 @@
package libcore.java.net;
-import dalvik.annotation.SideEffect;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -26,15 +25,11 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
-import java.security.Permission;
import java.security.PermissionCollection;
-import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.Manifest;
-import org.apache.harmony.security.tests.support.TestCertUtils;
-import tests.support.Support_Configuration;
import tests.support.Support_TestWebData;
import tests.support.Support_TestWebServer;
import tests.support.resource.Support_Resources;
@@ -42,15 +37,6 @@ import tests.support.resource.Support_Resources;
public class OldURLClassLoaderTest extends junit.framework.TestCase {
URLClassLoader ucl;
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkCreateClassLoader() {
- throw new SecurityException();
- }
- };
/**
* java.net.URLClassLoader#URLClassLoader(java.net.URL[])
@@ -58,8 +44,8 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase {
public void test_Constructor$Ljava_net_URL() throws MalformedURLException {
URL[] u = new URL[0];
ucl = new URLClassLoader(u);
- assertTrue("Failed to set parent", ucl != null
- && ucl.getParent() == URLClassLoader.getSystemClassLoader());
+ assertTrue("Failed to set parent",
+ ucl.getParent() == URLClassLoader.getSystemClassLoader());
URL [] urls = {new URL("http://foo.com/foo"),
@@ -87,7 +73,6 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase {
* java.net.URLClassLoader#findResources(java.lang.String)
*/
public void test_findResourcesLjava_lang_String() throws Exception {
- Enumeration<URL> res = null;
String[] resValues = { "This is a test resource file.",
"This is a resource from a subdir"};
@@ -115,7 +100,7 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase {
urls[1] = new URL("file://" + subDir.getAbsolutePath() + "/");
ucl = new URLClassLoader(urls);
- res = ucl.findResources("test0");
+ Enumeration<URL> res = ucl.findResources("test0");
assertNotNull("Failed to locate resources", res);
int i = 0;
@@ -207,7 +192,7 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase {
}
}
- @SideEffect("Support_TestWebServer requires isolation.")
+ // SideEffect: Support_TestWebServer requires isolation.
public void test_findResourceLjava_lang_String() throws Exception {
File tmp = File.createTempFile("test", ".txt");
@@ -232,7 +217,7 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase {
/**
* Regression for Harmony-2237
*/
- @SideEffect("Support_TestWebServer requires isolation.")
+ // SideEffect: Support_TestWebServer requires isolation.
public void test_findResource_String() throws Exception {
File tempFile1 = File.createTempFile("textFile", ".txt");
tempFile1.createNewFile();
@@ -250,19 +235,17 @@ public class OldURLClassLoaderTest extends junit.framework.TestCase {
"/tests/resources/hyts_patch.jar");
Support_Resources.copyLocalFileto(tempFile2, is);
String tempPath2 = tempFile2.getAbsolutePath();
- String tempPath3 = "http://localhost:" + port + "/";
URLClassLoader urlLoader = getURLClassLoader(tempPath1, tempPath2);
- assertNull("Found inexistant resource",
- urlLoader.findResource("XXX"));
+ assertNull("Found nonexistent resource", urlLoader.findResource("XXX"));
assertNotNull("Couldn't find resource from directory",
urlLoader.findResource(tempFile1.getName()));
- assertNotNull("Couldn't find resource from jar",
- urlLoader.findResource("Blah.txt"));
+ assertNotNull("Couldn't find resource from jar", urlLoader.findResource("Blah.txt"));
+
+ String tempPath3 = "http://localhost:" + port + "/";
urlLoader = getURLClassLoader(tempPath1, tempPath2, tempPath3);
- assertNotNull("Couldn't find resource from web",
- urlLoader.findResource("test1"));
- assertNull("Found inexistant resource from web",
- urlLoader.findResource("test3"));
+ assertNotNull("Couldn't find resource from web", urlLoader.findResource("test1"));
+ // Attempt to find a resource using a URL that will produce a 404.
+ assertNull("Found nonexistent resource from web", urlLoader.findResource("test9999"));
} finally {
server.close();
}
diff --git a/luni/src/test/java/libcore/java/net/ServerSocketTest.java b/luni/src/test/java/libcore/java/net/ServerSocketTest.java
index fe9d423..d82e934 100644
--- a/luni/src/test/java/libcore/java/net/ServerSocketTest.java
+++ b/luni/src/test/java/libcore/java/net/ServerSocketTest.java
@@ -17,6 +17,8 @@
package libcore.java.net;
import java.io.IOException;
+import java.net.Inet4Address;
+import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
@@ -43,4 +45,34 @@ public class ServerSocketTest extends junit.framework.TestCase {
t.join();
assertEquals(0, result[0].getSoTimeout());
}
+
+ public void testInitialState() throws Exception {
+ ServerSocket ss = new ServerSocket();
+ try {
+ assertFalse(ss.isBound());
+ assertFalse(ss.isClosed());
+ assertEquals(-1, ss.getLocalPort());
+ assertNull(ss.getLocalSocketAddress());
+ assertNull(ss.getInetAddress());
+ assertTrue(ss.getReuseAddress());
+ assertNull(ss.getChannel());
+ } finally {
+ ss.close();
+ }
+ }
+
+ public void testStateAfterClose() throws Exception {
+ ServerSocket ss = new ServerSocket();
+ ss.bind(new InetSocketAddress(Inet4Address.getLocalHost(), 0));
+ InetSocketAddress boundAddress = (InetSocketAddress) ss.getLocalSocketAddress();
+ ss.close();
+
+ assertTrue(ss.isBound());
+ assertTrue(ss.isClosed());
+ assertEquals(boundAddress.getAddress(), ss.getInetAddress());
+ assertEquals(boundAddress.getPort(), ss.getLocalPort());
+
+ InetSocketAddress localAddressAfterClose = (InetSocketAddress) ss.getLocalSocketAddress();
+ assertEquals(boundAddress, localAddressAfterClose);
+ }
}
diff --git a/luni/src/test/java/libcore/java/net/SocketTest.java b/luni/src/test/java/libcore/java/net/SocketTest.java
index 42b7250..fb09be0 100644
--- a/luni/src/test/java/libcore/java/net/SocketTest.java
+++ b/luni/src/test/java/libcore/java/net/SocketTest.java
@@ -20,6 +20,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
+import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
@@ -109,10 +110,12 @@ public class SocketTest extends junit.framework.TestCase {
in.socket().setTcpNoDelay(false);
}
+ InetSocketAddress listenAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
InetSocketAddress outRemoteAddress = (InetSocketAddress) out.socket().getRemoteSocketAddress();
InetSocketAddress outLocalAddress = (InetSocketAddress) out.socket().getLocalSocketAddress();
InetSocketAddress inLocalAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
InetSocketAddress inRemoteAddress = (InetSocketAddress) in.socket().getRemoteSocketAddress();
+ System.err.println("listenAddress: " + listenAddr);
System.err.println("inLocalAddress: " + inLocalAddress);
System.err.println("inRemoteAddress: " + inRemoteAddress);
System.err.println("outLocalAddress: " + outLocalAddress);
@@ -127,14 +130,42 @@ public class SocketTest extends junit.framework.TestCase {
assertEquals(outLocalAddress.getAddress(), ss.getInetAddress());
assertEquals(outRemoteAddress.getAddress(), ss.getInetAddress());
+ assertFalse(ssc.socket().isClosed());
+ assertTrue(ssc.socket().isBound());
+ assertTrue(in.isConnected());
+ assertTrue(in.socket().isConnected());
+ assertTrue(out.socket().isConnected());
+ assertTrue(out.isConnected());
+
in.close();
out.close();
ssc.close();
+ assertTrue(ssc.socket().isClosed());
+ assertTrue(ssc.socket().isBound());
+ assertFalse(in.isConnected());
+ assertFalse(in.socket().isConnected());
+ assertFalse(out.socket().isConnected());
+ assertFalse(out.isConnected());
+
assertNull(in.socket().getRemoteSocketAddress());
assertNull(out.socket().getRemoteSocketAddress());
- assertEquals(in.socket().getLocalSocketAddress(), ss.getLocalSocketAddress());
+ // As per docs and RI - server socket local address methods continue to return the bind()
+ // addresses even after close().
+ assertEquals(listenAddress, ssc.socket().getLocalSocketAddress());
+
+ // As per docs and RI - socket local address methods return the wildcard address before
+ // bind() and after close(), but the port will be the same as it was before close().
+ InetSocketAddress inLocalAddressAfterClose =
+ (InetSocketAddress) in.socket().getLocalSocketAddress();
+ assertTrue(inLocalAddressAfterClose.getAddress().isAnyLocalAddress());
+ assertEquals(inLocalAddress.getPort(), inLocalAddressAfterClose.getPort());
+
+ InetSocketAddress outLocalAddressAfterClose =
+ (InetSocketAddress) out.socket().getLocalSocketAddress();
+ assertTrue(outLocalAddressAfterClose.getAddress().isAnyLocalAddress());
+ assertEquals(outLocalAddress.getPort(), outLocalAddressAfterClose.getPort());
}
// SocketOptions.setOption has weird behavior for setSoLinger/SO_LINGER.
@@ -286,6 +317,42 @@ public class SocketTest extends junit.framework.TestCase {
serverSocket.close();
}
+ public void testInitialState() throws Exception {
+ Socket s = new Socket();
+ try {
+ assertFalse(s.isBound());
+ assertFalse(s.isClosed());
+ assertFalse(s.isConnected());
+ assertEquals(-1, s.getLocalPort());
+ assertTrue(s.getLocalAddress().isAnyLocalAddress());
+ assertNull(s.getLocalSocketAddress());
+ assertNull(s.getInetAddress());
+ assertEquals(0, s.getPort());
+ assertNull(s.getRemoteSocketAddress());
+ assertFalse(s.getReuseAddress());
+ assertNull(s.getChannel());
+ } finally {
+ s.close();
+ }
+ }
+
+ public void testStateAfterClose() throws Exception {
+ Socket s = new Socket();
+ s.bind(new InetSocketAddress(Inet4Address.getLocalHost(), 0));
+ InetSocketAddress boundAddress = (InetSocketAddress) s.getLocalSocketAddress();
+ s.close();
+
+ assertTrue(s.isBound());
+ assertTrue(s.isClosed());
+ assertFalse(s.isConnected());
+ assertTrue(s.getLocalAddress().isAnyLocalAddress());
+ assertEquals(boundAddress.getPort(), s.getLocalPort());
+
+ InetSocketAddress localAddressAfterClose = (InetSocketAddress) s.getLocalSocketAddress();
+ assertTrue(localAddressAfterClose.getAddress().isAnyLocalAddress());
+ assertEquals(boundAddress.getPort(), localAddressAfterClose.getPort());
+ }
+
static class MockServer {
private ExecutorService executor;
private ServerSocket serverSocket;
diff --git a/luni/src/test/java/libcore/java/net/URITest.java b/luni/src/test/java/libcore/java/net/URITest.java
index 04a7d2e..7f4c086 100644
--- a/luni/src/test/java/libcore/java/net/URITest.java
+++ b/luni/src/test/java/libcore/java/net/URITest.java
@@ -16,9 +16,9 @@
package libcore.java.net;
+import junit.framework.TestCase;
import java.net.URI;
import java.net.URISyntaxException;
-import junit.framework.TestCase;
import libcore.util.SerializationTester;
public final class URITest extends TestCase {
@@ -57,6 +57,24 @@ public final class URITest extends TestCase {
.equals(new URI("http://localhost/foo?bar=baz#QUUX")));
}
+ public void testEqualsEscaping() throws Exception {
+ // Case insensitive when comparing escaped values, but not when
+ // comparing unescaped values.
+ assertEquals(new URI("http://localhost/foo?bar=fooobar%E0%AE%A8%E0bar"),
+ new URI("http://localhost/foo?bar=fooobar%E0%AE%a8%e0bar"));
+ assertFalse(new URI("http://localhost/foo?bar=fooobar%E0%AE%A8%E0bar").equals(
+ new URI("http://localhost/foo?bar=FoooBar%E0%AE%a8%e0bar")));
+ assertFalse(new URI("http://localhost/foo?bar=fooobar%E0%AE%A8%E0bar").equals(
+ new URI("http://localhost/foo?bar=fooobar%E0%AE%a8%e0BaR")));
+
+ // Last byte replaced by an unescaped value.
+ assertFalse(new URI("http://localhost/foo?bar=%E0%AE%A8%E0").equals(
+ new URI("http://localhost/foo?bar=%E0%AE%a8xxx")));
+ // Missing byte.
+ assertFalse(new URI("http://localhost/foo?bar=%E0%AE%A8%E0").equals(
+ new URI("http://localhost/foo?bar=%E0%AE%a8")));
+ }
+
public void testFileEqualsWithEmptyHost() throws Exception {
assertEquals(new URI("file", "", "/a/", null), new URI("file:/a/"));
assertEquals(new URI("file", null, "/a/", null), new URI("file:/a/"));
@@ -511,7 +529,7 @@ public final class URITest extends TestCase {
assertEquals("b/c", a.relativize(b).toString()); // RI assumes a directory
}
- public void testParseServerAuthorityInvalidAuthority() throws Exception {
+ public void testParseServerAuthorityInvalidPortMinus() throws Exception {
URI uri = new URI("http://host:-2/");
assertEquals("host:-2", uri.getAuthority());
assertNull(uri.getHost());
@@ -523,6 +541,30 @@ public final class URITest extends TestCase {
}
}
+ public void testParseServerAuthorityInvalidPortPlus() throws Exception {
+ URI uri = new URI("http://host:+2/");
+ assertEquals("host:+2", uri.getAuthority());
+ assertNull(uri.getHost());
+ assertEquals(-1, uri.getPort());
+ try {
+ uri.parseServerAuthority();
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ }
+
+ public void testParseServerAuthorityInvalidPortNonASCII() throws Exception {
+ URI uri = new URI("http://host:١٢٣/"); // 123 in arabic
+ assertEquals("host:١٢٣", uri.getAuthority());
+ assertNull(uri.getHost());
+ assertEquals(-1, uri.getPort());
+ try {
+ uri.parseServerAuthority();
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ }
+
public void testParseServerAuthorityOmittedAuthority() throws Exception {
URI uri = new URI("http:file");
uri.parseServerAuthority(); // does nothing!
diff --git a/luni/src/test/java/libcore/java/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
index 4ed7f0e..f438d1b 100644
--- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java
+++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
@@ -21,9 +21,7 @@ import com.google.mockwebserver.MockResponse;
import com.google.mockwebserver.MockWebServer;
import com.google.mockwebserver.RecordedRequest;
import com.google.mockwebserver.SocketPolicy;
-import dalvik.system.CloseGuard;
import java.io.ByteArrayOutputStream;
-import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -31,7 +29,6 @@ import java.io.OutputStream;
import java.net.Authenticator;
import java.net.CacheRequest;
import java.net.CacheResponse;
-import java.net.ConnectException;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
@@ -71,20 +68,20 @@ import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
-import junit.framework.TestCase;
-import libcore.java.lang.ref.FinalizationTester;
import libcore.java.security.StandardNames;
import libcore.java.security.TestKeyStore;
+import libcore.java.util.AbstractResourceLeakageDetectorTestCase;
import libcore.javax.net.ssl.TestSSLContext;
import tests.net.StuckServer;
-import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AFTER_READING_REQUEST;
import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_END;
import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_START;
+import static com.google.mockwebserver.SocketPolicy.FAIL_HANDSHAKE;
import static com.google.mockwebserver.SocketPolicy.SHUTDOWN_INPUT_AT_END;
import static com.google.mockwebserver.SocketPolicy.SHUTDOWN_OUTPUT_AT_END;
-public final class URLConnectionTest extends TestCase {
+public final class URLConnectionTest extends AbstractResourceLeakageDetectorTestCase {
+
private MockWebServer server;
private HttpResponseCache cache;
private String hostName;
@@ -105,8 +102,10 @@ public final class URLConnectionTest extends TestCase {
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
server.shutdown();
+ server = null;
if (cache != null) {
cache.delete();
+ cache = null;
}
super.tearDown();
}
@@ -325,6 +324,12 @@ public final class URLConnectionTest extends TestCase {
public void testServerShutdownOutput() throws Exception {
// This test causes MockWebServer to log a "connection failed" stack trace
+
+ // Setting the server workerThreads to 1 ensures the responses are generated in the order
+ // the requests are accepted by the server. Without this the second and third requests made
+ // by the client (the request for "/b" and the retry for "/b" when the bad socket is
+ // detected) can be handled by the server out of order leading to test failure.
+ server.setWorkerThreads(1);
server.enqueue(new MockResponse()
.setBody("Output shutdown after this response")
.setSocketPolicy(SHUTDOWN_OUTPUT_AT_END));
@@ -433,7 +438,7 @@ public final class URLConnectionTest extends TestCase {
RecordedRequest request = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
- assertEquals("TLSv1", request.getSslProtocol());
+ assertEquals("TLSv1.2", request.getSslProtocol());
}
public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
@@ -801,47 +806,17 @@ public final class URLConnectionTest extends TestCase {
}
public void testDisconnectAfterOnlyResponseCodeCausesNoCloseGuardWarning() throws IOException {
- CloseGuardGuard guard = new CloseGuardGuard();
- try {
- server.enqueue(new MockResponse()
- .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
- .addHeader("Content-Encoding: gzip"));
- server.play();
+ server.enqueue(new MockResponse()
+ .setBody(gzip("ABCABCABC".getBytes("UTF-8")))
+ .addHeader("Content-Encoding: gzip"));
+ server.play();
- HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
+ HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
+ try {
assertEquals(200, connection.getResponseCode());
- connection.disconnect();
- connection = null;
- assertFalse(guard.wasCloseGuardCalled());
} finally {
- guard.close();
- }
- }
-
- public static class CloseGuardGuard implements Closeable, CloseGuard.Reporter {
- private final CloseGuard.Reporter oldReporter = CloseGuard.getReporter();
-
- private AtomicBoolean closeGuardCalled = new AtomicBoolean();
-
- public CloseGuardGuard() {
- CloseGuard.setReporter(this);
- }
-
- @Override public void report(String message, Throwable allocationSite) {
- oldReporter.report(message, allocationSite);
- closeGuardCalled.set(true);
- }
-
- public boolean wasCloseGuardCalled() {
- FinalizationTester.induceFinalization();
- close();
- return closeGuardCalled.get();
- }
-
- @Override public void close() {
- CloseGuard.setReporter(oldReporter);
+ connection.disconnect();
}
-
}
public void testDefaultRequestProperty() throws Exception {
@@ -990,6 +965,7 @@ public final class URLConnectionTest extends TestCase {
RecordedRequest request = server.takeRequest();
assertContains(request.getHeaders(), "Accept-Encoding: gzip");
+ assertEquals("gzip", connection.getContentEncoding());
}
public void testGzipAndConnectionReuseWithFixedLength() throws Exception {
@@ -1065,25 +1041,37 @@ public final class URLConnectionTest extends TestCase {
}
/**
- * Obnoxiously test that the chunk sizes transmitted exactly equal the
- * requested data+chunk header size. Although setChunkedStreamingMode()
- * isn't specific about whether the size applies to the data or the
- * complete chunk, the RI interprets it as a complete chunk.
+ * Test that request body chunking works. This test has been relaxed from treating
+ * the {@link java.net.HttpURLConnection#setChunkedStreamingMode(int)}
+ * chunk length as being fixed because OkHttp no longer guarantees
+ * the fixed chunk size. Instead, we check that chunking takes place
+ * and we force the chunk size with flushes.
*/
public void testSetChunkedStreamingMode() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
server.play();
HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
- urlConnection.setChunkedStreamingMode(8);
+ // Later releases of Android ignore the value for chunkLength if it is > 0 and default to
+ // a fixed chunkLength. During the change-over period while the chunkLength indicates the
+ // chunk buffer size (inc. header) the chunkLength has to be >= 8. This enables the flush()
+ // to dictate the size of the chunks.
+ urlConnection.setChunkedStreamingMode(50 /* chunkLength */);
urlConnection.setDoOutput(true);
OutputStream outputStream = urlConnection.getOutputStream();
- outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII"));
+ String outputString = "ABCDEFGH";
+ byte[] outputBytes = outputString.getBytes("US-ASCII");
+ int targetChunkSize = 3;
+ for (int i = 0; i < outputBytes.length; i += targetChunkSize) {
+ int count = i + targetChunkSize < outputBytes.length ? 3 : outputBytes.length - i;
+ outputStream.write(outputBytes, i, count);
+ outputStream.flush();
+ }
assertEquals(200, urlConnection.getResponseCode());
RecordedRequest request = server.takeRequest();
- assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII"));
- assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes());
+ assertEquals(outputString, new String(request.getBody(), "US-ASCII"));
+ assertEquals(Arrays.asList(3, 3, 2), request.getChunkSizes());
}
public void testAuthenticateWithFixedLengthStreaming() throws Exception {
@@ -1615,7 +1603,7 @@ public final class URLConnectionTest extends TestCase {
+ "CN=" + hostName + " 1, "
+ "CN=Test Intermediate Certificate Authority 1, "
+ "CN=Test Root Certificate Authority 1"
- + "] RSA"),
+ + "] ECDHE_RSA"),
trustManager.calls);
} finally {
HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
@@ -2190,16 +2178,15 @@ public final class URLConnectionTest extends TestCase {
}
}
+ // http://code.google.com/p/android/issues/detail?id=16895
public void testUrlWithSpaceInHostViaHttpProxy() throws Exception {
server.enqueue(new MockResponse());
server.play();
URLConnection urlConnection = new URL("http://and roid.com/")
.openConnection(server.toProxyAddress());
- try {
- urlConnection.getInputStream();
- fail(); // the RI makes a bogus proxy request for "GET http://and roid.com/ HTTP/1.1"
- } catch (UnknownHostException expected) {
- }
+
+ // This test is to check that a NullPointerException is not thrown.
+ urlConnection.getInputStream();
}
public void testSslFallback() throws Exception {
@@ -2213,7 +2200,7 @@ public final class URLConnectionTest extends TestCase {
"SSLv3");
server.useHttps(serverSocketFactory, false);
- server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
+ server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
server.enqueue(new MockResponse().setBody("This required a 2nd handshake"));
server.play();
@@ -2237,7 +2224,7 @@ public final class URLConnectionTest extends TestCase {
SSLSocket clientSocket1 = createdSockets.get(0);
List<String> clientSocket1EnabledProtocols = Arrays.asList(
clientSocket1.getEnabledProtocols());
- assertContains(clientSocket1EnabledProtocols, "TLSv1");
+ assertContains(clientSocket1EnabledProtocols, "TLSv1.2");
List<String> clientSocket1EnabledCiphers =
Arrays.asList(clientSocket1.getEnabledCipherSuites());
assertContainsNoneMatching(
@@ -2246,7 +2233,7 @@ public final class URLConnectionTest extends TestCase {
SSLSocket clientSocket2 = createdSockets.get(1);
List<String> clientSocket2EnabledProtocols =
Arrays.asList(clientSocket2.getEnabledProtocols());
- assertContainsNoneMatching(clientSocket2EnabledProtocols, "TLSv1");
+ assertContainsNoneMatching(clientSocket2EnabledProtocols, "TLSv1.2");
List<String> clientSocket2EnabledCiphers =
Arrays.asList(clientSocket2.getEnabledCipherSuites());
assertContains(clientSocket2EnabledCiphers, StandardNames.CIPHER_SUITE_FALLBACK);
@@ -2296,11 +2283,15 @@ public final class URLConnectionTest extends TestCase {
HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
connection.connect();
- assertNotNull(connection.getHostnameVerifier());
- assertNull(connection.getLocalCertificates());
- assertNotNull(connection.getServerCertificates());
- assertNotNull(connection.getCipherSuite());
- assertNotNull(connection.getPeerPrincipal());
+ try {
+ assertNotNull(connection.getHostnameVerifier());
+ assertNull(connection.getLocalCertificates());
+ assertNotNull(connection.getServerCertificates());
+ assertNotNull(connection.getCipherSuite());
+ assertNotNull(connection.getPeerPrincipal());
+ } finally {
+ connection.disconnect();
+ }
}
/**
diff --git a/luni/src/test/java/libcore/java/net/URLTest.java b/luni/src/test/java/libcore/java/net/URLTest.java
index a18816b..07e651c 100644
--- a/luni/src/test/java/libcore/java/net/URLTest.java
+++ b/luni/src/test/java/libcore/java/net/URLTest.java
@@ -350,7 +350,7 @@ public final class URLTest extends TestCase {
}
}
- public void testNegativePort() throws Exception {
+ public void testPortWithMinusSign() throws Exception {
try {
new URL("http://host:-2/");
fail();
@@ -358,6 +358,22 @@ public final class URLTest extends TestCase {
}
}
+ public void testPortWithPlusSign() throws Exception {
+ try {
+ new URL("http://host:+2/");
+ fail();
+ } catch (MalformedURLException expected) {
+ }
+ }
+
+ public void testPortNonASCII() throws Exception {
+ try {
+ new URL("http://host:١٢٣/"); // 123 in arabic
+ fail();
+ } catch (MalformedURLException expected) {
+ }
+ }
+
public void testNegativePortEqualsPlaceholder() throws Exception {
try {
new URL("http://host:-1/");
diff --git a/luni/src/test/java/libcore/java/nio/BufferTest.java b/luni/src/test/java/libcore/java/nio/BufferTest.java
index ae90d49..c936cdf 100644
--- a/luni/src/test/java/libcore/java/nio/BufferTest.java
+++ b/luni/src/test/java/libcore/java/nio/BufferTest.java
@@ -16,12 +16,28 @@
package libcore.java.nio;
-import java.io.*;
-import java.lang.reflect.*;
-import java.nio.*;
-import java.nio.channels.*;
-import java.util.Arrays;
import junit.framework.TestCase;
+import java.io.File;
+import java.io.RandomAccessFile;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.nio.Buffer;
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.CharBuffer;
+import java.nio.DoubleBuffer;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
+import java.nio.LongBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.NioUtils;
+import java.nio.ReadOnlyBufferException;
+import java.nio.ShortBuffer;
+import java.nio.channels.FileChannel;
+import java.util.Arrays;
+import libcore.io.SizeOf;
public class BufferTest extends TestCase {
private static ByteBuffer allocateMapped(int size) throws Exception {
@@ -586,17 +602,31 @@ public class BufferTest extends TestCase {
assertTrue(b.isDirect());
// Check the buffer has an array of the right size.
assertTrue(b.hasArray());
- assertEquals(0, b.arrayOffset());
byte[] array = b.array();
- assertEquals(10, array.length);
+ assertTrue(array.length >= b.capacity());
+ assertEquals(10, b.capacity());
// Check that writes to the array show up in the buffer.
assertEquals(0, b.get(0));
- array[0] = 1;
+ array[b.arrayOffset()] = 1;
assertEquals(1, b.get(0));
// Check that writes to the buffer show up in the array.
- assertEquals(1, array[0]);
+ assertEquals(1, array[b.arrayOffset()]);
b.put(0, (byte) 0);
- assertEquals(0, array[0]);
+ assertEquals(0, array[b.arrayOffset()]);
+ }
+
+ // Test that direct byte buffers are 8 byte aligned.
+ // http://b/16449607
+ public void testDirectByteBufferAlignment() throws Exception {
+ ByteBuffer b = ByteBuffer.allocateDirect(10);
+ Field addressField = Buffer.class.getDeclaredField("effectiveDirectAddress");
+ assertTrue(addressField != null);
+ addressField.setAccessible(true);
+ long address = addressField.getLong(b);
+ // Check that the address field is aligned by 8.
+ // Normally reading this field happens in native code by calling
+ // GetDirectBufferAddress.
+ assertEquals(0, address % 8);
}
public void testSliceOffset() throws Exception {
@@ -604,14 +634,12 @@ public class BufferTest extends TestCase {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.get();
ByteBuffer slice = buffer.slice();
- assertEquals(0, buffer.arrayOffset());
- assertEquals(1, slice.arrayOffset());
+ assertEquals(buffer.arrayOffset() + 1, slice.arrayOffset());
ByteBuffer directBuffer = ByteBuffer.allocateDirect(10);
directBuffer.get();
ByteBuffer directSlice = directBuffer.slice();
- assertEquals(0, directBuffer.arrayOffset());
- assertEquals(1, directSlice.arrayOffset());
+ assertEquals(directBuffer.arrayOffset() + 1, directSlice.arrayOffset());
}
// http://code.google.com/p/android/issues/detail?id=16184
@@ -855,4 +883,396 @@ public class BufferTest extends TestCase {
mapped.flip();
mapped.get();
}
+
+ public void testElementSizeShifts() {
+ // Element size shifts are the log base 2 of the element size
+ // of this buffer.
+ assertEquals(1, 1 << ByteBuffer.allocate(0).getElementSizeShift());
+
+ assertEquals(SizeOf.CHAR, 1 << CharBuffer.allocate(0).getElementSizeShift());
+ assertEquals(SizeOf.SHORT, 1 << ShortBuffer.allocate(0).getElementSizeShift());
+
+ assertEquals(SizeOf.INT, 1 << IntBuffer.allocate(0).getElementSizeShift());
+ assertEquals(SizeOf.FLOAT, 1 << FloatBuffer.allocate(0).getElementSizeShift());
+
+ assertEquals(SizeOf.LONG, 1 << LongBuffer.allocate(0).getElementSizeShift());
+ assertEquals(SizeOf.DOUBLE, 1 << DoubleBuffer.allocate(0).getElementSizeShift());
+ }
+
+ public void testFreed() {
+ ByteBuffer b1 = ByteBuffer.allocateDirect(1);
+ ByteBuffer b2 = b1.duplicate();
+ NioUtils.freeDirectBuffer(b1);
+ for (ByteBuffer b: new ByteBuffer[] { b1, b2 }) {
+ assertFalse(b.isAccessible());
+ try {
+ b.compact();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.duplicate();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ testFailForPutMethods(b);
+ testFailForAsMethods(b);
+ testFailForGetMethods(b);
+ NioUtils.freeDirectBuffer(b); // should be able to free twice
+ }
+ }
+
+ public void testAccess() {
+ ByteBuffer b1 = ByteBuffer.allocate(1);
+ ByteBuffer b2 = b1.duplicate();
+ for (ByteBuffer b: new ByteBuffer[] { b1, b2 }) {
+ try {
+ b.setAccessible(true);
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ try {
+ b.setAccessible(false);
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ }
+ b1 = ByteBuffer.allocateDirect(8);
+ b2 = b1.duplicate();
+ b1.setAccessible(false);
+ ByteBuffer b3 = b1.asReadOnlyBuffer();
+ for (ByteBuffer b: new ByteBuffer[] { b1, b2, b3 }) {
+ b.duplicate();
+ assertFalse(b.isAccessible());
+ // even read-only buffers should fail with IllegalStateException
+ testFailForPutMethods(b);
+ testAsMethods(b);
+ testFailForGetMethods(b);
+ b.position(0);
+ b.limit(8);
+ try {
+ b.asCharBuffer().get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asShortBuffer().get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asIntBuffer().get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asLongBuffer().get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asFloatBuffer().get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asDoubleBuffer().get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ }
+ b2.setAccessible(true);
+ for (ByteBuffer b: new ByteBuffer[] { b1, b2, b3 }) {
+ assertTrue(b.isAccessible());
+ b.position(0);
+ b.limit(8);
+ b.asCharBuffer().get(0);
+ b.asShortBuffer().get(0);
+ b.asIntBuffer().get(0);
+ b.asLongBuffer().get(0);
+ b.asFloatBuffer().get(0);
+ b.asDoubleBuffer().get(0);
+ if (!b.isReadOnly()) {
+ testPutMethods(b);
+ b.compact();
+ } else {
+ try {
+ b.put(0, (byte) 0);
+ fail();
+ } catch (ReadOnlyBufferException expected) {
+ }
+ }
+ testAsMethods(b);
+ testGetMethods(b);
+ }
+ }
+
+ private void testPutMethods(ByteBuffer b) {
+ b.position(0);
+ b.put((byte) 0);
+ b.put(0, (byte) 0);
+ b.put(new byte[1]);
+ b.put(new byte[1], 0, 1);
+ b.put(ByteBuffer.allocate(1));
+ b.putChar('a');
+ b.putChar(0, 'a');
+ b.position(0);
+ b.putDouble(0);
+ b.putDouble(0, 0);
+ b.position(0);
+ b.putFloat(0);
+ b.putFloat(0, 0);
+ b.putInt(0);
+ b.putInt(0, 0);
+ b.position(0);
+ b.putLong(0);
+ b.putLong(0, 0);
+ b.position(0);
+ b.putShort((short) 0);
+ b.putShort(0, (short) 0);
+ }
+
+ private void testFailForPutMethods(ByteBuffer b) {
+ try {
+ b.put((byte) 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.put(0, (byte) 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.put(new byte[1]);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.put(new byte[1], 0, 1);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.put(ByteBuffer.allocate(1));
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putChar('a');
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putChar(0, 'a');
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putDouble(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putDouble(0, 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putFloat(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putFloat(0, 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putInt(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putInt(0, 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putLong(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putLong(0, 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putShort((short) 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.putShort(0, (short) 0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ private void testGetMethods(ByteBuffer b) {
+ b.position(0);
+ b.get();
+ b.get(0);
+ b.get(new byte[1]);
+ b.get(new byte[1], 0, 1);
+ b.getChar();
+ b.getChar(0);
+ b.position(0);
+ b.getDouble();
+ b.getDouble(0);
+ b.position(0);
+ b.getFloat();
+ b.getFloat(0);
+ b.getInt();
+ b.getInt(0);
+ b.position(0);
+ b.getLong();
+ b.getLong(0);
+ b.position(0);
+ b.getShort();
+ b.getShort(0);
+ }
+
+ private void testFailForGetMethods(ByteBuffer b) {
+ try {
+ b.get();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.get(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.get(new byte[1]);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.get(new byte[1], 0, 1);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getChar();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getChar(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getDouble();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getDouble(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getFloat();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getFloat(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getInt();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getInt(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getLong();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getLong(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getShort();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.getShort(0);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ }
+
+ private void testAsMethods(ByteBuffer b) {
+ b.asCharBuffer();
+ b.asDoubleBuffer();
+ b.asFloatBuffer();
+ b.asIntBuffer();
+ b.asLongBuffer();
+ b.asReadOnlyBuffer();
+ b.asShortBuffer();
+ }
+
+ private void testFailForAsMethods(ByteBuffer b) {
+ try {
+ b.asCharBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asDoubleBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asFloatBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asIntBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asLongBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asReadOnlyBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ try {
+ b.asShortBuffer();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ }
+
}
diff --git a/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java
index 13757d2..efcfece 100644
--- a/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java
@@ -16,9 +16,19 @@
package libcore.java.nio.channels;
+import java.io.IOException;
import java.net.DatagramSocket;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
+import java.nio.channels.UnresolvedAddressException;
+import java.util.Enumeration;
+import java.util.Set;
public class DatagramChannelTest extends junit.framework.TestCase {
public void test_read_intoReadOnlyByteArrays() throws Exception {
@@ -55,4 +65,110 @@ public class DatagramChannelTest extends junit.framework.TestCase {
dc.close();
}
}
+
+ public void testInitialState() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ try {
+ DatagramSocket socket = dc.socket();
+ assertFalse(socket.isBound());
+ assertFalse(socket.getBroadcast());
+ assertFalse(socket.isClosed());
+ assertFalse(socket.isConnected());
+ assertEquals(0, socket.getLocalPort());
+ assertTrue(socket.getLocalAddress().isAnyLocalAddress());
+ assertNull(socket.getLocalSocketAddress());
+ assertNull(socket.getInetAddress());
+ assertEquals(-1, socket.getPort());
+ assertNull(socket.getRemoteSocketAddress());
+ assertFalse(socket.getReuseAddress());
+
+ assertSame(dc, socket.getChannel());
+ } finally {
+ dc.close();
+ }
+ }
+
+ public void test_bind_unresolvedAddress() throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ try {
+ dc.socket().bind(new InetSocketAddress("unresolvedname", 31415));
+ fail();
+ } catch (IOException expected) {
+ }
+
+ assertTrue(dc.isOpen());
+ assertFalse(dc.isConnected());
+
+ dc.close();
+ }
+
+ public void test_bind_any_IPv4() throws Exception {
+ test_bind_any(InetAddress.getByName("0.0.0.0"));
+ }
+
+ public void test_bind_any_IPv6() throws Exception {
+ test_bind_any(InetAddress.getByName("::"));
+ }
+
+ private void test_bind_any(InetAddress bindAddress) throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(bindAddress, 0));
+
+ assertTrue(dc.isOpen());
+ assertFalse(dc.isConnected());
+
+ InetSocketAddress actualAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
+ assertTrue(actualAddress.getAddress().isAnyLocalAddress());
+ assertTrue(actualAddress.getPort() > 0);
+
+ dc.close();
+ }
+
+ public void test_bind_loopback_IPv4() throws Exception {
+ test_bind(InetAddress.getByName("127.0.0.1"));
+ }
+
+ public void test_bind_loopback_IPv6() throws Exception {
+ test_bind(InetAddress.getByName("::1"));
+ }
+
+ public void test_bind_IPv4() throws Exception {
+ InetAddress bindAddress = getNonLoopbackNetworkInterfaceAddress(true /* ipv4 */);
+ test_bind(bindAddress);
+ }
+
+ public void test_bind_IPv6() throws Exception {
+ InetAddress bindAddress = getNonLoopbackNetworkInterfaceAddress(false /* ipv4 */);
+ test_bind(bindAddress);
+ }
+
+ private void test_bind(InetAddress bindAddress) throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(bindAddress, 0));
+
+ InetSocketAddress actualAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
+ assertEquals(bindAddress, actualAddress.getAddress());
+ assertTrue(actualAddress.getPort() > 0);
+
+ dc.close();
+ }
+
+ private static InetAddress getNonLoopbackNetworkInterfaceAddress(boolean ipv4) throws IOException {
+ Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
+ while (networkInterfaces.hasMoreElements()) {
+ NetworkInterface networkInterface = networkInterfaces.nextElement();
+ if (networkInterface.isLoopback() || !networkInterface.isUp()) {
+ continue;
+ }
+ Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
+ while (inetAddresses.hasMoreElements()) {
+ InetAddress inetAddress = inetAddresses.nextElement();
+ if ( (ipv4 && inetAddress instanceof Inet4Address)
+ || (!ipv4 && inetAddress instanceof Inet6Address)) {
+ return inetAddress;
+ }
+ }
+ }
+ return null;
+ }
}
diff --git a/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java
index 415ae0a..babbf41 100644
--- a/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/FileChannelTest.java
@@ -19,6 +19,8 @@ package libcore.java.nio.channels;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import libcore.io.IoUtils;
@@ -110,4 +112,121 @@ public class FileChannelTest extends junit.framework.TestCase {
assertEquals("hello world", new String(IoUtils.readFileAsString(tmp.getPath())));
}
+
+ public void test_position_writeAddsPadding() throws Exception {
+ byte[] initialBytes = "12345".getBytes("US-ASCII");
+ int initialFileSize = initialBytes.length; // 5
+ FileChannel fc = createFileContainingBytes(initialBytes);
+
+ int positionBeyondSize = 10;
+ fc.position(positionBeyondSize);
+ assertEquals(positionBeyondSize, fc.position());
+ assertEquals(initialFileSize, fc.size());
+
+ byte[] newBytes = "6789A".getBytes("US-ASCII");
+ fc.write(ByteBuffer.wrap(newBytes));
+
+ int expectedNewLength = positionBeyondSize + newBytes.length;
+ assertEquals(expectedNewLength, fc.position());
+ assertEquals(expectedNewLength, fc.size());
+
+ fc.close();
+ }
+
+ public void test_truncate_greaterThanSizeWithPositionChange() throws Exception {
+ byte[] initialBytes = "12345".getBytes("US-ASCII");
+ int initialFileSize = initialBytes.length; // 5
+ FileChannel fc = createFileContainingBytes(initialBytes);
+
+ int initialPosition = 40;
+ fc.position(initialPosition); // Should not affect the file size
+ assertEquals(initialPosition, fc.position());
+ assertEquals(initialFileSize, fc.size());
+
+ // truncateArg < position, truncateArg > initialFileSize: Should not affect the file size
+ // and should move the position.
+ int truncateArg = 10;
+ fc.truncate(truncateArg); // Should not affect the file size, but should move the position.
+ assertEquals(initialFileSize, fc.size());
+ // The RI does not behave properly here, according to the docs for truncate(), position()
+ // should now be the same as truncateArg.
+ assertEquals(truncateArg, fc.position());
+
+ fc.close();
+ }
+
+ public void test_truncate_greaterThanSizeWithoutPositionChange() throws Exception {
+ byte[] initialBytes = "123456789A".getBytes("US-ASCII");
+ int initialFileSize = initialBytes.length; // 10
+ FileChannel fc = createFileContainingBytes(initialBytes);
+
+ int initialPosition = 5;
+ fc.position(initialPosition);
+ assertEquals(initialPosition, fc.position());
+ assertEquals(initialFileSize, fc.size());
+
+ // truncateArg > position, truncateArg > initialFileSize: Should not affect the file size
+ // and should not move the position.
+ int truncateArg = 15;
+ fc.truncate(truncateArg);
+ assertEquals(initialFileSize, fc.size());
+ assertEquals(initialPosition, fc.position());
+
+ fc.close();
+ }
+
+ public void test_truncate_lessThanSizeWithPositionChange() throws Exception {
+ byte[] initialBytes = "123456789A".getBytes("US-ASCII");
+ int initialFileSize = initialBytes.length; // 10
+ FileChannel fc = createFileContainingBytes(initialBytes);
+
+ int initialPosition = initialFileSize;
+ fc.position(initialPosition);
+ assertEquals(initialPosition, fc.position());
+ assertEquals(initialFileSize, fc.size());
+
+ int truncateArg = 5;
+ // truncateArg < initialPosition, truncateArg < initialFileSize: Should affect the file size
+ // and should move the position.
+ fc.truncate(truncateArg);
+ assertEquals(truncateArg, fc.size());
+ assertEquals(truncateArg, fc.position());
+
+ fc.close();
+ }
+
+ public void test_truncate_lessThanSizeWithoutPositionChange() throws Exception {
+ byte[] initialBytes = "123456789A".getBytes("US-ASCII");
+ int initialFileSize = initialBytes.length; // 10
+ FileChannel fc = createFileContainingBytes(initialBytes);
+
+ int initialPosition = 4;
+ fc.position(initialPosition);
+ assertEquals(initialPosition, fc.position());
+ assertEquals(initialFileSize, fc.size());
+
+ int truncateArg = 5;
+ // truncateArg > initialPosition, truncateArg < initialFileSize: Should affect the file size
+ // and should not move the position.
+ fc.truncate(truncateArg);
+ assertEquals(truncateArg, fc.size());
+ assertEquals(initialPosition, fc.position());
+
+ fc.close();
+ }
+
+ private static FileChannel createFileContainingBytes(byte[] bytes) throws IOException {
+ File tmp = File.createTempFile("FileChannelTest", "tmp");
+ FileOutputStream fos = new FileOutputStream(tmp, true);
+ FileChannel fc = fos.getChannel();
+ fc.write(ByteBuffer.wrap(bytes));
+ fc.close();
+
+ assertEquals(bytes.length, tmp.length());
+
+ fc = new RandomAccessFile(tmp, "rw").getChannel();
+ assertEquals(bytes.length, fc.size());
+
+ return fc;
+ }
}
diff --git a/luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java b/luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java
new file mode 100644
index 0000000..02c6f3b
--- /dev/null
+++ b/luni/src/test/java/libcore/java/nio/channels/FileIOInterruptTest.java
@@ -0,0 +1,709 @@
+/*
+ * Copyright (C) 2014 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 libcore.java.nio.channels;
+
+import junit.framework.TestCase;
+
+import android.system.OsConstants;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InterruptedIOException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.AsynchronousCloseException;
+import java.nio.channels.ClosedByInterruptException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.FileChannel;
+import libcore.io.Libcore;
+
+import static libcore.io.IoUtils.closeQuietly;
+
+/**
+ * A test for file interrupt behavior. Because forcing a real file to block on read or write is
+ * difficult this test uses Unix FIFO / Named Pipes. FIFOs appear to Java as files but the test
+ * has more control over the available data. Reader will block until the other end writes, and
+ * writers can also be made to block.
+ *
+ * <p>Using FIFOs has a few drawbacks:
+ * <ol>
+ * <li>FIFOs are not supported from Java or the command-line on Android, so this test includes
+ * native code to create the FIFO.
+ * <li>FIFOs will not open() until there is both a reader and a writer of the FIFO; each test must
+ * always attach both ends or experience a blocked test.
+ * <li>FIFOs are not supported on some file systems. e.g. VFAT, so the test has to be particular
+ * about the temporary directory it uses to hold the FIFO.
+ * <li>Writes to FIFOs are buffered by the OS which makes blocking behavior more difficult to
+ * induce. See {@link ChannelWriter} and {@link StreamWriter}.
+ * </ol>
+ */
+public class FileIOInterruptTest extends TestCase {
+
+ private static File VOGAR_DEVICE_TEMP_DIR = new File("/data/data/file_io_interrupt_test");
+
+ private File fifoFile;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+
+ // This test relies on a FIFO file. The file system must support FIFOs, so we check the path.
+ String tmpDirName = System.getProperty("java.io.tmpdir");
+ File tmpDir;
+ if (tmpDirName.startsWith("/sdcard")) {
+ // Vogar execution on device runs in /sdcard. Unfortunately the file system used does not
+ // support FIFOs so the test must use one that is more likely to work.
+ if (!VOGAR_DEVICE_TEMP_DIR.exists()) {
+ assertTrue(VOGAR_DEVICE_TEMP_DIR.mkdir());
+ }
+ VOGAR_DEVICE_TEMP_DIR.deleteOnExit();
+ tmpDir = VOGAR_DEVICE_TEMP_DIR;
+ } else {
+ tmpDir = new File(tmpDirName);
+ }
+ fifoFile = new File(tmpDir, "fifo_file.tmp");
+ if (fifoFile.exists()) {
+ fifoFile.delete();
+ }
+ fifoFile.deleteOnExit();
+
+ // Create the fifo. This will throw an exception if the file system does not support it.
+ Libcore.os.mkfifo(fifoFile.getAbsolutePath(), OsConstants.S_IRWXU);
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ fifoFile.delete();
+ VOGAR_DEVICE_TEMP_DIR.delete();
+
+ // Clear the interrupted state, if set.
+ Thread.interrupted();
+ }
+
+ public void testStreamRead_exceptionWhenAlreadyClosed() throws Exception {
+ FifoWriter fifoWriter = new FifoWriter(fifoFile);
+ fifoWriter.start();
+
+ FileInputStream fis = new FileInputStream(fifoFile);
+ fis.close();
+
+ byte[] buffer = new byte[10];
+ try {
+ fis.read(buffer);
+ fail();
+ } catch (IOException expected) {
+ assertSame(IOException.class, expected.getClass());
+ }
+
+ fifoWriter.tidyUp();
+ }
+
+ // This test fails on the RI: close() does not wake up a blocking FileInputStream.read() call.
+ public void testStreamRead_exceptionOnCloseWhenBlocked() throws Exception {
+ FifoWriter fifoWriter = new FifoWriter(fifoFile);
+ fifoWriter.start();
+
+ FileInputStream fis = new FileInputStream(fifoFile);
+ StreamReader streamReader = new StreamReader(fis);
+ Thread streamReaderThread = createAndStartThread("StreamReader", streamReader);
+
+ // Delay until we can be fairly sure the reader thread is blocking.
+ streamReader.waitForThreadToBlock();
+
+ // Now close the OutputStream to see what happens.
+ fis.close();
+
+ // Test for expected behavior in the reader thread.
+ waitToDie(streamReaderThread);
+ assertSame(InterruptedIOException.class, streamReader.ioe.getClass());
+ assertFalse(streamReader.wasInterrupted);
+
+ // Tidy up the writer thread.
+ fifoWriter.tidyUp();
+ }
+
+ public void testStreamWrite_exceptionWhenAlreadyClosed() throws Exception {
+ FifoReader fifoReader = new FifoReader(fifoFile);
+ fifoReader.start();
+
+ FileOutputStream fos = new FileOutputStream(fifoFile);
+ byte[] buffer = new byte[10];
+ fos.close();
+
+ try {
+ fos.write(buffer);
+ fail();
+ } catch (IOException expected) {
+ assertSame(IOException.class, expected.getClass());
+ }
+
+ fifoReader.tidyUp();
+ }
+
+ // This test fails on the RI: close() does not wake up a blocking FileInputStream.write() call.
+ public void testStreamWrite_exceptionOnCloseWhenBlocked() throws Exception {
+ FifoReader fifoReader = new FifoReader(fifoFile);
+ fifoReader.start();
+
+ FileOutputStream fos = new FileOutputStream(fifoFile);
+ StreamWriter streamWriter = new StreamWriter(fos);
+ Thread streamWriterThread = createAndStartThread("StreamWriter", streamWriter);
+
+ // Delay until we can be fairly sure the writer thread is blocking.
+ streamWriter.waitForThreadToBlock();
+
+ // Now close the OutputStream to see what happens.
+ fos.close();
+
+ // Test for expected behavior in the writer thread.
+ waitToDie(streamWriterThread);
+ assertSame(InterruptedIOException.class, streamWriter.ioe.getClass());
+ assertFalse(streamWriter.wasInterrupted);
+
+ // Tidy up the reader thread.
+ fifoReader.tidyUp();
+ }
+
+ public void testChannelRead_exceptionWhenAlreadyClosed() throws Exception {
+ testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method.READ);
+ }
+
+ public void testChannelReadV_exceptionWhenAlreadyClosed() throws Exception {
+ testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method.READV);
+ }
+
+ private void testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method method)
+ throws Exception {
+ FifoWriter fifoWriter = new FifoWriter(fifoFile);
+ fifoWriter.start();
+ FileInputStream fis = new FileInputStream(fifoFile);
+ FileChannel fileInputChannel = fis.getChannel();
+ fileInputChannel.close();
+
+ ByteBuffer buffer = ByteBuffer.allocateDirect(10);
+ try {
+ if (method == ChannelReader.Method.READ) {
+ fileInputChannel.read(buffer);
+ } else {
+ ByteBuffer buffer2 = ByteBuffer.allocateDirect(10);
+ fileInputChannel.read(new ByteBuffer[] { buffer, buffer2});
+ }
+ fail();
+ } catch (IOException expected) {
+ assertSame(ClosedChannelException.class, expected.getClass());
+ }
+
+ fifoWriter.tidyUp();
+ }
+
+ public void testChannelRead_exceptionWhenAlreadyInterrupted() throws Exception {
+ testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method.READ);
+ }
+
+ public void testChannelReadV_exceptionWhenAlreadyInterrupted() throws Exception {
+ testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method.READV);
+ }
+
+ private void testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method method)
+ throws Exception {
+ FifoWriter fifoWriter = new FifoWriter(fifoFile);
+ fifoWriter.start();
+ FileInputStream fis = new FileInputStream(fifoFile);
+ FileChannel fileInputChannel = fis.getChannel();
+
+ Thread.currentThread().interrupt();
+
+ ByteBuffer buffer = ByteBuffer.allocateDirect(10);
+ try {
+ if (method == ChannelReader.Method.READ) {
+ fileInputChannel.read(buffer);
+ } else {
+ ByteBuffer buffer2 = ByteBuffer.allocateDirect(10);
+ fileInputChannel.read(new ByteBuffer[] { buffer, buffer2});
+ }
+ fail();
+ } catch (IOException expected) {
+ assertSame(ClosedByInterruptException.class, expected.getClass());
+ }
+
+ // Check but also clear the interrupted status, so we can wait for the FifoWriter thread in
+ // tidyUp().
+ assertTrue(Thread.interrupted());
+
+ fifoWriter.tidyUp();
+ }
+
+ public void testChannelRead_exceptionOnCloseWhenBlocked() throws Exception {
+ testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method.READ);
+ }
+
+ public void testChannelReadV_exceptionOnCloseWhenBlocked() throws Exception {
+ testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method.READV);
+ }
+
+ private void testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method method)
+ throws Exception {
+ FifoWriter fifoWriter = new FifoWriter(fifoFile);
+ fifoWriter.start();
+ FileInputStream fis = new FileInputStream(fifoFile);
+ FileChannel fileInputChannel = fis.getChannel();
+
+ ChannelReader channelReader = new ChannelReader(fileInputChannel, method);
+ Thread channelReaderThread = createAndStartThread("ChannelReader", channelReader);
+
+ // Delay until we can be fairly sure the reader thread is blocking.
+ channelReader.waitForThreadToBlock();
+
+ // Now close the FileChannel to see what happens.
+ fileInputChannel.close();
+
+ // Test for expected behavior in the reader thread.
+ waitToDie(channelReaderThread);
+ assertSame(AsynchronousCloseException.class, channelReader.ioe.getClass());
+ assertFalse(channelReader.wasInterrupted);
+
+ // Tidy up the writer thread.
+ fifoWriter.tidyUp();
+ }
+
+ public void testChannelRead_exceptionOnInterrupt() throws Exception {
+ testChannelRead_exceptionOnInterrupt(ChannelReader.Method.READ);
+ }
+
+ public void testChannelReadV_exceptionOnInterrupt() throws Exception {
+ testChannelRead_exceptionOnInterrupt(ChannelReader.Method.READV);
+ }
+
+ private void testChannelRead_exceptionOnInterrupt(ChannelReader.Method method) throws Exception {
+ FifoWriter fifoWriter = new FifoWriter(fifoFile);
+ fifoWriter.start();
+ FileChannel fileChannel = new FileInputStream(fifoFile).getChannel();
+
+ ChannelReader channelReader = new ChannelReader(fileChannel, method);
+ Thread channelReaderThread = createAndStartThread("ChannelReader", channelReader);
+
+ // Delay until we can be fairly sure the reader thread is blocking.
+ channelReader.waitForThreadToBlock();
+
+ // Now interrupt the reader thread to see what happens.
+ channelReaderThread.interrupt();
+
+ // Test for expected behavior in the reader thread.
+ waitToDie(channelReaderThread);
+ assertSame(ClosedByInterruptException.class, channelReader.ioe.getClass());
+ assertTrue(channelReader.wasInterrupted);
+
+ // Tidy up the writer thread.
+ fifoWriter.tidyUp();
+ }
+
+ public void testChannelWrite_exceptionWhenAlreadyClosed() throws Exception {
+ testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method.WRITE);
+ }
+
+ public void testChannelWriteV_exceptionWhenAlreadyClosed() throws Exception {
+ testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method.WRITEV);
+ }
+
+ private void testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method method)
+ throws Exception {
+ FifoReader fifoReader = new FifoReader(fifoFile);
+ fifoReader.start();
+ FileChannel fileOutputChannel = new FileOutputStream(fifoFile).getChannel();
+ fileOutputChannel.close();
+
+ ByteBuffer buffer = ByteBuffer.allocateDirect(10);
+ try {
+ if (method == ChannelWriter.Method.WRITE) {
+ fileOutputChannel.write(buffer);
+ } else {
+ ByteBuffer buffer2 = ByteBuffer.allocateDirect(10);
+ fileOutputChannel.write(new ByteBuffer[] { buffer, buffer2 });
+ }
+ fail();
+ } catch (IOException expected) {
+ assertSame(ClosedChannelException.class, expected.getClass());
+ }
+
+ fifoReader.tidyUp();
+ }
+
+ public void testChannelWrite_exceptionWhenAlreadyInterrupted() throws Exception {
+ testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method.WRITE);
+ }
+
+ public void testChannelWriteV_exceptionWhenAlreadyInterrupted() throws Exception {
+ testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method.WRITEV);
+ }
+
+ private void testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method method)
+ throws Exception {
+ FifoReader fifoReader = new FifoReader(fifoFile);
+ fifoReader.start();
+ FileOutputStream fos = new FileOutputStream(fifoFile);
+ FileChannel fileInputChannel = fos.getChannel();
+
+ Thread.currentThread().interrupt();
+
+ ByteBuffer buffer = ByteBuffer.allocateDirect(10);
+ try {
+ if (method == ChannelWriter.Method.WRITE) {
+ fileInputChannel.write(buffer);
+ } else {
+ ByteBuffer buffer2 = ByteBuffer.allocateDirect(10);
+ fileInputChannel.write(new ByteBuffer[] { buffer, buffer2 });
+ }
+ fail();
+ } catch (IOException expected) {
+ assertSame(ClosedByInterruptException.class, expected.getClass());
+ }
+
+ // Check but also clear the interrupted status, so we can wait for the FifoReader thread in
+ // tidyUp().
+ assertTrue(Thread.interrupted());
+
+ fifoReader.tidyUp();
+ }
+
+ public void testChannelWrite_exceptionOnCloseWhenBlocked() throws Exception {
+ testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method.WRITE);
+ }
+
+ public void testChannelWriteV_exceptionOnCloseWhenBlocked() throws Exception {
+ testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method.WRITEV);
+ }
+
+ private void testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method method)
+ throws Exception {
+ FifoReader fifoReader = new FifoReader(fifoFile);
+ fifoReader.start();
+ FileChannel fileOutputChannel = new FileOutputStream(fifoFile).getChannel();
+
+ ChannelWriter channelWriter = new ChannelWriter(fileOutputChannel, method);
+ Thread channelWriterThread = createAndStartThread("ChannelWriter", channelWriter);
+
+ // Delay until we can be fairly sure the writer thread is blocking.
+ channelWriter.waitForThreadToBlock();
+
+ // Now close the channel to see what happens.
+ fileOutputChannel.close();
+
+ // Test for expected behavior in the writer thread.
+ waitToDie(channelWriterThread);
+ // The RI throws ChannelClosedException. AsynchronousCloseException is more correct according to
+ // the docs.
+ assertSame(AsynchronousCloseException.class, channelWriter.ioe.getClass());
+ assertFalse(channelWriter.wasInterrupted);
+
+ // Tidy up the writer thread.
+ fifoReader.tidyUp();
+ }
+
+ public void testChannelWrite_exceptionOnInterrupt() throws Exception {
+ testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method.WRITE);
+ }
+
+ public void testChannelWriteV_exceptionOnInterrupt() throws Exception {
+ testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method.WRITEV);
+ }
+
+ private void testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method method) throws Exception {
+ FifoReader fifoReader = new FifoReader(fifoFile);
+ fifoReader.start();
+
+ FileChannel fileChannel = new FileOutputStream(fifoFile).getChannel();
+ ChannelWriter channelWriter = new ChannelWriter(fileChannel, method);
+ Thread channelWriterThread = createAndStartThread("ChannelWriter", channelWriter);
+
+ // Delay until we can be fairly sure the writer thread is blocking.
+ channelWriter.waitForThreadToBlock();
+
+ // Now interrupt the writer thread to see what happens.
+ channelWriterThread.interrupt();
+
+ // Test for expected behavior in the writer thread.
+ waitToDie(channelWriterThread);
+ assertSame(ClosedByInterruptException.class, channelWriter.ioe.getClass());
+ assertTrue(channelWriter.wasInterrupted);
+
+ // Tidy up the reader thread.
+ fifoReader.tidyUp();
+ }
+
+ private static class StreamReader implements Runnable {
+
+ private final FileInputStream inputStream;
+ volatile boolean started;
+ volatile IOException ioe;
+ volatile boolean wasInterrupted;
+
+ StreamReader(FileInputStream inputStream) {
+ this.inputStream = inputStream;
+ }
+
+ @Override
+ public void run() {
+ byte[] buffer = new byte[10];
+ try {
+ started = true;
+ int bytesRead = inputStream.read(buffer);
+ fail("This isn't supposed to happen: read() returned: " + bytesRead);
+ } catch (IOException e) {
+ this.ioe = e;
+ }
+ wasInterrupted = Thread.interrupted();
+ }
+
+ public void waitForThreadToBlock() {
+ for (int i = 0; i < 10 && !started; i++) {
+ delay(100);
+ }
+ assertTrue(started);
+ // Just give it some more time to start blocking.
+ delay(100);
+ }
+ }
+
+ private static class StreamWriter implements Runnable {
+
+ private final FileOutputStream outputStream;
+ volatile int bytesWritten;
+ volatile IOException ioe;
+ volatile boolean wasInterrupted;
+
+ StreamWriter(FileOutputStream outputStream) {
+ this.outputStream = outputStream;
+ }
+
+ @Override
+ public void run() {
+ // Writes to FIFOs are buffered. We try to fill the buffer and induce blocking (the
+ // buffer is typically 64k).
+ byte[] buffer = new byte[10000];
+ while (true) {
+ try {
+ outputStream.write(buffer);
+ bytesWritten += buffer.length;
+ } catch (IOException e) {
+ this.ioe = e;
+ break;
+ }
+ wasInterrupted = Thread.interrupted();
+ }
+ }
+
+ public void waitForThreadToBlock() {
+ int lastCount = bytesWritten;
+ for (int i = 0; i < 10; i++) {
+ delay(500);
+ int newBytesWritten = bytesWritten;
+ if (newBytesWritten > 0 && lastCount == newBytesWritten) {
+ // The thread is probably blocking.
+ return;
+ }
+ lastCount = bytesWritten;
+ }
+ fail("Writer never started blocking. Bytes written: " + bytesWritten);
+ }
+ }
+
+ private static class ChannelReader implements Runnable {
+ enum Method {
+ READ,
+ READV,
+ }
+
+ private final FileChannel channel;
+ private final Method method;
+ volatile boolean started;
+ volatile IOException ioe;
+ volatile boolean wasInterrupted;
+
+ ChannelReader(FileChannel channel, Method method) {
+ this.channel = channel;
+ this.method = method;
+ }
+
+ @Override
+ public void run() {
+ ByteBuffer buffer = ByteBuffer.allocateDirect(10);
+ try {
+ started = true;
+ if (method == Method.READ) {
+ channel.read(buffer);
+ } else {
+ ByteBuffer buffer2 = ByteBuffer.allocateDirect(10);
+ channel.read(new ByteBuffer[] { buffer, buffer2 });
+ }
+ fail("All tests should block until an exception");
+ } catch (IOException e) {
+ this.ioe = e;
+ }
+ wasInterrupted = Thread.interrupted();
+ }
+
+ public void waitForThreadToBlock() {
+ for (int i = 0; i < 10 && !started; i++) {
+ delay(100);
+ }
+ assertTrue(started);
+ // Just give it some more time to start blocking.
+ delay(100);
+ }
+ }
+
+ private static class ChannelWriter implements Runnable {
+ enum Method {
+ WRITE,
+ WRITEV,
+ }
+
+ private final FileChannel channel;
+ private final Method method;
+ volatile int bytesWritten;
+ volatile IOException ioe;
+ volatile boolean wasInterrupted;
+
+ ChannelWriter(FileChannel channel, Method method) {
+ this.channel = channel;
+ this.method = method;
+ }
+
+ @Override
+ public void run() {
+ ByteBuffer buffer1 = ByteBuffer.allocateDirect(10000);
+ ByteBuffer buffer2 = ByteBuffer.allocateDirect(10000);
+ // Writes to FIFOs are buffered. We try to fill the buffer and induce blocking (the
+ // buffer is typically 64k).
+ while (true) {
+ // Make the buffers look non-empty.
+ buffer1.position(0).limit(buffer1.capacity());
+ buffer2.position(0).limit(buffer2.capacity());
+ try {
+ if (method == Method.WRITE) {
+ bytesWritten += channel.write(buffer1);
+ } else {
+ bytesWritten += channel.write(new ByteBuffer[]{ buffer1, buffer2 });
+ }
+ } catch (IOException e) {
+ this.ioe = e;
+ break;
+ }
+ }
+ wasInterrupted = Thread.interrupted();
+ }
+
+ public void waitForThreadToBlock() {
+ int lastCount = bytesWritten;
+ for (int i = 0; i < 10; i++) {
+ delay(500);
+ int newBytesWritten = bytesWritten;
+ if (newBytesWritten > 0 && lastCount == newBytesWritten) {
+ // The thread is probably blocking.
+ return;
+ }
+ lastCount = bytesWritten;
+ }
+ fail("Writer never started blocking. Bytes written: " + bytesWritten);
+ }
+ }
+
+ /**
+ * Opens a FIFO for writing. Exists to unblock the other end of the FIFO.
+ */
+ private static class FifoWriter extends Thread {
+
+ private final File file;
+ private FileOutputStream fos;
+
+ public FifoWriter(File file) {
+ super("FifoWriter");
+ this.file = file;
+ }
+
+ @Override
+ public void run() {
+ try {
+ fos = new FileOutputStream(file);
+ } catch (IOException ignored) {
+ }
+ }
+
+ public void tidyUp() {
+ FileIOInterruptTest.waitToDie(this);
+ closeQuietly(fos);
+ }
+ }
+
+ /**
+ * Opens a FIFO for reading. Exists to unblock the other end of the FIFO.
+ */
+ private static class FifoReader extends Thread {
+
+ private final File file;
+ private FileInputStream fis;
+
+ public FifoReader(File file) {
+ super("FifoReader");
+ this.file = file;
+ }
+
+ @Override
+ public void run() {
+ try {
+ fis = new FileInputStream(file);
+ } catch (IOException ignored) {
+ }
+ }
+
+ public void tidyUp() {
+ FileIOInterruptTest.waitToDie(this);
+ closeQuietly(fis);
+ }
+ }
+
+ private static Thread createAndStartThread(String name, Runnable runnable) {
+ Thread t = new Thread(runnable, name);
+ t.setDaemon(true);
+ t.start();
+ return t;
+ }
+
+ private static void waitToDie(Thread thread) {
+ // Protect against this thread already being interrupted, which would prevent the test waiting
+ // for the requested time.
+ assertFalse(Thread.currentThread().isInterrupted());
+ try {
+ thread.join(5000);
+ } catch (InterruptedException ignored) {
+ }
+
+ if (thread.isAlive()) {
+ fail("Thread \"" + thread.getName() + "\" did not exit.");
+ }
+ }
+
+ private static void delay(int millis) {
+ // Protect against this thread being interrupted, which would prevent us waiting.
+ assertFalse(Thread.currentThread().isInterrupted());
+ try {
+ Thread.sleep(millis);
+ } catch (InterruptedException ignored) {
+ }
+ }
+
+}
diff --git a/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java
index 6560a7b..f849c33 100644
--- a/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java
@@ -17,9 +17,7 @@
package libcore.java.nio.channels;
-import dalvik.annotation.BrokenTest;
import java.io.IOException;
-import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
@@ -198,14 +196,12 @@ public class OldSocketChannelTest extends TestCase {
// expected
}
- SocketChannel channel1IP = null;
try {
- channel1IP = SocketChannel.open(null);
+ SocketChannel.open(null);
fail("Should throw an IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
}
- assertNull(channel1IP);
}
private void ensureServerClosed() throws IOException {
@@ -238,7 +234,7 @@ public class OldSocketChannelTest extends TestCase {
return connected;
}
- @BrokenTest("Occasionally fail in CTS, but works in CoreTestRunner")
+ // Broken Test: Occasionally fail in CTS, but works in CoreTestRunner
public void test_writeLjava_nio_ByteBuffer_Nonblocking_HugeData() throws IOException {
// initialize write content
ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_HUGE);
@@ -355,48 +351,59 @@ public class OldSocketChannelTest extends TestCase {
isConstructorCalled = true;
}
+ @Override
public Socket socket() {
return null;
}
+ @Override
public boolean isConnected() {
return false;
}
+ @Override
public boolean isConnectionPending() {
return false;
}
+ @Override
public boolean connect(SocketAddress address) throws IOException {
return false;
}
+ @Override
public boolean finishConnect() throws IOException {
return false;
}
+ @Override
public int read(ByteBuffer target) throws IOException {
return 0;
}
+ @Override
public long read(ByteBuffer[] targets, int offset, int length)
throws IOException {
return 0;
}
+ @Override
public int write(ByteBuffer source) throws IOException {
return 0;
}
+ @Override
public long write(ByteBuffer[] sources, int offset, int length)
throws IOException {
return 0;
}
+ @Override
protected void implCloseSelectableChannel() throws IOException {
// empty
}
+ @Override
protected void implConfigureBlocking(boolean blockingMode)
throws IOException {
// empty
diff --git a/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java b/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java
index b45f8e1..c5f449e 100644
--- a/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/SelectorTest.java
@@ -15,6 +15,7 @@
*/
package libcore.java.nio.channels;
+import android.system.OsConstants;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
@@ -26,9 +27,8 @@ import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import libcore.io.Libcore;
-import libcore.io.OsConstants;
import junit.framework.TestCase;
+import libcore.io.Libcore;
import tests.net.StuckServer;
public class SelectorTest extends TestCase {
@@ -93,11 +93,15 @@ public class SelectorTest extends TestCase {
// http://code.google.com/p/android/issues/detail?id=15388
public void testInterrupted() throws IOException {
Selector selector = Selector.open();
+ Thread.currentThread().interrupt();
try {
- Thread.currentThread().interrupt();
int count = selector.select();
assertEquals(0, count);
+ assertTrue(Thread.currentThread().isInterrupted());
} finally {
+ // Clear the interrupted thread state so that it does not interfere with later tests.
+ Thread.interrupted();
+
selector.close();
}
}
diff --git a/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java
index e66096c..1178b70 100644
--- a/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java
@@ -16,7 +16,18 @@
package libcore.java.nio.channels;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
+import java.net.ServerSocket;
+import java.net.SocketException;
+import java.nio.channels.ClosedChannelException;
import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.UnresolvedAddressException;
+import java.util.Enumeration;
+import java.util.Set;
public class ServerSocketChannelTest extends junit.framework.TestCase {
// http://code.google.com/p/android/issues/detail?id=16579
@@ -31,4 +42,107 @@ public class ServerSocketChannelTest extends junit.framework.TestCase {
ssc.close();
}
}
+
+ /** Checks the state of the ServerSocketChannel and associated ServerSocket after open() */
+ public void test_open_initialState() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ try {
+ assertNull(ssc.socket().getLocalSocketAddress());
+
+ ServerSocket socket = ssc.socket();
+ assertFalse(socket.isBound());
+ assertFalse(socket.isClosed());
+ assertEquals(-1, socket.getLocalPort());
+ assertNull(socket.getLocalSocketAddress());
+ assertNull(socket.getInetAddress());
+ assertTrue(socket.getReuseAddress());
+
+ assertSame(ssc, socket.getChannel());
+ } finally {
+ ssc.close();
+ }
+ }
+
+ public void test_bind_unresolvedAddress() throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ try {
+ ssc.socket().bind(new InetSocketAddress("unresolvedname", 31415));
+ fail();
+ } catch (SocketException expected) {
+ }
+
+ assertNull(ssc.socket().getLocalSocketAddress());
+ assertTrue(ssc.isOpen());
+
+ ssc.close();
+ }
+
+ public void test_bind_nullBindsToAll() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(null);
+ InetSocketAddress boundAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
+ assertTrue(boundAddress.getAddress().isAnyLocalAddress());
+ assertFalse(boundAddress.getAddress().isLinkLocalAddress());
+ assertFalse(boundAddress.getAddress().isLoopbackAddress());
+
+ // Attempt to connect to the "any" address.
+ assertTrue(canConnect(boundAddress));
+
+ // Go through all local IPs and try to connect to each in turn - all should succeed.
+ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ while (interfaces.hasMoreElements()) {
+ NetworkInterface nic = interfaces.nextElement();
+ Enumeration<InetAddress> inetAddresses = nic.getInetAddresses();
+ while (inetAddresses.hasMoreElements()) {
+ InetSocketAddress address =
+ new InetSocketAddress(inetAddresses.nextElement(), boundAddress.getPort());
+ assertTrue(canConnect(address));
+ }
+ }
+
+ ssc.close();
+ }
+
+ public void test_bind_loopback() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
+ InetSocketAddress boundAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
+ assertFalse(boundAddress.getAddress().isAnyLocalAddress());
+ assertFalse(boundAddress.getAddress().isLinkLocalAddress());
+ assertTrue(boundAddress.getAddress().isLoopbackAddress());
+
+ // Attempt to connect to the "loopback" address. Note: There can be several loopback
+ // addresses, such as 127.0.0.1 (IPv4) and 0:0:0:0:0:0:0:1 (IPv6) and only one will be
+ // bound.
+ InetSocketAddress loopbackAddress =
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), boundAddress.getPort());
+ assertTrue(canConnect(loopbackAddress));
+
+ // Go through all local IPs and try to connect to each in turn - all should fail except
+ // for the loopback.
+ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
+ while (interfaces.hasMoreElements()) {
+ NetworkInterface nic = interfaces.nextElement();
+ Enumeration<InetAddress> inetAddresses = nic.getInetAddresses();
+ while (inetAddresses.hasMoreElements()) {
+ InetSocketAddress address =
+ new InetSocketAddress(inetAddresses.nextElement(), boundAddress.getPort());
+ if (!address.equals(loopbackAddress)) {
+ assertFalse(canConnect(address));
+ }
+ }
+ }
+
+ ssc.close();
+ }
+
+ private static boolean canConnect(InetSocketAddress address) {
+ try {
+ SocketChannel socketChannel = SocketChannel.open(address);
+ socketChannel.close();
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java
index 6ab91ab..a54b30a 100644
--- a/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java
@@ -16,26 +16,37 @@
package libcore.java.nio.channels;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.net.ConnectException;
+import java.net.Socket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
-import java.nio.channels.SocketChannel;
+import java.nio.channels.UnresolvedAddressException;
+import java.util.Set;
+
import tests.io.MockOs;
-import static libcore.io.OsConstants.*;
+
+import static android.system.OsConstants.*;
public class SocketChannelTest extends junit.framework.TestCase {
+
private final MockOs mockOs = new MockOs();
- @Override public void setUp() throws Exception {
+ @Override
+ public void setUp() throws Exception {
mockOs.install();
}
- @Override protected void tearDown() throws Exception {
+ @Override
+ protected void tearDown() throws Exception {
mockOs.uninstall();
}
@@ -61,6 +72,7 @@ public class SocketChannelTest extends junit.framework.TestCase {
}
}
+ // https://code.google.com/p/android/issues/detail?id=56684
public void test_56684() throws Exception {
mockOs.enqueueFault("connect", ENETUNREACH);
@@ -78,7 +90,188 @@ public class SocketChannelTest extends junit.framework.TestCase {
try {
sc.finishConnect();
+ fail();
} catch (ClosedChannelException expected) {
}
}
+
+ /** Checks that closing a Socket's output stream also closes the Socket and SocketChannel. */
+ public void test_channelSocketOutputStreamClosureState() throws Exception {
+ ServerSocket ss = new ServerSocket(0);
+
+ SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
+ sc.configureBlocking(true);
+
+ Socket scSocket = sc.socket();
+ OutputStream os = scSocket.getOutputStream();
+
+ assertTrue(sc.isOpen());
+ assertFalse(scSocket.isClosed());
+
+ os.close();
+
+ assertFalse(sc.isOpen());
+ assertTrue(scSocket.isClosed());
+
+ ss.close();
+ }
+
+ /** Checks that closing a Socket's input stream also closes the Socket and SocketChannel. */
+ public void test_channelSocketInputStreamClosureState() throws Exception {
+ ServerSocket ss = new ServerSocket(0);
+
+ SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
+ sc.configureBlocking(true);
+
+ Socket scSocket = sc.socket();
+ InputStream is = scSocket.getInputStream();
+
+ assertTrue(sc.isOpen());
+ assertFalse(scSocket.isClosed());
+
+ is.close();
+
+ assertFalse(sc.isOpen());
+ assertTrue(scSocket.isClosed());
+
+ ss.close();
+ }
+
+ /** Checks the state of the SocketChannel and associated Socket after open() */
+ public void test_open_initialState() throws Exception {
+ SocketChannel sc = SocketChannel.open();
+ try {
+ assertNull(sc.socket().getLocalSocketAddress());
+
+ Socket socket = sc.socket();
+ assertFalse(socket.isBound());
+ assertFalse(socket.isClosed());
+ assertFalse(socket.isConnected());
+ assertEquals(-1, socket.getLocalPort());
+ assertTrue(socket.getLocalAddress().isAnyLocalAddress());
+ assertNull(socket.getLocalSocketAddress());
+ assertNull(socket.getInetAddress());
+ assertEquals(0, socket.getPort());
+ assertNull(socket.getRemoteSocketAddress());
+ assertFalse(socket.getReuseAddress());
+
+ assertSame(sc, socket.getChannel());
+ } finally {
+ sc.close();
+ }
+ }
+
+ public void test_bind_unresolvedAddress() throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ try {
+ sc.socket().bind(new InetSocketAddress("unresolvedname", 31415));
+ fail();
+ } catch (IOException expected) {
+ }
+
+ assertNull(sc.socket().getLocalSocketAddress());
+ assertTrue(sc.isOpen());
+ assertFalse(sc.isConnected());
+
+ sc.close();
+ }
+
+ /** Checks that the SocketChannel and associated Socket agree on the socket state. */
+ public void test_bind_socketStateSync() throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ assertNull(sc.socket().getLocalSocketAddress());
+
+ Socket socket = sc.socket();
+ assertNull(socket.getLocalSocketAddress());
+ assertFalse(socket.isBound());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ sc.socket().bind(bindAddr);
+
+ InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress();
+ assertEquals(actualAddr, socket.getLocalSocketAddress());
+ assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+ assertTrue(socket.isBound());
+ assertFalse(socket.isConnected());
+ assertFalse(socket.isClosed());
+
+ sc.close();
+
+ assertFalse(sc.isOpen());
+ assertTrue(socket.isClosed());
+ }
+
+ /**
+ * Checks that the SocketChannel and associated Socket agree on the socket state, even if
+ * the Socket object is requested/created after bind().
+ */
+ public void test_bind_socketObjectCreationAfterBind() throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ assertNull(sc.socket().getLocalSocketAddress());
+
+ InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+ sc.socket().bind(bindAddr);
+
+ // Socket object creation after bind().
+ Socket socket = sc.socket();
+ InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress();
+ assertEquals(actualAddr, socket.getLocalSocketAddress());
+ assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+ assertTrue(socket.isBound());
+ assertFalse(socket.isConnected());
+ assertFalse(socket.isClosed());
+
+ sc.close();
+
+ assertFalse(sc.isOpen());
+ assertTrue(socket.isClosed());
+ }
+
+ /**
+ * Tests connect() and object state for a blocking SocketChannel. Blocking mode is the default.
+ */
+ public void test_connect_blocking() throws Exception {
+ ServerSocket ss = new ServerSocket(0);
+
+ SocketChannel sc = SocketChannel.open();
+ assertTrue(sc.isBlocking());
+
+ assertTrue(sc.connect(ss.getLocalSocketAddress()));
+
+ assertTrue(sc.socket().isBound());
+ assertTrue(sc.isConnected());
+ assertTrue(sc.socket().isConnected());
+ assertFalse(sc.socket().isClosed());
+ assertTrue(sc.isBlocking());
+
+ ss.close();
+ sc.close();
+ }
+
+ /** Tests connect() and object state for a non-blocking SocketChannel. */
+ public void test_connect_nonBlocking() throws Exception {
+ ServerSocket ss = new ServerSocket(0);
+
+ SocketChannel sc = SocketChannel.open();
+ assertTrue(sc.isBlocking());
+ sc.configureBlocking(false);
+ assertFalse(sc.isBlocking());
+
+ if (!sc.connect(ss.getLocalSocketAddress())) {
+ do {
+ assertTrue(sc.socket().isBound());
+ assertFalse(sc.isConnected());
+ assertFalse(sc.socket().isConnected());
+ assertFalse(sc.socket().isClosed());
+ } while (!sc.finishConnect());
+ }
+ assertTrue(sc.socket().isBound());
+ assertTrue(sc.isConnected());
+ assertTrue(sc.socket().isConnected());
+ assertFalse(sc.socket().isClosed());
+ assertFalse(sc.isBlocking());
+
+ ss.close();
+ sc.close();
+ }
}
diff --git a/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java b/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java
index d0b46ed..e7fdb1f 100644
--- a/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java
+++ b/luni/src/test/java/libcore/java/security/KeyPairGeneratorTest.java
@@ -47,65 +47,120 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import javax.crypto.interfaces.DHPrivateKey;
+import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import junit.framework.TestCase;
public class KeyPairGeneratorTest extends TestCase {
- public void test_getInstance() throws Exception {
+ public void test_providerCount() {
Provider[] providers = Security.getProviders();
- for (Provider provider : providers) {
- Set<Provider.Service> services = provider.getServices();
- for (Provider.Service service : services) {
- String type = service.getType();
- if (!type.equals("KeyPairGenerator")) {
- continue;
- }
- String algorithm = service.getAlgorithm();
+ // We expect there to be at least one provider.
+ assertTrue(providers.length > 0);
+ // If this fails remember to add _provider methods below. This test is sharded because it
+ // takes a long time to execute.
+ assertTrue(providers.length < 10);
+ }
- // AndroidKeyStore is tested in CTS.
- if ("AndroidKeyStore".equals(provider.getName())) {
- continue;
- }
+ public void test_getInstance_provider0() throws Exception {
+ test_getInstance(0);
+ }
- AlgorithmParameterSpec params = null;
+ public void test_getInstance_provider1() throws Exception {
+ test_getInstance(1);
+ }
- // TODO: detect if we're running in vogar and run the full test
- if ("DH".equals(algorithm)) {
- params = getDHParams();
- }
+ public void test_getInstance_provider2() throws Exception {
+ test_getInstance(2);
+ }
- try {
- // KeyPairGenerator.getInstance(String)
- KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(algorithm);
- assertEquals(algorithm, kpg1.getAlgorithm());
- if (params != null) {
- kpg1.initialize(params);
- }
- test_KeyPairGenerator(kpg1);
-
- // KeyPairGenerator.getInstance(String, Provider)
- KeyPairGenerator kpg2 = KeyPairGenerator.getInstance(algorithm, provider);
- assertEquals(algorithm, kpg2.getAlgorithm());
- assertEquals(provider, kpg2.getProvider());
- if (params != null) {
- kpg2.initialize(params);
- }
- test_KeyPairGenerator(kpg2);
-
- // KeyPairGenerator.getInstance(String, String)
- KeyPairGenerator kpg3 = KeyPairGenerator.getInstance(algorithm,
- provider.getName());
- assertEquals(algorithm, kpg3.getAlgorithm());
- assertEquals(provider, kpg3.getProvider());
- if (params != null) {
- kpg3.initialize(params);
- }
- test_KeyPairGenerator(kpg3);
- } catch (Exception e) {
- throw new Exception("Problem testing KeyPairGenerator." + algorithm, e);
+ public void test_getInstance_provider3() throws Exception {
+ test_getInstance(3);
+ }
+
+ public void test_getInstance_provider4() throws Exception {
+ test_getInstance(4);
+ }
+
+ public void test_getInstance_provider5() throws Exception {
+ test_getInstance(5);
+ }
+
+ public void test_getInstance_provider6() throws Exception {
+ test_getInstance(6);
+ }
+
+ public void test_getInstance_provider7() throws Exception {
+ test_getInstance(7);
+ }
+
+ public void test_getInstance_provider8() throws Exception {
+ test_getInstance(8);
+ }
+
+ public void test_getInstance_provider9() throws Exception {
+ test_getInstance(9);
+ }
+
+ private void test_getInstance(int providerIndex) throws Exception {
+ Provider[] providers = Security.getProviders();
+ if (providerIndex >= providers.length) {
+ // Providers can be added by vendors and other tests. We do not
+ // specify a fixed number and silenty pass if the provider at the
+ // specified index does not exist.
+ return;
+ }
+ Provider provider = providers[providerIndex];
+ Set<Provider.Service> services = provider.getServices();
+ for (Provider.Service service : services) {
+ String type = service.getType();
+ if (!type.equals("KeyPairGenerator")) {
+ continue;
+ }
+ String algorithm = service.getAlgorithm();
+
+ // AndroidKeyStore is tested in CTS.
+ if ("AndroidKeyStore".equals(provider.getName())) {
+ continue;
+ }
+
+ AlgorithmParameterSpec params = null;
+
+ if ("DH".equals(algorithm)) {
+ params = getDHParams();
+ }
+
+ try {
+ // KeyPairGenerator.getInstance(String)
+ KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(algorithm);
+ assertEquals(algorithm, kpg1.getAlgorithm());
+ if (params != null) {
+ kpg1.initialize(params);
}
+ test_KeyPairGenerator(kpg1);
+
+ // KeyPairGenerator.getInstance(String, Provider)
+ KeyPairGenerator kpg2 = KeyPairGenerator.getInstance(algorithm, provider);
+ assertEquals(algorithm, kpg2.getAlgorithm());
+ assertEquals(provider, kpg2.getProvider());
+ if (params != null) {
+ kpg2.initialize(params);
+ }
+ test_KeyPairGenerator(kpg2);
+
+ // KeyPairGenerator.getInstance(String, String)
+ KeyPairGenerator kpg3 = KeyPairGenerator.getInstance(algorithm,
+ provider.getName());
+ assertEquals(algorithm, kpg3.getAlgorithm());
+ assertEquals(provider, kpg3.getProvider());
+ if (params != null) {
+ kpg3.initialize(params);
+ }
+ test_KeyPairGenerator(kpg3);
+ } catch (Exception e) {
+ throw new Exception("Problem testing KeyPairGenerator." + algorithm, e);
}
}
}
@@ -161,6 +216,14 @@ public class KeyPairGeneratorTest extends TestCase {
test_KeyPair(kpg, kpg.generateKeyPair());
String algorithm = kpg.getAlgorithm();
+
+ // TODO: detect if we're running in vogar and run the full test
+ if ("DH".equals(algorithm)) {
+ // Disabled because this takes too long on devices.
+ // TODO: Re-enable DH test. http://b/5513723.
+ return;
+ }
+
List<Integer> keySizes = getKeySizes(algorithm);
for (int keySize : keySizes) {
kpg.initialize(keySize);
@@ -206,6 +269,17 @@ public class KeyPairGeneratorTest extends TestCase {
expectedAlgorithm = "DH";
}
assertEquals(expectedAlgorithm, k.getAlgorithm().toUpperCase());
+ if (expectedAlgorithm.equals("DH")) {
+ if (k instanceof DHPublicKey) {
+ DHPublicKey dhPub = (DHPublicKey) k;
+ assertEquals(dhPub.getParams().getP(), getDHParams().getP());
+ } else if (k instanceof DHPrivateKey) {
+ DHPrivateKey dhPriv = (DHPrivateKey) k;
+ assertEquals(dhPriv.getParams().getP(), getDHParams().getP());
+ } else {
+ fail("not a public or private key!?");
+ }
+ }
assertNotNull(k.getEncoded());
assertNotNull(k.getFormat());
@@ -287,7 +361,7 @@ public class KeyPairGeneratorTest extends TestCase {
*
* openssl gendh 512 | openssl dhparams -C
*/
- private static AlgorithmParameterSpec getDHParams() {
+ private static DHParameterSpec getDHParams() {
BigInteger p = new BigInteger("E7AB1768BD75CD24700960FFA32D3F1557344E587101237532CC641646ED7A7C104743377F6D46251698B665CE2A6CBAB6714C2569A7D2CA22C0CF03FA40AC93", 16);
BigInteger g = new BigInteger("02", 16);
return new DHParameterSpec(p, g, 512);
@@ -341,8 +415,6 @@ public class KeyPairGeneratorTest extends TestCase {
public void testDSAGeneratorWithParams() throws Exception {
final DSAParameterSpec dsaSpec = new DSAParameterSpec(DSA_P, DSA_Q, DSA_G);
- boolean failure = false;
-
final Provider[] providers = Security.getProviders();
for (final Provider p : providers) {
Service s = p.getService("KeyPairGenerator", "DSA");
diff --git a/luni/src/test/java/libcore/java/security/KeyStoreTest.java b/luni/src/test/java/libcore/java/security/KeyStoreTest.java
index 47aa72a..9185ea8 100644
--- a/luni/src/test/java/libcore/java/security/KeyStoreTest.java
+++ b/luni/src/test/java/libcore/java/security/KeyStoreTest.java
@@ -46,6 +46,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -55,11 +56,17 @@ import junit.framework.TestCase;
public class KeyStoreTest extends TestCase {
- private static PrivateKeyEntry PRIVATE_KEY;
- private static PrivateKeyEntry PRIVATE_KEY_2;
+ private static final HashMap<String, PrivateKeyEntry> sPrivateKeys
+ = new HashMap<String, PrivateKeyEntry>();
- private static SecretKey SECRET_KEY;
- private static SecretKey SECRET_KEY_2;
+ private static TestKeyStore sTestKeyStore;
+
+ private static final String[] KEY_TYPES = new String[] { "DH", "DSA", "RSA", "EC" };
+
+ private static PrivateKeyEntry sPrivateKey2;
+
+ private static SecretKey sSecretKey;
+ private static SecretKey sSecretKey2;
private static final String ALIAS_PRIVATE = "private";
private static final String ALIAS_CERTIFICATE = "certificate";
@@ -87,31 +94,56 @@ public class KeyStoreTest extends TestCase {
private static final ProtectionParameter PARAM_BAD = new PasswordProtection(PASSWORD_BAD);
private static PrivateKeyEntry getPrivateKey() {
- if (PRIVATE_KEY == null) {
- PRIVATE_KEY = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
+ return getPrivateKey("RSA");
+ }
+
+ private static PrivateKeyEntry getPrivateKey(String keyType) {
+ // Avoiding initialization of TestKeyStore in the static initializer: it breaks CTS tests
+ // by causing a NetworkOnMainThreadException.
+ if (sTestKeyStore == null) {
+ sTestKeyStore = new TestKeyStore.Builder()
+ .keyAlgorithms("RSA", "DH_RSA", "DSA", "EC")
+ .aliasPrefix("rsa-dsa-ec-dh")
+ .build();
+ }
+
+ PrivateKeyEntry entry = sPrivateKeys.get(keyType);
+ if (entry == null) {
+ if ("RSA".equals(keyType)) {
+ entry = sTestKeyStore.getPrivateKey("RSA", "RSA");
+ } else if ("DH".equals(keyType)) {
+ entry = sTestKeyStore.getPrivateKey("DH", "RSA");
+ } else if ("DSA".equals(keyType)) {
+ entry = sTestKeyStore.getPrivateKey("DSA", "DSA");
+ } else if ("EC".equals(keyType)) {
+ entry = sTestKeyStore.getPrivateKey("EC", "EC");
+ } else {
+ throw new IllegalArgumentException("Unexpected key type " + keyType);
+ }
+ sPrivateKeys.put(keyType, entry);
}
- return PRIVATE_KEY;
+ return entry;
}
private static PrivateKeyEntry getPrivateKey2() {
- if (PRIVATE_KEY_2 == null) {
- PRIVATE_KEY_2 = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
+ if (sPrivateKey2 == null) {
+ sPrivateKey2 = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
}
- return PRIVATE_KEY_2;
+ return sPrivateKey2;
}
private static SecretKey getSecretKey() {
- if (SECRET_KEY == null) {
- SECRET_KEY = generateSecretKey();
+ if (sSecretKey == null) {
+ sSecretKey = generateSecretKey();
}
- return SECRET_KEY;
+ return sSecretKey;
}
private static SecretKey getSecretKey2() {
- if (SECRET_KEY_2 == null) {
- SECRET_KEY_2 = generateSecretKey();
+ if (sSecretKey2 == null) {
+ sSecretKey2 = generateSecretKey();
}
- return SECRET_KEY_2;
+ return sSecretKey2;
}
private static SecretKey generateSecretKey() {
@@ -341,10 +373,15 @@ public class KeyStoreTest extends TestCase {
ks.setCertificateEntry(alias, certificate);
}
+
public static void assertPrivateKey(Key actual)
throws Exception {
assertEquals(getPrivateKey().getPrivateKey(), actual);
}
+ public static void assertPrivateKey(String keyType, Key actual)
+ throws Exception {
+ assertEquals(getPrivateKey(keyType).getPrivateKey(), actual);
+ }
public static void assertPrivateKey2(Key actual)
throws Exception {
assertEquals(getPrivateKey2().getPrivateKey(), actual);
@@ -2183,8 +2220,10 @@ public class KeyStoreTest extends TestCase {
continue;
}
if (isNullPasswordAllowed(keyStore) || isKeyPasswordIgnored(keyStore)) {
- keyStore.setEntry(ALIAS_PRIVATE, getPrivateKey(), null);
- assertPrivateKey(keyStore.getKey(ALIAS_PRIVATE, null));
+ for (String keyType : KEY_TYPES) {
+ keyStore.setEntry(ALIAS_PRIVATE, getPrivateKey(keyType), null);
+ assertPrivateKey(keyType, keyStore.getKey(ALIAS_PRIVATE, null));
+ }
} else {
try {
keyStore.setEntry(ALIAS_PRIVATE, getPrivateKey(), null);
diff --git a/luni/src/test/java/libcore/java/security/MessageDigestTest.java b/luni/src/test/java/libcore/java/security/MessageDigestTest.java
index 3646a7a..ad410e4 100644
--- a/luni/src/test/java/libcore/java/security/MessageDigestTest.java
+++ b/luni/src/test/java/libcore/java/security/MessageDigestTest.java
@@ -24,6 +24,11 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
public final class MessageDigestTest extends TestCase {
@@ -116,6 +121,12 @@ public final class MessageDigestTest extends TestCase {
new byte[] { -38, 57, -93, -18, 94, 107, 75, 13,
50, 85, -65, -17, -107, 96, 24, -112,
-81, -40, 7, 9});
+ putExpectation("SHA-224",
+ INPUT_EMPTY,
+ new byte[] { -47, 74, 2, -116, 42, 58, 43, -55, 71,
+ 97, 2, -69, 40, -126, 52, -60, 21,
+ -94, -80, 31, -126, -114, -90, 42,
+ -59, -77, -28, 47});
putExpectation("SHA-256",
INPUT_EMPTY,
new byte[] { -29, -80, -60, 66, -104, -4, 28, 20,
@@ -163,6 +174,12 @@ public final class MessageDigestTest extends TestCase {
new byte[] { 123, -111, -37, -36, 86, -59, 120, 30,
-33, 108, -120, 71, -76, -86, 105, 101,
86, 108, 92, 117 });
+ putExpectation("SHA-224",
+ INPUT_256MB,
+ new byte[] { -78, 82, 5, -71, 57, 119, 77, -32,
+ -62, -74, -40, 64, -57, 79, 40, 116,
+ -18, 48, -69, 45, 18, -94, 111, 114,
+ -45, -93, 43, -11 });
putExpectation("SHA-256",
INPUT_256MB,
new byte[] { -90, -41, 42, -57, 105, 15, 83, -66,
@@ -227,4 +244,33 @@ public final class MessageDigestTest extends TestCase {
return buf.toString();
}
+ private final int THREAD_COUNT = 10;
+
+ public void testMessageDigest_MultipleThreads_Misuse() throws Exception {
+ ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
+
+ final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
+ final MessageDigest md = MessageDigest.getInstance("SHA-256");
+ final byte[] message = new byte[64];
+
+ for (int i = 0; i < THREAD_COUNT; i++) {
+ es.submit(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ // Try to make sure all the threads are ready first.
+ latch.countDown();
+ latch.await();
+
+ for (int j = 0; j < 100; j++) {
+ md.update(message);
+ md.digest();
+ }
+
+ return null;
+ }
+ });
+ }
+ es.shutdown();
+ assertTrue("Test should not timeout", es.awaitTermination(1, TimeUnit.MINUTES));
+ }
}
diff --git a/luni/src/test/java/libcore/java/security/MockPrivateKey.java b/luni/src/test/java/libcore/java/security/MockPrivateKey.java
new file mode 100644
index 0000000..e5ac797
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/MockPrivateKey.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2014 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 libcore.java.security;
+
+import java.security.PrivateKey;
+
+/**
+ * A mock PrivateKey class used for testing.
+ */
+@SuppressWarnings("serial")
+public class MockPrivateKey implements PrivateKey {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ return "MOCK";
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+}
diff --git a/luni/src/test/java/libcore/java/security/MockPrivateKey2.java b/luni/src/test/java/libcore/java/security/MockPrivateKey2.java
new file mode 100644
index 0000000..a1c02c9
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/MockPrivateKey2.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2014 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 libcore.java.security;
+
+import java.security.PrivateKey;
+
+/**
+ * A mock PrivateKey class used for testing.
+ */
+@SuppressWarnings("serial")
+public class MockPrivateKey2 implements PrivateKey {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ return "MOCK";
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+}
diff --git a/luni/src/test/java/libcore/java/security/MockPublicKey.java b/luni/src/test/java/libcore/java/security/MockPublicKey.java
new file mode 100644
index 0000000..130b461
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/MockPublicKey.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2014 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 libcore.java.security;
+
+import java.security.PublicKey;
+
+/**
+ * A mock PublicKey class used for testing.
+ */
+@SuppressWarnings("serial")
+public class MockPublicKey implements PublicKey {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ return "MOCK";
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+}
diff --git a/luni/src/test/java/libcore/java/security/MockSignatureSpi.java b/luni/src/test/java/libcore/java/security/MockSignatureSpi.java
new file mode 100644
index 0000000..6017547
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/MockSignatureSpi.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2014 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 libcore.java.security;
+
+import java.security.InvalidKeyException;
+import java.security.InvalidParameterException;
+import java.security.Key;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SignatureException;
+import java.security.SignatureSpi;
+
+/**
+ * Mock SignatureSpi used by {@link SignatureTest}.
+ */
+public class MockSignatureSpi extends SignatureSpi {
+ public static class SpecificKeyTypes extends MockSignatureSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockPrivateKey)) {
+ throw new InvalidKeyException("Must be MockPrivateKey!");
+ }
+ }
+ }
+
+ public static class SpecificKeyTypes2 extends MockSignatureSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockPrivateKey2)) {
+ throw new InvalidKeyException("Must be MockPrivateKey2!");
+ }
+ }
+ }
+
+ public static class AllKeyTypes extends MockSignatureSpi {
+ }
+
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineInitVerify(java.security.PublicKey)
+ */
+ @Override
+ protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineInitSign(java.security.PrivateKey)
+ */
+ @Override
+ protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
+ checkKeyType(privateKey);
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineUpdate(byte)
+ */
+ @Override
+ protected void engineUpdate(byte b) throws SignatureException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineSign()
+ */
+ @Override
+ protected byte[] engineSign() throws SignatureException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineVerify(byte[])
+ */
+ @Override
+ protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineSetParameter(java.lang.String, java.lang.Object)
+ */
+ @Override
+ protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineGetParameter(java.lang.String)
+ */
+ @Override
+ protected Object engineGetParameter(String param) throws InvalidParameterException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see java.security.SignatureSpi#engineUpdate(byte[], int, int)
+ */
+ @Override
+ protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+}
diff --git a/luni/src/test/java/libcore/java/security/OldDHTest.java b/luni/src/test/java/libcore/java/security/OldDHTest.java
index 421d153..58d96ed 100644
--- a/luni/src/test/java/libcore/java/security/OldDHTest.java
+++ b/luni/src/test/java/libcore/java/security/OldDHTest.java
@@ -15,7 +15,6 @@
*/
package libcore.java.security;
-import dalvik.annotation.BrokenTest;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.KeyPair;
@@ -27,7 +26,7 @@ import junit.framework.TestCase;
public class OldDHTest extends TestCase {
- @BrokenTest("Suffers from DH slowness, disabling for now")
+ // BrokenTest Suffers from DH slowness, disabling for now
public void testDHGen() throws Exception {
KeyPairGenerator gen = null;
try {
diff --git a/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java b/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java
index f39705b..9be282d 100644
--- a/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java
+++ b/luni/src/test/java/libcore/java/security/OldKeyPairGeneratorTestDH.java
@@ -15,7 +15,6 @@
*/
package libcore.java.security;
-import dalvik.annotation.BrokenTest;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
@@ -24,7 +23,7 @@ import tests.security.KeyAgreementHelper;
public class OldKeyPairGeneratorTestDH extends TestCase {
- @BrokenTest("Takes ages due to DH computations. Disabling for now.")
+ // Broken Test: Takes ages due to DH computations. Disabling for now.
public void testKeyPairGenerator() throws NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("DH");
diff --git a/luni/src/test/java/libcore/java/security/ProviderTest.java b/luni/src/test/java/libcore/java/security/ProviderTest.java
index 97a80a9..994214b 100644
--- a/luni/src/test/java/libcore/java/security/ProviderTest.java
+++ b/luni/src/test/java/libcore/java/security/ProviderTest.java
@@ -16,27 +16,40 @@
package libcore.java.security;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidParameterException;
+import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.SecureRandomSpi;
import java.security.Security;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.SecureRandomSpi;
-import java.security.Security;
+import java.security.cert.CRL;
+import java.security.cert.CRLSelector;
+import java.security.cert.CertSelector;
+import java.security.cert.CertStoreException;
+import java.security.cert.CertStoreParameters;
+import java.security.cert.CertStoreSpi;
+import java.security.cert.Certificate;
+import java.security.interfaces.RSAPrivateKey;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
-import java.util.Map.Entry;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import javax.crypto.Cipher;
+import javax.crypto.NoSuchPaddingException;
import junit.framework.TestCase;
+import libcore.javax.crypto.MockKey;
public class ProviderTest extends TestCase {
+ private static final boolean LOG_DEBUG = false;
/**
* Makes sure all all expected implementations (but not aliases)
@@ -44,16 +57,15 @@ public class ProviderTest extends TestCase {
* StandardNames
*/
public void test_Provider_getServices() throws Exception {
-
// build set of expected algorithms
- Map<String,Set<String>> remaining
+ Map<String,Set<String>> remainingExpected
= new HashMap<String,Set<String>>(StandardNames.PROVIDER_ALGORITHMS);
- for (Entry<String,Set<String>> entry : remaining.entrySet()) {
+ for (Entry<String,Set<String>> entry : remainingExpected.entrySet()) {
entry.setValue(new HashSet<String>(entry.getValue()));
}
- List<String> extra = new ArrayList();
- List<String> missing = new ArrayList();
+ List<String> extra = new ArrayList<String>();
+ List<String> missing = new ArrayList<String>();
Provider[] providers = Security.getProviders();
for (Provider provider : providers) {
@@ -70,7 +82,7 @@ public class ProviderTest extends TestCase {
String type = service.getType();
String algorithm = service.getAlgorithm().toUpperCase();
String className = service.getClassName();
- if (false) {
+ if (LOG_DEBUG) {
System.out.println(providerName
+ " " + type
+ " " + algorithm
@@ -78,8 +90,8 @@ public class ProviderTest extends TestCase {
}
// remove from remaining, assert unknown if missing
- Set<String> algorithms = remaining.get(type);
- if (algorithms == null || !algorithms.remove(algorithm)) {
+ Set<String> remainingAlgorithms = remainingExpected.get(type);
+ if (remainingAlgorithms == null || !remainingAlgorithms.remove(algorithm)) {
// seems to be missing, but sometimes the same
// algorithm is available from multiple providers
// (e.g. KeyFactory RSA is available from
@@ -89,9 +101,28 @@ public class ProviderTest extends TestCase {
&& StandardNames.PROVIDER_ALGORITHMS.get(type).contains(algorithm))) {
extra.add("Unknown " + type + " " + algorithm + " " + providerName + "\n");
}
+ } else if ("Cipher".equals(type) && !algorithm.contains("/")) {
+ /*
+ * Cipher selection follows special rules where you can
+ * specify the mode and padding during the getInstance call.
+ * Try to see if the service supports this.
+ */
+ Set<String> toRemove = new HashSet<String>();
+ for (String remainingAlgo : remainingAlgorithms) {
+ String[] parts = remainingAlgo.split("/");
+ if (parts.length == 3 && algorithm.equals(parts[0])) {
+ try {
+ Cipher.getInstance(remainingAlgo, provider);
+ toRemove.add(remainingAlgo);
+ } catch (NoSuchAlgorithmException ignored) {
+ } catch (NoSuchPaddingException ignored) {
+ }
+ }
+ }
+ remainingAlgorithms.removeAll(toRemove);
}
- if (algorithms != null && algorithms.isEmpty()) {
- remaining.remove(type);
+ if (remainingAlgorithms != null && remainingAlgorithms.isEmpty()) {
+ remainingExpected.remove(type);
}
// make sure class exists and can be initialized
@@ -113,7 +144,7 @@ public class ProviderTest extends TestCase {
assertEquals("Extra algorithms", Collections.EMPTY_LIST, extra);
// assert that we don't have any missing in the implementation
- assertEquals("Missing algorithms", Collections.EMPTY_MAP, remaining);
+ assertEquals("Missing algorithms", Collections.EMPTY_MAP, remainingExpected);
// assert that we don't have any missing classes
Collections.sort(missing); // sort it for readability
@@ -202,11 +233,356 @@ public class ProviderTest extends TestCase {
}
}
+ private static final String[] TYPES_SERVICES_CHECKED = new String[] {
+ "KeyFactory", "CertPathBuilder", "Cipher", "SecureRandom",
+ "AlgorithmParameterGenerator", "Signature", "KeyPairGenerator", "CertificateFactory",
+ "MessageDigest", "KeyAgreement", "CertStore", "SSLContext", "AlgorithmParameters",
+ "TrustManagerFactory", "KeyGenerator", "Mac", "CertPathValidator", "SecretKeyFactory",
+ "KeyManagerFactory", "KeyStore",
+ };
+
+ private static final HashSet<String> TYPES_SUPPORTS_PARAMETER = new HashSet<String>(
+ Arrays.asList(new String[] {
+ "Mac", "KeyAgreement", "Cipher", "Signature",
+ }));
+
+ private static final HashSet<String> TYPES_NOT_SUPPORTS_PARAMETER = new HashSet<String>(
+ Arrays.asList(TYPES_SERVICES_CHECKED));
+ static {
+ TYPES_NOT_SUPPORTS_PARAMETER.removeAll(TYPES_SUPPORTS_PARAMETER);
+ }
+
+ public void test_Provider_getServices_supportsParameter() throws Exception {
+ HashSet<String> remainingTypes = new HashSet<String>(Arrays.asList(TYPES_SERVICES_CHECKED));
+
+ HashSet<String> supportsParameterTypes = new HashSet<String>();
+ HashSet<String> noSupportsParameterTypes = new HashSet<String>();
+
+ Provider[] providers = Security.getProviders();
+ for (Provider provider : providers) {
+ Set<Provider.Service> services = provider.getServices();
+ assertNotNull(services);
+ assertFalse(services.isEmpty());
+
+ for (Provider.Service service : services) {
+ final String type = service.getType();
+ remainingTypes.remove(type);
+ try {
+ service.supportsParameter(new MockKey());
+ supportsParameterTypes.add(type);
+ } catch (InvalidParameterException e) {
+ noSupportsParameterTypes.add(type);
+ try {
+ service.supportsParameter(new Object());
+ fail("Should throw on non-Key parameter");
+ } catch (InvalidParameterException expected) {
+ }
+ }
+ }
+ }
+
+ supportsParameterTypes.retainAll(TYPES_SUPPORTS_PARAMETER);
+ assertEquals("Types that should support parameters", TYPES_SUPPORTS_PARAMETER,
+ supportsParameterTypes);
+
+ noSupportsParameterTypes.retainAll(TYPES_NOT_SUPPORTS_PARAMETER);
+ assertEquals("Types that should not support parameters", TYPES_NOT_SUPPORTS_PARAMETER,
+ noSupportsParameterTypes);
+
+ assertEquals("Types that should be checked", Collections.EMPTY_SET, remainingTypes);
+ }
+
+ public static class MockSpi {
+ public Object parameter;
+
+ public MockSpi(MockKey parameter) {
+ this.parameter = parameter;
+ }
+ };
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_UnknownService_Success() throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Fake.FOO", MockSpi.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Fake", "FOO");
+ assertTrue(service.supportsParameter(new Object()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_KnownService_NoClassInitialization_Success()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyClasses", getClass().getName()
+ + ".UninitializedMockKey");
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertFalse(service.supportsParameter(new MockKey()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public static class UninitializedMockKey extends MockKey {
+ static {
+ fail("This should not be initialized");
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_TypeDoesNotSupportParameter_Failure()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("KeyFactory.FOO", MockSpi.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("KeyFactory", "FOO");
+ try {
+ service.supportsParameter(new MockKey());
+ fail("Should always throw exception");
+ } catch (InvalidParameterException expected) {
+ }
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_SupportedKeyClasses_NonKeyClass_Success()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyClasses", MockSpi.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertFalse(service.supportsParameter(new MockKey()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_KnownService_NonKey_Failure()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ try {
+ service.supportsParameter(new Object());
+ fail("Should throw when non-Key passed in");
+ } catch (InvalidParameterException expected) {
+ }
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_KnownService_SupportedKeyClasses_NonKey_Failure()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyClasses", RSAPrivateKey.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ try {
+ service.supportsParameter(new Object());
+ fail("Should throw on non-Key instance passed in");
+ } catch (InvalidParameterException expected) {
+ }
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_KnownService_Null_Failure() throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyClasses", RSAPrivateKey.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertFalse(service.supportsParameter(null));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_SupportedKeyClasses_Success()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyClasses", MockKey.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertTrue(service.supportsParameter(new MockKey()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_SupportedKeyClasses_Failure()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyClasses", RSAPrivateKey.class.getName());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertFalse(service.supportsParameter(new MockKey()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_SupportedKeyFormats_Success()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyFormats", new MockKey().getFormat());
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertTrue(service.supportsParameter(new MockKey()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_supportsParameter_SupportedKeyFormats_Failure()
+ throws Exception {
+ Provider provider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSpi.class.getName());
+ put("Signature.FOO SupportedKeyFormats", "Invalid");
+ }
+ };
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("Signature", "FOO");
+ assertFalse(service.supportsParameter(new MockKey()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ @SuppressWarnings("serial")
+ public void testProviderService_newInstance_DoesNotCallSupportsParameter_Success()
+ throws Exception {
+ MockProvider provider = new MockProvider("MockProvider");
+
+ provider.putServiceForTest(new Provider.Service(provider, "CertStore", "FOO",
+ MyCertStoreSpi.class.getName(), null, null) {
+ @Override
+ public boolean supportsParameter(Object parameter) {
+ fail("This should not be called");
+ return false;
+ }
+ });
+
+ Security.addProvider(provider);
+ try {
+ Provider.Service service = provider.getService("CertStore", "FOO");
+ assertNotNull(service.newInstance(new MyCertStoreParameters()));
+ } finally {
+ Security.removeProvider(provider.getName());
+ }
+ }
+
+ public static class MyCertStoreSpi extends CertStoreSpi {
+ public MyCertStoreSpi(CertStoreParameters params) throws InvalidAlgorithmParameterException {
+ super(params);
+ }
+
+ @Override
+ public Collection<? extends Certificate> engineGetCertificates(CertSelector selector)
+ throws CertStoreException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Collection<? extends CRL> engineGetCRLs(CRLSelector selector)
+ throws CertStoreException {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public static class MyCertStoreParameters implements CertStoreParameters {
+ public Object clone() {
+ return new MyCertStoreParameters();
+ }
+ }
+
/**
* http://code.google.com/p/android/issues/detail?id=21449
*/
public void testSecureRandomImplementationOrder() {
- Provider srp = new SRProvider();
+ @SuppressWarnings("serial")
+ Provider srp = new MockProvider("SRProvider") {
+ public void setup() {
+ put("SecureRandom.SecureRandom1", SecureRandom1.class.getName());
+ put("SecureRandom.SecureRandom2", SecureRandom2.class.getName());
+ put("SecureRandom.SecureRandom3", SecureRandom3.class.getName());
+ }
+ };
try {
int position = Security.insertProviderAt(srp, 1); // first is one, not zero
assertEquals(1, position);
@@ -219,16 +595,22 @@ public class ProviderTest extends TestCase {
}
}
- public static class SRProvider extends Provider {
+ @SuppressWarnings("serial")
+ private static class MockProvider extends Provider {
+ public MockProvider(String name) {
+ super(name, 1.0, "Mock provider used for testing");
+ setup();
+ }
+
+ public void setup() {
+ }
- SRProvider() {
- super("SRProvider", 1.42, "SecureRandom Provider");
- put("SecureRandom.SecureRandom1", SecureRandom1.class.getName());
- put("SecureRandom.SecureRandom2", SecureRandom2.class.getName());
- put("SecureRandom.SecureRandom3", SecureRandom3.class.getName());
+ public void putServiceForTest(Provider.Service service) {
+ putService(service);
}
}
+ @SuppressWarnings("serial")
public static abstract class AbstractSecureRandom extends SecureRandomSpi {
protected void engineSetSeed(byte[] seed) {
throw new UnsupportedOperationException();
@@ -241,8 +623,13 @@ public class ProviderTest extends TestCase {
}
}
+ @SuppressWarnings("serial")
public static class SecureRandom1 extends AbstractSecureRandom {}
+
+ @SuppressWarnings("serial")
public static class SecureRandom2 extends AbstractSecureRandom {}
+
+ @SuppressWarnings("serial")
public static class SecureRandom3 extends AbstractSecureRandom {}
}
diff --git a/luni/src/test/java/libcore/java/security/SignatureTest.java b/luni/src/test/java/libcore/java/security/SignatureTest.java
index 7f8b4f4..5e02f10 100644
--- a/luni/src/test/java/libcore/java/security/SignatureTest.java
+++ b/luni/src/test/java/libcore/java/security/SignatureTest.java
@@ -18,9 +18,11 @@ package libcore.java.security;
import java.math.BigInteger;
import java.security.InvalidKeyException;
+import java.security.InvalidParameterException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
@@ -38,10 +40,197 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
public class SignatureTest extends TestCase {
+ private static abstract class MockProvider extends Provider {
+ public MockProvider(String name) {
+ super(name, 1.0, "Mock provider used for testing");
+ setup();
+ }
+
+ public abstract void setup();
+ }
+
+ public void testSignature_getInstance_SuppliedProviderNotRegistered_Success() throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ {
+ Signature s = Signature.getInstance("FOO", mockProvider);
+ s.initSign(new MockPrivateKey());
+ assertEquals(mockProvider, s.getProvider());
+ }
+ }
+
+ public void testSignature_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success()
+ throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProvider);
+ try {
+ {
+ Provider mockProvider2 = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName());
+ }
+ };
+ Signature s = Signature.getInstance("FOO", mockProvider2);
+ assertEquals(mockProvider2, s.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProvider.getName());
+ }
+ }
+
+ public void testSignature_getInstance_DelayedInitialization_KeyType() throws Exception {
+ Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") {
+ public void setup() {
+ put("Signature.FOO", MockSignatureSpi.SpecificKeyTypes.class.getName());
+ put("Signature.FOO SupportedKeyClasses", MockPrivateKey.class.getName());
+ }
+ };
+ Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") {
+ public void setup() {
+ put("Signature.FOO", MockSignatureSpi.SpecificKeyTypes2.class.getName());
+ put("Signature.FOO SupportedKeyClasses", MockPrivateKey2.class.getName());
+ }
+ };
+ Provider mockProviderAll = new MockProvider("MockProviderAll") {
+ public void setup() {
+ put("Signature.FOO", MockSignatureSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProviderSpecific);
+ Security.addProvider(mockProviderSpecific2);
+ Security.addProvider(mockProviderAll);
+
+ try {
+ {
+ Signature s = Signature.getInstance("FOO");
+ s.initSign(new MockPrivateKey());
+ assertEquals(mockProviderSpecific, s.getProvider());
+
+ try {
+ s.initSign(new MockPrivateKey2());
+ assertEquals(mockProviderSpecific2, s.getProvider());
+ if (StandardNames.IS_RI) {
+ fail("RI was broken before; fix tests now that it works!");
+ }
+ } catch (InvalidKeyException e) {
+ if (!StandardNames.IS_RI) {
+ fail("Non-RI should select the right provider");
+ }
+ }
+ }
+
+ {
+ Signature s = Signature.getInstance("FOO");
+ s.initSign(new PrivateKey() {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+ });
+ assertEquals(mockProviderAll, s.getProvider());
+ }
+
+ {
+ Signature s = Signature.getInstance("FOO");
+ assertEquals(mockProviderSpecific, s.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProviderSpecific.getName());
+ Security.removeProvider(mockProviderSpecific2.getName());
+ Security.removeProvider(mockProviderAll.getName());
+ }
+ }
+
+ private static class MySignature extends Signature {
+ protected MySignature(String algorithm) {
+ super(algorithm);
+ }
+
+ @Override
+ protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineUpdate(byte b) throws SignatureException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected byte[] engineSign() throws SignatureException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineSetParameter(String param, Object value) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Object engineGetParameter(String param) throws InvalidParameterException {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public void testSignature_getProvider_Subclass() throws Exception {
+ Provider mockProviderNonSpi = new MockProvider("MockProviderNonSpi") {
+ public void setup() {
+ put("Signature.FOO", MySignature.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProviderNonSpi);
+
+ try {
+ Signature s = new MySignature("FOO");
+ assertNull(s.getProvider());
+ } finally {
+ Security.removeProvider(mockProviderNonSpi.getName());
+ }
+ }
// 20 bytes for DSA
private final byte[] DATA = new byte[20];
@@ -140,6 +329,8 @@ public class SignatureTest extends TestCase {
// http://code.google.com/p/android/issues/detail?id=34933
sig.verify(signature);
}
+
+ testSignature_MultipleThreads_Misuse(sig);
}
private static final byte[] PK_BYTES = hexToBytes(
@@ -425,6 +616,44 @@ public class SignatureTest extends TestCase {
(byte) 0xc0, (byte) 0x09, (byte) 0x15, (byte) 0x7d, (byte) 0x8a, (byte) 0x21, (byte) 0xbc, (byte) 0xa3,
};
+ /*
+ * echo 'Android.' | openssl dgst -sha224 -binary -sign privkey.pem | recode ../x1 | sed 's/0x/(byte) 0x/g'
+ */
+ private static final byte[] SHA224withRSA_Vector2Signature = new byte[] {
+ (byte) 0xBD, (byte) 0x3F, (byte) 0xD4, (byte) 0x20, (byte) 0x5B, (byte) 0xC0, (byte) 0x89, (byte) 0x4F,
+ (byte) 0x99, (byte) 0x6C, (byte) 0xF4, (byte) 0xA4, (byte) 0x70, (byte) 0xE3, (byte) 0x5B, (byte) 0x33,
+ (byte) 0xB3, (byte) 0xCA, (byte) 0xFE, (byte) 0x1F, (byte) 0xB9, (byte) 0x3A, (byte) 0xD6, (byte) 0x9B,
+ (byte) 0x1E, (byte) 0xDA, (byte) 0x65, (byte) 0x06, (byte) 0xBD, (byte) 0xC3, (byte) 0x2B, (byte) 0xF8,
+ (byte) 0x0E, (byte) 0xA0, (byte) 0xB5, (byte) 0x33, (byte) 0x7F, (byte) 0x15, (byte) 0xDC, (byte) 0xBB,
+ (byte) 0xDC, (byte) 0x98, (byte) 0x96, (byte) 0xF5, (byte) 0xF8, (byte) 0xE5, (byte) 0x55, (byte) 0x7D,
+ (byte) 0x48, (byte) 0x51, (byte) 0xC5, (byte) 0xAE, (byte) 0x12, (byte) 0xA2, (byte) 0x61, (byte) 0xC7,
+ (byte) 0xA2, (byte) 0x00, (byte) 0x0F, (byte) 0x35, (byte) 0x54, (byte) 0x3C, (byte) 0x7E, (byte) 0x97,
+ (byte) 0x19, (byte) 0x2D, (byte) 0x8F, (byte) 0xFD, (byte) 0x51, (byte) 0x04, (byte) 0x72, (byte) 0x23,
+ (byte) 0x65, (byte) 0x16, (byte) 0x41, (byte) 0x12, (byte) 0x46, (byte) 0xD6, (byte) 0x20, (byte) 0xB6,
+ (byte) 0x4E, (byte) 0xD6, (byte) 0xE8, (byte) 0x60, (byte) 0x91, (byte) 0x05, (byte) 0xCA, (byte) 0x57,
+ (byte) 0x6F, (byte) 0x53, (byte) 0xA4, (byte) 0x05, (byte) 0x2A, (byte) 0x37, (byte) 0xDD, (byte) 0x2E,
+ (byte) 0xA4, (byte) 0xC7, (byte) 0xBF, (byte) 0x9E, (byte) 0xF6, (byte) 0xD5, (byte) 0xD4, (byte) 0x34,
+ (byte) 0xB8, (byte) 0xB3, (byte) 0x8B, (byte) 0x66, (byte) 0x2C, (byte) 0xB6, (byte) 0x5F, (byte) 0xA4,
+ (byte) 0xB7, (byte) 0x77, (byte) 0xF8, (byte) 0x9A, (byte) 0x9C, (byte) 0x44, (byte) 0x9F, (byte) 0xF0,
+ (byte) 0xCA, (byte) 0x53, (byte) 0x56, (byte) 0x2F, (byte) 0x99, (byte) 0x2E, (byte) 0x4B, (byte) 0xA2,
+ (byte) 0x26, (byte) 0x50, (byte) 0x30, (byte) 0x97, (byte) 0x2B, (byte) 0x4B, (byte) 0x0C, (byte) 0x3E,
+ (byte) 0x28, (byte) 0x0B, (byte) 0x88, (byte) 0x87, (byte) 0x9E, (byte) 0xCE, (byte) 0xCB, (byte) 0x57,
+ (byte) 0x72, (byte) 0x6B, (byte) 0xF6, (byte) 0xD6, (byte) 0xAA, (byte) 0x4D, (byte) 0x5F, (byte) 0x19,
+ (byte) 0x7A, (byte) 0xAD, (byte) 0x44, (byte) 0x09, (byte) 0x33, (byte) 0x62, (byte) 0xC8, (byte) 0x56,
+ (byte) 0x82, (byte) 0x84, (byte) 0xBF, (byte) 0x52, (byte) 0xC6, (byte) 0xA2, (byte) 0x2B, (byte) 0xE3,
+ (byte) 0xC2, (byte) 0x7F, (byte) 0xE3, (byte) 0x06, (byte) 0xC3, (byte) 0x30, (byte) 0xB8, (byte) 0xD4,
+ (byte) 0x01, (byte) 0xE6, (byte) 0x3D, (byte) 0xDB, (byte) 0xCA, (byte) 0xE4, (byte) 0xFB, (byte) 0xA8,
+ (byte) 0x7B, (byte) 0x2D, (byte) 0x8F, (byte) 0x39, (byte) 0x7A, (byte) 0x63, (byte) 0x9F, (byte) 0x02,
+ (byte) 0xE8, (byte) 0x91, (byte) 0xD1, (byte) 0xEE, (byte) 0x60, (byte) 0xEE, (byte) 0xCA, (byte) 0xF2,
+ (byte) 0x33, (byte) 0x7D, (byte) 0xF2, (byte) 0x41, (byte) 0x52, (byte) 0x0B, (byte) 0x9B, (byte) 0x1B,
+ (byte) 0x2D, (byte) 0x89, (byte) 0x38, (byte) 0xEC, (byte) 0x24, (byte) 0x60, (byte) 0x40, (byte) 0x40,
+ (byte) 0x6F, (byte) 0xB6, (byte) 0x6F, (byte) 0x86, (byte) 0xB5, (byte) 0x0A, (byte) 0x3D, (byte) 0x98,
+ (byte) 0x77, (byte) 0x3F, (byte) 0x59, (byte) 0x41, (byte) 0x3E, (byte) 0x4D, (byte) 0xE4, (byte) 0x4E,
+ (byte) 0x91, (byte) 0xCD, (byte) 0x8E, (byte) 0x33, (byte) 0x60, (byte) 0x16, (byte) 0x8D, (byte) 0xAB,
+ (byte) 0x04, (byte) 0x14, (byte) 0xE8, (byte) 0x76, (byte) 0xF1, (byte) 0x06, (byte) 0xCD, (byte) 0x4A,
+ (byte) 0x88, (byte) 0xC7, (byte) 0x69, (byte) 0x6B, (byte) 0xC6, (byte) 0xDA, (byte) 0x9E, (byte) 0x09
+ };
+
private static final byte[] SHA256withRSA_Vector2Signature = new byte[] {
(byte) 0x18, (byte) 0x6e, (byte) 0x31, (byte) 0x1f, (byte) 0x1d, (byte) 0x44, (byte) 0x09, (byte) 0x3e,
(byte) 0xa0, (byte) 0xc4, (byte) 0x3d, (byte) 0xb4, (byte) 0x1b, (byte) 0xf2, (byte) 0xd8, (byte) 0xa4,
@@ -871,6 +1100,30 @@ public class SignatureTest extends TestCase {
assertTrue("Signature must verify correctly", sig.verify(signature));
}
+ public void testSign_SHA224withRSA_Key_Success() throws Exception {
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(RSA_2048_modulus,
+ RSA_2048_privateExponent);
+
+ final PrivateKey privKey = kf.generatePrivate(keySpec);
+
+ Signature sig = Signature.getInstance("SHA224withRSA");
+ sig.initSign(privKey);
+ sig.update(Vector2Data);
+
+ byte[] signature = sig.sign();
+ assertNotNull("Signature must not be null", signature);
+ assertTrue("Signature should match expected",
+ Arrays.equals(signature, SHA224withRSA_Vector2Signature));
+
+ RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(RSA_2048_modulus,
+ RSA_2048_publicExponent);
+ PublicKey pubKey = kf.generatePublic(pubKeySpec);
+ sig.initVerify(pubKey);
+ sig.update(Vector2Data);
+ assertTrue("Signature must verify correctly", sig.verify(signature));
+ }
+
public void testSign_SHA256withRSA_Key_Success() throws Exception {
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(RSA_2048_modulus,
@@ -1225,6 +1478,34 @@ public class SignatureTest extends TestCase {
(byte) 0xdc, (byte) 0x73, (byte) 0x3d, (byte) 0xf3, (byte) 0x51, (byte) 0xc0, (byte) 0x57,
};
+ /**
+ * A possible signature using SHA224withDSA of Vector2Data. Note that DSS is
+ * randomized, so this won't be the exact signature you'll get out of
+ * another signing operation unless you use a fixed RNG.
+ */
+ public static final byte[] SHA224withDSA_Vector2Signature = new byte[] {
+ (byte) 0x30, (byte) 0x2D, (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0xAD, (byte) 0xE5, (byte) 0x6D,
+ (byte) 0xF5, (byte) 0x11, (byte) 0x8D, (byte) 0x2E, (byte) 0x62, (byte) 0x5D, (byte) 0x98, (byte) 0x8A,
+ (byte) 0xC4, (byte) 0x88, (byte) 0x7E, (byte) 0xE6, (byte) 0xA3, (byte) 0x44, (byte) 0x99, (byte) 0xEF,
+ (byte) 0x49, (byte) 0x02, (byte) 0x14, (byte) 0x15, (byte) 0x3E, (byte) 0x32, (byte) 0xD6, (byte) 0xF9,
+ (byte) 0x79, (byte) 0x2C, (byte) 0x60, (byte) 0x6E, (byte) 0xF9, (byte) 0xA9, (byte) 0x78, (byte) 0xE7,
+ (byte) 0x4B, (byte) 0x87, (byte) 0x08, (byte) 0x96, (byte) 0x60, (byte) 0xDE, (byte) 0xB5
+ };
+
+ /**
+ * A possible signature using SHA256withDSA of Vector2Data. Note that DSS is
+ * randomized, so this won't be the exact signature you'll get out of
+ * another signing operation unless you use a fixed RNG.
+ */
+ public static final byte[] SHA256withDSA_Vector2Signature = new byte[] {
+ (byte) 0x30, (byte) 0x2D, (byte) 0x02, (byte) 0x14, (byte) 0x0A, (byte) 0xB1, (byte) 0x74, (byte) 0x45,
+ (byte) 0xE1, (byte) 0x63, (byte) 0x43, (byte) 0x68, (byte) 0x65, (byte) 0xBC, (byte) 0xCA, (byte) 0x45,
+ (byte) 0x27, (byte) 0x11, (byte) 0x4D, (byte) 0x52, (byte) 0xFB, (byte) 0x22, (byte) 0x93, (byte) 0xDD,
+ (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0x98, (byte) 0x32, (byte) 0x1A, (byte) 0x16, (byte) 0x77,
+ (byte) 0x49, (byte) 0xA7, (byte) 0x78, (byte) 0xFD, (byte) 0xE0, (byte) 0xF7, (byte) 0x71, (byte) 0xD4,
+ (byte) 0x80, (byte) 0x50, (byte) 0xA7, (byte) 0xDD, (byte) 0x94, (byte) 0xD1, (byte) 0x6C
+ };
+
public void testSign_SHA1withDSA_Key_Success() throws Exception {
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(DSA_priv, DSA_P, DSA_Q, DSA_G);
@@ -1255,10 +1536,73 @@ public class SignatureTest extends TestCase {
assertTrue("Signature must verify correctly", sig.verify(SHA1withDSA_Vector2Signature));
}
+ public void testSign_SHA224withDSA_Key_Success() throws Exception {
+ KeyFactory kf = KeyFactory.getInstance("DSA");
+ DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(DSA_priv, DSA_P, DSA_Q, DSA_G);
+ PrivateKey privKey = kf.generatePrivate(keySpec);
+
+ Signature sig = Signature.getInstance("SHA224withDSA");
+ sig.initSign(privKey);
+ sig.update(Vector2Data);
+
+ byte[] signature = sig.sign();
+ assertNotNull("Signature must not be null", signature);
+
+ DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G);
+ PublicKey pubKey = kf.generatePublic(pubKeySpec);
+ sig.initVerify(pubKey);
+ sig.update(Vector2Data);
+ assertTrue("Signature must verify correctly", sig.verify(signature));
+ }
+
+ public void testVerify_SHA224withDSA_Key_Success() throws Exception {
+ KeyFactory kf = KeyFactory.getInstance("DSA");
+ DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G);
+ PublicKey pubKey = kf.generatePublic(pubKeySpec);
+
+ Signature sig = Signature.getInstance("SHA224withDSA");
+ sig.initVerify(pubKey);
+ sig.update(Vector2Data);
+ assertTrue("Signature must verify correctly", sig.verify(SHA224withDSA_Vector2Signature));
+ }
+
+ public void testSign_SHA256withDSA_Key_Success() throws Exception {
+ KeyFactory kf = KeyFactory.getInstance("DSA");
+ DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(DSA_priv, DSA_P, DSA_Q, DSA_G);
+ PrivateKey privKey = kf.generatePrivate(keySpec);
+
+ Signature sig = Signature.getInstance("SHA256withDSA");
+ sig.initSign(privKey);
+ sig.update(Vector2Data);
+
+ byte[] signature = sig.sign();
+ assertNotNull("Signature must not be null", signature);
+
+ DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G);
+ PublicKey pubKey = kf.generatePublic(pubKeySpec);
+ sig.initVerify(pubKey);
+ sig.update(Vector2Data);
+ assertTrue("Signature must verify correctly", sig.verify(signature));
+ }
+
+ public void testVerify_SHA256withDSA_Key_Success() throws Exception {
+ KeyFactory kf = KeyFactory.getInstance("DSA");
+ DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(DSA_pub, DSA_P, DSA_Q, DSA_G);
+ PublicKey pubKey = kf.generatePublic(pubKeySpec);
+
+ Signature sig = Signature.getInstance("SHA256withDSA");
+ sig.initVerify(pubKey);
+ sig.update(Vector2Data);
+ assertTrue("Signature must verify correctly", sig.verify(SHA256withDSA_Vector2Signature));
+ }
+
// NetscapeCertRequest looks up Signature algorithms by OID from
// BC but BC version 1.47 had registration bugs and MD5withRSA was
// overlooked. http://b/7453821
public void testGetInstanceFromOID() throws Exception {
+ if (StandardNames.IS_RI) {
+ return;
+ }
assertBouncyCastleSignatureFromOID("1.2.840.113549.1.1.4"); // MD5withRSA
assertBouncyCastleSignatureFromOID("1.2.840.113549.1.1.5"); // SHA1withRSA
assertBouncyCastleSignatureFromOID("1.3.14.3.2.29"); // SHA1withRSA
@@ -1273,4 +1617,33 @@ public class SignatureTest extends TestCase {
assertNotNull(oid, signature);
assertEquals(oid, signature.getAlgorithm());
}
+
+ private final int THREAD_COUNT = 10;
+
+ private void testSignature_MultipleThreads_Misuse(final Signature s) throws Exception {
+ ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
+
+ final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
+ final byte[] message = new byte[64];
+
+ for (int i = 0; i < THREAD_COUNT; i++) {
+ es.submit(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ // Try to make sure all the threads are ready first.
+ latch.countDown();
+ latch.await();
+
+ for (int j = 0; j < 100; j++) {
+ s.update(message);
+ s.sign();
+ }
+
+ return null;
+ }
+ });
+ }
+ es.shutdown();
+ assertTrue("Test should not timeout", es.awaitTermination(1, TimeUnit.MINUTES));
+ }
}
diff --git a/luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java b/luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java
new file mode 100644
index 0000000..8030de1
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/cert/CRLReasonTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2014 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 libcore.java.security.cert;
+
+import java.security.cert.CRLReason;
+
+import junit.framework.TestCase;
+
+public class CRLReasonTest extends TestCase {
+ public void testCryptoPrimitive_ordinal_ExpectedValues() throws Exception {
+ assertEquals("UNSPECIFIED", 0, CRLReason.UNSPECIFIED.ordinal());
+ assertEquals("KEY_COMPROMISE", 1, CRLReason.KEY_COMPROMISE.ordinal());
+ assertEquals("CA_COMPROMISE", 2, CRLReason.CA_COMPROMISE.ordinal());
+ assertEquals("AFFILIATION_CHANGED", 3, CRLReason.AFFILIATION_CHANGED.ordinal());
+ assertEquals("SUPERSEDED", 4, CRLReason.SUPERSEDED.ordinal());
+ assertEquals("CESSATION_OF_OPERATION", 5, CRLReason.CESSATION_OF_OPERATION.ordinal());
+ assertEquals("CERTIFICATE_HOLD", 6, CRLReason.CERTIFICATE_HOLD.ordinal());
+ assertEquals("UNUSED", 7, CRLReason.UNUSED.ordinal());
+ assertEquals("REMOVE_FROM_CRL", 8, CRLReason.REMOVE_FROM_CRL.ordinal());
+ assertEquals("PRIVILEGE_WITHDRAWN", 9, CRLReason.PRIVILEGE_WITHDRAWN.ordinal());
+ assertEquals("AA_COMPROMISE", 10, CRLReason.AA_COMPROMISE.ordinal());
+ }
+
+ public void testCRLReason_values_ExpectedValues() throws Exception {
+ CRLReason[] reasons = CRLReason.values();
+ assertEquals(11, reasons.length);
+ assertEquals(CRLReason.UNSPECIFIED, reasons[0]);
+ assertEquals(CRLReason.KEY_COMPROMISE, reasons[1]);
+ assertEquals(CRLReason.CA_COMPROMISE, reasons[2]);
+ assertEquals(CRLReason.AFFILIATION_CHANGED, reasons[3]);
+ assertEquals(CRLReason.SUPERSEDED, reasons[4]);
+ assertEquals(CRLReason.CESSATION_OF_OPERATION, reasons[5]);
+ assertEquals(CRLReason.CERTIFICATE_HOLD, reasons[6]);
+ assertEquals(CRLReason.UNUSED, reasons[7]);
+ assertEquals(CRLReason.REMOVE_FROM_CRL, reasons[8]);
+ assertEquals(CRLReason.PRIVILEGE_WITHDRAWN, reasons[9]);
+ assertEquals(CRLReason.AA_COMPROMISE, reasons[10]);
+ }
+
+ public void testCRLReason_valueOf_ExpectedValues() throws Exception {
+ assertEquals(CRLReason.UNSPECIFIED, CRLReason.valueOf("UNSPECIFIED"));
+ assertEquals(CRLReason.KEY_COMPROMISE, CRLReason.valueOf("KEY_COMPROMISE"));
+ assertEquals(CRLReason.CA_COMPROMISE, CRLReason.valueOf("CA_COMPROMISE"));
+ assertEquals(CRLReason.AFFILIATION_CHANGED, CRLReason.valueOf("AFFILIATION_CHANGED"));
+ assertEquals(CRLReason.SUPERSEDED, CRLReason.valueOf("SUPERSEDED"));
+ assertEquals(CRLReason.CESSATION_OF_OPERATION, CRLReason.valueOf("CESSATION_OF_OPERATION"));
+ assertEquals(CRLReason.CERTIFICATE_HOLD, CRLReason.valueOf("CERTIFICATE_HOLD"));
+ assertEquals(CRLReason.UNUSED, CRLReason.valueOf("UNUSED"));
+ assertEquals(CRLReason.REMOVE_FROM_CRL, CRLReason.valueOf("REMOVE_FROM_CRL"));
+ assertEquals(CRLReason.PRIVILEGE_WITHDRAWN, CRLReason.valueOf("PRIVILEGE_WITHDRAWN"));
+ assertEquals(CRLReason.AA_COMPROMISE, CRLReason.valueOf("AA_COMPROMISE"));
+ }
+}
diff --git a/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java b/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java
index d69e0e2..0832dae 100644
--- a/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java
+++ b/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java
@@ -22,7 +22,6 @@
package libcore.java.security.cert;
-import dalvik.annotation.BrokenTest;
import java.io.ByteArrayInputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
@@ -176,7 +175,7 @@ public class OldPKIXParametersTest extends TestCase {
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
*/
- @BrokenTest("Fails in CTS environment, but passes in CoreTestRunner")
+ // Broken Test: Fails in CTS environment, but passes in CoreTestRunner
public final void testPKIXParametersKeyStore04() throws Exception {
diff --git a/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java b/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java
index fa920ce..42de50a 100644
--- a/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java
+++ b/luni/src/test/java/libcore/java/security/cert/X509CRLTest.java
@@ -30,12 +30,14 @@ import java.security.Provider;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.CRL;
+import java.security.cert.CRLReason;
import java.security.cert.CertificateFactory;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Arrays;
+import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
@@ -120,7 +122,7 @@ public class X509CRLTest extends TestCase {
private Map<String, Date> getCrlDates(String name) throws Exception {
Map<String, Date> dates = new HashMap<String, Date>();
- final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz");
+ final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz", Locale.US);
final InputStream ris = Support_Resources.getStream(name);
try {
@@ -316,6 +318,22 @@ public class X509CRLTest extends TestCase {
assertEquals(result1, result2);
}
+ /*
+ * This is needed because the certificate revocation in our CRL can be a
+ * couple seconds ahead of the lastUpdate time in the CRL.
+ */
+ private static void assertDateSlightlyBefore(Date expected, Date actual) throws Exception {
+ Calendar c = Calendar.getInstance();
+
+ // Make sure it's within 2 seconds of expected.
+ c.setTime(expected);
+ c.add(Calendar.SECOND, -2);
+ assertTrue(actual.after(c.getTime()));
+
+ // Before or equal...
+ assertTrue(actual.before(expected) || actual.equals(expected));
+ }
+
private void assertRsaCrlEntry(CertificateFactory f, X509CRLEntry rsaEntry) throws Exception {
assertNotNull(rsaEntry);
@@ -324,7 +342,8 @@ public class X509CRLTest extends TestCase {
Date expectedDate = dates.get("lastUpdate");
assertEquals(rsaCert.getSerialNumber(), rsaEntry.getSerialNumber());
- assertDateEquals(expectedDate, rsaEntry.getRevocationDate());
+ assertDateSlightlyBefore(expectedDate, rsaEntry.getRevocationDate());
+ assertNull(rsaEntry.getRevocationReason());
assertNull(rsaEntry.getCertificateIssuer());
assertFalse(rsaEntry.hasExtensions());
assertNull(rsaEntry.getCriticalExtensionOIDs());
@@ -334,18 +353,24 @@ public class X509CRLTest extends TestCase {
}
private void assertDsaCrlEntry(CertificateFactory f, X509CRLEntry dsaEntry) throws Exception {
+ assertNotNull(dsaEntry);
+
X509Certificate dsaCert = getCertificate(f, CERT_DSA);
Map<String, Date> dates = getCrlDates(CRL_RSA_DSA_DATES);
Date expectedDate = dates.get("lastUpdate");
assertEquals(dsaCert.getSerialNumber(), dsaEntry.getSerialNumber());
- assertDateEquals(expectedDate, dsaEntry.getRevocationDate());
+ assertDateSlightlyBefore(expectedDate, dsaEntry.getRevocationDate());
+ assertEquals(CRLReason.CESSATION_OF_OPERATION, dsaEntry.getRevocationReason());
assertNull(dsaEntry.getCertificateIssuer());
assertTrue(dsaEntry.hasExtensions());
- /* TODO: get the OID */
assertNotNull(dsaEntry.getCriticalExtensionOIDs());
- /* TODO: get the OID */
+ assertEquals(0, dsaEntry.getCriticalExtensionOIDs().size());
assertNotNull(dsaEntry.getNonCriticalExtensionOIDs());
+ assertEquals(1, dsaEntry.getNonCriticalExtensionOIDs().size());
+ assertTrue(Arrays.toString(dsaEntry.getNonCriticalExtensionOIDs().toArray()),
+ dsaEntry.getNonCriticalExtensionOIDs().contains("2.5.29.21"));
+ System.out.println(Arrays.toString(dsaEntry.getExtensionValue("2.5.29.21")));
assertNotNull(dsaEntry.toString());
}
@@ -362,13 +387,16 @@ public class X509CRLTest extends TestCase {
assertEquals(1, entries.size());
for (X509CRLEntry e : entries) {
assertRsaCrlEntry(f, e);
+ assertRsaCrlEntry(f, crlRsa.getRevokedCertificate(e.getSerialNumber()));
}
X509CRL crlRsaDsa = getCRL(f, CRL_RSA_DSA);
Set<? extends X509CRLEntry> entries2 = crlRsaDsa.getRevokedCertificates();
assertEquals(2, entries2.size());
assertRsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(rsaCert));
+ assertRsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(rsaCert.getSerialNumber()));
assertDsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(dsaCert));
+ assertDsaCrlEntry(f, crlRsaDsa.getRevokedCertificate(dsaCert.getSerialNumber()));
}
private void getSigAlgParams(CertificateFactory f) throws Exception {
diff --git a/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java b/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java
index ffddcbe..c35f8e6 100644
--- a/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java
+++ b/luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java
@@ -170,7 +170,8 @@ public class X509CertificateTest extends TestCase {
final InputStream ris = Support_Resources.getStream("x509/cert-rsa-dates.txt");
try {
// notBefore=Dec 26 00:19:14 2012 GMT
- final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz");
+ final SimpleDateFormat sdf =
+ new SimpleDateFormat("MMM dd HH:mm:ss yyyy zzz", Locale.US);
final BufferedReader buf = new BufferedReader(new InputStreamReader(ris));
String line = buf.readLine();
diff --git a/luni/src/test/java/libcore/java/sql/ConnectionTest.java b/luni/src/test/java/libcore/java/sql/ConnectionTest.java
new file mode 100644
index 0000000..02046fc
--- /dev/null
+++ b/luni/src/test/java/libcore/java/sql/ConnectionTest.java
@@ -0,0 +1,69 @@
+package libcore.java.sql;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+
+public class ConnectionTest extends TestCase {
+
+ private File dbFile = null;
+ private String connectionURL = null;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+
+ // Trigger the static initializer that will cause the driver to register itself with
+ // DriverManager.
+ Class.forName("SQLite.JDBCDriver");
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ if (dbFile != null) {
+ dbFile.delete();
+ }
+ }
+
+ public void testDriverManager_getConnection() throws Exception {
+ Connection c = DriverManager.getConnection(getConnectionURL());
+ assertFalse(c.isClosed());
+ c.close();
+ assertTrue(c.isClosed());
+ }
+
+ public void testConnect() throws Exception {
+ Driver driver = DriverManager.getDriver(getConnectionURL());
+ assertNotNull(driver);
+ Connection c = driver.connect(getConnectionURL(), null);
+ assertFalse(c.isClosed());
+ c.close();
+ assertTrue(c.isClosed());
+ }
+
+ private String getConnectionURL() {
+ if (connectionURL == null) {
+ String tmp = System.getProperty("java.io.tmpdir");
+ File tmpDir = new File(tmp);
+ if (tmpDir.isDirectory()) {
+ try {
+ dbFile = File.createTempFile("OldJDBCDriverTest", ".db", tmpDir);
+ } catch (IOException e) {
+ System.err.println("error creating temporary DB file.");
+ }
+ dbFile.deleteOnExit();
+ } else {
+ System.err.println("java.io.tmpdir does not exist");
+ }
+
+ connectionURL = "jdbc:sqlite:/" + dbFile.getPath();
+ }
+
+ return connectionURL;
+ }
+}
diff --git a/luni/src/test/java/libcore/java/sql/DriverTest.java b/luni/src/test/java/libcore/java/sql/DriverTest.java
new file mode 100644
index 0000000..59d13bd
--- /dev/null
+++ b/luni/src/test/java/libcore/java/sql/DriverTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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 libcore.java.sql;
+
+import junit.framework.TestCase;
+
+import SQLite.JDBCDriver;
+
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+
+public final class DriverTest extends TestCase {
+
+ public static final String SQLITE_JDBC_URL = "jdbc:sqlite:/only_used_at_connect_time";
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+
+ // Trigger the static initializer that will cause the driver to register itself with
+ // DriverManager.
+ Class.forName("SQLite.JDBCDriver");
+ }
+
+ public void testDriverImplementation() throws Exception {
+ Driver driver = getDriver();
+ assertTrue(driver instanceof JDBCDriver);
+ }
+
+ public void testAcceptsURL() throws Exception {
+ Driver driver = getDriver();
+ assertTrue(driver.acceptsURL(SQLITE_JDBC_URL));
+ }
+
+ public void testGetMajorVersion() throws Exception {
+ assertTrue(getDriver().getMajorVersion() > 0);
+ }
+
+ public void testGetMinorVersion() throws Exception {
+ assertTrue(getDriver().getMinorVersion() > 0);
+ }
+
+ public void testGetPropertyInfo() throws Exception {
+ Driver driver = getDriver();
+ DriverPropertyInfo[] info = driver.getPropertyInfo(SQLITE_JDBC_URL, null);
+ assertNotNull(info);
+ assertTrue(info.length > 0);
+ }
+
+ public void testJdbcCompliant() throws Exception {
+ // The SQLite JDBC driver used by these tests is not actually JDBC compliant.
+ assertFalse(getDriver().jdbcCompliant());
+ }
+
+ private Driver getDriver() throws SQLException {
+ Driver driver = DriverManager.getDriver(SQLITE_JDBC_URL);
+ assertNotNull(driver);
+ return driver;
+ }
+}
diff --git a/luni/src/test/java/libcore/java/sql/OldResultSetTest.java b/luni/src/test/java/libcore/java/sql/OldResultSetTest.java
index ea18db6..a1654cf 100644
--- a/luni/src/test/java/libcore/java/sql/OldResultSetTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldResultSetTest.java
@@ -80,7 +80,7 @@ public final class OldResultSetTest extends OldSQLTest {
try {
target.close();
- target.beforeFirst();
+ target.afterLast();
fail("Should get SQLException");
} catch (SQLException e) {
}
diff --git a/luni/src/test/java/libcore/java/sql/OldTimestampTest.java b/luni/src/test/java/libcore/java/sql/OldTimestampTest.java
deleted file mode 100644
index ab2034b..0000000
--- a/luni/src/test/java/libcore/java/sql/OldTimestampTest.java
+++ /dev/null
@@ -1,41 +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 libcore.java.sql;
-
-import java.sql.Timestamp;
-import java.util.TimeZone;
-import junit.framework.TestCase;
-
-public final class OldTimestampTest extends TestCase {
-
- public void test_toString() {
- TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
-
- Timestamp t1 = new Timestamp(Long.MIN_VALUE);
- assertEquals("292278994-08-17 07:12:55.192", t1.toString());
-
- Timestamp t2 = new Timestamp(Long.MIN_VALUE + 1);
- assertEquals("292278994-08-17 07:12:55.193", t2.toString());
-
- Timestamp t3 = new Timestamp(Long.MIN_VALUE + 807);
- assertEquals("292278994-08-17 07:12:55.999", t3.toString());
-
- Timestamp t4 = new Timestamp(Long.MIN_VALUE + 808);
- assertEquals("292269055-12-02 16:47:05.0", t4.toString());
- }
-}
diff --git a/luni/src/test/java/libcore/java/sql/TimestampTest.java b/luni/src/test/java/libcore/java/sql/TimestampTest.java
new file mode 100644
index 0000000..2985848
--- /dev/null
+++ b/luni/src/test/java/libcore/java/sql/TimestampTest.java
@@ -0,0 +1,147 @@
+/*
+ * 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 libcore.java.sql;
+
+import java.sql.Timestamp;
+import java.util.TimeZone;
+import junit.framework.TestCase;
+
+public final class TimestampTest extends TestCase {
+
+ public void testToString() {
+ // Timestamp uses the current default timezone in toString() to convert to
+ // human-readable strings.
+ TimeZone defaultTimeZone = TimeZone.getDefault();
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+ try {
+ Timestamp t1 = new Timestamp(Long.MIN_VALUE);
+ assertEquals("292278994-08-17 07:12:55.192", t1.toString());
+
+ Timestamp t2 = new Timestamp(Long.MIN_VALUE + 1);
+ assertEquals("292278994-08-17 07:12:55.193", t2.toString());
+
+ Timestamp t3 = new Timestamp(Long.MIN_VALUE + 807);
+ assertEquals("292278994-08-17 07:12:55.999", t3.toString());
+
+ Timestamp t4 = new Timestamp(Long.MIN_VALUE + 808);
+ assertEquals("292269055-12-02 16:47:05.0", t4.toString());
+ } finally {
+ TimeZone.setDefault(defaultTimeZone);
+ }
+ }
+
+ public void testValueOf() {
+ // Timestamp uses the current default timezone in valueOf(String) to convert
+ // from human-readable strings.
+ TimeZone defaultTimeZone = TimeZone.getDefault();
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ try {
+ Timestamp t1 = Timestamp.valueOf("2001-12-31 21:45:57.123456789");
+ assertEquals(1009835157000L + 123456789 / 1000000, t1.getTime());
+ assertEquals(123456789, t1.getNanos());
+
+ Timestamp t2 = Timestamp.valueOf("2001-01-02 01:05:07.123");
+ assertEquals(978397507000L + 123000000 / 1000000, t2.getTime());
+ assertEquals(123000000, t2.getNanos());
+
+ Timestamp t3 = Timestamp.valueOf("2001-01-02 01:05:07");
+ assertEquals(978397507000L, t3.getTime());
+ assertEquals(0, t3.getNanos());
+ } finally {
+ TimeZone.setDefault(defaultTimeZone);
+ }
+ }
+
+ public void testValueOfInvalid() {
+ try {
+ Timestamp.valueOf("");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("+2001-12-31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001-+12-31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001-12-+31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("-2001-12-31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001--12-31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001-12--31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001--");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001--31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("-12-31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("-12-");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("--31");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001-12-31 21:45:57.+12345678");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001-12-31 21:45:57.-12345678");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ Timestamp.valueOf("2001-12-31 21:45:57.1234567891");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+ }
+
+}
diff --git a/luni/src/test/java/libcore/java/text/CollatorTest.java b/luni/src/test/java/libcore/java/text/CollatorTest.java
index 0a61f04..0f65b20 100644
--- a/luni/src/test/java/libcore/java/text/CollatorTest.java
+++ b/luni/src/test/java/libcore/java/text/CollatorTest.java
@@ -88,7 +88,7 @@ public class CollatorTest extends junit.framework.TestCase {
}
public void testEqualsObject() throws ParseException {
- String rule = "< a < b < c < d < e";
+ String rule = "&9 < a < b < c < d < e";
RuleBasedCollator coll = new RuleBasedCollator(rule);
assertEquals(Collator.TERTIARY, coll.getStrength());
@@ -109,7 +109,7 @@ public class CollatorTest extends junit.framework.TestCase {
// Regression test for HARMONY-1352, that doesn't get run in the harmony test suite because
// of an earlier failure.
try {
- new RuleBasedCollator("< a< b< c< d").getCollationElementIterator((CharacterIterator) null);
+ new RuleBasedCollator("&9 < a< b< c< d").getCollationElementIterator((CharacterIterator) null);
fail("NullPointerException expected");
} catch (NullPointerException expected) {
}
@@ -139,7 +139,7 @@ public class CollatorTest extends junit.framework.TestCase {
}
public void testGetCollationElementIteratorString_de_DE() throws Exception {
- assertGetCollationElementIteratorString(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 1, 1, 2);
+ assertGetCollationElementIteratorString(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 2);
}
public void testGetCollationElementIteratorCharacterIterator_es() throws Exception {
@@ -147,6 +147,6 @@ public class CollatorTest extends junit.framework.TestCase {
}
public void testGetCollationElementIteratorCharacterIterator_de_DE() throws Exception {
- assertGetCollationElementIteratorCharacterIterator(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 1, 1, 2);
+ assertGetCollationElementIteratorCharacterIterator(new Locale("de", "DE", ""), "\u00e6b", 0, 1, 1, 2);
}
}
diff --git a/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java b/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java
index e13e4df..057cd17 100644
--- a/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java
+++ b/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java
@@ -46,6 +46,10 @@ public class DateFormatSymbolsTest extends junit.framework.TestCase {
}
public void testSerialization() throws Exception {
+ // Set the default locale. The default locale used to determine what strings were used by
+ // the DateFormatSymbols after deserialization. See http://b/16502916
+ Locale.setDefault(Locale.US);
+
// The Polish language needs stand-alone month and weekday names.
Locale pl = new Locale("pl");
DateFormatSymbols originalDfs = new DateFormatSymbols(pl);
@@ -60,17 +64,16 @@ public class DateFormatSymbolsTest extends junit.framework.TestCase {
DateFormatSymbols deserializedDfs = (DateFormatSymbols) in.readObject();
assertEquals(-1, in.read());
- // The two objects should claim to be equal, even though they aren't really.
+ // The two objects be equal.
assertEquals(originalDfs, deserializedDfs);
// The original differentiates between regular month names and stand-alone month names...
assertEquals("stycznia", formatDate(pl, "MMMM", originalDfs));
assertEquals("stycze\u0144", formatDate(pl, "LLLL", originalDfs));
- // But the deserialized object is screwed because the RI's serialized form doesn't
- // contain the locale or the necessary strings. Don't serialize DateFormatSymbols, folks!
+ // And so does the deserialized version.
assertEquals("stycznia", formatDate(pl, "MMMM", deserializedDfs));
- assertEquals("January", formatDate(pl, "LLLL", deserializedDfs));
+ assertEquals("stycze\u0144", formatDate(pl, "LLLL", deserializedDfs));
}
private String formatDate(Locale l, String fmt, DateFormatSymbols dfs) {
diff --git a/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java b/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java
index 8b24c6d..619c38e 100644
--- a/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java
+++ b/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java
@@ -24,18 +24,21 @@ import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class DecimalFormatSymbolsTest extends junit.framework.TestCase {
- private void checkLocaleIsEquivalentToRoot(Locale locale) {
- DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
- assertEquals(DecimalFormatSymbols.getInstance(Locale.ROOT), dfs);
- }
public void test_getInstance_unknown_or_invalid_locale() throws Exception {
- // TODO: we fail these tests because ROOT has "INF" for infinity but 'dfs' has "\u221e".
- // On the RI, ROOT has "\u221e" too, but DecimalFormatSymbols.equals appears to be broken;
- // it returns false for objects that -- if you compare their externally visible state --
- // are equal. It could be that they're accidentally checking the Locale.
+ // http://b/17374604: this test passes on the host but fails on the target.
+ // ICU uses setlocale(3) to determine its default locale, and glibc (on my box at least)
+ // returns "en_US.UTF-8". bionic before L returned NULL and in L returns "C.UTF-8", both
+ // of which get treated as "en_US_POSIX". What that means for this test is that you get
+ // "INF" for infinity instead of "\u221e".
+ // On the RI, this test fails for a different reason: their DecimalFormatSymbols.equals
+ // appears to be broken. It could be that they're accidentally checking the Locale field?
checkLocaleIsEquivalentToRoot(new Locale("xx", "XX"));
checkLocaleIsEquivalentToRoot(new Locale("not exist language", "not exist country"));
}
+ private void checkLocaleIsEquivalentToRoot(Locale locale) {
+ DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
+ assertEquals(DecimalFormatSymbols.getInstance(Locale.ROOT), dfs);
+ }
// http://code.google.com/p/android/issues/detail?id=14495
public void testSerialization() throws Exception {
diff --git a/luni/src/test/java/libcore/java/text/DecimalFormatTest.java b/luni/src/test/java/libcore/java/text/DecimalFormatTest.java
index 1e40f8a..0eae20a 100644
--- a/luni/src/test/java/libcore/java/text/DecimalFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/DecimalFormatTest.java
@@ -21,7 +21,9 @@ import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
+import java.text.FieldPosition;
import java.text.NumberFormat;
+import java.text.ParsePosition;
import java.util.Currency;
import java.util.Locale;
@@ -122,21 +124,21 @@ public class DecimalFormatTest extends junit.framework.TestCase {
df.setMaximumFractionDigits(2);
df.setMultiplier(2);
assertEquals(df.format(BigDecimal.valueOf(0.16)),
- df.format(BigDecimal.valueOf(0.16).doubleValue()));
+ df.format(BigDecimal.valueOf(0.16).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(0.0293)),
- df.format(BigDecimal.valueOf(0.0293).doubleValue()));
+ df.format(BigDecimal.valueOf(0.0293).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(0.006)),
- df.format(BigDecimal.valueOf(0.006).doubleValue()));
+ df.format(BigDecimal.valueOf(0.006).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(0.00283)),
- df.format(BigDecimal.valueOf(0.00283).doubleValue()));
+ df.format(BigDecimal.valueOf(0.00283).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(1.60)),
df.format(BigDecimal.valueOf(1.60).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(15)),
- df.format(BigDecimal.valueOf(15).doubleValue()));
+ df.format(BigDecimal.valueOf(15).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(170)),
- df.format(BigDecimal.valueOf(170).doubleValue()));
+ df.format(BigDecimal.valueOf(170).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(234.56)),
- df.format(BigDecimal.valueOf(234.56).doubleValue()));
+ df.format(BigDecimal.valueOf(234.56).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(0)),
df.format(BigDecimal.valueOf(0).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(-1)),
@@ -144,11 +146,11 @@ public class DecimalFormatTest extends junit.framework.TestCase {
assertEquals(df.format(BigDecimal.valueOf(-10000)),
df.format(BigDecimal.valueOf(-10000).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(-0.001)),
- df.format(BigDecimal.valueOf(-0.001).doubleValue()));
+ df.format(BigDecimal.valueOf(-0.001).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(1234567890.1234567)),
- df.format(BigDecimal.valueOf(1234567890.1234567).doubleValue()));
+ df.format(BigDecimal.valueOf(1234567890.1234567).doubleValue()));
assertEquals(df.format(BigDecimal.valueOf(1.234567E100)),
- df.format(BigDecimal.valueOf(1.234567E100).doubleValue()));
+ df.format(BigDecimal.valueOf(1.234567E100).doubleValue()));
}
private void assertBigDecimalWithFraction(BigDecimal bd, String expectedResult, int fraction) {
@@ -197,4 +199,123 @@ public class DecimalFormatTest extends junit.framework.TestCase {
df.setCurrency(Currency.getInstance("CHF"));
df.setCurrency(Currency.getInstance("GBP"));
}
+
+ // Check we don't crash on null inputs.
+ public void testBug15081434() throws Exception {
+ DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
+ try {
+ df.parse(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ df.applyLocalizedPattern(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ df.applyPattern(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ df.applyPattern(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ df.format(null, new StringBuffer(), new FieldPosition(0));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ df.parse(null, new ParsePosition(0));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // This just ignores null.
+ df.setDecimalFormatSymbols(null);
+
+ try {
+ df.setCurrency(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // These just ignore null.
+ df.setNegativePrefix(null);
+ df.setNegativeSuffix(null);
+ df.setPositivePrefix(null);
+ df.setPositiveSuffix(null);
+
+ try {
+ df.setRoundingMode(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ // Confirm the fraction digits do not change when the currency is changed.
+ public void testBug71369() {
+ final String nonBreakingSpace = "\u00A0";
+
+ NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.GERMAN);
+ numberFormat.setCurrency(Currency.getInstance("USD"));
+
+ assertEquals("2,01" + nonBreakingSpace + "$", numberFormat.format(2.01));
+
+ numberFormat.setMinimumFractionDigits(0);
+ numberFormat.setMaximumFractionDigits(0);
+
+ String expected = "2" + nonBreakingSpace + "$";
+ assertEquals(expected, numberFormat.format(2.01));
+
+ // Changing the currency must not reset the digits.
+ numberFormat.setCurrency(Currency.getInstance("EUR"));
+ numberFormat.setCurrency(Currency.getInstance("USD"));
+
+ assertEquals(expected, numberFormat.format(2.01));
+ }
+
+ // Confirm the currency symbol used by a format is determined by the locale of the format
+ // not the current default Locale.
+ public void testSetCurrency_symbolOrigin() {
+ Currency currency = Currency.getInstance("CNY");
+ Locale locale1 = Locale.CHINA;
+ Locale locale2 = Locale.US;
+ String locale1Symbol = currency.getSymbol(locale1);
+ String locale2Symbol = currency.getSymbol(locale2);
+ // This test only works if we can tell where the symbol came from, which requires they are
+ // different across the two locales chosen.
+ assertFalse(locale1Symbol.equals(locale2Symbol));
+
+ Locale originalLocale = Locale.getDefault();
+ try {
+ Locale.setDefault(locale1);
+ String amountDefaultLocale1 =
+ formatArbitraryCurrencyAmountInLocale(currency, locale2);
+
+ Locale.setDefault(locale2);
+ String amountDefaultLocale2 =
+ formatArbitraryCurrencyAmountInLocale(currency, locale2);
+
+ // This used to fail because Currency.getSymbol() was used without providing the
+ // format's locale.
+ assertEquals(amountDefaultLocale1, amountDefaultLocale2);
+ } finally {
+ Locale.setDefault(originalLocale);
+ }
+ }
+
+ private String formatArbitraryCurrencyAmountInLocale(Currency currency, Locale locale) {
+ NumberFormat localeCurrencyFormat = NumberFormat.getCurrencyInstance(locale);
+ localeCurrencyFormat.setCurrency(currency);
+ return localeCurrencyFormat.format(1000);
+ }
}
diff --git a/luni/src/test/java/libcore/java/text/NumberFormatTest.java b/luni/src/test/java/libcore/java/text/NumberFormatTest.java
index 1a14462..4ff063b 100644
--- a/luni/src/test/java/libcore/java/text/NumberFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/NumberFormatTest.java
@@ -66,16 +66,16 @@ public class NumberFormatTest extends junit.framework.TestCase {
public void test_getIntegerInstance_ar() throws Exception {
NumberFormat numberFormat = NumberFormat.getNumberInstance(new Locale("ar"));
- assertEquals("#0.###;#0.###-", ((DecimalFormat) numberFormat).toPattern());
+ assertEquals("#,##0.###", ((DecimalFormat) numberFormat).toPattern());
NumberFormat integerFormat = NumberFormat.getIntegerInstance(new Locale("ar"));
- assertEquals("#0;#0-", ((DecimalFormat) integerFormat).toPattern());
+ assertEquals("#,##0", ((DecimalFormat) integerFormat).toPattern());
}
public void test_numberLocalization() throws Exception {
Locale arabic = new Locale("ar");
NumberFormat nf = NumberFormat.getNumberInstance(arabic);
assertEquals('\u0660', new DecimalFormatSymbols(arabic).getZeroDigit());
- assertEquals("١٢٣٤٥٦٧٨٩٠", nf.format(1234567890));
+ assertEquals("١٬٢٣٤٬٥٦٧٬٨٩٠", nf.format(1234567890));
}
// Formatting percentages is confusing but deliberate.
@@ -90,4 +90,40 @@ public class NumberFormatTest extends junit.framework.TestCase {
} catch (IllegalArgumentException expected) {
}
}
+
+ public void test_62269() throws Exception {
+ NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
+ try {
+ nf.parse(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_nullLocales() {
+ try {
+ NumberFormat.getInstance(null);
+ fail();
+ } catch (NullPointerException expected) {}
+
+ try {
+ NumberFormat.getIntegerInstance(null);
+ fail();
+ } catch (NullPointerException expected) {}
+
+ try {
+ NumberFormat.getCurrencyInstance(null);
+ fail();
+ } catch (NullPointerException expected) {}
+
+ try {
+ NumberFormat.getPercentInstance(null);
+ fail();
+ } catch (NullPointerException expected) {}
+
+ try {
+ NumberFormat.getNumberInstance(null);
+ fail();
+ } catch (NullPointerException expected) {}
+ }
}
diff --git a/luni/src/test/java/libcore/java/text/OldBidiTest.java b/luni/src/test/java/libcore/java/text/OldBidiTest.java
index 2e5fd21..45fe258 100644
--- a/luni/src/test/java/libcore/java/text/OldBidiTest.java
+++ b/luni/src/test/java/libcore/java/text/OldBidiTest.java
@@ -22,11 +22,9 @@ import junit.framework.TestCase;
public class OldBidiTest extends TestCase {
- Bidi bd;
-
public void testToString() {
try {
- bd = new Bidi("bidi", 173);
+ Bidi bd = new Bidi("bidi", 173);
assertNotNull("Bidi representation is null", bd.toString());
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
@@ -41,7 +39,7 @@ public class OldBidiTest extends TestCase {
}
public void testGetRunLevelLInt() {
- bd = new Bidi("text", Bidi.DIRECTION_LEFT_TO_RIGHT);
+ Bidi bd = new Bidi("text", Bidi.DIRECTION_LEFT_TO_RIGHT);
try {
assertEquals(0, bd.getRunLevel(0));
assertEquals(0, bd.getRunLevel(bd.getRunCount()));
@@ -65,25 +63,11 @@ public class OldBidiTest extends TestCase {
}
public void testGetRunStart() {
- bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -7,
+ Bidi bd = new Bidi(new char[] { 's', 's', 's' }, 0, new byte[] { (byte) -7,
(byte) -2, (byte) 3 }, 0, 3,
Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
assertEquals(0, bd.getRunStart(0));
assertEquals(1, bd.getRunStart(1));
assertEquals(2, bd.getRunStart(2));
-
- String LTR = "\u0061\u0062";
- String RTL = "\u05DC\u05DD";
- String newLine = "\n";
- String defText = LTR + newLine + RTL + LTR + RTL;
-
- int[][] expectedRuns = { { 0, 3 }, { 3, 5 }, { 5, 7 }, { 7, 9 }, };
-
- Bidi bi = new Bidi(defText, 0);
-
- final int count = bi.getRunCount();
- for (int i = 0; i < count; i++) {
- assertEquals(expectedRuns[i][0], bi.getRunStart(i));
- }
}
}
diff --git a/luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.java b/luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.java
deleted file mode 100644
index 9e98a56..0000000
--- a/luni/src/test/java/libcore/java/text/OldCollationElementIteratorTest.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 libcore.java.text;
-
-import java.text.CollationElementIterator;
-import java.text.Collator;
-import java.text.RuleBasedCollator;
-import java.util.Locale;
-import junit.framework.TestCase;
-
-public class OldCollationElementIteratorTest extends TestCase {
-
- public void testPrevious() {
- RuleBasedCollator coll = (RuleBasedCollator) Collator.getInstance(Locale.US);
- String text = "abc";
- CollationElementIterator iterator = coll
- .getCollationElementIterator(text);
- int[] orders = new int[text.length()];
- int order = iterator.next();
- int i = 0;
- while (order != CollationElementIterator.NULLORDER) {
- orders[i++] = order;
- order = iterator.next();
- }
-
- int offset = iterator.getOffset();
- assertEquals(text.length(), offset);
- order = iterator.previous();
-
- while (order != CollationElementIterator.NULLORDER) {
- assertEquals(orders[--i], order);
- order = iterator.previous();
- }
-
- assertEquals(0, iterator.getOffset());
- }
-}
diff --git a/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java b/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java
index 1fc8264..eea5246 100644
--- a/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java
+++ b/luni/src/test/java/libcore/java/text/OldCollationKeyTest.java
@@ -24,7 +24,7 @@ import java.text.RuleBasedCollator;
public class OldCollationKeyTest extends junit.framework.TestCase {
- public void test_toByteArray() {
+ public void test_toByteArray() throws ParseException {
// Test for method byte [] java.text.CollationKey.toByteArray()
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
@@ -32,12 +32,7 @@ public class OldCollationKeyTest extends junit.framework.TestCase {
byte[] bytes = key1.toByteArray();
assertTrue("Not enough bytes", bytes.length >= 3);
- try {
- collator = new RuleBasedCollator("= 1 , 2 ; 3 , 4 < 5 ; 6 , 7");
- } catch (ParseException e) {
- fail("ParseException");
- return;
- }
+ collator = new RuleBasedCollator("&0 = 1 , 2 ; 3 , 4 < 5 ; 6 , 7");
/*
* CollationElementIterator it =
* ((RuleBasedCollator)collator).getCollationElementIterator("1234567");
diff --git a/luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java b/luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java
deleted file mode 100644
index f3e016e..0000000
--- a/luni/src/test/java/libcore/java/text/OldDecimalFormatTest.java
+++ /dev/null
@@ -1,1007 +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 libcore.java.text;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.text.AttributedCharacterIterator;
-import java.text.DecimalFormat;
-import java.text.DecimalFormatSymbols;
-import java.text.FieldPosition;
-import java.text.NumberFormat;
-import java.text.ParseException;
-import java.text.ParsePosition;
-import java.util.BitSet;
-import java.util.Locale;
-import junit.framework.TestCase;
-import tests.support.Support_DecimalFormat;
-
-public class OldDecimalFormatTest extends TestCase {
-
- public void test_formatToCharacterIterator() throws Exception {
- AttributedCharacterIterator iterator;
- int[] runStarts;
- int[] runLimits;
- String result;
- char current;
-
- // For BigDecimal with multiplier test.
- DecimalFormat df = new DecimalFormat();
- df.setMultiplier(10);
- iterator = df.formatToCharacterIterator(new BigDecimal("12345678901234567890"));
- result = "123,456,789,012,345,678,900";
- current = iterator.current();
- for (int i = 0; i < result.length(); i++) {
- assertEquals("wrong char @" + i, result.charAt(i), current);
- current = iterator.next();
- }
-
- // For BigDecimal with multiplier test.
- df = new DecimalFormat();
- df.setMultiplier(-1);
- df.setMaximumFractionDigits(20);
- iterator = df.formatToCharacterIterator(new BigDecimal("1.23456789012345678901"));
- result = "-1.23456789012345678901";
- current = iterator.current();
- for (int i = 0; i < result.length(); i++) {
- assertEquals("wrong char @" + i, result.charAt(i), current);
- current = iterator.next();
- }
-
- iterator = new DecimalFormat()
- .formatToCharacterIterator(new BigDecimal("1.23456789E1234"));
- runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14};
- runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15};
- result = "12,345,678,900,"; // 000,000,000,000....
- current = iterator.current();
- for (int i = 0; i < runStarts.length; i++) {
- assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
- assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
- assertEquals("wrong char @" + i, result.charAt(i), current);
- current = iterator.next();
- }
- assertEquals(0, iterator.getBeginIndex());
- assertEquals(1646, iterator.getEndIndex());
-
- iterator = new DecimalFormat()
- .formatToCharacterIterator(new BigDecimal("1.23456789E301"));
- runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14};
- runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15};
- result = "12,345,678,900,"; // 000,000,000,000....
- current = iterator.current();
- for (int i = 0; i < runStarts.length; i++) {
- assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
- assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
- assertEquals("wrong char @" + i, result.charAt(i), current);
- current = iterator.next();
- }
- assertEquals(0, iterator.getBeginIndex());
- assertEquals(402, iterator.getEndIndex());
-
- iterator = new DecimalFormat()
- .formatToCharacterIterator(new BigDecimal("1.2345678E4"));
- runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7};
- runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10};
- result = "12,345.678";
- current = iterator.current();
- for (int i = 0; i < runStarts.length; i++) {
- assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
- assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
- assertEquals("wrong char @" + i, result.charAt(i), current);
- current = iterator.next();
- }
- assertEquals(0, iterator.getBeginIndex());
- assertEquals(10, iterator.getEndIndex());
-
- iterator = new DecimalFormat()
- .formatToCharacterIterator(new BigInteger("123456789"));
- runStarts = new int[] {0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8};
- runLimits = new int[] {3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11};
- result = "123,456,789";
- current = iterator.current();
- for (int i = 0; i < runStarts.length; i++) {
- assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
- assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
- assertEquals("wrong char @" + i, result.charAt(i), current);
- current = iterator.next();
- }
- assertEquals(0, iterator.getBeginIndex());
- assertEquals(11, iterator.getEndIndex());
- }
-
- /*
- * Test the getter and setter of parseBigDecimal and parseIntegerOnly and
- * test the default value of them.
- */
- public void test_isParseBigDecimalLjava_lang_Boolean_isParseIntegerOnlyLjava_lang_Boolean() {
-
- // parseBigDecimal default to false
- DecimalFormat form = (DecimalFormat) DecimalFormat
- .getInstance(Locale.US);
- assertFalse(form.isParseBigDecimal());
- form.setParseBigDecimal(true);
- assertTrue(form.isParseBigDecimal());
-
- try {
- Number result = form.parse("123.123");
- assertEquals(new BigDecimal("123.123"), result);
- } catch (ParseException e) {
- fail("ParseException was thrown.");
- }
-
- form.setParseBigDecimal(false);
- assertFalse(form.isParseBigDecimal());
-
- try {
- Number result = form.parse("123.123");
- assertFalse(result instanceof BigDecimal);
- } catch (ParseException e) {
- fail("ParseException was thrown.");
- }
-
- // parseIntegerOnly default to false
- assertFalse(form.isParseIntegerOnly());
- }
-
- public void test_isParseIntegerOnly() {
-
- DecimalFormat format = new DecimalFormat();
- assertFalse("Default value of isParseIntegerOnly is true",
- format.isParseIntegerOnly());
-
- format.setParseIntegerOnly(true);
- assertTrue(format.isParseIntegerOnly());
- try {
- Number result = format.parse("123.123");
- assertEquals(new Long("123"), result);
- } catch (ParseException e) {
- fail("ParseException was thrown.");
- }
-
- format.setParseIntegerOnly(false);
- assertFalse(format.isParseIntegerOnly());
- try {
- Number result = format.parse("123.123");
- assertEquals(new Double("123.123"), result);
- } catch (ParseException e) {
- fail("ParseException was thrown.");
- }
- }
-
- public void test_isGroupingUsed() {
- String [] patterns = {"####.##", "######.######", "000000.000000",
- "######.000000", "000000.######", " ###.###", "$#####.######",
- "$$####.######"};
-
- for(String pattern:patterns) {
- DecimalFormat format = new DecimalFormat(pattern);
- assertFalse(format.isGroupingUsed());
- }
-
- DecimalFormat format = new DecimalFormat("###,####");
- assertTrue(format.isGroupingUsed());
- }
-
- // Test the type of the returned object
- public void test_parseLjava_lang_String_Ljava_text_ParsePosition() {
- DecimalFormat form = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
- form.setParseIntegerOnly(true);
- form.setParseBigDecimal(true);
-
- final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408,"
- + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077,"
- + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653,"
- + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152,"
- + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806,"
- + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476,"
- + "354,361,838,599,762,500,808,052,368,249,716,736";
- Number number = form.parse(doubleMax2, new ParsePosition(0));
- assertTrue(number instanceof BigDecimal);
- BigDecimal result = (BigDecimal)number;
- assertEquals(new BigDecimal(Double.MAX_VALUE).add(new BigDecimal(
- Double.MAX_VALUE)), result);
- }
-
- // AndroidOnly: Difference to RI
- public void test_getMaximumIntegerDigits_AndroidOnly() {
- final int maxIntDigit = 309;
-
- // When use default locale, in this case zh_CN
- // the returned instance of NumberFormat is a DecimalFormat
- DecimalFormat form = new DecimalFormat("00.###E0");
- NumberFormat nform = DecimalFormat.getInstance(Locale.US);
- nform = DecimalFormat.getInstance(Locale.US);
- form = null;
- if (nform instanceof DecimalFormat) {
- form = (DecimalFormat) nform;
- }
- // getMaximumIntegerDigits from NumberFormat default to 309
- // getMaximumIntegerDigits from DecimalFormat default to 309
- // the following 2 assertions will fail on RI implementation, since the
- // implementation of ICU and RI are not identical. RI does not give
- // DecimalFormat an initial bound about its maximumIntegerDigits
- // (default to Integer.MAX_VALUE: 2147483647 )
- assertEquals(maxIntDigit, nform.getMaximumIntegerDigits());
- assertEquals(maxIntDigit, form.getMaximumIntegerDigits());
- }
-
- // AndroidOnly: second 0 needs to be quoted in icu.
- // (quoting special characters in prefix and suffix necessary)
- public void test_getMaximumIntegerDigits2() {
- // regression test for HARMONY-878
- assertTrue(new DecimalFormat("0\t'0'").getMaximumIntegerDigits() > 0);
- }
-
- public void test_setPositivePrefixLjava_lang_String() {
- DecimalFormat format = new DecimalFormat();
- assertEquals("", format.getPositivePrefix());
-
- format.setPositivePrefix("PosPrf");
- assertEquals("PosPrf", format.getPositivePrefix());
- try {
- assertTrue(format.parse("PosPrf123.45").doubleValue() == 123.45);
- } catch(java.text.ParseException pe) {
- fail("ParseException was thrown.");
- }
-
- format.setPositivePrefix("");
- assertEquals("", format.getPositivePrefix());
-
- format.setPositivePrefix(null);
- assertNull(format.getPositivePrefix());
- }
- public void test_setPositiveSuffixLjava_lang_String() {
- DecimalFormat format = new DecimalFormat();
- assertEquals("", format.getPositiveSuffix());
-
- format.setPositiveSuffix("PosSfx");
- assertEquals("PosSfx", format.getPositiveSuffix());
- try {
- assertTrue(format.parse("123.45PosSfx").doubleValue() == 123.45);
- } catch(java.text.ParseException pe) {
- fail("ParseException was thrown.");
- }
-
- format.setPositiveSuffix("");
- assertEquals("", format.getPositiveSuffix());
-
- format.setPositiveSuffix(null);
- assertNull(format.getPositiveSuffix());
- }
- public void test_setNegativePrefixLjava_lang_String() {
- DecimalFormat format = new DecimalFormat();
- assertEquals("-", format.getNegativePrefix());
-
- format.setNegativePrefix("NegPrf");
- assertEquals("NegPrf", format.getNegativePrefix());
- try {
- assertTrue(format.parse("NegPrf123.45").doubleValue() == -123.45);
- } catch(java.text.ParseException pe) {
- fail("ParseException was thrown.");
- }
- format.setNegativePrefix("");
- assertEquals("", format.getNegativePrefix());
-
- format.setNegativePrefix(null);
- assertNull(format.getNegativePrefix());
- }
- public void test_setNegativeSuffixLjava_lang_String() {
- DecimalFormat format = new DecimalFormat();
- assertEquals("", format.getNegativeSuffix());
-
- format.setNegativeSuffix("NegSfx");
- assertEquals("NegSfx", format.getNegativeSuffix());
- try {
- assertTrue(format.parse("123.45NegPfx").doubleValue() == 123.45);
- } catch(java.text.ParseException pe) {
- fail("ParseException was thrown.");
- }
-
- format.setNegativeSuffix("");
- assertEquals("", format.getNegativeSuffix());
-
- format.setNegativeSuffix(null);
- assertNull(format.getNegativeSuffix());
- }
-
- public void test_toLocalizedPattern() {
- DecimalFormat format = new DecimalFormat();
- format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
- try {
- format.applyLocalizedPattern("#.#");
- assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern());
- format.applyLocalizedPattern("#.");
- assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern());
- format.applyLocalizedPattern("#");
- assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern());
- format.applyLocalizedPattern(".#");
- assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_toPattern() {
- DecimalFormat format = new DecimalFormat();
- try {
- format.applyPattern("#.#");
- assertEquals("Wrong pattern 1", "#0.#", format.toPattern());
- format.applyPattern("#.");
- assertEquals("Wrong pattern 2", "#0.", format.toPattern());
- format.applyPattern("#");
- assertEquals("Wrong pattern 3", "#", format.toPattern());
- format.applyPattern(".#");
- assertEquals("Wrong pattern 4", "#.0", format.toPattern());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
- public void test_setGroupingUse() {
- DecimalFormat format = new DecimalFormat();
-
- StringBuffer buf = new StringBuffer();
- format.setGroupingUsed(false);
- format.format(new Long(1970), buf, new FieldPosition(0));
- assertEquals("1970", buf.toString());
- assertFalse(format.isGroupingUsed());
- format.format(new Long(1970), buf, new FieldPosition(0));
- assertEquals("19701970", buf.toString());
- assertFalse(format.isGroupingUsed());
-
- format.setGroupingUsed(true);
- format.format(new Long(1970), buf, new FieldPosition(0));
- assertEquals("197019701,970", buf.toString());
- assertTrue(format.isGroupingUsed());
- }
-
- public void test_Constructor() {
- // Test for method java.text.DecimalFormat()
- // the constructor form that specifies a pattern is equal to the form
- // constructed with no pattern and applying that pattern using the
- // applyPattern call
- try {
- DecimalFormat format1 = new DecimalFormat();
- format1.applyPattern("'$'1000.0000");
- DecimalFormat format2 = new DecimalFormat();
- format2.applyPattern("'$'1000.0000");
- assertTrue(
- "Constructed format did not match applied format object",
- format2.equals(format1));
- DecimalFormat format3 = new DecimalFormat("'$'1000.0000");
- assertTrue(
- "Constructed format did not match applied format object",
- format3.equals(format1));
- DecimalFormat format4 = new DecimalFormat("'$'8000.0000");
- assertTrue(
- "Constructed format did not match applied format object",
- !format4.equals(format1));
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.text.DecimalFormat(java.lang.String)
- // the constructor form that specifies a pattern is equal to the form
- // constructed with no pattern and applying that pattern using the
- // applyPattern call
- DecimalFormat format = new DecimalFormat("'$'0000.0000");
- DecimalFormat format1 = new DecimalFormat();
- format1.applyPattern("'$'0000.0000");
- assertTrue("Constructed format did not match applied format object",
- format.equals(format1));
-
- String [] patterns = {"####.##", "######.######", "000000.000000",
- "######.000000", "000000.######", " ###.###", "$#####.######",
- "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)"};
-
- for(String str:patterns) {
- new DecimalFormat(str);
- }
-
- try {
- new DecimalFormat(null);
- fail("NullPointerException wasn't thrown.");
- } catch(NullPointerException npe){
- //expected
- }
-
- String [] incPatterns = {"%#,##,###,####'", "#.##0.00"};
- for(String str:incPatterns) {
- try {
- new DecimalFormat(str);
- fail("IllegalArgumentException wasn't thrown for pattern: " + str);
- } catch(IllegalArgumentException iae){
- //expected
- }
- }
- }
-
- /**
- * Case 1: Try to construct object using correct pattern and fromat symbols.
- * Case 2: Try to construct object using null arguments.
- * Case 3: Try to construct object using incorrect pattern.
- */
- public void test_ConstructorLjava_lang_StringLjava_text_DecimalFormatSymbols() {
- try {
- // case 1: Try to construct object using correct pattern and fromat
- // symbols.
- DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.CANADA);
- DecimalFormat format1 = new DecimalFormat("'$'1000.0000", dfs);
- DecimalFormat format2 = new DecimalFormat();
- format2.applyPattern("'$'1000.0000");
- format2.setDecimalFormatSymbols(dfs);
- assertTrue(
- "Constructed format did not match applied format object",
- format2.equals(format1));
- assertTrue(
- "Constructed format did not match applied format object",
- !format1.equals(new DecimalFormat("'$'1000.0000",
- new DecimalFormatSymbols(Locale.CHINA))));
-
- // case 2: Try to construct object using null arguments.
- try {
- new DecimalFormat("'$'1000.0000", (DecimalFormatSymbols) null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new DecimalFormat(null, new DecimalFormatSymbols());
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new DecimalFormat(null, (DecimalFormatSymbols) null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
-
- // case 3: Try to construct object using incorrect pattern.
- try {
- new DecimalFormat("$'", new DecimalFormatSymbols());
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException e) {
- // expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * Case 1: Try to apply correct variants of pattern.
- * Case 2: Try to apply malformed patten. Case 3: Try to apply null pattern.
- */
- public void test_applyLocalizedPatternLjava_lang_String() {
- DecimalFormat format = new DecimalFormat();
- try {
- // case 1: Try to apply correct variants of pattern.
- format.applyLocalizedPattern("#.#");
- assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern());
- format.applyLocalizedPattern("#.");
- assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern());
- format.applyLocalizedPattern("#");
- assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern());
- format.applyLocalizedPattern(".#");
- assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern());
-
- // case 2: Try to apply malformed patten.
- try {
- format.applyLocalizedPattern("'#,#:#0.0#;(#)");
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- // case 3: Try to apply null patern.
- try {
- format.applyLocalizedPattern((String) null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_applyPatternLjava_lang_String() {
- DecimalFormat format = new DecimalFormat("#.#");
- assertEquals("Wrong pattern 1", "#0.#", format.toPattern());
- format = new DecimalFormat("#.");
- assertEquals("Wrong pattern 2", "#0.", format.toPattern());
- format = new DecimalFormat("#");
- assertEquals("Wrong pattern 3", "#", format.toPattern());
- format = new DecimalFormat(".#");
- assertEquals("Wrong pattern 4", "#.0", format.toPattern());
-
- DecimalFormat decFormat = new DecimalFormat("#.#");
-
- try {
- decFormat.applyPattern(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- String [] incPatterns = {"%#,##,###,####'", "#.##0.00"};
- for(String str:incPatterns) {
- try {
- decFormat.applyPattern(str);
- fail("IllegalArgumentException was not thrown for pattern: " +
- str);
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
- }
-
- // AndroidOnly: icu supports 2 grouping sizes
- public void test_applyPatternLjava_lang_String2() {
- DecimalFormat decFormat = new DecimalFormat("#.#");
- String [] patterns = {"####.##", "######.######", "000000.000000",
- "######.000000", "000000.######", " ###.###", "$#####.######",
- "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)",
- "##.##-E"};
-
- String [] expResult = {"#0.##", "#0.######", "#000000.000000",
- "#.000000", "#000000.######", " #0.###", "$#0.######",
- "$$#0.######",
- "%#,###,####", // icu only. icu supports two grouping sizes
- "#,##0.00;(#,##0.00)",
- "#0.##-'E'"}; // icu only. E in the suffix does not need to be
- // quoted. This is done automatically.
-
- for (int i = 0; i < patterns.length; i++) {
- decFormat.applyPattern(patterns[i]);
- String result = decFormat.toPattern();
- assertEquals("Failed to apply following pattern: " + patterns[i] +
- " expected: " + expResult[i] + " returned: " + result,
- expResult[i], result);
- }
- }
-
- public void test_clone() {
- DecimalFormat format = (DecimalFormat) DecimalFormat
- .getInstance(Locale.US);
- DecimalFormat cloned = (DecimalFormat) format.clone();
- assertEquals(cloned.getDecimalFormatSymbols(), format
- .getDecimalFormatSymbols());
-
- format = new DecimalFormat("'$'0000.0000");
- DecimalFormat format1 = (DecimalFormat) (format.clone());
- // make sure the objects are equal
- assertTrue("Object's clone isn't equal!", format.equals(format1));
- // change the content of the clone and make sure it's not equal anymore
- // verifies that it's data is now distinct from the original
- format1.applyPattern("'$'0000.####");
- assertTrue("Object's changed clone should not be equal!", !format
- .equals(format1));
- }
-
- private void compare(String testName, String format, String expected) {
- assertTrue(testName + " got: " + format + " expected: " + expected,
- format.equals(expected));
- }
-
- private boolean compare(int count, String format, String expected) {
- boolean result = format.equals(expected);
- if (!result)
- System.out.println("Failure test: " + count + " got: " + format
- + " expected: " + expected);
- return result;
- }
-
- public void test_formatDLjava_lang_StringBufferLjava_text_FieldPosition() {
- new Support_DecimalFormat(
- "test_formatDLjava_lang_StringBufferLjava_text_FieldPosition")
- .t_format_with_FieldPosition();
-
- int failCount = 0;
- BitSet failures = new BitSet();
-
- final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
-
- DecimalFormat df = new DecimalFormat("00.0#E0", dfs);
- compare("00.0#E0: 0.0", df.format(0.0), "00.0E0");
- compare("00.0#E0: 1.0", df.format(1.0), "10.0E-1");
- compare("00.0#E0: 12.0", df.format(12.0), "12.0E0");
- compare("00.0#E0: 123.0", df.format(123.0), "12.3E1");
- compare("00.0#E0: 1234.0", df.format(1234.0), "12.34E2");
- compare("00.0#E0: 12346.0", df.format(12346.0), "12.35E3");
- compare("00.0#E0: 99999.0", df.format(99999.0), "10.0E4");
- compare("00.0#E0: 1.2", df.format(1.2), "12.0E-1");
- compare("00.0#E0: 12.3", df.format(12.3), "12.3E0");
- compare("00.0#E0: 123.4", df.format(123.4), "12.34E1");
- compare("00.0#E0: 1234.6", df.format(1234.6), "12.35E2");
- compare("00.0#E0: 9999.9", df.format(9999.9), "10.0E3");
- compare("00.0#E0: 0.1", df.format(0.1), "10.0E-2");
- compare("00.0#E0: 0.12", df.format(0.12), "12.0E-2");
- compare("00.0#E0: 0.123", df.format(0.123), "12.3E-2");
- compare("00.0#E0: 0.1234", df.format(0.1234), "12.34E-2");
- compare("00.0#E0: 0.12346", df.format(0.12346), "12.35E-2");
- compare("00.0#E0: 0.99999", df.format(0.99999), "10.0E-1");
- compare("00.0#E0: -0.0", df.format(-0.0), "-00.0E0");
- compare("00.0#E0: -1.0", df.format(-1.0), "-10.0E-1");
- compare("00.0#E0: -12.0", df.format(-12.0), "-12.0E0");
- compare("00.0#E0: -123.0", df.format(-123.0), "-12.3E1");
- compare("00.0#E0: -1234.0", df.format(-1234.0), "-12.34E2");
- compare("00.0#E0: -12346.0", df.format(-12346.0), "-12.35E3");
- compare("00.0#E0: -99999.0", df.format(-99999.0), "-10.0E4");
-
- df = new DecimalFormat("##0.0E0", dfs);
- compare("##0.0E0: -0.0", df.format(-0.0), "-0.0E0");
- compare("##0.0E0: 0.0", df.format(0.0), "0.0E0");
- compare("##0.0E0: 1.0", df.format(1.0), "1.0E0");
- compare("##0.0E0: 12.0", df.format(12.0), "12E0");
- compare("##0.0E0: 123.0", df.format(123.0), "123E0"); // Android fails, here!
- compare("##0.0E0: 1234.0", df.format(1234.0), "1.234E3");
- compare("##0.0E0: 12346.0", df.format(12346.0), "12.35E3");
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(99999.0), "100E3"))
- failures.set(failCount);
- failCount++;
- compare("##0.0E0: 999999.0", df.format(999999.0), "1.0E6");
-
- df = new DecimalFormat("#00.0##E0", dfs);
- compare("#00.0##E0: 0.1", df.format(0.1), "100E-3");
- compare("#00.0##E0: 0.12", df.format(0.12), "120E-3");
- compare("#00.0##E0: 0.123", df.format(0.123), "123E-3");
- compare("#00.0##E0: 0.1234", df.format(0.1234), "123.4E-3");
- compare("#00.0##E0: 0.1234567", df.format(0.1234567), "123.457E-3");
- compare("#00.0##E0: 0.01", df.format(0.01), "10.0E-3");
- compare("#00.0##E0: 0.012", df.format(0.012), "12.0E-3");
- compare("#00.0##E0: 0.0123", df.format(0.0123), "12.3E-3");
- compare("#00.0##E0: 0.01234", df.format(0.01234), "12.34E-3");
- compare("#00.0##E0: 0.01234567", df.format(0.01234567), "12.3457E-3");
- compare("#00.0##E0: 0.001", df.format(0.001), "1.00E-3");
- compare("#00.0##E0: 0.0012", df.format(0.0012), "1.20E-3");
- compare("#00.0##E0: 0.00123", df.format(0.00123), "1.23E-3");
- compare("#00.0##E0: 0.001234", df.format(0.001234), "1.234E-3");
- compare("#00.0##E0: 0.001234567", df.format(0.001234567), "1.23457E-3");
- compare("#00.0##E0: 0.0001", df.format(0.0001), "100E-6");
- compare("#00.0##E0: 0.00012", df.format(0.00012), "120E-6");
- compare("#00.0##E0: 0.000123", df.format(0.000123), "123E-6");
- compare("#00.0##E0: 0.0001234", df.format(0.0001234), "123.4E-6");
- compare("#00.0##E0: 0.0001234567", df.format(0.0001234567),
- "123.457E-6");
-
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(0.0), "0.00E0"))
- failures.set(failCount);
- failCount++;
- compare("#00.0##E0: 1.0", df.format(1.0), "1.00E0");
- compare("#00.0##E0: 12.0", df.format(12.0), "12.0E0");
- compare("#00.0##E0: 123.0", df.format(123.0), "123E0");
- compare("#00.0##E0: 1234.0", df.format(1234.0), "1.234E3");
- compare("#00.0##E0: 12345.0", df.format(12345.0), "12.345E3");
- compare("#00.0##E0: 123456.0", df.format(123456.0), "123.456E3");
- compare("#00.0##E0: 1234567.0", df.format(1234567.0), "1.23457E6");
- compare("#00.0##E0: 12345678.0", df.format(12345678.0), "12.3457E6");
- compare("#00.0##E0: 99999999.0", df.format(99999999.0), "100E6");
-
- df = new DecimalFormat("#.0E0", dfs);
- compare("#.0E0: -0.0", df.format(-0.0), "-.0E0");
- compare("#.0E0: 0.0", df.format(0.0), ".0E0");
- compare("#.0E0: 1.0", df.format(1.0), ".1E1");
- compare("#.0E0: 12.0", df.format(12.0), ".12E2");
- compare("#.0E0: 123.0", df.format(123.0), ".12E3");
- compare("#.0E0: 1234.0", df.format(1234.0), ".12E4");
- compare("#.0E0: 9999.0", df.format(9999.0), ".1E5");
-
- df = new DecimalFormat("0.#E0", dfs);
- compare("0.#E0: -0.0", df.format(-0.0), "-0E0");
- compare("0.#E0: 0.0", df.format(0.0), "0E0");
- compare("0.#E0: 1.0", df.format(1.0), "1E0");
- compare("0.#E0: 12.0", df.format(12.0), "1.2E1");
- compare("0.#E0: 123.0", df.format(123.0), "1.2E2");
- compare("0.#E0: 1234.0", df.format(1234.0), "1.2E3");
- compare("0.#E0: 9999.0", df.format(9999.0), "1E4");
-
- df = new DecimalFormat(".0E0", dfs);
- compare(".0E0: -0.0", df.format(-0.0), "-.0E0");
- compare(".0E0: 0.0", df.format(0.0), ".0E0");
- compare(".0E0: 1.0", df.format(1.0), ".1E1");
- compare(".0E0: 12.0", df.format(12.0), ".1E2");
- compare(".0E0: 123.0", df.format(123.0), ".1E3");
- compare(".0E0: 1234.0", df.format(1234.0), ".1E4");
- compare(".0E0: 9999.0", df.format(9999.0), ".1E5");
-
- df = new DecimalFormat("0.E0", dfs);
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(0.0), "0.E0"))
- failures.set(failCount);
- failCount++;
- if (!compare(failCount, df.format(1.0), "1.E0"))
- failures.set(failCount);
- failCount++;
- if (!compare(failCount, df.format(12.0), "1.E1"))
- failures.set(failCount);
- failCount++;
- if (!compare(failCount, df.format(123.0), "1.E2"))
- failures.set(failCount);
- failCount++;
- if (!compare(failCount, df.format(1234.0), "1.E3"))
- failures.set(failCount);
- failCount++;
- if (!compare(failCount, df.format(9999.0), "1.E4"))
- failures.set(failCount);
- failCount++;
-
- df = new DecimalFormat("##0.00#E0", dfs);
- compare("##0.00#E0: 0.1", df.format(0.1), "100E-3");
- compare("##0.00#E0: 0.1234567", df.format(0.1234567), "123.457E-3");
- compare("##0.00#E0: 0.9999999", df.format(0.9999999), "1.00E0");
- compare("##0.00#E0: 0.01", df.format(0.01), "10.0E-3");
- compare("##0.00#E0: 0.01234567", df.format(0.01234567), "12.3457E-3");
- compare("##0.00#E0: 0.09999999", df.format(0.09999999), "100E-3");
- compare("##0.00#E0: 0.001", df.format(0.001), "1.00E-3");
- compare("##0.00#E0: 0.001234567", df.format(0.001234567), "1.23457E-3");
- compare("##0.00#E0: 0.009999999", df.format(0.009999999), "10.0E-3");
- compare("##0.00#E0: 0.0001", df.format(0.0001), "100E-6");
- compare("##0.00#E0: 0.0001234567", df.format(0.0001234567),
- "123.457E-6");
- compare("##0.00#E0: 0.0009999999", df.format(0.0009999999), "1.00E-3");
-
- df = new DecimalFormat("###0.00#E0", dfs);
- compare("###0.00#E0: 0.1", df.format(0.1), "1000E-4");
- compare("###0.00#E0: 0.12345678", df.format(0.12345678), "1234.568E-4");
- compare("###0.00#E0: 0.99999999", df.format(0.99999999), "1.00E0");
- compare("###0.00#E0: 0.01", df.format(0.01), "100E-4");
- compare("###0.00#E0: 0.012345678", df.format(0.012345678),
- "123.4568E-4");
- compare("###0.00#E0: 0.099999999", df.format(0.099999999), "1000E-4");
- compare("###0.00#E0: 0.001", df.format(0.001), "10.0E-4");
- compare("###0.00#E0: 0.0012345678", df.format(0.0012345678),
- "12.34568E-4");
- compare("###0.00#E0: 0.0099999999", df.format(0.0099999999), "100E-4");
- compare("###0.00#E0: 0.0001", df.format(0.0001), "1.00E-4");
- compare("###0.00#E0: 0.00012345678", df.format(0.00012345678),
- "1.234568E-4");
- compare("###0.00#E0: 0.00099999999", df.format(0.00099999999),
- "10.0E-4");
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(0.00001), "1000E-8"))
- failures.set(failCount);
- failCount++;
- compare("###0.00#E0: 0.000012345678", df.format(0.000012345678),
- "1234.568E-8");
- compare("###0.00#E0: 0.000099999999", df.format(0.000099999999),
- "1.00E-4");
-
- df = new DecimalFormat("###0.0#E0", dfs);
- compare("###0.0#E0: 0.1", df.format(0.1), "1000E-4");
- compare("###0.0#E0: 0.1234567", df.format(0.1234567), "1234.57E-4");
- compare("###0.0#E0: 0.9999999", df.format(0.9999999), "1.0E0");
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(0.01), "100E-4"))
- failures.set(failCount);
- failCount++;
- compare("###0.0#E0: 0.01234567", df.format(0.01234567), "123.457E-4");
- compare("###0.0#E0: 0.09999999", df.format(0.09999999), "1000E-4");
- compare("###0.0#E0: 0.001", df.format(0.001), "10E-4");
- compare("###0.0#E0: 0.001234567", df.format(0.001234567), "12.3457E-4");
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(0.009999999), "100E-4"))
- failures.set(failCount);
- failCount++;
- compare("###0.0#E0: 0.0001", df.format(0.0001), "1.0E-4");
- compare("###0.0#E0: 0.0001234567", df.format(0.0001234567),
- "1.23457E-4");
- compare("###0.0#E0: 0.0009999999", df.format(0.0009999999), "10E-4");
- // Fails in JDK 1.2.2
- if (!compare(failCount, df.format(0.00001), "1000E-8"))
- failures.set(failCount);
- failCount++;
- compare("###0.0#E0: 0.00001234567", df.format(0.00001234567),
- "1234.57E-8");
- compare("###0.0#E0: 0.00009999999", df.format(0.00009999999), "1.0E-4");
-
- assertTrue("Failed " + failures + " of " + failCount,
- failures.length() == 0);
-
- String formatString = "##0.#";
- df = new DecimalFormat(formatString, dfs);
- df.setMinimumFractionDigits(30);
- compare(formatString + ": 0.000000000000000000000000000000", df
- .format(0.0), "0.000000000000000000000000000000");
- compare(formatString + ": -0.000000000000000000000000000000", df
- .format(-0.0), "-0.000000000000000000000000000000");
- compare(formatString + ": 1.000000000000000000000000000000", df
- .format(1.0), "1.000000000000000000000000000000");
- compare(formatString + ": -1.000000000000000000000000000000", df
- .format(-1.0), "-1.000000000000000000000000000000");
-
- df = new DecimalFormat(formatString);
- df.setMaximumFractionDigits(30);
- compare(formatString + ": 0", df.format(0.0), "0");
- compare(formatString + ": -0", df.format(-0.0), "-0");
- compare(formatString + ": 1", df.format(1.0), "1");
- compare(formatString + ": -1", df.format(-1.0), "-1");
- }
-
- public void test_formatD() {
- DecimalFormat format = (DecimalFormat) NumberFormat
- .getInstance(Locale.ENGLISH);
- format.setGroupingUsed(false);
- format.setMaximumFractionDigits(400);
- assertEquals("123456789012345", format.format(123456789012345.));
- assertEquals("1", "12345678901234.5", format.format(12345678901234.5));
- assertEquals("2", "1234567890123.25", format.format(1234567890123.25));
- assertEquals("3", "999999999999.375", format.format(999999999999.375));
- assertEquals("4", "99999999999.0625", format.format(99999999999.0625));
- assertEquals("5", "9999999999.03125", format.format(9999999999.03125));
- assertEquals("6", "999999999.015625", format.format(999999999.015625));
- assertEquals("7", "99999999.0078125", format.format(99999999.0078125));
- assertEquals("8", "9999999.00390625", format.format(9999999.00390625));
- assertEquals("9", "999999.001953125", format.format(999999.001953125));
- assertEquals("10", "9999.00048828125", format.format(9999.00048828125));
- assertEquals("11", "999.000244140625", format.format(999.000244140625));
- assertEquals("12", "99.0001220703125", format.format(99.0001220703125));
- assertEquals("13", "9.00006103515625", format.format(9.00006103515625));
- assertEquals("14", "0.000030517578125", format.format(0.000030517578125));
- }
-
-
- public void test_getNegativePrefix() {
- DecimalFormat df = new DecimalFormat();
- try {
- df.setNegativePrefix("--");
- assertTrue("Incorrect negative prefix", df.getNegativePrefix()
- .equals("--"));
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_getNegativeSuffix() {
- DecimalFormat df = new DecimalFormat();
- try {
- df.setNegativeSuffix("&");
- assertTrue("Incorrect negative suffix", df.getNegativeSuffix()
- .equals("&"));
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_getPositivePrefix() {
- DecimalFormat df = new DecimalFormat();
- try {
- df.setPositivePrefix("++");
- assertTrue("Incorrect positive prefix", df.getPositivePrefix()
- .equals("++"));
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_getPositiveSuffix() {
- DecimalFormat df = new DecimalFormat();
- try {
- df.setPositiveSuffix("%");
- assertTrue("Incorrect positive prefix", df.getPositiveSuffix()
- .equals("%"));
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_hashCode() {
- try {
- DecimalFormat df1 = new DecimalFormat();
- DecimalFormat df2 = (DecimalFormat) df1.clone();
- assertTrue("Hash codes of equals object are not equal", df2
- .hashCode() == df1.hashCode());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_parseLjava_lang_StringLjava_text_ParsePosition() {
- DecimalFormat format = (DecimalFormat) NumberFormat
- .getNumberInstance(Locale.ENGLISH);
- ParsePosition pos = new ParsePosition(0);
- Number result = format.parse("9223372036854775807", pos);
- assertTrue("Wrong result type for Long.MAX_VALUE",
- result.getClass() == Long.class);
- assertEquals("Wrong result Long.MAX_VALUE",
- Long.MAX_VALUE, result.longValue());
- pos = new ParsePosition(0);
- result = format.parse("-9223372036854775808", pos);
- assertTrue("Wrong result type for Long.MIN_VALUE",
- result.getClass() == Long.class);
- assertTrue("Wrong result Long.MIN_VALUE: " + result.longValue(), result
- .longValue() == Long.MIN_VALUE);
- pos = new ParsePosition(0);
- result = format.parse("9223372036854775808", pos);
- assertTrue("Wrong result type for Long.MAX_VALUE+1",
- result.getClass() == Double.class);
- assertEquals("Wrong result Long.MAX_VALUE + 1",
- (double) Long.MAX_VALUE + 1, result.doubleValue());
- pos = new ParsePosition(0);
- result = format.parse("-9223372036854775809", pos);
- assertTrue("Wrong result type for Long.MIN_VALUE - 1",
- result.getClass() == Double.class);
- assertEquals("Wrong result Long.MIN_VALUE - 1",
- (double) Long.MIN_VALUE - 1, result.doubleValue());
-
- pos = new ParsePosition(0);
- result = format.parse("18446744073709551629", pos);
- assertTrue("Wrong result type for overflow",
- result.getClass() == Double.class);
- assertEquals("Wrong result for overflow",
- 18446744073709551629d, result.doubleValue());
-
- pos = new ParsePosition(0);
- result = format.parse("42325917317067571199", pos);
- assertTrue("Wrong result type for overflow a: " + result, result
- .getClass() == Double.class);
- assertTrue("Wrong result for overflow a: " + result, result
- .doubleValue() == 42325917317067571199d);
- pos = new ParsePosition(0);
- result = format.parse("4232591731706757119E1", pos);
- assertTrue("Wrong result type for overflow b: " + result, result
- .getClass() == Double.class);
- assertEquals("Wrong result for overflow b: " + result,
- 42325917317067571190d, result.doubleValue());
- pos = new ParsePosition(0);
- result = format.parse(".42325917317067571199E20", pos);
- assertTrue("Wrong result type for overflow c: " + result, result
- .getClass() == Double.class);
- assertTrue("Wrong result for overflow c: " + result, result
- .doubleValue() == 42325917317067571199d);
- pos = new ParsePosition(0);
- result = format.parse("922337203685477580.9E1", pos);
- assertTrue("Wrong result type for overflow d: " + result, result
- .getClass() == Double.class);
- assertTrue("Wrong result for overflow d: " + result, result
- .doubleValue() == 9223372036854775809d);
- pos = new ParsePosition(0);
- result = format.parse("9.223372036854775809E18", pos);
- assertTrue("Wrong result type for overflow e: " + result, result
- .getClass() == Double.class);
- assertTrue("Wrong result for overflow e: " + result, result
- .doubleValue() == 9223372036854775809d);
-
- // test parse with multipliers
- format.setMultiplier(100);
- result = format.parse("9223372036854775807", new ParsePosition(0));
- assertEquals("Wrong result type multiplier 100: " + result, Long.class, result.getClass());
- // RI on windows and linux both answer with a slightly rounded result
- assertTrue("Wrong result for multiplier 100: " + result, result
- .longValue() == 92233720368547760L);
- format.setMultiplier(1000);
- result = format.parse("9223372036854775807", new ParsePosition(0));
- assertTrue("Wrong result type multiplier 1000: " + result, result
- .getClass() == Long.class);
- assertTrue("Wrong result for multiplier 1000: " + result, result
- .longValue() == 9223372036854776L);
-
- format.setMultiplier(10000);
- result = format.parse("9223372036854775807", new ParsePosition(0));
- assertTrue("Wrong result type multiplier 10000: " + result, result
- .getClass() == Double.class);
- assertTrue("Wrong result for multiplier 10000: " + result, result
- .doubleValue() == 922337203685477.5807d);
-
- }
-}
diff --git a/luni/src/test/java/libcore/java/text/OldFieldPositionTest.java b/luni/src/test/java/libcore/java/text/OldFieldPositionTest.java
deleted file mode 100644
index b6fbd98..0000000
--- a/luni/src/test/java/libcore/java/text/OldFieldPositionTest.java
+++ /dev/null
@@ -1,79 +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 libcore.java.text;
-
-import java.text.DateFormat;
-import java.text.FieldPosition;
-
-public class OldFieldPositionTest extends junit.framework.TestCase {
-
- public void test_hashCode() {
- // Test for method int java.text.FieldPosition.hashCode()
- FieldPosition fpos1 = new FieldPosition(1);
- FieldPosition fpos2 = new FieldPosition(1);
- assertTrue("test 1: hash codes are not equal for equal objects.",
- fpos1.hashCode() == fpos2.hashCode());
- fpos1.setBeginIndex(5);
- fpos1.setEndIndex(110);
- assertTrue("test 2: hash codes are equal for non equal objects.",
- fpos1.hashCode() != fpos2.hashCode());
- fpos2.setBeginIndex(5);
- fpos2.setEndIndex(110);
- assertTrue("test 3: hash codes are not equal for equal objects.",
- fpos1.hashCode() == fpos2.hashCode());
-
- FieldPosition fpos3 = new FieldPosition(
- DateFormat.Field.DAY_OF_WEEK_IN_MONTH);
-
- assertTrue("test 4: hash codes are equal for non equal objects.",
- fpos2.hashCode() != fpos3.hashCode());
- }
-
- public void test_setBeginIndexI() {
- // Test for method void java.text.FieldPosition.setBeginIndex(int)
- FieldPosition fpos = new FieldPosition(1);
- fpos.setBeginIndex(2);
- fpos.setEndIndex(3);
- assertEquals("beginIndex should have been set to 2", 2, fpos
- .getBeginIndex());
-
- fpos.setBeginIndex(Integer.MAX_VALUE);
- assertEquals("beginIndex should have been set to Integer.MAX_VALUE",
- Integer.MAX_VALUE, fpos.getBeginIndex());
-
- fpos.setBeginIndex(-1);
- assertEquals("beginIndex should have been set to -1",
- -1, fpos.getBeginIndex());
- }
-
- public void test_setEndIndexI() {
- // Test for method void java.text.FieldPosition.setEndIndex(int)
- FieldPosition fpos = new FieldPosition(1);
- fpos.setEndIndex(3);
- fpos.setBeginIndex(2);
- assertEquals("EndIndex should have been set to 3", 3, fpos
- .getEndIndex());
-
- fpos.setEndIndex(Integer.MAX_VALUE);
- assertEquals("endIndex should have been set to Integer.MAX_VALUE",
- Integer.MAX_VALUE, fpos.getEndIndex());
-
- fpos.setEndIndex(-1);
- assertEquals("endIndex should have been set to -1",
- -1, fpos.getEndIndex());
- }
-}
diff --git a/luni/src/test/java/libcore/java/text/OldMessageFormatTest.java b/luni/src/test/java/libcore/java/text/OldMessageFormatTest.java
deleted file mode 100644
index 2701d0e..0000000
--- a/luni/src/test/java/libcore/java/text/OldMessageFormatTest.java
+++ /dev/null
@@ -1,463 +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 libcore.java.text;
-
-import java.text.ChoiceFormat;
-import java.text.DateFormat;
-import java.text.FieldPosition;
-import java.text.Format;
-import java.text.MessageFormat;
-import java.text.NumberFormat;
-import java.text.ParseException;
-import java.text.ParsePosition;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Locale;
-import java.util.TimeZone;
-import junit.framework.TestCase;
-import tests.support.Support_MessageFormat;
-
-public class OldMessageFormatTest extends TestCase {
-
- private MessageFormat format1;
-
- protected void setUp() {
- Locale.setDefault(Locale.US);
-
- // test with repeating formats and max argument index < max offset
- String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}";
- format1 = new MessageFormat(pattern);
- }
-
- public void test_applyPatternLjava_lang_String_AndroidFailure() {
- MessageFormat format = new MessageFormat("test");
- format.setLocale(Locale.FRENCH); // use French since English has the
- // same LONG and FULL time patterns
- format.applyPattern("{0,time, Full}");
- assertEquals("Wrong full time pattern", "{0,time,full}", format
- .toPattern());
- }
-
- public void test_formatToCharacterIteratorLjava_lang_Object() {
- // Test for method formatToCharacterIterator(java.lang.Object)
- new Support_MessageFormat(
- "test_formatToCharacterIteratorLjava_lang_Object")
- .t_formatToCharacterIterator();
-
- try {
- new MessageFormat("{1, number}").formatToCharacterIterator(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- new MessageFormat("{0, time}").formatToCharacterIterator(new Object[]{""});
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- public void test_getLocale() {
- try {
- Locale[] l = {
- Locale.FRANCE,
- Locale.KOREA,
- new Locale(Locale.FRANCE.getCountry(), Locale.FRANCE
- .getLanguage()), new Locale("mk"),
- new Locale("mk", "MK"), Locale.US,
- new Locale("#ru", "@31230") };
-
- String pattern = "getLocale test {0,number,#,####}";
- MessageFormat mf;
-
- for (int i = 0; i < 0; i++) {
- mf = new MessageFormat(pattern, l[i]);
- Locale result = mf.getLocale();
- assertEquals("Returned local: " + result + " instead of "
- + l[i], l[i], result);
- assertEquals("Returned language: " + result.getLanguage()
- + " instead of " + l[i].getLanguage(), l[i]
- .getLanguage(), result.getLanguage());
- assertEquals("Returned country: " + result.getCountry()
- + " instead of " + l[i].getCountry(),
- l[i].getCountry(), result.getCountry());
- }
-
- mf = new MessageFormat(pattern);
- mf.setLocale(null);
- Locale result = mf.getLocale();
- assertEquals("Returned local: " + result + " instead of null",
- null, result);
- } catch (Exception e) {
- fail("unexpected exception " + e.toString());
- }
- }
-
- /**
- * java.text.MessageFormat#setFormat(int, Format) Test of method
- * java.text.MessageFormat#setFormat(int, Format). Case 1: Compare
- * getFormats() results after calls to setFormat(). Case 2: Try to
- * call setFormat() using incorrect index.
- */
- public void test_setFormatILjava_text_Format() {
- try {
- // case 1: Compare getFormats() results after calls to setFormat()
- MessageFormat f1 = (MessageFormat) format1.clone();
- f1.setFormat(0, DateFormat.getTimeInstance());
- f1.setFormat(1, DateFormat.getTimeInstance());
- f1.setFormat(2, NumberFormat.getInstance());
- f1.setFormat(3, new ChoiceFormat("0#off|1#on"));
- f1.setFormat(4, new ChoiceFormat("1#few|2#ok|3#a lot"));
- f1.setFormat(5, DateFormat.getTimeInstance());
-
- Format[] formats = f1.getFormats();
- formats = f1.getFormats();
-
- Format[] correctFormats = new Format[] {
- DateFormat.getTimeInstance(), DateFormat.getTimeInstance(),
- NumberFormat.getInstance(), new ChoiceFormat("0#off|1#on"),
- new ChoiceFormat("1#few|2#ok|3#a lot"),
- DateFormat.getTimeInstance() };
-
- assertEquals("Test1A:Returned wrong number of formats:",
- correctFormats.length, formats.length);
- for (int i = 0; i < correctFormats.length; i++) {
- assertEquals(
- "Test1B:wrong format for pattern index " + i + ":",
- correctFormats[i], formats[i]);
- }
-
- // case 2: Try to setFormat using incorrect index
- try {
- f1.setFormat(-1, DateFormat.getDateInstance());
- fail("Expected ArrayIndexOutOfBoundsException was not thrown");
- f1.setFormat(f1.getFormats().length, DateFormat
- .getDateInstance());
- fail("Expected ArrayIndexOutOfBoundsException was not thrown");
- } catch (ArrayIndexOutOfBoundsException e) {
- // expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_format$Ljava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
- // Test for method java.lang.StringBuffer
- // java.text.MessageFormat.format(java.lang.Object [],
- // java.lang.StringBuffer, java.text.FieldPosition)
- MessageFormat format = new MessageFormat("{1,number,integer}");
- StringBuffer buffer = new StringBuffer();
- format.format(new Object[] { "0", new Double(53.863) }, buffer,
- new FieldPosition(MessageFormat.Field.ARGUMENT));
- assertEquals("Wrong result", "54", buffer.toString());
-
- format.format(new Object[] { "0", new Double(53.863) }, buffer,
- new FieldPosition(MessageFormat.Field.ARGUMENT));
-
- assertEquals("Wrong result", "5454", buffer.toString());
-
- buffer = new StringBuffer();
- format
- .applyPattern("{0,choice,0#zero|1#one '{1,choice,2#two {2,time}}'}");
- Date date = new Date();
- String expected = "one two "
- + DateFormat.getTimeInstance().format(date);
- format.format(new Object[] { new Double(1.6),
- new Integer(3), date }, buffer, new FieldPosition(MessageFormat
- .Field.ARGUMENT));
- assertEquals("Choice not recursive:\n" + expected + "\n" + buffer,
- expected, buffer.toString());
-
- StringBuffer str = format.format(new Object[] { new Double(0.6),
- new Integer(3)}, buffer, null);
-
- assertEquals(expected + "zero", str.toString());
- assertEquals(expected + "zero", buffer.toString());
-
- try {
- format.format(new Object[] { "0", new Double(1), "" }, buffer,
- new FieldPosition(MessageFormat.Field.ARGUMENT));
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- format.format(new Object[] { "", new Integer(3)}, buffer,
- new FieldPosition(MessageFormat.Field.ARGUMENT));
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- public void test_formatLjava_lang_StringLjava_lang_Object() {
- TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
- int iCurrency = 123;
- int iInteger = Integer.MIN_VALUE;
-
- Date date = new Date(12345678);
- Object[] args = { date, iCurrency, iInteger };
- String resStr = "Date: Jan 1, 1970 Currency: $" + iCurrency
- + ".00 Integer: -2,147,483,648";
- String pattern = "Date: {0,date} Currency: {1, number, currency} Integer: {2, number, integer}";
- String sFormat = MessageFormat.format(pattern, (Object[]) args);
- assertEquals(
- "format(String, Object[]) with valid parameters returns incorrect string: case 1",
- sFormat, resStr);
-
- pattern = "abc {4, number, integer} def {3,date} ghi {2,number} jkl {1,choice,0#low|1#high} mnop {0}";
- resStr = "abc -2,147,483,648 def Jan 1, 1970 ghi -2,147,483,648 jkl high mnop -2,147,483,648";
- Object[] args_ = { iInteger, 1, iInteger, date, iInteger };
- sFormat = MessageFormat.format(pattern, args_);
- assertEquals(
- "format(String, Object[]) with valid parameters returns incorrect string: case 1",
- sFormat, resStr);
-
- try {
- args = null;
- MessageFormat.format(null, args);
- fail("Doesn't throw IllegalArgumentException: null, null");
- } catch (Exception e) {
- // expected
- }
-
- try {
- MessageFormat.format("Invalid {1,foobar} format descriptor!",
- new Object[] {iInteger} );
- fail("Doesn't throw IllegalArgumentException with invalid pattern as a parameter: case 1");
- } catch (IllegalArgumentException ex) {
- // expected
- }
-
- try {
- MessageFormat.format(
- "Invalid {1,date,invalid-spec} format descriptor!", new Object[]{""});
- fail("Doesn't throw IllegalArgumentException with invalid pattern as a parameter: case 2");
- } catch (IllegalArgumentException ex) {
- // expected
- }
-
- try {
- MessageFormat.format("{0,number,integer", new Object[] {iInteger});
- fail("Doesn't throw IllegalArgumentException, doesn't detect unmatched brackets");
- } catch (IllegalArgumentException ex) {
- // expected
- }
-
- try {
- MessageFormat.format(
- "Valid {1, date} format {0, number} descriptor!", new Object[]{ "" } );
- fail("Doesn't throw IllegalArgumentException with invalid Object array");
- } catch (IllegalArgumentException ex) {
- // expected
- }
- }
-
- public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
- // Test for method java.lang.StringBuffer
- // java.text.MessageFormat.format(java.lang.Object,
- // java.lang.StringBuffer, java.text.FieldPosition)
- new Support_MessageFormat(
- "test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition")
- .t_format_with_FieldPosition();
-
- String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} " +
- "hamburger{2,choice,1#|1<s}.";
- MessageFormat format = new MessageFormat(pattern, Locale.US);
-
- Object[] objects = new Object[] { "", new Integer(3), 8, ""};
-
- try {
- format.format(objects, new StringBuffer(),
- new FieldPosition(DateFormat.Field.AM_PM));
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- public void test_setFormats$Ljava_text_Format() {
- try {
- MessageFormat f1 = (MessageFormat) format1.clone();
-
- // case 1: Test with repeating formats and max argument index < max
- // offset
- // compare getFormats() results after calls to setFormats(Format[])
- Format[] correctFormats = new Format[] {
- DateFormat.getTimeInstance(),
- new ChoiceFormat("0#off|1#on"),
- DateFormat.getTimeInstance(),
- NumberFormat.getCurrencyInstance(),
- new ChoiceFormat("1#few|2#ok|3#a lot") };
-
- f1.setFormats(correctFormats);
- Format[] formats = f1.getFormats();
-
- assertTrue("Test1A:Returned wrong number of formats:",
- correctFormats.length <= formats.length);
- for (int i = 0; i < correctFormats.length; i++) {
- assertEquals("Test1B:wrong format for argument index " + i
- + ":", correctFormats[i], formats[i]);
- }
-
- // case 2: Try to pass null argument to setFormats().
- try {
- f1.setFormats(null);
- fail("Expected exception NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_parseLjava_lang_String() throws ParseException {
- String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4} E {1,choice,0#off|1#on} F {0, date}";
- MessageFormat mf = new MessageFormat(pattern);
- String sToParse = "A $12,345.00 B 9:56:07 AM C 3,200% D 1/15/70 9:56 AM E on F Jan 1, 1970";
- Object[] result;
- try {
- result = mf.parse(sToParse);
-
- assertTrue("No result: " + result.length, result.length == 5);
- assertTrue("Object 0 is not date", result[0] instanceof Date);
- assertEquals("Object 1 is not stringr", result[1].toString(), "1.0");
- assertTrue("Object 2 is not date", result[2] instanceof Date);
- assertEquals("Object 3 is not number", result[3].toString(),
- "12345");
- assertEquals("Object 4 is not string", result[4].toString(),
- "1/15/70 9:56 AM");
-
- } catch (java.text.ParseException pe) {
- fail("ParseException is thrown for incorrect string " + sToParse);
- }
-
- sToParse = "xxdate is Feb 28, 1999";
- try {
- result = format1.parse(sToParse);
- fail("ParseException is thrown for incorrect string " + sToParse);
- } catch (java.text.ParseException pe) {
- // expected
- }
-
- sToParse = "vm=Test, @3 4 6, 3 ";
- mf = new MessageFormat("vm={0},{1},{2}");
- try {
- result = mf.parse(sToParse);
- assertTrue("No result: " + result.length, result.length == 3);
- assertEquals("Object 0 is not string", result[0].toString(), "Test");
- assertEquals("Object 1 is not string", result[1].toString(),
- " @3 4 6");
- assertEquals("Object 2 is not string", result[2].toString(),
- " 3 ");
- } catch (java.text.ParseException pe) {
- fail("ParseException is thrown for correct string " + sToParse);
- }
-
- try {
- result = mf.parse(null);
- fail("ParseException is not thrown for null " + sToParse);
- } catch (java.text.ParseException pe) {
- // expected
- }
- }
-
- /**
- * java.text.MessageFormat#parseObject(java.lang.String,
- * java.text.ParsePosition) Test of method
- * java.text.MessageFormat#parseObject(java.lang.String,
- * java.text.ParsePosition). Case 1: Parsing of correct data string.
- * Case 2: Parsing of partial correct data string. Case 3: Try to use
- * argument ParsePosition as null.
- */
- public void test_parseObjectLjava_lang_StringLjavajava_text_ParsePosition() {
- MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
- try {
- // case 1: Try to parse correct data string.
- Object[] objs = { new Double(3.1415) };
- String result = mf.format(objs);
- // result now equals "3.14, 3.1"
- Object[] res = null;
- ParsePosition pp = new ParsePosition(0);
- int parseIndex = pp.getIndex();
- res = (Object[]) mf.parseObject(result, pp);
- assertTrue("Parse operation return null", res != null);
- assertTrue("parse operation return array with incorrect length",
- 1 == res.length);
- assertTrue("ParseIndex is incorrect", pp.getIndex() != parseIndex);
- assertTrue("Result object is incorrect", new Double(3.1)
- .equals(res[0]));
-
- // case 2: Try to parse partially correct data string.
- pp.setIndex(0);
- char[] cur = result.toCharArray();
- cur[cur.length / 2] = 'Z';
- String partialCorrect = new String(cur);
- res = (Object[]) mf.parseObject(partialCorrect, pp);
- assertTrue("Parse operation return null", res == null);
- assertTrue("ParseIndex is incorrect", pp.getIndex() == 0);
- assertTrue("ParseErrorIndex is incorrect",
- pp.getErrorIndex() == cur.length / 2);
-
- // case 3: Try to use argument ParsePosition as null.
- try {
- mf.parseObject(result, null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- public void test_format_Object() {
- // Regression for HARMONY-1875
- Locale.setDefault(Locale.CANADA);
- TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
- String pat = "text here {0,date,yyyyyyyyy} and here";
- Calendar c = Calendar.getInstance();
- String etalon = "text here 00000" + c.get(Calendar.YEAR) + " and here";
- MessageFormat obj = new MessageFormat(pat);
- assertEquals(etalon, obj.format(new Object[] { new Date() }));
- }
-
- public void test_parseLjava_lang_StringLjava_text_ParsePosition() {
- ParsePosition pos = new ParsePosition(2);
-
- MessageFormat mf = new MessageFormat("{0}; {0}; {0}");
- String parse = "a; b; c";
- try {
- mf.parse(parse, null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- mf.parse(null, pos);
- } catch(NullPointerException npe) {
- fail("NullPointerException was thrown.");
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java b/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java
index b7ae098..d281a91 100644
--- a/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java
@@ -16,7 +16,6 @@
*/
package libcore.java.text;
-import dalvik.annotation.BrokenTest;
import java.text.ChoiceFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
@@ -50,10 +49,14 @@ public class OldNumberFormatTest extends TestCase {
Locale arLocale = new Locale("ar", "AE");
format = (DecimalFormat) NumberFormat.getIntegerInstance(arLocale);
- assertEquals("#0;#0-", format.toPattern());
- assertEquals("\u0666-", format.format(-6));
- assertEquals(new Long(-36), format.parse("36-"));
- assertEquals(new Long(-36), format.parseObject("36-"));
+ assertEquals("#,##0", format.toPattern());
+ assertEquals("\u0666\u0667", format.format(67));
+
+ assertEquals("\u200f-\u0666", format.format(-6));
+ assertEquals(-36L, format.parse("-36"));
+
+ // New Arabic formats do not support '-' to right of digits.
+ assertEquals(36L, format.parseObject("36-"));
assertEquals(0, format.getMaximumFractionDigits());
assertTrue(format.isParseIntegerOnly());
}
@@ -729,7 +732,7 @@ public class OldNumberFormatTest extends TestCase {
+ " instead of Integer.MIN_VALUE", result == 0);
}
- @BrokenTest("Fails in CTS, passes in CoreTestRunner")
+ // Broken Test: Fails in CTS, passes in CoreTestRunner
public void test_parseLjava_lang_String() {
NumberFormat nf1 = NumberFormat.getInstance();
try {
diff --git a/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java
deleted file mode 100644
index 1cc7554..0000000
--- a/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java
+++ /dev/null
@@ -1,539 +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 libcore.java.text;
-
-import java.text.DateFormat;
-import java.text.DateFormatSymbols;
-import java.text.FieldPosition;
-import java.text.ParsePosition;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.SimpleTimeZone;
-import java.util.TimeZone;
-
-public class OldSimpleDateFormatTest extends junit.framework.TestCase {
-
- SimpleDateFormat format = null;
- SimpleDateFormat pFormat = null;
-
- @Override
- protected void setUp() throws Exception {
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
- format = new SimpleDateFormat("", Locale.ENGLISH);
- pFormat = new SimpleDateFormat("", Locale.ENGLISH);
- }
-
- @Override
- protected void tearDown() throws Exception {
- format = null;
- pFormat = null;
- }
-
- class FormatTester {
- boolean testsFailed = false;
-
- public void test(String pattern, Calendar cal, String expected, int field) {
- StringBuffer buffer = new StringBuffer();
- FieldPosition position = new FieldPosition(field);
- format.applyPattern(pattern);
- format.format(cal.getTime(), buffer, position);
- String result = buffer.toString();
- if (!result.equals(expected)) {
- System.out.println("Wrong format: \"" + pattern
- + "\" expected: " + expected + " result: "
- + result);
- testsFailed = true;
- }
- }
-
- public void parse(String pattern, String input, Date expected, int start, int end) {
- pFormat.applyPattern(pattern);
- ParsePosition position = new ParsePosition(start);
- Date result = pFormat.parse(input, position);
- assertTrue("Wrong result: " + pattern + " input: " + input
- + " expected: " + expected + " result: " + result, expected
- .equals(result));
- assertTrue("Wrong end position: " + pattern + " input: " + input,
- position.getIndex() == end);
- }
-
- public void verifyFormatTimezone(String timeZoneId, String expected1,
- String expected2, Date date) {
- format.setTimeZone(SimpleTimeZone.getTimeZone(timeZoneId));
- format.applyPattern("z, zzzz");
- assertEquals("Test z for TimeZone : " + timeZoneId, expected1,
- format.format(date));
-
- format.applyPattern("Z, ZZZZ");
- assertEquals("Test Z for TimeZone : " + timeZoneId, expected2,
- format.format(date));
- }
- }
-
- /**
- * java.text.SimpleDateFormat#SimpleDateFormat(java.lang.String,
- * java.text.DateFormatSymbols)
- */
- public void test_ConstructorLjava_lang_StringLjava_text_DateFormatSymbols() {
- // Test for method java.text.SimpleDateFormat(java.lang.String,
- // java.text.DateFormatSymbols)
- DateFormatSymbols symbols = new DateFormatSymbols(Locale.ENGLISH);
- symbols.setEras(new String[] { "Before", "After" });
- SimpleDateFormat f2 = new SimpleDateFormat("y'y'yy", symbols);
- assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
- assertEquals("Wrong pattern", "y'y'yy", f2.toPattern());
- assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(symbols));
- assertTrue("Doesn't work",
- f2.format(new Date()).getClass() == String.class);
-
- try {
- new SimpleDateFormat(null, symbols);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- new SimpleDateFormat("eee", symbols);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- public void test_ConstructorLjava_lang_StringLjava_util_Locale() {
- // Test for method java.text.SimpleDateFormat(java.lang.String,
- // java.util.Locale)
- SimpleDateFormat f2 = new SimpleDateFormat("'yyyy' MM yy",
- Locale.GERMAN);
- assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
- assertEquals("Wrong pattern", "'yyyy' MM yy", f2.toPattern());
- assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
- new DateFormatSymbols(Locale.GERMAN)));
- assertTrue("Doesn't work",
- f2.format(new Date()).getClass() == String.class);
-
- try {
- new SimpleDateFormat(null, Locale.GERMAN);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- try {
- new SimpleDateFormat("eee", Locale.GERMAN);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- public void test_applyLocalizedPatternLjava_lang_String() {
- // Test for method void
- // java.text.SimpleDateFormat.applyLocalizedPattern(java.lang.String)
- SimpleDateFormat f2 = new SimpleDateFormat("y", new Locale("de", "CH"));
- // BEGIN android-removed
- // This test doesn't work like this. The cause lies inside of icu
- // that doesn't support localized pattern characters anymore. So this
- // test fails because the pattern template contains characters that are
- // not part of the standard pattern returned for every locale.
- // The default pattern characters are: GyMdkHmsSEDFwWahKzZ
- //
- // f2.applyLocalizedPattern("GuMtkHmsSEDFwWahKz");
- // String pattern = f2.toPattern();
- // assertTrue("Wrong pattern: " + pattern, pattern
- // .equals("GyMdkHmsSEDFwWahKz"));
- //
- // test the new "Z" pattern char
- // f2 = new SimpleDateFormat("y", new Locale("de", "CH"));
- // f2.applyLocalizedPattern("G u M t Z");
- // pattern = f2.toPattern();
- // assertTrue("Wrong pattern: " + pattern, pattern.equals("G y M d Z"));
- // END android-removed
-
- // test invalid patterns
- try {
- f2.applyLocalizedPattern("b");
- fail("Expected IllegalArgumentException for pattern with invalid pattern letter: b");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- // ICU only! this fails on the RI
- f2.applyLocalizedPattern("u");
- fail("Expected IllegalArgumentException for pattern with invalid pattern letter: u");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- f2.applyLocalizedPattern("a '");
- fail("Expected IllegalArgumentException for pattern with unterminated quote: a '");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- f2.applyLocalizedPattern(null);
- fail("Expected NullPointerException for null pattern");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * java.text.SimpleDateFormat#applyPattern(java.lang.String)
- */
- public void test_applyPatternLjava_lang_String() {
- // Test for method void
- // java.text.SimpleDateFormat.applyPattern(java.lang.String)
- SimpleDateFormat f2 = new SimpleDateFormat("y", new Locale("de", "CH"));
- // BEGIN android-changed
- f2.applyPattern("GyMdkHmsSEDFwWahKzZ");
- assertEquals("Wrong pattern", "GyMdkHmsSEDFwWahKzZ", f2.toPattern());
- // END android-changed
-
- // test invalid patterns
- try {
- f2.applyPattern("u");
- fail("Expected IllegalArgumentException for pattern with invalid patter letter: u");
- } catch (IllegalArgumentException e) {
- }
- }
-
- public void test_hashCode() {
- SimpleDateFormat format = (SimpleDateFormat) DateFormat.getInstance();
- SimpleDateFormat clone = (SimpleDateFormat) format.clone();
- assertTrue("clone has not equal hash code", clone.hashCode() == format
- .hashCode());
- format.format(new Date());
- assertTrue("clone has not equal hash code after format", clone
- .hashCode() == format.hashCode());
- DateFormatSymbols symbols = new DateFormatSymbols(Locale.ENGLISH);
- symbols.setEras(new String[] { "Before", "After" });
- SimpleDateFormat format2 = new SimpleDateFormat("y'y'yy", symbols);
- assertFalse("objects has equal hash code", format2.hashCode() == format
- .hashCode());
- }
-
- public void test_formatLjava_util_DateLjava_lang_StringBufferLjava_text_FieldPosition() {
- FormatTester test = new FormatTester();
-
- Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
- test.test(" G", cal, " AD", DateFormat.ERA_FIELD);
- test.test(" GG", cal, " AD", DateFormat.ERA_FIELD);
- test.test(" GGG", cal, " AD", DateFormat.ERA_FIELD);
- test.test(" G", new GregorianCalendar(-1999, Calendar.JUNE, 2), " BC",
- DateFormat.ERA_FIELD);
-
- test.test(" M", cal, " 6", DateFormat.MONTH_FIELD);
- test.test(" M", new GregorianCalendar(1999, Calendar.NOVEMBER, 2),
- " 11", DateFormat.MONTH_FIELD);
- test.test(" MM", cal, " 06", DateFormat.MONTH_FIELD);
- test.test(" MMM", cal, " Jun", DateFormat.MONTH_FIELD);
- test.test(" MMMM", cal, " June", DateFormat.MONTH_FIELD);
- test.test(" MMMMM", cal, " J", DateFormat.MONTH_FIELD);
-
- test.test(" d", cal, " 2", DateFormat.DATE_FIELD);
- test.test(" d", new GregorianCalendar(1999, Calendar.NOVEMBER, 12),
- " 12", DateFormat.DATE_FIELD);
- test.test(" dd", cal, " 02", DateFormat.DATE_FIELD);
- test.test(" dddd", cal, " 0002", DateFormat.DATE_FIELD);
-
- test.test(" h", cal, " 3", DateFormat.HOUR1_FIELD);
- test.test(" h", new GregorianCalendar(1999, Calendar.NOVEMBER, 12),
- " 12", DateFormat.HOUR1_FIELD);
- test.test(" hh", cal, " 03", DateFormat.HOUR1_FIELD);
- test.test(" hhhh", cal, " 0003", DateFormat.HOUR1_FIELD);
-
- test.test(" H", cal, " 15", DateFormat.HOUR_OF_DAY0_FIELD);
- test.test(" H",
- new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 0), " 4",
- DateFormat.HOUR_OF_DAY0_FIELD);
- test.test(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 12,
- 0), " 12", DateFormat.HOUR_OF_DAY0_FIELD);
- test.test(" H", new GregorianCalendar(1999, Calendar.NOVEMBER, 12),
- " 0", DateFormat.HOUR_OF_DAY0_FIELD);
- test.test(" HH", cal, " 15", DateFormat.HOUR_OF_DAY0_FIELD);
- test.test(" HHHH", cal, " 0015", DateFormat.HOUR_OF_DAY0_FIELD);
-
- test.test(" m", cal, " 3", DateFormat.MINUTE_FIELD);
- test.test(" m", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4,
- 47), " 47", DateFormat.MINUTE_FIELD);
- test.test(" mm", cal, " 03", DateFormat.MINUTE_FIELD);
- test.test(" mmmm", cal, " 0003", DateFormat.MINUTE_FIELD);
-
- test.test(" s", cal, " 6", DateFormat.SECOND_FIELD);
- test.test(" s", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4,
- 47, 13), " 13", DateFormat.SECOND_FIELD);
- test.test(" ss", cal, " 06", DateFormat.SECOND_FIELD);
- test.test(" ssss", cal, " 0006", DateFormat.SECOND_FIELD);
-
- test.test(" S", cal, " 0", DateFormat.MILLISECOND_FIELD);
- Calendar temp = new GregorianCalendar();
- temp.set(Calendar.MILLISECOND, 961);
-
- test.test(" SS", temp, " 961", DateFormat.MILLISECOND_FIELD);
- test.test(" SSSS", cal, " 0000", DateFormat.MILLISECOND_FIELD);
-
- test.test(" SS", cal, " 00", DateFormat.MILLISECOND_FIELD);
-
- test.test(" E", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD);
- test.test(" EE", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD);
- test.test(" EEE", cal, " Wed", DateFormat.DAY_OF_WEEK_FIELD);
- test.test(" EEEE", cal, " Wednesday", DateFormat.DAY_OF_WEEK_FIELD);
- test.test(" EEEEE", cal, " W", DateFormat.DAY_OF_WEEK_FIELD);
-
- test.test(" D", cal, " 153", DateFormat.DAY_OF_YEAR_FIELD);
- test.test(" DD", cal, " 153", DateFormat.DAY_OF_YEAR_FIELD);
- test.test(" DDDD", cal, " 0153", DateFormat.DAY_OF_YEAR_FIELD);
-
- test.test(" F", cal, " 1", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
- test.test(" F", new GregorianCalendar(1999, Calendar.NOVEMBER, 14),
- " 2", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
- test.test(" FF", cal, " 01", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
- test.test(" FFFF", cal, " 0001", DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD);
-
- test.test(" a", cal, " PM", DateFormat.AM_PM_FIELD);
- test.test(" a", new GregorianCalendar(1999, Calendar.NOVEMBER, 14),
- " AM", DateFormat.AM_PM_FIELD);
- test.test(" a", new GregorianCalendar(1999, Calendar.NOVEMBER, 14, 12,
- 0), " PM", DateFormat.AM_PM_FIELD);
- test.test(" aa", cal, " PM", DateFormat.AM_PM_FIELD);
- test.test(" aaa", cal, " PM", DateFormat.AM_PM_FIELD);
- test.test(" aaaa", cal, " PM", DateFormat.AM_PM_FIELD);
- test.test(" aaaaa", cal, " PM", DateFormat.AM_PM_FIELD);
-
- test.test(" k", cal, " 15", DateFormat.HOUR_OF_DAY1_FIELD);
- test.test(" k",
- new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 4, 0), " 4",
- DateFormat.HOUR_OF_DAY1_FIELD);
- test.test(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12, 12,
- 0), " 12", DateFormat.HOUR_OF_DAY1_FIELD);
- test.test(" k", new GregorianCalendar(1999, Calendar.NOVEMBER, 12),
- " 24", DateFormat.HOUR_OF_DAY1_FIELD);
- test.test(" kk", cal, " 15", DateFormat.HOUR_OF_DAY1_FIELD);
- test.test(" kkkk", cal, " 0015", DateFormat.HOUR_OF_DAY1_FIELD);
-
- test.test(" K", cal, " 3", DateFormat.HOUR0_FIELD);
- test.test(" K", new GregorianCalendar(1999, Calendar.NOVEMBER, 12),
- " 0", DateFormat.HOUR0_FIELD);
- test.test(" KK", cal, " 03", DateFormat.HOUR0_FIELD);
- test.test(" KKKK", cal, " 0003", DateFormat.HOUR0_FIELD);
-
- format.applyPattern("'Mkz''':.@5");
- assertEquals("Wrong output", "Mkz':.@5", format.format(new Date()));
-
- //assertTrue("Tests failed", !test.testsFailed());
-
- // Test invalid args to format.
- SimpleDateFormat dateFormat = new SimpleDateFormat();
- try {
- dateFormat.format(null, new StringBuffer(), new FieldPosition(1));
- fail("Expected test to throw NPE.");
- } catch (NullPointerException ex) {
- // expected
- } catch (Throwable ex) {
- fail("Expected test to throw NPE, not " + ex.getClass().getName());
- }
-
- assertFalse(test.testsFailed);
- }
-
- /**
- * This test assumes Unicode behavior where 'y' and 'yyy' don't truncate,
- * which means that it will fail on the RI.
- */
- public void testFormattingYear() {
- FormatTester test = new FormatTester();
-
- Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
- test.test(" y", cal, " 1999", DateFormat.YEAR_FIELD);
- test.test(" yy", cal, " 99", DateFormat.YEAR_FIELD);
- test.test(" yy", new GregorianCalendar(2001, Calendar.JUNE, 2), " 01",
- DateFormat.YEAR_FIELD);
- test.test(" yy", new GregorianCalendar(2000, Calendar.JUNE, 2), " 00",
- DateFormat.YEAR_FIELD);
- test.test(" yyy", new GregorianCalendar(2000, Calendar.JUNE, 2), " 2000",
- DateFormat.YEAR_FIELD);
- test.test(" yyy", cal, " 1999", DateFormat.YEAR_FIELD);
- test.test(" yyyy", cal, " 1999", DateFormat.YEAR_FIELD);
- test.test(" yyyyy", cal, " 01999", DateFormat.YEAR_FIELD);
-
- assertFalse(test.testsFailed);
- }
-
- public void testFormattingWeekOfYear() {
- FormatTester test = new FormatTester();
- Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
- cal.setMinimalDaysInFirstWeek(1);
- cal.setFirstDayOfWeek(1);
-
- test.test(" w", cal, " 23", DateFormat.WEEK_OF_YEAR_FIELD);
- test.test(" ww", cal, " 23", DateFormat.WEEK_OF_YEAR_FIELD);
- test.test(" wwww", cal, " 0023", DateFormat.WEEK_OF_YEAR_FIELD);
-
- test.test(" W", cal, " 1", DateFormat.WEEK_OF_MONTH_FIELD);
- test.test(" W", new GregorianCalendar(1999, Calendar.NOVEMBER, 14),
- " 3", DateFormat.WEEK_OF_MONTH_FIELD);
- test.test(" WW", cal, " 01", DateFormat.WEEK_OF_MONTH_FIELD);
- test.test(" WWWW", cal, " 0001", DateFormat.WEEK_OF_MONTH_FIELD);
-
- assertFalse(test.testsFailed);
- }
-
- public void testFormattingTimezones() {
- FormatTester test = new FormatTester();
- Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
-
- TimeZone tz0001 = new SimpleTimeZone(60000, "ONE MINUTE");
- TimeZone tz0130 = new SimpleTimeZone(5400000, "ONE HOUR, THIRTY");
- TimeZone tzMinus0130 = new SimpleTimeZone(-5400000, "NEG ONE HOUR, THIRTY");
-
- format.setTimeZone(tz0001);
- test.test(" Z", cal, " +0001", DateFormat.TIMEZONE_FIELD);
- test.test(" ZZZZ", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
- test.test(" ZZZZZ", cal, " +00:01", DateFormat.TIMEZONE_FIELD);
- format.setTimeZone(tz0130);
- test.test(" Z", cal, " +0130", DateFormat.TIMEZONE_FIELD);
- format.setTimeZone(tzMinus0130);
- test.test(" Z", cal, " -0130", DateFormat.TIMEZONE_FIELD);
-
- format.setTimeZone(tz0001);
- test.test(" z", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
- test.test(" zzzz", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
- format.setTimeZone(tz0130);
- test.test(" z", cal, " GMT+01:30", DateFormat.TIMEZONE_FIELD);
- format.setTimeZone(tzMinus0130);
- test.test(" z", cal, " GMT-01:30", DateFormat.TIMEZONE_FIELD);
-
- format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
- test.test(" z", cal, " EDT", DateFormat.TIMEZONE_FIELD);
- Calendar temp2 = new GregorianCalendar(1999, Calendar.JANUARY, 12);
- test.test(" z", temp2, " EST", DateFormat.TIMEZONE_FIELD);
- test.test(" zz", cal, " EDT", DateFormat.TIMEZONE_FIELD);
- test.test(" zzz", cal, " EDT", DateFormat.TIMEZONE_FIELD);
- test.test(" zzzz", cal, " Eastern Daylight Time", DateFormat.TIMEZONE_FIELD);
- test.test(" zzzz", temp2, " Eastern Standard Time", DateFormat.TIMEZONE_FIELD);
- test.test(" zzzzz", cal, " Eastern Daylight Time", DateFormat.TIMEZONE_FIELD);
-
- assertFalse(test.testsFailed);
- }
-
- /**
- * java.text.SimpleDateFormat#format(java.util.Date)
- */
- public void test_timeZoneFormatting() {
- // tests specific to formatting of timezones
- Date summerDate = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6).getTime();
- Date winterDate = new GregorianCalendar(1999, Calendar.JANUARY, 12).getTime();
-
- FormatTester test = new FormatTester();
- test.verifyFormatTimezone("GMT-7", "GMT-07:00, GMT-07:00", "-0700, GMT-07:00", summerDate);
- test.verifyFormatTimezone("GMT-7", "GMT-07:00, GMT-07:00", "-0700, GMT-07:00", winterDate);
-
- test.verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", summerDate);
- test.verifyFormatTimezone("GMT+14", "GMT+14:00, GMT+14:00", "+1400, GMT+14:00", winterDate);
-
- test.verifyFormatTimezone("America/Los_Angeles", "PDT, Pacific Daylight Time", "-0700, GMT-07:00", summerDate);
- test.verifyFormatTimezone("America/Los_Angeles", "PST, Pacific Standard Time", "-0800, GMT-08:00", winterDate);
-
- // this fails on the RI!
- test.verifyFormatTimezone("America/Detroit", "EDT, Eastern Daylight Time", "-0400, GMT-04:00", summerDate);
- test.verifyFormatTimezone("America/Detroit", "EST, Eastern Standard Time", "-0500, GMT-05:00", winterDate);
-
- assertFalse(test.testsFailed);
- }
-
- public void test_parseLjava_lang_StringLjava_text_ParsePosition_2() {
- try {
- format.parse("240 11 2002 March", null);
- fail("ParsePosition is null: NullPointerException was not thrown.");
- } catch(NullPointerException pe) {
- //expected
- }
-
- try {
- format.parse(null, new ParsePosition(0));
- fail("String is null: NullPointerException was not thrown.");
- } catch(NullPointerException pe) {
- //expected
- }
- }
-
- public void test_setDateFormatSymbolsLjava_text_DateFormatSymbols() {
- // Test for method void
- // java.text.SimpleDateFormat.setDateFormatSymbols(java.text.DateFormatSymbols)
- SimpleDateFormat f1 = new SimpleDateFormat("a");
- DateFormatSymbols symbols = new DateFormatSymbols();
- symbols.setAmPmStrings(new String[] { "morning", "night" });
- f1.setDateFormatSymbols(symbols);
- DateFormatSymbols newSym = f1.getDateFormatSymbols();
- assertTrue("Set incorrectly", newSym.equals(symbols));
- assertTrue("Not a clone", f1.getDateFormatSymbols() != symbols);
- String result = f1.format(new GregorianCalendar(1999, Calendar.JUNE,
- 12, 3, 0).getTime());
- assertEquals("Incorrect symbols used", "morning", result);
- symbols.setEras(new String[] { "before", "after" });
- assertTrue("Identical symbols", !f1.getDateFormatSymbols().equals(
- symbols));
-
- try {
- f1.setDateFormatSymbols(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- public void test_toLocalizedPattern() {
- // BEGIN android-changed
- // Test for method java.lang.String
- // java.text.SimpleDateFormat.toLocalizedPattern()
- SimpleDateFormat f2 = new SimpleDateFormat("GyMdkHmsSEDFwWahKzZ",
- new Locale("de", "CH"));
- String pattern = f2.toLocalizedPattern();
- // the default localized pattern characters are the same for all locales
- // since icu has dropped support for this. the default pattern characters
- // are these: GyMdkHmsSEDFwWahKz
- // ICU only! this fails on the RI
- assertTrue("Wrong pattern: " + pattern, pattern
- .equals("GyMdkHmsSEDFwWahKzZ"));
-
-
- // test the new "Z" pattern char
- f2 = new SimpleDateFormat("G y M d Z", new Locale("de", "CH"));
- pattern = f2.toLocalizedPattern();
- // assertTrue("Wrong pattern: " + pattern, pattern.equals("G u M t Z"));
- assertTrue("Wrong pattern: " + pattern, pattern.equals("G y M d Z"));
- // END android-changed
- }
-
- public void test_toPattern() {
- String pattern = "yyyy mm dd";
- SimpleDateFormat f = new SimpleDateFormat(pattern);
- assertEquals("Wrong pattern: " + pattern, pattern, f.toPattern());
-
- pattern = "GyMdkHmsSEDFwWahKz";
- f = new SimpleDateFormat("GyMdkHmsSEDFwWahKz", new Locale("de", "CH"));
- assertTrue("Wrong pattern: " + pattern, f.toPattern().equals(pattern));
-
- pattern = "G y M d Z";
- f = new SimpleDateFormat(pattern, new Locale("de", "CH"));
- pattern = f.toPattern();
- assertTrue("Wrong pattern: " + pattern, f.toPattern().equals(pattern));
- }
-}
diff --git a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
index 2813cee..e73104d 100644
--- a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
@@ -80,27 +80,12 @@ public class SimpleDateFormatTest extends junit.framework.TestCase {
// The RI fails this test because it doesn't fully support UTS #35.
// https://code.google.com/p/android/issues/detail?id=39616
public void testFiveCount_parsing() throws Exception {
- // It's pretty silly to try to parse the shortest names, because they're almost always ambiguous.
- try {
- parseDate(Locale.ENGLISH, "MMMMM", "J");
- fail();
- } catch (junit.framework.AssertionFailedError expected) {
- }
- try {
- parseDate(Locale.ENGLISH, "LLLLL", "J");
- fail();
- } catch (junit.framework.AssertionFailedError expected) {
- }
- try {
- parseDate(Locale.ENGLISH, "EEEEE", "T");
- fail();
- } catch (junit.framework.AssertionFailedError expected) {
- }
- try {
- parseDate(Locale.ENGLISH, "ccccc", "T");
- fail();
- } catch (junit.framework.AssertionFailedError expected) {
- }
+ // It's pretty silly to try to parse the shortest names, because they're almost always
+ // ambiguous.
+ assertCannotParse(Locale.ENGLISH, "MMMMM", "J");
+ assertCannotParse(Locale.ENGLISH, "LLLLL", "J");
+ assertCannotParse(Locale.ENGLISH, "EEEEE", "T");
+ assertCannotParse(Locale.ENGLISH, "ccccc", "T");
}
// The RI fails this test because it doesn't fully support UTS #35.
@@ -197,6 +182,13 @@ public class SimpleDateFormatTest extends junit.framework.TestCase {
return dateFormat.format(new Date(0));
}
+ private static void assertCannotParse(Locale l, String fmt, String value) {
+ SimpleDateFormat sdf = new SimpleDateFormat(fmt, l);
+ ParsePosition pp = new ParsePosition(0);
+ Date d = sdf.parse(value, pp);
+ assertNull("Value " + value + " must not parse in locale " + l + " with format " + fmt, d);
+ }
+
private static Calendar parseDate(Locale l, String fmt, String value) {
SimpleDateFormat sdf = new SimpleDateFormat(fmt, l);
ParsePosition pp = new ParsePosition(0);
@@ -215,21 +207,37 @@ public class SimpleDateFormatTest extends junit.framework.TestCase {
String date = "2010-12-23 12:44:57.0 CET";
// ICU considers "CET" (Central European Time) to be common in Britain...
assertEquals(1293104697000L, parseDate(Locale.UK, fmt, date).getTimeInMillis());
- // ...but not in the US. Check we can parse such a date anyway.
- assertEquals(1293104697000L, parseDate(Locale.US, fmt, date).getTimeInMillis());
+ // ...but not in the US.
+ assertCannotParse(Locale.US, fmt, date);
}
+ // In Honeycomb, only one Olson id was associated with CET (or any other "uncommon"
+ // abbreviation). This was changed after KitKat to avoid Java hacks on top of ICU data.
+ // ICU data only provides abbreviations for timezones in the locales where they would
+ // not be ambiguous to most people of that locale.
public void testFormattingUncommonTimeZoneAbbreviations() {
- // In Honeycomb, only one Olson id was associated with CET (or any
- // other "uncommon" abbreviation).
String fmt = "yyyy-MM-dd HH:mm:ss.SSS z";
- String date = "1970-01-01 01:00:00.000 CET";
- SimpleDateFormat sdf = new SimpleDateFormat(fmt, Locale.US);
+ String unambiguousDate = "1970-01-01 01:00:00.000 CET";
+ String ambiguousDate = "1970-01-01 01:00:00.000 GMT+01:00";
+
+ // The locale to use when formatting. Not every Locale renders "Europe/Berlin" as "CET". The
+ // UK is one that does, the US is one that does not.
+ Locale cetUnambiguousLocale = Locale.UK;
+ Locale cetAmbiguousLocale = Locale.US;
+
+ SimpleDateFormat sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale);
+ sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
+ assertEquals(unambiguousDate, sdf.format(new Date(0)));
+ sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale);
+ sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
+ assertEquals(unambiguousDate, sdf.format(new Date(0)));
+
+ sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale);
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
- assertEquals(date, sdf.format(new Date(0)));
- sdf = new SimpleDateFormat(fmt, Locale.US);
+ assertEquals(ambiguousDate, sdf.format(new Date(0)));
+ sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale);
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
- assertEquals(date, sdf.format(new Date(0)));
+ assertEquals(ambiguousDate, sdf.format(new Date(0)));
}
// http://code.google.com/p/android/issues/detail?id=8258
@@ -270,17 +278,6 @@ public class SimpleDateFormatTest extends junit.framework.TestCase {
assertEquals("2010-07-08T02:44:48+0000", sdf.format(date));
}
- /**
- * Africa/Cairo standard time is EET and daylight time is EEST. They no
- * longer use their DST zone but we should continue to parse it properly.
- */
- public void testObsoleteDstZoneName() throws Exception {
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm zzzz", Locale.US);
- Date normal = format.parse("1970-01-01T00:00 EET");
- Date dst = format.parse("1970-01-01T00:00 EEST");
- assertEquals(60 * 60 * 1000, normal.getTime() - dst.getTime());
- }
-
public void testDstZoneNameWithNonDstTimestamp() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm zzzz", Locale.US);
Calendar calendar = new GregorianCalendar(AMERICA_LOS_ANGELES);
@@ -353,4 +350,32 @@ public class SimpleDateFormatTest extends junit.framework.TestCase {
assertEquals(1376927400000L, sdf.parse("19. Aug 2013 8:50").getTime());
assertEquals(1376927400000L, sdf.parse("19. Aug. 2013 8:50").getTime());
}
+
+ // http://b/16969112
+ public void test_fractionalSeconds() throws Exception {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
+ assertEquals("1970-01-02 02:17:36.7", sdf.format(sdf.parse("1970-01-02 02:17:36.7")));
+
+ // We only have millisecond precision for Date objects, so we'll lose
+ // information from the fractional seconds section of the string presentation.
+ sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
+ assertEquals("1970-01-02 02:17:36.789000", sdf.format(sdf.parse("1970-01-02 02:17:36.789564")));
+ }
+
+ public void test_nullLocales() {
+ try {
+ SimpleDateFormat.getDateInstance(DateFormat.SHORT, null);
+ fail();
+ } catch (NullPointerException expected) {}
+
+ try {
+ SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, null);
+ fail();
+ } catch (NullPointerException expected) {}
+
+ try {
+ SimpleDateFormat.getTimeInstance(DateFormat.SHORT, null);
+ fail();
+ } catch (NullPointerException expected) {}
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java b/luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java
new file mode 100644
index 0000000..5ea67d3
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/AbstractResourceLeakageDetectorTestCase.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2014 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 libcore.java.util;
+
+import junit.framework.TestCase;
+
+/**
+ * Ensures that resources used within a test are cleaned up; will detect problems with tests and
+ * also with runtime.
+ */
+public abstract class AbstractResourceLeakageDetectorTestCase extends TestCase {
+ /**
+ * The leakage detector.
+ */
+ private ResourceLeakageDetector detector;
+
+ @Override
+ protected void setUp() throws Exception {
+ detector = ResourceLeakageDetector.newDetector();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ // If available check for resource leakage. At this point it is impossible to determine
+ // whether the test has thrown an exception. If it has then the exception thrown by this
+ // could hide that test failure; it largely depends on the test runner.
+ if (detector != null) {
+ detector.checkForLeaks();
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/CalendarTest.java b/luni/src/test/java/libcore/java/util/CalendarTest.java
index dd44789..e0e1a35 100644
--- a/luni/src/test/java/libcore/java/util/CalendarTest.java
+++ b/luni/src/test/java/libcore/java/util/CalendarTest.java
@@ -17,6 +17,7 @@
package libcore.java.util;
import java.util.Calendar;
+import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
@@ -187,8 +188,10 @@ public class CalendarTest extends junit.framework.TestCase {
+ "10000000500000001000000200000000178";
Calendar calendar = new GregorianCalendar(1970, 1, 1, 0, 0, 0);
calendar.setTimeZone(TimeZone.getTimeZone("GMT-08:00"));
- // Starting from ICU4.8 release, the default minimalDaysInFirstWeek changed from 4 to 1.
+ // Calendar fields firstDayOfWeek and minimalDaysInFirstWeek are are sensitive to the Locale
+ // and ICU data. Specifying the values here makes the serialized form stable.
calendar.setMinimalDaysInFirstWeek(4);
+ calendar.setFirstDayOfWeek(Calendar.SUNDAY);
new SerializationTester<Calendar>(calendar, s).test();
}
@@ -236,4 +239,28 @@ public class CalendarTest extends junit.framework.TestCase {
cal.set(Calendar.HOUR_OF_DAY, 1);
assertEquals(32400000, cal.getTimeInMillis());
}
+
+ // http://b/16938922.
+ //
+ // TODO: This is for backwards compatibility only. Seems like a better idea to throw
+ // here. We should add a targetSdkVersion based check and throw for each of these
+ // cases.
+ public void test_nullLocale() {
+ assertCalendarConfigEquals(
+ Calendar.getInstance(Locale.getDefault()),
+ Calendar.getInstance((Locale) null));
+ assertCalendarConfigEquals(
+ Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()),
+ Calendar.getInstance(TimeZone.getDefault(), null));
+ assertCalendarConfigEquals(
+ new GregorianCalendar(Locale.getDefault()),
+ new GregorianCalendar((Locale) null));
+ }
+
+ public void assertCalendarConfigEquals(Calendar a, Calendar b) {
+ Date d = new Date();
+ a.setTime(d);
+ b.setTime(d);
+ assertEquals(a, b);
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/CurrencyTest.java b/luni/src/test/java/libcore/java/util/CurrencyTest.java
index 61a22fd..cf2a1b6 100644
--- a/luni/src/test/java/libcore/java/util/CurrencyTest.java
+++ b/luni/src/test/java/libcore/java/util/CurrencyTest.java
@@ -79,4 +79,12 @@ public class CurrencyTest extends junit.framework.TestCase {
assertEquals("€", Currency.getInstance(pt_PT).getSymbol(pt_BR));
assertEquals("€", Currency.getInstance(pt_PT).getSymbol(pt_PT));
}
+
+ public void test_nullLocales() {
+ Currency currency = Currency.getInstance(Locale.getDefault());
+ try {
+ currency.getSymbol(null);
+ fail();
+ } catch (NullPointerException expected) {}
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/DateTest.java b/luni/src/test/java/libcore/java/util/DateTest.java
index ddcc3e5..3ed0952 100644
--- a/luni/src/test/java/libcore/java/util/DateTest.java
+++ b/luni/src/test/java/libcore/java/util/DateTest.java
@@ -24,16 +24,26 @@ import junit.framework.TestCase;
public class DateTest extends TestCase {
// http://code.google.com/p/android/issues/detail?id=6013
- public void test_toString() throws Exception {
- // Ensure that no matter where this is run, we know what time zone
- // to expect. (Though we still assume an "en" locale.)
+ public void test_toString_us() throws Exception {
+ // Ensure that no matter where this is run, we know what time zone to expect.
+ Locale.setDefault(Locale.US);
TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
assertEquals("Wed Dec 31 18:00:00 CST 1969", new Date(0).toString());
}
- public void test_toGMTString() throws Exception {
+ public void test_toString_nonUs() {
+ // The string for the timezone depends on what the default locale is. Not every locale
+ // has a short-name for America/Chicago -> PST.
+ Locale.setDefault(Locale.UK);
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
+ assertEquals("Wed Dec 31 18:00:00 GMT-06:00 1969", new Date(0).toString());
+ }
+
+ public void test_toGMTString_us() throws Exception {
// Based on https://issues.apache.org/jira/browse/HARMONY-501
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+ Locale.setDefault(Locale.US);
+
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 21);
@@ -43,4 +53,18 @@ public class DateTest extends TestCase {
assertEquals("Sun Jan 01 00:00:00 PST 321", c.getTime().toString());
assertEquals("1 Jan 321 08:00:00 GMT", c.getTime().toGMTString());
}
+
+ public void test_toGMTString_nonUs() throws Exception {
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+ Locale.setDefault(Locale.UK);
+
+ Calendar c = Calendar.getInstance();
+ c.clear();
+ c.set(Calendar.YEAR, 21);
+ assertEquals("Wed Jan 01 00:00:00 GMT-08:00 21", c.getTime().toString());
+ assertEquals("1 Jan 21 08:00:00 GMT", c.getTime().toGMTString());
+ c.set(Calendar.YEAR, 321);
+ assertEquals("Sun Jan 01 00:00:00 GMT-08:00 321", c.getTime().toString());
+ assertEquals("1 Jan 321 08:00:00 GMT", c.getTime().toGMTString());
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/GregorianCalendarTest.java b/luni/src/test/java/libcore/java/util/GregorianCalendarTest.java
new file mode 100644
index 0000000..b2c50b2
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/GregorianCalendarTest.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2013 Google Inc.
+ *
+ * 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 libcore.java.util;
+
+
+import junit.framework.TestCase;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+
+public class GregorianCalendarTest extends TestCase {
+
+ // https://code.google.com/p/android/issues/detail?id=61993
+ public void test_computeFields_dayOfWeekAndWeekOfYearSet() {
+ Calendar greg = GregorianCalendar.getInstance();
+
+ // Setting WEEK_OF_YEAR and DAY_OF_WEEK with an intervening
+ // call to computeFields will work.
+ greg.set(Calendar.WEEK_OF_YEAR, 1);
+ assertEquals(1, greg.get(Calendar.WEEK_OF_YEAR));
+ greg.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ assertEquals(1, greg.get(Calendar.WEEK_OF_YEAR));
+
+ // Setting WEEK_OF_YEAR after DAY_OF_WEEK with no intervening
+ // call to computeFields will work.
+ greg = GregorianCalendar.getInstance();
+ greg.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ greg.set(Calendar.WEEK_OF_YEAR, 1);
+ assertEquals(1, greg.get(Calendar.WEEK_OF_YEAR));
+ assertEquals(Calendar.MONDAY, greg.get(Calendar.DAY_OF_WEEK));
+
+ // Setting DAY_OF_WEEK *after* WEEK_OF_YEAR with no intervening computeFields
+ // will make WEEK_OF_YEAR have no effect. This is a limitation of the API.
+ // Combinations are chosen based *only* on the value of the last field set,
+ // which in this case is DAY_OF_WEEK.
+ greg = GregorianCalendar.getInstance();
+ int weekOfYear = greg.get(Calendar.WEEK_OF_YEAR);
+ greg.set(Calendar.WEEK_OF_YEAR, 1);
+ greg.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
+ // Unchanged WEEK_OF_YEAR.
+ assertEquals(weekOfYear, greg.get(Calendar.WEEK_OF_YEAR));
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/LocaleInternalsTest.java b/luni/src/test/java/libcore/java/util/LocaleInternalsTest.java
new file mode 100644
index 0000000..5344f08
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/LocaleInternalsTest.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * 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 libcore.java.util;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import junit.framework.TestCase;
+import libcore.icu.ICU;
+
+public class LocaleInternalsTest extends TestCase {
+
+ public void test_serializeExtensions() {
+ Map<Character, String> extensions = new TreeMap<Character, String>();
+
+ extensions.put('x', "fooo-baar-baaz");
+ assertEquals("x-fooo-baar-baaz", Locale.serializeExtensions(extensions));
+
+ extensions.put('y', "gaaa-caar-caaz");
+ // Must show up in lexical order.
+ assertEquals("x-fooo-baar-baaz-y-gaaa-caar-caaz",
+ Locale.serializeExtensions(extensions));
+ }
+
+ public void test_parseSerializedExtensions() {
+ Map<Character, String> extensions = new HashMap<Character, String>();
+
+ Locale.parseSerializedExtensions("x-foo", extensions);
+ assertEquals("foo", extensions.get('x'));
+
+ extensions.clear();
+ Locale.parseSerializedExtensions("x-foo-y-bar-z-baz", extensions);
+ assertEquals("foo", extensions.get('x'));
+ assertEquals("bar", extensions.get('y'));
+ assertEquals("baz", extensions.get('z'));
+
+ extensions.clear();
+ Locale.parseSerializedExtensions("x-fooo-baar-baaz", extensions);
+ assertEquals("fooo-baar-baaz", extensions.get('x'));
+
+ extensions.clear();
+ Locale.parseSerializedExtensions("x-fooo-baar-baaz-y-gaaa-caar-caaz", extensions);
+ assertEquals("fooo-baar-baaz", extensions.get('x'));
+ assertEquals("gaaa-caar-caaz", extensions.get('y'));
+ }
+
+ public void test_parseUnicodeExtension() {
+ Map<String, String> keywords = new HashMap<String, String>();
+ Set<String> attributes = new HashSet<String>();
+
+ // Only attributes.
+ Locale.parseUnicodeExtension("foooo".split("-"), keywords, attributes);
+ assertTrue(attributes.contains("foooo"));
+ assertEquals(Collections.EMPTY_SET, keywords.keySet());
+
+ attributes.clear();
+ keywords.clear();
+ Locale.parseUnicodeExtension("foooo-baa-baaabaaa".split("-"),
+ keywords, attributes);
+ assertTrue(attributes.contains("foooo"));
+ assertTrue(attributes.contains("baa"));
+ assertTrue(attributes.contains("baaabaaa"));
+ assertEquals(Collections.EMPTY_SET, keywords.keySet());
+
+ // Only keywords
+ attributes.clear();
+ keywords.clear();
+ Locale.parseUnicodeExtension("ko-koko".split("-"), keywords, attributes);
+ assertTrue(attributes.isEmpty());
+ assertEquals("koko", keywords.get("ko"));
+
+ attributes.clear();
+ keywords.clear();
+ Locale.parseUnicodeExtension("ko-koko-kokoko".split("-"), keywords, attributes);
+ assertTrue(attributes.isEmpty());
+ assertEquals("koko-kokoko", keywords.get("ko"));
+
+ attributes.clear();
+ keywords.clear();
+ Locale.parseUnicodeExtension("ko-koko-kokoko-ba-baba-bababa".split("-"),
+ keywords, attributes);
+ assertTrue(attributes.isEmpty());
+ assertEquals("koko-kokoko", keywords.get("ko"));
+ assertEquals("baba-bababa", keywords.get("ba"));
+
+ // A mixture of attributes and keywords.
+ attributes.clear();
+ keywords.clear();
+ Locale.parseUnicodeExtension("attri1-attri2-k1-type1-type1-k2-type2".split("-"),
+ keywords, attributes);
+ assertTrue(attributes.contains("attri1"));
+ assertTrue(attributes.contains("attri2"));
+ assertEquals("type1-type1", keywords.get("k1"));
+ assertEquals("type2", keywords.get("k2"));
+ }
+
+ public void test_setDefault_setsICUDefaultLocale() {
+ Locale.setDefault(Locale.GERMANY);
+ assertEquals("de_DE", ICU.getDefaultLocale());
+
+ try {
+ Locale.setDefault(null);
+ fail();
+ } catch (NullPointerException expected) {
+ assertEquals(Locale.GERMANY, Locale.getDefault());
+ }
+
+ Locale.setDefault(new Locale("bogus", "LOCALE"));
+ assertEquals("und", ICU.getDefaultLocale());
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/LocaleTest.java b/luni/src/test/java/libcore/java/util/LocaleTest.java
index dee529f..c72ecd7 100644
--- a/luni/src/test/java/libcore/java/util/LocaleTest.java
+++ b/luni/src/test/java/libcore/java/util/LocaleTest.java
@@ -20,10 +20,9 @@ import java.text.BreakIterator;
import java.text.Collator;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
-import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
-import java.util.Arrays;
import java.util.Calendar;
+import java.util.IllformedLocaleException;
import java.util.Locale;
import java.util.MissingResourceException;
@@ -40,9 +39,22 @@ public class LocaleTest extends junit.framework.TestCase {
// and variant, but a display name made up of the raw strings.
// Newer releases return slightly different results, but no less unreasonable.
assertEquals("aabbcc", invalid.getDisplayLanguage());
- assertEquals("", invalid.getDisplayCountry());
- assertEquals("DDEEFF_GGHHII", invalid.getDisplayVariant());
- assertEquals("aabbcc (DDEEFF,DDEEFF_GGHHII)", invalid.getDisplayName());
+ assertEquals("DDEEFF", invalid.getDisplayCountry());
+ assertEquals("GGHHII", invalid.getDisplayVariant());
+ assertEquals("aabbcc (DDEEFF,GGHHII)", invalid.getDisplayName());
+ }
+
+ public void test_getDisplayName_emptyCodes() {
+ Locale emptyLanguage = new Locale("", "DdeEFf");
+ assertEquals("", emptyLanguage.getDisplayLanguage());
+
+ Locale emptyCountry = new Locale("AaBbCc", "");
+ assertEquals("", emptyCountry.getDisplayCountry());
+
+ Locale emptyCountryAndLanguage = new Locale("", "", "Farl");
+ assertEquals("", emptyCountryAndLanguage.getDisplayLanguage());
+ assertEquals("", emptyCountryAndLanguage.getDisplayCountry());
+ assertEquals("Farl", emptyCountryAndLanguage.getDisplayVariant());
}
// http://b/2611311; if there's no display language/country/variant, use the raw codes.
@@ -54,8 +66,8 @@ public class LocaleTest extends junit.framework.TestCase {
assertEquals("xx", unknown.getDisplayLanguage());
assertEquals("YY", unknown.getDisplayCountry());
- assertEquals("TRADITIONAL", unknown.getDisplayVariant());
- assertEquals("xx (YY,TRADITIONAL)", unknown.getDisplayName());
+ assertEquals("Traditional", unknown.getDisplayVariant());
+ assertEquals("xx (YY,Traditional)", unknown.getDisplayName());
}
public void test_getDisplayName_easy() throws Exception {
@@ -65,36 +77,68 @@ public class LocaleTest extends junit.framework.TestCase {
assertEquals("Deutsch", Locale.GERMAN.getDisplayLanguage(Locale.GERMAN));
}
+ // https://b/issue?id=13790528
+ public void test_getDisplayName_withScriptsAndVariants() throws Exception {
+ // Script + Country.
+ assertEquals("Chinese (Traditional Han,China)",
+ Locale.forLanguageTag("zh-Hant-CN").getDisplayName(Locale.US));
+ // Script + Variant.
+ assertEquals("Chinese (Traditional Han,VARIANT)",
+ Locale.forLanguageTag("zh-Hant-VARIANT").getDisplayName(Locale.US));
+ // Country + Variant.
+ assertEquals("Chinese (China,VARIANT)",
+ Locale.forLanguageTag("zh-CN-VARIANT").getDisplayName(Locale.US));
+ // Script + Country + variant.
+ assertEquals("Chinese (Traditional Han,China,VARIANT)",
+ Locale.forLanguageTag("zh-Hant-CN-VARIANT").getDisplayName(Locale.US));
+ }
+
public void test_getDisplayCountry_8870289() throws Exception {
assertEquals("Hong Kong", new Locale("", "HK").getDisplayCountry(Locale.US));
assertEquals("Macau", new Locale("", "MO").getDisplayCountry(Locale.US));
assertEquals("Palestine", new Locale("", "PS").getDisplayCountry(Locale.US));
- assertEquals("Cocos [Keeling] Islands", new Locale("", "CC").getDisplayCountry(Locale.US));
- assertEquals("Congo [DRC]", new Locale("", "CD").getDisplayCountry(Locale.US));
- assertEquals("Congo [Republic]", new Locale("", "CG").getDisplayCountry(Locale.US));
- assertEquals("Falkland Islands [Islas Malvinas]", new Locale("", "FK").getDisplayCountry(Locale.US));
- assertEquals("Macedonia [FYROM]", new Locale("", "MK").getDisplayCountry(Locale.US));
- assertEquals("Myanmar [Burma]", new Locale("", "MM").getDisplayCountry(Locale.US));
+ assertEquals("Cocos (Keeling) Islands", new Locale("", "CC").getDisplayCountry(Locale.US));
+ assertEquals("Congo (DRC)", new Locale("", "CD").getDisplayCountry(Locale.US));
+ assertEquals("Congo (Republic)", new Locale("", "CG").getDisplayCountry(Locale.US));
+ assertEquals("Falkland Islands (Islas Malvinas)", new Locale("", "FK").getDisplayCountry(Locale.US));
+ assertEquals("Macedonia (FYROM)", new Locale("", "MK").getDisplayCountry(Locale.US));
+ assertEquals("Myanmar (Burma)", new Locale("", "MM").getDisplayCountry(Locale.US));
assertEquals("Taiwan", new Locale("", "TW").getDisplayCountry(Locale.US));
}
- public void test_tl() throws Exception {
+ public void test_tl_and_fil() throws Exception {
// In jb-mr1, we had a last-minute hack to always return "Filipino" because
- // icu4c 4.8 didn't have any localizations for fil. (http://b/7291355)
+ // icu4c 4.8 didn't have any localizations for fil. (http://b/7291355).
+ //
+ // After the icu4c 4.9 upgrade, we could localize "fil" correctly, though we
+ // needed another hack to supply "fil" instead of "tl" to icu4c. (http://b/8023288).
+ //
+ // These hacks have now been reverted, so "tl" really does represent
+ // tagalog and not filipino.
Locale tl = new Locale("tl");
Locale tl_PH = new Locale("tl", "PH");
- assertEquals("Filipino", tl.getDisplayLanguage(Locale.ENGLISH));
- assertEquals("Filipino", tl_PH.getDisplayLanguage(Locale.ENGLISH));
- assertEquals("Filipino", tl.getDisplayLanguage(tl));
- assertEquals("Filipino", tl_PH.getDisplayLanguage(tl_PH));
+ assertEquals("Tagalog", tl.getDisplayLanguage(Locale.ENGLISH));
+ assertEquals("Tagalog", tl_PH.getDisplayLanguage(Locale.ENGLISH));
+ assertEquals("tl", tl.getDisplayLanguage(tl));
+ assertEquals("tl", tl_PH.getDisplayLanguage(tl_PH));
- // After the icu4c 4.9 upgrade, we could localize "fil" correctly, though we
- // needed another hack to supply "fil" instead of "tl" to icu4c. (http://b/8023288)
Locale es_MX = new Locale("es", "MX");
- assertEquals("filipino", tl.getDisplayLanguage(es_MX));
- assertEquals("filipino", tl_PH.getDisplayLanguage(es_MX));
- }
+ assertEquals("tagalo", tl.getDisplayLanguage(es_MX));
+ assertEquals("tagalo", tl_PH.getDisplayLanguage(es_MX));
+
+ // Assert that we can deal with "fil" correctly, since we've switched
+ // to using "fil" for Filipino, and not "tl". (http://b/15873165).
+ Locale fil = new Locale("fil");
+ Locale fil_PH = new Locale("fil", "PH");
+ assertEquals("Filipino", fil.getDisplayLanguage(Locale.ENGLISH));
+ assertEquals("Filipino", fil_PH.getDisplayLanguage(Locale.ENGLISH));
+ assertEquals("Filipino", fil.getDisplayLanguage(fil));
+ assertEquals("Filipino", fil_PH.getDisplayLanguage(fil_PH));
+
+ assertEquals("filipino", fil.getDisplayLanguage(es_MX));
+ assertEquals("filipino", fil_PH.getDisplayLanguage(es_MX));
+ }
// http://b/3452611; Locale.getDisplayLanguage fails for the obsolete language codes.
public void test_getDisplayName_obsolete() throws Exception {
@@ -158,6 +202,10 @@ public class LocaleTest extends junit.framework.TestCase {
assertEquals("CAN", new Locale("", "CA").getISO3Country());
assertEquals("CAN", new Locale("en", "CA").getISO3Country());
assertEquals("CAN", new Locale("xx", "CA").getISO3Country());
+
+ // 3 letter country codes.
+ assertEquals("CAN", new Locale("en", "CAN").getISO3Country());
+ assertEquals("CAN", new Locale("frankenderp", "CAN").getISO3Country());
}
public void test_getISO3Language() {
@@ -177,5 +225,925 @@ public class LocaleTest extends junit.framework.TestCase {
assertEquals("eng", new Locale("en", "").getISO3Language());
assertEquals("eng", new Locale("en", "CA").getISO3Language());
assertEquals("eng", new Locale("en", "XX").getISO3Language());
+
+ // 3 letter language code.
+ assertEquals("eng", new Locale("eng", "USA").getISO3Language());
+ assertEquals("eng", new Locale("eng", "US").getISO3Language());
+ }
+
+ public void test_Builder_setLanguage() {
+ Locale.Builder b = new Locale.Builder();
+
+ // Should normalize to lower case.
+ b.setLanguage("EN");
+ assertEquals("en", b.build().getLanguage());
+
+ b = new Locale.Builder();
+
+ // Too short.
+ try {
+ b.setLanguage("e");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Too long
+ try {
+ b.setLanguage("engl");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Contains non ASCII characters
+ try {
+ b.setLanguage("தமிழà¯");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Null or empty languages must clear state.
+ b = new Locale.Builder();
+ b.setLanguage("en");
+ b.setLanguage(null);
+ assertEquals("", b.build().getLanguage());
+
+ b = new Locale.Builder();
+ b.setLanguage("en");
+ b.setLanguage("");
+ assertEquals("", b.build().getLanguage());
+ }
+
+ public void test_Builder_setRegion() {
+ Locale.Builder b = new Locale.Builder();
+
+ // Should normalize to upper case.
+ b.setRegion("us");
+ assertEquals("US", b.build().getCountry());
+
+ b = new Locale.Builder();
+
+ // Too short.
+ try {
+ b.setRegion("e");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Too long
+ try {
+ b.setRegion("USA");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Contains non ASCII characters
+ try {
+ b.setLanguage("திழà¯");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Null or empty regions must clear state.
+ b = new Locale.Builder();
+ b.setRegion("US");
+ b.setRegion(null);
+ assertEquals("", b.build().getCountry());
+
+ b = new Locale.Builder();
+ b.setRegion("US");
+ b.setRegion("");
+ assertEquals("", b.build().getCountry());
+ }
+
+ public void test_Builder_setVariant() {
+ Locale.Builder b = new Locale.Builder();
+
+ // Should normalize "_" to "-"
+ b = new Locale.Builder();
+ b.setVariant("vArIaNt-VaRiAnT-VARIANT");
+ assertEquals("vArIaNt_VaRiAnT_VARIANT", b.build().getVariant());
+
+ b = new Locale.Builder();
+ // Too short
+ try {
+ b.setVariant("shor");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Too long
+ try {
+ b.setVariant("waytoolong");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ try {
+ b.setVariant("foooo-foooo-fo");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Special case. Variants of length 4 are allowed when the first
+ // character is a digit.
+ b.setVariant("0ABC");
+ assertEquals("0ABC", b.build().getVariant());
+
+ b = new Locale.Builder();
+ b.setVariant("variant");
+ b.setVariant(null);
+ assertEquals("", b.build().getVariant());
+
+ b = new Locale.Builder();
+ b.setVariant("variant");
+ b.setVariant("");
+ assertEquals("", b.build().getVariant());
+ }
+
+ public void test_Builder_setLocale() {
+ // Default case.
+ Locale.Builder b = new Locale.Builder();
+ b.setLocale(Locale.US);
+ assertEquals("en", b.build().getLanguage());
+ assertEquals("US", b.build().getCountry());
+
+ // Should throw when locale is malformed.
+ // - Bad language
+ Locale bad = new Locale("e", "US");
+ b = new Locale.Builder();
+ try {
+ b.setLocale(bad);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+ // - Bad country
+ bad = new Locale("en", "USA");
+ try {
+ b.setLocale(bad);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // - Bad variant
+ bad = new Locale("en", "US", "c");
+ try {
+ b.setLocale(bad);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Test values are normalized as they should be
+ b = new Locale.Builder();
+ Locale good = new Locale("EN", "us", "variant-VARIANT");
+ b.setLocale(good);
+ Locale l = b.build();
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+ assertEquals("variant_VARIANT", l.getVariant());
+
+ // Test that none of the existing fields are messed with
+ // if the locale update fails.
+ b = new Locale.Builder();
+ b.setLanguage("fr").setRegion("FR");
+
+ try {
+ b.setLocale(bad);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ l = b.build();
+ assertEquals("fr", l.getLanguage());
+ assertEquals("FR", l.getCountry());
+ }
+
+ public void test_Builder_setScript() {
+ Locale.Builder b = new Locale.Builder();
+
+ // Should normalize variants to lower case.
+ b.setScript("lAtN");
+ assertEquals("Latn", b.build().getScript());
+
+ b = new Locale.Builder();
+ // Too short
+ try {
+ b.setScript("lat");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Too long
+ try {
+ b.setScript("latin");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ b = new Locale.Builder();
+ b.setScript("Latn");
+ b.setScript(null);
+ assertEquals("", b.build().getScript());
+
+ b = new Locale.Builder();
+ b.setScript("Latn");
+ b.setScript("");
+ assertEquals("", b.build().getScript());
+ }
+
+ public void test_Builder_clear() {
+ Locale.Builder b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setRegion("US")
+ .setVariant("POSIX").setExtension('g', "foo")
+ .setUnicodeLocaleKeyword("fo", "baar")
+ .addUnicodeLocaleAttribute("baaaaz");
+
+ Locale l = b.clear().build();
+ assertEquals("", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+ assertTrue(l.getExtensionKeys().isEmpty());
+ }
+
+ public void test_Builder_setExtension() {
+ Locale.Builder b = new Locale.Builder();
+ b.setExtension('g', "FO_ba-BR_bg");
+
+ Locale l = b.build();
+ assertEquals("fo-ba-br-bg", l.getExtension('g'));
+
+ b = new Locale.Builder();
+
+ // Too short
+ try {
+ b.setExtension('g', "fo-ba-br-x");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Too long
+ try {
+ b.setExtension('g', "fo-ba-br-extension");
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Special case, the private use extension allows single char subtags.
+ b.setExtension(Locale.PRIVATE_USE_EXTENSION, "fo-ba-br-m");
+ l = b.build();
+ assertEquals("fo-ba-br-m", l.getExtension('x'));
+
+ // Special case, the unicode locale extension must be parsed into
+ // its individual components. The correctness of the parse is tested
+ // in test_parseUnicodeExtension.
+ b.setExtension(Locale.UNICODE_LOCALE_EXTENSION, "foooo_BaaaR-BA_Baz-bI_BIZ");
+ l = b.build();
+ // Note that attributes and keywords are sorted alphabetically.
+ assertEquals("baaar-foooo-ba-baz-bi-biz", l.getExtension('u'));
+
+ assertTrue(l.getUnicodeLocaleAttributes().contains("foooo"));
+ assertTrue(l.getUnicodeLocaleAttributes().contains("baaar"));
+ assertEquals("baz", l.getUnicodeLocaleType("ba"));
+ assertEquals("biz", l.getUnicodeLocaleType("bi"));
+ }
+
+ public void test_Builder_clearExtensions() {
+ Locale.Builder b = new Locale.Builder();
+ b.setExtension('g', "FO_ba-BR_bg");
+ b.setExtension(Locale.PRIVATE_USE_EXTENSION, "fo-ba-br-m");
+ b.clearExtensions();
+
+ assertTrue(b.build().getExtensionKeys().isEmpty());
+ }
+
+ private static Locale fromLanguageTag(String languageTag, boolean useBuilder) {
+ if (useBuilder) {
+ return (new Locale.Builder().setLanguageTag(languageTag).build());
+ } else {
+ return Locale.forLanguageTag(languageTag);
+ }
+ }
+
+ private void test_setLanguageTag_wellFormedsingleSubtag(boolean useBuilder) {
+ Locale l = fromLanguageTag("en", useBuilder);
+ assertEquals("en", l.getLanguage());
+
+ l = fromLanguageTag("eng", useBuilder);
+ assertEquals("eng", l.getLanguage());
+ }
+
+ private void test_setLanguageTag_twoWellFormedSubtags(boolean useBuilder) {
+ Locale l = fromLanguageTag("en-US", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+
+ l = fromLanguageTag("eng-419", useBuilder);
+ assertEquals("eng", l.getLanguage());
+ assertEquals("419", l.getCountry());
+
+ // Script tags shouldn't be mis-recognized as regions.
+ l = fromLanguageTag("en-Latn", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("Latn", l.getScript());
+
+ // Neither should variant tags.
+ l = fromLanguageTag("en-POSIX", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getScript());
+ assertEquals("POSIX", l.getVariant());
+ }
+
+ public void test_Builder_setLanguageTag_malformedTags() {
+ try {
+ fromLanguageTag("a", true);
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ // Three subtags
+ // lang-region-illformedvariant
+ try {
+ fromLanguageTag("en-US-BA", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // lang-variant-illformedvariant
+ try {
+ fromLanguageTag("en-FOOOO-BA", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Four or more sub tags
+ try {
+ fromLanguageTag("en-US-POSIX-P2", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ try {
+ fromLanguageTag("en-Latn-US-P2", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Extensions
+ // Ill-formed empty extension.
+ try {
+ fromLanguageTag("en-f-f", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Ill-formed empty extension.
+ try {
+ fromLanguageTag("en-f", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Two extension keys in a row (i.e, another case of an ill-formed
+ // empty exception).
+ try {
+ fromLanguageTag("en-f-g-fo-baar", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Dangling empty key after a well formed extension.
+ try {
+ fromLanguageTag("en-f-fo-baar-g", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+
+ // Ill-formed extension with long subtag.
+ try {
+ fromLanguageTag("en-f-fooobaaaz", true);
+ fail();
+ } catch (IllformedLocaleException expected) {
+ }
+ }
+
+ private void test_setLanguageTag_threeWellFormedSubtags(boolean useBuilder) {
+ // lang-region-variant
+ Locale l = fromLanguageTag("en-US-FOOOO", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+ assertEquals("", l.getScript());
+ assertEquals("FOOOO", l.getVariant());
+
+ // lang-script-variant
+ l = fromLanguageTag("en-Latn-FOOOO", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("Latn", l.getScript());
+ assertEquals("FOOOO", l.getVariant());
+
+ // lang-script-region
+ l = fromLanguageTag("en-Latn-US", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+ assertEquals("Latn", l.getScript());
+ assertEquals("", l.getVariant());
+
+ // lang-variant-variant
+ l = fromLanguageTag("en-FOOOO-BAAAR", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getScript());
+ assertEquals("FOOOO_BAAAR", l.getVariant());
+ }
+
+ private void test_setLanguageTag_fourOrMoreWellFormedSubtags(boolean useBuilder) {
+ // lang-script-region-variant.
+ Locale l = fromLanguageTag("en-Latn-US-foooo", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("US", l.getCountry());
+ assertEquals("foooo", l.getVariant());
+
+ // Variant with multiple subtags.
+ l = fromLanguageTag("en-Latn-US-foooo-gfffh", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("US", l.getCountry());
+ assertEquals("foooo_gfffh", l.getVariant());
+
+ // Variant with 3 subtags. POSIX shouldn't be recognized
+ // as a region or a script.
+ l = fromLanguageTag("en-POSIX-P2003-P2004", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getScript());
+ assertEquals("", l.getCountry());
+ assertEquals("POSIX_P2003_P2004", l.getVariant());
+
+ // lang-script-variant-variant.
+ l = fromLanguageTag("en-Latn-POSIX-P2003", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("", l.getCountry());
+ assertEquals("POSIX_P2003", l.getVariant());
+
+ // lang-region-variant-variant
+ l = fromLanguageTag("en-US-POSIX-P2003", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getScript());
+ assertEquals("US", l.getCountry());
+ assertEquals("POSIX_P2003", l.getVariant());
+ }
+
+ private void test_setLanguageTag_withWellFormedExtensions(boolean useBuilder) {
+ Locale l = fromLanguageTag("en-Latn-GB-foooo-g-fo-bar-baaz", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("GB", l.getCountry());
+ assertEquals("foooo", l.getVariant());
+ assertEquals("fo-bar-baaz", l.getExtension('g'));
+
+ // Multiple extensions
+ l = fromLanguageTag("en-Latn-US-foooo-g-fo-bar-h-go-gaz", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("US", l.getCountry());
+ assertEquals("foooo", l.getVariant());
+ assertEquals("fo-bar", l.getExtension('g'));
+ assertEquals("go-gaz", l.getExtension('h'));
+
+ // Unicode locale extension.
+ l = fromLanguageTag("en-Latn-US-foooo-u-koooo-fo-bar", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("US", l.getCountry());
+ assertEquals("koooo-fo-bar", l.getExtension('u'));
+ assertTrue(l.getUnicodeLocaleAttributes().contains("koooo"));
+ assertEquals("bar", l.getUnicodeLocaleType("fo"));
+
+ // Extensions without variants
+ l = fromLanguageTag("en-Latn-US-f-fo", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("US", l.getCountry());
+ assertEquals("fo", l.getExtension('f'));
+
+ l = fromLanguageTag("en-Latn-f-fo", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("Latn", l.getScript());
+ assertEquals("fo", l.getExtension('f'));
+
+ l = fromLanguageTag("en-f-fo", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getScript());
+ assertEquals("", l.getCountry());
+ assertEquals("fo", l.getExtension('f'));
+
+ l = fromLanguageTag("en-f-fo-x-a-b-c-d-e-fo", useBuilder);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getScript());
+ assertEquals("", l.getCountry());
+ assertEquals("fo", l.getExtension('f'));
+ assertEquals("a-b-c-d-e-fo", l.getExtension('x'));
+ }
+
+ public void test_forLanguageTag() {
+ test_setLanguageTag_wellFormedsingleSubtag(false);
+ test_setLanguageTag_twoWellFormedSubtags(false);
+ test_setLanguageTag_threeWellFormedSubtags(false);
+ test_setLanguageTag_fourOrMoreWellFormedSubtags(false);
+ test_setLanguageTag_withWellFormedExtensions(false);
+ }
+
+ public void test_Builder_setLanguageTag() {
+ test_setLanguageTag_wellFormedsingleSubtag(true);
+ test_setLanguageTag_twoWellFormedSubtags(true);
+ test_setLanguageTag_threeWellFormedSubtags(true);
+ test_setLanguageTag_fourOrMoreWellFormedSubtags(true);
+ test_setLanguageTag_withWellFormedExtensions(true);
+ }
+
+ public void test_getDisplayScript() {
+ Locale.Builder b = new Locale.Builder();
+ b.setLanguage("en").setRegion("US").setScript("Latn");
+
+ Locale l = b.build();
+
+ // getDisplayScript() test relies on the default locale. We set it here to avoid test
+ // failures if the test device is set to a non-English locale.
+ Locale.setDefault(Locale.US);
+ assertEquals("Latin", l.getDisplayScript());
+
+ assertEquals("Lateinisch", l.getDisplayScript(Locale.GERMAN));
+ // Fallback for navajo, a language for which we don't have data.
+ assertEquals("Latin", l.getDisplayScript(new Locale("nv", "US")));
+
+ b= new Locale.Builder();
+ b.setLanguage("en").setRegion("US").setScript("Fooo");
+
+ // Will be equivalent to getScriptCode for scripts that aren't
+ // registered with ISO-15429 (but are otherwise well formed).
+ l = b.build();
+ assertEquals("Fooo", l.getDisplayScript());
+ }
+
+ public void test_setLanguageTag_malformedTags() {
+ Locale l = fromLanguageTag("a", false);
+ assertEquals("und", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-US-BA", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-FOOOO-BA", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("FOOOO", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-US-POSIX-P2", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+ assertEquals("POSIX", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-Latn-US-P2", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("US", l.getCountry());
+ assertEquals("Latn", l.getScript());
+
+ l = fromLanguageTag("en-f-f", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-f", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-f-fooobaaaz", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+
+ l = fromLanguageTag("en-9-baa", false);
+ assertEquals("en", l.getLanguage());
+ assertEquals("", l.getCountry());
+ assertEquals("", l.getVariant());
+ assertEquals("", l.getScript());
+ }
+
+ public void test_Builder_unicodeAttributes() {
+ // Adding and removing attributes
+ Locale.Builder b = new Locale.Builder();
+ b.setLanguage("en");
+
+ // Well formed attribute.
+ b.addUnicodeLocaleAttribute("foooo");
+
+ try {
+ b.addUnicodeLocaleAttribute("fo");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ try {
+ b.removeUnicodeLocaleAttribute("fo");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ try {
+ b.addUnicodeLocaleAttribute("greaterthaneightchars");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ try {
+ b.removeUnicodeLocaleAttribute("greaterthaneightchars");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ try {
+ b.addUnicodeLocaleAttribute(null);
+ fail();
+ } catch (NullPointerException npe) {
+ }
+
+ try {
+ b.removeUnicodeLocaleAttribute(null);
+ fail();
+ } catch (NullPointerException npe) {
+ }
+
+ Locale l = b.build();
+ assertEquals("en-u-foooo", l.toLanguageTag());
+ assertTrue(l.getUnicodeLocaleAttributes().contains("foooo"));
+
+ b.addUnicodeLocaleAttribute("dAtA");
+ l = b.build();
+ assertEquals("data-foooo", l.getExtension('u'));
+ assertTrue(l.getUnicodeLocaleAttributes().contains("data"));
+ assertTrue(l.getUnicodeLocaleAttributes().contains("foooo"));
+ }
+
+ public void test_Builder_unicodeKeywords() {
+ // Adding and removing attributes
+ Locale.Builder b = new Locale.Builder();
+ b.setLanguage("en");
+
+ // Key not of length 2.
+ try {
+ b.setUnicodeLocaleKeyword("k", "fooo");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ // Value too short
+ try {
+ b.setUnicodeLocaleKeyword("k", "fo");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+ // Value too long
+ try {
+ b.setUnicodeLocaleKeyword("k", "foooooooo");
+ fail();
+ } catch (IllformedLocaleException ifle) {
+ }
+
+
+ // Null should clear the key.
+ b.setUnicodeLocaleKeyword("bo", "baaz");
+ Locale l = b.build();
+ assertEquals("bo-baaz", l.getExtension('u'));
+ assertEquals("baaz", l.getUnicodeLocaleType("bo"));
+
+ b = new Locale.Builder();
+ b.setUnicodeLocaleKeyword("bo", "baaz");
+ b.setUnicodeLocaleKeyword("bo", null);
+ l = b.build();
+ assertNull(l.getExtension('u'));
+ assertNull(l.getUnicodeLocaleType("bo"));
+
+ // When we set attributes, they should show up before extensions.
+ b = new Locale.Builder();
+ b.addUnicodeLocaleAttribute("fooo");
+ b.addUnicodeLocaleAttribute("gooo");
+ b.setUnicodeLocaleKeyword("fo", "baz");
+ b.setUnicodeLocaleKeyword("ka", "kaz");
+ l = b.build();
+ assertEquals("fooo-gooo-fo-baz-ka-kaz", l.getExtension('u'));
+ assertEquals("baz", l.getUnicodeLocaleType("fo"));
+ assertEquals("kaz", l.getUnicodeLocaleType("ka"));
+ assertTrue(l.getUnicodeLocaleAttributes().contains("fooo"));
+ assertTrue(l.getUnicodeLocaleAttributes().contains("gooo"));
+ }
+
+ public void test_multipleExtensions() {
+ Locale.Builder b = new Locale.Builder();
+ b.setLanguage("en");
+ b.addUnicodeLocaleAttribute("attrib");
+ b.addUnicodeLocaleAttribute("attrib2");
+ b.setExtension('f', "fo-baaz-ga-gaaz");
+ b.setExtension('x', "xo-baaz-ga-gaaz");
+ b.setExtension('z', "zo-baaz-ga-gaaz");
+
+ Locale l = b.build();
+ // Implicitly added because we added unicode locale attributes.
+ assertEquals("attrib-attrib2", l.getExtension('u'));
+ assertEquals("fo-baaz-ga-gaaz", l.getExtension('f'));
+ assertEquals("xo-baaz-ga-gaaz", l.getExtension('x'));
+ assertEquals("zo-baaz-ga-gaaz", l.getExtension('z'));
+ }
+
+ public void test_immutability() {
+ Locale.Builder b = new Locale.Builder();
+ b.setExtension('g', "fooo-baaz-baar");
+ b.setExtension('u', "foooo-baaar-ba-baaz-ka-kaaz");
+
+ Locale l = b.build();
+ try {
+ l.getExtensionKeys().add('g');
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ try {
+ l.getUnicodeLocaleAttributes().add("fooo");
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ }
+
+ public void test_toLanguageTag() {
+ Locale.Builder b = new Locale.Builder();
+
+ // Empty builder.
+ Locale l = b.build();
+ // TODO: Fix this. We should return "und" and not NULL.
+ // assertEquals("und", l.toLanguageTag());
+
+ // Only language.
+ b = new Locale.Builder();
+ b.setLanguage("en");
+ assertEquals("en", b.build().toLanguageTag());
+
+ // Language & Region
+ b = new Locale.Builder();
+ b.setLanguage("en").setRegion("US");
+ assertEquals("en-US", b.build().toLanguageTag());
+
+ // Language & Script
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn");
+ assertEquals("en-Latn", b.build().toLanguageTag());
+
+ // Language & Variant
+ b = new Locale.Builder();
+ b.setLanguage("en").setVariant("foooo");
+ assertEquals("en-foooo", b.build().toLanguageTag());
+
+ // Language / script & country
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setRegion("US");
+ assertEquals("en-Latn-US", b.build().toLanguageTag());
+
+ // Language / script & variant
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setVariant("foooo");
+ assertEquals("en-Latn-foooo", b.build().toLanguageTag());
+
+ // Language / script / country / variant.
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setVariant("foooo").setRegion("US");
+ assertEquals("en-Latn-US-foooo", b.build().toLanguageTag());
+
+ // Language / extension
+ b = new Locale.Builder();
+ b.setLanguage("en").setExtension('x', "fooo-baar");
+ assertEquals("en-x-fooo-baar", b.build().toLanguageTag());
+
+ // Language & multiple extensions (including unicode).
+ b = new Locale.Builder();
+ b.setLanguage("en");
+ b.addUnicodeLocaleAttribute("attrib");
+ b.addUnicodeLocaleAttribute("attrib2");
+ b.setExtension('f', "fo-baaz-ga-gaaz");
+ b.setExtension('x', "xo-baaz-ga-gaaz");
+ b.setExtension('z', "zo-baaz-ga-gaaz");
+
+ l = b.build();
+ // Implicitly added because we added unicode locale attributes.
+ assertEquals("attrib-attrib2", l.getExtension('u'));
+ assertEquals("fo-baaz-ga-gaaz", l.getExtension('f'));
+ assertEquals("xo-baaz-ga-gaaz", l.getExtension('x'));
+ assertEquals("zo-baaz-ga-gaaz", l.getExtension('z'));
+
+ assertEquals("en-" +
+ "f-fo-baaz-ga-gaaz-" + // extension tags in lexical order
+ "u-attrib-attrib2-z-zo-baaz-ga-gaaz-" + // unicode attribs & keywords in lex order
+ "x-xo-baaz-ga-gaaz", // private use extension unmodified.
+ l.toLanguageTag());
+ }
+
+ public void test_toString() {
+ Locale.Builder b = new Locale.Builder();
+
+ // Empty builder.
+ Locale l = b.build();
+ assertEquals("", l.toString());
+
+ // Only language.
+ b = new Locale.Builder();
+ b.setLanguage("en");
+ assertEquals("en", b.build().toString());
+
+ // Only region
+ b = new Locale.Builder();
+ b.setRegion("US");
+ assertEquals("_US", b.build().toString());
+
+ // Language & Region
+ b = new Locale.Builder();
+ b.setLanguage("en").setRegion("US");
+ assertEquals("en_US", b.build().toString());
+
+ // Language & Script
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn");
+ assertEquals("en__#Latn", b.build().toString());
+
+ // Language & Variant
+ b = new Locale.Builder();
+ b.setLanguage("en").setVariant("foooo");
+ assertEquals("en__foooo", b.build().toString());
+
+ // Language / script & country
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setRegion("US");
+ assertEquals("en_US_#Latn", b.build().toString());
+
+ // Language / script & variant
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setVariant("foooo");
+ assertEquals("en__foooo_#Latn", b.build().toString());
+
+ // Language / script / country / variant.
+ b = new Locale.Builder();
+ b.setLanguage("en").setScript("Latn").setVariant("foooo").setRegion("US");
+ assertEquals("en_US_foooo_#Latn", b.build().toString());
+
+ // Language / extension
+ b = new Locale.Builder();
+ b.setLanguage("en").setExtension('x', "fooo-baar");
+ assertEquals("en__#x-fooo-baar", b.build().toString());
+ }
+
+ // Tests cases where our "guess" for the output size is incorrect.
+ //
+ // https://b.corp.google.com/issue?id=13414549
+ public void test_toLanguageTag_largerTag() {
+ Locale posix = new Locale.Builder()
+ .setLanguage("en").setRegion("US").setVariant("POSIX")
+ .build();
+ assertEquals("en-US-POSIX", posix.toLanguageTag());
+ }
+
+ public void test_forLanguageTag_grandFatheredLocale() {
+ // Regular grandfathered locale.
+ Locale gaulish = Locale.forLanguageTag("cel-gaulish");
+ assertEquals("xtg", gaulish.getLanguage());
+ assertEquals("cel-gaulish", gaulish.getExtension(Locale.PRIVATE_USE_EXTENSION));
+ assertEquals("", gaulish.getCountry());
+ assertEquals("", gaulish.getScript());
+ assertEquals("", gaulish.getVariant());
+
+ // Irregular grandfathered locale.
+ Locale enochian = Locale.forLanguageTag("i-enochian");
+ assertEquals("und", enochian.getLanguage());
+ assertEquals("i-enochian", enochian.getExtension(Locale.PRIVATE_USE_EXTENSION));
+ assertEquals("", enochian.getCountry());
+ assertEquals("", enochian.getScript());
+ assertEquals("", enochian.getVariant());
+ }
+
+ // Test case from http://b/16811867
+ public void testVariantsCaseSensitive() {
+ final Locale locale = new Locale("en", "US", "variant");
+ assertEquals("variant", locale.getVariant());
+ assertEquals(locale, Locale.forLanguageTag(locale.toLanguageTag()));
}
- }
+}
diff --git a/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java b/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java
index fa761d3..87f2f9d 100644
--- a/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java
+++ b/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java
@@ -76,9 +76,16 @@ public class OldAndroidLocaleTest extends TestCase {
// This one makes sure we have all necessary locales installed.
public void testICULocales() {
- String[] locales = new String[] {
- // List of locales currently required for Android.
- "en_US", "es_US", "en_GB", "fr_FR", "de_DE", "de_AT", "cs_CZ", "nl_NL" };
+ // List of locales currently required for Android.
+ Locale[] locales = new Locale[] {
+ new Locale("en", "US"),
+ new Locale("es", "US"),
+ new Locale("en", "GB"),
+ new Locale("fr", "FR"),
+ new Locale("de", "DE"),
+ new Locale("de", "AT"),
+ new Locale("cs", "CZ"),
+ new Locale("nl", "NL") };
String[] mondays = new String[] {
"Monday", "lunes", "Monday", "lundi", "Montag", "Montag", "pond\u011bl\u00ed", "maandag" };
@@ -87,14 +94,12 @@ public class OldAndroidLocaleTest extends TestCase {
"USD", "USD", "GBP", "EUR", "EUR", "EUR", "CZK", "EUR"};
for (int i = 0; i < locales.length; i++) {
- Locale l = new Locale(locales[i].substring(0, 2), locales[i].substring(3));
+ final Locale l = locales[i];
- // Check language part of locale.
DateFormatSymbols d = new DateFormatSymbols(l);
assertEquals("Monday name for " + locales[i] + " must match",
mondays[i], d.getWeekdays()[2]);
- // Check country part of locale.
Currency c = Currency.getInstance(l);
assertEquals("Currency code for " + locales[i] + " must match",
currencies[i], c.getCurrencyCode());
diff --git a/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java b/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java
index 713e1b5..ecf2e5f 100644
--- a/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java
+++ b/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java
@@ -25,7 +25,7 @@ import junit.framework.TestCase;
public class OldTimeZoneTest extends TestCase {
- class Mock_TimeZone extends TimeZone {
+ static class Mock_TimeZone extends TimeZone {
@Override
public int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds) {
return 0;
@@ -91,29 +91,50 @@ public class OldTimeZoneTest extends TestCase {
public void test_getDisplayNameLjava_util_Locale() {
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("Pacific Standard Time", tz.getDisplayName(new Locale("US")));
- assertEquals("heure normale du Pacifique", tz.getDisplayName(Locale.FRANCE));
+ assertEquals("Pacific Standard Time", tz.getDisplayName(Locale.US));
+ assertEquals("heure normale du Pacifique nord-américain", tz.getDisplayName(Locale.FRANCE));
}
public void test_getDisplayNameZI() {
Locale.setDefault(Locale.US);
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("PST", tz.getDisplayName(false, 0));
- assertEquals("Pacific Daylight Time", tz.getDisplayName(true, 1));
- assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1));
+ assertEquals("PST", tz.getDisplayName(false, TimeZone.SHORT));
+ assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG));
+ assertEquals("Pacific Standard Time", tz.getDisplayName(false, TimeZone.LONG));
}
@AndroidOnly("fail on RI. See comment below")
public void test_getDisplayNameZILjava_util_Locale() {
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("PST", tz.getDisplayName(false, 0, Locale.US));
- assertEquals("Pacific Daylight Time", tz.getDisplayName(true, 1, Locale.US));
- assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1, Locale.UK));
- // RI always returns short time zone name as "PST"
- // ICU zone/root.txt patched to allow metazone names.
- assertEquals("PST", tz.getDisplayName(false, 0, Locale.FRANCE));
- assertEquals("heure avanc\u00e9e du Pacifique", tz.getDisplayName(true, 1, Locale.FRANCE));
- assertEquals("heure normale du Pacifique", tz.getDisplayName(false, 1, Locale.FRANCE));
+ assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG, Locale.US));
+ assertEquals("Pacific Standard Time", tz.getDisplayName(false, TimeZone.LONG, Locale.UK));
+ assertEquals("heure avanc\u00e9e du Pacifique",
+ tz.getDisplayName(true, TimeZone.LONG, Locale.FRANCE));
+ assertEquals("heure normale du Pacifique nord-américain",
+ tz.getDisplayName(false, TimeZone.LONG, Locale.FRANCE));
+
+ assertEquals("PDT", tz.getDisplayName(true, TimeZone.SHORT, Locale.US));
+ assertEquals("PST", tz.getDisplayName(false, TimeZone.SHORT, Locale.US));
+ // RI fails on following lines. RI always returns short time zone name for
+ // "America/Los_Angeles" as "PST", Android only returns a string if ICU has a translation.
+ // There is no short time zone name for America/Los_Angeles in French or British English in
+ // ICU data so an offset is returned instead.
+ assertEquals("GMT-08:00", tz.getDisplayName(false, TimeZone.SHORT, Locale.FRANCE));
+ assertEquals("GMT-07:00", tz.getDisplayName(true, TimeZone.SHORT, Locale.FRANCE));
+ assertEquals("GMT-08:00", tz.getDisplayName(false, TimeZone.SHORT, Locale.UK));
+ assertEquals("GMT-07:00", tz.getDisplayName(true, TimeZone.SHORT, Locale.UK));
+
+ // The RI behavior mentioned above does not appear to be because "PST" is a legacy
+ // three-character timezone supported by the RI: it happens for "Asia/Tehran"/"IRST" too
+ // (IRST is not a legacy code). The RI may just use a different dataset that has "PST" /
+ // "IRST" as valid translations (even for scripts like Chinese).
+ TimeZone iranTz = TimeZone.getTimeZone("Asia/Tehran");
+ assertEquals("Iran Summer Time", iranTz.getDisplayName(true, TimeZone.LONG, Locale.UK));
+ assertEquals("Iran Daylight Time", iranTz.getDisplayName(true, TimeZone.LONG, Locale.US));
+ assertEquals("Iran Standard Time", iranTz.getDisplayName(false, TimeZone.LONG, Locale.UK));
+ assertEquals("Iran Standard Time", iranTz.getDisplayName(false, TimeZone.LONG, Locale.US));
+ assertEquals("GMT+03:30", iranTz.getDisplayName(false, TimeZone.SHORT, Locale.UK));
+ assertEquals("GMT+04:30", iranTz.getDisplayName(true, TimeZone.SHORT, Locale.UK));
}
public void test_getID() {
diff --git a/luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java b/luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java
new file mode 100644
index 0000000..954665a
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/ResourceLeakageDetector.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2014 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 libcore.java.util;
+
+/**
+ * Detects resource leakages for resources that are protected by <code>CloseGuard</code> mechanism.
+ *
+ * <p>If multiple instances of this are active at the same time, i.e. have been created but not yet
+ * had their {@link #checkForLeaks()} method called then while they will report all the leakages
+ * detected they may report the leakages caused by the code being tested by another detector.
+ *
+ * <p>The underlying CloseGuardMonitor is loaded using reflection to ensure that this will run,
+ * albeit doing nothing, on the reference implementation.
+ */
+public class ResourceLeakageDetector {
+ /** The class for the CloseGuardMonitor, null if not supported. */
+ private static final Class<?> CLOSE_GUARD_MONITOR_CLASS;
+
+ static {
+ ClassLoader classLoader = ResourceLeakageDetector.class.getClassLoader();
+ Class<?> clazz;
+ try {
+ // Make sure that the CloseGuard class exists; this ensures that this is not running
+ // on a RI JVM.
+ classLoader.loadClass("dalvik.system.CloseGuard");
+
+ // Load the monitor class for later instantiation.
+ clazz = classLoader.loadClass("dalvik.system.CloseGuardMonitor");
+
+ } catch (ClassNotFoundException e) {
+ System.err.println("Resource leakage will not be detected; "
+ + "this is expected in the reference implementation");
+ e.printStackTrace(System.err);
+
+ // Ignore, probably running in reference implementation.
+ clazz = null;
+ }
+
+ CLOSE_GUARD_MONITOR_CLASS = clazz;
+ }
+
+ /**
+ * The underlying CloseGuardMonitor that will perform the post test checks for resource
+ * leakage.
+ */
+ private Runnable postTestChecker;
+
+ /**
+ * Create a new detector.
+ *
+ * @return The new {@link ResourceLeakageDetector}, its {@link #checkForLeaks()} method must be
+ * called otherwise it will not clean up properly after itself.
+ */
+ public static ResourceLeakageDetector newDetector()
+ throws Exception {
+ return new ResourceLeakageDetector();
+ }
+
+ private ResourceLeakageDetector()
+ throws Exception {
+ if (CLOSE_GUARD_MONITOR_CLASS != null) {
+ postTestChecker = (Runnable) CLOSE_GUARD_MONITOR_CLASS.newInstance();
+ }
+ }
+
+ /**
+ * Detect any leaks that have arisen since this was created.
+ *
+ * @throws Exception If any leaks were detected.
+ */
+ public void checkForLeaks() throws Exception {
+ // If available check for resource leakage.
+ if (postTestChecker != null) {
+ postTestChecker.run();
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java b/luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java
new file mode 100644
index 0000000..d86c9f2
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/ResourceLeakageDetectorTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2014 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 libcore.java.util;
+
+import dalvik.system.CloseGuard;
+import junit.framework.TestCase;
+
+/**
+ * Test for {@link ResourceLeakageDetector}
+ */
+public class ResourceLeakageDetectorTest extends TestCase {
+ /**
+ * This test will not work on RI as it does not support the <code>CloseGuard</code> or similar
+ * mechanism.
+ */
+ public void testDetectsUnclosedCloseGuard() throws Exception {
+ ResourceLeakageDetector detector = ResourceLeakageDetector.newDetector();
+ try {
+ CloseGuard closeGuard = createCloseGuard();
+ closeGuard.open("open");
+ } finally {
+ try {
+ System.logI("Checking for leaks");
+ detector.checkForLeaks();
+ fail();
+ } catch (AssertionError expected) {
+ }
+ }
+ }
+
+ public void testIgnoresClosedCloseGuard() throws Exception {
+ ResourceLeakageDetector detector = ResourceLeakageDetector.newDetector();
+ try {
+ CloseGuard closeGuard = createCloseGuard();
+ closeGuard.open("open");
+ closeGuard.close();
+ } finally {
+ detector.checkForLeaks();
+ }
+ }
+
+ /**
+ * Private method to ensure that the CloseGuard object is garbage collected.
+ */
+ private CloseGuard createCloseGuard() {
+ final CloseGuard closeGuard = CloseGuard.get();
+ new Object() {
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ closeGuard.warnIfOpen();
+ } finally {
+ super.finalize();
+ }
+ }
+ };
+
+ return closeGuard;
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/TimeZoneTest.java b/luni/src/test/java/libcore/java/util/TimeZoneTest.java
index 08d1e69..0bc02b0 100644
--- a/luni/src/test/java/libcore/java/util/TimeZoneTest.java
+++ b/luni/src/test/java/libcore/java/util/TimeZoneTest.java
@@ -57,6 +57,7 @@ public class TimeZoneTest extends TestCase {
// http://code.google.com/p/android/issues/detail?id=14395
public void testPreHistoricInDaylightTime() throws Exception {
+ Locale.setDefault(Locale.US);
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
TimeZone.setDefault(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
@@ -275,14 +276,6 @@ public class TimeZoneTest extends TestCase {
assertEquals("", failures.toString());
}
- public void testSantiago() throws Exception {
- TimeZone tz = TimeZone.getTimeZone("America/Santiago");
- assertEquals("Chile Summer Time", tz.getDisplayName(true, TimeZone.LONG, Locale.US));
- assertEquals("Chile Standard Time", tz.getDisplayName(false, TimeZone.LONG, Locale.US));
- assertEquals("GMT-03:00", tz.getDisplayName(true, TimeZone.SHORT, Locale.US));
- assertEquals("GMT-04:00", tz.getDisplayName(false, TimeZone.SHORT, Locale.US));
- }
-
// http://b/7955614
public void testApia() throws Exception {
TimeZone tz = TimeZone.getTimeZone("Pacific/Apia");
diff --git a/luni/src/test/java/libcore/java/util/UUIDTest.java b/luni/src/test/java/libcore/java/util/UUIDTest.java
new file mode 100644
index 0000000..61e4ae0
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/UUIDTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2014 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 libcore.java.util;
+
+import java.util.UUID;
+import junit.framework.TestCase;
+
+// There are more tests in the harmony suite:
+// harmony-tests/src/test/java/org/apache/harmony/tests/java/util/UUIDTest.java
+public class UUIDTest extends TestCase {
+
+ public void testFromStringInvalidValues() {
+ try {
+ UUID.fromString("+f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ UUID.fromString("f81d4fae-+7dec-11d0-a765-00a0c91e6bf6");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ UUID.fromString("f81d4fae-7dec-+11d0-a765-00a0c91e6bf6");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ UUID.fromString("f81d4fae-7dec-11d0-+a765-00a0c91e6bf6");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+
+ try {
+ UUID.fromString("f81d4fae-7dec-11d0-a765-+00a0c91e6bf6");
+ fail();
+ } catch (IllegalArgumentException expected) { }
+ }
+
+}
diff --git a/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java b/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java
deleted file mode 100644
index 021cd3f..0000000
--- a/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java
+++ /dev/null
@@ -1,258 +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 libcore.java.util.jar;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import junit.framework.TestCase;
-import libcore.io.Streams;
-import static tests.support.Support_Exec.execAndGetOutput;
-import tests.support.resource.Support_Resources;
-
-
-public class DalvikExecTest extends TestCase {
-
- String execDalvik1(String classpath, String mainClass, String arg1)
- throws IOException, InterruptedException {
- ProcessBuilder builder = new ProcessBuilder();
-
- File dalvikvm = new File("/system/bin/dalvikvm");
- if (dalvikvm.exists()) {
- builder.command().add(dalvikvm.getPath());
- } else {
- builder.command().add("dalvikvm"); // for host mode, assume dalvikvm is on the path
- }
-
- builder.command().add("-Duser.language=en");
- builder.command().add("-Duser.region=US");
- builder.command().add("-Xbootclasspath:" + System.getProperty("java.boot.class.path"));
- builder.command().add("-classpath");
- builder.command().add(classpath);
- builder.command().add(mainClass);
-
- if (arg1 != null) {
- builder.command().add(arg1);
- }
-
- // Create a writable dalvik-cache under ANDROID_DATA.
- // The default dalvik-cache is only writable by the system user (and root).
- String tmp = System.getProperty("java.io.tmpdir");
- builder.environment().put("ANDROID_DATA", tmp);
- new File(tmp, "dalvik-cache").mkdir();
-
- return execAndGetOutput(builder);
- }
-
- String execDalvik (String classpath, String mainClass)
- throws IOException, InterruptedException {
- return execDalvik1(classpath, mainClass, null);
- }
-
- // Execute an existing JAR on dalvikvm using -classpath option.",
- public void test_execExistingJar () throws IOException, InterruptedException {
- String res;
- File jarFile;
- if (System.getProperty("java.vendor").contains("Android")) {
- //
- // Test against Android:
- //
- File tempDir = Support_Resources.createTempFolder();
- jarFile = Support_Resources.copyFile(
- tempDir, null, "cts_dalvikExecTest.jar" );
- res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.HelloWorld");
- assertEquals("Hello Android World!", "Hello Android World!\n", res);
-
- res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.ResourceDumper");
- assertTrue("Android Resource Dumper started",
- res.contains("Android Resource Dumper started"));
- assertTrue("This Resource contains some text.",
- res.contains("This Resource contains some text."));
- } else {
- //
- // Test against RI:
- //
- // Do nothing!
- }
- }
-
- // Create a temp file, fill it with contents according to Dalvik JAR format, and execute it on dalvikvm using -classpath option.",
- public void test_execCreatedJar () throws IOException, InterruptedException {
- File jarFile = File.createTempFile("cts_dalvikExecTest_", ".jar");
- jarFile.deleteOnExit();
-
- // Create a JAR output stream on the temp file:
- JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarFile));
-
- // Define the entry for the classes.dex:
- jarOut.putNextEntry(new JarEntry("classes.dex"));
-
- // Fill in the classes.dex contents, i.e. the Dalvik executable code:
- // (See below for the detailed source code contents.)
- Streams.copy(Support_Resources.getResourceStream("cts_dalvikExecTest_classes.dex"), jarOut);
-
- // Now add a resource file:
- //
- jarOut.putNextEntry(new JarEntry("dalvikExecTest/myResource"));
- jarOut.write("This Resource contains some text.".getBytes());
-
- // Close the stream to the completed JAR file.
- jarOut.close();
-
- // The resulting JAR file contains the classes listed at the end of this text,
- // like the 'cts_dalvikExecTest.jar' as part of the resources, too.
-
- String res;
-
- res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.HelloWorld");
- assertEquals("Hello Android World!", "Hello Android World!\n", res);
-
- res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.ResourceDumper");
- assertTrue("Android Resource Dumper started",
- res.contains("Android Resource Dumper started"));
- assertTrue("This Resource contains some text.",
- res.contains("This Resource contains some text."));
- }
-
-
- /**
- * This test does quite the same as test_execCreatedJar, but includes a manifest.
- * Note however that the Dalvik JAR format does not require this manifest.
- * We just test whether the manifest is placed correctly within the JAR by
- * dumping its contents read as a simple text resource.
- * No! We can't do that so easily either, as there are other (parent) JARs
- * with a manifest inside, taken with precedence.
- * So we will reopen the JAR as a JarFile and check the manifest
- * with a top level end-to-end approach.
- */
- public void test_execCreatedJarWithManifest () throws IOException, InterruptedException {
- File jarFile = File.createTempFile("cts_dalvikExecTest_", ".jar");
- jarFile.deleteOnExit();
-
- // Create the manifest:
- Manifest manifest = new Manifest();
- Attributes attrs = manifest.getMainAttributes();
- attrs.put(Attributes.Name.MANIFEST_VERSION, "3.1415962");
- attrs.put(Attributes.Name.MAIN_CLASS, "dalvikExecTest.HelloWorld");
- attrs.put(Attributes.Name.CLASS_PATH, jarFile.getName());
-
- // Create a JAR output stream on the temp file using the manifest:
- JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest);
-
- // Define the entry for the classes.dex:
- jarOut.putNextEntry(new JarEntry("classes.dex"));
-
- // Fill in the classes.dex contents, i.e. the Dalvik executable code:
- // (See below for the detailed source code contents.)
- Streams.copy(Support_Resources.getResourceStream("cts_dalvikExecTest_classes.dex"), jarOut);
-
- // Now add a resource file:
- //
- jarOut.putNextEntry(new JarEntry("dalvikExecTest/myResource"));
- jarOut.write("This Resource contains some text.".getBytes());
-
- // Close the stream to the completed JAR file.
- jarOut.close();
-
- // The resulting JAR file contains the classes listed at the end of this text,
- // like the 'cts_dalvikExecTest.jar' as part of the resources, too.
-
- String res;
-
- res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.HelloWorld");
- assertEquals("Hello Android World!", "Hello Android World!\n", res);
-
- res = execDalvik(jarFile.getAbsolutePath(), "dalvikExecTest.ResourceDumper");
- assertTrue("Android Resource Dumper started",
- res.contains("Android Resource Dumper started"));
- assertTrue("This Resource contains some text.",
- res.contains("This Resource contains some text."));
-
- // And now reread the manifest:
- //
- JarFile jarIn = new JarFile(jarFile);
- manifest = jarIn.getManifest();
- attrs = manifest.getMainAttributes();
- assertEquals("MANIFEST_VERSION must match!", "3.1415962",
- attrs.get(Attributes.Name.MANIFEST_VERSION));
- assertEquals("MAIN_CLASS must match!", "dalvikExecTest.HelloWorld",
- attrs.get(Attributes.Name.MAIN_CLASS));
- assertEquals("CLASS_PATH must match!", jarFile.getName(),
- attrs.get(Attributes.Name.CLASS_PATH));
- }
-
-
- /*
- * The following two classes are added, here, only for completeness.
- * They form the contents of the dalvikExecTest package contained
- * in the 'cts_dalvikExecTest_classes.dex' resource file.
- */
- /**
- * @hide
- */
- public static class HelloWorld {
-
- public static void main(String[] args) {
- System.out.println("Hello Android World!");
- }
-
- }
-
- public static class ResourceDumper {
-
- static ByteArrayOutputStream outputFrom (InputStream input) throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buffer = new byte[512];
- int total = 0;
- int count;
- count = input.read(buffer);
- while (count != -1) {
- out.write(buffer, 0, count);
- total = total + count;
- count = input.read(buffer);
- }
- return out;
- }
-
- public static void main(String[] args) throws IOException {
- System.out.print("Android Resource Dumper started ");
- String fileName;
- if (args.length >= 1) {
- fileName = args[0];
- System.out.format("for argument '%s'.\n", fileName);
- } else {
- System.out.print("standard ");
- fileName = "myResource";
- System.out.println("for standard 'myResource'.");
- }
- InputStream is = ResourceDumper.class.getResourceAsStream(fileName);
- if (is != null) {
- System.out.println("Resource obtained and being dumped:");
- System.out.println(outputFrom(is).toString());
- }
- }
-
- }
-
-}
diff --git a/luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java b/luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java
new file mode 100644
index 0000000..e5a6cd8
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/StrictJarFileTest.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2013 Google Inc.
+ *
+ * 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 libcore.java.util.jar;
+
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.jar.StrictJarFile;
+import java.util.zip.ZipEntry;
+import libcore.io.Streams;
+
+public class StrictJarFileTest extends TestCase {
+
+ // A well formed jar file with 6 entries.
+ private static final String JAR_1 = "hyts_patch.jar";
+
+ private File resources;
+
+ @Override
+ protected void setUp() {
+ resources = Support_Resources.createTempFolder();
+ }
+
+ public void testConstructor() throws Exception {
+ try {
+ StrictJarFile jarFile = new StrictJarFile("Wrong.file");
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ Support_Resources.copyFile(resources, null, JAR_1);
+ String fileName = (new File(resources, JAR_1)).getCanonicalPath();
+ StrictJarFile jarFile = new StrictJarFile(fileName);
+ jarFile.close();
+ }
+
+ public void testIteration() throws Exception {
+ Support_Resources.copyFile(resources, null, JAR_1);
+ StrictJarFile jarFile = new StrictJarFile(new File(resources, JAR_1).getAbsolutePath());
+
+ Iterator<ZipEntry> it = jarFile.iterator();
+ HashMap<String, ZipEntry> entries = new HashMap<String, ZipEntry>();
+ while (it.hasNext()) {
+ final ZipEntry ze = it.next();
+ entries.put(ze.getName(), ze);
+ }
+
+ assertEquals(6, entries.size());
+ assertTrue(entries.containsKey("META-INF/"));
+
+ assertTrue(entries.containsKey("META-INF/MANIFEST.MF"));
+ ZipEntry ze = entries.get("META-INF/MANIFEST.MF");
+ assertEquals(62, ze.getSize());
+ assertEquals(ZipEntry.DEFLATED, ze.getMethod());
+ assertEquals(61, ze.getCompressedSize());
+
+ assertTrue(entries.containsKey("Blah.txt"));
+ ze = entries.get("Blah.txt");
+ assertEquals(4, ze.getSize());
+ assertEquals(ZipEntry.DEFLATED, ze.getMethod());
+ assertEquals(6, ze.getCompressedSize());
+ assertEquals("Blah", new String(Streams.readFully(jarFile.getInputStream(ze)),
+ Charset.forName("UTF-8")));
+
+ assertTrue(entries.containsKey("foo/"));
+ assertTrue(entries.containsKey("foo/bar/"));
+ assertTrue(entries.containsKey("foo/bar/A.class"));
+ ze = entries.get("foo/bar/A.class");
+ assertEquals(311, ze.getSize());
+ assertEquals(ZipEntry.DEFLATED, ze.getMethod());
+ assertEquals(225, ze.getCompressedSize());
+ }
+
+ public void testFindEntry() throws Exception {
+ Support_Resources.copyFile(resources, null, JAR_1);
+ StrictJarFile jarFile = new StrictJarFile(new File(resources, JAR_1).getAbsolutePath());
+
+ assertNull(jarFile.findEntry("foobar"));
+ assertNull(jarFile.findEntry("blah.txt"));
+ assertNotNull(jarFile.findEntry("Blah.txt"));
+ final ZipEntry ze = jarFile.findEntry("Blah.txt");
+ assertEquals(4, ze.getSize());
+ assertEquals(ZipEntry.DEFLATED, ze.getMethod());
+ assertEquals(6, ze.getCompressedSize());
+ assertEquals("Blah", new String(Streams.readFully(jarFile.getInputStream(ze)),
+ Charset.forName("UTF-8")));
+ }
+
+ public void testGetManifest() throws Exception {
+ Support_Resources.copyFile(resources, null, JAR_1);
+ StrictJarFile jarFile = new StrictJarFile(new File(resources, JAR_1).getAbsolutePath());
+
+ assertNotNull(jarFile.getManifest());
+ assertEquals("1.4.2 (IBM Corporation)", jarFile.getManifest().getMainAttributes().getValue("Created-By"));
+ }
+
+ public void testJarSigning_wellFormed() throws IOException {
+ Support_Resources.copyFile(resources, null, "Integrate.jar");
+ StrictJarFile jarFile = new StrictJarFile(new File(resources, "Integrate.jar").getAbsolutePath());
+ Iterator<ZipEntry> entries = jarFile.iterator();
+ while (entries.hasNext()) {
+ ZipEntry zipEntry = entries.next();
+ jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
+ if ("Test.class".equals(zipEntry.getName())) {
+ assertNotNull(jarFile.getCertificates(zipEntry));
+ assertNotNull(jarFile.getCertificateChains(zipEntry));
+ }
+ }
+ }
+
+ public void testJarSigning_fudgedEntry() throws IOException {
+ Support_Resources.copyFile(resources, null, "Integrate.jar");
+ StrictJarFile jarFile = new StrictJarFile(
+ new File(resources, "Integrate.jar").getAbsolutePath());
+
+ ZipEntry ze = jarFile.findEntry("Test.class");
+ jarFile.getInputStream(ze).skip(Long.MAX_VALUE);
+
+ // Fudge the size so that certificates do not match.
+ ze.setSize(ze.getSize() - 1);
+ try {
+ jarFile.getInputStream(ze).skip(Long.MAX_VALUE);
+ fail();
+ } catch (SecurityException expected) {
+ }
+ }
+
+ public void testJarSigning_modifiedClass() throws IOException {
+ Support_Resources.copyFile(resources, null, "Modified_Class.jar");
+ StrictJarFile jarFile = new StrictJarFile(
+ new File(resources, "Modified_Class.jar").getAbsolutePath());
+
+ ZipEntry ze = jarFile.findEntry("Test.class");
+ try {
+ jarFile.getInputStream(ze).skip(Long.MAX_VALUE);
+ fail();
+ } catch (SecurityException expected) {
+ }
+ }
+
+ public void testJarSigning_brokenMainAttributes() throws Exception {
+ assertThrowsOnInit("Modified_Manifest_MainAttributes.jar");
+ }
+
+ public void testJarSigning_brokenEntryAttributes() throws Exception {
+ assertThrowsOnInit("Modified_Manifest_EntryAttributes.jar");
+ }
+
+ public void testJarSigning_brokenSignatureFile() throws Exception {
+ assertThrowsOnInit("Modified_SF_EntryAttributes.jar");
+ }
+
+ private void assertThrowsOnInit(String name) throws Exception {
+ Support_Resources.copyFile(resources, null, name);
+ try {
+ StrictJarFile jarFile = new StrictJarFile(
+ new File(resources, name).getAbsolutePath());
+ fail();
+ } catch (SecurityException expected) {
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java
index b9d3f1d..693f0c2 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldAbstractPreferencesTest.java
@@ -18,6 +18,7 @@ package libcore.java.util.prefs;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.File;
import java.io.IOException;
import java.util.prefs.AbstractPreferences;
import java.util.prefs.BackingStoreException;
@@ -27,12 +28,17 @@ import java.util.prefs.NodeChangeListener;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
import junit.framework.TestCase;
+import libcore.io.IoUtils;
public final class OldAbstractPreferencesTest extends TestCase {
static final String nodeName = "mock";
+ private PreferencesFactory defaultFactory;
+
AbstractPreferences pref;
AbstractPreferences root;
AbstractPreferences parent = null;
@@ -40,16 +46,24 @@ public final class OldAbstractPreferencesTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
+ File tmpDir = IoUtils.createTemporaryDirectory("OldAbstractPreferencesTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath()));
+
root = (AbstractPreferences) Preferences.userRoot();
- for (String child : root.childrenNames()) {
- root.node(child).removeNode();
- }
- root.clear();
+ assertEquals(0, root.childrenNames().length);
+ assertEquals(0, root.keys().length);
parent = (AbstractPreferences) Preferences.userNodeForPackage(getClass());
pref = (AbstractPreferences) parent.node(nodeName);
}
+ @Override
+ public void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ super.tearDown();
+ }
+
public void testToString() {
assertTrue(pref.toString().contains(nodeName));
}
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java b/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java
index 93ba485..ea8cb39 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldFilePreferencesImplTest.java
@@ -16,11 +16,32 @@
package libcore.java.util.prefs;
+import java.io.File;
import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
import junit.framework.TestCase;
+import libcore.io.IoUtils;
+
public final class OldFilePreferencesImplTest extends TestCase {
+ private PreferencesFactory defaultFactory;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ File tmpDir = IoUtils.createTemporaryDirectory("OldFilePreferencesImplTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath()));
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ super.tearDown();
+ }
+
// AndroidOnly: the RI can't remove nodes created in the system root.
public void testSystemChildNodes() throws Exception {
Preferences sroot = Preferences.systemRoot().node("test");
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java b/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java
index f2d483e..7ba1dfe 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java
@@ -16,15 +16,36 @@
package libcore.java.util.prefs;
+import java.io.File;
import java.util.prefs.AbstractPreferences;
import java.util.prefs.BackingStoreException;
import java.util.prefs.NodeChangeEvent;
import java.util.prefs.NodeChangeListener;
import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
import junit.framework.TestCase;
+import libcore.io.IoUtils;
+
public final class OldNodeChangeEventTest extends TestCase {
+ private PreferencesFactory defaultFactory;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ File tmpDir = IoUtils.createTemporaryDirectory("OldNodeChangeEventTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath()));
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ super.tearDown();
+ }
+
public void testGetChild() throws BackingStoreException {
AbstractPreferences parent = (AbstractPreferences) Preferences
.userNodeForPackage(Preferences.class);
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java b/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java
index acdbd69..d77a11c 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java
@@ -16,14 +16,35 @@
package libcore.java.util.prefs;
+import java.io.File;
import java.util.prefs.AbstractPreferences;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
import junit.framework.TestCase;
+import libcore.io.IoUtils;
+
public final class OldPreferenceChangeEventTest extends TestCase {
+ private PreferencesFactory defaultFactory;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ File tmpDir = IoUtils.createTemporaryDirectory("OldPreferenceChangeEventTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath()));
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ super.tearDown();
+ }
+
public void testGetKey() {
AbstractPreferences parent = (AbstractPreferences) Preferences
.userNodeForPackage(Preferences.class);
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java
index f8a8154..7245af7 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java
@@ -16,6 +16,7 @@
package libcore.java.util.prefs;
+import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
@@ -25,7 +26,9 @@ import java.util.prefs.NodeChangeListener;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
import junit.framework.TestCase;
+import libcore.io.IoUtils;
public final class OldPreferencesTest extends TestCase {
@@ -48,8 +51,14 @@ public final class OldPreferencesTest extends TestCase {
longValue = value.toString();
}
- @Override protected void setUp() throws Exception {
+ private PreferencesFactory defaultFactory;
+
+ @Override
+ protected void setUp() throws Exception {
super.setUp();
+ final File tmpDir = IoUtils.createTemporaryDirectory("OldPreferenceTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new PreferencesTest.TestPreferencesFactory(tmpDir.getAbsolutePath()));
Preferences pref = Preferences.userNodeForPackage(Preferences.class);
for (String child : pref.childrenNames()) {
@@ -58,6 +67,11 @@ public final class OldPreferencesTest extends TestCase {
pref.clear();
}
+ @Override
+ protected void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ }
+
public void testAbstractMethods() throws IOException, BackingStoreException {
Preferences p = new MockPreferences();
p.absolutePath();
diff --git a/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java
index 1560fbe..6c57ef9 100644
--- a/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/PreferencesTest.java
@@ -19,17 +19,58 @@ package libcore.java.util.prefs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
+import java.util.prefs.FilePreferencesImpl;
import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
import junit.framework.TestCase;
+import libcore.io.IoUtils;
public final class PreferencesTest extends TestCase {
/**
+ * A preferences factory rooted at a given path.
+ */
+ public static final class TestPreferencesFactory implements PreferencesFactory {
+ private final Preferences userPrefs;
+ private final Preferences systemPrefs;
+
+ public TestPreferencesFactory(String root) {
+ userPrefs = new FilePreferencesImpl(root + "/user", true);
+ systemPrefs = new FilePreferencesImpl(root + "/system", false);
+ }
+
+ public Preferences userRoot() {
+ return userPrefs;
+ }
+
+ public Preferences systemRoot() {
+ return systemPrefs;
+ }
+ }
+
+ private PreferencesFactory defaultFactory;
+ private File temporaryDirectory;
+
+ @Override
+ public void setUp() throws Exception {
+ temporaryDirectory = IoUtils.createTemporaryDirectory("PreferencesTest");
+ defaultFactory = Preferences.setPreferencesFactory(
+ new TestPreferencesFactory(temporaryDirectory.getAbsolutePath()));
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ Preferences.setPreferencesFactory(defaultFactory);
+ }
+
+ /**
* The preferences API is designed to be hostile towards files that exist
* where it wants to store its XML data. http://b/3431233
*/
public void testPreferencesClobbersExistingFiles() throws Exception {
- File userPrefs = new File(System.getProperty("user.home") + "/.java/.userPrefs/prefs.xml");
+ final File userPrefsDir = new File(temporaryDirectory + "/user");
+ final File userPrefs = new File(userPrefsDir, "prefs.xml");
+ assertTrue(userPrefs.createNewFile());
FileWriter writer = new FileWriter(userPrefs);
writer.write("lamb");
writer.close();
diff --git a/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java
index a28fae5..494520a 100644
--- a/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/GZIPInputStreamTest.java
@@ -18,22 +18,29 @@ package libcore.java.util.zip;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+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.Arrays;
import java.util.Random;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import junit.framework.TestCase;
+import libcore.io.IoUtils;
+import libcore.io.Streams;
public final class GZIPInputStreamTest extends TestCase {
+
+ private static final byte[] HELLO_WORLD_GZIPPED = new byte[] {
+ 31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 87, 8, -49,
+ 47, -54, 73, 1, 0, 86, -79, 23, 74, 11, 0, 0, 0
+ };
+
public void testShortMessage() throws IOException {
- byte[] data = new byte[] {
- 31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 87, 8, -49,
- 47, -54, 73, 1, 0, 86, -79, 23, 74, 11, 0, 0, 0
- };
- assertEquals("Hello World", new String(gunzip(data), "UTF-8"));
+ assertEquals("Hello World", new String(gunzip(HELLO_WORLD_GZIPPED), "UTF-8"));
}
public void testLongMessage() throws IOException {
@@ -59,15 +66,114 @@ public final class GZIPInputStreamTest extends TestCase {
in.close();
}
+ // https://code.google.com/p/android/issues/detail?id=63873
+ public void testMultipleMembers() throws Exception {
+ final int length = HELLO_WORLD_GZIPPED.length;
+ byte[] data = new byte[length * 2];
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length);
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, length, length);
+
+ assertEquals("Hello WorldHello World", new String(gunzip(data), "UTF-8"));
+ }
+
+ // https://code.google.com/p/android/issues/detail?id=63873
+ public void testTrailingNonGzipData() throws Exception {
+ final int length = HELLO_WORLD_GZIPPED.length;
+ // 50 bytes of 0s at the end of the first message.
+ byte[] data = new byte[length + 50];
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length);
+ assertEquals("Hello World", new String(gunzip(data), "UTF-8"));
+ }
+
+ // https://code.google.com/p/android/issues/detail?id=63873
+ //
+ // Differences from the RI: Tests show the RI ignores *some* types of partial
+ // data but not others and this test case fails as a result. Our implementation
+ // will throw if it sees the gzip magic sequence at the end of a member
+ // but malformed / invalid data after.
+ public void testTrailingHeaderAndPartialMember() throws Exception {
+ final int length = HELLO_WORLD_GZIPPED.length;
+ // Copy just the header from HELLO_WORLD_GZIPPED so that our input
+ // stream becomes one complete member + a header member.
+ byte[] data = new byte[length + 10];
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length);
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, length, 10);
+
+ try {
+ gunzip(data);
+ fail();
+ } catch (EOFException expected) {
+ }
+
+ // Copy just the header from HELLO_WORLD_GZIPPED so that our input
+ // stream becomes one complete member + a header member.
+ data = new byte[length + 18];
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, 0, length);
+ System.arraycopy(HELLO_WORLD_GZIPPED, 0, data, length, 18);
+
+ try {
+ gunzip(data);
+ fail();
+ } catch (EOFException expected) {
+ }
+ }
+
+ // https://code.google.com/p/android/issues/detail?id=66409
+ public void testMultipleMembersWithCustomBufferSize() throws Exception {
+ final int[] memberSizes = new int[] { 1000, 2000 };
+
+ // We don't care what the exact contents of this file is, as long
+ // as the file has multiple members, and that the (compressed) size of
+ // the second member is larger than the size of the input buffer.
+ //
+ // There's no way to achieve this for a GZIPOutputStream so we generate
+ // pseudo-random sequence of bytes and assert that they don't compress
+ // well.
+ final Random r = new Random(10);
+ byte[] bytes = new byte[3000];
+ r.nextBytes(bytes);
+
+ File f = File.createTempFile("GZIPInputStreamTest", ".gzip");
+ int offset = 0;
+ for (int size : memberSizes) {
+ GZIPOutputStream gzos = null;
+ try {
+ FileOutputStream fos = new FileOutputStream(f, true /* append */);
+ gzos = new GZIPOutputStream(fos, size + 1);
+ gzos.write(bytes, offset, size);
+ offset += size;
+ gzos.finish();
+ } finally {
+ IoUtils.closeQuietly(gzos);
+ }
+ }
+
+ assertTrue(f.length() > 2048);
+
+ FileInputStream fis = new FileInputStream(f);
+ GZIPInputStream gzip = null;
+ try {
+ gzip = new GZIPInputStream(fis, memberSizes[0]);
+ byte[] unzipped = Streams.readFully(gzip);
+ assertTrue(Arrays.equals(bytes, unzipped));
+ } finally {
+ IoUtils.closeQuietly(gzip);
+ }
+ }
+
public static byte[] gunzip(byte[] bytes) throws IOException {
- InputStream in = new GZIPInputStream(new ByteArrayInputStream(bytes));
+ ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
+ InputStream in = new GZIPInputStream(bis);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
+
+ byte[] outArray = out.toByteArray();
in.close();
- return out.toByteArray();
+
+ return outArray;
}
}
diff --git a/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java
index 55e45bc..3b785c9 100644
--- a/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java
@@ -16,17 +16,14 @@
package libcore.java.util.zip;
-import java.io.ByteArrayInputStream;
+import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
-import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
-import java.util.zip.InflaterInputStream;
-import junit.framework.TestCase;
public final class GZIPOutputStreamTest extends TestCase {
public void testShortMessage() throws IOException {
@@ -67,4 +64,15 @@ public final class GZIPOutputStreamTest extends TestCase {
in.close();
}
+ // https://code.google.com/p/android/issues/detail?id=62589
+ public void testFlushAfterFinish() throws Exception {
+ byte[] responseBytes = "Some data to gzip".getBytes();
+ ByteArrayOutputStream output = new ByteArrayOutputStream(responseBytes.length);
+ GZIPOutputStream gzipOutputStream = new GZIPOutputStream(output, true);
+ gzipOutputStream.write(responseBytes);
+ gzipOutputStream.finish();
+ // Calling flush() after finish() shouldn't throw.
+ gzipOutputStream.flush();
+ gzipOutputStream.close();
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java
index 9f2864b..2104655 100644
--- a/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java
@@ -17,21 +17,14 @@
package libcore.java.util.zip;
-import tests.support.Support_PlatformFile;
-import tests.support.resource.Support_Resources;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
-import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
-import java.security.Permission;
-import java.util.Enumeration;
import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
import java.util.zip.ZipFile;
+import tests.support.resource.Support_Resources;
public class OldZipFileTest extends junit.framework.TestCase {
@@ -150,24 +143,15 @@ public class OldZipFileTest extends junit.framework.TestCase {
@Override
protected void setUp() throws IOException {
// Create a local copy of the file since some tests want to alter information.
- tempFileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (tempFileName.charAt(tempFileName.length() - 1) == separator.charAt(0)) {
- tempFileName = Support_PlatformFile.getNewPlatformFile(tempFileName, "gabba.zip");
- } else {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName + separator, "gabba.zip");
- }
-
- File f = new File(tempFileName);
- f.delete();
+ File tempFile = File.createTempFile("OldZipFileTest", "zip");
+ tempFileName = tempFile.getAbsolutePath();
InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
- FileOutputStream fos = new FileOutputStream(f);
+ FileOutputStream fos = new FileOutputStream(tempFile);
byte[] rbuf = getAllBytesFromStream(is);
fos.write(rbuf, 0, rbuf.length);
is.close();
fos.close();
- zfile = new ZipFile(f);
+ zfile = new ZipFile(tempFile);
}
/**
@@ -179,18 +163,5 @@ public class OldZipFileTest extends junit.framework.TestCase {
// Note zfile is a user-defined zip file used by other tests and
// should not be deleted
zfile.close();
- tempFileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (tempFileName.charAt(tempFileName.length() - 1) == separator
- .charAt(0)) {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName, "gabba.zip");
- } else {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName + separator, "gabba.zip");
- }
-
- File f = new File(tempFileName);
- f.delete();
}
}
diff --git a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
index 60af4d0..a9ff56f 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
@@ -21,11 +21,17 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
import java.util.Random;
+import java.util.Set;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
@@ -34,6 +40,8 @@ import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
public final class ZipFileTest extends TestCase {
/**
* Exercise Inflater's ability to refill the zlib's input buffer. As of this
@@ -160,7 +168,7 @@ public final class ZipFileTest extends TestCase {
}
assertEquals(expectedLength, count);
-
+ zip.close();
}
public void testInflatingStreamsRequiringZipRefill() throws IOException {
@@ -218,21 +226,23 @@ public final class ZipFileTest extends TestCase {
byte[] writeBuffer = new byte[8192];
Random random = new Random();
- ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(result)));
- for (int entry = 0; entry < entryCount; ++entry) {
- ZipEntry ze = new ZipEntry(Integer.toHexString(entry));
- out.putNextEntry(ze);
+ ZipOutputStream out = createZipOutputStream(result);
+ try {
+ for (int entry = 0; entry < entryCount; ++entry) {
+ ZipEntry ze = new ZipEntry(Integer.toHexString(entry));
+ out.putNextEntry(ze);
+
+ for (int i = 0; i < entrySize; i += writeBuffer.length) {
+ random.nextBytes(writeBuffer);
+ int byteCount = Math.min(writeBuffer.length, entrySize - i);
+ out.write(writeBuffer, 0, byteCount);
+ }
- for (int i = 0; i < entrySize; i += writeBuffer.length) {
- random.nextBytes(writeBuffer);
- int byteCount = Math.min(writeBuffer.length, entrySize - i);
- out.write(writeBuffer, 0, byteCount);
+ out.closeEntry();
}
-
- out.closeEntry();
+ } finally {
+ out.close();
}
-
- out.close();
return result;
}
@@ -468,4 +478,30 @@ public final class ZipFileTest extends TestCase {
out.closeEntry();
out.close();
}
+
+ /**
+ * RI does not allow reading of an empty zip using a {@link ZipFile}.
+ */
+ public void testConstructorFailsWhenReadingEmptyZipArchive() throws IOException {
+
+ File resources = Support_Resources.createTempFolder();
+ File emptyZip = Support_Resources.copyFile(
+ resources, "java/util/zip", "EmptyArchive.zip");
+
+ try {
+ // The following should fail with an exception but if it doesn't then we need to clean
+ // up the resource so we need a reference to it.
+ ZipFile zipFile = new ZipFile(emptyZip);
+
+ // Clean up the resource.
+ try {
+ zipFile.close();
+ } catch (Exception e) {
+ // Ignore
+ }
+ fail();
+ } catch (ZipException expected) {
+ // expected
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java
index cb98322..49990a3 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipInputStreamTest.java
@@ -20,15 +20,24 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
import java.util.Random;
+import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
+
import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
public final class ZipInputStreamTest extends TestCase {
+
public void testShortMessage() throws IOException {
byte[] data = "Hello World".getBytes("UTF-8");
byte[] zipped = ZipOutputStreamTest.zip("short", data);
@@ -59,4 +68,18 @@ public final class ZipInputStreamTest extends TestCase {
in.close();
return out.toByteArray();
}
+
+ /**
+ * Reference implementation allows reading of empty zip using a {@link ZipInputStream}.
+ */
+ public void testReadEmpty() throws IOException {
+ InputStream emptyZipIn = Support_Resources.getStream("java/util/zip/EmptyArchive.zip");
+ ZipInputStream in = new ZipInputStream(emptyZipIn);
+ try {
+ ZipEntry entry = in.getNextEntry();
+ assertNull("An empty zip has no entries", entry);
+ } finally {
+ in.close();
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java
index e7c518f..e69f010 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipOutputStreamTest.java
@@ -16,15 +16,16 @@
package libcore.java.util.zip;
-import java.io.ByteArrayInputStream;
+import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
+import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
import junit.framework.TestCase;
@@ -60,4 +61,30 @@ public final class ZipOutputStreamTest extends TestCase {
zippedOut.close();
return bytesOut.toByteArray();
}
+
+ /**
+ * Reference implementation does NOT allow writing of an empty zip using a
+ * {@link ZipOutputStream}.
+ */
+ public void testCreateEmpty() throws IOException {
+ File result = File.createTempFile("ZipFileTest", "zip");
+ ZipOutputStream out =
+ new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(result)));
+ try {
+ out.close();
+ fail("Close on empty stream failed to throw exception");
+ } catch (ZipException e) {
+ // expected
+ }
+ }
+
+ /** Regression test for null comment causing a NullPointerException during write. */
+ public void testNullComment() throws IOException {
+ ZipOutputStream out = new ZipOutputStream(new ByteArrayOutputStream());
+ out.setComment(null);
+ out.putNextEntry(new ZipEntry("name"));
+ out.write(new byte[1]);
+ out.closeEntry();
+ out.finish();
+ }
}
diff --git a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
index 28d95f2..67ed36c 100644
--- a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
@@ -18,8 +18,10 @@ package libcore.javax.crypto;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
@@ -30,37 +32,134 @@ import junit.framework.TestCase;
public final class CipherInputStreamTest extends TestCase {
- private final byte[] keyBytes = { 127, -2, -95, -39, 35, 118, 121, -92 };
+ private final byte[] aesKeyBytes = {
+ (byte) 0x50, (byte) 0x98, (byte) 0xF2, (byte) 0xC3, (byte) 0x85, (byte) 0x23,
+ (byte) 0xA3, (byte) 0x33, (byte) 0x50, (byte) 0x98, (byte) 0xF2, (byte) 0xC3,
+ (byte) 0x85, (byte) 0x23, (byte) 0xA3, (byte) 0x33,
+ };
+
+ private final byte[] aesIvBytes = {
+ (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ };
+
+ private final byte[] aesCipherText = {
+ (byte) 0x2F, (byte) 0x2C, (byte) 0x74, (byte) 0x31, (byte) 0xFF, (byte) 0xCC,
+ (byte) 0x28, (byte) 0x7D, (byte) 0x59, (byte) 0xBD, (byte) 0xE5, (byte) 0x0A,
+ (byte) 0x30, (byte) 0x7E, (byte) 0x6A, (byte) 0x4A
+ };
+
+ private final byte[] rc4CipherText = {
+ (byte) 0x88, (byte) 0x01, (byte) 0xE3, (byte) 0x52, (byte) 0x7B
+ };
+
private final String plainText = "abcde";
- private final byte[] cipherText = { 121, -124, -106, 43, -55, -67, -105, -75 };
private SecretKey key;
+ private SecretKey rc4Key;
+ private AlgorithmParameterSpec iv;
@Override protected void setUp() throws Exception {
- key = new SecretKeySpec(keyBytes, "DES");
+ key = new SecretKeySpec(aesKeyBytes, "AES");
+ rc4Key = new SecretKeySpec(aesKeyBytes, "RC4");
+ iv = new IvParameterSpec(aesIvBytes);
+ }
+
+ private static class MeasuringInputStream extends FilterInputStream {
+ private int totalRead;
+
+ protected MeasuringInputStream(InputStream in) {
+ super(in);
+ }
+
+ @Override
+ public int read() throws IOException {
+ int c = super.read();
+ totalRead++;
+ return c;
+ }
+
+ @Override
+ public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
+ int numRead = super.read(buffer, byteOffset, byteCount);
+ if (numRead != -1) {
+ totalRead += numRead;
+ }
+ return numRead;
+ }
+
+ public int getTotalRead() {
+ return totalRead;
+ }
+ }
+
+ public void testAvailable() throws Exception {
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, iv);
+ MeasuringInputStream in = new MeasuringInputStream(new ByteArrayInputStream(aesCipherText));
+ InputStream cin = new CipherInputStream(in, cipher);
+ assertTrue(cin.read() != -1);
+ assertEquals(aesCipherText.length, in.getTotalRead());
+ }
+
+ public void testDecrypt_NullInput_Discarded() throws Exception {
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, iv);
+ InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher);
+ int discard = 3;
+ while (discard != 0) {
+ discard -= in.read(null, 0, discard);
+ }
+ byte[] bytes = readAll(in);
+ assertEquals(Arrays.toString(plainText.substring(3).getBytes("UTF-8")),
+ Arrays.toString(bytes));
}
public void testEncrypt() throws Exception {
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.ENCRYPT_MODE, key);
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.ENCRYPT_MODE, key, iv);
InputStream in = new CipherInputStream(
new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher);
byte[] bytes = readAll(in);
- assertEquals(Arrays.toString(cipherText), Arrays.toString(bytes));
+ assertEquals(Arrays.toString(aesCipherText), Arrays.toString(bytes));
+
+ // Reading again shouldn't throw an exception.
+ assertEquals(-1, in.read());
+ }
+
+ public void testEncrypt_RC4() throws Exception {
+ Cipher cipher = Cipher.getInstance("RC4");
+ cipher.init(Cipher.ENCRYPT_MODE, rc4Key);
+ InputStream in = new CipherInputStream(
+ new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher);
+ byte[] bytes = readAll(in);
+ assertEquals(Arrays.toString(rc4CipherText), Arrays.toString(bytes));
+
+ // Reading again shouldn't throw an exception.
+ assertEquals(-1, in.read());
}
public void testDecrypt() throws Exception {
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.DECRYPT_MODE, key);
- InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher);
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, iv);
+ InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher);
byte[] bytes = readAll(in);
- assertEquals(plainText, new String(bytes, "UTF-8"));
+ assertEquals(Arrays.toString(plainText.getBytes("UTF-8")), Arrays.toString(bytes));
+ }
+
+ public void testDecrypt_RC4() throws Exception {
+ Cipher cipher = Cipher.getInstance("RC4");
+ cipher.init(Cipher.DECRYPT_MODE, rc4Key);
+ InputStream in = new CipherInputStream(new ByteArrayInputStream(rc4CipherText), cipher);
+ byte[] bytes = readAll(in);
+ assertEquals(Arrays.toString(plainText.getBytes("UTF-8")), Arrays.toString(bytes));
}
public void testSkip() throws Exception {
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.DECRYPT_MODE, key);
- InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher);
- assertTrue(in.skip(5) > 0);
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, iv);
+ InputStream in = new CipherInputStream(new ByteArrayInputStream(aesCipherText), cipher);
+ assertTrue(in.skip(5) >= 0);
}
private byte[] readAll(InputStream in) throws IOException {
@@ -75,10 +174,33 @@ public final class CipherInputStreamTest extends TestCase {
public void testCipherInputStream_TruncatedInput_Failure() throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(new byte[16], "AES"),
- new IvParameterSpec(new byte[16]));
+ cipher.init(Cipher.DECRYPT_MODE, key, iv);
InputStream is = new CipherInputStream(new ByteArrayInputStream(new byte[31]), cipher);
is.read(new byte[4]);
is.close();
}
+
+ public void testCipherInputStream_NullInputStream_Failure() throws Exception {
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, iv);
+ InputStream is = new CipherInputStream(null, cipher);
+ try {
+ is.read();
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ byte[] buffer = new byte[128];
+ try {
+ is.read(buffer);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ is.read(buffer, 0, buffer.length);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/javax/crypto/CipherTest.java b/luni/src/test/java/libcore/javax/crypto/CipherTest.java
index 7922a04..c89886c 100644
--- a/luni/src/test/java/libcore/javax/crypto/CipherTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/CipherTest.java
@@ -26,14 +26,13 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
-import java.security.interfaces.RSAPrivateKey;
-import java.security.interfaces.RSAPublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
@@ -53,6 +52,7 @@ import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.ShortBufferException;
+import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
@@ -60,10 +60,12 @@ import javax.crypto.spec.SecretKeySpec;
import junit.framework.TestCase;
import libcore.java.security.StandardNames;
import libcore.java.security.TestKeyStore;
-import libcore.util.EmptyArray;
public final class CipherTest extends TestCase {
+ /** GCM tag size used for tests. */
+ private static final int GCM_TAG_SIZE_BITS = 96;
+
private static final String[] RSA_PROVIDERS = ((StandardNames.IS_RI)
? new String[] { "SunJCE" }
: new String[] { "BC" , "AndroidOpenSSL" });
@@ -72,27 +74,6 @@ public final class CipherTest extends TestCase {
? new String[] { "SunJCE" }
: new String[] { "BC", "AndroidOpenSSL" });
- private static final boolean IS_UNLIMITED;
- static {
- boolean is_unlimited;
- if (StandardNames.IS_RI) {
- try {
- String algorithm = "PBEWITHMD5ANDTRIPLEDES";
- Cipher.getInstance(algorithm).init(getEncryptMode(algorithm),
- getEncryptKey(algorithm),
- getEncryptAlgorithmParameterSpec(algorithm));
- is_unlimited = true;
- } catch (Exception e) {
- is_unlimited = false;
- System.out.println("WARNING: Some tests disabled due to lack of "
- + "'Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files'");
- }
- } else {
- is_unlimited = true;
- }
- IS_UNLIMITED = is_unlimited;
- }
-
private static boolean isSupported(String algorithm, String provider) {
if (algorithm.equals("RC2")) {
return false;
@@ -117,12 +98,16 @@ public final class CipherTest extends TestCase {
return false;
}
}
- // stream modes CFB, CTR, CTS, OFB with PKCS5Padding don't really make sense
+ // stream modes CFB, CTR, CTS, OFB with PKCS5Padding or PKCS7Padding don't really make sense
if (!provider.equals("AndroidOpenSSL") &&
(algorithm.equals("AES/CFB/PKCS5PADDING")
+ || algorithm.equals("AES/CFB/PKCS7PADDING")
|| algorithm.equals("AES/CTR/PKCS5PADDING")
+ || algorithm.equals("AES/CTR/PKCS7PADDING")
|| algorithm.equals("AES/CTS/PKCS5PADDING")
- || algorithm.equals("AES/OFB/PKCS5PADDING"))) {
+ || algorithm.equals("AES/CTS/PKCS7PADDING")
+ || algorithm.equals("AES/OFB/PKCS5PADDING")
+ || algorithm.equals("AES/OFB/PKCS7PADDING"))) {
return false;
}
return true;
@@ -138,7 +123,7 @@ public final class CipherTest extends TestCase {
return false;
}
// AESWRAP should be used instead, fails with BC and SunJCE otherwise.
- if (algorithm.startsWith("AES")) {
+ if (algorithm.startsWith("AES") || algorithm.startsWith("DESEDE")) {
return false;
}
return true;
@@ -165,6 +150,12 @@ public final class CipherTest extends TestCase {
if (algorithm.startsWith("AES/")) {
return "AES";
}
+ if (algorithm.equals("GCM")) {
+ return "AES";
+ }
+ if (algorithm.startsWith("DESEDE/")) {
+ return "DESEDE";
+ }
if (algorithm.equals("PBEWITHMD5AND128BITAES-CBC-OPENSSL")) {
return "AES";
}
@@ -240,6 +231,11 @@ public final class CipherTest extends TestCase {
return algorithm.startsWith("PBE");
}
+ private static boolean isStreamMode(String algorithm) {
+ return algorithm.contains("/CTR/") || algorithm.contains("/OFB")
+ || algorithm.contains("/CFB");
+ }
+
private static Map<String, Key> ENCRYPT_KEYS = new HashMap<String, Key>();
private synchronized static Key getEncryptKey(String algorithm) throws Exception {
Key key = ENCRYPT_KEYS.get(algorithm);
@@ -285,17 +281,24 @@ public final class CipherTest extends TestCase {
static {
setExpectedBlockSize("AES", 16);
setExpectedBlockSize("AES/CBC/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CBC/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CBC/NOPADDING", 16);
setExpectedBlockSize("AES/CFB/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CFB/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CFB/NOPADDING", 16);
setExpectedBlockSize("AES/CTR/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CTR/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CTR/NOPADDING", 16);
setExpectedBlockSize("AES/CTS/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/CTS/PKCS7PADDING", 16);
setExpectedBlockSize("AES/CTS/NOPADDING", 16);
setExpectedBlockSize("AES/ECB/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/ECB/PKCS7PADDING", 16);
setExpectedBlockSize("AES/ECB/NOPADDING", 16);
setExpectedBlockSize("AES/OFB/PKCS5PADDING", 16);
+ setExpectedBlockSize("AES/OFB/PKCS7PADDING", 16);
setExpectedBlockSize("AES/OFB/NOPADDING", 16);
+ setExpectedBlockSize("GCM", 16);
setExpectedBlockSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", 16);
setExpectedBlockSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", 16);
setExpectedBlockSize("PBEWITHMD5AND256BITAES-CBC-OPENSSL", 16);
@@ -324,6 +327,24 @@ public final class CipherTest extends TestCase {
setExpectedBlockSize("PBEWITHSHA1ANDDES", 8);
setExpectedBlockSize("DESEDE", 8);
+ setExpectedBlockSize("DESEDE/CBC/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CBC/PKCS7PADDING", 8);
+ setExpectedBlockSize("DESEDE/CBC/NOPADDING", 8);
+ setExpectedBlockSize("DESEDE/CFB/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CFB/PKCS7PADDING", 8);
+ setExpectedBlockSize("DESEDE/CFB/NOPADDING", 8);
+ setExpectedBlockSize("DESEDE/CTR/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CTR/PKCS7PADDING", 8);
+ setExpectedBlockSize("DESEDE/CTR/NOPADDING", 8);
+ setExpectedBlockSize("DESEDE/CTS/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/CTS/PKCS7PADDING", 8);
+ setExpectedBlockSize("DESEDE/CTS/NOPADDING", 8);
+ setExpectedBlockSize("DESEDE/ECB/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/ECB/PKCS7PADDING", 8);
+ setExpectedBlockSize("DESEDE/ECB/NOPADDING", 8);
+ setExpectedBlockSize("DESEDE/OFB/PKCS5PADDING", 8);
+ setExpectedBlockSize("DESEDE/OFB/PKCS7PADDING", 8);
+ setExpectedBlockSize("DESEDE/OFB/NOPADDING", 8);
setExpectedBlockSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", 8);
setExpectedBlockSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", 8);
setExpectedBlockSize("PBEWITHMD5ANDTRIPLEDES", 8);
@@ -423,11 +444,18 @@ public final class CipherTest extends TestCase {
setExpectedOutputSize("AES", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 16);
+ setExpectedOutputSize("GCM", Cipher.ENCRYPT_MODE, GCM_TAG_SIZE_BITS / 8);
setExpectedOutputSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", 16);
setExpectedOutputSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", 16);
setExpectedOutputSize("PBEWITHMD5AND256BITAES-CBC-OPENSSL", 16);
@@ -439,17 +467,28 @@ public final class CipherTest extends TestCase {
setExpectedOutputSize("PBEWITHSHAAND256BITAES-CBC-BC", 16);
// AndroidOpenSSL returns zero for the non-block ciphers
setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
+ setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, "AndroidOpenSSL", 0);
setExpectedOutputSize("AES", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CTR/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CTR/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/CTS/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/CTS/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("AES/OFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("AES/OFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("GCM", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5AND128BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5AND192BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5AND256BITAES-CBC-OPENSSL", Cipher.DECRYPT_MODE, 0);
@@ -461,7 +500,13 @@ public final class CipherTest extends TestCase {
setExpectedOutputSize("PBEWITHSHAAND256BITAES-CBC-BC", Cipher.DECRYPT_MODE, 0);
// AndroidOpenSSL returns the block size for the block ciphers
setExpectedOutputSize("AES/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
+ setExpectedOutputSize("AES/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
setExpectedOutputSize("AES/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
+ setExpectedOutputSize("AES/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 16);
+ setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
+ setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
+ setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
+ setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, "AndroidOpenSSL", 8);
if (StandardNames.IS_RI) {
setExpectedOutputSize("AESWRAP", Cipher.WRAP_MODE, 8);
@@ -486,13 +531,44 @@ public final class CipherTest extends TestCase {
setExpectedOutputSize("PBEWITHMD5ANDDES", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHSHA1ANDDES", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CBC/NOPADDING", 0);
+ setExpectedOutputSize("DESEDE/CFB/NOPADDING", 0);
+ setExpectedOutputSize("DESEDE/CTR/NOPADDING", 0);
+ setExpectedOutputSize("DESEDE/CTS/NOPADDING", 0);
+ setExpectedOutputSize("DESEDE/ECB/NOPADDING", 0);
+ setExpectedOutputSize("DESEDE/OFB/NOPADDING", 0);
+
setExpectedOutputSize("DESEDE", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CTR/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CTR/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CTS/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/CTS/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/OFB/PKCS5PADDING", Cipher.ENCRYPT_MODE, 8);
+ setExpectedOutputSize("DESEDE/OFB/PKCS7PADDING", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHMD5ANDTRIPLEDES", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("PBEWITHSHA1ANDDESEDE", Cipher.ENCRYPT_MODE, 8);
setExpectedOutputSize("DESEDE", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CBC/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CBC/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CTR/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CTR/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CTS/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/CTS/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/ECB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/ECB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/OFB/PKCS5PADDING", Cipher.DECRYPT_MODE, 0);
+ setExpectedOutputSize("DESEDE/OFB/PKCS7PADDING", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHSHAAND2-KEYTRIPLEDES-CBC", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHSHAAND3-KEYTRIPLEDES-CBC", Cipher.DECRYPT_MODE, 0);
setExpectedOutputSize("PBEWITHMD5ANDTRIPLEDES", Cipher.DECRYPT_MODE, 0);
@@ -542,6 +618,8 @@ public final class CipherTest extends TestCase {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 };
+ private static byte[] EIGHT_BYTE_BLOCK_PLAIN_TEXT = new byte[] { 0x0a, 0x0b, 0x0c, 0x00,
+ 0x00, 0x00, 0x00, 0x00 };
private static byte[] PKCS1_BLOCK_TYPE_00_PADDED_PLAIN_TEXT = new byte[] {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -638,6 +716,11 @@ public final class CipherTest extends TestCase {
|| algorithm.equals("AES/ECB/NOPADDING")) {
return SIXTEEN_BYTE_BLOCK_PLAIN_TEXT;
}
+ if (algorithm.equals("DESEDE")
+ || algorithm.equals("DESEDE/CBC/NOPADDING")
+ || algorithm.equals("DESEDE/ECB/NOPADDING")) {
+ return EIGHT_BYTE_BLOCK_PLAIN_TEXT;
+ }
return ORIGINAL_PLAIN_TEXT;
}
@@ -649,6 +732,11 @@ public final class CipherTest extends TestCase {
|| algorithm.equals("AES/ECB/NOPADDING")) {
return SIXTEEN_BYTE_BLOCK_PLAIN_TEXT;
}
+ if (algorithm.equals("DESEDE")
+ || algorithm.equals("DESEDE/CBC/NOPADDING")
+ || algorithm.equals("DESEDE/ECB/NOPADDING")) {
+ return EIGHT_BYTE_BLOCK_PLAIN_TEXT;
+ }
// BC strips the leading 0 for us even when NoPadding is specified
if (!provider.equals("BC") && algorithm.equals("RSA/ECB/NOPADDING")) {
return PKCS1_BLOCK_TYPE_00_PADDED_PLAIN_TEXT;
@@ -662,8 +750,14 @@ public final class CipherTest extends TestCase {
new SecureRandom().nextBytes(salt);
return new PBEParameterSpec(salt, 1024);
}
+ if (algorithm.equals("GCM")) {
+ final byte[] iv = new byte[8];
+ new SecureRandom().nextBytes(iv);
+ return new GCMParameterSpec(GCM_TAG_SIZE_BITS, iv);
+ }
if (algorithm.equals("AES/CBC/NOPADDING")
|| algorithm.equals("AES/CBC/PKCS5PADDING")
+ || algorithm.equals("AES/CBC/PKCS7PADDING")
|| algorithm.equals("AES/CFB/NOPADDING")
|| algorithm.equals("AES/CTR/NOPADDING")
|| algorithm.equals("AES/CTS/NOPADDING")
@@ -672,6 +766,17 @@ public final class CipherTest extends TestCase {
new SecureRandom().nextBytes(iv);
return new IvParameterSpec(iv);
}
+ if (algorithm.equals("DESEDE/CBC/NOPADDING")
+ || algorithm.equals("DESEDE/CBC/PKCS5PADDING")
+ || algorithm.equals("DESEDE/CBC/PKCS7PADDING")
+ || algorithm.equals("DESEDE/CFB/NOPADDING")
+ || algorithm.equals("DESEDE/CTR/NOPADDING")
+ || algorithm.equals("DESEDE/CTS/NOPADDING")
+ || algorithm.equals("DESEDE/OFB/NOPADDING")) {
+ final byte[] iv = new byte[8];
+ new SecureRandom().nextBytes(iv);
+ return new IvParameterSpec(iv);
+ }
return null;
}
@@ -686,11 +791,193 @@ public final class CipherTest extends TestCase {
}
byte[] iv = encryptCipher.getIV();
if (iv != null) {
+ if ("GCM".equals(algorithm)) {
+ return new GCMParameterSpec(GCM_TAG_SIZE_BITS, iv);
+ }
return new IvParameterSpec(iv);
}
return null;
}
+ /*
+ * This must be below everything else to make sure the other static blocks
+ * have run first.
+ */
+ private static final boolean IS_UNLIMITED;
+ static {
+ boolean is_unlimited;
+ if (StandardNames.IS_RI) {
+ try {
+ String algorithm = "PBEWITHMD5ANDTRIPLEDES";
+ Cipher.getInstance(algorithm).init(getEncryptMode(algorithm),
+ getEncryptKey(algorithm),
+ getEncryptAlgorithmParameterSpec(algorithm));
+ is_unlimited = true;
+ } catch (Exception e) {
+ is_unlimited = false;
+ System.out.println("WARNING: Some tests disabled due to lack of "
+ + "'Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files'");
+ }
+ } else {
+ is_unlimited = true;
+ }
+ IS_UNLIMITED = is_unlimited;
+ }
+
+ private static abstract class MockProvider extends Provider {
+ public MockProvider(String name) {
+ super(name, 1.0, "Mock provider used for testing");
+ setup();
+ }
+
+ public abstract void setup();
+ }
+
+ public void testCipher_getInstance_SuppliedProviderNotRegistered_Success() throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ {
+ Cipher c = Cipher.getInstance("FOO", mockProvider);
+ c.init(Cipher.ENCRYPT_MODE, new MockKey());
+ assertEquals(mockProvider, c.getProvider());
+ }
+ }
+
+ public void testCipher_getInstance_SuppliedProviderNotRegistered_MultipartTransform_Success()
+ throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ {
+ Cipher c = Cipher.getInstance("FOO/FOO/FOO", mockProvider);
+ c.init(Cipher.ENCRYPT_MODE, new MockKey());
+ assertEquals(mockProvider, c.getProvider());
+ }
+ }
+
+ public void testCipher_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success()
+ throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProvider);
+ try {
+ {
+ Provider mockProvider2 = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
+ }
+ };
+ Cipher c = Cipher.getInstance("FOO", mockProvider2);
+ assertEquals(mockProvider2, c.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProvider.getName());
+ }
+ }
+
+ public void testCipher_getInstance_DelayedInitialization_KeyType() throws Exception {
+ Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes.class.getName());
+ put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());
+ }
+ };
+ Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes2.class.getName());
+ put("Cipher.FOO SupportedKeyClasses", MockKey2.class.getName());
+ }
+ };
+ Provider mockProviderAll = new MockProvider("MockProviderAll") {
+ public void setup() {
+ put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProviderSpecific);
+ Security.addProvider(mockProviderSpecific2);
+ Security.addProvider(mockProviderAll);
+
+ try {
+ {
+ System.out.println(Arrays.deepToString(Security.getProviders("Cipher.FOO")));
+ Cipher c = Cipher.getInstance("FOO");
+ c.init(Cipher.ENCRYPT_MODE, new MockKey());
+ assertEquals(mockProviderSpecific, c.getProvider());
+
+ try {
+ c.init(Cipher.ENCRYPT_MODE, new MockKey2());
+ assertEquals(mockProviderSpecific2, c.getProvider());
+ if (StandardNames.IS_RI) {
+ fail("RI was broken before; fix tests now that it works!");
+ }
+ } catch (InvalidKeyException e) {
+ if (!StandardNames.IS_RI) {
+ fail("Non-RI should select the right provider");
+ }
+ }
+ }
+
+ {
+ Cipher c = Cipher.getInstance("FOO");
+ c.init(Cipher.ENCRYPT_MODE, new Key() {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+ });
+ assertEquals(mockProviderAll, c.getProvider());
+ }
+
+ {
+ Cipher c = Cipher.getInstance("FOO");
+ assertEquals(mockProviderSpecific, c.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProviderSpecific.getName());
+ Security.removeProvider(mockProviderSpecific2.getName());
+ Security.removeProvider(mockProviderAll.getName());
+ }
+ }
+
+ public void testCipher_getInstance_WrongType_Failure() throws Exception {
+ Provider mockProviderInvalid = new MockProvider("MockProviderInvalid") {
+ public void setup() {
+ put("Cipher.FOO", Object.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProviderInvalid);
+ try {
+ Cipher.getInstance("FOO");
+ fail("Should not find any matching providers");
+ } catch (NoSuchAlgorithmException expected) {
+ } finally {
+ Security.removeProvider(mockProviderInvalid.getName());
+ }
+ }
+
public void test_getInstance() throws Exception {
final ByteArrayOutputStream errBuffer = new ByteArrayOutputStream();
PrintStream out = new PrintStream(errBuffer);
@@ -723,7 +1010,9 @@ public final class CipherTest extends TestCase {
if (!seenBaseCipherNames.contains(baseCipherName)) {
seenCiphersWithModeAndPadding.add(baseCipherName);
}
- continue;
+ if (!"AndroidOpenSSL".equals(provider.getName())) {
+ continue;
+ }
}
try {
@@ -832,11 +1121,18 @@ public final class CipherTest extends TestCase {
}
}
+ test_Cipher_init_NullParameters(c, encryptMode, encryptKey);
+
c.init(encryptMode, encryptKey, encryptSpec);
assertEquals(cipherID + " getBlockSize() encryptMode",
getExpectedBlockSize(algorithm, encryptMode, providerName), c.getBlockSize());
assertEquals(cipherID + " getOutputSize(0) encryptMode",
getExpectedOutputSize(algorithm, encryptMode, providerName), c.getOutputSize(0));
+ if ((algorithm.endsWith("/PKCS5PADDING") || algorithm.endsWith("/PKCS7PADDING"))
+ && isStreamMode(algorithm)) {
+ assertEquals(getExpectedOutputSize(algorithm, encryptMode, providerName),
+ c.doFinal(new byte[1]).length);
+ }
final AlgorithmParameterSpec decryptSpec = getDecryptAlgorithmParameterSpec(encryptSpec, c);
int decryptMode = getDecryptMode(algorithm);
@@ -856,6 +1152,11 @@ public final class CipherTest extends TestCase {
assertEquals(cipherID + " getIV()",
Arrays.toString(((IvParameterSpec) decryptSpec).getIV()),
Arrays.toString(c.getIV()));
+ } else if (decryptSpec instanceof GCMParameterSpec) {
+ assertNotNull(c.getIV());
+ assertEquals(cipherID + " getIV()",
+ Arrays.toString(((GCMParameterSpec) decryptSpec).getIV()),
+ Arrays.toString(c.getIV()));
} else {
try {
assertNull(cipherID + " getIV()", c.getIV());
@@ -885,7 +1186,9 @@ public final class CipherTest extends TestCase {
assertNull(cipherID, c.getExemptionMechanism());
// Test wrapping a key. Every cipher should be able to wrap. Except those that can't.
- if (isSupportedForWrapping(algorithm)) {
+ /* Bouncycastle is broken for wrapping because getIV() fails. */
+ if (isSupportedForWrapping(algorithm)
+ && !algorithm.equals("GCM") && !providerName.equals("BC")) {
// Generate a small SecretKey for AES.
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
@@ -910,11 +1213,58 @@ public final class CipherTest extends TestCase {
if (!isOnlyWrappingAlgorithm(algorithm)) {
c.init(Cipher.ENCRYPT_MODE, encryptKey, encryptSpec);
byte[] cipherText = c.doFinal(getActualPlainText(algorithm));
+ byte[] cipherText2 = c.doFinal(getActualPlainText(algorithm));
+ assertEquals(cipherID,
+ Arrays.toString(cipherText),
+ Arrays.toString(cipherText2));
c.init(Cipher.DECRYPT_MODE, getDecryptKey(algorithm), decryptSpec);
byte[] decryptedPlainText = c.doFinal(cipherText);
assertEquals(cipherID,
Arrays.toString(getExpectedPlainText(algorithm, providerName)),
Arrays.toString(decryptedPlainText));
+ byte[] decryptedPlainText2 = c.doFinal(cipherText);
+ assertEquals(cipherID,
+ Arrays.toString(decryptedPlainText),
+ Arrays.toString(decryptedPlainText2));
+ }
+ }
+
+ /**
+ * Try various .init(...) calls with null parameters to make sure it is
+ * handled.
+ */
+ private void test_Cipher_init_NullParameters(Cipher c, int encryptMode, Key encryptKey)
+ throws Exception {
+ try {
+ c.init(encryptMode, encryptKey, (AlgorithmParameterSpec) null);
+ } catch (InvalidAlgorithmParameterException e) {
+ if (!isPBE(c.getAlgorithm())) {
+ throw e;
+ }
+ }
+
+ try {
+ c.init(encryptMode, encryptKey, (AlgorithmParameterSpec) null, (SecureRandom) null);
+ } catch (InvalidAlgorithmParameterException e) {
+ if (!isPBE(c.getAlgorithm())) {
+ throw e;
+ }
+ }
+
+ try {
+ c.init(encryptMode, encryptKey, (AlgorithmParameters) null);
+ } catch (InvalidAlgorithmParameterException e) {
+ if (!isPBE(c.getAlgorithm())) {
+ throw e;
+ }
+ }
+
+ try {
+ c.init(encryptMode, encryptKey, (AlgorithmParameters) null, (SecureRandom) null);
+ } catch (InvalidAlgorithmParameterException e) {
+ if (!isPBE(c.getAlgorithm())) {
+ throw e;
+ }
}
}
@@ -2135,7 +2485,7 @@ public final class CipherTest extends TestCase {
};
private static class CipherTestParam {
- public final String mode;
+ public final String transformation;
public final byte[] key;
@@ -2147,9 +2497,9 @@ public final class CipherTest extends TestCase {
public final byte[] plaintextPadded;
- public CipherTestParam(String mode, byte[] key, byte[] iv, byte[] plaintext,
+ public CipherTestParam(String transformation, byte[] key, byte[] iv, byte[] plaintext,
byte[] plaintextPadded, byte[] ciphertext) {
- this.mode = mode;
+ this.transformation = transformation;
this.key = key;
this.iv = iv;
this.plaintext = plaintext;
@@ -2160,13 +2510,24 @@ public final class CipherTest extends TestCase {
private static List<CipherTestParam> CIPHER_TEST_PARAMS = new ArrayList<CipherTestParam>();
static {
- CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB", AES_128_KEY,
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB/PKCS5Padding", AES_128_KEY,
+ null,
+ AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext,
+ AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded,
+ AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted));
+ // PKCS#5 is assumed to be equivalent to PKCS#7 -- same test vectors are thus used for both.
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/ECB/PKCS7Padding", AES_128_KEY,
null,
AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext,
AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded,
AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted));
if (IS_UNLIMITED) {
- CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC", AES_256_KEY,
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC/PKCS5Padding", AES_256_KEY,
+ AES_256_CBC_PKCS5Padding_TestVector_1_IV,
+ AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext,
+ AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext_Padded,
+ AES_256_CBC_PKCS5Padding_TestVector_1_Ciphertext));
+ CIPHER_TEST_PARAMS.add(new CipherTestParam("AES/CBC/PKCS7Padding", AES_256_KEY,
AES_256_CBC_PKCS5Padding_TestVector_1_IV,
AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext,
AES_256_CBC_PKCS5Padding_TestVector_1_Plaintext_Padded,
@@ -2187,7 +2548,7 @@ public final class CipherTest extends TestCase {
try {
checkCipher(p, provider);
} catch (Exception e) {
- out.append("Error encountered checking " + p.mode + ", keySize="
+ out.append("Error encountered checking " + p.transformation + ", keySize="
+ (p.key.length * 8)
+ " with provider " + provider + "\n");
@@ -2202,7 +2563,7 @@ public final class CipherTest extends TestCase {
private void checkCipher(CipherTestParam p, String provider) throws Exception {
SecretKey key = new SecretKeySpec(p.key, "AES");
- Cipher c = Cipher.getInstance(p.mode + "/PKCS5Padding", provider);
+ Cipher c = Cipher.getInstance(p.transformation, provider);
AlgorithmParameterSpec spec = null;
if (p.iv != null) {
spec = new IvParameterSpec(p.iv);
@@ -2224,16 +2585,16 @@ public final class CipherTest extends TestCase {
}
byte[] emptyPlainText = c.doFinal(emptyCipherText);
- assertEquals(Arrays.toString(EmptyArray.BYTE), Arrays.toString(emptyPlainText));
+ assertEquals(Arrays.toString(new byte[0]), Arrays.toString(emptyPlainText));
// empty decrypt
{
if (StandardNames.IS_RI) {
- assertEquals(Arrays.toString(EmptyArray.BYTE),
+ assertEquals(Arrays.toString(new byte[0]),
Arrays.toString(c.doFinal()));
- c.update(EmptyArray.BYTE);
- assertEquals(Arrays.toString(EmptyArray.BYTE),
+ c.update(new byte[0]);
+ assertEquals(Arrays.toString(new byte[0]),
Arrays.toString(c.doFinal()));
} else if (provider.equals("BC")) {
try {
@@ -2242,7 +2603,7 @@ public final class CipherTest extends TestCase {
} catch (IllegalBlockSizeException expected) {
}
try {
- c.update(EmptyArray.BYTE);
+ c.update(new byte[0]);
c.doFinal();
fail();
} catch (IllegalBlockSizeException expected) {
@@ -2250,7 +2611,7 @@ public final class CipherTest extends TestCase {
} else if (provider.equals("AndroidOpenSSL")) {
assertNull(c.doFinal());
- c.update(EmptyArray.BYTE);
+ c.update(new byte[0]);
assertNull(c.doFinal());
} else {
throw new AssertionError("Define your behavior here for " + provider);
@@ -2287,11 +2648,13 @@ public final class CipherTest extends TestCase {
Arrays.toString(Arrays.copyOfRange(actualPlaintext, 1, p.plaintext.length + 1)));
}
- Cipher cNoPad = Cipher.getInstance(p.mode + "/NoPadding", provider);
+ Cipher cNoPad = Cipher.getInstance(
+ getCipherTransformationWithNoPadding(p.transformation), provider);
cNoPad.init(Cipher.DECRYPT_MODE, key, spec);
final byte[] actualPlaintextPadded = cNoPad.doFinal(p.ciphertext);
- assertEquals(Arrays.toString(p.plaintextPadded), Arrays.toString(actualPlaintextPadded));
+ assertEquals(provider + ":" + cNoPad.getAlgorithm(), Arrays.toString(p.plaintextPadded),
+ Arrays.toString(actualPlaintextPadded));
// Test wrapping a key. Every cipher should be able to wrap.
{
@@ -2316,6 +2679,23 @@ public final class CipherTest extends TestCase {
}
}
+ /**
+ * Gets the Cipher transformation with the same algorithm and mode as the provided one but
+ * which uses no padding.
+ */
+ private static String getCipherTransformationWithNoPadding(String transformation) {
+ // The transformation is assumed to be in the Algorithm/Mode/Padding format.
+ int paddingModeDelimiterIndex = transformation.lastIndexOf('/');
+ if (paddingModeDelimiterIndex == -1) {
+ fail("No padding mode delimiter: " + transformation);
+ }
+ String paddingMode = transformation.substring(paddingModeDelimiterIndex + 1);
+ if (!paddingMode.toLowerCase().endsWith("padding")) {
+ fail("No padding mode specified:" + transformation);
+ }
+ return transformation.substring(0, paddingModeDelimiterIndex) + "/NoPadding";
+ }
+
public void testCipher_updateAAD_BeforeInit_Failure() throws Exception {
Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
@@ -2405,7 +2785,7 @@ public final class CipherTest extends TestCase {
try {
checkCipher_ShortBlock_Failure(p, provider);
} catch (Exception e) {
- out.append("Error encountered checking " + p.mode + ", keySize="
+ out.append("Error encountered checking " + p.transformation + ", keySize="
+ (p.key.length * 8)
+ " with provider " + provider + "\n");
e.printStackTrace(out);
@@ -2419,7 +2799,8 @@ public final class CipherTest extends TestCase {
private void checkCipher_ShortBlock_Failure(CipherTestParam p, String provider) throws Exception {
SecretKey key = new SecretKeySpec(p.key, "AES");
- Cipher c = Cipher.getInstance(p.mode + "/NoPadding", provider);
+ Cipher c = Cipher.getInstance(
+ getCipherTransformationWithNoPadding(p.transformation), provider);
if (c.getBlockSize() == 0) {
return;
}
@@ -2427,7 +2808,8 @@ public final class CipherTest extends TestCase {
c.init(Cipher.ENCRYPT_MODE, key);
try {
c.doFinal(new byte[] { 0x01, 0x02, 0x03 });
- fail("Should throw IllegalBlockSizeException on wrong-sized block");
+ fail("Should throw IllegalBlockSizeException on wrong-sized block; provider="
+ + provider);
} catch (IllegalBlockSizeException expected) {
}
}
@@ -2495,6 +2877,7 @@ public final class CipherTest extends TestCase {
private void testAES_ECB_NoPadding_IncrementalUpdate_Success(String provider) throws Exception {
SecretKey key = new SecretKeySpec(AES_128_KEY, "AES");
Cipher c = Cipher.getInstance("AES/ECB/NoPadding", provider);
+ assertEquals(provider, c.getProvider().getName());
c.init(Cipher.ENCRYPT_MODE, key);
for (int i = 0; i < AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length - 1; i++) {
@@ -2506,10 +2889,11 @@ public final class CipherTest extends TestCase {
final byte[] output = c.doFinal(AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded,
AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length - 1, 1);
- assertNotNull(output);
- assertEquals(AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length, output.length);
+ assertNotNull(provider, output);
+ assertEquals(provider, AES_128_ECB_PKCS5Padding_TestVector_1_Plaintext_Padded.length,
+ output.length);
- assertTrue(Arrays.equals(AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted, output));
+ assertTrue(provider, Arrays.equals(AES_128_ECB_PKCS5Padding_TestVector_1_Encrypted, output));
}
private static final byte[] AES_IV_ZEROES = new byte[] {
@@ -2531,7 +2915,7 @@ public final class CipherTest extends TestCase {
AlgorithmParameterSpec spec = new IvParameterSpec(AES_IV_ZEROES);
try {
c.init(Cipher.ENCRYPT_MODE, key, spec);
- fail("Should not accept an IV in ECB mode");
+ fail("Should not accept an IV in ECB mode; provider=" + provider);
} catch (InvalidAlgorithmParameterException expected) {
}
}
diff --git a/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java b/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java
index 29efd3a..8bbd548 100644
--- a/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java
@@ -114,6 +114,8 @@ public class KeyGeneratorTest extends TestCase {
putKeySize("HmacMD5", 1025);
putKeySize("HmacSHA1", 1);
putKeySize("HmacSHA1", 1025);
+ putKeySize("HmacSHA224", 40);
+ putKeySize("HmacSHA224", 1025);
putKeySize("HmacSHA256", 40);
putKeySize("HmacSHA256", 1025);
putKeySize("HmacSHA384", 40);
diff --git a/luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java b/luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java
new file mode 100644
index 0000000..6742cf3
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/crypto/MockCipherSpi.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2013 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 libcore.javax.crypto;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.CipherSpi;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.ShortBufferException;
+
+/**
+ * Mock CipherSpi used by {@link CipherTest}.
+ */
+public class MockCipherSpi extends CipherSpi {
+ public static class SpecificKeyTypes extends MockCipherSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockKey)) {
+ throw new InvalidKeyException("Must be MockKey!");
+ }
+ }
+ }
+
+ public static class SpecificKeyTypes2 extends MockCipherSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ System.err.println("Checking key of type " + key.getClass().getName());
+ if (!(key instanceof MockKey2)) {
+ throw new InvalidKeyException("Must be MockKey2!");
+ }
+ }
+ }
+
+ public static class AllKeyTypes extends MockCipherSpi {
+ }
+
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ }
+
+ @Override
+ protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
+ if (!"FOO".equals(mode)) {
+ throw new UnsupportedOperationException("not implemented");
+ }
+ }
+
+ @Override
+ protected void engineSetPadding(String padding) throws NoSuchPaddingException {
+ if (!"FOO".equals(padding)) {
+ throw new UnsupportedOperationException("not implemented");
+ }
+ }
+
+ @Override
+ protected int engineGetBlockSize() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected int engineGetOutputSize(int inputLen) {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected byte[] engineGetIV() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected AlgorithmParameters engineGetParameters() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException {
+ checkKeyType(key);
+ }
+
+ @Override
+ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
+ SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
+ checkKeyType(key);
+ }
+
+ @Override
+ protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ checkKeyType(key);
+ }
+
+ @Override
+ protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output,
+ int outputOffset) throws ShortBufferException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
+ throws IllegalBlockSizeException, BadPaddingException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
+ int outputOffset) throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException {
+ throw new UnsupportedOperationException("not implemented");
+ }
+}
diff --git a/luni/src/test/java/libcore/sqlite/OldExceptionTest.java b/luni/src/test/java/libcore/javax/crypto/MockKey.java
index dddfd6b..248e2de 100644
--- a/luni/src/test/java/libcore/sqlite/OldExceptionTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/MockKey.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright 2013 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.
@@ -14,26 +14,27 @@
* limitations under the License.
*/
-package libcore.sqlite;
+package libcore.javax.crypto;
-import SQLite.Database;
-import SQLite.Exception;
+import java.security.Key;
-public final class OldExceptionTest extends OldSQLiteTest {
-
- private Database db = null;
+/**
+ * A mock Key class used for testing.
+ */
+@SuppressWarnings("serial")
+public class MockKey implements Key {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
- @Override public void setUp() throws java.lang.Exception {
- super.setUp();
- db = new Database();
+ @Override
+ public String getFormat() {
+ return "MOCK";
}
- public void testException() {
- try {
- db.open(dbFile.getName(), 0);
- } catch (Exception e) {
- assertNotNull(e);
- assertNotNull(e.getMessage());
- }
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
}
}
diff --git a/luni/src/test/java/libcore/javax/crypto/MockKey2.java b/luni/src/test/java/libcore/javax/crypto/MockKey2.java
new file mode 100644
index 0000000..44ac0cc
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/crypto/MockKey2.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2013 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 libcore.javax.crypto;
+
+import java.security.Key;
+
+/**
+ * A mock Key class used for testing.
+ */
+@SuppressWarnings("serial")
+public class MockKey2 implements Key {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ return "MOCK";
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+}
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java
index 578ee6b..e64fb9e 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java
@@ -26,7 +26,7 @@ public class AlgorithmParameterGeneratorTestDH extends
super("DH", new AlgorithmParameterKeyAgreementHelper("DH"));
}
- @BrokenTest("Suffers from DH slowness, disabling for now")
+ // Broken Test: Suffers from DH slowness, disabling for now
public void testAlgorithmParameterGenerator() {
super.testAlgorithmParameterGenerator();
}
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java
index 165daa1..897e62b 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java
@@ -15,7 +15,6 @@
*/
package libcore.javax.crypto.spec;
-import dalvik.annotation.BrokenTest;
import java.math.BigInteger;
import javax.crypto.spec.DHParameterSpec;
import tests.security.AlgorithmParameterKeyAgreementHelper;
@@ -61,7 +60,7 @@ public class AlgorithmParametersTestDH extends AlgorithmParametersTest {
}
- @BrokenTest("Suffers from DH slowness, disabling for now")
+ // Broken Test: Suffers from DH slowness, disabling for now
public void testAlgorithmParameters() {
super.testAlgorithmParameters();
}
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java
index c4322ff..8e500e1 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java
@@ -15,7 +15,6 @@
*/
package libcore.javax.crypto.spec;
-import dalvik.annotation.BrokenTest;
import java.security.NoSuchAlgorithmException;
import tests.security.KeyAgreementHelper;
import tests.security.KeyPairGeneratorTest;
@@ -26,7 +25,7 @@ public class KeyPairGeneratorTestDH extends KeyPairGeneratorTest {
super("DH", new KeyAgreementHelper("DH"));
}
- @BrokenTest("Takes ages due to DH computations. Disabling for now.")
+ // Broken Test: Takes ages due to DH computations. Disabling for now.
public void testKeyPairGenerator() throws NoSuchAlgorithmException {
super.testKeyPairGenerator();
}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java b/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java
index e1c9fe3..feecebe 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/DefaultHostnameVerifierTest.java
@@ -114,15 +114,18 @@ public final class DefaultHostnameVerifierTest extends TestCase {
public void testWildcardMatchesWildcardSuffix() {
assertTrue(verifier.verifyHostName("b.c.d", "*.b.c.d"));
assertTrue(verifier.verifyHostName("imap.google.com", "*.imap.google.com"));
+ assertFalse(verifier.verifyHostName("imap.google.com.au", "*.imap.google.com"));
}
public void testWildcardMatchingSubstring() {
assertTrue(verifier.verifyHostName("b.c.d", "b*.c.d"));
assertTrue(verifier.verifyHostName("imap.google.com", "ima*.google.com"));
+ assertFalse(verifier.verifyHostName("imap.google.com.au", "ima*.google.com"));
}
public void testWildcardMatchingEmptySubstring() {
assertTrue(verifier.verifyHostName("imap.google.com", "imap*.google.com"));
+ assertFalse(verifier.verifyHostName("imap.google.com.au", "imap*.google.com"));
}
public void testWildcardMatchesChildDomain() {
diff --git a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
index f2d36c8..0657f18 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
@@ -45,8 +45,8 @@ public class KeyManagerFactoryTest extends TestCase {
private static TestKeyStore getTestKeyStore() throws Exception {
if (TEST_KEY_STORE == null) {
TEST_KEY_STORE = new TestKeyStore.Builder()
- .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
- .aliasPrefix("rsa-dsa-ec")
+ .keyAlgorithms("RSA", "DH_RSA", "DSA", "DH_DSA", "EC", "EC_RSA")
+ .aliasPrefix("rsa-dsa-ec-dh")
.build();
}
return TEST_KEY_STORE;
diff --git a/luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java b/luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java
new file mode 100644
index 0000000..1daa346
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2014 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 libcore.javax.net.ssl;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.Socket;
+import javax.crypto.SecretKey;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLEngine;
+
+/**
+ * Reflection-based implementation of {@code PSKKeyManager} from Conscrypt on which these tests
+ * cannot depend directly.
+ */
+class PSKKeyManagerProxy implements InvocationHandler {
+
+ static KeyManager getConscryptPSKKeyManager(PSKKeyManagerProxy delegate) {
+ Class<?> pskKeyManagerInterface;
+ try {
+ pskKeyManagerInterface = Class.forName("com.android.org.conscrypt.PSKKeyManager");
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+ return (KeyManager) Proxy.newProxyInstance(
+ PSKKeyManagerProxy.class.getClassLoader(),
+ new Class[] {pskKeyManagerInterface},
+ delegate);
+ }
+
+ @SuppressWarnings("unused")
+ protected SecretKey getKey(String identityHint, String identity, Socket socket) {
+ return null;
+ }
+
+ @SuppressWarnings("unused")
+ protected SecretKey getKey(String identityHint, String identity, SSLEngine engine) {
+ return null;
+ }
+
+ @SuppressWarnings("unused")
+ protected String chooseServerKeyIdentityHint(Socket socket) {
+ return null;
+ }
+
+ @SuppressWarnings("unused")
+ protected String chooseServerKeyIdentityHint(SSLEngine engine) {
+ return null;
+ }
+
+ @SuppressWarnings("unused")
+ protected String chooseClientKeyIdentity(String identityHint, Socket socket) {
+ return null;
+ }
+
+ @SuppressWarnings("unused")
+ protected String chooseClientKeyIdentity(String identityHint, SSLEngine engine) {
+ return null;
+ }
+
+ @Override
+ public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ String methodName = method.getName();
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ boolean sslEngineVariant = (parameterTypes.length > 0)
+ && (SSLEngine.class.equals(parameterTypes[parameterTypes.length - 1]));
+ if ("getKey".equals(methodName)) {
+ if (sslEngineVariant) {
+ return getKey((String) args[0], (String) args[1], (SSLEngine) args[2]);
+ } else {
+ return getKey((String) args[0], (String) args[1], (Socket) args[2]);
+ }
+ } else if ("chooseServerKeyIdentityHint".equals(methodName)) {
+ if (sslEngineVariant) {
+ return chooseServerKeyIdentityHint((SSLEngine) args[0]);
+ } else {
+ return chooseServerKeyIdentityHint((Socket) args[0]);
+ }
+ } else if ("chooseClientKeyIdentity".equals(methodName)) {
+ if (sslEngineVariant) {
+ return chooseClientKeyIdentity((String) args[0], (SSLEngine) args[1]);
+ } else {
+ return chooseClientKeyIdentity((String) args[0], (Socket) args[1]);
+ }
+ } else {
+ throw new IllegalArgumentException("Unexpected method: " + method);
+ }
+ }
+} \ No newline at end of file
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
index 900d950..dccadbd 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
@@ -16,17 +16,39 @@
package libcore.javax.net.ssl;
+import java.security.InvalidAlgorithmParameterException;
import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
import java.security.Provider;
+import java.security.Security;
+import java.security.UnrecoverableKeyException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import libcore.io.IoUtils;
import libcore.java.security.StandardNames;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.KeyManagerFactorySpi;
+import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.TrustManagerFactorySpi;
+import javax.net.ssl.X509KeyManager;
+import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
public class SSLContextTest extends TestCase {
@@ -59,6 +81,106 @@ public class SSLContextTest extends TestCase {
SSLContext.setDefault(defaultContext);
}
+ public void test_SSLContext_defaultConfiguration() throws Exception {
+ SSLDefaultConfigurationAsserts.assertSSLContext(SSLContext.getDefault());
+
+ for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
+ SSLContext sslContext = SSLContext.getInstance(protocol);
+ if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
+ sslContext.init(null, null, null);
+ }
+ SSLDefaultConfigurationAsserts.assertSSLContext(sslContext);
+ }
+ }
+
+ public void test_SSLContext_pskOnlyConfiguration_defaultProviderOnly() throws Exception {
+ // Test the scenario where only a PSKKeyManager is provided and no TrustManagers are
+ // provided.
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(
+ new KeyManager[] {
+ PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy())
+ },
+ new TrustManager[0],
+ null);
+ List<String> expectedCipherSuites =
+ new ArrayList<String>(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
+ expectedCipherSuites.add(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION);
+ assertEnabledCipherSuites(expectedCipherSuites, sslContext);
+ }
+
+ public void test_SSLContext_x509AndPskConfiguration_defaultProviderOnly() throws Exception {
+ // Test the scenario where an X509TrustManager and PSKKeyManager are provided.
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(
+ new KeyManager[] {
+ PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy())
+ },
+ null, // Use default trust managers, one of which is an X.509 one.
+ null);
+ List<String> expectedCipherSuites =
+ new ArrayList<String>(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
+ expectedCipherSuites.addAll(StandardNames.CIPHER_SUITES_DEFAULT);
+ assertEnabledCipherSuites(expectedCipherSuites, sslContext);
+
+ // Test the scenario where an X509KeyManager and PSKKeyManager are provided.
+ sslContext = SSLContext.getInstance("TLS");
+ // Just an arbitrary X509KeyManager -- it won't be invoked in this test.
+ X509KeyManager x509KeyManager = new RandomPrivateKeyX509ExtendedKeyManager(null);
+ sslContext.init(
+ new KeyManager[] {
+ x509KeyManager,
+ PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy())
+ },
+ new TrustManager[0],
+ null);
+ assertEnabledCipherSuites(expectedCipherSuites, sslContext);
+ }
+
+ public void test_SSLContext_emptyConfiguration_defaultProviderOnly() throws Exception {
+ // Test the scenario where neither X.509 nor PSK KeyManagers or TrustManagers are provided.
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(
+ new KeyManager[0],
+ new TrustManager[0],
+ null);
+ assertEnabledCipherSuites(
+ Arrays.asList(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION),
+ sslContext);
+ }
+
+ private static void assertEnabledCipherSuites(
+ List<String> expectedCipherSuites, SSLContext sslContext) throws Exception {
+ assertContentsInOrder(
+ expectedCipherSuites, sslContext.createSSLEngine().getEnabledCipherSuites());
+ assertContentsInOrder(
+ expectedCipherSuites,
+ sslContext.createSSLEngine().getSSLParameters().getCipherSuites());
+ assertContentsInOrder(
+ expectedCipherSuites, sslContext.getSocketFactory().getDefaultCipherSuites());
+ assertContentsInOrder(
+ expectedCipherSuites, sslContext.getServerSocketFactory().getDefaultCipherSuites());
+
+ SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket();
+ try {
+ assertContentsInOrder(
+ expectedCipherSuites, sslSocket.getEnabledCipherSuites());
+ assertContentsInOrder(
+ expectedCipherSuites, sslSocket.getSSLParameters().getCipherSuites());
+ } finally {
+ IoUtils.closeQuietly(sslSocket);
+ }
+
+ SSLServerSocket sslServerSocket =
+ (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
+ try {
+ assertContentsInOrder(
+ expectedCipherSuites, sslServerSocket.getEnabledCipherSuites());
+ } finally {
+ IoUtils.closeQuietly(sslSocket);
+ }
+ }
+
public void test_SSLContext_getInstance() throws Exception {
try {
SSLContext.getInstance(null);
@@ -109,16 +231,183 @@ public class SSLContextTest extends TestCase {
assertEquals(StandardNames.JSSE_PROVIDER_NAME, provider.getName());
}
- public void test_SSLContext_init() throws Exception {
+ public void test_SSLContext_init_Default() throws Exception {
+ // Assert that initializing a default SSLContext fails because it's supposed to be
+ // initialized already.
+ SSLContext sslContext = SSLContext.getInstance(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT);
+ try {
+ sslContext.init(null, null, null);
+ fail();
+ } catch (KeyManagementException expected) {}
+ try {
+ sslContext.init(new KeyManager[0], new TrustManager[0], null);
+ fail();
+ } catch (KeyManagementException expected) {}
+ try {
+ sslContext.init(
+ new KeyManager[] {new KeyManager() {}},
+ new TrustManager[] {new TrustManager() {}},
+ null);
+ fail();
+ } catch (KeyManagementException expected) {}
+ }
+
+ public void test_SSLContext_init_withNullManagerArrays() throws Exception {
+ // Assert that SSLContext.init works fine even when provided with null arrays of
+ // KeyManagers and TrustManagers.
+ // The contract of SSLContext.init is that it will for default X.509 KeyManager and
+ // TrustManager from the highest priority KeyManagerFactory and TrustManagerFactory.
for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(protocol);
if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- try {
- sslContext.init(null, null, null);
- } catch (KeyManagementException expected) {
+ // Default SSLContext is provided in an already initialized state
+ continue;
+ }
+ SSLContext sslContext = SSLContext.getInstance(protocol);
+ sslContext.init(null, null, null);
+ }
+ }
+
+ public void test_SSLContext_init_withEmptyManagerArrays() throws Exception {
+ // Assert that SSLContext.init works fine even when provided with empty arrays of
+ // KeyManagers and TrustManagers.
+ // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and
+ // TrustManager.
+ // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose
+ // factories throw exceptions which will make this test fail if the factories are used.
+ Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider();
+ invokeWithHighestPrioritySecurityProvider(provider, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ assertEquals(
+ ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
+ TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
+ .getProvider().getClass());
+ assertEquals(
+ ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
+ KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
+ .getProvider().getClass());
+
+ KeyManager[] keyManagers = new KeyManager[0];
+ TrustManager[] trustManagers = new TrustManager[0];
+ for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
+ if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
+ // Default SSLContext is provided in an already initialized state
+ continue;
+ }
+ SSLContext sslContext = SSLContext.getInstance(protocol);
+ sslContext.init(keyManagers, trustManagers, null);
}
- } else {
- sslContext.init(null, null, null);
+
+ return null;
+ }
+ });
+ }
+
+ public void test_SSLContext_init_withoutX509() throws Exception {
+ // Assert that SSLContext.init works fine even when provided with KeyManagers and
+ // TrustManagers which don't include the X.509 ones.
+ // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and
+ // TrustManager.
+ // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose
+ // factories throw exceptions which will make this test fail if the factories are used.
+ Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider();
+ invokeWithHighestPrioritySecurityProvider(provider, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ assertEquals(
+ ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
+ TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
+ .getProvider().getClass());
+ assertEquals(
+ ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
+ KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
+ .getProvider().getClass());
+
+ KeyManager[] keyManagers = new KeyManager[] {new KeyManager() {}};
+ TrustManager[] trustManagers = new TrustManager[] {new TrustManager() {}};
+ for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
+ if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
+ // Default SSLContext is provided in an already initialized state
+ continue;
+ }
+ SSLContext sslContext = SSLContext.getInstance(protocol);
+ sslContext.init(keyManagers, trustManagers, null);
+ }
+
+ return null;
+ }
+ });
+ }
+
+ public static class ThrowExceptionKeyAndTrustManagerFactoryProvider extends Provider {
+ public ThrowExceptionKeyAndTrustManagerFactoryProvider() {
+ super("ThrowExceptionKeyAndTrustManagerProvider",
+ 1.0,
+ "SSLContextTest fake KeyManagerFactory and TrustManagerFactory provider");
+
+ put("TrustManagerFactory." + TrustManagerFactory.getDefaultAlgorithm(),
+ ThrowExceptionTrustManagagerFactorySpi.class.getName());
+ put("TrustManagerFactory.PKIX", ThrowExceptionTrustManagagerFactorySpi.class.getName());
+
+ put("KeyManagerFactory." + KeyManagerFactory.getDefaultAlgorithm(),
+ ThrowExceptionKeyManagagerFactorySpi.class.getName());
+ put("KeyManagerFactory.PKIX", ThrowExceptionKeyManagagerFactorySpi.class.getName());
+ }
+ }
+
+ public static class ThrowExceptionTrustManagagerFactorySpi extends TrustManagerFactorySpi {
+ @Override
+ protected void engineInit(KeyStore ks) throws KeyStoreException {
+ fail();
+ }
+
+ @Override
+ protected void engineInit(ManagerFactoryParameters spec)
+ throws InvalidAlgorithmParameterException {
+ fail();
+ }
+
+ @Override
+ protected TrustManager[] engineGetTrustManagers() {
+ throw new AssertionFailedError();
+ }
+ }
+
+ public static class ThrowExceptionKeyManagagerFactorySpi extends KeyManagerFactorySpi {
+ @Override
+ protected void engineInit(KeyStore ks, char[] password) throws KeyStoreException,
+ NoSuchAlgorithmException, UnrecoverableKeyException {
+ fail();
+ }
+
+ @Override
+ protected void engineInit(ManagerFactoryParameters spec)
+ throws InvalidAlgorithmParameterException {
+ fail();
+ }
+
+ @Override
+ protected KeyManager[] engineGetKeyManagers() {
+ throw new AssertionFailedError();
+ }
+ }
+
+ /**
+ * Installs the specified security provider as the highest provider, invokes the provided
+ * {@link Callable}, and removes the provider.
+ *
+ * @return result returned by the {@code callable}.
+ */
+ private static <T> T invokeWithHighestPrioritySecurityProvider(
+ Provider provider, Callable<T> callable) throws Exception {
+ int providerPosition = -1;
+ try {
+ providerPosition = Security.insertProviderAt(provider, 1);
+ assertEquals(1, providerPosition);
+ return callable.call();
+ } finally {
+ if (providerPosition != -1) {
+ Security.removeProvider(provider.getName());
}
}
}
@@ -244,53 +533,6 @@ public class SSLContextTest extends TestCase {
}
}
- public void test_SSLContext_getDefaultSSLParameters() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
-
- SSLParameters p = sslContext.getDefaultSSLParameters();
- assertNotNull(p);
-
- String[] cipherSuites = p.getCipherSuites();
- assertNotNull(cipherSuites);
- StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
-
- String[] protocols = p.getProtocols();
- assertNotNull(protocols);
- StandardNames.assertValidCipherSuites(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
-
- assertFalse(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
- }
- }
-
- public void test_SSLContext_getSupportedSSLParameters() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
-
- SSLParameters p = sslContext.getSupportedSSLParameters();
- assertNotNull(p);
-
- String[] cipherSuites = p.getCipherSuites();
- assertNotNull(cipherSuites);
- StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
-
- String[] protocols = p.getProtocols();
- assertNotNull(protocols);
- StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS,
- protocols);
-
- assertFalse(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
- }
- }
-
public void test_SSLContextTest_TestSSLContext_create() {
TestSSLContext testContext = TestSSLContext.create();
assertNotNull(testContext);
@@ -298,8 +540,16 @@ public class SSLContextTest extends TestCase {
assertNull(testContext.clientStorePassword);
assertNotNull(testContext.serverKeyStore);
assertEquals(StandardNames.IS_RI, testContext.serverStorePassword != null);
- assertNotNull(testContext.clientKeyManager);
- assertNotNull(testContext.serverKeyManager);
+ assertNotNull(testContext.clientKeyManagers);
+ assertNotNull(testContext.serverKeyManagers);
+ if (testContext.clientKeyManagers.length == 0) {
+ fail("No client KeyManagers");
+ }
+ if (testContext.serverKeyManagers.length == 0) {
+ fail("No server KeyManagers");
+ }
+ assertNotNull(testContext.clientKeyManagers[0]);
+ assertNotNull(testContext.serverKeyManagers[0]);
assertNotNull(testContext.clientTrustManager);
assertNotNull(testContext.serverTrustManager);
assertNotNull(testContext.clientContext);
@@ -309,4 +559,16 @@ public class SSLContextTest extends TestCase {
assertTrue(testContext.port != 0);
testContext.close();
}
+
+ private static void assertContentsInOrder(List<String> expected, String... actual) {
+ if (expected.size() != actual.length) {
+ fail("Unexpected length. Expected len <" + expected.size()
+ + ">, actual len <" + actual.length + ">, expected <" + expected
+ + ">, actual <" + Arrays.asList(actual) + ">");
+ }
+ if (!expected.equals(Arrays.asList(actual))) {
+ fail("Unexpected element(s). Expected <" + expected
+ + ">, actual <" + Arrays.asList(actual) + ">" );
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
index 33a8923..fb7e0c9 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
@@ -17,15 +17,20 @@
package libcore.javax.net.ssl;
import java.io.IOException;
+import java.nio.ByteBuffer;
import java.util.Arrays;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
+import javax.net.ssl.X509ExtendedKeyManager;
import junit.framework.TestCase;
import libcore.java.security.StandardNames;
import libcore.java.security.TestKeyStore;
@@ -59,13 +64,15 @@ public class SSLEngineTest extends TestCase {
&& !b.isOutboundDone());
}
- public void test_SSLEngine_getSupportedCipherSuites_names() throws Exception {
+ public void test_SSLEngine_defaultConfiguration() throws Exception {
+ SSLDefaultConfigurationAsserts.assertSSLEngine(
+ TestSSLContext.create().clientContext.createSSLEngine());
+ }
+
+ public void test_SSLEngine_getSupportedCipherSuites_returnsCopies() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
- String[] cipherSuites = e.getSupportedCipherSuites();
- StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES_SSLENGINE,
- cipherSuites);
- assertNotSame(cipherSuites, e.getSupportedCipherSuites());
+ assertNotSame(e.getSupportedCipherSuites(), e.getSupportedCipherSuites());
c.close();
}
@@ -77,105 +84,214 @@ public class SSLEngineTest extends TestCase {
.ca(true)
.build();
test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, false);
- if (StandardNames.IS_RI) {
- test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, true);
- }
+ test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, true);
}
private void test_SSLEngine_getSupportedCipherSuites_connect(TestKeyStore testKeyStore,
boolean secureRenegotiation)
throws Exception {
- TestSSLContext c = TestSSLContext.create(testKeyStore, testKeyStore);
+ KeyManager pskKeyManager = PSKKeyManagerProxy.getConscryptPSKKeyManager(
+ new PSKKeyManagerProxy() {
+ @Override
+ protected SecretKey getKey(String identityHint, String identity, SSLEngine engine) {
+ return new SecretKeySpec("Just an arbitrary key".getBytes(), "RAW");
+ }
+ });
+ TestSSLContext c = TestSSLContext.createWithAdditionalKeyManagers(
+ testKeyStore, testKeyStore,
+ new KeyManager[] {pskKeyManager}, new KeyManager[] {pskKeyManager});
// Create a TestSSLContext where the KeyManager returns wrong (randomly generated) private
// keys, matching the algorithm and parameters of the correct keys.
// I couldn't find a more elegant way to achieve this other than temporarily replacing the
- // first element of TestKeyStore.keyManagers while invoking TestSSLContext.create.
+ // first X509ExtendedKeyManager element of TestKeyStore.keyManagers while invoking
+ // TestSSLContext.create.
TestSSLContext cWithWrongPrivateKeys;
{
- KeyManager originalKeyManager = testKeyStore.keyManagers[0];
- testKeyStore.keyManagers[0] =
- new RandomPrivateKeyX509ExtendedKeyManager(c.serverKeyManager);
+ // Create a RandomPrivateKeyX509ExtendedKeyManager based on the first
+ // X509ExtendedKeyManager in c.serverKeyManagers.
+ KeyManager randomPrivateKeyX509ExtendedKeyManager = null;
+ for (KeyManager keyManager : c.serverKeyManagers) {
+ if (keyManager instanceof X509ExtendedKeyManager) {
+ randomPrivateKeyX509ExtendedKeyManager =
+ new RandomPrivateKeyX509ExtendedKeyManager((X509ExtendedKeyManager) keyManager);
+ break;
+ }
+ }
+ if (randomPrivateKeyX509ExtendedKeyManager == null) {
+ fail("No X509ExtendedKeyManager in c.serverKeyManagers");
+ }
+
+ // Find the first X509ExtendedKeyManager in testKeyStore.keyManagers
+ int replaceIndex = -1;
+ for (int i = 0; i < testKeyStore.keyManagers.length; i++) {
+ KeyManager keyManager = testKeyStore.keyManagers[i];
+ if (keyManager instanceof X509ExtendedKeyManager) {
+ replaceIndex = i;
+ break;
+ }
+ }
+ if (replaceIndex == -1) {
+ fail("No X509ExtendedKeyManager in testKeyStore.keyManagers");
+ }
+
+ // Temporarily substitute the RandomPrivateKeyX509ExtendedKeyManager in place of the
+ // original X509ExtendedKeyManager.
+ KeyManager originalKeyManager = testKeyStore.keyManagers[replaceIndex];
+ testKeyStore.keyManagers[replaceIndex] = randomPrivateKeyX509ExtendedKeyManager;
cWithWrongPrivateKeys = TestSSLContext.create(testKeyStore, testKeyStore);
- testKeyStore.keyManagers[0] = originalKeyManager;
+ testKeyStore.keyManagers[replaceIndex] = originalKeyManager;
}
+ // To catch all the errors.
+ StringBuilder error = new StringBuilder();
+
String[] cipherSuites = c.clientContext.createSSLEngine().getSupportedCipherSuites();
for (String cipherSuite : cipherSuites) {
- boolean errorExpected = StandardNames.IS_RI && cipherSuite.endsWith("_SHA256");
try {
- /*
- * TLS_EMPTY_RENEGOTIATION_INFO_SCSV cannot be used on
- * its own, but instead in conjunction with other
- * cipher suites.
- */
- if (cipherSuite.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION)
- || cipherSuite.equals(StandardNames.CIPHER_SUITE_FALLBACK)) {
- continue;
- }
- /*
- * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
- * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html
- * #KRBRequire
- */
- if (cipherSuite.startsWith("TLS_KRB5_")) {
- continue;
- }
+ // Skip cipher suites that are obsoleted.
+ if (StandardNames.IS_RI && "TLSv1.2".equals(c.clientContext.getProtocol())
+ && StandardNames.CIPHER_SUITES_OBSOLETE_TLS12.contains(cipherSuite)) {
+ continue;
+ }
+ /*
+ * Signaling Cipher Suite Values (SCSV) cannot be used on their own, but instead in
+ * conjunction with other cipher suites.
+ */
+ if (cipherSuite.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION)
+ || cipherSuite.equals(StandardNames.CIPHER_SUITE_FALLBACK)) {
+ continue;
+ }
+ /*
+ * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
+ * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html
+ * #KRBRequire
+ */
+ if (cipherSuite.startsWith("TLS_KRB5_")) {
+ continue;
+ }
- final String[] cipherSuiteArray
- = (secureRenegotiation
- ? new String[] { cipherSuite,
- StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION }
- : new String[] { cipherSuite });
+ final String[] cipherSuiteArray
+ = (secureRenegotiation
+ ? new String[] { cipherSuite,
+ StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION }
+ : new String[] { cipherSuite });
- // Check that handshake succeeds.
- assertConnected(TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
+ // Check that handshake succeeds.
+ TestSSLEnginePair pair = TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
+ @Override
+ void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
+ client.setEnabledCipherSuites(cipherSuiteArray);
+ server.setEnabledCipherSuites(cipherSuiteArray);
+ }
+ });
+ assertConnected(pair);
+
+ boolean needsRecordSplit =
+ ("TLS".equalsIgnoreCase(c.clientContext.getProtocol())
+ || "SSLv3".equalsIgnoreCase(c.clientContext.getProtocol()))
+ && cipherSuite.contains("_CBC_");
+
+ assertSendsCorrectly("This is the client. Hello!".getBytes(),
+ pair.client, pair.server, needsRecordSplit);
+ assertSendsCorrectly("This is the server. Hi!".getBytes(),
+ pair.server, pair.client, needsRecordSplit);
+
+ // Check that handshake fails when the server does not possess the private key
+ // corresponding to the server's certificate. This is achieved by using SSLContext
+ // cWithWrongPrivateKeys whose KeyManager returns wrong private keys that match
+ // the algorithm (and parameters) of the correct keys.
+ boolean serverAuthenticatedUsingPublicKey = true;
+ if (cipherSuite.contains("_anon_")) {
+ serverAuthenticatedUsingPublicKey = false;
+ } else if ((cipherSuite.startsWith("TLS_PSK_"))
+ || (cipherSuite.startsWith("TLS_ECDHE_PSK_"))) {
+ serverAuthenticatedUsingPublicKey = false;
+ }
+ if (serverAuthenticatedUsingPublicKey) {
+ try {
+ TestSSLEnginePair p = TestSSLEnginePair.create(
+ cWithWrongPrivateKeys, new TestSSLEnginePair.Hooks() {
@Override
void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
client.setEnabledCipherSuites(cipherSuiteArray);
server.setEnabledCipherSuites(cipherSuiteArray);
}
- }));
- assertFalse(errorExpected);
-
- // Check that handshake fails when the server does not possess the private key
- // corresponding to the server's certificate. This is achieved by using SSLContext
- // cWithWrongPrivateKeys whose KeyManager returns wrong private keys that match
- // the algorithm (and parameters) of the correct keys.
- if (!cipherSuite.contains("_anon_")) {
- // The identity of the server is verified only in non-anonymous key exchanges.
- try {
- TestSSLEnginePair p = TestSSLEnginePair.create(
- cWithWrongPrivateKeys, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- client.setEnabledCipherSuites(cipherSuiteArray);
- server.setEnabledCipherSuites(cipherSuiteArray);
- }
- });
- assertConnected(p);
- fail("Handshake succeeded for " + cipherSuite
- + " despite server not having the correct private key");
- } catch (IOException expected) {}
- }
- } catch (Exception maybeExpected) {
- if (!errorExpected) {
- throw new Exception("Problem trying to connect cipher suite " + cipherSuite,
- maybeExpected);
- }
+ });
+ assertNotConnected(p);
+ } catch (IOException expected) {}
+ }
+ } catch (Exception e) {
+ String message = ("Problem trying to connect cipher suite " + cipherSuite);
+ System.out.println(message);
+ e.printStackTrace();
+ error.append(message);
+ error.append('\n');
}
}
c.close();
+
+ if (error.length() > 0) {
+ throw new Exception("One or more problems in "
+ + "test_SSLEngine_getSupportedCipherSuites_connect:\n" + error);
+ }
+ }
+
+ private static void assertSendsCorrectly(final byte[] sourceBytes, SSLEngine source,
+ SSLEngine dest, boolean needsRecordSplit) throws SSLException {
+ ByteBuffer sourceOut = ByteBuffer.wrap(sourceBytes);
+ SSLSession sourceSession = source.getSession();
+ ByteBuffer sourceToDest = ByteBuffer.allocate(sourceSession.getPacketBufferSize());
+ SSLEngineResult sourceOutRes = source.wrap(sourceOut, sourceToDest);
+ sourceToDest.flip();
+
+ String sourceCipherSuite = source.getSession().getCipherSuite();
+ assertEquals(sourceCipherSuite, sourceBytes.length, sourceOutRes.bytesConsumed());
+ assertEquals(sourceCipherSuite, HandshakeStatus.NOT_HANDSHAKING,
+ sourceOutRes.getHandshakeStatus());
+
+ SSLSession destSession = dest.getSession();
+ ByteBuffer destIn = ByteBuffer.allocate(destSession.getApplicationBufferSize());
+
+ int numUnwrapCalls = 0;
+ while (destIn.position() != sourceOut.limit()) {
+ SSLEngineResult destRes = dest.unwrap(sourceToDest, destIn);
+ assertEquals(sourceCipherSuite, HandshakeStatus.NOT_HANDSHAKING,
+ destRes.getHandshakeStatus());
+ if (needsRecordSplit && numUnwrapCalls == 0) {
+ assertEquals(sourceCipherSuite, 1, destRes.bytesProduced());
+ }
+ numUnwrapCalls++;
+ }
+
+ destIn.flip();
+ byte[] actual = new byte[destIn.remaining()];
+ destIn.get(actual);
+ assertEquals(sourceCipherSuite, Arrays.toString(sourceBytes), Arrays.toString(actual));
+
+ if (needsRecordSplit) {
+ assertEquals(sourceCipherSuite, 2, numUnwrapCalls);
+ } else {
+ assertEquals(sourceCipherSuite, 1, numUnwrapCalls);
+ }
}
- public void test_SSLEngine_getEnabledCipherSuites() throws Exception {
+ public void test_SSLEngine_getEnabledCipherSuites_returnsCopies() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
- String[] cipherSuites = e.getEnabledCipherSuites();
- StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
- assertNotSame(cipherSuites, e.getEnabledCipherSuites());
+ assertNotSame(e.getEnabledCipherSuites(), e.getEnabledCipherSuites());
c.close();
}
+ public void test_SSLEngine_setEnabledCipherSuites_storesCopy() throws Exception {
+ TestSSLContext c = TestSSLContext.create();
+ SSLEngine e = c.clientContext.createSSLEngine();
+ String[] array = new String[] {e.getEnabledCipherSuites()[0]};
+ String originalFirstElement = array[0];
+ e.setEnabledCipherSuites(array);
+ array[0] = "Modified after having been set";
+ assertEquals(originalFirstElement, e.getEnabledCipherSuites()[0]);
+ }
+
public void test_SSLEngine_setEnabledCipherSuites() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
@@ -199,28 +315,39 @@ public class SSLEngineTest extends TestCase {
e.setEnabledCipherSuites(new String[0]);
e.setEnabledCipherSuites(e.getEnabledCipherSuites());
e.setEnabledCipherSuites(e.getSupportedCipherSuites());
+
+ // Check that setEnabledCipherSuites affects getEnabledCipherSuites
+ String[] cipherSuites = new String[] { e.getSupportedCipherSuites()[0] };
+ e.setEnabledCipherSuites(cipherSuites);
+ assertEquals(Arrays.asList(cipherSuites), Arrays.asList(e.getEnabledCipherSuites()));
+
c.close();
}
- public void test_SSLEngine_getSupportedProtocols() throws Exception {
+ public void test_SSLEngine_getSupportedProtocols_returnsCopies() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
- String[] protocols = e.getSupportedProtocols();
- StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS_SSLENGINE,
- protocols);
- assertNotSame(protocols, e.getSupportedProtocols());
+ assertNotSame(e.getSupportedProtocols(), e.getSupportedProtocols());
c.close();
}
- public void test_SSLEngine_getEnabledProtocols() throws Exception {
+ public void test_SSLEngine_getEnabledProtocols_returnsCopies() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
- String[] protocols = e.getEnabledProtocols();
- StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
- assertNotSame(protocols, e.getEnabledProtocols());
+ assertNotSame(e.getEnabledProtocols(), e.getEnabledProtocols());
c.close();
}
+ public void test_SSLEngine_setEnabledProtocols_storesCopy() throws Exception {
+ TestSSLContext c = TestSSLContext.create();
+ SSLEngine e = c.clientContext.createSSLEngine();
+ String[] array = new String[] {e.getEnabledProtocols()[0]};
+ String originalFirstElement = array[0];
+ e.setEnabledProtocols(array);
+ array[0] = "Modified after having been set";
+ assertEquals(originalFirstElement, e.getEnabledProtocols()[0]);
+ }
+
public void test_SSLEngine_setEnabledProtocols() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
@@ -243,6 +370,22 @@ public class SSLEngineTest extends TestCase {
e.setEnabledProtocols(new String[0]);
e.setEnabledProtocols(e.getEnabledProtocols());
e.setEnabledProtocols(e.getSupportedProtocols());
+
+ // Check that setEnabledProtocols affects getEnabledProtocols
+ for (String protocol : e.getSupportedProtocols()) {
+ if ("SSLv2Hello".equals(protocol)) {
+ try {
+ e.setEnabledProtocols(new String[] { protocol });
+ fail("Should fail when SSLv2Hello is set by itself");
+ } catch (IllegalArgumentException expected) {}
+ } else {
+ String[] protocols = new String[] { protocol };
+ e.setEnabledProtocols(protocols);
+ assertEquals(Arrays.deepToString(protocols),
+ Arrays.deepToString(e.getEnabledProtocols()));
+ }
+ }
+
c.close();
}
@@ -297,17 +440,34 @@ public class SSLEngineTest extends TestCase {
}
public void test_SSLEngine_setUseClientMode() throws Exception {
+ boolean[] finished;
+
// client is client, server is server
- assertConnected(test_SSLEngine_setUseClientMode(true, false));
+ finished = new boolean[2];
+ assertConnected(test_SSLEngine_setUseClientMode(true, false, finished));
+ assertTrue(finished[0]);
+ assertTrue(finished[1]);
// client is server, server is client
- assertConnected(test_SSLEngine_setUseClientMode(false, true));
+ finished = new boolean[2];
+ assertConnected(test_SSLEngine_setUseClientMode(false, true, finished));
+ assertTrue(finished[0]);
+ assertTrue(finished[1]);
// both are client
- assertNotConnected(test_SSLEngine_setUseClientMode(true, true));
+ /*
+ * Our implementation throws an SSLHandshakeException, but RI just
+ * stalls forever
+ */
+ try {
+ assertNotConnected(test_SSLEngine_setUseClientMode(true, true, null));
+ assertTrue(StandardNames.IS_RI);
+ } catch (SSLHandshakeException maybeExpected) {
+ assertFalse(StandardNames.IS_RI);
+ }
// both are server
- assertNotConnected(test_SSLEngine_setUseClientMode(false, false));
+ assertNotConnected(test_SSLEngine_setUseClientMode(false, false, null));
}
public void test_SSLEngine_setUseClientMode_afterHandshake() throws Exception {
@@ -327,7 +487,8 @@ public class SSLEngineTest extends TestCase {
}
private TestSSLEnginePair test_SSLEngine_setUseClientMode(final boolean clientClientMode,
- final boolean serverClientMode)
+ final boolean serverClientMode,
+ final boolean[] finished)
throws Exception {
TestSSLContext c;
if (!clientClientMode && serverClientMode) {
@@ -342,7 +503,7 @@ public class SSLEngineTest extends TestCase {
client.setUseClientMode(clientClientMode);
server.setUseClientMode(serverClientMode);
}
- });
+ }, finished);
}
public void test_SSLEngine_clientAuth() throws Exception {
@@ -440,13 +601,19 @@ public class SSLEngineTest extends TestCase {
}
public void test_SSLEngine_setEnableSessionCreation_server() throws Exception {
- TestSSLEnginePair p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- server.setEnableSessionCreation(false);
- }
- });
- assertNotConnected(p);
+ try {
+ TestSSLEnginePair p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() {
+ @Override
+ void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
+ server.setEnableSessionCreation(false);
+ }
+ });
+ // For some reason, the RI doesn't throw an SSLException.
+ assertTrue(StandardNames.IS_RI);
+ assertNotConnected(p);
+ } catch (SSLException maybeExpected) {
+ assertFalse(StandardNames.IS_RI);
+ }
}
public void test_SSLEngine_setEnableSessionCreation_client() throws Exception {
@@ -470,12 +637,10 @@ public class SSLEngineTest extends TestCase {
assertNotNull(p);
String[] cipherSuites = p.getCipherSuites();
- StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
assertNotSame(cipherSuites, e.getEnabledCipherSuites());
assertEquals(Arrays.asList(cipherSuites), Arrays.asList(e.getEnabledCipherSuites()));
String[] protocols = p.getProtocols();
- StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
assertNotSame(protocols, e.getEnabledProtocols());
assertEquals(Arrays.asList(protocols), Arrays.asList(e.getEnabledProtocols()));
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java
new file mode 100644
index 0000000..ea9c3f0
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2013 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 libcore.javax.net.ssl;
+
+import javax.net.ssl.SSLServerSocketFactory;
+import junit.framework.TestCase;
+
+public class SSLServerSocketFactoryTest extends TestCase {
+
+ public void testDefaultConfiguration() throws Exception {
+ SSLDefaultConfigurationAsserts.assertSSLServerSocketFactory(
+ (SSLServerSocketFactory) SSLServerSocketFactory.getDefault());
+ }
+}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java
new file mode 100644
index 0000000..59c44c1
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2013 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 libcore.javax.net.ssl;
+
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLServerSocketFactory;
+import junit.framework.TestCase;
+import java.util.Arrays;
+
+public class SSLServerSocketTest extends TestCase {
+
+ public void testDefaultConfiguration() throws Exception {
+ SSLDefaultConfigurationAsserts.assertSSLServerSocket(
+ (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket());
+ }
+
+ public void testSetEnabledCipherSuitesAffectsGetter() throws Exception {
+ SSLServerSocket socket =
+ (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
+ String[] cipherSuites = new String[] {socket.getSupportedCipherSuites()[0]};
+ socket.setEnabledCipherSuites(cipherSuites);
+ assertEquals(Arrays.asList(cipherSuites), Arrays.asList(socket.getEnabledCipherSuites()));
+ }
+
+ public void testSetEnabledCipherSuitesStoresCopy() throws Exception {
+ SSLServerSocket socket =
+ (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
+ String[] array = new String[] {socket.getEnabledCipherSuites()[0]};
+ String originalFirstElement = array[0];
+ socket.setEnabledCipherSuites(array);
+ array[0] = "Modified after having been set";
+ assertEquals(originalFirstElement, socket.getEnabledCipherSuites()[0]);
+ }
+
+ public void testSetEnabledProtocolsAffectsGetter() throws Exception {
+ SSLServerSocket socket =
+ (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
+ String[] protocols = new String[] {socket.getSupportedProtocols()[0]};
+ socket.setEnabledProtocols(protocols);
+ assertEquals(Arrays.asList(protocols), Arrays.asList(socket.getEnabledProtocols()));
+ }
+
+ public void testSetEnabledProtocolsStoresCopy() throws Exception {
+ SSLServerSocket socket =
+ (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
+ String[] array = new String[] {socket.getEnabledProtocols()[0]};
+ String originalFirstElement = array[0];
+ socket.setEnabledProtocols(array);
+ array[0] = "Modified after having been set";
+ assertEquals(originalFirstElement, socket.getEnabledProtocols()[0]);
+ }
+}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
index ba048a8..a434d94 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
@@ -49,7 +49,7 @@ public class SSLSessionTest extends TestCase {
assertNotNull(s.client.getCipherSuite());
assertEquals(s.server.getCipherSuite(),
s.client.getCipherSuite());
- assertTrue(StandardNames.CIPHER_SUITES.contains(s.server.getCipherSuite()));
+ StandardNames.assertValidCipherSuites(new String[] {s.server.getCipherSuite()});
s.close();
}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java
index 14a54fd..acf69c0 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java
@@ -16,37 +16,212 @@
package libcore.javax.net.ssl;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
-import libcore.java.security.StandardNames;
+import java.security.KeyManagementException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.util.Properties;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLContextSpi;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
import junit.framework.TestCase;
+import libcore.java.security.StandardNames;
public class SSLSocketFactoryTest extends TestCase {
+ private static final String SSL_PROPERTY = "ssl.SocketFactory.provider";
+
public void test_SSLSocketFactory_getDefault() {
SocketFactory sf = SSLSocketFactory.getDefault();
assertNotNull(sf);
assertTrue(SSLSocketFactory.class.isAssignableFrom(sf.getClass()));
}
- public void test_SSLSocketFactory_getDefaultCipherSuites() {
+ public static class FakeSSLSocketProvider extends Provider {
+ public FakeSSLSocketProvider() {
+ super("FakeSSLSocketProvider", 1.0, "Testing provider");
+ put("SSLContext.Default", FakeSSLContextSpi.class.getName());
+ }
+ }
+
+ public static final class FakeSSLContextSpi extends SSLContextSpi {
+ @Override
+ protected void engineInit(KeyManager[] keyManagers, TrustManager[] trustManagers,
+ SecureRandom secureRandom) throws KeyManagementException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected SSLSocketFactory engineGetSocketFactory() {
+ return new FakeSSLSocketFactory();
+ }
+
+ @Override
+ protected SSLServerSocketFactory engineGetServerSocketFactory() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected SSLEngine engineCreateSSLEngine(String s, int i) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected SSLEngine engineCreateSSLEngine() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected SSLSessionContext engineGetServerSessionContext() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected SSLSessionContext engineGetClientSessionContext() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public static class FakeSSLSocketFactory extends SSLSocketFactory {
+ public FakeSSLSocketFactory() {
+ }
+
+ @Override
+ public String[] getDefaultCipherSuites() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String[] getSupportedCipherSuites() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Socket createSocket(Socket s, String host, int port, boolean autoClose) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
+ int localPort) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Socket createSocket(InetAddress host, int port) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Socket createSocket(String host, int port, InetAddress localHost, int localPort) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Socket createSocket(String host, int port) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ public void test_SSLSocketFactory_getDefault_cacheInvalidate() throws Exception {
+ String origProvider = resetSslProvider();
+ try {
+ SocketFactory sf1 = SSLSocketFactory.getDefault();
+ assertNotNull(sf1);
+ assertTrue(SSLSocketFactory.class.isAssignableFrom(sf1.getClass()));
+
+ Provider fakeProvider = new FakeSSLSocketProvider();
+ SocketFactory sf4 = null;
+ SSLContext origContext = null;
+ try {
+ origContext = SSLContext.getDefault();
+ Security.insertProviderAt(fakeProvider, 1);
+ SSLContext.setDefault(SSLContext.getInstance("Default", fakeProvider));
+
+ sf4 = SSLSocketFactory.getDefault();
+ assertNotNull(sf4);
+ assertTrue(SSLSocketFactory.class.isAssignableFrom(sf4.getClass()));
+
+ assertFalse(sf1.getClass() + " should not be " + sf4.getClass(),
+ sf1.getClass().equals(sf4.getClass()));
+ } finally {
+ SSLContext.setDefault(origContext);
+ Security.removeProvider(fakeProvider.getName());
+ }
+
+ SocketFactory sf3 = SSLSocketFactory.getDefault();
+ assertNotNull(sf3);
+ assertTrue(SSLSocketFactory.class.isAssignableFrom(sf3.getClass()));
+
+ assertTrue(sf1.getClass() + " should be " + sf3.getClass(),
+ sf1.getClass().equals(sf3.getClass()));
+
+ if (!StandardNames.IS_RI) {
+ Security.setProperty(SSL_PROPERTY, FakeSSLSocketFactory.class.getName());
+ SocketFactory sf2 = SSLSocketFactory.getDefault();
+ assertNotNull(sf2);
+ assertTrue(SSLSocketFactory.class.isAssignableFrom(sf2.getClass()));
+
+ assertFalse(sf2.getClass().getName() + " should not be " + Security.getProperty(SSL_PROPERTY),
+ sf1.getClass().equals(sf2.getClass()));
+ assertTrue(sf2.getClass().equals(sf4.getClass()));
+
+ resetSslProvider();
+ }
+ } finally {
+ Security.setProperty(SSL_PROPERTY, origProvider);
+ }
+ }
+
+ private String resetSslProvider() {
+ String origProvider = Security.getProperty(SSL_PROPERTY);
+
+ try {
+ Field field_secprops = Security.class.getDeclaredField("secprops");
+ field_secprops.setAccessible(true);
+ Properties secprops = (Properties) field_secprops.get(null);
+ secprops.remove(SSL_PROPERTY);
+
+ Class<?> class_services =
+ Class.forName("org.apache.harmony.security.fortress.Services");
+ Method m_setNeedRefresh = class_services.getMethod("setNeedRefresh");
+ m_setNeedRefresh.invoke(null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail("Cannot find a way to clear out the SocketFactory provider");
+ }
+
+ assertNull(Security.getProperty(SSL_PROPERTY));
+ return origProvider;
+ }
+
+ public void test_SSLSocketFactory_defaultConfiguration() throws Exception {
+ SSLDefaultConfigurationAsserts.assertSSLSocketFactory(
+ (SSLSocketFactory) SSLSocketFactory.getDefault());
+ }
+
+ public void test_SSLSocketFactory_getDefaultCipherSuitesReturnsCopies() {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- String[] cipherSuites = sf.getDefaultCipherSuites();
- StandardNames.assertDefaultCipherSuites(cipherSuites);
- assertNotSame(cipherSuites, sf.getDefaultCipherSuites());
+ assertNotSame(sf.getDefaultCipherSuites(), sf.getDefaultCipherSuites());
}
- public void test_SSLSocketFactory_getSupportedCipherSuites() {
+ public void test_SSLSocketFactory_getSupportedCipherSuitesReturnsCopies() {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- String[] cipherSuites = sf.getSupportedCipherSuites();
- StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
- assertNotSame(cipherSuites, sf.getSupportedCipherSuites());
+ assertNotSame(sf.getSupportedCipherSuites(), sf.getSupportedCipherSuites());
}
public void test_SSLSocketFactory_createSocket() throws Exception {
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
index 8e009bd..4681877 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
@@ -16,6 +16,7 @@
package libcore.javax.net.ssl;
+import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -33,12 +34,15 @@ import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import javax.net.ServerSocketFactory;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.KeyManager;
@@ -56,17 +60,22 @@ import javax.net.ssl.TrustManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import junit.framework.TestCase;
+import libcore.io.IoUtils;
+import libcore.io.Streams;
import libcore.java.security.StandardNames;
import libcore.java.security.TestKeyStore;
public class SSLSocketTest extends TestCase {
- public void test_SSLSocket_getSupportedCipherSuites_names() throws Exception {
+ public void test_SSLSocket_defaultConfiguration() throws Exception {
+ SSLDefaultConfigurationAsserts.assertSSLSocket(
+ (SSLSocket) SSLSocketFactory.getDefault().createSocket());
+ }
+
+ public void test_SSLSocket_getSupportedCipherSuites_returnsCopies() throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] cipherSuites = ssl.getSupportedCipherSuites();
- StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
- assertNotSame(cipherSuites, ssl.getSupportedCipherSuites());
+ assertNotSame(ssl.getSupportedCipherSuites(), ssl.getSupportedCipherSuites());
}
public void test_SSLSocket_getSupportedCipherSuites_connect() throws Exception {
@@ -77,49 +86,13 @@ public class SSLSocketTest extends TestCase {
.ca(true)
.build();
StringBuilder error = new StringBuilder();
- if (StandardNames.IS_RI) {
- test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore,
- StandardNames.JSSE_PROVIDER_NAME,
- StandardNames.JSSE_PROVIDER_NAME,
- true,
- true,
- error);
- } else {
- test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore,
- "HarmonyJSSE",
- "HarmonyJSSE",
- false,
- false,
- error);
- test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore,
- "AndroidOpenSSL",
- "AndroidOpenSSL",
- true,
- true,
- error);
- test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore,
- "HarmonyJSSE",
- "AndroidOpenSSL",
- false,
- true,
- error);
- test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore,
- "AndroidOpenSSL",
- "HarmonyJSSE",
- true,
- false,
- error);
- }
+ test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, error);
if (error.length() > 0) {
throw new Exception("One or more problems in "
+ "test_SSLSocket_getSupportedCipherSuites_connect:\n" + error);
}
}
private void test_SSLSocket_getSupportedCipherSuites_connect(TestKeyStore testKeyStore,
- String clientProvider,
- String serverProvider,
- boolean clientSecureRenegotiation,
- boolean serverSecureRenegotiation,
StringBuilder error)
throws Exception {
@@ -128,20 +101,18 @@ public class SSLSocketTest extends TestCase {
byte[] clientToServer = clientToServerString.getBytes();
byte[] serverToClient = serverToClientString.getBytes();
- TestSSLContext c = TestSSLContext.create(testKeyStore, testKeyStore,
- clientProvider, serverProvider);
- String[] cipherSuites;
- if (clientProvider.equals(serverProvider)) {
- cipherSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites();
- } else {
- String[] clientSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites();
- String[] serverSuites = c.serverContext.getSocketFactory().getSupportedCipherSuites();
- Set<String> ccs = new HashSet<String>(Arrays.asList(clientSuites));
- Set<String> scs = new HashSet<String>(Arrays.asList(serverSuites));
- Set<String> cs = new HashSet<String>(ccs);
- cs.retainAll(scs);
- cipherSuites = cs.toArray(new String[cs.size()]);
- }
+ KeyManager pskKeyManager = PSKKeyManagerProxy.getConscryptPSKKeyManager(
+ new PSKKeyManagerProxy() {
+ @Override
+ protected SecretKey getKey(String identityHint, String identity, Socket socket) {
+ return new SecretKeySpec("Just an arbitrary key".getBytes(), "RAW");
+ }
+ });
+ TestSSLContext c = TestSSLContext.createWithAdditionalKeyManagers(
+ testKeyStore, testKeyStore,
+ new KeyManager[] {pskKeyManager}, new KeyManager[] {pskKeyManager});
+
+ String[] cipherSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites();
for (String cipherSuite : cipherSuites) {
boolean errorExpected = StandardNames.IS_RI && cipherSuite.endsWith("_SHA256");
@@ -171,41 +142,48 @@ public class SSLSocketTest extends TestCase {
continue;
}
- String[] clientCipherSuiteArray
- = (clientSecureRenegotiation
- ? new String[] { cipherSuite,
- StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION }
- : new String[] { cipherSuite });
- String[] serverCipherSuiteArray
- = (serverSecureRenegotiation
- ? new String[] { cipherSuite,
- StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION }
- : new String[] { cipherSuite });
+ String[] clientCipherSuiteArray = new String[] {
+ cipherSuite,
+ StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION };
+ String[] serverCipherSuiteArray = clientCipherSuiteArray;
SSLSocket[] pair = TestSSLSocketPair.connect(c,
clientCipherSuiteArray,
serverCipherSuiteArray);
SSLSocket server = pair[0];
SSLSocket client = pair[1];
+
+ // Check that the client can read the message sent by the server
server.getOutputStream().write(serverToClient);
+ byte[] clientFromServer = new byte[serverToClient.length];
+ Streams.readFully(client.getInputStream(), clientFromServer);
+ assertEquals(serverToClientString, new String(clientFromServer));
+
+ // Check that the server can read the message sent by the client
client.getOutputStream().write(clientToServer);
- // arrays are too big to make sure we get back only what we expect
- byte[] clientFromServer = new byte[serverToClient.length+1];
- byte[] serverFromClient = new byte[clientToServer.length+1];
- int readFromServer = client.getInputStream().read(clientFromServer);
- int readFromClient = server.getInputStream().read(serverFromClient);
- assertEquals(serverToClient.length, readFromServer);
- assertEquals(clientToServer.length, readFromClient);
- assertEquals(clientToServerString, new String(serverFromClient, 0, readFromClient));
- assertEquals(serverToClientString, new String(clientFromServer, 0, readFromServer));
+ byte[] serverFromClient = new byte[clientToServer.length];
+ Streams.readFully(server.getInputStream(), serverFromClient);
+ assertEquals(clientToServerString, new String(serverFromClient));
+
+ // Check that the server and the client cannot read anything else
+ // (reads should time out)
+ server.setSoTimeout(10);
+ try {
+ server.getInputStream().read();
+ fail();
+ } catch (IOException expected) {}
+ client.setSoTimeout(10);
+ try {
+ client.getInputStream().read();
+ fail();
+ } catch (IOException expected) {}
+
client.close();
server.close();
assertFalse(errorExpected);
} catch (Exception maybeExpected) {
if (!errorExpected) {
- String message = ("Problem trying to connect cipher suite " + cipherSuite
- + " client=" + clientProvider
- + " server=" + serverProvider);
+ String message = ("Problem trying to connect cipher suite " + cipherSuite);
System.out.println(message);
maybeExpected.printStackTrace();
error.append(message);
@@ -216,12 +194,20 @@ public class SSLSocketTest extends TestCase {
c.close();
}
- public void test_SSLSocket_getEnabledCipherSuites() throws Exception {
+ public void test_SSLSocket_getEnabledCipherSuites_returnsCopies() throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] cipherSuites = ssl.getEnabledCipherSuites();
- StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
- assertNotSame(cipherSuites, ssl.getEnabledCipherSuites());
+ assertNotSame(ssl.getEnabledCipherSuites(), ssl.getEnabledCipherSuites());
+ }
+
+ public void test_SSLSocket_setEnabledCipherSuites_storesCopy() throws Exception {
+ SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
+ SSLSocket ssl = (SSLSocket) sf.createSocket();
+ String[] array = new String[] {ssl.getEnabledCipherSuites()[0]};
+ String originalFirstElement = array[0];
+ ssl.setEnabledCipherSuites(array);
+ array[0] = "Modified after having been set";
+ assertEquals(originalFirstElement, ssl.getEnabledCipherSuites()[0]);
}
public void test_SSLSocket_setEnabledCipherSuites() throws Exception {
@@ -247,22 +233,33 @@ public class SSLSocketTest extends TestCase {
ssl.setEnabledCipherSuites(new String[0]);
ssl.setEnabledCipherSuites(ssl.getEnabledCipherSuites());
ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
+
+ // Check that setEnabledCipherSuites affects getEnabledCipherSuites
+ String[] cipherSuites = new String[] { ssl.getSupportedCipherSuites()[0] };
+ ssl.setEnabledCipherSuites(cipherSuites);
+ assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites()));
}
- public void test_SSLSocket_getSupportedProtocols() throws Exception {
+ public void test_SSLSocket_getSupportedProtocols_returnsCopies() throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] protocols = ssl.getSupportedProtocols();
- StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
- assertNotSame(protocols, ssl.getSupportedProtocols());
+ assertNotSame(ssl.getSupportedProtocols(), ssl.getSupportedProtocols());
}
- public void test_SSLSocket_getEnabledProtocols() throws Exception {
+ public void test_SSLSocket_getEnabledProtocols_returnsCopies() throws Exception {
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] protocols = ssl.getEnabledProtocols();
- StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
- assertNotSame(protocols, ssl.getEnabledProtocols());
+ assertNotSame(ssl.getEnabledProtocols(), ssl.getEnabledProtocols());
+ }
+
+ public void test_SSLSocket_setEnabledProtocols_storesCopy() throws Exception {
+ SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
+ SSLSocket ssl = (SSLSocket) sf.createSocket();
+ String[] array = new String[] {ssl.getEnabledProtocols()[0]};
+ String originalFirstElement = array[0];
+ ssl.setEnabledProtocols(array);
+ array[0] = "Modified after having been set";
+ assertEquals(originalFirstElement, ssl.getEnabledProtocols()[0]);
}
public void test_SSLSocket_setEnabledProtocols() throws Exception {
@@ -287,6 +284,21 @@ public class SSLSocketTest extends TestCase {
ssl.setEnabledProtocols(new String[0]);
ssl.setEnabledProtocols(ssl.getEnabledProtocols());
ssl.setEnabledProtocols(ssl.getSupportedProtocols());
+
+ // Check that setEnabledProtocols affects getEnabledProtocols
+ for (String protocol : ssl.getSupportedProtocols()) {
+ if ("SSLv2Hello".equals(protocol)) {
+ try {
+ ssl.setEnabledProtocols(new String[] { protocol });
+ fail("Should fail when SSLv2Hello is set by itself");
+ } catch (IllegalArgumentException expected) {}
+ } else {
+ String[] protocols = new String[] { protocol };
+ ssl.setEnabledProtocols(protocols);
+ assertEquals(Arrays.deepToString(protocols),
+ Arrays.deepToString(ssl.getEnabledProtocols()));
+ }
+ }
}
public void test_SSLSocket_getSession() throws Exception {
@@ -394,35 +406,26 @@ public class SSLSocketTest extends TestCase {
SSLContext.getDefault(), SSLContext.getDefault());
SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host,
c.port);
- // RI used to throw SSLException on accept, now throws on startHandshake
- if (StandardNames.IS_RI) {
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Future<Void> future = executor.submit(new Callable<Void>() {
- @Override public Void call() throws Exception {
- try {
- server.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- }
- return null;
+ final SSLSocket server = (SSLSocket) c.serverSocket.accept();
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ Future<Void> future = executor.submit(new Callable<Void>() {
+ @Override public Void call() throws Exception {
+ try {
+ server.startHandshake();
+ fail();
+ } catch (SSLHandshakeException expected) {
}
- });
- executor.shutdown();
- try {
- client.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- }
- future.get();
- server.close();
- } else {
- try {
- c.serverSocket.accept();
- fail();
- } catch (SSLException expected) {
+ return null;
}
+ });
+ executor.shutdown();
+ try {
+ client.startHandshake();
+ fail();
+ } catch (SSLHandshakeException expected) {
}
+ future.get();
+ server.close();
client.close();
c.close();
}
@@ -526,6 +529,8 @@ public class SSLSocketTest extends TestCase {
assertNotNull(socket);
assertSame(client, socket);
+ assertTrue(socket instanceof SSLSocket);
+
synchronized (handshakeCompletedListenerCalled) {
handshakeCompletedListenerCalled[0] = true;
handshakeCompletedListenerCalled.notify();
@@ -675,7 +680,7 @@ public class SSLSocketTest extends TestCase {
public void test_SSLSocket_setUseClientMode_afterHandshake() throws Exception {
// can't set after handshake
- TestSSLEnginePair pair = TestSSLEnginePair.create(null);
+ TestSSLSocketPair pair = TestSSLSocketPair.create();
try {
pair.server.setUseClientMode(false);
fail();
@@ -699,9 +704,8 @@ public class SSLSocketTest extends TestCase {
@Override public Void call() throws Exception {
try {
server.startHandshake();
- assertFalse(StandardNames.IS_RI);
+ fail();
} catch (SSLHandshakeException expected) {
- assertTrue(StandardNames.IS_RI);
}
return null;
}
@@ -713,9 +717,10 @@ public class SSLSocketTest extends TestCase {
} catch (SSLHandshakeException expected) {
assertTrue(expected.getCause() instanceof CertificateException);
}
+ future.get();
client.close();
server.close();
- future.get();
+ c.close();
}
public void test_SSLSocket_clientAuth() throws Exception {
@@ -846,7 +851,11 @@ public class SSLSocketTest extends TestCase {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new Callable<Void>() {
@Override public Void call() throws Exception {
- server.startHandshake();
+ try {
+ server.startHandshake();
+ fail();
+ } catch (SSLHandshakeException expected) {
+ }
return null;
}
});
@@ -942,12 +951,10 @@ public class SSLSocketTest extends TestCase {
assertNotNull(p);
String[] cipherSuites = p.getCipherSuites();
- StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
assertNotSame(cipherSuites, ssl.getEnabledCipherSuites());
assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites()));
String[] protocols = p.getProtocols();
- StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
assertNotSame(protocols, ssl.getEnabledProtocols());
assertEquals(Arrays.asList(protocols), Arrays.asList(ssl.getEnabledProtocols()));
@@ -1327,10 +1334,7 @@ public class SSLSocketTest extends TestCase {
test_SSLSocket_interrupt_case(true, true);
test_SSLSocket_interrupt_case(true, false);
test_SSLSocket_interrupt_case(false, true);
- // Currently failing due to reader blocking closing thread http://b/10681815
- if (StandardNames.IS_RI) {
- test_SSLSocket_interrupt_case(false, false);
- }
+ test_SSLSocket_interrupt_case(false, false);
}
private void test_SSLSocket_interrupt_case(boolean readUnderlying, boolean closeUnderlying)
@@ -1373,7 +1377,7 @@ public class SSLSocketTest extends TestCase {
/**
* b/7014266 Test to confirm that an SSLSocket.close() on one
- * thread will interupt another thread blocked reading on the same
+ * thread will interrupt another thread blocked reading on the same
* socket.
*/
public void test_SSLSocket_interrupt_read() throws Exception {
@@ -1384,7 +1388,16 @@ public class SSLSocketTest extends TestCase {
c.host.getHostName(),
c.port,
false);
- ExecutorService executor = Executors.newSingleThreadExecutor();
+
+ // Create our own thread group so we can inspect the stack state later.
+ final ThreadGroup clientGroup = new ThreadGroup("client");
+ ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(clientGroup, r);
+ }
+ });
+
Future<Void> clientFuture = executor.submit(new Callable<Void>() {
@Override public Void call() throws Exception {
try {
@@ -1402,6 +1415,26 @@ public class SSLSocketTest extends TestCase {
SSLSocket server = (SSLSocket) c.serverSocket.accept();
server.startHandshake();
+
+ /*
+ * Wait for the client to at least be in the "read" method before
+ * calling close()
+ */
+ Thread[] threads = new Thread[1];
+ clientGroup.enumerate(threads);
+ if (threads[0] != null) {
+ boolean clientInRead = false;
+ while (!clientInRead) {
+ StackTraceElement[] elements = threads[0].getStackTrace();
+ for (StackTraceElement element : elements) {
+ if ("read".equals(element.getMethodName())) {
+ clientInRead = true;
+ break;
+ }
+ }
+ }
+ }
+
wrapping.close();
clientFuture.get();
server.close();
@@ -1423,6 +1456,120 @@ public class SSLSocketTest extends TestCase {
test.close();
}
+ public void test_SSLSocket_ClientHello_size() throws Exception {
+ // This test checks the size of ClientHello of the default SSLSocket. TLS/SSL handshakes
+ // with older/unpatched F5/BIG-IP appliances are known to stall and time out when
+ // the fragment containing ClientHello is between 256 and 511 (inclusive) bytes long.
+ //
+ // Since there's no straightforward way to obtain a ClientHello from SSLSocket, this test
+ // does the following:
+ // 1. Creates a listening server socket (a plain one rather than a TLS/SSL one).
+ // 2. Creates a client SSLSocket, which connects to the server socket and initiates the
+ // TLS/SSL handshake.
+ // 3. Makes the server socket accept an incoming connection on the server socket, and reads
+ // the first chunk of data received. This chunk is assumed to be the ClientHello.
+ // NOTE: Steps 2 and 3 run concurrently.
+ ServerSocket listeningSocket = null;
+ ExecutorService executorService = Executors.newFixedThreadPool(2);
+
+ // Some Socket operations are not interruptible via Thread.interrupt for some reason. To
+ // work around, we unblock these sockets using Socket.close.
+ final Socket[] sockets = new Socket[2];
+ try {
+ // 1. Create the listening server socket.
+ listeningSocket = ServerSocketFactory.getDefault().createServerSocket(0);
+ final ServerSocket finalListeningSocket = listeningSocket;
+ // 2. (in background) Wait for an incoming connection and read its first chunk.
+ final Future<byte[]> readFirstReceivedChunkFuture =
+ executorService.submit(new Callable<byte[]>() {
+ @Override
+ public byte[] call() throws Exception {
+ Socket socket = finalListeningSocket.accept();
+ sockets[1] = socket;
+ try {
+ byte[] buffer = new byte[64 * 1024];
+ int bytesRead = socket.getInputStream().read(buffer);
+ if (bytesRead == -1) {
+ throw new EOFException("Failed to read anything");
+ }
+ return Arrays.copyOf(buffer, bytesRead);
+ } finally {
+ IoUtils.closeQuietly(socket);
+ }
+ }
+ });
+
+ // 3. Create a client socket, connect it to the server socket, and start the TLS/SSL
+ // handshake.
+ executorService.submit(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(null, null, null);
+ SSLSocket client = (SSLSocket) sslContext.getSocketFactory().createSocket();
+ sockets[0] = client;
+ try {
+ // Enable SNI extension on the socket (this is typically enabled by default)
+ // to increase the size of ClientHello.
+ try {
+ Method setHostname =
+ client.getClass().getMethod("setHostname", String.class);
+ setHostname.invoke(client, "sslsockettest.androidcts.google.com");
+ } catch (NoSuchMethodException ignored) {}
+
+ // Enable Session Tickets extension on the socket (this is typically enabled
+ // by default) to increase the size of ClientHello.
+ try {
+ Method setUseSessionTickets =
+ client.getClass().getMethod(
+ "setUseSessionTickets", boolean.class);
+ setUseSessionTickets.invoke(client, true);
+ } catch (NoSuchMethodException ignored) {}
+
+ client.connect(finalListeningSocket.getLocalSocketAddress());
+ // Initiate the TLS/SSL handshake which is expected to fail as soon as the
+ // server socket receives a ClientHello.
+ try {
+ client.startHandshake();
+ fail();
+ return null;
+ } catch (IOException expected) {}
+ return null;
+ } finally {
+ IoUtils.closeQuietly(client);
+
+ // Cancel the reading task. If this task succeeded, then the reading task
+ // is done and this will have no effect. If this task failed prematurely,
+ // then the reading task might get unblocked (we're interrupting the thread
+ // it's running on), will fail early, and we'll thus save some time in this
+ // test.
+ readFirstReceivedChunkFuture.cancel(true);
+ }
+ }
+ });
+
+ // Wait for the ClientHello to arrive
+ byte[] clientHello = readFirstReceivedChunkFuture.get(10, TimeUnit.SECONDS);
+
+ // Check for ClientHello length that may cause handshake to fail/time out with older
+ // F5/BIG-IP appliances.
+ assertEquals("TLS record type: handshake", 22, clientHello[0]);
+ int fragmentLength = ((clientHello[3] & 0xff) << 8) | (clientHello[4] & 0xff);
+ if ((fragmentLength >= 256) && (fragmentLength <= 511)) {
+ fail("Fragment containing ClientHello is of dangerous length: "
+ + fragmentLength + " bytes");
+ }
+ } finally {
+ executorService.shutdownNow();
+ IoUtils.closeQuietly(listeningSocket);
+ IoUtils.closeQuietly(sockets[0]);
+ IoUtils.closeQuietly(sockets[1]);
+ if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
+ fail("Timed out while waiting for the test to shut down");
+ }
+ }
+ }
+
public void test_SSLSocket_sendsTlsFallbackScsv_Fallback_Success() throws Exception {
TestSSLContext context = TestSSLContext.create();
@@ -1461,6 +1608,42 @@ public class SSLSocketTest extends TestCase {
context.close();
}
+ // Confirms that communication without the TLS_FALLBACK_SCSV cipher works as it always did.
+ public void test_SSLSocket_sendsNoTlsFallbackScsv_Fallback_Success() throws Exception {
+ TestSSLContext context = TestSSLContext.create();
+
+ final SSLSocket client = (SSLSocket)
+ context.clientContext.getSocketFactory().createSocket(context.host, context.port);
+ final SSLSocket server = (SSLSocket) context.serverSocket.accept();
+
+ // Confirm absence of TLS_FALLBACK_SCSV.
+ assertFalse(Arrays.asList(client.getEnabledCipherSuites())
+ .contains(StandardNames.CIPHER_SUITE_FALLBACK));
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ Future<Void> s = executor.submit(new Callable<Void>() {
+ public Void call() throws Exception {
+ server.setEnabledProtocols(new String[] { "TLSv1", "SSLv3" });
+ server.startHandshake();
+ return null;
+ }
+ });
+ Future<Void> c = executor.submit(new Callable<Void>() {
+ public Void call() throws Exception {
+ client.setEnabledProtocols(new String[] { "SSLv3" });
+ client.startHandshake();
+ return null;
+ }
+ });
+ executor.shutdown();
+
+ s.get();
+ c.get();
+ client.close();
+ server.close();
+ context.close();
+ }
+
public void test_SSLSocket_sendsTlsFallbackScsv_InappropriateFallback_Failure() throws Exception {
TestSSLContext context = TestSSLContext.create();
@@ -1469,6 +1652,8 @@ public class SSLSocketTest extends TestCase {
final SSLSocket server = (SSLSocket) context.serverSocket.accept();
final String[] serverCipherSuites = server.getEnabledCipherSuites();
+
+ // Add TLS_FALLBACK_SCSV
final String[] clientCipherSuites = new String[serverCipherSuites.length + 1];
System.arraycopy(serverCipherSuites, 0, clientCipherSuites, 0, serverCipherSuites.length);
clientCipherSuites[serverCipherSuites.length] = StandardNames.CIPHER_SUITE_FALLBACK;
diff --git a/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java b/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java
index 7ee5778..571aa9c 100644
--- a/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java
+++ b/luni/src/test/java/libcore/javax/security/auth/x500/X500PrincipalTest.java
@@ -57,20 +57,21 @@ public class X500PrincipalTest extends TestCase {
*/
public void testGetName() throws Exception {
CertificateFactory certFactBC = CertificateFactory.getInstance("X.509", "BC");
- CertificateFactory certFactDRL = CertificateFactory.getInstance("X.509", "DRLCertFactory");
+ CertificateFactory certFactOpenSSL = CertificateFactory.getInstance("X.509",
+ "AndroidOpenSSL");
X509Certificate certBC = (X509Certificate)
certFactBC.generateCertificate(new ByteArrayInputStream(T61STRING_CERT));
- X509Certificate certDRL = (X509Certificate)
- certFactDRL.generateCertificate(new ByteArrayInputStream(T61STRING_CERT));
+ X509Certificate certOpenSSL = (X509Certificate)
+ certFactOpenSSL.generateCertificate(new ByteArrayInputStream(T61STRING_CERT));
- assertEquals(certBC, certDRL);
+ assertEquals(certBC, certOpenSSL);
assertEquals(certBC.getSubjectX500Principal(), certBC.getSubjectX500Principal());
- assertEquals(certDRL.getIssuerX500Principal(), certDRL.getIssuerX500Principal());
+ assertEquals(certOpenSSL.getIssuerX500Principal(), certOpenSSL.getIssuerX500Principal());
- assertEquals(certBC.getSubjectX500Principal(), certDRL.getSubjectX500Principal());
- assertEquals(certBC.getIssuerX500Principal(), certDRL.getIssuerX500Principal());
+ assertEquals(certBC.getSubjectX500Principal(), certOpenSSL.getSubjectX500Principal());
+ assertEquals(certBC.getIssuerX500Principal(), certOpenSSL.getIssuerX500Principal());
String[] formats = {
X500Principal.CANONICAL,
@@ -79,9 +80,9 @@ public class X500PrincipalTest extends TestCase {
};
for (String format : formats) {
assertEquals(certBC.getSubjectX500Principal().getName(format),
- certDRL.getSubjectX500Principal().getName(format));
+ certOpenSSL.getSubjectX500Principal().getName(format));
assertEquals(certBC.getIssuerX500Principal().getName(format),
- certDRL.getIssuerX500Principal().getName(format));
+ certOpenSSL.getIssuerX500Principal().getName(format));
}
String expected = ""
+ "cn=entrust.net certification authority (2048),"
diff --git a/luni/src/test/java/libcore/net/MimeUtilsTest.java b/luni/src/test/java/libcore/net/MimeUtilsTest.java
new file mode 100644
index 0000000..36476e9
--- /dev/null
+++ b/luni/src/test/java/libcore/net/MimeUtilsTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2014 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 libcore.net;
+
+import junit.framework.TestCase;
+
+import libcore.net.MimeUtils;
+
+public class MimeUtilsTest extends TestCase {
+ public void test_15715370() {
+ assertEquals("audio/flac", MimeUtils.guessMimeTypeFromExtension("flac"));
+ assertEquals("flac", MimeUtils.guessExtensionFromMimeType("audio/flac"));
+ assertEquals("flac", MimeUtils.guessExtensionFromMimeType("application/x-flac"));
+ }
+
+ public void test_16978217() {
+ assertEquals("image/x-ms-bmp", MimeUtils.guessMimeTypeFromExtension("bmp"));
+ assertEquals("image/x-icon", MimeUtils.guessMimeTypeFromExtension("ico"));
+ assertEquals("video/mp2ts", MimeUtils.guessMimeTypeFromExtension("ts"));
+ }
+
+ public void testCommon() {
+ assertEquals("audio/mpeg", MimeUtils.guessMimeTypeFromExtension("mp3"));
+ assertEquals("image/png", MimeUtils.guessMimeTypeFromExtension("png"));
+ assertEquals("application/zip", MimeUtils.guessMimeTypeFromExtension("zip"));
+
+ assertEquals("mp3", MimeUtils.guessExtensionFromMimeType("audio/mpeg"));
+ assertEquals("png", MimeUtils.guessExtensionFromMimeType("image/png"));
+ assertEquals("zip", MimeUtils.guessExtensionFromMimeType("application/zip"));
+ }
+}
diff --git a/luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java b/luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java
new file mode 100644
index 0000000..dc32da6
--- /dev/null
+++ b/luni/src/test/java/libcore/net/event/NetworkEventDispatcherTest.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2014 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 libcore.net.event;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for {@link NetworkEventDispatcher}.
+ */
+public class NetworkEventDispatcherTest extends TestCase {
+
+ public void testGetInstance_isSingleton() {
+ assertSame(NetworkEventDispatcher.getInstance(), NetworkEventDispatcher.getInstance());
+ }
+
+ public void testAddListener_null() throws Exception {
+ NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {};
+ try {
+ networkEventDispatcher.addListener(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testOnNetworkConfigurationChanged_noListeners() throws Exception {
+ NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {};
+ networkEventDispatcher.onNetworkConfigurationChanged();
+ }
+
+ public void testFireNetworkEvent_oneListener() throws Exception {
+ FakeNetworkEventListener listener = new FakeNetworkEventListener();
+ NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {};
+ networkEventDispatcher.addListener(listener);
+
+ networkEventDispatcher.onNetworkConfigurationChanged();
+
+ listener.assertNetworkConfigurationChangedEvent(1);
+ }
+
+ public void testRemoveEventListener() throws Exception {
+ FakeNetworkEventListener listener = new FakeNetworkEventListener();
+ NetworkEventDispatcher networkEventDispatcher = new NetworkEventDispatcher() {};
+ networkEventDispatcher.addListener(listener);
+ networkEventDispatcher.removeListener(listener);
+
+ networkEventDispatcher.onNetworkConfigurationChanged();
+
+ listener.assertNetworkConfigurationChangedEvent(0);
+ }
+
+ private static class FakeNetworkEventListener extends NetworkEventListener {
+
+ private int networkConfigurationChangedCount;
+
+ @Override
+ public void onNetworkConfigurationChanged() {
+ networkConfigurationChangedCount++;
+ }
+
+ public void assertNetworkConfigurationChangedEvent(int expectedCount) {
+ assertEquals(expectedCount, networkConfigurationChangedCount);
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/reflect/InternalNamesTest.java b/luni/src/test/java/libcore/reflect/InternalNamesTest.java
new file mode 100644
index 0000000..bb305ff
--- /dev/null
+++ b/luni/src/test/java/libcore/reflect/InternalNamesTest.java
@@ -0,0 +1,82 @@
+/*
+ * 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 libcore.reflect;
+
+import junit.framework.TestCase;
+
+public final class InternalNamesTest extends TestCase {
+ private final ClassLoader loader = InternalNames.class.getClassLoader();
+
+ public void testGetClassNull() {
+ try {
+ InternalNames.getClass(loader, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testGetInternalNameNull() {
+ try {
+ InternalNames.getInternalName(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testInternalNameToPrimitive() {
+ assertEquals(byte.class, InternalNames.getClass(loader, "B"));
+ assertEquals(char.class, InternalNames.getClass(loader, "C"));
+ assertEquals(double.class, InternalNames.getClass(loader, "D"));
+ assertEquals(float.class, InternalNames.getClass(loader, "F"));
+ assertEquals(int.class, InternalNames.getClass(loader, "I"));
+ assertEquals(long.class, InternalNames.getClass(loader, "J"));
+ assertEquals(short.class, InternalNames.getClass(loader, "S"));
+ assertEquals(boolean.class, InternalNames.getClass(loader, "Z"));
+ assertEquals(void.class, InternalNames.getClass(loader, "V"));
+ }
+
+ public void testPrimitiveToInternalName() {
+ assertEquals("B", InternalNames.getInternalName(byte.class));
+ assertEquals("C", InternalNames.getInternalName(char.class));
+ assertEquals("D", InternalNames.getInternalName(double.class));
+ assertEquals("F", InternalNames.getInternalName(float.class));
+ assertEquals("I", InternalNames.getInternalName(int.class));
+ assertEquals("J", InternalNames.getInternalName(long.class));
+ assertEquals("S", InternalNames.getInternalName(short.class));
+ assertEquals("Z", InternalNames.getInternalName(boolean.class));
+ assertEquals("V", InternalNames.getInternalName(void.class));
+ }
+
+ public void testInternalNameToClass() {
+ assertEquals(String.class, InternalNames.getClass(loader, "Ljava/lang/String;"));
+ }
+
+ public void testClassToInternalName() {
+ assertEquals("Ljava/lang/String;", InternalNames.getInternalName(String.class));
+ }
+
+ public void testInternalNameToPrimitiveArray() {
+ assertEquals(int[].class, InternalNames.getClass(loader, "[I"));
+ assertEquals(int[][][][].class, InternalNames.getClass(loader, "[[[[I"));
+ }
+
+ public void testInternalNameToObjectArray() {
+ assertEquals(String[].class, InternalNames.getClass(loader, "[Ljava/lang/String;"));
+ assertEquals(String[][][][].class,
+ InternalNames.getClass(loader, "[[[[Ljava/lang/String;"));
+ }
+}
diff --git a/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java b/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java
deleted file mode 100644
index d194548..0000000
--- a/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2007 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 libcore.sqlite;
-
-import SQLite.Exception;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import junit.framework.TestCase;
-
-
-/**
- * This class provides SQL unit test, which can be used by subclasses eg. to
- * test JDBC drivers.
- */
-abstract class AbstractSqlTest extends TestCase {
-
- /**
- * The first connection.
- */
- private Connection firstConnection;
-
- /**
- * The second connection.
- */
- private Connection secondConnection;
-
- /**
- * The statement from the first connection.
- */
- private Statement firstStmt;
-
- /**
- * The statement from the second connection.
- */
- private Statement secondStmt;
-
- /**
- * The values of the first column "one".
- */
- private final String[] ones = {"hello!", "goodbye"};
-
- /**
- * The values of the second column "two".
- */
- private final short[] twos = {10, 20};
-
- /**
- * The updated values of the first column "one".
- */
- private final String[] ones_updated;
-
- /** Creates a new instance of this class */
- public AbstractSqlTest() {
- super();
- ones_updated = new String[ones.length];
- for (int i = 0; i < ones.length; i++) {
- ones_updated[i] = ones[i] + twos[i];
- }
- }
-
- /**
- * Sets up a unit test, by creating two statements from two connections and
- * creating a test table.
- *
- * @exception SQLException if there is a problem accessing the database
- * @throws Exception
- * @exception Exception may be thrown by subclasses
- */
- @Override
- protected void setUp() throws java.lang.Exception {
- Class.forName(getDriverClassName()).newInstance();
- firstConnection = DriverManager.getConnection(getConnectionURL());
- firstConnection.setTransactionIsolation(getTransactionIsolation());
- secondConnection = DriverManager.getConnection(getConnectionURL());
- secondConnection.setTransactionIsolation(getTransactionIsolation());
- firstStmt = firstConnection.createStatement();
- firstStmt.execute("create table tbl1(one varchar(10), two smallint)");
- secondStmt = secondConnection.createStatement();
- }
-
- /**
- * Tears down a unit test, by setting the auto commit property of the first
- * connection back to true, dropping the test table and closing the two
- * connections.
- */
- @Override
- protected void tearDown() throws SQLException {
- firstStmt.close();
- secondStmt.close();
- firstConnection.setAutoCommit(true);
- firstStmt = firstConnection.createStatement();
- firstStmt.execute("drop table tbl1");
- firstStmt.close();
- firstConnection.close();
- secondConnection.close();
- }
-
- /**
- * Adds some rows to the test table and asserts that the rows can be
- * retrieved again.
- *
- * @throws SQLException if there is a problem accessing the database
- */
- private void autoCommitInsertSelect() throws SQLException {
- firstStmt.getConnection().setAutoCommit(true);
- for (int i = 0; i < ones.length; i++) {
- firstStmt.execute("insert into tbl1 values('" + ones[i] + "',"
- + twos[i] + ")");
- }
- assertAllFromTbl1(firstStmt, ones, twos);
- }
-
- /**
- * Asserts that the expected values can be selected from the test table.
- *
- * @param stmt the statement to be used for the selection of the data
- * @param ones the expected values of the column 'one'
- * @param twos the expected values of the column 'two'
- * @throws SQLException if there is a problem accessing the database
- */
- private void assertAllFromTbl1(Statement stmt, String[] ones, short[] twos)
- throws SQLException {
- ResultSet rs = stmt.executeQuery("select * from tbl1");
- int i = 0;
- for (; rs.next(); i++) {
- assertTrue(i < ones.length);
- assertEquals(ones[i], rs.getString("one"));
- assertEquals(twos[i], rs.getShort("two"));
- }
- assertTrue(i == ones.length);
- }
-
- public void testAutoCommitInsertSelect() throws SQLException{
- autoCommitInsertSelect();
- }
-
- /**
- * Tests the following sequence after successful insertion of some test
- * data:
- * - update data from connection one
- * - select data from connection two (-> should have the old values)
- * - commit data from connection one
- * - select data from connection two (-> should have the new values)
- *
- * @throws SQLException if there is a problem accessing the database
- */
- public void testUpdateSelectCommitSelect() throws SQLException {
- autoCommitInsertSelect();
- firstStmt.getConnection().setAutoCommit(false);
- updateOnes(firstStmt, ones_updated, twos);
- assertAllFromTbl1(secondStmt, ones, twos);
- firstStmt.getConnection().commit();
- assertAllFromTbl1(secondStmt, ones_updated, twos);
- }
-
- /**
- * Tests the following sequence after successful insertion of some test
- * data:
- * - update data from connection one
- * - select data from connection two (-> should have the old values)
- * - rollback data from connection one
- * - select data from connection two (-> should still have the old values)
- *
- * @throws SQLException if there is a problem accessing the database
- */
- public void testUpdateSelectRollbackSelect() throws SQLException {
- autoCommitInsertSelect();
- firstStmt.getConnection().setAutoCommit(false);
- updateOnes(firstStmt, ones_updated, twos);
- assertAllFromTbl1(secondStmt, ones, twos);
- firstStmt.getConnection().rollback();
- assertAllFromTbl1(secondStmt, ones, twos);
- }
-
- /**
- * Updates the values in column 'one'
- * @param stmt the statement to be used to update the data
- * @param ones_updated the updated valus of column 'one'
- * @param twos the reference values of column 'two'
- * @throws SQLException if there is a problem accessing the database
- */
- private void updateOnes(Statement stmt, String[] ones_updated, short[] twos)
- throws SQLException {
- for (int i = 0; i < ones_updated.length; i++) {
- stmt.execute("UPDATE tbl1 SET one = '" + ones_updated[i]
- + "' WHERE two = " + twos[i]);
- }
- }
-
- protected abstract String getConnectionURL();
-
- protected abstract String getDriverClassName();
-
- protected abstract int getTransactionIsolation();
-
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldBlobTest.java b/luni/src/test/java/libcore/sqlite/OldBlobTest.java
deleted file mode 100644
index 3289d38..0000000
--- a/luni/src/test/java/libcore/sqlite/OldBlobTest.java
+++ /dev/null
@@ -1,135 +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 libcore.sqlite;
-
-import SQLite.Blob;
-import SQLite.Database;
-import SQLite.Exception;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import tests.support.Support_SQL;
-
-public final class OldBlobTest extends OldSQLiteTest {
-
- private static Blob testBlob = null;
-
- private static Database db = null;
-
- public void setUp() throws java.lang.Exception {
- super.setUp();
- testBlob = new Blob();
-
- super.setUp();
- Support_SQL.loadDriver();
- db = new Database();
- db.open(dbFile.getPath(), 0);
-
- db.exec("create table B(id integer primary key, val blob)",null);
- db.exec("insert into B values(1, zeroblob(128))", null);
- db.exec("insert into B values(2, zeroblob(128))", null);
- db.exec("insert into B values(3, zeroblob(128))", null);
-
- // can not fill Blob with data at this point...
- /*
- File resources = Support_Resources.createTempFolder();
- BufferedReader r = null;
- try {
- Class c = Class.forName(this.getClass().getName());
- assertNotNull(c);
- file = Class.forName(this.getClass().getName())
- .getResourceAsStream("/blob.c");
- r = new BufferedReader(new InputStreamReader(file));
- } catch (NullPointerException e) {
- fail("Should not throw NullPointerException reading file"
- + e.getMessage());
- }
- OutputStream out = testBlob.getOutputStream();
- String s = null;
- while ((s = r.readLine()) != null) {
- out.write(r.readLine().getBytes());
- }
- out.flush();
- out.close();
- testBlob.close();
- */
- }
-
- @Override public void tearDown() throws java.lang.Exception {
- testBlob.close();
- super.tearDown();
- }
-
- /**
- * db.open_blob is not supported.
- */
- public void testBlob() throws Exception, IOException {
- byte[] b = new byte[4];
- byte[] b128 = new byte[128];
- for (int i = 0; i < b128.length; i++) {
- b128[i] = (byte) i;
- }
- Blob blob = db.open_blob(dbFile.getPath(), "B", "val", 1, true);
- try {
-
- OutputStream os = blob.getOutputStream();
- os.write(b128);
- os.close();
-
- InputStream is = blob.getInputStream();
- is.skip(96);
- assertEquals(4,is.read(b));
- is.close();
- } finally {
- blob.close();
- }
- }
-
- public void testGetInputStream() {
- InputStream in = testBlob.getInputStream();
- try {
- in.read();
- fail("Exception not thrown for invalid Blob.");
- } catch (Throwable e) {
- //ok
- }
- }
-
- public void testGetOutputStream() {
- OutputStream out = testBlob.getOutputStream();
-
- try {
- out.write(null);
- fail("Write operation unsupported");
- } catch (Throwable e) {
- assertEquals("Write operation unsupported", e.getMessage());
- }
- }
-
- public void testClose() {
- assertNotNull(testBlob);
-
- testBlob.close();
- // inputStream either null or some error occurs
- try {
- // TODO This does look a bit weird. Revisit later.
- assertNull(testBlob.getInputStream());
- } catch (Throwable e) {
- //ok
- }
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java b/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java
deleted file mode 100644
index f2cbc57..0000000
--- a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java
+++ /dev/null
@@ -1,1224 +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 libcore.sqlite;
-
-import SQLite.Authorizer;
-import SQLite.Blob;
-import SQLite.BusyHandler;
-import SQLite.Callback;
-import SQLite.Constants;
-import SQLite.Database;
-import SQLite.Exception;
-import SQLite.Function;
-import SQLite.FunctionContext;
-import SQLite.ProgressHandler;
-import SQLite.Stmt;
-import SQLite.TableResult;
-import SQLite.Trace;
-import SQLite.Vm;
-import java.io.File;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URL;
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.logging.Logger;
-import tests.support.DatabaseCreator;
-import tests.support.MockFunction;
-import tests.support.ThreadPool;
-
-public final class OldDatabaseTest extends OldSQLiteTest {
-
- private static ErrorTracker tracker = null;
-
- private Statement statement;
-
- private Database db = null;
-
- private static final int numThreads = 10;
-
- private static final int numOfRecords = 30;
-
- @Override public void setUp() throws java.lang.Exception {
- super.setUp();
- assertNotNull("Could not establish DB connection",conn);
- tracker = new ErrorTracker();
-
- statement = conn.createStatement();
-
- // Cleanup tables if necessary
-
- DatabaseMetaData meta = conn.getMetaData();
- assertNotNull(meta);
- ResultSet userTab = meta.getTables(null, null, null, null);
- while (userTab.next()) {
- String tableName = userTab.getString("TABLE_NAME");
- this.statement.execute("drop table " + tableName);
- }
-
- // Create default test table
- statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
- statement.close();
-
- db = new Database();
- db.open(dbFile.getPath(), 0);
- db.busy_handler(null);
- }
-
- public void tearDown() throws java.lang.Exception {
- try {
- db.close();
- } catch (Exception e) {
- if (!(e.getMessage().equals("database already closed"))) {
- System.err.println("Error closing DB " + dbFile.getPath());
- }
- }
- tracker.reset();
- super.tearDown();
- }
-
- public void testDatabase() throws Exception {
- // db closed
- Database db2 = new Database();
- db.close();
- db2 = new Database();
- db2.open(dbFile.getPath(), 0);
- db2.close();
- db.open(dbFile.getPath(), 0);
- //db is open
- db2.open(dbFile.getPath(), 0);
- db2.close();
- }
-
- public void testOpen() throws Exception {
- db.close();
- db.open(dbFile.getPath(), 0);
- // open second db while db1 still open
- Database db2 = new Database();
- db2.open(dbFile.getPath(), 0);
- db2.open(dbFile.getPath(), 0);
- db2.close();
- // open non db file
- try {
- URL file = OldDatabaseTest.class.getResource("/blob.c");
- db2.open(file.getPath(), 0);
- fail("Should not be able to open non db file");
- } catch (SQLite.Exception e) {
- assertEquals("unknown error in open", e.getMessage());
- }
- }
-
- public void testOpen_aux_file() {
- File temp = null;
- try {
- db.open_aux_file("");
- fail("open should fail");
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
-
- /*
- try {
- temp = File.createTempFile("openAuxMethod", ".db");
- db.open_aux_file("");
- db.exec("create table AUX_TABLE", null);
- db.close();
- } catch (Exception e) {
- temp.delete();
- fail("Error handling temporary file "+e.getMessage());
- e.printStackTrace();
- } catch (IOException e) {
- temp.delete();
- fail("Could not create temporary File");
- e.printStackTrace();
- }
- try {
- db.open(dbFile.getPath(),0);
- db.exec("select * from AUX_TABLE", null);
- fail("Statement should fail");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- temp.delete();
- */
- }
-
- public void testClose() throws Exception {
- try {
- db.close();
- db.get_table("test");
- fail();
- } catch (Exception e) {
- assertTrue(e.getMessage().equals("database already closed"));
- try {
- db.open(dbFile.getPath(), 0);
- } catch (Exception e1) {
- fail("Database object could not be reopened after 'close': "
- + e.getMessage());
- e1.printStackTrace();
- }
- }
-
- try {
- db.close();
- db.close();
- fail();
- } catch (Exception e) {
- assertTrue(e.getMessage().equals("database already closed"));
- db.open(dbFile.getPath(), 0);
- }
- }
-
- public void testExecStringCallback() throws Exception {
- TableResult res = new TableResult();
- db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(1, 10, 20)", null);
- db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
- db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1 + " where 1", null);
- String row[] = (String[]) res.rows.elementAt(0);
- assertEquals(Integer.parseInt(row[0]), 1);
- assertEquals(Integer.parseInt(row[1]), 10);
- assertEquals(Integer.parseInt(row[2]), 20);
- }
-
- public void testExecStringCallbackStringArray() throws Exception {
- TableResult res = new TableResult();
- String args[] = new String[1];
- args[0] = "table";
- db.exec("select name from sqlite_master where type = '%q';", res, args);
- String[] s = (String[]) res.rows.elementAt(0);
- assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
-
- try {
- db.exec("select name from sqlite_master where type = ", res, args);
- fail("Testmethod should fail");
- } catch (Exception e) {
- // Ok
- }
- }
-
- public void testLast_insert_rowid() throws Exception {
- assertEquals(0, db.last_insert_rowid());
- db.exec("create table TEST5(id integer, firstname text, lastname text);", null);
- db.exec("insert into TEST5 values (1,'James','Bond');", null);
- db.exec("insert into TEST5 values (2,'Fiona','Apple');", null);
- assertEquals(2, db.last_insert_rowid());
- assertEquals(db.last_insert_rowid(), db.last_insert_rowid());
-
- db.exec("drop table TEST5;", null);
- assertEquals(2, db.last_insert_rowid());
- }
-
- /**
- * Reason for failure unknown: Database should be locked. Specification
- * of interrupt is scarce.
- */
- public void testInterrupt() throws Exception, SQLException {
- ThreadPool threadPool = new ThreadPool(numThreads);
-
- // initialization
- ResultSet userTabs;
- userTabs = conn.getMetaData().getTables(null, null, null, null);
- while (userTabs.next()) {
- String tableName = userTabs.getString("TABLE_NAME");
- if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
- statement.execute(DatabaseCreator.DROP_TABLE1);
- }
- }
- db.exec(DatabaseCreator.CREATE_TABLE3, null);
- db.exec(DatabaseCreator.CREATE_TABLE1, null);
-
- int id1 = numOfRecords - 3;
- threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
- // should not be able to do any other insertions since task 1 holds lock
- int id2 = numOfRecords + 3;
- threadPool
- .runTask(createTask2Interrupt(id2, dbFile.getPath(), tracker));
-
- threadPool.join();
-
- List<String> errors = tracker.getErrors();
- System.out.println("Last error: " + db.error_message());
- if (errors.size() > 0) {
- assertEquals(errors.get(0), db.error_string(Constants.SQLITE_LOCKED));
- for (String s : errors) {
- Logger.global.info("INTERRUPT Error: " + s);
- }
-
- } else {
- fail("Should have one exception: database should be locked.");
- }
-
- // reset
- db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", null);
- db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", null);
- }
-
- /**
- * Returns wrong number for updates: returns value > 1 for select.
- */
- public void testChanges() throws Exception {
- TableResult res = new TableResult();
- assertTrue(db.changes() == 0);
- db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(2, 5, 7);", null);
- int rows = (int) db.changes();
- assertEquals(1,db.changes());
- db.exec("update " + DatabaseCreator.SIMPLE_TABLE1
- + " set speed = 7, size= 5 where id = 2;", null);
- assertEquals(1,db.changes());
- db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
- assertEquals(0,db.changes());
- db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(8, 5, 7);", null);
- db.exec("Update "+DatabaseCreator.SIMPLE_TABLE1+" set speed = 10;",null);
- assertTrue(db.changes() > 2);
- }
-
- /**
- * method test fails once in a while. Cannot be sure that exception is
- * thrown in every test execution.
- */
- public void testBusy_handler() throws SQLException, Exception {
- TestBusyHandler bh = new TestBusyHandler();
- db.busy_handler(bh);
- int counter = 0;
- ThreadPool threadPool = new ThreadPool(numThreads);
-
- // initialization
- ResultSet userTabs;
- userTabs = conn.getMetaData().getTables(null, null, null, null);
- while (userTabs.next()) {
- String tableName = userTabs.getString("TABLE_NAME");
- if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
- statement.execute(DatabaseCreator.DROP_TABLE1);
- }
- }
- db.exec(DatabaseCreator.CREATE_TABLE3, null);
- db.exec(DatabaseCreator.CREATE_TABLE1, null);
-
-
- try {
- conn.setAutoCommit(false);
- int id1 = numOfRecords - 3;
- threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
- int id2 = numOfRecords + 3;
- threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
- int oldID = 5;
- int newID = 100;
- threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID,
- tracker));
-
- threadPool.join();
-
- List<String> errors = tracker.getErrors();
- if (errors.size() > 0) {
-// assertEquals(errors.get(0),
-// db.error_string(Constants.SQLITE_LOCKED));
- for (String s: errors) {
- System.out.println("Round 2 Error: "+s);
- }
- } else {
- fail("No error happened");
- }
-
- // reset
-
-
- db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
- null);
- db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
- null);
-//
-// // increase timeout for retry
-// db.busy_timeout(1000);
-// db.busy_handler(bh);
-// tracker.reset();
-
-// threadPool = new ThreadPool(numThreads);
-//
-// threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
-// threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
-//
-// threadPool.join();
-//
-// errors = tracker.getErrors();
-// if (errors.size() > 0) {
-// // assertEquals(errors.get(0),
-// // db.error_string(Constants.SQLITE_LOCKED));
-// for (String s: errors) {
-// System.out.println("Round 2 Error"+s);
-// }
-// } else {
-// // ok
-// System.out.println("BUSY: No Error!");
-// }
-//
-//
- } finally {
- conn.setAutoCommit(true);
- db.exec(DatabaseCreator.DROP_TABLE1, null);
- db.exec(DatabaseCreator.DROP_TABLE3, null);
- }
- }
-
- /**
- * test fails. Cannot be sure that exception is thrown every time.
- * Database does not lock values.
- */
- public void testBusy_timeout() throws Exception, SQLException {
- int counter = 0;
- ThreadPool threadPool = new ThreadPool(numThreads);
-
- // initialization
- ResultSet userTabs = conn.getMetaData().getTables(null, null, null, null);
- while (userTabs.next()) {
- String tableName = userTabs.getString("TABLE_NAME");
- if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
- statement.execute(DatabaseCreator.DROP_TABLE1);
- }
- }
- db.exec(DatabaseCreator.CREATE_TABLE3, null);
- db.exec(DatabaseCreator.CREATE_TABLE1, null);
-
- // test run
- try {
- conn.setAutoCommit(false);
-
-// DatabaseCreator.fillTestTable1(conn, numOfRecords);
- // set to fail immediately if table is locked.
- db.busy_handler(null);
- db.busy_timeout(0);
- int id1 = numOfRecords - 3;
-
- threadPool.runTask(createTask2(id1, dbFile.getPath(), tracker));
- int id2 = numOfRecords + 3;
- threadPool.runTask(createTask1(id2, dbFile.getPath(), tracker));
- int oldID = 5;
- int newID = 100;
- threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID,
- tracker));
-
- threadPool.join();
-
- List<String> errors = tracker.getErrors();
- assertTrue("No error occurred on DB but should have",errors.size() > 0);
-
- assertEquals(errors.get(0),
- db.error_string(Constants.SQLITE_LOCKED));
- assertEquals(errors.get(0), "database is locked");
-
- // reset
-
- db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
- null);
- db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
- null);
-
- // increase timeout for retry
- db.busy_timeout(10000);
- db.busy_handler(null);
- tracker.reset();
- threadPool = new ThreadPool(numThreads);
-
- threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
- threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
-
- threadPool.join();
-
- errors = tracker.getErrors();
- if (errors.size() > 0) {
- fail("busy timeout should prevent from lock exception!");
- for (String s: errors) {
- System.out.println("Round 2 Error"+s);
- }
- } else {
- // ok
- }
- } finally {
- conn.setAutoCommit(true);
- // cleanup
- db.exec(DatabaseCreator.DROP_TABLE1, null);
- db.exec(DatabaseCreator.DROP_TABLE3, null);
- }
- }
-
- public void testGet_tableString() throws Exception {
- TableResult emptyTable = new TableResult();
- //select from empty table
- TableResult res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- assertEquals(res.toString(), emptyTable.toString());
- //fill table-> t
-// DatabaseCreator.fillSimpleTable1(conn);
-// res = db.get_table("select * from "
-// + DatabaseCreator.SIMPLE_TABLE1);
-// assertFalse(emptyTable.toString().equals(res.toString()));
-
- db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 + " VALUES(1, 10, 20)", null);
- res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1
- + " where 1", null);
- String row[] = (String[]) res.rows.elementAt(0);
- assertEquals(Integer.parseInt(row[0]), 1);
- assertEquals(Integer.parseInt(row[1]), 10);
- assertEquals(Integer.parseInt(row[2]), 20);
- }
-
- public void testGet_tableStringStringArray() throws Exception {
- String args[] = new String[1];
- args[0] = "table";
- String argsFail[] = new String[1];
- try {
- db.get_table("select name from sqlite_master where type = ", argsFail);
- fail("Testmethod should fail");
- } catch (Exception e) {
- }
-
- TableResult res = db.get_table(
- "select name from sqlite_master where type = '%q'",
- args);
- String[] s = (String[]) res.rows.elementAt(0);
- assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
- }
-
- public void testGet_tableStringStringArrayTableResult() throws Exception {
- String args[] = new String[1];
- String argsFail[] = new String[1];
- TableResult res = new TableResult();
- TableResult defaultTableRes = new TableResult();
- args[0] = "table";
-
- try {
- db.get_table("select name from sqlite_master where type = '%q'", argsFail, res);
- assertEquals(defaultTableRes.toString(), res.toString());
- } catch (Exception e) {
- db.get_table("select name from sqlite_master where type = '%q'", args, res);
- String[] s = (String[]) res.rows.elementAt(0);
- assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
- System.out.println("DatabaseTest.testGet_tableStringStringArrayTableResult() "
- + Arrays.toString(res.types));
- }
- }
-
- public void testComplete() {
- assertFalse(db.complete("create"));
- assertTrue(db.complete("create table TEST (res double);"));
- }
-
- public void testVersion() {
- String version = db.version();
- if (version != null) {
- assertTrue(Integer.parseInt(db.version().substring(0, 1)) > 0);
- assertEquals(db.version(), db.version());
- } else {
- fail("DB version info missing");
- }
- }
-
- public void testDbversion() throws Exception {
- String verNo = "";
- try {
- verNo = db.dbversion();
- db.close();
- assertEquals(db.dbversion(),"unknown");
- db.open(dbFile.getPath(), 0);
- assertEquals(verNo, db.dbversion());
- } catch (Exception e) {
- db.open(dbFile.getPath(), 0);
- }
-
- assertTrue(Integer.parseInt(verNo.substring(0, 1))>= 3 );
-
- }
-
- public void testCreate_function() throws Exception {
- double input = 1.0;
- db.exec("create table TEST (res double)", null);
- db.exec("insert into TEST values (" + Double.toString(input) + ")",
- null);
- TableResult res = new TableResult();
- Function sinFunc = (Function) new SinFunc();
- db.create_function("sin", 1, sinFunc);
- db.exec("select sin(res) from TEST WHERE res = "
- + Double.toString(input), res);
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
- double sinusVal = Double.parseDouble(val);
- double funcVal = Math.sin(input);
-
- assertTrue(Math.round(funcVal) == Math.round(sinusVal));
- }
-
- /**
- * Aggregation function not called.
- */
- public void testCreate_aggregate() throws Exception {
- TestTrace t = new TestTrace();
- MockFunction aggFunction = new MockFunction();
- db.exec("create table TEST(id integer, firstname text, lastname text)", null);
- db.exec("insert into TEST values(3, 'James', 'Bond'); ", null);
- db.exec("insert into TEST values(4, 'Fiona', 'Apple'); ", null);
- db.trace((Trace) t);
- db.create_aggregate("myaggfunc", 1, aggFunction);
- db.function_type("myaggfunc", Constants.SQLITE3_TEXT);
- db.exec("PRAGMA show_datatypes = on", null);
-
- assertFalse(aggFunction.functionCalled);
- assertFalse(aggFunction.stepCalled);
- assertFalse(aggFunction.lastStepCalled);
- db.exec("select myaggfunc(TEST.firstname) from TEST", t);
- assertTrue(aggFunction.stepCalled);
- assertTrue(aggFunction.lastStepCalled);
- assertTrue(aggFunction.functionCalled);
-
- assertEquals("James Fiona ",aggFunction.getAggValue());
- db.exec("drop table TEST", null);
-
- try {
- db.create_aggregate("myaggfunc", 0, null);
- } catch (Throwable e) {
- assertEquals("null SQLite.Function not allowed",e.getMessage());
- }
-
- try {
- db.create_aggregate("myaggfunc", 0, aggFunction);
- } catch (Throwable e) {
- assertEquals("wrong number of arguments to function myaggfunc()",e.getMessage());
- }
- }
-
- public void testFunction_type() throws Exception {
- double input = 1.0;
- TableResult res = new TableResult();
- Function sinFunc = (Function) new SinFunc();
-
- db.exec("PRAGMA show_datatypes = on", null);
- db.exec("create table TEST (res double)", null);
- db.exec("insert into TEST values (" + Double.toString(input) + ")",
- null);
-
- db.create_function("sin", 1, sinFunc);
- db.function_type("sin", Constants.SQLITE_FLOAT);
- res = db.get_table("select sin(res) from TEST WHERE res = "
- + Double.toString(input));
-
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
- assertTrue("double".equalsIgnoreCase(res.types[0]));
- assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val)));
-
- // function determines return type: test that Double type is returned.
- db.function_type("sin", Constants.SQLITE_BLOB);
- Stmt s = db.prepare("select sin(res) from TEST WHERE res = ?");
- s.bind(1, input);
- s.step();
-
- res = db.get_table("select sin(res) from TEST WHERE res = "
- + Double.toString(input));
- assertTrue("double".equalsIgnoreCase(res.types[0]));
- row = (String[]) res.rows.elementAt(0);
- val = row[0];
- assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val)));
- }
-
- public void testLast_error() {
- assertEquals(db.last_error(), Constants.SQLITE_OK);
- try {
- db.exec("create table TEST (res double)",null);
- db.exec("create table TEST (res double)",null);
- fail("Error should have happened");
- } catch (Exception e) {
- assertEquals(db.last_error(),db.last_error());
- assertEquals(db.last_error(),Constants.SQLITE_ERROR);
- }
- }
-
- public void testSet_last_error() {
- assertEquals(db.last_error(), Constants.SQLITE_OK);
- try {
- db.exec("sel from test;", null);
- } catch (Exception e) {
- assertEquals(Constants.SQLITE_ERROR,db.last_error());
- }
- }
-
- public void testError_message() {
- String statement = "create table TEST (res double)";
- try {
- db.exec(statement,null);
- db.exec(statement,null);
- fail("DB Error expected");
- } catch (Exception e) {
- String dbError = db.error_message();
- assertTrue(e.getMessage().equals(dbError));
-
- }
- }
-
- public void testError_string() {
- TestTrace t = new TestTrace();
- assertEquals(db.last_error(), Constants.SQLITE_OK);
- String errorString = db.error_string(Constants.SQLITE_ERROR);
- try {
- db.trace((Trace) t);
- db.exec("create table TEST (res double)", t);
- db.exec("create table TEST (res double)", t);
- } catch (Exception e) {
- assertEquals(db.last_error(), Constants.SQLITE_ERROR);
- if (db.is3()) {
- assertEquals("Unsupported Method (sqlite 3): error_string", db
- .error_string(db.last_error()), errorString);
- }
- }
- }
-
- /**
- * ASCII encoding does not work: a UTF encoded val is returned. Spec is not
- * sufficient. Might be that test impl is wrong or String constructor for
- * the ASCII encoding.
- */
- public void testSet_encoding() throws UnsupportedEncodingException, Exception {
- String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana?
- TableResult res = new TableResult();
- String refOutput = null;
- Stmt stat = null;
-
- // DB setup
- db.exec("create table encodingTest (encoded text DEFAULT NULL);",
- null);
- stat = db
- .prepare("insert into encodingTest(encoded) values(:one);");
- stat.bind(1, input);
- stat.step();
- // stat.close();
- db.exec("select * from encodingTest;", res);
- String[] encInput = (String[]) res.rows.elementAt(0);
- String output = encInput[0];
- assertEquals(input, output);
- // db.exec("delete from encodingTest where 1", null);
-
- // tests for different encoding schemes
- String[] charsetNames = {"UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE"};
- for (int i = 0; i < charsetNames.length; i++) {
- byte[] encInputBytes = input.getBytes(charsetNames[i]);
- db.set_encoding(charsetNames[i]);
- db.exec("select * from encodingTest;", res);
- String[] encOutput = (String[]) res.rows.elementAt(0);
- String inputAsString = new String(encInputBytes,charsetNames[i]);
- assertEquals(inputAsString, encOutput[0]);
- }
-
- // Default tests
- db.set_encoding("UTF-16");
- db.exec("select * from encodingTest;", res);
- String[] encOutput1 = (String[]) res.rows.elementAt(0);
- assertEquals("Got "+encOutput1[0]+" as UTF-16",input,encOutput1[0]);
-
- db.set_encoding("US-ASCII");
- db.exec("select * from encodingTest;", res);
- String[] encOutput2 = (String[]) res.rows.elementAt(0);
- assertEquals(new String(input.getBytes(),"US-ASCII"),encOutput2[0]);
-
- // DB teardown
- stat.close();
- db.exec("delete from encodingTest", null);
-
- // Default tests
- try {
- db.set_encoding("");
- fail("invalid input should fail");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * Callback never made for authorization. Results of private table are
- * returned withouth furhter checks.
- *
- * Test fails -> implemented correctly?
- */
- public void testSet_authorizer() throws Exception {
- TableResult resPriv = null;
- TableResult resPub = null;
- TableResult emptyTable = new TableResult();
- String insertPublic = "insert into public_table values(1,2)";
- String insertPrivate = "insert into private_table values(1,2)";
- // prepare, authorizer is not activated yet
- db.exec("create table public_table(c1 integer, c2 integer);", null);
- db.exec("create table private_table(c1 integer, c2 integer);", null);
- // inserts
- db.exec(insertPublic, null);
- db.exec(insertPrivate, null);
- // selects
- resPriv = db.get_table("select * from private_table");
- resPub = db.get_table("select * from public_table");
-
-// db.exec("delete from public_table where 1", null);
-// TableResult emptyPubTable = db.exec("select * from public");
-
- // set Authorizer (positive case): denies private table
- AuthorizerCallback cb = new AuthorizerCallback();
- db.set_authorizer(cb);
- //select
-
- db.exec("select * from private_table", cb);
- assertTrue(cb.wasCalled());
-
- /*
- TableResult res = db.get_table("select * from private_table");
- assertEquals(emptyTable.toString(),res.toString());
- assertFalse(emptyTable.equals(resPriv));
-
- res = db.get_table("select * from public_table");
- assertEquals(resPub,res);
- */
-
- // Try insert
- try {
- db.exec(insertPublic, null);
- fail("authorization failed");
- } catch (Exception e) {
- }
-
- try {
- db.exec(insertPrivate, null);
- fail("authorization failed");
- } catch (Exception e1) {
- // ok
- }
- }
-
- public void testTrace() throws Exception {
- String stmt = "create table TEST (res double);";
- TestTrace t = new TestTrace();
- assertFalse(t.traceCalled);
- assertEquals(db.last_error(),Constants.SQLITE_OK);
- db.trace((Trace) t);
- db.exec(stmt,t);
- assertTrue(t.traceCalled);
- assertEquals(t.getTrace(),stmt);
-
- try {
- db.close();
- db.exec(stmt,t);
- fail("Exception Expected");
- } catch (Exception e) {
- //ok
- }
- }
-
- public void testCompileString() throws Exception {
- db.compile("select name from sqlite_master;");
- try {
- db.compile("test");
- fail("Compiling of inaccurate statement does not fail.");
- } catch (Exception e) {
- }
- }
-
- public void testCompileStringStringArray() throws Exception {
- String args[] = new String[1];
- args[0] = "table";
- db.compile("select name from sqlite_master where type = '%q';",args);
-
- try {
- db.compile("test",null);
- fail("Compiling of inaccurate statement does not fail.");
- } catch (Exception e) {
- }
- }
-
- public void testPrepare() throws Exception {
- Stmt st = null;
- Stmt st2 = null;
- // test empty statement
- try {
- st = db.prepare("");
- assertEquals(0, st.bind_parameter_count());
- st.step();
- fail("stmt should not be prepared");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- // test statement with unbound arguments
- try {
- st2 = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(3, st2.bind_parameter_count());
- assertEquals(3, st2.bind_parameter_index(":three"));
- assertEquals(":two", st2.bind_parameter_name(2));
- } finally {
- st2.close();
- }
-
- try {
- db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values(:one,:two,:three,:four);");
- } catch (Exception e) {
- assertEquals("table " + DatabaseCreator.SIMPLE_TABLE1
- + " has 3 columns but 4 values were supplied", e
- .getMessage());
- }
-
- try {
- db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values(5, '10, 20);");
- } catch (Exception e) {
- assertEquals("unrecognized token: \"'10, 20);\"", e.getMessage());
- }
-
- try {
- db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values(5, 10 20);");
- } catch (Exception e) {
- assertEquals("near \"20\": syntax error", e.getMessage());
- }
-
- }
-
- /**
- * Not supported.
- */
- public void testOpen_blob() throws Exception, java.lang.Exception {
- Stmt statement2;
- Blob blobInput = new Blob();
-
- // Create test input Blob
- InputStream inStream = null;
- byte[] in = {(byte) 1, (byte) 2, (byte) 3, (byte) 4};
-
- // setup test input
- db.exec("create table TEST (res blob)",null);
- inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c");
- assertNotNull(inStream);
-
- // insert byte array in db
- statement2 = db.prepare("insert into TEST(res) values (?)");
- statement2.bind(1, in);
- statement2.step();
- statement2.close();
-
- // read from db
- Blob blob = db.open_blob(dbFile.getPath(), "TEST", "res", 1, true);
- if (blob == null) {
- fail("Blob could not be retrieved");
- }
- //read from blob and compare values (positive case)
- InputStream is = blob.getInputStream();
-
- int i = 0;
- int outByte = 0;
- byte[] out = new byte[4];
- while ((outByte = is.read()) > -1) {
- out[i] = (byte) outByte;
- i++;
- }
- is.close();
-
- blob.close();
-
- assertTrue(Arrays.equals(in, out));
-
- //read from blob and compare values (default blob)
- db.exec("insert into TEST values(zeroblob(128))", null);
- Blob blob2 = db.open_blob(dbFile.getPath(), "TEST", "res", 2, true);
- is = blob2.getInputStream();
- for (i = 0; i < 128; i++) {
- assertEquals(0, is.read());
- }
- is.close();
- }
-
- public void testIs3() {
- int ver = Integer.parseInt(db.version().substring(0,1));
- if (db.is3()) {
- assertTrue( ver == 3);
- } else {
- assertTrue(ver != 3);
- }
- }
-
- public void testProgress_handler() throws Exception {
- int inputVal = 3;
- TestProgressHandler prog = new TestProgressHandler();
- db.exec("create table TEST5(id integer, firstname text, lastname text)",null);
- Vm vm = db.compile("select * from TEST5; "
- + "insert into TEST5 values(3, 'James', 'Bond'); "
- + "delete from TEST5 where id = 3; "
- + "select * from TEST5");
- int stmt = 0;
- do {
- ++stmt;
- if (stmt > inputVal) {
- db.progress_handler(inputVal, prog);
- } else {
- assertEquals(0, prog.getCounts());
- }
- while (vm.step(prog)) {
- }
- } while (vm.compile());
- assertEquals(inputVal,prog.getCounts());
-
- // Boundary value test
- inputVal = 0;
- TestProgressHandler progBoundary = new TestProgressHandler();
- db.progress_handler(inputVal, progBoundary);
- Vm vm2 = db.compile("select * from TEST5; "
- + "insert into TEST5 values(3, 'James', 'Bond'); "
- + "delete from TEST5 where id = 3; "
- + "select * from TEST5");
- do {
- vm2.step(progBoundary);
- } while (vm2.compile());
- assertEquals(inputVal, progBoundary.getCounts());
-
- try {
- db.exec("drop table TEST5",null);
- } catch (Exception e) {
- System.out.println(e.getMessage());
- e.printStackTrace();
- }
- }
-
- class SinFunc implements Function {
- public void function(FunctionContext fc, String args[]) {
- Double d = new Double(args[0]);
- fc.set_result(Math.sin(d.doubleValue()));
- }
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class TestTrace implements Trace,Callback {
-
- private StringBuffer buf = new StringBuffer();
-
- public boolean traceCalled = false;
-
- public String getTrace() {
- return buf.toString();
- }
-
- public void trace(String stmt) {
- traceCalled = true;
- buf.append(stmt);
- }
-
- public void columns(String[] coldata) {}
-
- public boolean newrow(String[] rowdata) {
- return false;
- }
-
- public void types(String[] types) {}
- }
-
- class AuthorizerCallback implements Authorizer, Callback {
-
- private boolean isAuthorizing = false;
-
- public boolean wasCalled() {
- return isAuthorizing;
- }
-
- public int authorize(int action, String arg1, String arg2, String arg3,
- String arg4) {
- Logger.global.info("DB authorization callback " + action + " " + arg1 + " " + arg2 + " "
- + arg3 + " " + arg4 + " ");
- this.isAuthorizing = true;
- if (action != Constants.SQLITE_SELECT || arg1.contains("private_table")) {
- return Constants.SQLITE_DENY;
- } else {
- return Constants.SQLITE_OK;
- }
- }
-
- public void columns(String[] coldata) {}
-
- public boolean newrow(String[] rowdata) {
- return false;
- }
-
- public void types(String[] types) {}
-
- }
-
- class TestBusyHandler implements BusyHandler, Callback {
-
- public boolean busy(String table, int count) {
- return true;
- }
-
- public void columns(String[] coldata) {}
-
- public boolean newrow(String[] rowdata) {
- return false;
- }
-
- public void types(String[] types) {}
- }
-
- class TestProgressHandler implements ProgressHandler, Callback {
-
- private boolean progressed = false;
-
- private int counter = 0;
-
- public int getCounts() {
- return counter;
- }
-
- public boolean progress() {
- this.progressed = true;
- counter++;
- return true;
- }
-
- public void columns(String[] coldata) {}
-
- public boolean newrow(String[] rowdata) {
- return false;
- }
-
- public void types(String[] types) {}
- }
-
- /**
- * This method creates a Runnable that executes insert operation for the first table
- */
- private static Runnable createTask2Interrupt(final int id,
- final String dbName, final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- Database db = new Database();
- try {
- String value = DatabaseCreator.defaultString + id;
-
- db.open(dbName, 0);
- String insertQuery = "INSERT INTO "
- + DatabaseCreator.TEST_TABLE1
- + " (id, field1, field2, field3) VALUES(" + id
- + ", '" + value + "', " + id + ", " + id + ")";
- db.exec(insertQuery, null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
- try {
- db.interrupt();
- db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1
- + " WHERE id=" + id, null);
- } catch (Exception e1) {
- errorTracker.registerException(this, e1);
- }
- }
- }
- };
- }
-
- /**
- * This method creates a Runnable that executes delete operation for the first table
- */
- private static Runnable createTask1(final int id, final String dbName,
- final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- try {
- Database db = new Database();
- db.open(dbName, 0);
- db.exec("DELETE FROM "
- + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id, null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
- }
- }
- };
- }
-
- /**
- * This method creates a Runnable that executes insert operation for the first table
- */
- private static Runnable createTask2(final int id, final String dbName,
- final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- try {
- String value = DatabaseCreator.defaultString + id;
- Database db = new Database();
- db.open(dbName, 0);
- String insertQuery = "INSERT INTO "
- + DatabaseCreator.TEST_TABLE1
- + " (id, field1, field2, field3) VALUES(" + id
- + ", '" + value + "', " + id + ", " + id + ")";
- db.exec(insertQuery, null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
-
- }
- }
- };
- }
-
- /**
- * This method creates a Runnable that executes update operation for the one record of the first
- * table
- */
- private static Runnable createTask3(final int oldID, final String dbName,
- final int newID, final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- Database db = new Database();
- try {
- db.open(dbName, 0);
- String value = DatabaseCreator.defaultString + newID;
- String updateQuery = "UPDATE "
- + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID
- + ", field1='" + value + "', field2=" + newID
- + ", field3=" + newID + " WHERE id=" + oldID;
- db.exec(updateQuery, null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
- }
- }
- };
- }
-
- private class ErrorTracker {
-
- private List<String> errors = new ArrayList<String>();
-
- public void registerException(Runnable runnable, Exception e) {
- System.out.println("Registered: " + e.getMessage());
- errors.add(e.getMessage());
- }
-
- public List<String> getErrors() {
- return errors;
- }
-
- public void reset() {
- errors.clear();
- }
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java b/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java
deleted file mode 100644
index 0924317..0000000
--- a/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java
+++ /dev/null
@@ -1,314 +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 libcore.sqlite;
-
-import SQLite.Database;
-import SQLite.Exception;
-import SQLite.Function;
-import SQLite.FunctionContext;
-import SQLite.Stmt;
-import SQLite.TableResult;
-import java.io.UnsupportedEncodingException;
-import java.sql.SQLException;
-import java.sql.Statement;
-import tests.support.DatabaseCreator;
-
-public final class OldFunctionContextTest extends OldSQLiteTest {
-
- private Database db = null;
-
- @Override public void setUp() throws java.lang.Exception {
- super.setUp();
- db = new Database();
- db.open(dbFile.getPath(), 0);
- Statement st = conn.createStatement();
- st.execute(DatabaseCreator.CREATE_TABLE2);
- st.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
- st.close();
- }
-
- public void testSet_resultString() throws Exception {
- TestFCString testString = new TestFCString();
- db.exec("insert into " + DatabaseCreator.TEST_TABLE2
- + " (ftext) values ('TestInput')", null);
- db.create_function("test", 1, testString);
- TableResult res = db.get_table("select test(ftext) from "
- + DatabaseCreator.TEST_TABLE2);
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
-
- assertEquals("TestInput", val);
- }
-
- public void testSet_resultInt() throws Exception {
- TestFCInt testInt = new TestFCInt();
- db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (1,'" + testInt.intVal + "',3)", null);
- db.create_function("testInt", 1, testInt);
- TableResult res = db.get_table("select testInt(speed) from "
- + DatabaseCreator.SIMPLE_TABLE1);
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
-
- assertEquals(testInt.intVal, Integer.parseInt(val));
- }
-
- public void testSet_resultDouble() throws Exception {
- SinFunc testD = new SinFunc();
- db.exec("insert into " + DatabaseCreator.TEST_TABLE2
- + " (fdouble) values (" + testD.testDouble + ")", null);
- db.create_function("testDouble", 1, testD);
- TableResult res = db.get_table("select testDouble(fdouble) from "
- + DatabaseCreator.TEST_TABLE2);
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
-
- assertEquals(testD.testDouble, Double.parseDouble(val));
-
- assertTrue(testD.functionCalled);
- }
-
- public void testSet_error() throws Exception {
- TestFCError testError = new TestFCError();
- SinFunc testD = new SinFunc();
- db.exec("insert into " + DatabaseCreator.TEST_TABLE2
- + " (fdouble) values (" + testD.testDouble + ")", null);
- db.create_function("testError", 1, testError);
-
- try {
- TableResult res = db.get_table("select testError(fdouble) from "
- + DatabaseCreator.TEST_TABLE2);
- fail("Should get Exception");
- } catch (Exception e) {
- assertEquals("error in step", e.getMessage());
- }
-
- assertFalse(testD.functionCalled);
- }
-
- public void testSet_resultByteArray() throws Exception, UnsupportedEncodingException {
- Stmt st = null;
- TestFCByteArray testBinArrayFnc = new TestFCByteArray();
- String expected = "";
- expected = "X'" + getHexString(testBinArrayFnc.byteVal) + "'";
-
- // setup
- db.exec("create table testBinaryData (binVal BINARY) ;", null);
-
- try {
- st = db.prepare("insert into testBinaryData values (?)");
- st.bind(1, testBinArrayFnc.byteVal);
- st.step();
-
-
- db.create_function("testBinArray", 1, testBinArrayFnc);
- TableResult res = db
- .get_table("select testBinArray(binVal) from testBinaryData");
-
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
-
- assertTrue(expected.equalsIgnoreCase(val));
-
- assertTrue(testBinArrayFnc.functionCalled);
-
- } finally {
- //teardown
- db.exec("drop table testBinaryData;", null);
- }
- }
-
- /**
- * ZeroBlob not supported
- */
- public void testSet_result_zeroblob() throws Exception,
- UnsupportedEncodingException {
- Stmt st = null;
- TestFCZeroBlob testZeroBlobFnc = new TestFCZeroBlob();
- byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3};
-
-
- // setup
- db.exec("create table testBinaryData (binVal BINARY) ;", null);
-
- try {
- st = db.prepare("insert into testBinaryData values (?)");
- st.bind(1, byteVal);
- st.step();
-
-
- db.create_function("testZeroBlob", 0, testZeroBlobFnc);
- TableResult res = db
- .get_table("select testZeroBlob() from testBinaryData");
- TableResult res2 = db.get_table("select zeroblob("
- + testZeroBlobFnc.numBytes + ") from testBinaryData");
-
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
-
- assertNotNull(val);
-
- assertEquals(((String[]) res2.rows.elementAt(0))[0], val);
- assertTrue(testZeroBlobFnc.functionCalled);
-
- } finally {
- // teardown
- db.exec("drop table if exists testBinaryData;", null);
- }
- }
-
- /**
- * Test Method results in a segmentation fault
- */
- public void testCount() throws SQLException, Exception {
- TestFCCount countTest = new TestFCCount();
- int inputCount = 10;
-
- assertFalse(countTest.functionCalled);
-
- DatabaseCreator.fillTestTable2(conn, inputCount);
- db.create_function("testCount", 0, countTest);
- // the invokation of testCount leads to a Segmentation fault
- /*
- TableResult res = db
- .get_table("select testCount() from "+DatabaseCreator.TEST_TABLE2);
-
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
-
- assertTrue(countTest.functionCalled);
- assertEquals(inputCount,Integer.parseInt(val));
- */
-
- }
-
- class TestFCError implements Function {
- public boolean functionCalled = false;
- public String errorMsg = "FunctionError";
-
- public void function(FunctionContext fc, String args[]) {
- functionCalled = true;
- fc.set_error(errorMsg);
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class TestFCCount implements Function {
- public boolean functionCalled = false;
- public int noOfRows = 0;
-
- public void function(FunctionContext fc, String args[]) {
- functionCalled = true;
- noOfRows = fc.count();
- fc.set_result(noOfRows);
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class TestFCZeroBlob implements Function {
- public int numBytes = 16;
- public boolean functionCalled = false;
-
- public void function(FunctionContext fc, String args[]) {
- functionCalled = true;
- fc.set_result_zeroblob(numBytes);
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class TestFCString implements Function {
- public String testString = "TestString";
- public boolean functionCalled;
-
- public void function(FunctionContext fc, String args[]) {
- assertNotNull(args);
- functionCalled = true;
- fc.set_result(args[0]);
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class TestFCInt implements Function {
- public int intVal = Integer.MAX_VALUE;
- public boolean functionCalled;
-
- public void function(FunctionContext fc, String args[]) {
- assertNotNull(args);
- functionCalled = true;
- fc.set_result(Integer.parseInt(args[0]));
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class TestFCByteArray implements Function {
- public byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3};
- public boolean functionCalled;
-
- public void function(FunctionContext fc, String args[]) {
- assertNotNull(args);
- functionCalled = true;
- fc.set_result(args[0].getBytes());
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- class SinFunc implements Function {
- public Double testDouble = 3.0;
- public boolean functionCalled = false;
-
- public void function(FunctionContext fc, String args[]) {
- Double d = new Double(args[0]);
- functionCalled = true;
- fc.set_result(d.doubleValue());
- }
-
- public void last_step(FunctionContext fc) {}
- public void step(FunctionContext fc, String[] args) {}
- }
-
- static final byte[] HEX_CHAR_TABLE = {
- (byte)'0', (byte)'1', (byte)'2', (byte)'3',
- (byte)'4', (byte)'5', (byte)'6', (byte)'7',
- (byte)'8', (byte)'9', (byte)'a', (byte)'b',
- (byte)'c', (byte)'d', (byte)'e', (byte)'f'
- };
-
- public static String getHexString(byte[] raw)
- throws UnsupportedEncodingException {
- byte[] hex = new byte[2 * raw.length];
- int index = 0;
-
- for (byte b : raw) {
- int v = b & 0xFF;
- hex[index++] = HEX_CHAR_TABLE[v >>> 4];
- hex[index++] = HEX_CHAR_TABLE[v & 0xF];
- }
- return new String(hex, "ASCII");
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java
deleted file mode 100644
index 48eeab1..0000000
--- a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2007 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 libcore.sqlite;
-
-import java.io.File;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.SQLException;
-
-/**
- * Tests the SQLite.JDBCDriver.
- */
-public class OldJDBCDriverFunctionalTest extends AbstractSqlTest {
- private File dbFile = null;
- private String connectionURL = "empty";
-
- @Override protected void tearDown() throws SQLException {
- super.tearDown();
- dbFile.delete();
- }
-
- @Override protected String getConnectionURL() {
- if (connectionURL.equals("empty")) {
- String tmp = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(tmp);
- if (tmpDir.isDirectory()) {
- try {
- dbFile = File.createTempFile("JDBCDriverFunctionalTest", ".db", tmpDir);
- } catch (IOException e) {
- System.err.println("error creating temporary DB file.");
- }
- dbFile.deleteOnExit();
- } else {
- System.err.println("java.io.tmpdir does not exist");
- }
-
- connectionURL = "jdbc:sqlite:/" + dbFile.getPath();
- }
-
- return connectionURL;
- }
-
- @Override protected String getDriverClassName() {
- return "SQLite.JDBCDriver";
- }
-
- @Override protected int getTransactionIsolation() {
- return Connection.TRANSACTION_SERIALIZABLE;
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java
deleted file mode 100644
index ae06dc6..0000000
--- a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java
+++ /dev/null
@@ -1,113 +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 libcore.sqlite;
-
-import SQLite.JDBCDriver;
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.DriverPropertyInfo;
-import java.sql.SQLException;
-
-
-public final class OldJDBCDriverTest extends OldJDBCDriverFunctionalTest {
-
- /**
- * The SQLite db file.
- */
- private JDBCDriver jDriver;
-
- private Driver returnedDriver;
-
- @Override public void setUp() throws java.lang.Exception {
- super.setUp();
- returnedDriver = DriverManager.getDriver(getConnectionURL());
- if (returnedDriver instanceof JDBCDriver) {
- this.jDriver = (JDBCDriver) returnedDriver;
- }
- }
-
- public void testJDBCDriver() {
- assertTrue(returnedDriver instanceof JDBCDriver);
- }
-
- public void testAcceptsURL() {
- try {
- if (this.jDriver != null) {
- assertTrue(jDriver.acceptsURL(getConnectionURL()));
- } else {
- fail("no Driver available");
- }
- } catch (SQLException e) {
- fail("Driver does not accept URL");
- e.printStackTrace();
- }
- }
-
- public void testConnect() {
- try {
- if (this.jDriver != null) {
- Connection c = jDriver.connect(getConnectionURL(), null);
- assertFalse(c.isClosed());
- DriverManager.getConnection(getConnectionURL());
- } else {
- fail("no Driver available");
- }
- } catch (SQLException e) {
- fail("Driver does not connect");
- e.printStackTrace();
- }
- }
-
- public void testGetMajorVersion() {
- if (this.jDriver != null) {
- assertTrue(jDriver.getMajorVersion() > 0);
- } else {
- fail("no Driver available");
- }
- }
-
- public void testGetMinorVersion() {
- if (this.jDriver != null) {
- assertTrue(jDriver.getMinorVersion() > 0);
- } else {
- fail("no version information available");
- }
- }
-
- public void testGetPropertyInfo() throws SQLException {
- DriverPropertyInfo[] info = null;
- if (this.jDriver != null) {
- info = jDriver.getPropertyInfo(getConnectionURL(), null);
- assertNotNull(info);
- assertTrue(info.length > 0);
- } else {
- fail("no Driver available");
- }
-
- assertNotNull(info);
-
- }
-
- public void testJdbcCompliant() {
- if (this.jDriver != null) {
- assertFalse(jDriver.jdbcCompliant());
- } else {
- fail("no version information available");
- }
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java b/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java
deleted file mode 100644
index e6b7f22..0000000
--- a/luni/src/test/java/libcore/sqlite/OldSQLiteTest.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 libcore.sqlite;
-
-import java.io.File;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.util.logging.Logger;
-import junit.framework.TestCase;
-
-public abstract class OldSQLiteTest extends TestCase {
-
- public static Connection conn;
-
- public static File dbFile = null;
-
- @Override public void setUp() throws Exception {
- String tmp = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(tmp);
- try {
- if (tmpDir.isDirectory()) {
- dbFile = File.createTempFile("sqliteTest", ".db", tmpDir);
- dbFile.deleteOnExit();
- } else {
- System.out.println("ctsdir does not exist");
- }
-
- Class.forName("SQLite.JDBCDriver").newInstance();
-
- if (!dbFile.exists()) {
- Logger.global.severe("DB file could not be created. Tests can not be executed.");
- } else {
- conn = DriverManager.getConnection("jdbc:sqlite:/" + dbFile.getPath());
- }
- assertNotNull("Error creating connection", conn);
- } catch (IOException e) {
- System.out.println("Problem creating test file in " + tmp);
- }
- }
-
- @Override public void tearDown() throws java.lang.Exception {
- if (!conn.isClosed()) {
- conn.close();
- }
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/OldStmtTest.java b/luni/src/test/java/libcore/sqlite/OldStmtTest.java
deleted file mode 100644
index 4d379ed..0000000
--- a/luni/src/test/java/libcore/sqlite/OldStmtTest.java
+++ /dev/null
@@ -1,823 +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 libcore.sqlite;
-
-import SQLite.Constants;
-import SQLite.Database;
-import SQLite.Stmt;
-import SQLite.TableResult;
-import java.sql.Connection;
-import tests.support.DatabaseCreator;
-import tests.support.Support_SQL;
-
-public class OldStmtTest extends OldSQLiteTest {
-
- private Database db;
- private Stmt st;
-
- private static final String CREATE_ALL_TYPES = "create table type ("
- + " BoolVal BOOLEAN,"
- + " IntVal INT,"
- + " LongVal LONG,"
- + " Bint BIGINT,"
- + " Tint TINYINT,"
- + " Sint SMALLINT,"
- + " Mint MEDIUMINT,"
- + " IntegerVal INTEGER,"
- + " RealVal REAL,"
- + " DoubleVal DOUBLE,"
- + " FloatVal FLOAT,"
- + " DecVal DECIMAL,"
- + " NumVal NUMERIC,"
- + " charStr CHAR(20),"
- + " dateVal DATE,"
- + " timeVal TIME,"
- + " TS TIMESTAMP,"
- + " DT DATETIME,"
- + " TBlob TINYBLOB,"
- + " BlobVal BLOB,"
- + " MBlob MEDIUMBLOB,"
- + " LBlob LONGBLOB,"
- + " TText TINYTEXT,"
- + " TextVal TEXT,"
- + " MText MEDIUMTEXT,"
- + " LText LONGTEXT,"
- + " MaxLongVal BIGINT,"
- + " MinLongVal BIGINT,"
- + " validURL URL,"
- + " invalidURL URL);";
-
- static final String INSERT_ALL_TYPES = "insert into type ("
- + "BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,IntegerVal, RealVal, DoubleVal, "
- + "FloatVal, DecVal,NumVal, charStr, dateVal, timeVal, TS,DT, TBlob, BlobVal, MBlob, "
- + "LBlob,TText, TextVal, MText, LText, MaxLongVal, MinLongVal, validURL, invalidURL) "
- + "values (1, -1, 22, 2, 33,3, 1, 2, 3.9, 23.2, 33.3, 44,5, 'test string', '1799-05-26',"
- + "'12:35:45', '2007-10-09 14:28:02.0','1221-09-22 10:11:55', 1, 2, 3, 4,"
- + "'Test text message tiny', 'Test text', 'Test text message medium',"
- + "'Test text message long', " + Long.MAX_VALUE + ", " + Long.MIN_VALUE + ","
- + "null, null);";
-
- static final String ALL_TYPES_TABLE = "type";
-
- @Override public void setUp() throws Exception {
- super.setUp();
- Support_SQL.loadDriver();
- db = new Database();
- db.open(dbFile.getPath(), 0);
- db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null);
- DatabaseCreator.fillSimpleTable1(conn);
-
- st = new Stmt();
- }
-
- @Override public void tearDown() throws Exception {
- if (st != null) {
- try {
- st.close();
- } catch (Exception e) {
- }
- }
- db.close();
- Connection con = Support_SQL.getConnection();
- con.close();
- super.tearDown();
- }
-
- public void testStmt() throws Exception {
- db.prepare("");
-
- try {
- st.step();
- fail("Cannot execute non prepared Stmt");
- } catch (SQLite.Exception expected) {
- }
- }
-
- public void testPrepare() throws Exception {
- try {
- st = db.prepare("");
- st.prepare();
- fail("statement is closed");
- } catch (SQLite.Exception expected) {
- assertEquals("stmt already closed", expected.getMessage());
- }
-
- st = new Stmt();
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- assertFalse(st.prepare());
- st = new Stmt();
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertFalse(st.prepare());
- st = new Stmt();
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.bind(1, 1);
- st.bind(2, 10);
- st.bind(3, 30);
- assertFalse(st.prepare());
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1
- + "; " + "delete from " + DatabaseCreator.SIMPLE_TABLE1
- + " where id = 5; " + "insert into "
- + DatabaseCreator.SIMPLE_TABLE1 + " values(5, 10, 20); "
- + "select * from " + DatabaseCreator.SIMPLE_TABLE1 + ";");
- assertTrue(st.prepare());
- assertTrue(st.prepare());
- assertTrue(st.prepare());
- assertFalse(st.prepare());
- }
-
- public void testStep() throws Exception {
- try {
- st.step();
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("stmt already closed", expected.getMessage());
- }
-
- st = new Stmt();
- st = db.prepare("select name from sqlite_master where type = 'table'");
- st.step();
- }
-
- public void testClose() throws Exception {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.close();
-
- try {
- st.step();
- fail("Test fails");
- } catch (SQLite.Exception expected) {
- assertEquals("stmt already closed", expected.getMessage());
- }
- }
-
- public void testReset() throws Exception {
- db.exec("create table TEST (res integer not null)", null);
-
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, 1);
- st.step();
-
- // verify that parameter is still bound
- st.reset();
- assertEquals(1,st.bind_parameter_count());
- st.step();
-
- TableResult count = db.get_table("select count(*) from TEST where res=1", null);
-
- String[] row0 = (String[]) count.rows.elementAt(0);
- assertEquals(2, Integer.parseInt(row0[0]));
- }
-
- public void testClear_bindings() {
- try {
- st.clear_bindings();
- } catch (SQLite.Exception expected) {
- assertEquals("unsupported", expected.getMessage());
- }
- }
-
- public void testBindIntInt() throws Exception {
- int input = 0;
- int maxVal = Integer.MAX_VALUE;
- int minVal = Integer.MIN_VALUE;
-
- db.exec("create table TEST (res integer)", null);
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, input);
- st.step();
-
- st.reset();
- st.bind(1,maxVal);
- st.step();
-
- st.reset();
- st.bind(1,minVal);
- st.step();
-
- TableResult r = db.get_table("select * from TEST");
-
- String[] row0 = (String[]) r.rows.elementAt(0);
- assertEquals(input,Integer.parseInt(row0[0]));
-
- String[] row1 = (String[]) r.rows.elementAt(1);
- assertEquals(maxVal,Integer.parseInt(row1[0]));
-
- String[] row2 = (String[]) r.rows.elementAt(2);
- assertEquals(minVal,Integer.parseInt(row2[0]));
-
- try {
- st.close();
- st.bind(1,Integer.MIN_VALUE);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- }
- }
-
- public void testBindIntLong() throws Exception {
- long input = 0;
- long maxVal = Long.MAX_VALUE;
- long minVal = Long.MIN_VALUE;
-
- db.exec("create table TEST (res long)", null);
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, input);
- st.step();
-
- st.reset();
- st.bind(1,maxVal);
- st.step();
-
- st.reset();
- st.bind(1,minVal);
- st.step();
-
- TableResult r = db.get_table("select * from TEST");
-
- String[] row0 = (String[]) r.rows.elementAt(0);
- assertEquals(input,Long.parseLong(row0[0]));
-
- String[] row1 = (String[]) r.rows.elementAt(1);
- assertEquals(maxVal,Long.parseLong(row1[0]));
-
- String[] row2 = (String[]) r.rows.elementAt(2);
- assertEquals(minVal,Long.parseLong(row2[0]));
-
- try {
- st.close();
- st.bind(1,Long.MIN_VALUE);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- }
- }
-
- public void testBindIntDouble() throws Exception {
- double input = 0.0;
- double maxVal = Double.MAX_VALUE;
- double minVal = Double.MIN_VALUE;
- double negInf = Double.NEGATIVE_INFINITY;
- double posInf = Double.POSITIVE_INFINITY;
- double nan = Double.NaN;
-
- db.exec("create table TEST (res double)", null);
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, input);
- st.step();
-
- st.reset();
- st.bind(1, maxVal);
- st.step();
-
- st.reset();
- st.bind(1, minVal);
- st.step();
-
- st.reset();
- st.bind(1, negInf);
- st.step();
-
- st.reset();
- st.bind(1, posInf);
- st.step();
-
- st.reset();
- st.bind(1, nan);
- st.step();
-
-
- TableResult r = db.get_table("select * from TEST");
-
- String[] row0 = (String[]) r.rows.elementAt(0);
- assertTrue(Double.compare(input, Double.parseDouble(row0[0])) == 0);
-
- String[] row1 = (String[]) r.rows.elementAt(1);
- assertFalse(Double.compare(maxVal, Double.parseDouble(row1[0])) == 0);
- assertTrue(Double.compare(maxVal, Double.parseDouble(row1[0])) < 0);
- assertTrue(Double.isInfinite(Double.parseDouble(row1[0])));
-
- String[] row2 = (String[]) r.rows.elementAt(2);
- assertTrue(Double.compare(minVal, Double.parseDouble(row2[0])) == 0);
-
- String[] row3 = (String[]) r.rows.elementAt(3);
- assertEquals("Double.NEGATIVE_INFINITY SQLite representation",
- "-Inf", row3[0]);
-
- String[] row4 = (String[]) r.rows.elementAt(4);
- assertEquals("Double.POSITIVE_INFINITY SQLite representation",
- "Inf", row4[0]);
-
- String[] row5 = (String[]) r.rows.elementAt(4);
- assertEquals("Double.Nan SQLite representation", "Inf", row5[0]);
-
- try {
- st.close();
- st.bind(1,0.0);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- }
- }
-
- public void testBindIntByteArray() throws Exception {
- String name = "Hello World";
- byte[] b = name.getBytes();
- String stringInHex = "";
-
- db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
- st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
- + " values (:one, :two);");
- st.bind(1, 2);
- st.bind(2, b);
- st.step();
-
- //compare what was stored with input based on Hex representation
- // since type of column is CHAR
- TableResult r = db.get_table("select * from "
- + DatabaseCreator.PARENT_TABLE);
- String[] row = (String[]) r.rows.elementAt(0);
-
- for (byte aByte : b) {
- stringInHex += Integer.toHexString(aByte);
- }
- stringInHex = "X'" + stringInHex + "'";
- assertTrue(stringInHex.equalsIgnoreCase(row[1]));
-
- try {
- st.close();
- st.bind(1,name.getBytes());
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- }
- }
-
- public void testBindIntString() throws Exception {
- String name = "Hello World";
- db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
- st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
- + " values (:one, :two);");
- st.bind(1, 2);
- st.bind(2, name);
- st.step();
-
- TableResult r = db.get_table("select * from "
- + DatabaseCreator.PARENT_TABLE);
- String[] row = (String[]) r.rows.elementAt(0);
- assertEquals(name,row[1]);
-
- try {
- st.close();
- st.bind(1,name);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- }
- }
-
- public void testBindInt() throws Exception {
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.bind(4);
- st.bind(1, 4);
- st.bind(2, 10);
- st.bind(3, 30);
- st.step();
- fail();
- } catch (SQLite.Exception expected) {
- // What happens if null is bound to non existing variable position
- assertEquals("parameter position out of bounds", expected.getMessage());
- }
-
- // functional tests
-
- try {
- st.reset();
- st.bind(1);
- st.bind(2, 10);
- st.bind(3, 30);
- st.step();
- fail();
- } catch (SQLite.Exception expected) {
- // What happens if null is bound to NON NULL field
- assertEquals("SQL logic error or missing database", expected.getMessage());
- }
-
- st.reset();
- st.bind(1, 3);
- st.bind(2);
- st.bind(3, 30);
- st.step();
- }
-
- public void testBind_zeroblob() {
- try {
- st.bind_zeroblob(1, 128);
- fail();
- } catch (SQLite.Exception expected) {
- assertEquals("unsupported", expected.getMessage());
- }
- }
-
- public void testBind_parameter_count() throws Exception {
- try {
- st.bind_parameter_count();
- fail();
- } catch (SQLite.Exception expected) {
- assertEquals("stmt already closed", expected.getMessage());
- }
-
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(3, st.bind_parameter_count());
-
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (?, ?, ?)");
- assertEquals(3, st.bind_parameter_count());
-
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- assertEquals(0, st.bind_parameter_count());
-
- try {
- st.close();
- st.bind_parameter_count();
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- }
-
- }
-
- public void testBind_parameter_name() {
- try {
- st.bind_parameter_name(1);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("stmt already closed", expected.getMessage());
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(":one", st.bind_parameter_name(1));
- assertEquals(":two", st.bind_parameter_name(2));
- assertEquals(":three", st.bind_parameter_name(3));
- st.bind_parameter_name(4);
- fail();
- } catch (SQLite.Exception expected) {
- assertEquals("parameter position out of bounds", expected.getMessage());
- }
- }
-
- public void testBind_parameter_index() throws Exception {
- try {
- st.bind_parameter_index("");
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("stmt already closed", expected.getMessage());
- }
-
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(3, st.bind_parameter_index(":three"));
-
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(0, st.bind_parameter_index(":t"));
-
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (?, ?, ?)");
- assertEquals(0, st.bind_parameter_index("?"));
- }
-
- public void testColumn_int() throws Exception {
- db.exec(CREATE_ALL_TYPES, null);
- db.exec(INSERT_ALL_TYPES, null);
-
- Object columnObject;
- int intColumn;
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
-
- st = db.prepare(selectStmt);
- st.step();
- // select 'speed' value
- columnObject = st.column(1);
- intColumn = st.column_int(1);
- assertNotNull(intColumn);
-
- assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
- int stSpeed = Integer.parseInt(columnObject.toString());
- assertNotNull(stSpeed);
- assertEquals( intColumn, stSpeed);
- assertEquals(10,stSpeed);
-
- selectStmt = "select TextVal from "+ ALL_TYPES_TABLE;
-
- st = db.prepare(selectStmt);
- st.step();
- st.column_int(0);
- }
-
- public void testColumn_long() throws Exception {
- Object columnObject;
- long longColumn;
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- st = db.prepare(selectStmt);
- st.step();
- columnObject = st.column(1);
- longColumn = st.column_long(1);
- assertNotNull(longColumn);
- // column declared as integer
- assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
- int stSpeed = Integer.parseInt(columnObject.toString());
- assertNotNull(stSpeed);
- assertEquals( longColumn, stSpeed);
-
- try {
- st.column_long(4);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("column out of bounds", expected.getMessage());
- }
-
- try {
- st.column_long(-1);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("column out of bounds", expected.getMessage());
- }
- }
-
- public void testColumn_double() throws Exception {
- db.exec(CREATE_ALL_TYPES, null);
- db.exec(INSERT_ALL_TYPES, null);
-
- double doubleColumn;
- double actualVal = 23.2;
- String selectStmt = "select DoubleVal from "+ ALL_TYPES_TABLE;
-
- st = db.prepare(selectStmt);
- st.step();
- // select double value
- doubleColumn = st.column_double(0);
- assertNotNull(doubleColumn);
-
- assertTrue("DOUBLE".equalsIgnoreCase(st.column_decltype(0)));
- assertNotNull(doubleColumn);
- assertEquals( actualVal, doubleColumn);
-
- // Exception test
- selectStmt = "select dateVal from "+ ALL_TYPES_TABLE;
-
- st = db.prepare(selectStmt);
- st.step();
- // select double value
- st.column_double(0);
- }
-
- public void testColumn_bytes() throws Exception {
- db.exec("create table B(id integer primary key, val blob)",null);
- db.exec("insert into B values(1, zeroblob(128))", null);
- st = db.prepare("select val from B where id = 1");
- assertTrue(st.step());
- st.column_bytes(0);
- }
-
- public void testColumn_string() throws Exception {
- db.exec(CREATE_ALL_TYPES, null);
- db.exec(INSERT_ALL_TYPES, null);
-
- String stringColumn;
- String actualVal = "test string";
- String selectStmt = "select charStr from "+ ALL_TYPES_TABLE;
-
- st = db.prepare(selectStmt);
- st.step();
- // select string value
- stringColumn = st.column_string(0);
- assertNotNull(stringColumn);
-
- assertTrue("CHAR(20)".equalsIgnoreCase(st.column_decltype(0)));
- assertNotNull(stringColumn);
- assertEquals( actualVal, stringColumn);
-
- // Exception test
- selectStmt = "select DoubleVal from "+ ALL_TYPES_TABLE;
-
- st = db.prepare(selectStmt);
- st.step();
- st.column_string(0);
- }
-
- public void testColumn_type() throws Exception {
- db.exec(CREATE_ALL_TYPES, null);
- db.exec(INSERT_ALL_TYPES, null);
- st = db.prepare("select * from " + ALL_TYPES_TABLE);
- st.step();
-
- // Exception test
- try {
- st.column_type(100);
- fail();
- } catch (SQLite.Exception expected) {
- }
-
- /*
- Dictionary
-
- public static final int SQLITE_INTEGER = 1;
- public static final int SQLITE_FLOAT = 2;
- public static final int SQLITE_BLOB = 4;
- public static final int SQLITE_NULL = 5;
- public static final int SQLITE3_TEXT = 3;
- public static final int SQLITE_NUMERIC = -1;
- */
-
- assertEquals(Constants.SQLITE3_TEXT, st.column_type(23)); // ok TEXT
- assertEquals(Constants.SQLITE3_TEXT, st.column_type(13)); // CHAR(20)
-
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(8));
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(9));
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(10)); // FLOAT
-
- for (int i = 0; i < 8; i++) {
- assertEquals("Expected Integer at position " + i,
- Constants.SQLITE_INTEGER, st.column_type(i));
- }
-
- assertEquals(Constants.SQLITE_NULL, st.column_type(28));
- assertEquals(Constants.SQLITE_NULL, st.column_type(29));
-
- // Failing tests
- assertTrue("INTEGER".equalsIgnoreCase(st.column_decltype(12)));
- assertEquals(Constants.SQLITE_INTEGER, st.column_type(12));
-
- assertTrue("FLOAT".equalsIgnoreCase(st.column_decltype(11)));
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(11)); // FLOAT ->
- // got INTEGER
- assertTrue("BLOB".equalsIgnoreCase(st.column_decltype(19)));
- assertEquals(Constants.SQLITE_BLOB, st.column_type(19)); // Blob got
- // INTEGER
-
- }
-
- /**
- * Wrong value is returned in case of a prepared statement to which a '*' bound
- */
- public void testColumn_count() throws Exception {
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- st = db.prepare(selectStmt);
-
- assertEquals(3, st.column_count());
-
- st.step();
- int columnCount = st.column_count();
- assertNotNull(columnCount);
- assertEquals( 3, columnCount);
-
- // actual prepared statement
- selectStmt = "select ? from "+DatabaseCreator.SIMPLE_TABLE1;
- st = db.prepare(selectStmt);
-
- assertEquals(3, st.column_count());
-
- st.bind(1, "*");
- st.step();
- columnCount = st.column_count();
- assertNotNull(columnCount);
- assertEquals( 3, columnCount);
- }
-
- public void testColumn() throws Exception {
- Object columnObject;
- int intColumn;
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- db.get_table(selectStmt);
- st = db.prepare(selectStmt);
- st.step();
- columnObject = st.column(1);
- intColumn = st.column_int(1);
- assertNotNull(intColumn);
- assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
- int stSpeed = Integer.parseInt(columnObject.toString());
- assertNotNull(stSpeed);
- assertEquals( intColumn, stSpeed);
-
- try {
- assertNotNull(columnObject);
- ((Integer) columnObject).intValue();
- fail("Cast to Integer should fail");
- } catch (ClassCastException expected) {
- }
-
- try {
- st.column(4);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("column out of bounds", expected.getMessage());
- }
-
- try {
- st.column(-1);
- fail("Exception expected");
- } catch (SQLite.Exception expected) {
- assertEquals("column out of bounds", expected.getMessage());
- }
- }
-
- public void testColumn_table_name() {
- try {
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- st.column_table_name(1);
- fail("Function is now supported.");
- } catch (SQLite.Exception expected) {
- assertEquals("unsupported", expected.getMessage());
- }
- }
-
- public void testColumn_database_name() {
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.column_database_name(1);
- fail("Function is now supported.");
- } catch (SQLite.Exception expected) {
- assertEquals("unsupported", expected.getMessage());
- }
- }
-
- public void testColumn_decltype() throws Exception {
- db.exec(CREATE_ALL_TYPES, null);
- db.exec(INSERT_ALL_TYPES, null);
- st = db.prepare("select * from " + ALL_TYPES_TABLE);
- st.step();
-
- // Exception test
- try {
- st.column_decltype(100);
- fail();
- } catch (SQLite.Exception expected) {
- }
-
- assertTrue(st.column_decltype(0), "BOOLEAN".equalsIgnoreCase(st
- .column_decltype(0)));
- assertTrue(st.column_decltype(1), "INT".equalsIgnoreCase(st
- .column_decltype(1)));
- assertTrue(st.column_decltype(2), "LONG".equalsIgnoreCase(st
- .column_decltype(2)));
- assertTrue(st.column_decltype(3), "BIGINT".equalsIgnoreCase(st
- .column_decltype(3)));
- assertTrue(st.column_decltype(4), "TINYINT".equalsIgnoreCase(st
- .column_decltype(4)));
- assertTrue(st.column_decltype(5), "SMALLINT".equalsIgnoreCase(st
- .column_decltype(5)));
- assertTrue(st.column_decltype(6), "MEDIUMINT".equalsIgnoreCase(st
- .column_decltype(6)));
- assertTrue(st.column_decltype(7), "INTEGER".equalsIgnoreCase(st
- .column_decltype(7)));
- assertTrue(st.column_decltype(8), "REAL".equalsIgnoreCase(st
- .column_decltype(8)));
- assertTrue(st.column_decltype(9), "DOUBLE".equalsIgnoreCase(st
- .column_decltype(9)));
- assertTrue(st.column_decltype(10), "FLOAT".equalsIgnoreCase(st
- .column_decltype(10)));
- assertTrue(st.column_decltype(11), "DECIMAL".equalsIgnoreCase(st
- .column_decltype(11)));
- assertTrue(st.column_decltype(12), "NUMERIC".equalsIgnoreCase(st
- .column_decltype(12)));
- assertTrue(st.column_decltype(13), "CHAR(20)".equalsIgnoreCase(st
- .column_decltype(13)));
-
- assertTrue(st.column_decltype(19), "BLOB".equalsIgnoreCase(st
- .column_decltype(19)));
-
- assertTrue(st.column_decltype(23), "TEXT".equalsIgnoreCase(st
- .column_decltype(23)));
- assertTrue(st.column_decltype(28), "URL".equalsIgnoreCase(st
- .column_decltype(28)));
- assertTrue(st.column_decltype(29), "URL".equalsIgnoreCase(st
- .column_decltype(29)));
- }
-
- public void testColumn_origin_name() {
- try {
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- st.column_origin_name(1);
- fail("Function is now supported.");
- } catch (SQLite.Exception expected) {
- assertEquals("unsupported", expected.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java b/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java
deleted file mode 100644
index 8febfff..0000000
--- a/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2007 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 libcore.sqlite;
-
-import SQLite.Database;
-import SQLite.Function;
-import SQLite.FunctionContext;
-import SQLite.JDBC2z.JDBCConnection;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import junit.framework.TestCase;
-import tests.support.Support_SQL;
-
-
-/**
- * Test that statements honor their timeout.
- */
-public final class QueryTimeoutTest extends TestCase {
-
- private static final String EXEC_QUERY
- = "insert into t_copy select a from t_orig where DELAY(2,1)=1";
-
- private static final String FETCH_QUERY = "select a from t_orig where DELAY(2,1)=1";
-
- private Connection connection;
-
- @Override public void setUp() throws Exception {
- Support_SQL.loadDriver();
- connection = Support_SQL.getConnection();
-
- exec("drop table if exists t_orig;");
- exec("drop table if exists t_copy;");
- exec("create table t_orig (a int)");
- exec("create table t_copy (a int)");
-
- for (int i = 0; i < 7; i++) {
- exec("insert into t_orig values (" + i + ");");
- }
-
- Database database = ((JDBCConnection) connection).getSQLiteDatabase();
- database.create_function("DELAY", 2, new Function() {
- @Override public void function(FunctionContext functionContext, String[] args) {
- try {
- int seconds = Integer.parseInt(args[0]);
- Thread.sleep(seconds * 1000);
- } catch (InterruptedException ignored) {
- }
- functionContext.set_result(Integer.parseInt(args[1]));
- }
- @Override public void last_step(FunctionContext functionContext) {
- }
- @Override public void step(FunctionContext functionContext, String[] args) {
- }
- });
-
- connection.setAutoCommit(true);
- }
-
- @Override public void tearDown() throws Exception {
- connection.close();
- }
-
- private void exec(String queryString) throws Exception {
- System.out.println("Executing " + queryString);
- Statement statement = null;
- try {
- statement = connection.createStatement();
- statement.execute(queryString);
- } finally {
- if (statement != null) {
- statement.close();
- }
- }
- }
-
- public void testPreparedStatementFetch() throws Exception {
- PreparedStatement statement = connection.prepareStatement(FETCH_QUERY);
- statement.setQueryTimeout(1);
- ResultSet resultSet = null;
- try {
- resultSet = statement.executeQuery();
- while (resultSet.next()) {
- }
- fail();
- } catch (SQLException expected) {
- } finally {
- statement.close();
- if (resultSet != null) {
- resultSet.close();
- }
- }
- }
-
- public void testPreparedStatementUpdate() throws Exception {
- PreparedStatement statement = connection.prepareStatement(EXEC_QUERY);
- try {
- statement.setQueryTimeout(1);
- statement.execute();
- fail();
- } catch (SQLException expected) {
- } finally {
- statement.close();
- }
- }
-
- public void testInvalidTimeout() throws Exception {
- connection.setAutoCommit(true);
- PreparedStatement statement = connection.prepareStatement("select 'hello'");
-
- try {
- statement.setQueryTimeout(-1);
- fail();
- } catch (SQLException expected) {
- }
-
- ResultSet resultSet = statement.executeQuery();
- resultSet.close();
- statement.close();
- }
-
- public void testExecuteUpdate() throws Exception {
- Statement statement = connection.createStatement();
- try {
- statement.setQueryTimeout(1);
- statement.executeUpdate(EXEC_QUERY);
- fail();
- } catch (SQLException expected) {
- } finally {
- statement.close();
- }
- }
-
- public void testTimeoutAndStatementReuse() throws Exception {
- Statement statement = connection.createStatement();
- statement.setQueryTimeout(1);
- for (int i = 0; i < 3; i++) {
- try {
- ResultSet resultSet = statement.executeQuery(FETCH_QUERY);
- while (resultSet.next()) {
- }
- fail();
- } catch (SQLException expected) {
- }
- }
- statement.close();
- }
-}
diff --git a/luni/src/test/java/libcore/util/ZoneInfoDBTest.java b/luni/src/test/java/libcore/util/ZoneInfoDBTest.java
index 28ae416..9875647 100644
--- a/luni/src/test/java/libcore/util/ZoneInfoDBTest.java
+++ b/luni/src/test/java/libcore/util/ZoneInfoDBTest.java
@@ -22,25 +22,27 @@ import java.io.RandomAccessFile;
import java.util.TimeZone;
public class ZoneInfoDBTest extends junit.framework.TestCase {
- private static final String CURRENT_VERSION = ZoneInfoDB.getInstance().getVersion();
- // Any new file in /data...
- private static final String TZDATA_IN_DATA = System.getenv("ANDROID_DATA") + "/misc/zoneinfo/tzdata";
- // ...overrides any existing file in /system.
- private static final String TZDATA_IN_ROOT = System.getenv("ANDROID_ROOT") + "/usr/share/zoneinfo/tzdata";
+ // The base tzdata file, always present on a device.
+ private static final String TZDATA_IN_ROOT =
+ System.getenv("ANDROID_ROOT") + "/usr/share/zoneinfo/tzdata";
// An empty override file should fall back to the default file.
public void testEmptyOverrideFile() throws Exception {
- ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(makeEmptyFile(), TZDATA_IN_DATA, TZDATA_IN_ROOT);
- assertEquals(CURRENT_VERSION, data.getVersion());
- assertEquals(TimeZone.getAvailableIDs().length, data.getAvailableIDs().length);
+ ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT);
+ ZoneInfoDB.TzData dataWithEmptyOverride =
+ new ZoneInfoDB.TzData(makeEmptyFile(), TZDATA_IN_ROOT);
+ assertEquals(data.getVersion(), dataWithEmptyOverride.getVersion());
+ assertEquals(data.getAvailableIDs().length, dataWithEmptyOverride.getAvailableIDs().length);
}
// A corrupt override file should fall back to the default file.
public void testCorruptOverrideFile() throws Exception {
- ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(makeCorruptFile(), TZDATA_IN_DATA, TZDATA_IN_ROOT);
- assertEquals(CURRENT_VERSION, data.getVersion());
- assertEquals(TimeZone.getAvailableIDs().length, data.getAvailableIDs().length);
+ ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT);
+ ZoneInfoDB.TzData dataWithCorruptOverride =
+ new ZoneInfoDB.TzData(makeCorruptFile(), TZDATA_IN_ROOT);
+ assertEquals(data.getVersion(), dataWithCorruptOverride.getVersion());
+ assertEquals(data.getAvailableIDs().length, dataWithCorruptOverride.getAvailableIDs().length);
}
// Given no tzdata files we can use, we should fall back to built-in "GMT".
@@ -53,7 +55,6 @@ public class ZoneInfoDBTest extends junit.framework.TestCase {
// Given a valid override file, we should find ourselves using that.
public void testGoodOverrideFile() throws Exception {
- // We copy /system/usr/share/zoneinfo/tzdata because we know that always exists.
RandomAccessFile in = new RandomAccessFile(TZDATA_IN_ROOT, "r");
byte[] content = new byte[(int) in.length()];
in.readFully(content);
@@ -65,16 +66,40 @@ public class ZoneInfoDBTest extends junit.framework.TestCase {
content[10] = 'z';
in.close();
+ ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT);
String goodFile = makeTemporaryFile(content);
try {
- ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(goodFile, TZDATA_IN_DATA, TZDATA_IN_ROOT);
- assertEquals("9999z", data.getVersion());
- assertEquals(TimeZone.getAvailableIDs().length, data.getAvailableIDs().length);
+ ZoneInfoDB.TzData dataWithOverride = new ZoneInfoDB.TzData(goodFile, TZDATA_IN_ROOT);
+ assertEquals("9999z", dataWithOverride.getVersion());
+ assertEquals(data.getAvailableIDs().length, dataWithOverride.getAvailableIDs().length);
} finally {
new File(goodFile).delete();
}
}
+ // Confirms any caching that exists correctly handles TimeZone mutability.
+ public void testMakeTimeZone_timeZoneMutability() throws Exception {
+ ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT);
+ String tzId = "Europe/London";
+ ZoneInfo first = data.makeTimeZone(tzId);
+ ZoneInfo second = data.makeTimeZone(tzId);
+ assertNotSame(first, second);
+
+ assertTrue(first.hasSameRules(second));
+
+ first.setID("Not Europe/London");
+
+ assertFalse(first.getID().equals(second.getID()));
+
+ first.setRawOffset(3600);
+ assertFalse(first.getRawOffset() == second.getRawOffset());
+ }
+
+ public void testMakeTimeZone_notFound() throws Exception {
+ ZoneInfoDB.TzData data = new ZoneInfoDB.TzData(TZDATA_IN_ROOT);
+ assertNull(data.makeTimeZone("THIS_TZ_DOES_NOT_EXIST"));
+ }
+
private static String makeCorruptFile() throws Exception {
return makeTemporaryFile("invalid content".getBytes());
}
diff --git a/luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java b/luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java
new file mode 100644
index 0000000..7194414
--- /dev/null
+++ b/luni/src/test/java/libcore/xml/XmlPullParserFactoryTest.java
@@ -0,0 +1,374 @@
+/*
+ * Copyright (C) 2013 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 libcore.xml;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import junit.framework.TestCase;
+import org.kxml2.io.KXmlParser;
+import org.kxml2.io.KXmlSerializer;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlPullParserFactory;
+import org.xmlpull.v1.XmlSerializer;
+
+public class XmlPullParserFactoryTest extends TestCase {
+
+ public void testDefaultNewInstance() throws Exception {
+ XmlPullParserFactory factory = XmlPullParserFactory.newInstance(null, null);
+ XmlPullParser parser = factory.newPullParser();
+ XmlSerializer serializer = factory.newSerializer();
+
+ assertNotNull(parser);
+ assertNotNull(serializer);
+ assertTrue(parser instanceof KXmlParser);
+ assertTrue(serializer instanceof KXmlSerializer);
+ }
+
+ /**
+ * Tests that trying to instantiate a parser with an empty list of
+ * parsers and serializers fails.
+ */
+ public void testOverriding_emptyClassList() {
+ TestXmlPullParserFactory tf = new TestXmlPullParserFactory(null, null);
+
+ try {
+ tf.newPullParser();
+ fail();
+ } catch (XmlPullParserException expected) {
+ }
+
+ try {
+ tf.newPullParser();
+ fail();
+ } catch (XmlPullParserException expected) {
+ }
+ }
+
+ public void testOverriding_customClassList() throws Exception {
+ TestXmlPullParserFactory tf = new TestXmlPullParserFactory(
+ new String[] { "libcore.xml.XmlPullParserFactoryTest$XmlPullParserStub" },
+ new String[] { "libcore.xml.XmlPullParserFactoryTest$XmlSerializerStub" });
+
+ assertTrue(tf.newPullParser() instanceof XmlPullParserStub);
+ assertTrue(tf.newSerializer() instanceof XmlSerializerStub);
+
+ // Also check that we ignore instantiation errors as long as
+ // at least one parser / serializer is instantiable.
+ tf = new TestXmlPullParserFactory(
+ new String[] {
+ "libcore.xml.XmlPullParserFactoryTest$InaccessibleXmlParser",
+ "libcore.xml.XmlPullParserFactoryTest$XmlPullParserStub" },
+ new String[] {
+ "libcore.xml.XmlPullParserFactoryTest$InaccessibleXmlSerializer",
+ "libcore.xml.XmlPullParserFactoryTest$XmlSerializerStub" });
+
+ assertTrue(tf.newPullParser() instanceof XmlPullParserStub);
+ assertTrue(tf.newSerializer() instanceof XmlSerializerStub);
+ }
+
+ // https://b/12956724
+ public void testSetFeature_setsFeatureOnlyIfTrue() throws Exception {
+ TestXmlPullParserFactory tf = new TestXmlPullParserFactory(
+ new String[] { "libcore.xml.XmlPullParserFactoryTest$XmlParserThatHatesAllFeatures" }, null);
+
+ tf.setFeature("foo", false);
+ tf.newPullParser();
+ }
+
+
+ /**
+ * A class that makes use of inherited XmlPullParserFactory fields to check they are
+ * supported.
+ */
+ static final class TestXmlPullParserFactory extends XmlPullParserFactory {
+ TestXmlPullParserFactory(String[] parserClassList, String[] serializerClassList) {
+ super();
+ parserClasses.remove(0);
+ serializerClasses.remove(0);
+
+ try {
+ if (parserClassList != null) {
+ for (String parserClass : parserClassList) {
+ parserClasses.add(Class.forName(parserClass));
+ }
+ }
+
+ if (serializerClassList != null) {
+ for (String serializerClass : serializerClassList) {
+ serializerClasses.add(Class.forName(serializerClass));
+ }
+ }
+ } catch (ClassNotFoundException ignored) {
+ throw new AssertionError(ignored);
+ }
+ }
+ }
+
+ public static final class XmlParserThatHatesAllFeatures extends XmlPullParserStub {
+ @Override
+ public void setFeature(String name, boolean state) {
+ fail();
+ }
+ }
+
+ static final class InaccessibleXmlSerializer extends XmlSerializerStub {
+ }
+
+ static final class InaccessibleXmlParser extends XmlPullParserStub {
+ }
+
+ public static class XmlSerializerStub implements XmlSerializer {
+
+ public void setFeature(String name, boolean state) throws IllegalArgumentException,
+ IllegalStateException {
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public void setProperty(String name, Object value) {
+ }
+
+ public Object getProperty(String name) {
+ return null;
+ }
+
+ public void setOutput(OutputStream os, String encoding) throws IOException {
+ }
+
+ public void setOutput(Writer writer) throws IOException {
+ }
+
+ public void startDocument(String encoding, Boolean standalone) throws IOException {
+ }
+
+ public void endDocument() throws IOException {
+ }
+
+ public void setPrefix(String prefix, String namespace) throws IOException {
+ }
+
+ public String getPrefix(String namespace, boolean generatePrefix) throws IllegalArgumentException {
+ return null;
+ }
+
+ public int getDepth() {
+ return 0;
+ }
+
+ public String getNamespace() {
+ return null;
+ }
+
+ public String getName() {
+ return null;
+ }
+
+ public XmlSerializer startTag(String namespace, String name) throws IOException {
+ return null;
+ }
+
+ public XmlSerializer attribute(String namespace, String name, String value) throws IOException {
+ return null;
+ }
+
+ public XmlSerializer endTag(String namespace, String name) throws IOException {
+ return null;
+ }
+
+ public XmlSerializer text(String text) throws IOException {
+ return null;
+ }
+
+ public XmlSerializer text(char[] buf, int start, int len) throws IOException {
+ return null;
+ }
+
+ public void cdsect(String text) throws IOException {
+ }
+
+ public void entityRef(String text) throws IOException {
+ }
+
+ public void processingInstruction(String text) throws IOException {
+ }
+
+ public void comment(String text) throws IOException {
+ }
+
+ public void docdecl(String text) throws IOException {
+ }
+
+ public void ignorableWhitespace(String text) throws IOException {
+ }
+
+ public void flush() throws IOException {
+ }
+ }
+
+ public static class XmlPullParserStub implements XmlPullParser {
+ public void setFeature(String name, boolean state) throws XmlPullParserException {
+ }
+
+ public boolean getFeature(String name) {
+ return false;
+ }
+
+ public void setProperty(String name, Object value) throws XmlPullParserException {
+ }
+
+ public Object getProperty(String name) {
+ return null;
+ }
+
+ public void setInput(Reader in) throws XmlPullParserException {
+ }
+
+ public void setInput(InputStream inputStream, String inputEncoding)
+ throws XmlPullParserException {
+ }
+
+ public String getInputEncoding() {
+ return null;
+ }
+
+ public void defineEntityReplacementText(String entityName, String replacementText)
+ throws XmlPullParserException {
+ }
+
+ public int getNamespaceCount(int depth) throws XmlPullParserException {
+ return 0;
+ }
+
+ public String getNamespacePrefix(int pos) throws XmlPullParserException {
+ return null;
+ }
+
+ public String getNamespaceUri(int pos) throws XmlPullParserException {
+ return null;
+ }
+
+ public String getNamespace(String prefix) {
+ return null;
+ }
+
+ public int getDepth() {
+ return 0;
+ }
+
+ public String getPositionDescription() {
+ return null;
+ }
+
+ public int getLineNumber() {
+ return 0;
+ }
+
+ public int getColumnNumber() {
+ return 0;
+ }
+
+ public boolean isWhitespace() throws XmlPullParserException {
+ return false;
+ }
+
+ public String getText() {
+ return null;
+ }
+
+ public char[] getTextCharacters(int[] holderForStartAndLength) {
+ return null;
+ }
+
+ public String getNamespace() {
+ return null;
+ }
+
+ public String getName() {
+ return null;
+ }
+
+ public String getPrefix() {
+ return null;
+ }
+
+ public boolean isEmptyElementTag() throws XmlPullParserException {
+ return false;
+ }
+
+ public int getAttributeCount() {
+ return 0;
+ }
+
+ public String getAttributeNamespace(int index) {
+ return null;
+ }
+
+ public String getAttributeName(int index) {
+ return null;
+ }
+
+ public String getAttributePrefix(int index) {
+ return null;
+ }
+
+ public String getAttributeType(int index) {
+ return null;
+ }
+
+ public boolean isAttributeDefault(int index) {
+ return false;
+ }
+
+ public String getAttributeValue(int index) {
+ return null;
+ }
+
+ public String getAttributeValue(String namespace, String name) {
+ return null;
+ }
+
+ public int getEventType() throws XmlPullParserException {
+ return 0;
+ }
+
+ public int next() throws XmlPullParserException, IOException {
+ return 0;
+ }
+
+ public int nextToken() throws XmlPullParserException, IOException {
+ return 0;
+ }
+
+ public void require(int type, String namespace, String name)
+ throws XmlPullParserException, IOException {
+ }
+
+ public String nextText() throws XmlPullParserException, IOException {
+ return null;
+ }
+
+ public int nextTag() throws XmlPullParserException, IOException {
+ return 0;
+ }
+ }
+}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java
deleted file mode 100644
index afdce5d..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java
+++ /dev/null
@@ -1,1001 +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.harmony.archive.tests.java.util.jar;
-
-
-import junit.framework.TestCase;
-
-import tests.support.Support_PlatformFile;
-import tests.support.resource.Support_Resources;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.security.Permission;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.Vector;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipFile;
-
-
-public class JarFileTest extends TestCase {
-
- // BEGIN android-added
- public byte[] getAllBytesFromStream(InputStream is) throws IOException {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- byte[] buf = new byte[666];
- int iRead;
- int off;
- while (is.available() > 0) {
- iRead = is.read(buf, 0, buf.length);
- if (iRead > 0) bs.write(buf, 0, iRead);
- }
- return bs.toByteArray();
- }
-
- // END android-added
-
- private final String jarName = "hyts_patch.jar"; // a 'normal' jar file
-
- private final String jarName2 = "hyts_patch2.jar";
-
- private final String jarName3 = "hyts_manifest1.jar";
-
- private final String jarName4 = "hyts_signed.jar";
-
- private final String jarName5 = "hyts_signed_inc.jar";
-
- private final String jarName6 = "hyts_signed_sha256withrsa.jar";
-
- private final String jarName7 = "hyts_signed_sha256digest_sha256withrsa.jar";
-
- private final String jarName8 = "hyts_signed_sha512digest_sha512withecdsa.jar";
-
- private final String authAttrsJar = "hyts_signed_authAttrs.jar";
-
- private final String entryName = "foo/bar/A.class";
-
- private final String entryName3 = "coucou/FileAccess.class";
-
- private final String integrateJar = "Integrate.jar";
-
- private final String integrateJarEntry = "Test.class";
-
- private final String emptyEntryJar = "EmptyEntries_signed.jar";
-
- private final String emptyEntry1 = "subfolder/internalSubset01.js";
-
- private final String emptyEntry2 = "svgtest.js";
-
- private final String emptyEntry3 = "svgunit.js";
-
- private static final String VALID_CHAIN_JAR = "hyts_signed_validChain.jar";
-
- private static final String INVALID_CHAIN_JAR = "hyts_signed_invalidChain.jar";
-
- private File resources;
-
- // custom security manager
- SecurityManager sm = new SecurityManager() {
- final String forbidenPermissionName = "user.dir";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- @Override
- protected void setUp() {
- resources = Support_Resources.createTempFolder();
- }
-
- /**
- * java.util.jar.JarFile#JarFile(java.io.File)
- */
- public void test_ConstructorLjava_io_File() {
- try {
- JarFile jarFile = new JarFile(new File("Wrong.file"));
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- } catch (IOException e) {
- fail("Should not throw IOException");
- }
- }
-
- /**
- * java.util.jar.JarFile#JarFile(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- try {
- JarFile jarFile = new JarFile("Wrong.file");
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- String fileName = (new File(resources, jarName)).getCanonicalPath();
- JarFile jarFile = new JarFile(fileName);
- } catch (IOException e) {
- fail("Should not throw IOException");
- }
- }
-
- /**
- * java.util.jar.JarFile#JarFile(java.lang.String, boolean)
- */
- public void test_ConstructorLjava_lang_StringZ() {
- try {
- JarFile jarFile = new JarFile("Wrong.file", false);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- String fileName = (new File(resources, jarName)).getCanonicalPath();
- JarFile jarFile = new JarFile(fileName, true);
- } catch (IOException e) {
- fail("Should not throw IOException");
- }
- }
-
- /**
- * java.util.jar.JarFile#JarFile(java.io.File, boolean)
- */
- public void test_ConstructorLjava_io_FileZ() {
- try {
- JarFile jarFile = new JarFile(new File("Wrong.file"), true);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName), false);
- } catch (IOException e) {
- fail("Should not throw IOException");
- }
- }
-
- /**
- * java.util.jar.JarFile#JarFile(java.io.File, boolean, int)
- */
- public void test_ConstructorLjava_io_FileZI() {
- try {
- JarFile jarFile = new JarFile(new File("Wrong.file"), true,
- ZipFile.OPEN_READ);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName), false,
- ZipFile.OPEN_READ);
- } catch (IOException e) {
- fail("Should not throw IOException");
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName), false,
- ZipFile.OPEN_READ | ZipFile.OPEN_DELETE + 33);
- fail("Should throw IllegalArgumentException");
- } catch (IOException e) {
- fail("Should not throw IOException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * Constructs JarFile object.
- *
- * java.util.jar.JarFile#JarFile(java.io.File)
- * java.util.jar.JarFile#JarFile(java.lang.String)
- */
- public void testConstructor_file() throws IOException {
- File f = new File(resources, jarName);
- Support_Resources.copyFile(resources, null, jarName);
- assertTrue(new JarFile(f).getEntry(entryName).getName().equals(
- entryName));
- assertTrue(new JarFile(f.getPath()).getEntry(entryName).getName()
- .equals(entryName));
- }
-
- /**
- * java.util.jar.JarFile#entries()
- */
- public void test_entries() throws Exception {
- /*
- * Note only (and all of) the following should be contained in the file
- * META-INF/ META-INF/MANIFEST.MF foo/ foo/bar/ foo/bar/A.class Blah.txt
- */
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- Enumeration<JarEntry> e = jarFile.entries();
- int i;
- for (i = 0; e.hasMoreElements(); i++) {
- e.nextElement();
- }
- assertEquals(jarFile.size(), i);
- jarFile.close();
- assertEquals(6, i);
- }
-
- public void test_entries2() throws Exception {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- Enumeration<JarEntry> enumeration = jarFile.entries();
- jarFile.close();
- try {
- enumeration.hasMoreElements();
- fail("hasMoreElements() did not detect a closed jar file");
- } catch (IllegalStateException e) {
- }
- Support_Resources.copyFile(resources, null, jarName);
- jarFile = new JarFile(new File(resources, jarName));
- enumeration = jarFile.entries();
- jarFile.close();
- try {
- enumeration.nextElement();
- fail("nextElement() did not detect closed jar file");
- } catch (IllegalStateException e) {
- }
- }
-
- /**
- * @throws IOException
- * java.util.jar.JarFile#getJarEntry(java.lang.String)
- */
- public void test_getEntryLjava_lang_String() throws IOException {
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- assertEquals("Error in returned entry", 311, jarFile.getEntry(
- entryName).getSize());
- jarFile.close();
- } catch (Exception e) {
- fail("Exception during test: " + e.toString());
- }
-
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- Enumeration<JarEntry> enumeration = jarFile.entries();
- assertTrue(enumeration.hasMoreElements());
- while (enumeration.hasMoreElements()) {
- JarEntry je = enumeration.nextElement();
- jarFile.getEntry(je.getName());
- }
-
- enumeration = jarFile.entries();
- assertTrue(enumeration.hasMoreElements());
- JarEntry je = enumeration.nextElement();
- try {
- jarFile.close();
- jarFile.getEntry(je.getName());
- // fail("IllegalStateException expected.");
- } catch (IllegalStateException ee) { // Per documentation exception
- // may be thrown.
- // expected
- }
- }
-
- /**
- * @throws IOException
- * java.util.jar.JarFile#getJarEntry(java.lang.String)
- */
- public void test_getJarEntryLjava_lang_String() throws IOException {
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- assertEquals("Error in returned entry", 311, jarFile.getJarEntry(
- entryName).getSize());
- jarFile.close();
- } catch (Exception e) {
- fail("Exception during test: " + e.toString());
- }
-
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- Enumeration<JarEntry> enumeration = jarFile.entries();
- assertTrue(enumeration.hasMoreElements());
- while (enumeration.hasMoreElements()) {
- JarEntry je = enumeration.nextElement();
- jarFile.getJarEntry(je.getName());
- }
-
- enumeration = jarFile.entries();
- assertTrue(enumeration.hasMoreElements());
- JarEntry je = enumeration.nextElement();
- try {
- jarFile.close();
- jarFile.getJarEntry(je.getName());
- // fail("IllegalStateException expected.");
- } catch (IllegalStateException ee) { // Per documentation exception
- // may be thrown.
- // expected
- }
- }
-
-
- /**
- * java.util.jar.JarFile#getJarEntry(java.lang.String)
- */
- public void testGetJarEntry() throws Exception {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- assertEquals("Error in returned entry", 311, jarFile.getEntry(
- entryName).getSize());
- jarFile.close();
-
- // tests for signed jars
- // test all signed jars in the /Testres/Internal/SignedJars directory
- String jarDirUrl = Support_Resources
- .getResourceURL("/../internalres/signedjars");
- Vector<String> signedJars = new Vector<String>();
- try {
- InputStream is = new URL(jarDirUrl + "/jarlist.txt").openStream();
- while (is.available() > 0) {
- StringBuilder linebuff = new StringBuilder(80); // Typical line
- // length
- done: while (true) {
- int nextByte = is.read();
- switch (nextByte) {
- case -1:
- break done;
- case (byte) '\r':
- if (linebuff.length() == 0) {
- // ignore
- }
- break done;
- case (byte) '\n':
- if (linebuff.length() == 0) {
- // ignore
- }
- break done;
- default:
- linebuff.append((char) nextByte);
- }
- }
- if (linebuff.length() == 0) {
- break;
- }
- String line = linebuff.toString();
- signedJars.add(line);
- }
- is.close();
- } catch (IOException e) {
- // no list of jars found
- }
-
- for (int i = 0; i < signedJars.size(); i++) {
- String jarName = signedJars.get(i);
- try {
- File file = Support_Resources.getExternalLocalFile(jarDirUrl
- + "/" + jarName);
- jarFile = new JarFile(file, true);
- boolean foundCerts = false;
- Enumeration<JarEntry> e = jarFile.entries();
- while (e.hasMoreElements()) {
- JarEntry entry = e.nextElement();
- InputStream is = jarFile.getInputStream(entry);
- is.skip(100000);
- is.close();
- Certificate[] certs = entry.getCertificates();
- if (certs != null && certs.length > 0) {
- foundCerts = true;
- break;
- }
- }
- assertTrue(
- "No certificates found during signed jar test for jar \""
- + jarName + "\"", foundCerts);
- } catch (IOException e) {
- fail("Exception during signed jar test for jar \"" + jarName
- + "\": " + e.toString());
- }
- }
- }
-
- /**
- * java.util.jar.JarFile#getManifest()
- */
- public void test_getManifest() {
- // Test for method java.util.jar.Manifest
- // java.util.jar.JarFile.getManifest()
- try {
- Support_Resources.copyFile(resources, null, jarName);
- JarFile jarFile = new JarFile(new File(resources, jarName));
- assertNotNull("Error--Manifest not returned", jarFile.getManifest());
- jarFile.close();
- } catch (Exception e) {
- fail("Exception during 1st test: " + e.toString());
- }
- try {
- Support_Resources.copyFile(resources, null, jarName2);
- JarFile jarFile = new JarFile(new File(resources, jarName2));
- assertNull("Error--should have returned null", jarFile
- .getManifest());
- jarFile.close();
- } catch (Exception e) {
- fail("Exception during 2nd test: " + e.toString());
- }
-
- try {
- // jarName3 was created using the following test
- Support_Resources.copyFile(resources, null, jarName3);
- JarFile jarFile = new JarFile(new File(resources, jarName3));
- assertNotNull("Should find manifest without verifying", jarFile
- .getManifest());
- jarFile.close();
- } catch (Exception e) {
- fail("Exception during 3rd test: " + e.toString());
- }
-
- try {
- // this is used to create jarName3 used in the previous test
- Manifest manifest = new Manifest();
- Attributes attributes = manifest.getMainAttributes();
- attributes.put(new Attributes.Name("Manifest-Version"), "1.0");
- ByteArrayOutputStream manOut = new ByteArrayOutputStream();
- manifest.write(manOut);
- byte[] manBytes = manOut.toByteArray();
- File file = File.createTempFile(
- Support_PlatformFile.getNewPlatformFile("hyts_manifest1",
- ""), ".jar");
- JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(
- file.getAbsolutePath()));
- ZipEntry entry = new ZipEntry("META-INF/");
- entry.setSize(0);
- jarOut.putNextEntry(entry);
- entry = new ZipEntry(JarFile.MANIFEST_NAME);
- entry.setSize(manBytes.length);
- jarOut.putNextEntry(entry);
- jarOut.write(manBytes);
- entry = new ZipEntry("myfile");
- entry.setSize(1);
- jarOut.putNextEntry(entry);
- jarOut.write(65);
- jarOut.close();
- JarFile jar = new JarFile(file.getAbsolutePath(), false);
- assertNotNull("Should find manifest without verifying", jar
- .getManifest());
- jar.close();
- file.delete();
- } catch (IOException e) {
- fail("IOException 3");
- }
- try {
- Support_Resources.copyFile(resources, null, jarName2);
- JarFile jF = new JarFile(new File(resources, jarName2));
- jF.close();
- jF.getManifest();
- fail("FAILED: expected IllegalStateException");
- } catch (IllegalStateException ise) {
- // expected;
- } catch (Exception e) {
- fail("Exception during 4th test: " + e.toString());
- }
-
- Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
- JarFile jf;
- try {
- jf = new JarFile(new File(resources, "Broken_manifest.jar"));
- jf.getManifest();
- fail("IOException expected.");
- } catch (IOException e) {
- // expected.
- }
- }
-
- /**
- * java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
- */
- // This test doesn't pass on RI. If entry size is set up incorrectly,
- // SecurityException is thrown. But SecurityException is thrown on RI only
- // if jar file is signed incorrectly.
- public void test_getInputStreamLjava_util_jar_JarEntry_subtest0() throws Exception {
- File signedFile = null;
- try {
- Support_Resources.copyFile(resources, null, jarName4);
- signedFile = new File(resources, jarName4);
- } catch (Exception e) {
- fail("Failed to create local file 2: " + e);
- }
-
- try {
- JarFile jar = new JarFile(signedFile);
- JarEntry entry = new JarEntry(entryName3);
- InputStream in = jar.getInputStream(entry);
- in.read();
- } catch (Exception e) {
- fail("Exception during test 3: " + e);
- }
-
- try {
- JarFile jar = new JarFile(signedFile);
- JarEntry entry = new JarEntry(entryName3);
- InputStream in = jar.getInputStream(entry);
- // BEGIN android-added
- byte[] dummy = getAllBytesFromStream(in);
- // END android-added
- assertNull("found certificates", entry.getCertificates());
- } catch (Exception e) {
- fail("Exception during test 4: " + e);
- }
-
- try {
- JarFile jar = new JarFile(signedFile);
- JarEntry entry = new JarEntry(entryName3);
- entry.setSize(1076);
- InputStream in = jar.getInputStream(entry);
- // BEGIN android-added
- byte[] dummy = getAllBytesFromStream(in);
- // END android-added
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (Exception e) {
- fail("Exception during test 5: " + e);
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName5);
- signedFile = new File(resources, jarName5);
- } catch (Exception e) {
- fail("Failed to create local file 5: " + e);
- }
-
- try {
- JarFile jar = new JarFile(signedFile);
- JarEntry entry = new JarEntry(entryName3);
- InputStream in = jar.getInputStream(entry);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (Exception e) {
- fail("Exception during test 5: " + e);
- }
-
- // SHA1 digest, SHA256withRSA signed JAR
- checkSignedJar(jarName6);
-
- // SHA-256 digest, SHA256withRSA signed JAR
- checkSignedJar(jarName7);
-
- // SHA-512 digest, SHA512withECDSA signed JAR
- checkSignedJar(jarName8);
-
- // JAR with a signature that has PKCS#7 Authenticated Attributes
- checkSignedJar(authAttrsJar);
- }
-
- private void checkSignedJar(String jarName) throws Exception {
- Support_Resources.copyFile(resources, null, jarName);
-
- File file = new File(resources, jarName);
-
- JarFile jarFile = new JarFile(file, true);
-
- boolean foundCerts = false;
-
- Enumeration<JarEntry> e = jarFile.entries();
- while (e.hasMoreElements()) {
- JarEntry entry = e.nextElement();
- InputStream is = jarFile.getInputStream(entry);
- is.skip(100000);
- is.close();
- Certificate[] certs = entry.getCertificates();
- if (certs != null && certs.length > 0) {
- foundCerts = true;
- break;
- }
- }
-
- assertTrue(
- "No certificates found during signed jar test for jar \""
- + jarName + "\"", foundCerts);
- }
-
- private Certificate[] getSignedJarCerts(String jarName, boolean chainCheck) throws Exception {
- Support_Resources.copyFile(resources, null, jarName);
-
- File file = new File(resources, jarName);
- Certificate[] foundCerts = null;
-
- JarFile jarFile = new JarFile(file, true, ZipFile.OPEN_READ, chainCheck);
- try {
-
- Enumeration<JarEntry> e = jarFile.entries();
- while (e.hasMoreElements()) {
- JarEntry entry = e.nextElement();
- InputStream is = jarFile.getInputStream(entry);
- // Skip bytes because we have to read the entire file for it to read signatures.
- is.skip(entry.getSize());
- is.close();
- Certificate[] certs = entry.getCertificates();
- if (certs != null && certs.length > 0) {
- foundCerts = certs;
- break;
- }
- }
- } finally {
- jarFile.close();
- }
-
- return foundCerts;
- }
-
- public void testJarFile_Signed_ValidChain_NoCheck() throws Exception {
- Certificate[] certs = getSignedJarCerts(VALID_CHAIN_JAR, false);
- assertNotNull(certs);
- assertEquals(Arrays.deepToString(certs), 3, certs.length);
- assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString());
- assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString());
- assertEquals("CN=root1", ((X509Certificate) certs[2]).getSubjectDN().toString());
- }
-
- public void testJarFile_Signed_ValidChain_Check() throws Exception {
- Certificate[] certs = getSignedJarCerts(VALID_CHAIN_JAR, true);
- assertNotNull(certs);
- assertEquals(Arrays.deepToString(certs), 3, certs.length);
- assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString());
- assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString());
- assertEquals("CN=root1", ((X509Certificate) certs[2]).getSubjectDN().toString());
- }
-
- public void testJarFile_Signed_InvalidChain_NoCheck() throws Exception {
- Certificate[] certs = getSignedJarCerts(INVALID_CHAIN_JAR, false);
- assertNotNull(certs);
- assertEquals(Arrays.deepToString(certs), 3, certs.length);
- assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString());
- assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString());
- assertEquals("CN=root1", ((X509Certificate) certs[2]).getSubjectDN().toString());
- }
-
- public void testJarFile_Signed_InvalidChain_Check() throws Exception {
- Certificate[] certs = getSignedJarCerts(INVALID_CHAIN_JAR, true);
- assertNotNull(certs);
- assertEquals(Arrays.deepToString(certs), 2, certs.length);
- assertEquals("CN=fake-chain", ((X509Certificate) certs[0]).getSubjectDN().toString());
- assertEquals("CN=intermediate1", ((X509Certificate) certs[1]).getSubjectDN().toString());
- }
-
- /*
- * The jar created by 1.4 which does not provide a
- * algorithm-Digest-Manifest-Main-Attributes entry in .SF file.
- */
- public void test_Jar_created_before_java_5() throws IOException {
- String modifiedJarName = "Created_by_1_4.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- jarFile.getInputStream(zipEntry);
- }
- }
-
- /* The jar is intact, then everything is all right. */
- public void test_JarFile_Integrate_Jar() throws IOException {
- String modifiedJarName = "Integrate.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
- }
- }
-
- /**
- * The jar is intact, but the entry object is modified.
- */
- public void testJarVerificationModifiedEntry() throws IOException {
- Support_Resources.copyFile(resources, null, integrateJar);
- File f = new File(resources, integrateJar);
-
- JarFile jarFile = new JarFile(f);
- ZipEntry zipEntry = jarFile.getJarEntry(integrateJarEntry);
- zipEntry.setSize(zipEntry.getSize() + 1);
- jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
-
- jarFile = new JarFile(f);
- zipEntry = jarFile.getJarEntry(integrateJarEntry);
- zipEntry.setSize(zipEntry.getSize() - 1);
- try {
- //jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
- jarFile.getInputStream(zipEntry).read(new byte[5000], 0, 5000);
- fail("SecurityException expected");
- } catch (SecurityException e) {
- // desired
- }
- }
-
- /*
- * If another entry is inserted into Manifest, no security exception will be
- * thrown out.
- */
- public void test_JarFile_InsertEntry_in_Manifest_Jar() throws IOException {
- String modifiedJarName = "Inserted_Entry_Manifest.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- int count = 0;
- while (entries.hasMoreElements()) {
-
- ZipEntry zipEntry = entries.nextElement();
- jarFile.getInputStream(zipEntry);
- count++;
- }
- assertEquals(5, count);
- }
-
- /*
- * If another entry is inserted into Manifest, no security exception will be
- * thrown out.
- */
- public void test_Inserted_Entry_Manifest_with_DigestCode()
- throws IOException {
- String modifiedJarName = "Inserted_Entry_Manifest_with_DigestCode.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- int count = 0;
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- jarFile.getInputStream(zipEntry);
- count++;
- }
- assertEquals(5, count);
- }
-
- /*
- * The content of Test.class is modified, jarFile.getInputStream will not
- * throw security Exception, but it will anytime before the inputStream got
- * from getInputStream method has been read to end.
- */
- public void test_JarFile_Modified_Class() throws IOException {
- String modifiedJarName = "Modified_Class.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- jarFile.getInputStream(zipEntry);
- }
- /* The content of Test.class has been tampered. */
- ZipEntry zipEntry = jarFile.getEntry("Test.class");
- InputStream in = jarFile.getInputStream(zipEntry);
- byte[] buffer = new byte[1024];
- try {
- while (in.available() > 0) {
- in.read(buffer);
- }
- fail("SecurityException expected");
- } catch (SecurityException e) {
- // desired
- }
- }
-
- /*
- * In the Modified.jar, the main attributes of META-INF/MANIFEST.MF is
- * tampered manually. Hence the RI 5.0 JarFile.getInputStream of any
- * JarEntry will throw security exception.
- */
- public void test_JarFile_Modified_Manifest_MainAttributes()
- throws IOException {
- String modifiedJarName = "Modified_Manifest_MainAttributes.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- try {
- jarFile.getInputStream(zipEntry);
- fail("SecurityException expected");
- } catch (SecurityException e) {
- // desired
- }
- }
- }
-
- /*
- * It is all right in our original JarFile. If the Entry Attributes, for
- * example Test.class in our jar, the jarFile.getInputStream will throw
- * Security Exception.
- */
- public void test_JarFile_Modified_Manifest_EntryAttributes()
- throws IOException {
- String modifiedJarName = "Modified_Manifest_EntryAttributes.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- try {
- jarFile.getInputStream(zipEntry);
- fail("should throw Security Exception");
- } catch (SecurityException e) {
- // desired
- }
- }
- }
-
- /*
- * If the content of the .SA file is modified, no matter what it resides,
- * JarFile.getInputStream of any JarEntry will throw Security Exception.
- */
- public void test_JarFile_Modified_SF_EntryAttributes() throws IOException {
- String modifiedJarName = "Modified_SF_EntryAttributes.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry zipEntry = entries.nextElement();
- try {
- jarFile.getInputStream(zipEntry);
- fail("should throw Security Exception");
- } catch (SecurityException e) {
- // desired
- }
- }
- }
-
- public void test_close() throws IOException {
- String modifiedJarName = "Modified_SF_EntryAttributes.jar";
- Support_Resources.copyFile(resources, null, modifiedJarName);
- JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
- true);
- Enumeration<JarEntry> entries = jarFile.entries();
-
- jarFile.close();
- jarFile.close();
-
- // Can not check IOException
- }
-
- /**
- * @throws IOException
- * java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
- */
- public void test_getInputStreamLjava_util_jar_JarEntry() throws IOException {
- File localFile = null;
- try {
- Support_Resources.copyFile(resources, null, jarName);
- localFile = new File(resources, jarName);
- } catch (Exception e) {
- fail("Failed to create local file: " + e);
- }
-
- byte[] b = new byte[1024];
- try {
- JarFile jf = new JarFile(localFile);
- java.io.InputStream is = jf.getInputStream(jf.getEntry(entryName));
- // BEGIN android-removed
- // jf.close();
- // END android-removed
- assertTrue("Returned invalid stream", is.available() > 0);
- int r = is.read(b, 0, 1024);
- is.close();
- StringBuffer sb = new StringBuffer(r);
- for (int i = 0; i < r; i++) {
- sb.append((char) (b[i] & 0xff));
- }
- String contents = sb.toString();
- assertTrue("Incorrect stream read", contents.indexOf("bar") > 0);
- // BEGIN android-added
- jf.close();
- // END android-added
- } catch (Exception e) {
- fail("Exception during test: " + e.toString());
- }
-
- try {
- JarFile jf = new JarFile(localFile);
- InputStream in = jf.getInputStream(new JarEntry("invalid"));
- assertNull("Got stream for non-existent entry", in);
- } catch (Exception e) {
- fail("Exception during test 2: " + e);
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- File signedFile = new File(resources, jarName);
- JarFile jf = new JarFile(signedFile);
- JarEntry jre = new JarEntry("foo/bar/A.class");
- jf.getInputStream(jre);
- // InputStream returned in any way, exception can be thrown in case
- // of reading from this stream only.
- // fail("Should throw ZipException");
- } catch (ZipException ee) {
- // expected
- }
-
- try {
- Support_Resources.copyFile(resources, null, jarName);
- File signedFile = new File(resources, jarName);
- JarFile jf = new JarFile(signedFile);
- JarEntry jre = new JarEntry("foo/bar/A.class");
- jf.close();
- jf.getInputStream(jre);
- // InputStream returned in any way, exception can be thrown in case
- // of reading from this stream only.
- // The same for IOException
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException ee) {
- // expected
- }
- }
-
- /**
- * The jar is intact, but the entry object is modified.
- */
- // Regression test for issue introduced by HARMONY-4569: signed archives containing files with size 0 could not get verified.
- public void testJarVerificationEmptyEntry() throws IOException {
- Support_Resources.copyFile(resources, null, emptyEntryJar);
- File f = new File(resources, emptyEntryJar);
-
- JarFile jarFile = new JarFile(f);
-
- ZipEntry zipEntry = jarFile.getJarEntry(emptyEntry1);
- int res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
- assertEquals("Wrong length of empty jar entry", -1, res);
-
- zipEntry = jarFile.getJarEntry(emptyEntry2);
- res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
- assertEquals("Wrong length of empty jar entry", -1, res);
-
- zipEntry = jarFile.getJarEntry(emptyEntry3);
- res = jarFile.getInputStream(zipEntry).read();
- assertEquals("Wrong length of empty jar entry", -1, res);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java
deleted file mode 100644
index a423f22..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java
+++ /dev/null
@@ -1,505 +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.harmony.archive.tests.java.util.zip;
-
-import tests.support.Support_PlatformFile;
-import tests.support.resource.Support_Resources;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.security.Permission;
-import java.util.Enumeration;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipFile;
-import libcore.java.lang.ref.FinalizationTester;
-
-public class ZipFileTest extends junit.framework.TestCase {
-
- public byte[] getAllBytesFromStream(InputStream is) throws IOException {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- byte[] buf = new byte[512];
- int iRead;
- int off;
- while (is.available() > 0) {
- iRead = is.read(buf, 0, buf.length);
- if (iRead > 0) bs.write(buf, 0, iRead);
- }
- return bs.toByteArray();
- }
-
- // the file hyts_zipFile.zip in setup must be included as a resource
- private String tempFileName;
-
- private ZipFile zfile;
-
- // custom security manager
- SecurityManager sm = new SecurityManager() {
- final String forbidenPermissionAction = "read";
-
-
-
- public void checkPermission(Permission perm) {
- // only check if it's a FilePermission because Locale checks
- // for a PropertyPermission with action"read" to get system props.
- if (perm instanceof FilePermission
- && perm.getActions().equals(forbidenPermissionAction)) {
- throw new SecurityException();
- }
- }
- };
-
- /**
- * java.util.zip.ZipFile#ZipFile(java.io.File)
- */
- public void test_ConstructorLjava_io_File() {
- // Test for method java.util.zip.ZipFile(java.io.File)
- assertTrue("Used to test", true);
- }
-
- /**
- * java.util.zip.ZipFile#ZipFile(java.io.File, int)
- */
- public void test_ConstructorLjava_io_FileI() throws IOException {
- zfile.close(); // about to reopen the same temp file
- File file = new File(tempFileName);
- ZipFile zip = new ZipFile(file, ZipFile.OPEN_DELETE | ZipFile.OPEN_READ);
- zip.close();
- assertTrue("Zip should not exist", !file.exists());
- file = new File(tempFileName);
- file.delete();
- try {
- zip = new ZipFile(file, ZipFile.OPEN_READ);
- fail("IOException expected");
- } catch (IOException ee) {
- // expected
- }
- file = new File(tempFileName);
- try {
- zip = new ZipFile(file, -1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * java.util.zip.ZipFile#ZipFile(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() throws IOException {
- System.setProperty("user.dir", System.getProperty("java.io.tmpdir"));
-
- zfile.close(); // about to reopen the same temp file
- ZipFile zip = new ZipFile(tempFileName);
- zip.close();
- File file = File.createTempFile("zip", "tmp");
- try {
- zip = new ZipFile(file.getName());
- fail("ZipException expected");
- } catch (ZipException ee) {
- // expected
- }
- file.delete();
- }
-
- protected ZipEntry test_finalize1(ZipFile zip) {
- return zip.getEntry("File1.txt");
- }
-
- protected ZipFile test_finalize2(File file) throws IOException {
- return new ZipFile(file);
- }
-
- /**
- * java.util.zip.ZipFile#finalize()
- */
- public void test_finalize() throws IOException {
- InputStream in = Support_Resources.getStream("hyts_ZipFile.zip");
- File file = Support_Resources.createTempFile(".jar");
- OutputStream out = new FileOutputStream(file);
- int result;
- byte[] buf = new byte[4096];
- while ((result = in.read(buf)) != -1) {
- out.write(buf, 0, result);
- }
- in.close();
- out.close();
- /*
- * ZipFile zip = new ZipFile(file); ZipEntry entry1 =
- * zip.getEntry("File1.txt"); assertNotNull("Did not find entry",
- * entry1); entry1 = null; zip = null;
- */
-
- assertNotNull("Did not find entry", test_finalize1(test_finalize2(file)));
- FinalizationTester.induceFinalization();
- file.delete();
- assertTrue("Zip should not exist", !file.exists());
- }
-
- /**
- * @throws IOException
- * java.util.zip.ZipFile#close()
- */
- public void test_close() throws IOException {
- // Test for method void java.util.zip.ZipFile.close()
- File fl = new File(tempFileName);
- ZipFile zf = new ZipFile(fl);
- InputStream is1 = zf.getInputStream(zf.getEntry("File1.txt"));
- InputStream is2 = zf.getInputStream(zf.getEntry("File2.txt"));
-
- is1.read();
- is2.read();
-
- zf.close();
-
- try {
- is1.read();
- fail("IOException expected");
- } catch (IOException ee) {
- // expected
- }
-
- try {
- is2.read();
- fail("IOException expected");
- } catch (IOException ee) {
- // expected
- }
- }
-
- /**
- * java.util.zip.ZipFile#entries()
- */
- public void test_entries() throws Exception {
- // Test for method java.util.Enumeration java.util.zip.ZipFile.entries()
- Enumeration<? extends ZipEntry> enumer = zfile.entries();
- int c = 0;
- while (enumer.hasMoreElements()) {
- ++c;
- enumer.nextElement();
- }
- assertTrue("Incorrect number of entries returned: " + c, c == 6);
-
- Enumeration<? extends ZipEntry> enumeration = zfile.entries();
- zfile.close();
- try {
- enumeration.nextElement();
- fail("did not detect closed file");
- } catch (IllegalStateException expected) {
- }
-
- try {
- enumeration.hasMoreElements();
- fail("did not detect closed file");
- } catch (IllegalStateException expected) {
- }
-
- try {
- zfile.entries();
- fail("did not detect closed file");
- } catch (IllegalStateException expected) {
- }
- }
-
- /**
- * java.util.zip.ZipFile#getEntry(java.lang.String)
- */
- public void test_getEntryLjava_lang_String() throws IOException {
- // Test for method java.util.zip.ZipEntry
- // java.util.zip.ZipFile.getEntry(java.lang.String)
- java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
- assertNotNull("Could not obtain ZipEntry", zentry);
- int r;
- InputStream in;
-
- zentry = zfile.getEntry("testdir1/File1.txt");
- assertNotNull("Could not obtain ZipEntry: testdir1/File1.txt", zentry);
- zentry = zfile.getEntry("testdir1/");
- assertNotNull("Could not obtain ZipEntry: testdir1/", zentry);
- in = zfile.getInputStream(zentry);
- assertNotNull("testdir1/ should not have null input stream", in);
- r = in.read();
- in.close();
- assertEquals("testdir1/ should not contain data", -1, r);
-
- zentry = zfile.getEntry("testdir1/testdir1");
- assertNotNull("Could not obtain ZipEntry: testdir1/testdir1", zentry);
- in = zfile.getInputStream(zentry);
- byte[] buf = new byte[256];
- r = in.read(buf);
- in.close();
- assertEquals("incorrect contents", "This is also text", new String(buf,
- 0, r));
- }
-
- public void test_getEntryLjava_lang_String_AndroidOnly() throws IOException {
- java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
- assertNotNull("Could not obtain ZipEntry", zentry);
- int r;
- InputStream in;
-
- zentry = zfile.getEntry("testdir1");
- assertNotNull("Must be able to obtain ZipEntry: testdir1", zentry);
- in = zfile.getInputStream(zentry);
- /*
- * Android delivers empty InputStream, RI no InputStream at all. The
- * spec doesn't clarify this, so we need to deal with both situations.
- */
- int data = -1;
- if (in != null) {
- data = in.read();
- in.close();
- }
- assertEquals("Must not be able to read directory data", -1, data);
- }
-
- public void test_getEntryLjava_lang_String_Ex() throws IOException {
- java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
- assertNotNull("Could not obtain ZipEntry", zentry);
-
- zfile.close();
- try {
- zfile.getEntry("File2.txt");
- fail("IllegalStateException expected");
- } catch (IllegalStateException ee) {
- }
- }
-
- /**
- * @throws IOException
- * java.util.zip.ZipFile#getInputStream(java.util.zip.ZipEntry)
- */
- public void test_getInputStreamLjava_util_zip_ZipEntry() throws IOException {
- // Test for method java.io.InputStream
- // java.util.zip.ZipFile.getInputStream(java.util.zip.ZipEntry)
- ZipEntry zentry = null;
- InputStream is = null;
- try {
- zentry = zfile.getEntry("File1.txt");
- is = zfile.getInputStream(zentry);
- byte[] rbuf = new byte[1000];
- int r;
- is.read(rbuf, 0, r = (int) zentry.getSize());
- assertEquals("getInputStream read incorrect data", "This is text",
- new String(rbuf, 0, r));
- } catch (java.io.IOException e) {
- fail("IOException during getInputStream");
- } finally {
- try {
- is.close();
- } catch (java.io.IOException e) {
- fail("Failed to close input stream");
- }
- }
-
- zentry = zfile.getEntry("File2.txt");
- zfile.close();
- try {
- is = zfile.getInputStream(zentry);
- fail("IllegalStateException expected");
- } catch (IllegalStateException ee) {
- // expected
- }
-
- // ZipException can not be checked. Stream object returned or null.
- }
-
- /**
- * java.util.zip.ZipFile#getName()
- */
- public void test_getName() {
- // Test for method java.lang.String java.util.zip.ZipFile.getName()
- assertTrue("Returned incorrect name: " + zfile.getName(), zfile
- .getName().equals(tempFileName));
- }
-
- /**
- * @throws IOException
- * java.util.zip.ZipFile#size()
- */
- public void test_size() throws IOException {
- assertEquals(6, zfile.size());
- zfile.close();
- try {
- zfile.size();
- fail("IllegalStateException expected");
- } catch (IllegalStateException expected) {
- }
- }
-
- /**
- * java.io.InputStream#reset()
- */
- public void test_reset() throws IOException {
- // read an uncompressed entry
- ZipEntry zentry = zfile.getEntry("File1.txt");
- InputStream is = zfile.getInputStream(zentry);
- byte[] rbuf1 = new byte[6];
- byte[] rbuf2 = new byte[6];
- int r1, r2;
- r1 = is.read(rbuf1);
- assertEquals(rbuf1.length, r1);
- r2 = is.read(rbuf2);
- assertEquals(rbuf2.length, r2);
-
- try {
- is.reset();
- fail();
- } catch (IOException expected) {
- }
- is.close();
-
- // read a compressed entry
- byte[] rbuf3 = new byte[4185];
- ZipEntry zentry2 = zfile.getEntry("File3.txt");
- is = zfile.getInputStream(zentry2);
- r1 = is.read(rbuf3);
- assertEquals(4183, r1);
- try {
- is.reset();
- fail();
- } catch (IOException expected) {
- }
- is.close();
-
- is = zfile.getInputStream(zentry2);
- r1 = is.read(rbuf3, 0, 3000);
- assertEquals(3000, r1);
- try {
- is.reset();
- fail();
- } catch (IOException expected) {
- }
- is.close();
- }
-
- /**
- * java.io.InputStream#reset()
- */
- public void test_reset_subtest0() throws IOException {
- // read an uncompressed entry
- ZipEntry zentry = zfile.getEntry("File1.txt");
- InputStream is = zfile.getInputStream(zentry);
- byte[] rbuf1 = new byte[12];
- byte[] rbuf2 = new byte[12];
- int r = is.read(rbuf1, 0, 4);
- assertEquals(4, r);
- is.mark(0);
- r = is.read(rbuf1);
- assertEquals(8, r);
- assertEquals(-1, is.read());
-
- try {
- is.reset();
- fail();
- } catch (IOException expected) {
- }
-
- is.close();
-
- // read a compressed entry
- byte[] rbuf3 = new byte[4185];
- ZipEntry zentry2 = zfile.getEntry("File3.txt");
- is = zfile.getInputStream(zentry2);
- r = is.read(rbuf3, 0, 3000);
- assertEquals(3000, r);
- is.mark(0);
- r = is.read(rbuf3);
- assertEquals(1183, r);
- assertEquals(-1, is.read());
-
- try {
- is.reset();
- fail();
- } catch (IOException expected) {
- }
-
- is.close();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- @Override
- protected void setUp() {
- try {
- // Create a local copy of the file since some tests want to alter
- // information.
- tempFileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (tempFileName.charAt(tempFileName.length() - 1) == separator
- .charAt(0)) {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName, "gabba.zip");
- } else {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName + separator, "gabba.zip");
- }
-
- File f = new File(tempFileName);
- f.delete();
- InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
- FileOutputStream fos = new FileOutputStream(f);
- byte[] rbuf = getAllBytesFromStream(is);
- fos.write(rbuf, 0, rbuf.length);
- is.close();
- fos.close();
- zfile = new ZipFile(f);
- } catch (Exception e) {
- System.out.println("Exception during ZipFile setup:");
- e.printStackTrace();
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- @Override
- protected void tearDown() {
- try {
- if (zfile != null) {
- // Note zfile is a user-defined zip file used by other tests and
- // should not be deleted
- zfile.close();
- tempFileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (tempFileName.charAt(tempFileName.length() - 1) == separator
- .charAt(0)) {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName, "gabba.zip");
- } else {
- tempFileName = Support_PlatformFile.getNewPlatformFile(
- tempFileName + separator, "gabba.zip");
- }
-
- File f = new File(tempFileName);
- f.delete();
- }
- } catch (Exception e) {
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java
index f617adb..87b2913 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/ExemptionMechanismTest.java
@@ -17,8 +17,6 @@
package org.apache.harmony.crypto.tests.javax.crypto;
-import dalvik.annotation.SideEffect;
-
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
@@ -186,7 +184,7 @@ public class ExemptionMechanismTest extends TestCase {
}
}
- @SideEffect("Causes OutOfMemoryError to test finalization")
+ // Side Effect: Causes OutOfMemoryError to test finalization
public void test_finalize () {
Mock_ExemptionMechanism mem = new Mock_ExemptionMechanism(null, null, "Name");
assertNotNull(mem);
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java
index 99d127a..0642229 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/KeyAgreementTest.java
@@ -22,6 +22,8 @@
package org.apache.harmony.crypto.tests.javax.crypto;
+import org.apache.harmony.security.tests.support.SpiEngUtils;
+import org.apache.harmony.security.tests.support.TestKeyPair;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
@@ -31,6 +33,7 @@ import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
+import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.DSAParameterSpec;
import java.security.spec.RSAKeyGenParameterSpec;
@@ -40,12 +43,10 @@ import javax.crypto.KeyAgreementSpi;
import javax.crypto.ShortBufferException;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.spec.DHParameterSpec;
-
-import org.apache.harmony.crypto.tests.support.MyKeyAgreementSpi;
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.security.tests.support.TestKeyPair;
-
import junit.framework.TestCase;
+import libcore.java.security.StandardNames;
+import libcore.javax.crypto.MockKey;
+import libcore.javax.crypto.MockKey2;
/**
@@ -676,4 +677,127 @@ public class KeyAgreementTest extends TestCase {
//expected
}
}
+
+ private static abstract class MockProvider extends Provider {
+ public MockProvider(String name) {
+ super(name, 1.0, "Mock provider used for testing");
+ setup();
+ }
+
+ public abstract void setup();
+ }
+
+ public void testKeyAgreement_getInstance_SuppliedProviderNotRegistered_Success()
+ throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ {
+ KeyAgreement s = KeyAgreement.getInstance("FOO", mockProvider);
+ s.init(new MockKey());
+ assertEquals(mockProvider, s.getProvider());
+ }
+ }
+
+ public void testKeyAgreement_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success()
+ throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProvider);
+ try {
+ {
+ Provider mockProvider2 = new MockProvider("MockProvider") {
+ public void setup() {
+ put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName());
+ }
+ };
+ KeyAgreement s = KeyAgreement.getInstance("FOO", mockProvider2);
+ assertEquals(mockProvider2, s.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProvider.getName());
+ }
+ }
+
+ public void testKeyAgreement_getInstance_DelayedInitialization_KeyType() throws Exception {
+ Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") {
+ public void setup() {
+ put("KeyAgreement.FOO", MockKeyAgreementSpi.SpecificKeyTypes.class.getName());
+ put("KeyAgreement.FOO SupportedKeyClasses", MockKey.class.getName());
+ }
+ };
+ Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") {
+ public void setup() {
+ put("KeyAgreement.FOO", MockKeyAgreementSpi.SpecificKeyTypes2.class.getName());
+ put("KeyAgreement.FOO SupportedKeyClasses", MockKey2.class.getName());
+ }
+ };
+ Provider mockProviderAll = new MockProvider("MockProviderAll") {
+ public void setup() {
+ put("KeyAgreement.FOO", MockKeyAgreementSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProviderSpecific);
+ Security.addProvider(mockProviderSpecific2);
+ Security.addProvider(mockProviderAll);
+
+ try {
+ {
+ KeyAgreement s = KeyAgreement.getInstance("FOO");
+ s.init(new MockKey());
+ assertEquals(mockProviderSpecific, s.getProvider());
+
+ try {
+ s.init(new MockKey2());
+ assertEquals(mockProviderSpecific2, s.getProvider());
+ if (StandardNames.IS_RI) {
+ fail("RI was broken before; fix tests now that it works!");
+ }
+ } catch (InvalidKeyException e) {
+ if (!StandardNames.IS_RI) {
+ fail("Non-RI should select the right provider");
+ }
+ }
+ }
+
+ {
+ KeyAgreement s = KeyAgreement.getInstance("FOO");
+ s.init(new PrivateKey() {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+ });
+ assertEquals(mockProviderAll, s.getProvider());
+ }
+
+ {
+ KeyAgreement s = KeyAgreement.getInstance("FOO");
+ assertEquals(mockProviderSpecific, s.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProviderSpecific.getName());
+ Security.removeProvider(mockProviderSpecific2.getName());
+ Security.removeProvider(mockProviderAll.getName());
+ }
+ }
+
}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java
index b1559f5..ddd0695 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java
@@ -27,26 +27,26 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.spec.PSSParameterSpec;
+import java.util.ArrayList;
import java.util.Arrays;
-
import javax.crypto.Mac;
import javax.crypto.MacSpi;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.DHGenParameterSpec;
-
import javax.crypto.spec.SecretKeySpec;
-
import org.apache.harmony.crypto.tests.support.MyMacSpi;
import org.apache.harmony.security.tests.support.SpiEngUtils;
-
import junit.framework.TestCase;
-
import junit.framework.Test;
import junit.framework.TestSuite;
+import libcore.java.security.StandardNames;
+import libcore.javax.crypto.MockKey;
+import libcore.javax.crypto.MockKey2;
/**
* Tests for Mac class constructors and methods
@@ -71,7 +71,7 @@ public class MacTest extends TestCase {
private static String[] validValues = new String[3];
public static final String validAlgorithmsMac [] =
- {"HmacSHA1", "HmacMD5", "HmacSHA256", "HmacSHA384", "HmacSHA512"};
+ {"HmacSHA1", "HmacMD5", "HmacSHA224", "HmacSHA256", "HmacSHA384", "HmacSHA512"};
static {
@@ -90,20 +90,19 @@ public class MacTest extends TestCase {
}
}
- private Mac [] createMacs() {
+ private Mac[] createMacs() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return null;
}
- try {
- Mac m [] = new Mac[3];
- m[0] = Mac.getInstance(defaultAlgorithm);
- m[1] = Mac.getInstance(defaultAlgorithm, defaultProvider);
- m[2] = Mac.getInstance(defaultAlgorithm, defaultProviderName);
- return m;
- } catch (Exception e) {
- return null;
+ ArrayList<Mac> macList = new ArrayList<Mac>();
+ macList.add(Mac.getInstance(defaultAlgorithm));
+ macList.add(Mac.getInstance(defaultAlgorithm, defaultProvider));
+ macList.add(Mac.getInstance(defaultAlgorithm, defaultProviderName));
+ for (Provider p : Security.getProviders("Mac." + defaultAlgorithm)) {
+ macList.add(Mac.getInstance(defaultAlgorithm, p));
}
+ return macList.toArray(new Mac[macList.size()]);
}
/**
@@ -356,9 +355,7 @@ public class MacTest extends TestCase {
* throws ShotBufferException when outOffset is negative or
* outOffset >= output.length or when given buffer is small
*/
- public void testMac10() throws NoSuchAlgorithmException,
- NoSuchProviderException, IllegalArgumentException,
- IllegalStateException, InvalidKeyException {
+ public void testMac10() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -404,9 +401,7 @@ public class MacTest extends TestCase {
* <code>doFinal()</code> methods Assertion: Mac result is stored in
* output buffer
*/
- public void testMac11() throws NoSuchAlgorithmException, NoSuchProviderException,
- IllegalArgumentException, IllegalStateException,
- InvalidKeyException, ShortBufferException {
+ public void testMac11() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -430,9 +425,7 @@ public class MacTest extends TestCase {
* Test for <code>doFinal(byte[] input)</code> method
* Assertion: update Mac and returns result
*/
- public void testMac12() throws NoSuchAlgorithmException, NoSuchProviderException,
- IllegalArgumentException, IllegalStateException,
- InvalidKeyException {
+ public void testMac12() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -447,15 +440,15 @@ public class MacTest extends TestCase {
byte[] res1 = macs[i].doFinal();
byte[] res2 = macs[i].doFinal();
assertEquals("Results are not the same",
- IntegralToString.bytesToHexString(res1, false),
- IntegralToString.bytesToHexString(res2, false));
+ Arrays.toString(res1),
+ Arrays.toString(res2));
res2 = macs[i].doFinal(upd);
macs[i].update(upd);
res1 = macs[i].doFinal();
assertEquals("Results are not the same",
- IntegralToString.bytesToHexString(res1, false),
- IntegralToString.bytesToHexString(res2, false));
+ Arrays.toString(res1),
+ Arrays.toString(res2));
}
}
@@ -464,9 +457,7 @@ public class MacTest extends TestCase {
* Assertion: throws IllegalArgumentException when offset or len is negative,
* offset + len >= input.length
*/
- public void testMac13() throws NoSuchAlgorithmException,
- NoSuchProviderException, IllegalArgumentException, IllegalStateException,
- InvalidKeyException {
+ public void testMac13() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -505,9 +496,7 @@ public class MacTest extends TestCase {
* methods
* Assertion: updates Mac
*/
- public void testMac14() throws NoSuchAlgorithmException,
- NoSuchProviderException, IllegalArgumentException, IllegalStateException,
- InvalidKeyException {
+ public void testMac14() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -547,7 +536,7 @@ public class MacTest extends TestCase {
* Test for <code>clone()</code> method
* Assertion: returns Mac object or throws CloneNotSupportedException
*/
- public void testMacClone() throws NoSuchAlgorithmException, CloneNotSupportedException {
+ public void testMacClone() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -572,9 +561,7 @@ public class MacTest extends TestCase {
* Assertion: throws InvalidKeyException and InvalidAlgorithmParameterException
* when parameters are not appropriate
*/
- public void testInit() throws NoSuchAlgorithmException, NoSuchProviderException,
- IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException,
- InvalidKeyException {
+ public void testInit() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -588,6 +575,7 @@ public class MacTest extends TestCase {
SecretKeySpec sks1 = new SecretKeySpec(b, "RSA");
for (int i = 0; i < macs.length; i++) {
+ macs[i].reset();
macs[i].init(sks);
try {
macs[i].init(sks1, algPSS);
@@ -621,9 +609,7 @@ public class MacTest extends TestCase {
* methods
* Assertion: processes Mac; if input is null then do nothing
*/
- public void testUpdateByteBuffer01() throws NoSuchAlgorithmException, NoSuchProviderException,
- IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException,
- InvalidKeyException {
+ public void testUpdateByteBuffer01() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -664,9 +650,7 @@ public class MacTest extends TestCase {
* methods
* Assertion: processes Mac
*/
- public void testUpdateByteBuffer02() throws NoSuchAlgorithmException, NoSuchProviderException,
- IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException,
- InvalidKeyException {
+ public void testUpdateByteBuffer02() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -699,7 +683,7 @@ public class MacTest extends TestCase {
* Test for <code>clone()</code> method
* Assertion: clone if provider is clo
*/
- public void testClone() {
+ public void testClone() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -720,7 +704,7 @@ public class MacTest extends TestCase {
* Test for <code>getMacLength()</code> method
* Assertion: return Mac length
*/
- public void testGetMacLength() {
+ public void testGetMacLength() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -736,7 +720,7 @@ public class MacTest extends TestCase {
* Test for <code>reset()</code> method
* Assertion: return Mac length
*/
- public void testReset() throws InvalidKeyException {
+ public void testReset() throws Exception {
if (!DEFSupported) {
fail(NotSupportedMsg);
return;
@@ -781,15 +765,14 @@ public class MacTest extends TestCase {
}
MacSpi spi = new MyMacSpi();
Mac mac = new myMac(spi, defaultProvider, defaultAlgorithm);
- assertEquals("Incorrect algorithm", mac.getAlgorithm(),
- defaultAlgorithm);
- assertEquals("Incorrect provider", mac.getProvider(), defaultProvider);
+ assertEquals("Incorrect algorithm", defaultAlgorithm, mac.getAlgorithm());
+ assertEquals("Incorrect provider", defaultProvider, mac.getProvider());
try {
mac.init(null, null);
fail("Exception should be thrown because init(..) uses incorrect parameters");
} catch (Exception e) {
}
- assertEquals("Invalid mac length", mac.getMacLength(), 0);
+ assertEquals("Invalid mac length", 0, mac.getMacLength());
mac = new myMac(null, null, null);
assertNull("Algorithm must be null", mac.getAlgorithm());
@@ -892,6 +875,127 @@ public class MacTest extends TestCase {
}
}
+ private static abstract class MockProvider extends Provider {
+ public MockProvider(String name) {
+ super(name, 1.0, "Mock provider used for testing");
+ setup();
+ }
+
+ public abstract void setup();
+ }
+
+ public void testMac_getInstance_SuppliedProviderNotRegistered_Success() throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ {
+ Mac s = Mac.getInstance("FOO", mockProvider);
+ s.init(new MockKey());
+ assertEquals(mockProvider, s.getProvider());
+ }
+ }
+
+ public void testMac_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success()
+ throws Exception {
+ Provider mockProvider = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProvider);
+ try {
+ {
+ Provider mockProvider2 = new MockProvider("MockProvider") {
+ public void setup() {
+ put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName());
+ }
+ };
+ Mac s = Mac.getInstance("FOO", mockProvider2);
+ assertEquals(mockProvider2, s.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProvider.getName());
+ }
+ }
+
+ public void testMac_getInstance_DelayedInitialization_KeyType() throws Exception {
+ Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") {
+ public void setup() {
+ put("Mac.FOO", MockMacSpi.SpecificKeyTypes.class.getName());
+ put("Mac.FOO SupportedKeyClasses", MockKey.class.getName());
+ }
+ };
+ Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") {
+ public void setup() {
+ put("Mac.FOO", MockMacSpi.SpecificKeyTypes2.class.getName());
+ put("Mac.FOO SupportedKeyClasses", MockKey2.class.getName());
+ }
+ };
+ Provider mockProviderAll = new MockProvider("MockProviderAll") {
+ public void setup() {
+ put("Mac.FOO", MockMacSpi.AllKeyTypes.class.getName());
+ }
+ };
+
+ Security.addProvider(mockProviderSpecific);
+ Security.addProvider(mockProviderSpecific2);
+ Security.addProvider(mockProviderAll);
+
+ try {
+ {
+ Mac s = Mac.getInstance("FOO");
+ s.init(new MockKey());
+ assertEquals(mockProviderSpecific, s.getProvider());
+
+ try {
+ s.init(new MockKey2());
+ assertEquals(mockProviderSpecific2, s.getProvider());
+ if (StandardNames.IS_RI) {
+ fail("RI was broken before; fix tests now that it works!");
+ }
+ } catch (InvalidKeyException e) {
+ if (!StandardNames.IS_RI) {
+ fail("Non-RI should select the right provider");
+ }
+ }
+ }
+
+ {
+ Mac s = Mac.getInstance("FOO");
+ s.init(new PrivateKey() {
+ @Override
+ public String getAlgorithm() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public String getFormat() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+
+ @Override
+ public byte[] getEncoded() {
+ throw new UnsupportedOperationException("not implemented");
+ }
+ });
+ assertEquals(mockProviderAll, s.getProvider());
+ }
+
+ {
+ Mac s = Mac.getInstance("FOO");
+ assertEquals(mockProviderSpecific, s.getProvider());
+ }
+ } finally {
+ Security.removeProvider(mockProviderSpecific.getName());
+ Security.removeProvider(mockProviderSpecific2.getName());
+ Security.removeProvider(mockProviderAll.getName());
+ }
+ }
+
public static Test suite() {
return new TestSuite(MacTest.class);
}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java
new file mode 100644
index 0000000..4b53a6b
--- /dev/null
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockKeyAgreementSpi.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2014 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.harmony.crypto.tests.javax.crypto;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+import javax.crypto.KeyAgreementSpi;
+import javax.crypto.SecretKey;
+import javax.crypto.ShortBufferException;
+import libcore.javax.crypto.MockKey;
+import libcore.javax.crypto.MockKey2;
+
+public class MockKeyAgreementSpi extends KeyAgreementSpi {
+ public static class SpecificKeyTypes extends MockKeyAgreementSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockKey)) {
+ throw new InvalidKeyException("Must be MockKey!");
+ }
+ }
+ }
+
+ public static class SpecificKeyTypes2 extends MockKeyAgreementSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockKey2)) {
+ throw new InvalidKeyException("Must be MockKey2!");
+ }
+ }
+ }
+
+ public static class AllKeyTypes extends MockKeyAgreementSpi {
+ }
+
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ }
+
+ @Override
+ protected Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException,
+ IllegalStateException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected byte[] engineGenerateSecret() throws IllegalStateException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected int engineGenerateSecret(byte[] sharedSecret, int offset)
+ throws IllegalStateException, ShortBufferException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected SecretKey engineGenerateSecret(String algorithm) throws IllegalStateException,
+ NoSuchAlgorithmException, InvalidKeyException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineInit(Key key, SecureRandom random) throws InvalidKeyException {
+ checkKeyType(key);
+ }
+
+ @Override
+ protected void engineInit(Key key, AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ checkKeyType(key);
+ }
+}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java
new file mode 100644
index 0000000..6a28fb3
--- /dev/null
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MockMacSpi.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2014 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.harmony.crypto.tests.javax.crypto;
+
+import java.security.InvalidKeyException;
+import java.security.InvalidParameterException;
+import java.security.Key;
+import java.security.spec.AlgorithmParameterSpec;
+import javax.crypto.MacSpi;
+import libcore.javax.crypto.MockKey;
+import libcore.javax.crypto.MockKey2;
+
+public class MockMacSpi extends MacSpi {
+ public static class SpecificKeyTypes extends MockMacSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockKey)) {
+ throw new InvalidKeyException("Must be MockKey!");
+ }
+ }
+ }
+
+ public static class SpecificKeyTypes2 extends MockMacSpi {
+ @Override
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ if (!(key instanceof MockKey2)) {
+ throw new InvalidKeyException("Must be MockKey2!");
+ }
+ }
+ }
+
+ public static class AllKeyTypes extends MockMacSpi {
+ }
+
+ public void checkKeyType(Key key) throws InvalidKeyException {
+ }
+
+ @Override
+ protected int engineGetMacLength() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException,
+ InvalidParameterException {
+ checkKeyType(key);
+ }
+
+ @Override
+ protected void engineUpdate(byte input) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineUpdate(byte[] input, int offset, int len) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected byte[] engineDoFinal() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected void engineReset() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java
index 3ea57bf..5cbdab3 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/SealedObjectTest.java
@@ -165,6 +165,34 @@ public class SealedObjectTest extends TestCase {
+ "in cipher.", algorithm, so.getAlgorithm());
}
+ // https://code.google.com/p/android/issues/detail?id=73235
+ public void testGetAlgorithmAfterSerialization() throws Exception {
+ String secret = "secret string";
+ String algorithm = "DES";
+ KeyGenerator kg = KeyGenerator.getInstance(algorithm);
+ Key key = kg.generateKey();
+
+ Cipher cipher = Cipher.getInstance(algorithm);
+ cipher.init(Cipher.ENCRYPT_MODE, key);
+ SealedObject so = new SealedObject(secret, cipher);
+
+ assertEquals("The algorithm name should be the same as used "
+ + "in cipher.", algorithm, so.getAlgorithm());
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(so);
+ oos.close();
+
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
+ SealedObject readSo = (SealedObject) ois.readObject();
+ ois.close();
+
+ // Bug 73235 would swap the Cipher algorithm and parameters. Parameters is not public but
+ // algorithm is so we check that.
+ assertEquals(so.getAlgorithm(), readSo.getAlgorithm());
+ }
+
/**
* getObject(Key key) method testing. Tests if the object sealed with
* encryption algorithm and specified parameters can be retrieved by
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java
index 0b8f017..85c2438 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherAesTest.java
@@ -18,7 +18,7 @@ package org.apache.harmony.crypto.tests.javax.crypto.func;
import junit.framework.TestCase;
public class CipherAesTest extends TestCase {
-// 216 cases checked
+// 324 cases checked
public void test_AesNoISO() {
CipherSymmetricKeyThread aesNoISO = new CipherSymmetricKeyThread("AES",
new int[] {128, 192, 256}, // Keysize must be 128, 192, 256.
@@ -29,7 +29,8 @@ public class CipherAesTest extends TestCase {
"CFB128", "OFB", "OFB8", "OFB16", "OFB24", "OFB32",
"OFB40", "OFB48", "OFB56", "OFB64", "OFB72", "OFB80",
"OFB88", "OFB96", "OFB104", "OFB112", "OFB120",
- "OFB128"}, new String[] {"NoPadding", "PKCS5Padding"});
+ "OFB128"},
+ new String[] {"NoPadding", "PKCS5Padding", "PKCS7Padding"});
aesNoISO.launcher();
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java
index d8565f1..c7b4f20 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherDESedeTest.java
@@ -18,7 +18,7 @@ package org.apache.harmony.crypto.tests.javax.crypto.func;
import junit.framework.TestCase;
public class CipherDESedeTest extends TestCase {
-// 80 cases checked
+// 120 cases checked
public void test_DESedeNoISO() {
CipherSymmetricKeyThread DESedeNoISO = new CipherSymmetricKeyThread(
"DESede", new int[] {112, 168},// Keysize must be 112 or 168.
@@ -26,7 +26,8 @@ public class CipherDESedeTest extends TestCase {
"ECB", "CBC", "CFB", "CFB8", "CFB16", "CFB24", "CFB32",
"CFB40", "CFB48", "CFB56", "CFB64", "OFB", "OFB8",
"OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56",
- "OFB64"}, new String[] {"NoPadding", "PKCS5Padding"});
+ "OFB64"},
+ new String[] {"NoPadding", "PKCS5Padding", "PKCS7Padding"});
DESedeNoISO.launcher();
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java b/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java
index c9eb26e..ff4babc 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/support/MyCipher.java
@@ -52,7 +52,8 @@ public class MyCipher extends CipherSpi {
@Override
protected void engineSetPadding(String padding)
throws NoSuchPaddingException {
- if (!"PKCS5Padding".equals(padding)) {
+ if ((!"PKCS5Padding".equals(padding))
+ && (!"PKCS7Padding".equals(padding))) {
throw new NoSuchPaddingException(padding);
}
}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
index 5d8c621..290ae9a 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
@@ -17,8 +17,6 @@
package org.apache.harmony.luni.tests.internal.net.www.protocol.http;
-import dalvik.annotation.SideEffect;
-
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
@@ -270,7 +268,7 @@ public class HttpURLConnectionTest extends TestCase {
ProxySelector.setDefault(defPS);
}
}
- @SideEffect("Suffers from side effect of other, currently unknown test")
+ // SideEffect: Suffers from side effect of other, currently unknown test
public void testProxyAuthorization() throws Exception {
// Set up test Authenticator
Authenticator.setDefault(new Authenticator() {
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
index c516f67..5258fd1 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
@@ -17,6 +17,12 @@
package org.apache.harmony.luni.tests.internal.net.www.protocol.https;
+import com.google.mockwebserver.Dispatcher;
+import com.google.mockwebserver.MockResponse;
+import com.google.mockwebserver.MockWebServer;
+import com.google.mockwebserver.RecordedRequest;
+import com.google.mockwebserver.SocketPolicy;
+
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -25,7 +31,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.io.PrintStream;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
@@ -36,20 +41,15 @@ import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Arrays;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
+import java.util.Collections;
+import java.util.LinkedList;
+
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
@@ -59,22 +59,26 @@ import libcore.javax.net.ssl.TestTrustManager;
/**
* Implementation independent test for HttpsURLConnection.
- * The test needs certstore file placed in system classpath
- * and named as "key_store." + the type of the
- * default KeyStore installed in the system in lower case.
- * <br>
- * For example: if default KeyStore type in the system is BKS
- * (i.e. java.security file sets up the property keystore.type=BKS),
- * thus classpath should point to the directory with "key_store.bks"
- * file.
- * <br>
- * This certstore file should contain self-signed certificate
- * generated by keytool utility in a usual way.
- * <br>
- * The password to the certstore should be "password" (without quotes).
*/
public class HttpsURLConnectionTest extends TestCase {
+ private static final String POST_METHOD = "POST";
+
+ private static final String GET_METHOD = "GET";
+
+ /**
+ * Data to be posted by client to the server when the method is POST.
+ */
+ private static final String POST_DATA = "_.-^ Client's Data ^-._";
+
+ /**
+ * The content of the response to be sent during HTTPS session.
+ */
+ private static final String RESPONSE_CONTENT
+ = "<HTML>\n"
+ + "<HEAD><TITLE>HTTPS Response Content</TITLE></HEAD>\n"
+ + "</HTML>";
+
// the password to the store
private static final String KS_PASSWORD = "password";
@@ -107,7 +111,7 @@ public class HttpsURLConnectionTest extends TestCase {
* Checks that HttpsURLConnection's default SSLSocketFactory is operable.
*/
public void testGetDefaultSSLSocketFactory() throws Exception {
- // set up the properties defining the default values needed by SSL stuff
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
SSLSocketFactory defaultSSLSF = HttpsURLConnection.getDefaultSSLSocketFactory();
@@ -119,55 +123,58 @@ public class HttpsURLConnectionTest extends TestCase {
}
public void testHttpsConnection() throws Throwable {
- // set up the properties defining the default values needed by SSL stuff
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSL server socket acting as a server
SSLContext ctx = getContext();
- ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
+
+ // create a webserver to check and respond to requests
+ SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ MockWebServer webServer = createWebServer(ctx, dispatcher);
// create url connection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL url = webServer.getUrl("/");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ctx.getSocketFactory());
// perform the interaction between the peers
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
+ executeClientRequest(connection, false /* doOutput */);
- // check the connection state
- checkConnectionStateParameters(connection, peerSocket);
+ checkConnectionStateParameters(connection, dispatcher.getLastRequest());
// should silently exit
connection.connect();
+
+ webServer.shutdown();
}
/**
- * Tests the behaviour of HTTPS connection in case of unavailability
- * of requested resource.
+ * Tests the behaviour of HTTPS connection in case of unavailability of requested resource.
*/
public void testHttpsConnection_Not_Found_Response() throws Throwable {
- // set up the properties defining the default values needed by SSL stuff
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSL server socket acting as a server
SSLContext ctx = getContext();
- ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
+
+ // create a webserver to check and respond to requests
+ SingleRequestDispatcher dispatcher =
+ new SingleRequestDispatcher(GET_METHOD, NOT_FOUND_CODE);
+ MockWebServer webServer = createWebServer(ctx, dispatcher);
// create url connection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL url = webServer.getUrl("/");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ctx.getSocketFactory());
try {
- doInteraction(connection, ss, NOT_FOUND_CODE);
+ executeClientRequest(connection, false /* doOutput */);
fail("Expected exception was not thrown.");
} catch (FileNotFoundException e) {
if (DO_LOG) {
@@ -178,94 +185,100 @@ public class HttpsURLConnectionTest extends TestCase {
// should silently exit
connection.connect();
+
+ webServer.shutdown();
}
/**
- * Tests possibility to set up the default SSLSocketFactory
- * to be used by HttpsURLConnection.
+ * Tests possibility to set up the default SSLSocketFactory to be used by HttpsURLConnection.
*/
public void testSetDefaultSSLSocketFactory() throws Throwable {
- // create the SSLServerSocket which will be used by server side
+ // set up the properties pointing to the key/trust stores
+ setUpStoreProperties();
+
SSLContext ctx = getContext();
- SSLServerSocket ss = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(0);
- SSLSocketFactory socketFactory = (SSLSocketFactory) ctx.getSocketFactory();
+ SSLSocketFactory socketFactory = ctx.getSocketFactory();
// set up the factory as default
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
// check the result
assertSame("Default SSLSocketFactory differs from expected",
- socketFactory, HttpsURLConnection.getDefaultSSLSocketFactory());
+ socketFactory, HttpsURLConnection.getDefaultSSLSocketFactory());
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the initial default host name verifier.
+ TestHostnameVerifier initialHostnameVerifier = new TestHostnameVerifier();
+ HttpsURLConnection.setDefaultHostnameVerifier(initialHostnameVerifier);
+
+ // create a webserver to check and respond to requests
+ SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ MockWebServer webServer = createWebServer(ctx, dispatcher);
// create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL url = webServer.getUrl("/");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- TestHostnameVerifier hnv_late = new TestHostnameVerifier();
- // late initialization: should not be used for created connection
- HttpsURLConnection.setDefaultHostnameVerifier(hnv_late);
+ // late initialization: this HostnameVerifier should not be used for created connection
+ TestHostnameVerifier lateHostnameVerifier = new TestHostnameVerifier();
+ HttpsURLConnection.setDefaultHostnameVerifier(lateHostnameVerifier);
// perform the interaction between the peers
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- // check the connection state
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection, false /* doOutput */);
+ checkConnectionStateParameters(connection, dispatcher.getLastRequest());
+
// check the verification process
- assertTrue("Hostname verification was not done", hnv.verified);
+ assertTrue("Hostname verification was not done", initialHostnameVerifier.verified);
assertFalse("Hostname verification should not be done by this verifier",
- hnv_late.verified);
+ lateHostnameVerifier.verified);
// check the used SSLSocketFactory
assertSame("Default SSLSocketFactory should be used",
- HttpsURLConnection.getDefaultSSLSocketFactory(),
- connection.getSSLSocketFactory());
+ HttpsURLConnection.getDefaultSSLSocketFactory(),
+ connection.getSSLSocketFactory());
- // should silently exit
- connection.connect();
+ webServer.shutdown();
}
/**
- * Tests possibility to set up the SSLSocketFactory
- * to be used by HttpsURLConnection.
+ * Tests
+ * {@link javax.net.ssl.HttpsURLConnection#setSSLSocketFactory(javax.net.ssl.SSLSocketFactory)}.
*/
public void testSetSSLSocketFactory() throws Throwable {
- // create the SSLServerSocket which will be used by server side
+ // set up the properties pointing to the key/trust stores
SSLContext ctx = getContext();
- SSLServerSocket ss = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(0);
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the initial default host name verifier.
+ TestHostnameVerifier hostnameVerifier = new TestHostnameVerifier();
+ HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
+
+ // create a webserver to check and respond to requests
+ SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ MockWebServer webServer = createWebServer(ctx, dispatcher);
// create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL url = webServer.getUrl("/");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- SSLSocketFactory socketFactory = (SSLSocketFactory) ctx.getSocketFactory();
+ // late initialization: should not be used for the created connection.
+ SSLSocketFactory socketFactory = ctx.getSocketFactory();
connection.setSSLSocketFactory(socketFactory);
- TestHostnameVerifier hnv_late = new TestHostnameVerifier();
// late initialization: should not be used for created connection
- HttpsURLConnection.setDefaultHostnameVerifier(hnv_late);
+ TestHostnameVerifier lateHostnameVerifier = new TestHostnameVerifier();
+ HttpsURLConnection.setDefaultHostnameVerifier(lateHostnameVerifier);
// perform the interaction between the peers
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- // check the connection state
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection, false /* doOutput */);
+ checkConnectionStateParameters(connection, dispatcher.getLastRequest());
// check the verification process
- assertTrue("Hostname verification was not done", hnv.verified);
+ assertTrue("Hostname verification was not done", hostnameVerifier.verified);
assertFalse("Hostname verification should not be done by this verifier",
- hnv_late.verified);
+ lateHostnameVerifier.verified);
// check the used SSLSocketFactory
assertNotSame("Default SSLSocketFactory should not be used",
- HttpsURLConnection.getDefaultSSLSocketFactory(),
- connection.getSSLSocketFactory());
- assertSame("Result differs from expected",
- socketFactory, connection.getSSLSocketFactory());
+ HttpsURLConnection.getDefaultSSLSocketFactory(),
+ connection.getSSLSocketFactory());
+ assertSame("Result differs from expected", socketFactory, connection.getSSLSocketFactory());
- // should silently exit
- connection.connect();
+ webServer.shutdown();
}
/**
@@ -304,97 +317,107 @@ public class HttpsURLConnectionTest extends TestCase {
* Tests if setHostnameVerifier() method replaces default verifier.
*/
public void testSetHostnameVerifier() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- SSLServerSocket ss = (SSLServerSocket)
- getContext().getServerSocketFactory().createServerSocket(0);
+ SSLContext ctx = getContext();
+
+ TestHostnameVerifier defaultHostnameVerifier = new TestHostnameVerifier();
+ HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // create a webserver to check and respond to requests
+ SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ MockWebServer webServer = createWebServer(ctx, dispatcher);
// create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL url = webServer.getUrl("/");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(getContext().getSocketFactory());
- TestHostnameVerifier hnv_late = new TestHostnameVerifier();
- // replace default verifier
- connection.setHostnameVerifier(hnv_late);
+ // replace the default verifier
+ TestHostnameVerifier connectionHostnameVerifier = new TestHostnameVerifier();
+ connection.setHostnameVerifier(connectionHostnameVerifier);
// perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- assertTrue("Hostname verification was not done", hnv_late.verified);
+ executeClientRequest(connection, false /* doOutput */);
+ assertTrue("Hostname verification was not done", connectionHostnameVerifier.verified);
assertFalse("Hostname verification should not be done by this verifier",
- hnv.verified);
- checkConnectionStateParameters(connection, peerSocket);
+ defaultHostnameVerifier.verified);
- // should silently exit
- connection.connect();
+ checkConnectionStateParameters(connection, dispatcher.getLastRequest());
+
+ webServer.shutdown();
}
/**
* Tests the behaviour in case of sending the data to the server.
*/
public void test_doOutput() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- SSLServerSocket ss = (SSLServerSocket)
- getContext().getServerSocketFactory().createServerSocket(0);
+ SSLContext ctx = getContext();
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // create a webserver to check and respond to requests
+ SingleRequestDispatcher dispatcher = new SingleRequestDispatcher(POST_METHOD, OK_CODE);
+ MockWebServer webServer = createWebServer(ctx, dispatcher);
+
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
// create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL url = webServer.getUrl("/");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(getContext().getSocketFactory());
- connection.setDoOutput(true);
// perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection, true /* doOutput */);
+ checkConnectionStateParameters(connection, dispatcher.getLastRequest());
// should silently exit
connection.connect();
+
+ webServer.shutdown();
}
/**
* Tests HTTPS connection process made through the proxy server.
*/
public void testProxyConnection() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
+ SSLContext ctx = getContext();
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
+
+ // create a server that pretends to be both a proxy and then the webserver
+ // request 1: proxy CONNECT, respond with OK
+ ProxyConnectDispatcher proxyConnectDispatcher =
+ new ProxyConnectDispatcher(false /* authenticationRequired */);
+ // request 2: tunnelled GET, respond with OK
+ SingleRequestDispatcher getDispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ DelegatingDispatcher delegatingDispatcher =
+ new DelegatingDispatcher(proxyConnectDispatcher, getDispatcher);
+ MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher);
// create HttpsURLConnection to be tested
+ URL proxyUrl = proxyAndWebServer.getUrl("/");
+ InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort());
URL url = new URL("https://requested.host:55556/requested.data");
HttpsURLConnection connection = (HttpsURLConnection)
- url.openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- ss.getLocalPort())));
+ url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress));
connection.setSSLSocketFactory(getContext().getSocketFactory());
// perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection, false /* doOutput */);
+ checkConnectionStateParameters(connection, getDispatcher.getLastRequest());
// should silently exit
connection.connect();
+
+ proxyAndWebServer.shutdown();
}
/**
@@ -402,81 +425,105 @@ public class HttpsURLConnectionTest extends TestCase {
* Proxy server needs authentication.
*/
public void testProxyAuthConnection() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
+ SSLContext ctx = getContext();
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
Authenticator.setDefault(new Authenticator() {
-
protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("user", "password"
- .toCharArray());
+ return new PasswordAuthentication("user", "password".toCharArray());
}
});
+ // create a server that pretends to be both a proxy and then the webserver
+ // request 1: proxy CONNECT, respond with auth challenge
+ ProxyConnectAuthFailDispatcher authFailDispatcher = new ProxyConnectAuthFailDispatcher();
+ // request 2: proxy CONNECT, respond with OK
+ ProxyConnectDispatcher proxyConnectDispatcher =
+ new ProxyConnectDispatcher(true /* authenticationRequired */);
+ // request 3: tunnelled GET, respond with OK
+ SingleRequestDispatcher getDispatcher = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ DelegatingDispatcher delegatingDispatcher = new DelegatingDispatcher(
+ authFailDispatcher, proxyConnectDispatcher, getDispatcher);
+ MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher);
+
// create HttpsURLConnection to be tested
+ URL proxyUrl = proxyAndWebServer.getUrl("/");
+ InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort());
URL url = new URL("https://requested.host:55555/requested.data");
HttpsURLConnection connection = (HttpsURLConnection)
- url.openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- ss.getLocalPort())));
+ url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress));
connection.setSSLSocketFactory(getContext().getSocketFactory());
// perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection, false /* doOutput */);
+ checkConnectionStateParameters(connection, getDispatcher.getLastRequest());
// should silently exit
connection.connect();
+
+ proxyAndWebServer.shutdown();
}
/**
* Tests HTTPS connection process made through the proxy server.
- * 2 HTTPS connections are opened for one URL. For the first time
- * the connection is opened through one proxy,
- * for the second time through another.
+ * Two HTTPS connections are opened for one URL: the first time the connection is opened
+ * through one proxy, the second time it is opened through another.
*/
public void testConsequentProxyConnection() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // create a server that pretends to be both a proxy and then the webserver
+ SingleRequestDispatcher getDispatcher1 = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ MockWebServer proxyAndWebServer1 = createProxiedServer(getDispatcher1);
// create HttpsURLConnection to be tested
+ URL proxyUrl1 = proxyAndWebServer1.getUrl("/");
URL url = new URL("https://requested.host:55555/requested.data");
+ InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl1.getPort());
HttpsURLConnection connection = (HttpsURLConnection)
- url.openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- ss.getLocalPort())));
+ url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress));
connection.setSSLSocketFactory(getContext().getSocketFactory());
+ executeClientRequest(connection, false /* doOutput */);
+ checkConnectionStateParameters(connection, getDispatcher1.getLastRequest());
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
+ proxyAndWebServer1.shutdown();
- // create another SSLServerSocket which will be used by server side
- ss = new ServerSocket(0);
+ // create another server
+ SingleRequestDispatcher getDispatcher2 = new SingleRequestDispatcher(GET_METHOD, OK_CODE);
+ MockWebServer proxyAndWebServer2 = createProxiedServer(getDispatcher2);
- connection = (HttpsURLConnection) url.openConnection(new Proxy(
- Proxy.Type.HTTP, new InetSocketAddress("localhost", ss.getLocalPort())));
- connection.setSSLSocketFactory(getContext().getSocketFactory());
+ // create another HttpsURLConnection to be tested
+ URL proxyUrl2 = proxyAndWebServer2.getUrl("/");
+ InetSocketAddress proxyAddress2 = new InetSocketAddress("localhost", proxyUrl2.getPort());
+ HttpsURLConnection connection2 = (HttpsURLConnection) url.openConnection(
+ new Proxy(Proxy.Type.HTTP, proxyAddress2));
+ connection2.setSSLSocketFactory(getContext().getSocketFactory());
// perform the interaction between the peers and check the results
- peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection2, false /* doOutput */);
+ checkConnectionStateParameters(connection2, getDispatcher2.getLastRequest());
+
+ proxyAndWebServer2.shutdown();
+ }
+
+ private static MockWebServer createProxiedServer(Dispatcher getDispatcher)
+ throws Exception {
+ // request 1: proxy CONNECT, respond with OK
+ ProxyConnectDispatcher proxyConnectDispatcher =
+ new ProxyConnectDispatcher(false /* authenticationRequired */);
+ // request 2: The get dispatcher.
+ DelegatingDispatcher delegatingDispatcher1 =
+ new DelegatingDispatcher(proxyConnectDispatcher, getDispatcher);
+ return createProxyAndWebServer(getContext(), delegatingDispatcher1);
}
/**
@@ -485,37 +532,47 @@ public class HttpsURLConnectionTest extends TestCase {
* Client sends data to the server.
*/
public void testProxyAuthConnection_doOutput() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
+ SSLContext ctx = getContext();
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
Authenticator.setDefault(new Authenticator() {
-
protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("user", "password"
- .toCharArray());
+ return new PasswordAuthentication("user", "password".toCharArray());
}
});
+ // create a server that pretends to be both a proxy and then the webserver
+ // request 1: proxy CONNECT, respond with auth challenge
+ ProxyConnectAuthFailDispatcher authFailDispatcher = new ProxyConnectAuthFailDispatcher();
+ // request 2: proxy CONNECT, respond with OK
+ ProxyConnectDispatcher proxyConnectDispatcher =
+ new ProxyConnectDispatcher(true /* authenticationRequired */);
+ // request 3: tunnelled POST, respond with OK
+ SingleRequestDispatcher postDispatcher = new SingleRequestDispatcher(POST_METHOD, OK_CODE);
+ DelegatingDispatcher delegatingDispatcher = new DelegatingDispatcher(
+ authFailDispatcher, proxyConnectDispatcher, postDispatcher);
+ MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher);
+ URL proxyUrl = proxyAndWebServer.getUrl("/");
+
// create HttpsURLConnection to be tested
- URL url = new URL("https://requested.host:55554/requested.data");
+ InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort());
HttpsURLConnection connection = (HttpsURLConnection)
- url.openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- ss.getLocalPort())));
+ proxyUrl.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress));
connection.setSSLSocketFactory(getContext().getSocketFactory());
- connection.setDoOutput(true);
// perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss, OK_CODE, true);
- checkConnectionStateParameters(connection, peerSocket);
+ executeClientRequest(connection, true /* doOutput */);
+ checkConnectionStateParameters(connection, postDispatcher.getLastRequest());
+
+ // should silently exit
+ connection.connect();
+
+ proxyAndWebServer.shutdown();
}
/**
@@ -524,79 +581,82 @@ public class HttpsURLConnectionTest extends TestCase {
* (Authenticator was not set up in the system).
*/
public void testProxyAuthConnectionFailed() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // create a server that pretends to be both a proxy that requests authentication.
+ MockWebServer proxyAndWebServer = new MockWebServer();
+ ProxyConnectAuthFailDispatcher authFailDispatcher = new ProxyConnectAuthFailDispatcher();
+ proxyAndWebServer.setDispatcher(authFailDispatcher);
+ proxyAndWebServer.play();
// create HttpsURLConnection to be tested
+ URL proxyUrl = proxyAndWebServer.getUrl("/");
+ InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort());
URL url = new URL("https://requested.host:55555/requested.data");
HttpsURLConnection connection = (HttpsURLConnection)
- url.openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- ss.getLocalPort())));
+ url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress));
connection.setSSLSocketFactory(getContext().getSocketFactory());
// perform the interaction between the peers and check the results
try {
- doInteraction(connection, ss, AUTHENTICATION_REQUIRED_CODE, true);
+ executeClientRequest(connection, false);
} catch (IOException e) {
// SSL Tunnelling failed
if (DO_LOG) {
- System.out.println("Got expected IOException: "
- + e.getMessage());
+ System.out.println("Got expected IOException: " + e.getMessage());
}
}
}
/**
- * Tests the behaviour of HTTPS connection in case of unavailability
- * of requested resource.
+ * Tests the behaviour of HTTPS connection in case of unavailability of requested resource (as
+ * reported by the target web server).
*/
public void testProxyConnection_Not_Found_Response() throws Throwable {
- // setting up the properties pointing to the key/trust stores
+ // set up the properties pointing to the key/trust stores
setUpStoreProperties();
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
+ SSLContext ctx = getContext();
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
+ // set the HostnameVerifier required to satisfy SSL - always returns "verified".
+ HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
+
+ // create a server that pretends to be a proxy
+ ProxyConnectDispatcher proxyConnectDispatcher =
+ new ProxyConnectDispatcher(false /* authenticationRequired */);
+ SingleRequestDispatcher notFoundDispatcher =
+ new SingleRequestDispatcher(GET_METHOD, NOT_FOUND_CODE);
+ DelegatingDispatcher delegatingDispatcher =
+ new DelegatingDispatcher(proxyConnectDispatcher, notFoundDispatcher);
+ MockWebServer proxyAndWebServer = createProxyAndWebServer(ctx, delegatingDispatcher);
// create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
+ URL proxyUrl = proxyAndWebServer.getUrl("/");
+ InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyUrl.getPort());
+ URL url = new URL("https://requested.host:55555/requested.data");
HttpsURLConnection connection = (HttpsURLConnection)
- url.openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- ss.getLocalPort())));
+ url.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddress));
connection.setSSLSocketFactory(getContext().getSocketFactory());
try {
- doInteraction(connection, ss, NOT_FOUND_CODE); // NOT FOUND
+ executeClientRequest(connection, false /* doOutput */);
fail("Expected exception was not thrown.");
} catch (FileNotFoundException e) {
if (DO_LOG) {
- System.out.println("Expected exception was thrown: "
- + e.getMessage());
+ System.out.println("Expected exception was thrown: " + e.getMessage());
}
}
}
- /**
- * Log the name of the test case to be executed.
- */
public void setUp() throws Exception {
super.setUp();
if (DO_LOG) {
+ // Log the name of the test case to be executed.
System.out.println();
System.out.println("------------------------");
System.out.println("------ " + getName());
@@ -604,8 +664,8 @@ public class HttpsURLConnectionTest extends TestCase {
}
if (store != null) {
- String ksFileName = ("org/apache/harmony/luni/tests/key_store."
- + KeyStore.getDefaultType().toLowerCase());
+ String ksFileName = "org/apache/harmony/luni/tests/key_store." +
+ KeyStore.getDefaultType().toLowerCase();
InputStream in = getClass().getClassLoader().getResourceAsStream(ksFileName);
FileOutputStream out = new FileOutputStream(store);
BufferedInputStream bufIn = new BufferedInputStream(in, 8192);
@@ -627,28 +687,21 @@ public class HttpsURLConnectionTest extends TestCase {
}
}
- /**
- * Checks the HttpsURLConnection getter's values and compares
- * them with actual corresponding values of remote peer.
- */
- public static void checkConnectionStateParameters(
- HttpsURLConnection clientConnection, SSLSocket serverPeer)
- throws Exception {
- SSLSession session = serverPeer.getSession();
-
- assertEquals(session.getCipherSuite(), clientConnection.getCipherSuite());
- assertEquals(session.getLocalPrincipal(), clientConnection.getPeerPrincipal());
- assertEquals(session.getPeerPrincipal(), clientConnection.getLocalPrincipal());
+ private static void checkConnectionStateParameters(
+ HttpsURLConnection connection, RecordedRequest request) throws Exception {
+ assertEquals(request.getSslCipherSuite(), connection.getCipherSuite());
+ assertEquals(request.getSslLocalPrincipal(), connection.getPeerPrincipal());
+ assertEquals(request.getSslPeerPrincipal(), connection.getLocalPrincipal());
- Certificate[] serverCertificates = clientConnection.getServerCertificates();
- Certificate[] localCertificates = session.getLocalCertificates();
+ Certificate[] serverCertificates = connection.getServerCertificates();
+ Certificate[] localCertificates = request.getSslLocalCertificates();
assertTrue("Server certificates differ from expected",
- Arrays.equals(serverCertificates, localCertificates));
+ Arrays.equals(serverCertificates, localCertificates));
- localCertificates = clientConnection.getLocalCertificates();
- serverCertificates = session.getPeerCertificates();
+ localCertificates = connection.getLocalCertificates();
+ serverCertificates = request.getSslPeerCertificates();
assertTrue("Local certificates differ from expected",
- Arrays.equals(serverCertificates, localCertificates));
+ Arrays.equals(serverCertificates, localCertificates));
}
/**
@@ -714,395 +767,233 @@ public class HttpsURLConnectionTest extends TestCase {
}
/**
- * Performs interaction between client's HttpsURLConnection and
- * servers side (ServerSocket).
+ * The host name verifier used in test.
*/
- public static Socket doInteraction(final HttpsURLConnection clientConnection,
- final ServerSocket serverSocket)
- throws Throwable {
- return doInteraction(clientConnection, serverSocket, OK_CODE, false);
+ static class TestHostnameVerifier implements HostnameVerifier {
+
+ boolean verified = false;
+
+ public boolean verify(String hostname, SSLSession session) {
+ if (DO_LOG) {
+ System.out.println("***> verification " + hostname + " "
+ + session.getPeerHost());
+ }
+ verified = true;
+ return true;
+ }
}
/**
- * Performs interaction between client's HttpsURLConnection and
- * servers side (ServerSocket). Server will response with specified
- * response code.
+ * Creates a {@link MockWebServer} that acts as both a proxy and then a web server with the
+ * supplied {@link SSLContext} and {@link Dispatcher}. The dispatcher provided must handle the
+ * CONNECT request/responses and {@link SocketPolicy} needed to simulate the hand-off from proxy
+ * to web server. See {@link HttpsURLConnectionTest.ProxyConnectDispatcher}.
*/
- public static Socket doInteraction(final HttpsURLConnection clientConnection,
- final ServerSocket serverSocket,
- final int responseCode)
- throws Throwable {
- return doInteraction(clientConnection, serverSocket, responseCode, false);
+ private static MockWebServer createProxyAndWebServer(SSLContext ctx, Dispatcher dispatcher)
+ throws IOException {
+ return createServer(ctx, dispatcher, true /* handleProxying */);
}
/**
- * Performs interaction between client's HttpsURLConnection and
- * servers side (ServerSocket). Server will response with specified
- * response code.
- * @param doAuthentication specifies
- * if the server needs client authentication.
+ * Creates a {@link MockWebServer} that acts as (only) a web server with the supplied
+ * {@link SSLContext} and {@link Dispatcher}.
*/
- public static Socket doInteraction(final HttpsURLConnection clientConnection,
- final ServerSocket serverSocket,
- final int responseCode,
- final boolean doAuthentication)
- throws Throwable {
- // set up the connection
- clientConnection.setDoInput(true);
- clientConnection.setConnectTimeout(TIMEOUT);
- clientConnection.setReadTimeout(TIMEOUT);
+ private static MockWebServer createWebServer(SSLContext ctx, Dispatcher dispatcher)
+ throws IOException {
+ return createServer(ctx, dispatcher, false /* handleProxying */);
+ }
- ServerWork server = new ServerWork(serverSocket, responseCode, doAuthentication);
+ private static MockWebServer createServer(
+ SSLContext ctx, Dispatcher dispatcher, boolean handleProxying)
+ throws IOException {
+ MockWebServer webServer = new MockWebServer();
+ webServer.useHttps(ctx.getSocketFactory(), handleProxying /* tunnelProxy */);
+ webServer.setDispatcher(dispatcher);
+ webServer.play();
+ return webServer;
+ }
- ClientConnectionWork client = new ClientConnectionWork(clientConnection);
+ /**
+ * A {@link Dispatcher} that has a list of dispatchers to delegate to, each of which will be
+ * used for one request and then discarded.
+ */
+ private static class DelegatingDispatcher extends Dispatcher {
+ private LinkedList<Dispatcher> delegates = new LinkedList<Dispatcher>();
- ExecutorService executorService = Executors.newFixedThreadPool(2);
- try {
- Future<Void> serverFuture = executorService.submit(server);
- Future<Void> clientFuture = executorService.submit(client);
-
- Throwable t = null;
- try {
- serverFuture.get(30, TimeUnit.SECONDS);
- } catch (ExecutionException e) {
- t = e.getCause();
- }
- try {
- clientFuture.get(30, TimeUnit.SECONDS);
- } catch (ExecutionException e) {
- // two problems? log the first before overwriting
- if (t != null) {
- t.printStackTrace();
- }
- t = e.getCause();
- }
- if (t != null) {
- throw t;
- }
- } catch (ExecutionException e) {
- throw e.getCause();
- } finally {
- executorService.shutdown();
+ public DelegatingDispatcher(Dispatcher... dispatchers) {
+ addAll(dispatchers);
+ }
+
+ private void addAll(Dispatcher... dispatchers) {
+ Collections.addAll(delegates, dispatchers);
+ }
+
+ @Override
+ public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
+ return delegates.removeFirst().dispatch(request);
}
- return server.peerSocket;
+ @Override
+ public SocketPolicy peekSocketPolicy() {
+ return delegates.getFirst().peekSocketPolicy();
+ }
}
- /**
- * The host name verifier used in test.
- */
- static class TestHostnameVerifier implements HostnameVerifier {
+ /** Handles a request for SSL tunnel: Answers with a request to authenticate. */
+ private static class ProxyConnectAuthFailDispatcher extends Dispatcher {
- boolean verified = false;
+ @Override
+ public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
+ assertEquals("CONNECT", request.getMethod());
- public boolean verify(String hostname, SSLSession session) {
- if (DO_LOG) {
- System.out.println("***> verification " + hostname + " "
- + session.getPeerHost());
- }
- verified = true;
- return true;
+ MockResponse response = new MockResponse();
+ response.setResponseCode(AUTHENTICATION_REQUIRED_CODE);
+ response.addHeader("Proxy-authenticate: Basic realm=\"localhost\"");
+ log("Authentication required. Sending response: " + response);
+ return response;
+ }
+
+ private void log(String msg) {
+ HttpsURLConnectionTest.log("ProxyConnectAuthFailDispatcher", msg);
}
}
/**
- * The base class for mock Client and Server.
+ * Handles a request for SSL tunnel: Answers with a success and the socket is upgraded to SSL.
*/
- static class Work {
-
- /**
- * The header of OK HTTP response.
- */
- static final String responseHead = "HTTP/1.1 200 OK\r\n";
-
- /**
- * The response message to be sent to the proxy CONNECT request.
- */
- static final String proxyResponse = responseHead + "\r\n";
-
- /**
- * The content of the response to be sent during HTTPS session.
- */
- static final String httpsResponseContent
- = "<HTML>\n"
- + "<HEAD><TITLE>HTTPS Response Content</TITLE></HEAD>\n"
- + "</HTML>";
-
- /**
- * The tail of the response to be sent during HTTPS session.
- */
- static final String httpsResponseTail
- = "Content-type: text/html\r\n"
- + "Content-length: " + httpsResponseContent.length() + "\r\n"
- + "\r\n"
- + httpsResponseContent;
-
- /**
- * The response requiring client's proxy authentication.
- */
- static final String respAuthenticationRequired
- = "HTTP/1.0 407 Proxy authentication required\r\n"
- + "Proxy-authenticate: Basic realm=\"localhost\"\r\n"
- + "\r\n";
-
- /**
- * The data to be posted by client to the server.
- */
- static final String clientsData = "_.-^ Client's Data ^-._";
-
- /**
- * The print stream used for debug log.
- * If it is null debug info will not be printed.
- */
- private PrintStream out = System.out;
-
- /**
- * Prints log message.
- */
- public synchronized void log(String message) {
- if (DO_LOG && (out != null)) {
- out.println("[" + this + "]: " + message);
+ private static class ProxyConnectDispatcher extends Dispatcher {
+
+ private final boolean authenticationRequired;
+
+ private ProxyConnectDispatcher(boolean authenticationRequired) {
+ this.authenticationRequired = authenticationRequired;
+ }
+
+ @Override
+ public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
+ if (authenticationRequired) {
+ // check provided authorization credentials
+ assertNotNull("no proxy-authorization credentials: " + request,
+ request.getHeader("proxy-authorization"));
+ log("Got authenticated request:\n" + request);
+ log("------------------");
}
+
+ assertEquals("CONNECT", request.getMethod());
+ log("Send proxy response");
+ MockResponse response = new MockResponse();
+ response.setResponseCode(200);
+ response.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END);
+ return response;
+ }
+
+ @Override
+ public SocketPolicy peekSocketPolicy() {
+ return SocketPolicy.UPGRADE_TO_SSL_AT_END;
+ }
+
+ private void log(String msg) {
+ HttpsURLConnectionTest.log("ProxyConnectDispatcher", msg);
}
}
/**
- * The class used for server side works.
+ * Handles a request: Answers with a response with a specified status code.
+ * If the {@code expectedMethod} is {@code POST} a hardcoded response body {@link #POST_DATA}
+ * will be included in the response.
*/
- static class ServerWork extends Work implements Callable<Void> {
-
- // the server socket used for connection
- private final ServerSocket serverSocket;
+ private static class SingleRequestDispatcher extends Dispatcher {
- // indicates if the server acts as proxy server
- private final boolean actAsProxy;
-
- // indicates if the server needs proxy authentication
- private final boolean needProxyAuthentication;
-
- // response code to be send to the client peer
+ private final String expectedMethod;
private final int responseCode;
- // the socket connected with client peer
- private Socket peerSocket;
-
- /**
- * Creates the thread acting as a server side.
- * @param serverSocket the server socket to be used during connection
- * @param responseCode the response code to be sent to the client
- * @param needProxyAuthentication
- * indicates if the server needs proxy authentication
- */
- public ServerWork(ServerSocket serverSocket,
- int responseCode,
- boolean needProxyAuthentication) {
- this.serverSocket = serverSocket;
+ private RecordedRequest lastRequest;
+
+ private SingleRequestDispatcher(String expectedMethod, int responseCode) {
this.responseCode = responseCode;
- this.needProxyAuthentication = needProxyAuthentication;
- // will act as a proxy server if the specified server socket
- // is not a secure server socket
- this.actAsProxy = !(serverSocket instanceof SSLServerSocket);
- if (!actAsProxy) {
- // demand client to send its certificate
- ((SSLServerSocket) serverSocket).setNeedClientAuth(true);
- }
+ this.expectedMethod = expectedMethod;
}
- /**
- * Closes the connection.
- */
- public void closeSocket(Socket socket) {
- if (socket == null) {
- return;
+ @Override
+ public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
+ if (lastRequest != null) {
+ fail("More than one request received");
}
- try {
- socket.getInputStream().close();
- } catch (IOException e) {}
- try {
- socket.getOutputStream().close();
- } catch (IOException e) {}
- try {
- socket.close();
- } catch (IOException e) {}
+ log("Request received: " + request);
+ lastRequest = request;
+ assertEquals(expectedMethod, request.getMethod());
+ if (POST_METHOD.equals(expectedMethod)) {
+ assertEquals(POST_DATA, request.getUtf8Body());
+ }
+
+ MockResponse response = new MockResponse();
+ response.setResponseCode(responseCode);
+ response.setBody(RESPONSE_CONTENT);
+
+ log("Responding with: " + response);
+ return response;
}
- /**
- * Performs the actual server work.
- * If some exception occurs during the work it will be
- * stored in the <code>thrown</code> field.
- */
- public Void call() throws Exception {
- // the buffer used for reading the messages
- byte[] buff = new byte[2048];
- // the number of bytes read into the buffer
- try {
- // configure the server socket to avoid blocking
- serverSocket.setSoTimeout(TIMEOUT);
- // accept client connection
- peerSocket = serverSocket.accept();
- // configure the client connection to avoid blocking
- peerSocket.setSoTimeout(TIMEOUT);
- log("Client connection ACCEPTED");
-
- InputStream is = peerSocket.getInputStream();
- OutputStream os = peerSocket.getOutputStream();
-
- int num = is.read(buff);
- if (num == -1) {
- log("Unexpected EOF");
- return null;
- }
-
- String message = new String(buff, 0, num);
- log("Got request:\n" + message);
- log("------------------");
+ public RecordedRequest getLastRequest() {
+ return lastRequest;
+ }
- if (!actAsProxy) {
- // Act as Server (not Proxy) side
- if (message.startsWith("POST")) {
- // client connection sent some data
- log("try to read client data");
- String data = message.substring(message.indexOf("\r\n\r\n")+4);
- log("client's data: '" + data + "'");
- // check the received data
- assertEquals(clientsData, data);
- }
- } else {
- if (needProxyAuthentication) {
- // Do proxy work
- log("Authentication required...");
- // send Authentication Request
- os.write(respAuthenticationRequired.getBytes());
- // read request
- num = is.read(buff);
- if (num == -1) {
- // this connection was closed,
- // do clean up and create new one:
- closeSocket(peerSocket);
- peerSocket = serverSocket.accept();
- peerSocket.setSoTimeout(TIMEOUT);
- log("New client connection ACCEPTED");
- is = peerSocket.getInputStream();
- os = peerSocket.getOutputStream();
- num = is.read(buff);
- }
- message = new String(buff, 0, num);
- log("Got authenticated request:\n" + message);
- log("------------------");
- // check provided authorization credentials
- assertTrue("no proxy-authorization credentials: " + message,
- message.toLowerCase().indexOf("proxy-authorization:") != -1);
- }
-
- assertTrue(message.startsWith("CONNECT"));
- // request for SSL tunnel
- log("Send proxy response");
- os.write(proxyResponse.getBytes());
-
- log("Perform SSL Handshake...");
- // create sslSocket acting as a remote server peer
- SSLSocket sslSocket = (SSLSocket)
- getContext().getSocketFactory().createSocket(peerSocket,
- "localhost",
- peerSocket.getPort(),
- true); // do autoclose
- sslSocket.setUseClientMode(false);
- // demand client authentication
- sslSocket.setNeedClientAuth(true);
- sslSocket.startHandshake();
- peerSocket = sslSocket;
- is = peerSocket.getInputStream();
- os = peerSocket.getOutputStream();
-
- // read the HTTP request sent by secure connection
- // (HTTPS request)
- num = is.read(buff);
- message = new String(buff, 0, num);
- log("[Remote Server] Request from SSL tunnel:\n" + message);
- log("------------------");
-
- if (message.startsWith("POST")) {
- // client connection sent some data
- log("[Remote Server] try to read client data");
- String data = message.substring(message.indexOf("\r\n\r\n")+4);
- log("[Remote Server] client's data: '" + message + "'");
- // check the received data
- assertEquals(clientsData, data);
- }
-
- log("[Remote Server] Sending the response by SSL tunnel...");
- }
-
- // send the response with specified response code
- os.write(("HTTP/1.1 " + responseCode
- + " Message\r\n" + httpsResponseTail).getBytes());
- os.flush();
- os.close();
- log("Work is DONE actAsProxy=" + actAsProxy);
- return null;
- } finally {
- closeSocket(peerSocket);
- try {
- serverSocket.close();
- } catch (IOException e) {}
- }
+ @Override
+ public SocketPolicy peekSocketPolicy() {
+ return SocketPolicy.DISCONNECT_AT_END;
}
- @Override public String toString() {
- return actAsProxy ? "Proxy Server" : "Server";
+ private void log(String msg) {
+ HttpsURLConnectionTest.log("SingleRequestDispatcher", msg);
}
}
/**
- * The class used for client side work.
+ * Executes an HTTP request using the supplied connection. If {@code doOutput} is {@code true}
+ * the request made is a POST and the request body sent is {@link #POST_DATA}.
+ * If {@code doOutput} is {@code false} the request made is a GET. The response must be a
+ * success with a body {@link #RESPONSE_CONTENT}.
*/
- static class ClientConnectionWork extends Work implements Callable<Void> {
-
- // connection to be used to contact the server side
- private HttpsURLConnection connection;
-
- /**
- * Creates the thread acting as a client side.
- * @param connection connection to be used to contact the server side
- */
- public ClientConnectionWork(HttpsURLConnection connection) {
- this.connection = connection;
- log("Created over connection: " + connection.getClass());
- }
+ private static void executeClientRequest(
+ HttpsURLConnection connection, boolean doOutput) throws IOException {
- /**
- * Performs the actual client work.
- * If some exception occurs during the work it will be
- * stored in the <code>thrown<code> field.
- */
- public Void call() throws Exception {
- log("Opening the connection to " + connection.getURL());
- connection.connect();
- log("Connection has been ESTABLISHED, using proxy: " + connection.usingProxy());
- if (connection.getDoOutput()) {
- log("Posting data");
- // connection configured to post data, do so
- connection.getOutputStream().write(clientsData.getBytes());
- }
- // read the content of HTTP(s) response
- InputStream is = connection.getInputStream();
- log("Input Stream obtained");
- byte[] buff = new byte[2048];
- int num = 0;
- int byt = 0;
- while ((num < buff.length) && ((byt = is.read()) != -1)) {
- buff[num++] = (byte) byt;
- }
- String message = new String(buff, 0, num);
- log("Got content:\n" + message);
- log("------------------");
- log("Response code: " + connection.getResponseCode());
- assertEquals(httpsResponseContent, message);
- return null;
+ // set up the connection
+ connection.setDoInput(true);
+ connection.setConnectTimeout(TIMEOUT);
+ connection.setReadTimeout(TIMEOUT);
+ connection.setDoOutput(doOutput);
+
+ log("Client", "Opening the connection to " + connection.getURL());
+ connection.connect();
+ log("Client", "Connection has been ESTABLISHED, using proxy: " + connection.usingProxy());
+ if (doOutput) {
+ log("Client", "Posting data");
+ // connection configured to post data, do so
+ OutputStream os = connection.getOutputStream();
+ os.write(POST_DATA.getBytes());
+ }
+ // read the content of HTTP(s) response
+ InputStream is = connection.getInputStream();
+ log("Client", "Input Stream obtained");
+ byte[] buff = new byte[2048];
+ int num = 0;
+ int byt;
+ while ((num < buff.length) && ((byt = is.read()) != -1)) {
+ buff[num++] = (byte) byt;
}
+ String message = new String(buff, 0, num);
+ log("Client", "Got content:\n" + message);
+ log("Client", "------------------");
+ log("Client", "Response code: " + connection.getResponseCode());
+ assertEquals(RESPONSE_CONTENT, message);
+ }
- @Override public String toString() {
- return "Client Connection";
+ /**
+ * Prints log message.
+ */
+ public static synchronized void log(String origin, String message) {
+ if (DO_LOG) {
+ System.out.println("[" + origin + "]: " + message);
}
}
}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java
index 12406f3..d1f92ec 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java
@@ -17,13 +17,17 @@
package org.apache.harmony.luni.tests.java.io;
+import junit.framework.TestCase;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+import tests.support.Support_ASimpleInputStream;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -35,34 +39,22 @@ import java.io.ObjectInputValidation;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
+import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.Serializable;
-import java.io.SerializablePermission;
import java.io.StreamCorruptedException;
import java.lang.reflect.Proxy;
-import java.security.Permission;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
@SuppressWarnings("serial")
public class ObjectInputStreamTest extends TestCase implements
Serializable {
- ObjectInputStream ois;
-
- ObjectOutputStream oos;
-
- ByteArrayOutputStream bao;
-
public class SerializableTestHelper implements Serializable {
public String aField1;
@@ -127,9 +119,306 @@ public class ObjectInputStreamTest extends TestCase implements
Hashtable h = new Hashtable();
}
- /**
- * java.io.ObjectInputStream#readObject()
- */
+ static final long serialVersionUID = 1L;
+
+ ObjectInputStream ois;
+
+ ObjectOutputStream oos;
+
+ ByteArrayOutputStream bao;
+
+ boolean readStreamHeaderCalled;
+
+ private final String testString = "Lorem ipsum...";
+
+ private final int testLength = testString.length();
+
+ public void test_ConstructorLjava_io_InputStream_IOException() throws IOException {
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois = new ObjectInputStream(sis);
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ }
+
+ public void test_ClassDescriptor() throws IOException,
+ ClassNotFoundException {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc(
+ baos);
+ oos.writeObject(String.class);
+ oos.close();
+ Class<?> cls = TestClassForSerialization.class;
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ ObjectInputStreamWithReadDesc ois = new ObjectInputStreamWithReadDesc(
+ bais, cls);
+ Object obj = ois.readObject();
+ ois.close();
+ assertEquals(cls, obj);
+ }
+
+ public void test_available_IOException() throws IOException {
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.available();
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public void test_close() throws Exception {
+ // Test for method void java.io.ObjectInputStream.close()
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.close();
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public void test_enableResolveObjectB() throws IOException {
+ // Start testing without a SecurityManager.
+ BasicObjectInputStream bois = new BasicObjectInputStream();
+ assertFalse("Test 1: Object resolving must be disabled by default.",
+ bois.enableResolveObject(true));
+
+ assertTrue("Test 2: enableResolveObject did not return the previous value.",
+ bois.enableResolveObject(false));
+ }
+
+ public void test_read_IOException() throws IOException {
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.read();
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public void test_read$BII_Exception() throws IOException {
+ byte[] buf = new byte[testLength];
+ oos.writeObject(testString);
+ oos.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ try {
+ ois.read(buf, 0, -1);
+ fail("IndexOutOfBoundsException was not thrown.");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ ois.read(buf, -1,1);
+ fail("IndexOutOfBoundsException was not thrown.");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ ois.read(buf, testLength, 1);
+ fail("IndexOutOfBoundsException was not thrown.");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ ois.close();
+
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.read(buf, 0, testLength);
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public void test_readFully$B() throws IOException {
+ byte[] buf = new byte[testLength];
+ oos.writeBytes(testString);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.readFully(buf);
+ assertEquals("Test 1: Incorrect bytes read;",
+ testString, new String(buf));
+ ois.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.read();
+ try {
+ ois.readFully(buf);
+ fail("Test 2: EOFException expected.");
+ } catch (EOFException e) {
+ // Expected.
+ }
+ }
+
+ public void test_readFully$B_Exception() throws IOException {
+ byte[] buf = new byte[testLength];
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.readFully(buf);
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public void test_readFully$BII() throws IOException {
+ // Test for method void java.io.ObjectInputStream.readFully(byte [],
+ // int, int)
+ byte[] buf = new byte[testLength];
+ oos.writeBytes(testString);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.readFully(buf, 0, testLength);
+ assertEquals("Read incorrect bytes", testString, new String(buf));
+ ois.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.read();
+ try {
+ ois.readFully(buf);
+ fail("Test 2: EOFException expected.");
+ } catch (EOFException e) {
+ // Expected.
+ }
+ }
+
+ public void test_readFully$BII_Exception() throws IOException {
+ byte[] buf = new byte[testLength];
+ oos.writeObject(testString);
+ oos.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ try {
+ ois.readFully(buf, 0, -1);
+ fail("IndexOutOfBoundsException was not thrown.");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ ois.readFully(buf, -1,1);
+ fail("IndexOutOfBoundsException was not thrown.");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ ois.readFully(buf, testLength, 1);
+ fail("IndexOutOfBoundsException was not thrown.");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ ois.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.readFully(buf, 0, 1);
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public void test_readLine_IOException() throws IOException {
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.readLine();
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ private void fillStreamHeader(byte[] buffer) {
+ short magic = java.io.ObjectStreamConstants.STREAM_MAGIC;
+ short version = java.io.ObjectStreamConstants.STREAM_VERSION;
+
+ if (buffer.length < 4) {
+ throw new IllegalArgumentException("The buffer's minimal length must be 4.");
+ }
+
+ // Initialize the buffer with the correct header for object streams
+ buffer[0] = (byte) (magic >> 8);
+ buffer[1] = (byte) magic;
+ buffer[2] = (byte) (version >> 8);
+ buffer[3] = (byte) (version);
+ }
+
+ public void test_readObjectOverride() throws Exception {
+ byte[] buffer = new byte[4];
+
+ // Initialize the buffer with the correct header for object streams
+ fillStreamHeader(buffer);
+
+ // Test 1: Check that readObjectOverride() returns null if there
+ // is no input stream.
+ BasicObjectInputStream bois = new BasicObjectInputStream();
+ assertNull("Test 1:", bois.readObjectOverride());
+
+ // Test 2: Check that readObjectOverride() throws an IOException
+ // if there is an input stream.
+ bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
+ try {
+ bois.readObjectOverride();
+ fail("Test 2: IOException expected.");
+ } catch (IOException e) {}
+
+ bois.close();
+ }
+
public void test_readObjectMissingClasses() throws Exception {
SerializationTest.verifySelf(new A1(), new SerializableAssert() {
public void assertDeserialized(Serializable initial,
@@ -139,9 +428,190 @@ public class ObjectInputStreamTest extends TestCase implements
});
}
- /**
- * java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream)
- */
+ public void test_readStreamHeader() throws IOException {
+ String testString = "Lorem ipsum";
+ BasicObjectInputStream bois;
+ short magic = java.io.ObjectStreamConstants.STREAM_MAGIC;
+ short version = java.io.ObjectStreamConstants.STREAM_VERSION;
+ byte[] buffer = new byte[20];
+
+ // Initialize the buffer with the correct header for object streams
+ fillStreamHeader(buffer);
+ System.arraycopy(testString.getBytes(), 0, buffer, 4, testString.length());
+
+ // Test 1: readStreamHeader should not throw a StreamCorruptedException.
+ // It should get called by the ObjectInputStream constructor.
+ try {
+ readStreamHeaderCalled = false;
+ bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
+ bois.close();
+ } catch (StreamCorruptedException e) {
+ fail("Test 1: Unexpected StreamCorruptedException.");
+ }
+ assertTrue("Test 1: readStreamHeader() has not been called.",
+ readStreamHeaderCalled);
+
+ // Test 2: Make the stream magic number invalid and check that
+ // readStreamHeader() throws an exception.
+ buffer[0] = (byte)magic;
+ buffer[1] = (byte)(magic >> 8);
+ try {
+ readStreamHeaderCalled = false;
+ bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
+ fail("Test 2: StreamCorruptedException expected.");
+ bois.close();
+ } catch (StreamCorruptedException e) {
+ }
+ assertTrue("Test 2: readStreamHeader() has not been called.",
+ readStreamHeaderCalled);
+
+ // Test 3: Make the stream version invalid and check that
+ // readStreamHeader() throws an exception.
+ buffer[0] = (byte)(magic >> 8);
+ buffer[1] = (byte)magic;
+ buffer[2] = (byte)(version);
+ buffer[3] = (byte)(version >> 8);
+ try {
+ readStreamHeaderCalled = false;
+ bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
+ fail("Test 3: StreamCorruptedException expected.");
+ bois.close();
+ } catch (StreamCorruptedException e) {
+ }
+ assertTrue("Test 3: readStreamHeader() has not been called.",
+ readStreamHeaderCalled);
+ }
+
+ public void test_readUnsignedByte() throws IOException {
+ oos.writeByte(-1);
+ oos.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Test 1: Incorrect unsigned byte written or read.",
+ 255, ois.readUnsignedByte());
+
+ try {
+ ois.readUnsignedByte();
+ fail("Test 2: EOFException expected.");
+ } catch (EOFException e) {
+ // Expected.
+ }
+
+ ois.close();
+ try {
+ ois.readUnsignedByte();
+ fail("Test 3: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ }
+
+ public void test_readUnsignedShort() throws IOException {
+ // Test for method int java.io.ObjectInputStream.readUnsignedShort()
+ oos.writeShort(-1);
+ oos.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Test 1: Incorrect unsigned short written or read.",
+ 65535, ois.readUnsignedShort());
+
+ try {
+ ois.readUnsignedShort();
+ fail("Test 2: EOFException expected.");
+ } catch (EOFException e) {
+ // Expected.
+ }
+
+ ois.close();
+ try {
+ ois.readUnsignedShort();
+ fail("Test 3: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ }
+
+ public void test_skipBytesI_IOException() throws IOException {
+ oos.writeObject(testString);
+ oos.close();
+
+ Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
+ ois = new ObjectInputStream(sis);
+ sis.throwExceptionOnNextUse = true;
+ try {
+ ois.skipBytes(5);
+ fail("Test 1: IOException expected.");
+ } catch (IOException e) {
+ // Expected.
+ }
+ sis.throwExceptionOnNextUse = false;
+ ois.close();
+ }
+
+ public static class A implements Serializable {
+
+ private static final long serialVersionUID = 11L;
+
+ public String name = "name";
+ }
+
+ public static class B extends A {}
+
+ public static class C extends B {
+
+ private static final long serialVersionUID = 33L;
+ }
+
+ class BasicObjectInputStream extends ObjectInputStream {
+ public BasicObjectInputStream() throws IOException, SecurityException {
+ super();
+ }
+
+ public BasicObjectInputStream(InputStream input) throws IOException {
+ super(input);
+ }
+
+ public boolean enableResolveObject(boolean enable)
+ throws SecurityException {
+ return super.enableResolveObject(enable);
+ }
+
+ public Object readObjectOverride() throws ClassNotFoundException, IOException {
+ return super.readObjectOverride();
+ }
+
+ public void readStreamHeader() throws IOException {
+ readStreamHeaderCalled = true;
+ super.readStreamHeader();
+ }
+
+ public Class<?> resolveProxyClass(String[] interfaceNames)
+ throws IOException, ClassNotFoundException {
+ return super.resolveProxyClass(interfaceNames);
+ }
+ }
+
+ public static class ObjectInputStreamWithReadDesc extends
+ ObjectInputStream {
+ private Class returnClass;
+
+ public ObjectInputStreamWithReadDesc(InputStream is, Class returnClass)
+ throws IOException {
+ super(is);
+ this.returnClass = returnClass;
+ }
+
+ public ObjectStreamClass readClassDescriptor() throws IOException,
+ ClassNotFoundException {
+ return ObjectStreamClass.lookup(returnClass);
+
+ }
+ }
+
+ static class TestClassForSerialization implements Serializable {
+ private static final long serialVersionUID = 1L;
+ }
+
public void test_ConstructorLjava_io_InputStream() throws IOException {
oos.writeDouble(Double.MAX_VALUE);
oos.close();
@@ -207,9 +677,6 @@ public class ObjectInputStreamTest extends TestCase implements
}
- /**
- * java.io.ObjectInputStream#available()
- */
public void test_available() throws IOException {
oos.writeBytes("HelloWorld");
oos.close();
@@ -219,16 +686,6 @@ public class ObjectInputStreamTest extends TestCase implements
}
/**
- * java.io.ObjectInputStream#close()
- */
- public void test_close() throws IOException {
- oos.writeBytes("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.close();
- }
-
- /**
* java.io.ObjectInputStream#defaultReadObject()
*/
public void test_defaultReadObject() throws Exception {
@@ -356,34 +813,6 @@ public class ObjectInputStreamTest extends TestCase implements
}
/**
- * java.io.ObjectInputStream#readFully(byte[])
- */
- public void test_readFully$B() throws IOException {
- byte[] buf = new byte[10];
- oos.writeBytes("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf);
- ois.close();
- assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
- 10, "UTF-8"));
- }
-
- /**
- * java.io.ObjectInputStream#readFully(byte[], int, int)
- */
- public void test_readFully$BII() throws IOException {
- byte[] buf = new byte[10];
- oos.writeBytes("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf, 0, 10);
- ois.close();
- assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
- 10, "UTF-8"));
- }
-
- /**
* java.io.ObjectInputStream#readInt()
*/
public void test_readInt() throws IOException {
@@ -510,36 +939,6 @@ public class ObjectInputStreamTest extends TestCase implements
}
/**
- * java.io.ObjectInputStream#readObjectOverride()
- */
- public void test_readObjectOverride() throws Exception {
- // Regression for HARMONY-846
- assertNull(new ObjectInputStream() {
-
- @Override
- public Object readObjectOverride() throws IOException,
- ClassNotFoundException {
- return super.readObjectOverride();
- }
-
- }.readObjectOverride());
- }
-
- public static class A implements Serializable {
-
- private static final long serialVersionUID = 11L;
-
- public String name = "name";
- }
-
- public static class B extends A {}
-
- public static class C extends B {
-
- private static final long serialVersionUID = 33L;
- }
-
- /**
* java.io.ObjectInputStream#readObject()
*/
public void test_readObjectCorrupt() throws IOException, ClassNotFoundException {
@@ -568,30 +967,6 @@ public class ObjectInputStreamTest extends TestCase implements
}
/**
- * java.io.ObjectInputStream#readUnsignedByte()
- */
- public void test_readUnsignedByte() throws IOException {
- oos.writeByte(-1);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Read incorrect unsignedByte value", 255, ois
- .readUnsignedByte());
- ois.close();
- }
-
- /**
- * java.io.ObjectInputStream#readUnsignedShort()
- */
- public void test_readUnsignedShort() throws IOException {
- oos.writeShort(-1);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Read incorrect unsignedShort value", 65535, ois
- .readUnsignedShort());
- ois.close();
- }
-
- /**
* java.io.ObjectInputStream#readUTF()
*/
public void test_readUTF() throws IOException {
@@ -617,26 +992,27 @@ public class ObjectInputStreamTest extends TestCase implements
// Regression for HARMONY-844
try {
- new ObjectInputStream() {}.skipBytes(0);
+ new ObjectInputStream() {
+ }.skipBytes(0);
fail("NullPointerException expected");
- } catch (NullPointerException e) {}
+ } catch (NullPointerException e) {
+ }
}
// Regression Test for JIRA 2192
- public void test_readObject_withPrimitiveClass() throws Exception {
- File file = new File("test.ser");
- file.deleteOnExit();
- Test test = new Test();
- ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
- file));
- out.writeObject(test);
- out.close();
-
- ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
- Test another = (Test) in.readObject();
- in.close();
- assertEquals(test, another);
- }
+ public void test_readObject_withPrimitiveClass() throws Exception {
+ File file = File.createTempFile("ObjectInputStreamTest", ".ser");
+ Test test = new Test();
+ ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
+ file));
+ out.writeObject(test);
+ out.close();
+
+ ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
+ Test another = (Test) in.readObject();
+ in.close();
+ assertEquals(test, another);
+ }
//Regression Test for JIRA-2249
public static class ObjectOutputStreamWithWriteDesc extends
@@ -652,75 +1028,36 @@ public class ObjectInputStreamTest extends TestCase implements
}
}
- public static class ObjectIutputStreamWithReadDesc extends
+ // Regression Test for JIRA-2340
+ public static class ObjectOutputStreamWithWriteDesc1 extends
+ ObjectOutputStream {
+ public ObjectOutputStreamWithWriteDesc1(OutputStream os)
+ throws IOException {
+ super(os);
+ }
+
+ @Override
+ public void writeClassDescriptor(ObjectStreamClass desc)
+ throws IOException {
+ super.writeClassDescriptor(desc);
+ }
+ }
+
+ public static class ObjectInputStreamWithReadDesc1 extends
ObjectInputStream {
- private Class returnClass;
- public ObjectIutputStreamWithReadDesc(InputStream is, Class returnClass)
+ public ObjectInputStreamWithReadDesc1(InputStream is)
throws IOException {
super(is);
- this.returnClass = returnClass;
}
@Override
public ObjectStreamClass readClassDescriptor() throws IOException,
ClassNotFoundException {
- return ObjectStreamClass.lookup(returnClass);
-
+ return super.readClassDescriptor();
}
}
- static class TestClassForSerialization implements Serializable {
- private static final long serialVersionUID = 1L;
- }
-
- public void test_ClassDescriptor() throws IOException,
- ClassNotFoundException {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc(
- baos);
- oos.writeObject(String.class);
- oos.close();
- Class cls = TestClassForSerialization.class;
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- ObjectIutputStreamWithReadDesc ois = new ObjectIutputStreamWithReadDesc(
- bais, cls);
- Object obj = ois.readObject();
- ois.close();
- assertEquals(cls, obj);
- }
-
- // Regression Test for JIRA-2340
- public static class ObjectOutputStreamWithWriteDesc1 extends
- ObjectOutputStream {
- public ObjectOutputStreamWithWriteDesc1(OutputStream os)
- throws IOException {
- super(os);
- }
-
- @Override
- public void writeClassDescriptor(ObjectStreamClass desc)
- throws IOException {
- super.writeClassDescriptor(desc);
- }
- }
-
- public static class ObjectIutputStreamWithReadDesc1 extends
- ObjectInputStream {
-
- public ObjectIutputStreamWithReadDesc1(InputStream is)
- throws IOException {
- super(is);
- }
-
- @Override
- public ObjectStreamClass readClassDescriptor() throws IOException,
- ClassNotFoundException {
- return super.readClassDescriptor();
- }
- }
-
// Regression test for Harmony-1921
public static class ObjectInputStreamWithResolve extends ObjectInputStream {
public ObjectInputStreamWithResolve(InputStream in) throws IOException {
@@ -769,7 +1106,7 @@ public class ObjectInputStreamTest extends TestCase implements
@Override
protected Object resolveObject(Object obj) throws IOException {
- if(obj instanceof Integer){
+ if (obj instanceof Integer) {
obj = intObj;
}
return super.resolveObject(obj);
@@ -792,7 +1129,7 @@ public class ObjectInputStreamTest extends TestCase implements
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStreamWithResolveObject ois =
- new ObjectInputStreamWithResolveObject(bais);
+ new ObjectInputStreamWithResolveObject(bais);
Integer actual = (Integer) ois.readObject();
ois.close();
@@ -800,30 +1137,30 @@ public class ObjectInputStreamTest extends TestCase implements
assertEquals(ObjectInputStreamWithResolveObject.intObj, actual);
}
- public void test_readClassDescriptor() throws IOException,
- ClassNotFoundException {
+ public void test_readClassDescriptor() throws IOException,
+ ClassNotFoundException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithWriteDesc1 oos = new ObjectOutputStreamWithWriteDesc1(
- baos);
- ObjectStreamClass desc = ObjectStreamClass
- .lookup(TestClassForSerialization.class);
- oos.writeClassDescriptor(desc);
- oos.close();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStreamWithWriteDesc1 oos = new ObjectOutputStreamWithWriteDesc1(
+ baos);
+ ObjectStreamClass desc = ObjectStreamClass
+ .lookup(TestClassForSerialization.class);
+ oos.writeClassDescriptor(desc);
+ oos.close();
byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectIutputStreamWithReadDesc1 ois = new ObjectIutputStreamWithReadDesc1(
- bais);
- Object obj = ois.readClassDescriptor();
- ois.close();
- assertEquals(desc.getClass(), obj.getClass());
+ ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ ObjectInputStreamWithReadDesc1 ois = new ObjectInputStreamWithReadDesc1(
+ bais);
+ Object obj = ois.readClassDescriptor();
+ ois.close();
+ assertEquals(desc.getClass(), obj.getClass());
//eof
bais = new ByteArrayInputStream(bytes);
ExceptionalBufferedInputStream bis = new ExceptionalBufferedInputStream(
bais);
- ois = new ObjectIutputStreamWithReadDesc1(bis);
+ ois = new ObjectInputStreamWithReadDesc1(bis);
bis.setEOF(true);
@@ -838,7 +1175,7 @@ public class ObjectInputStreamTest extends TestCase implements
//throw exception
bais = new ByteArrayInputStream(bytes);
bis = new ExceptionalBufferedInputStream(bais);
- ois = new ObjectIutputStreamWithReadDesc1(bis);
+ ois = new ObjectInputStreamWithReadDesc1(bis);
bis.setException(new IOException());
@@ -853,7 +1190,7 @@ public class ObjectInputStreamTest extends TestCase implements
//corrupt
bais = new ByteArrayInputStream(bytes);
bis = new ExceptionalBufferedInputStream(bais);
- ois = new ObjectIutputStreamWithReadDesc1(bis);
+ ois = new ObjectInputStreamWithReadDesc1(bis);
bis.setCorrupt(true);
@@ -864,7 +1201,7 @@ public class ObjectInputStreamTest extends TestCase implements
} finally {
ois.close();
}
- }
+ }
static class ExceptionalBufferedInputStream extends BufferedInputStream {
private boolean eof = false;
@@ -1000,26 +1337,15 @@ public class ObjectInputStreamTest extends TestCase implements
//Regression Test for HARMONY-3726
public void test_readObject_array() throws Exception {
-
- final String resourcePrefix = ObjectInputStreamTest.class.getPackage().getName().replace('.', '/');
-
-// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_strings.ser"));
-// TestArray ta = new TestArray(new String[] { "AAA", "BBB" });
-// oos.writeObject(ta);
-// oos.close();
-// oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_integers.ser"));
-// ta = new TestArray(new Integer[] { 10, 20 });
-// oos.writeObject(ta);
-// oos.close();
-
+ final String resourcePrefix = "serialization/org/apache/harmony/luni/tests/java/io";
ObjectInputStream oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream(
- "serialization/" + resourcePrefix + "/test_array_strings.ser"));
- TestArray testArray = (TestArray) oin.readObject();
+ resourcePrefix + "/test_array_strings.ser"));
+ org.apache.harmony.luni.tests.java.io.TestArray testArray = (TestArray) oin.readObject();
String[] strings = new String[] { "AAA", "BBB" };
assertTrue(java.util.Arrays.equals(strings, testArray.array));
oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream(
- "serialization/" + resourcePrefix + "/test_array_integers.ser"));
+ resourcePrefix + "/test_array_integers.ser"));
testArray = (TestArray) oin.readObject();
Integer[] integers = new Integer[] { 10, 20 };
assertTrue(java.util.Arrays.equals(integers, testArray.array));
@@ -1046,7 +1372,8 @@ public class ObjectInputStreamTest extends TestCase implements
@Override
protected void writeClassDescriptor(ObjectStreamClass osc) throws IOException {
- objs[pos++] = osc; }
+ objs[pos++] = osc;
+ }
}
static class TestObjectInputStream extends ObjectInputStream {
@@ -1078,6 +1405,27 @@ public class ObjectInputStreamTest extends TestCase implements
oin.readObject();
}
+ public void test_readObject_replacedClassField() throws Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(out);
+ FieldReplacementTestClass obj = new FieldReplacementTestClass(1234);
+ oos.writeObject(obj);
+ out.flush();
+ out.close();
+
+ ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+ ObjectInputStream ois = new ObjectInputStream(in);
+
+ try {
+ FieldReplacementTestClass result =
+ (FieldReplacementTestClass) ois.readObject();
+ fail("should throw ClassCastException");
+ } catch (ClassCastException e) {
+ // expected
+ }
+ ois.close();
+ }
+
/**
* Sets up the fixture, for example, open a network connection. This method
* is called before a test is executed.
@@ -1087,10 +1435,40 @@ public class ObjectInputStreamTest extends TestCase implements
super.setUp();
oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
}
+
+ public static class FieldReplacementTestClass implements Serializable {
+ private FieldClass c;
+
+ public FieldReplacementTestClass(int i) {
+ super();
+ c = new FieldClass(i);
+ }
+ }
+
+ public static class FieldClass implements Serializable {
+ private int i;
+
+ public FieldClass(int i) {
+ super();
+ this.i = i;
+ }
+
+ protected Object writeReplace() throws ObjectStreamException {
+ return new ReplacementFieldClass(i);
+ }
+ }
+
+ public static class ReplacementFieldClass implements Serializable {
+ private int i;
+
+ public ReplacementFieldClass(int i) {
+ super();
+ this.i = i;
+ }
+ }
}
-class TestArray implements Serializable
-{
+class TestArray implements Serializable {
private static final long serialVersionUID = 1L;
public Object[] array;
@@ -1098,20 +1476,19 @@ class TestArray implements Serializable
public TestArray(Object[] array) {
this.array = array;
}
-
}
class Test implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- Class classes[] = new Class[] { byte.class, short.class, int.class,
- long.class, boolean.class, char.class, float.class, double.class };
+ Class<?> classes[] = new Class[] { byte.class, short.class, int.class,
+ long.class, boolean.class, char.class, float.class, double.class };
- @Override
+ @Override
public boolean equals(Object o) {
- if (!(o instanceof Test)) {
- return false;
- }
- return Arrays.equals(classes, ((Test) o).classes);
- }
+ if (!(o instanceof Test)) {
+ return false;
+ }
+ return Arrays.equals(classes, ((Test) o).classes);
+ }
}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java
deleted file mode 100644
index 74b2276..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java
+++ /dev/null
@@ -1,147 +0,0 @@
-package org.apache.harmony.luni.tests.java.net;
-
-import dalvik.annotation.SideEffect;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.net.ContentHandler;
-import java.net.ContentHandlerFactory;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-
-public class ContentHandlerFactoryTest extends TestCase {
-
- ContentHandlerFactory oldFactory = null;
- Field factoryField = null;
-
- boolean isTestable = false;
-
- boolean isGetContentCalled = false;
- boolean isCreateContentHandlerCalled = false;
-
- @SideEffect("This test affects tests that are run after this one." +
- " The reason are side effects due to caching in URLConnection." +
- " Maybe this test needs to be run in isolation.")
- public void test_createContentHandler() throws IOException {
-
- TestContentHandlerFactory factory = new TestContentHandlerFactory();
-
- if(isTestable) {
-
- assertFalse(isCreateContentHandlerCalled);
-
- URL url = new URL("http://" +
- Support_Configuration.SpecialInetTestAddress);
-
- URLConnection.setContentHandlerFactory(factory);
-
- URLConnection con = url.openConnection();
-
- try {
- con.getContent();
- assertTrue(isCreateContentHandlerCalled);
- assertTrue(isGetContentCalled);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- isGetContentCalled = false;
-
- try {
- con.getContent(new Class[] {});
- assertTrue(isGetContentCalled);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- try {
- con.setContentHandlerFactory(factory);
- fail("java.lang.Error was not thrown.");
- } catch(java.lang.Error e) {
- //expected
- }
-
- try {
- con.setContentHandlerFactory(null);
- fail("java.lang.Error was not thrown.");
- } catch(java.lang.Error e) {
- //expected
- }
-
- } else {
- ContentHandler ch = factory.createContentHandler("text/plain");
- URL url;
- try {
- url = new URL("http://" +
- Support_Configuration.SpecialInetTestAddress);
- assertNotNull(ch.getContent(url.openConnection()));
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown: " + e.getMessage());
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
- }
-
- public void setUp() {
- Field [] fields = URLConnection.class.getDeclaredFields();
- int counter = 0;
- for (Field field : fields) {
- if (ContentHandlerFactory.class.equals(field.getType())) {
- counter++;
- factoryField = field;
- }
- }
-
- if(counter == 1) {
-
- isTestable = true;
-
- factoryField.setAccessible(true);
- try {
- oldFactory = (ContentHandlerFactory) factoryField.get(null);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during setUp: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during setUp: "
- + e.getMessage());
- }
- }
- }
-
- public void tearDown() {
- if(isTestable) {
- try {
- factoryField.set(null, oldFactory);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during tearDown: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during tearDown: "
- + e.getMessage());
- }
- }
- }
-
- public class TestContentHandler extends ContentHandler {
-
- public Object getContent(URLConnection u) {
- isGetContentCalled = true;
- return null;
- }
- }
-
- public class TestContentHandlerFactory implements ContentHandlerFactory {
-
- public ContentHandler createContentHandler(String mimetype) {
- isCreateContentHandlerCalled = true;
- return new TestContentHandler();
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
index d1674f3..5307cf4 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
@@ -16,7 +16,6 @@
package org.apache.harmony.luni.tests.java.net;
-import dalvik.annotation.BrokenTest;
import junit.framework.TestCase;
import tests.support.Support_Configuration;
import tests.support.Support_TestWebData;
@@ -209,10 +208,14 @@ public class URLConnectionTest extends TestCase {
URL url2;
+ URL url3;
+
URLConnection uc;
URLConnection uc2;
+ URLConnection uc3;
+
Support_TestWebServer server;
@Override
@@ -225,6 +228,8 @@ public class URLConnectionTest extends TestCase {
uc = url.openConnection();
url2 = new URL("http://localhost:" + port + "/test2");
uc2 = url2.openConnection();
+ url3 = new URL("http://localhost:" + port + "/test3");
+ uc3 = url3.openConnection();
fileURL = createTempHelloWorldFile();
fileURLCon = fileURL.openConnection();
@@ -239,6 +244,7 @@ public class URLConnectionTest extends TestCase {
server.close();
((HttpURLConnection) uc).disconnect();
((HttpURLConnection) uc2).disconnect();
+ ((HttpURLConnection) uc3).disconnect();
}
/**
@@ -432,39 +438,6 @@ public class URLConnectionTest extends TestCase {
}
/**
- * @throws IOException
- * {@link java.net.URLConnection#getContentEncoding()}
- */
- @BrokenTest("Fails in CTS, passes in CoreTestRunner")
- public void test_getContentEncoding() throws IOException {
- // faulty setup
- try {
-
- fileURLCon.getContentEncoding();
- fail("Exception expected");
- } catch (Throwable e) {
- //ok
- }
-
- // positive case
-
- URL url = new URL("http://www.amazon.com/");
-
- URLConnection con = url.openConnection();
- con.setRequestProperty("Accept-Encoding", "gzip");
- con.connect();
-
- assertEquals(con.getContentEncoding(), "gzip");
-
-
- uc2.setRequestProperty("Accept-Encoding", "bla");
- uc2.connect();
-
- assertNull(uc2.getContentEncoding());
-
- }
-
- /**
* {@link java.net.URLConnection#getContentLength()}
*/
public void test_getContentLength() throws Exception {
@@ -472,8 +445,8 @@ public class URLConnectionTest extends TestCase {
assertEquals(Support_TestWebData.test1.length, uc.getContentLength());
assertEquals(Support_TestWebData.test2.length, uc2.getContentLength());
- assertNotNull(jarURLCon.getContentLength());
- assertNotNull(gifURLCon.getContentLength());
+ assertTrue(jarURLCon.getContentLength() > 0);
+ assertTrue(gifURLCon.getContentLength() > 0);
fileURLCon.getInputStream().close();
}
@@ -719,17 +692,17 @@ public class URLConnectionTest extends TestCase {
}
/**
- * @throws IOException
* {@link java.net.URLConnection#getHeaderFieldInt(String, int)}
*/
public void test_getHeaderFieldInt() throws IOException, ParseException {
- Support_TestWebData params = Support_TestWebData.testParams[1];
+ // Test getHeaderFieldInt() can read an int value.
+ Support_TestWebData params1 = Support_TestWebData.testParams[1];
+ int hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE);
+ assertEquals(params1.testLength, hf);
- int hf = 0;
+ // The remaining fields should be invalid or missing. Confirm the default is returned.
hf = uc2.getHeaderFieldInt("Content-Encoding", Integer.MIN_VALUE);
assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE);
- assertEquals(params.testLength, hf);
hf = uc2.getHeaderFieldInt("Content-Type", Integer.MIN_VALUE);
assertEquals(Integer.MIN_VALUE, hf);
hf = uc2.getHeaderFieldInt("Date", Integer.MIN_VALUE);
@@ -745,6 +718,10 @@ public class URLConnectionTest extends TestCase {
hf = uc2.getHeaderFieldInt("DoesNotExist", Integer.MIN_VALUE);
assertEquals(Integer.MIN_VALUE, hf);
+ // Test getHeaderFieldInt() for a value outside of the range of int.
+ Support_TestWebData params2 = Support_TestWebData.testParams[2];
+ hf = uc3.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE);
+ assertEquals(Integer.MIN_VALUE, hf);
}
/**
@@ -823,34 +800,6 @@ public class URLConnectionTest extends TestCase {
}
}
- /**
- * @throws IOException
- * {@link java.net.URLConnection#getLastModified()}
- */
- public void test_getLastModified() throws IOException {
-
- URL url4 = new URL(Support_Configuration.hTTPURLwLastModified);
- URLConnection uc4 = url4.openConnection();
-
- uc4.connect();
-
- if (uc4.getLastModified() == 0) {
- System.out
- .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run");
- return;
- }
-
- long millis = uc4.getHeaderFieldDate("Last-Modified", 0);
-
- assertEquals(
- "Returned wrong getLastModified value. Wanted: "
- + " got: " + uc4.getLastModified(),
- millis, uc4.getLastModified());
-
-
- ((HttpURLConnection) uc).disconnect();
- }
-
public void test_getOutputStream_failAfterDisconnect() throws IOException {
((HttpURLConnection) uc2).disconnect();
@@ -1253,7 +1202,7 @@ public class URLConnectionTest extends TestCase {
String cts = System.getProperty("java.io.tmpdir");
File tmpDir = new File(cts);
Support_Resources.copyFile(tmpDir, null, "Harmony.GIF");
- URL fUrl1 = new URL("file:/" + tmpDir.getPath()
+ URL fUrl1 = new URL("file://" + tmpDir.getPath()
+ "/Harmony.GIF");
URLConnection con1 = fUrl1.openConnection();
return con1;
diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java
index a158c83..6b93abe 100644
--- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java
+++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreTest.java
@@ -228,9 +228,6 @@ public class KeyStoreTest extends TestCase {
}
}
- /**
- * @test java.security.KeyStore.PasswordProtection.getPassword()
- */
public void testKeyStorePPGetPassword() {
// Regression for HARMONY-1539
// no exception expected
diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java
index bef27ba..f939730 100644
--- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java
+++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderServiceTest.java
@@ -124,13 +124,6 @@ public class ProviderServiceTest extends TestCase {
Object o = s.newInstance(null);
assertTrue("incorrect instance", o instanceof RandomImpl);
-
- try {
- o = s.newInstance(new Object());
- fail("No expected NoSuchAlgorithmException");
- } catch (NoSuchAlgorithmException e) {
- }
-
}
public void testGetAlgorithm() {
diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java
index 7886e3e..ad084e1 100644
--- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java
+++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/Signature2Test.java
@@ -68,7 +68,17 @@ public class Signature2Test extends junit.framework.TestCase {
* java.security.Signature#clone()
*/
public void test_clone() throws Exception {
+ // A Signature may be cloneable according to the API, in practice the implementation isn't
+ // once it has been initialized. Checking for runtime exceptions rather than useful
+ // behavior.
Signature s = Signature.getInstance("DSA");
+ Signature clone = (Signature) s.clone();
+ assertNotNull(clone);
+ assertEquals(s.getAlgorithm(), clone.getAlgorithm());
+ assertEquals(s.getProvider(), clone.getProvider());
+
+ KeyPair keyPair = getDsaKeys();
+ s.initSign(keyPair.getPrivate());
try {
s.clone();
fail();
diff --git a/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java b/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java
deleted file mode 100644
index 458c27f..0000000
--- a/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java
+++ /dev/null
@@ -1,145 +0,0 @@
-package tests.api.java.io;
-
-import java.io.ObjectInputStream;
-
-public class ComputeSerialVersionUIDTest extends junit.framework.TestCase {
-
-
- private String path = "/serialization/tests/api/java/io/";
-
- public void testComputeSUIDClass() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(getClass()
- .getResourceAsStream(path + "testComputeSUIDClass.ser"));
- SerializationTestClass.TestClassName1 o1 = (SerializationTestClass.TestClassName1) ois
- .readObject();
- SerializationTestClass.TestClassName2T_T$T o2 = (SerializationTestClass.TestClassName2T_T$T) ois
- .readObject();
- SerializationTestClass.TestClassModifierPublic o6 = (SerializationTestClass.TestClassModifierPublic) ois
- .readObject();
- SerializationTestClass.TestClassModifierAbstract o3 = (SerializationTestClass.TestClassModifierAbstract) ois
- .readObject();
- SerializationTestClass.TestClassModifierFinal o4 = (SerializationTestClass.TestClassModifierFinal) ois
- .readObject();
- SerializationTestClass.TestClassModifierInterface o5 = (SerializationTestClass.TestClassModifierInterface) ois
- .readObject();
- ois.close();
- }
-
- public void testComputeSUIDInterfaces() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(getClass()
- .getResourceAsStream(path + "testComputeSUIDInterfaces.ser"));
- SerializationTestClass.TestIntefaces o1 = (SerializationTestClass.TestIntefaces) ois
- .readObject();
- SerializationTestClass.TestIntefacesA o2 = (SerializationTestClass.TestIntefacesA) ois
- .readObject();
- SerializationTestClass.TestIntefacesAB o3 = (SerializationTestClass.TestIntefacesAB) ois
- .readObject();
- SerializationTestClass.TestIntefacesBA o4 = (SerializationTestClass.TestIntefacesBA) ois
- .readObject();
- SerializationTestClass.TestIntefacesC o5 = (SerializationTestClass.TestIntefacesC) ois
- .readObject();
- SerializationTestClass.TestIntefacesAC o6 = (SerializationTestClass.TestIntefacesAC) ois
- .readObject();
- SerializationTestClass.TestIntefacesCA o7 = (SerializationTestClass.TestIntefacesCA) ois
- .readObject();
- SerializationTestClass.TestIntefacesABC o8 = (SerializationTestClass.TestIntefacesABC) ois
- .readObject();
- SerializationTestClass.TestIntefacesACB o9 = (SerializationTestClass.TestIntefacesACB) ois
- .readObject();
- SerializationTestClass.TestIntefacesBAC o10 = (SerializationTestClass.TestIntefacesBAC) ois
- .readObject();
- SerializationTestClass.TestIntefacesBCA o11 = (SerializationTestClass.TestIntefacesBCA) ois
- .readObject();
- SerializationTestClass.TestIntefacesCAB o12 = (SerializationTestClass.TestIntefacesCAB) ois
- .readObject();
- SerializationTestClass.TestIntefacesCBA o13 = (SerializationTestClass.TestIntefacesCBA) ois
- .readObject();
- ois.close();
- }
-
- public void testComputeSUIDFields() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(getClass()
- .getResourceAsStream(path + "testComputeSUIDFields.ser"));
- SerializationTestClass.TestFieldsNone o1 = (SerializationTestClass.TestFieldsNone) ois
- .readObject();
- SerializationTestClass.TestFieldsOneFinal o2 = (SerializationTestClass.TestFieldsOneFinal) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoFinal o3 = (SerializationTestClass.TestFieldsTwoFinal) ois
- .readObject();
- SerializationTestClass.TestFieldsOnePrivate o4 = (SerializationTestClass.TestFieldsOnePrivate) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoPrivate o5 = (SerializationTestClass.TestFieldsTwoPrivate) ois
- .readObject();
- SerializationTestClass.TestFieldsOneProtected o6 = (SerializationTestClass.TestFieldsOneProtected) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoProtected o7 = (SerializationTestClass.TestFieldsTwoProtected) ois
- .readObject();
- SerializationTestClass.TestFieldsOnePublic o8 = (SerializationTestClass.TestFieldsOnePublic) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoPublic o9 = (SerializationTestClass.TestFieldsTwoPublic) ois
- .readObject();
- SerializationTestClass.TestFieldsOneStatic o10 = (SerializationTestClass.TestFieldsOneStatic) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoStatic o11 = (SerializationTestClass.TestFieldsTwoStatic) ois
- .readObject();
- SerializationTestClass.TestFieldsOneTransient o12 = (SerializationTestClass.TestFieldsOneTransient) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoTransient o13 = (SerializationTestClass.TestFieldsTwoTransient) ois
- .readObject();
- SerializationTestClass.TestFieldsOneVolatile o14 = (SerializationTestClass.TestFieldsOneVolatile) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoVolatile o15 = (SerializationTestClass.TestFieldsTwoVolatile) ois
- .readObject();
- SerializationTestClass.TestFieldSignatures o16 = (SerializationTestClass.TestFieldSignatures) ois
- .readObject();
- ois.close();
- }
-
- public void testComputeSUIDConstructors() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(getClass()
- .getResourceAsStream(path + "testComputeSUIDConstructors.ser"));
- SerializationTestClass.TestConstructorNone o1 = (SerializationTestClass.TestConstructorNone) ois
- .readObject();
- SerializationTestClass.TestConstructorOne o2 = (SerializationTestClass.TestConstructorOne) ois
- .readObject();
- SerializationTestClass.TestConstructorPrivate o3 = (SerializationTestClass.TestConstructorPrivate) ois
- .readObject();
- SerializationTestClass.TestConstructorProtected o4 = (SerializationTestClass.TestConstructorProtected) ois
- .readObject();
- SerializationTestClass.TestConstructorPublic o5 = (SerializationTestClass.TestConstructorPublic) ois
- .readObject();
- SerializationTestClass.TestConstructorSignature o6 = (SerializationTestClass.TestConstructorSignature) ois
- .readObject();
- SerializationTestClass.TestConstructorTwo o7 = (SerializationTestClass.TestConstructorTwo) ois
- .readObject();
- SerializationTestClass.TestConstructorTwoReverse o8 = (SerializationTestClass.TestConstructorTwoReverse) ois
- .readObject();
- ois.close();
- }
-
- public void testComputeSUIDMethods() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(getClass()
- .getResourceAsStream(path + "testComputeSUIDMethods.ser"));
- SerializationTestClass.TestMehodPrivate o1 = (SerializationTestClass.TestMehodPrivate) ois
- .readObject();
- SerializationTestClass.TestMethodAbstract o2 = (SerializationTestClass.TestMethodAbstract) ois
- .readObject();
- SerializationTestClass.TestMethodFinal o3 = (SerializationTestClass.TestMethodFinal) ois
- .readObject();
- SerializationTestClass.TestMethodNative o4 = (SerializationTestClass.TestMethodNative) ois
- .readObject();
- SerializationTestClass.TestMethodProtected o5 = (SerializationTestClass.TestMethodProtected) ois
- .readObject();
- SerializationTestClass.TestMethodPublic o6 = (SerializationTestClass.TestMethodPublic) ois
- .readObject();
- SerializationTestClass.TestMethodStatic o7 = (SerializationTestClass.TestMethodStatic) ois
- .readObject();
- SerializationTestClass.TestMethodSignature o9 = (SerializationTestClass.TestMethodSignature) ois
- .readObject();
- SerializationTestClass.TestMethodReturnSignature o10 = (SerializationTestClass.TestMethodReturnSignature) ois
- .readObject();
- SerializationTestClass.TestMethodSynchronized o8 = (SerializationTestClass.TestMethodSynchronized) ois
- .readObject();
- ois.close();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java b/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java
deleted file mode 100644
index 434d31c..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java
+++ /dev/null
@@ -1,687 +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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.OutputStream;
-import java.io.Serializable;
-import java.io.StreamCorruptedException;
-import java.util.Arrays;
-import java.util.Hashtable;
-import java.util.Vector;
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-import tests.support.Support_ASimpleInputStream;
-
-public class ObjectInputStreamTest extends junit.framework.TestCase implements
- Serializable {
-
- static final long serialVersionUID = 1L;
-
- ObjectInputStream ois;
-
- ObjectOutputStream oos;
-
- ByteArrayOutputStream bao;
-
- boolean readStreamHeaderCalled;
-
- private final String testString = "Lorem ipsum...";
-
- private final int testLength = testString.length();
-
- public void test_ConstructorLjava_io_InputStream_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- sis.throwExceptionOnNextUse = true;
- try {
- ois = new ObjectInputStream(sis);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- }
-
- public void test_ClassDescriptor() throws IOException,
- ClassNotFoundException {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc(
- baos);
- oos.writeObject(String.class);
- oos.close();
- Class<?> cls = TestClassForSerialization.class;
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- ObjectInputStreamWithReadDesc ois = new ObjectInputStreamWithReadDesc(
- bais, cls);
- Object obj = ois.readObject();
- ois.close();
- assertEquals(cls, obj);
- }
-
- public void test_available() throws IOException {
- // Test for method int java.io.ObjectInputStream.available()
- oos.writeBytes(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- assertEquals("Test 1: Incorrect number of bytes;", testLength, ois.available());
- ois.close();
- }
-
- public void test_available_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.available();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- public void test_close() throws Exception {
- // Test for method void java.io.ObjectInputStream.close()
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.close();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- public void test_enableResolveObjectB() throws IOException {
- // Start testing without a SecurityManager.
- BasicObjectInputStream bois = new BasicObjectInputStream();
- assertFalse("Test 1: Object resolving must be disabled by default.",
- bois.enableResolveObject(true));
-
- assertTrue("Test 2: enableResolveObject did not return the previous value.",
- bois.enableResolveObject(false));
- }
-
- public void test_read_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.read();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- public void test_read$BII() throws IOException {
- // Test for method int java.io.ObjectInputStream.read(byte [], int, int)
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read(buf, 0, testLength);
- ois.close();
- assertEquals("Read incorrect bytes", testString, new String(buf));
- }
-
- public void test_read$BII_Exception() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeObject(testString);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.read(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.read(buf, -1,1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.read(buf, testLength, 1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- ois.close();
-
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.read(buf, 0, testLength);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- public void test_readFully$B() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf);
- assertEquals("Test 1: Incorrect bytes read;",
- testString, new String(buf));
- ois.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read();
- try {
- ois.readFully(buf);
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
- }
-
- public void test_readFully$B_Exception() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readFully(buf);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- public void test_readFully$BII() throws IOException {
- // Test for method void java.io.ObjectInputStream.readFully(byte [],
- // int, int)
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf, 0, testLength);
- assertEquals("Read incorrect bytes", testString, new String(buf));
- ois.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read();
- try {
- ois.readFully(buf);
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
- }
-
- public void test_readFully$BII_Exception() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeObject(testString);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.readFully(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.readFully(buf, -1,1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.readFully(buf, testLength, 1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- ois.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readFully(buf, 0, 1);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- @SuppressWarnings("deprecation")
- public void test_readLine() throws IOException {
- String line;
- oos.writeBytes("Lorem\nipsum\rdolor sit amet...");
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- line = ois.readLine();
- assertTrue("Test 1: Incorrect line written or read: " + line,
- line.equals("Lorem"));
- line = ois.readLine();
- assertTrue("Test 2: Incorrect line written or read: " + line,
- line.equals("ipsum"));
- line = ois.readLine();
- assertTrue("Test 3: Incorrect line written or read: " + line,
- line.equals("dolor sit amet..."));
- ois.close();
- }
-
- public void test_readLine_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readLine();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- private void fillStreamHeader(byte[] buffer) {
- short magic = java.io.ObjectStreamConstants.STREAM_MAGIC;
- short version = java.io.ObjectStreamConstants.STREAM_VERSION;
-
- if (buffer.length < 4) {
- throw new IllegalArgumentException("The buffer's minimal length must be 4.");
- }
-
- // Initialize the buffer with the correct header for object streams
- buffer[0] = (byte) (magic >> 8);
- buffer[1] = (byte) magic;
- buffer[2] = (byte) (version >> 8);
- buffer[3] = (byte) (version);
- }
-
- public void test_readObjectOverride() throws Exception {
- byte[] buffer = new byte[4];
-
- // Initialize the buffer with the correct header for object streams
- fillStreamHeader(buffer);
-
- // Test 1: Check that readObjectOverride() returns null if there
- // is no input stream.
- BasicObjectInputStream bois = new BasicObjectInputStream();
- assertNull("Test 1:", bois.readObjectOverride());
-
- // Test 2: Check that readObjectOverride() throws an IOException
- // if there is an input stream.
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- try {
- bois.readObjectOverride();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {}
-
- bois.close();
- }
-
- public void test_readObjectMissingClasses() throws Exception {
- SerializationTest.verifySelf(new A1(), new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
- assertEquals(5, ((A1) deserialized).b1.i);
- }
- });
- }
-
- public void test_readObjectCorrupt() {
- byte[] bytes = { 00, 00, 00, 0x64, 0x43, 0x48, (byte) 0xFD, 0x71, 00,
- 00, 0x0B, (byte) 0xB8, 0x4D, 0x65 };
- ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
- boolean exception = false;
- try {
- ObjectInputStream in = new ObjectInputStream(bin);
- in.readObject();
- fail("Unexpected read of corrupted stream");
- } catch (StreamCorruptedException e) {
- exception = true;
- } catch (IOException e) {
- fail("Unexpected: " + e);
- } catch (ClassNotFoundException e) {
- fail("Unexpected: " + e);
- }
- assertTrue("Expected StreamCorruptedException", exception);
- }
-
- public void test_readStreamHeader() throws IOException {
- String testString = "Lorem ipsum";
- BasicObjectInputStream bois;
- short magic = java.io.ObjectStreamConstants.STREAM_MAGIC;
- short version = java.io.ObjectStreamConstants.STREAM_VERSION;
- byte[] buffer = new byte[20];
-
- // Initialize the buffer with the correct header for object streams
- fillStreamHeader(buffer);
- System.arraycopy(testString.getBytes(), 0, buffer, 4, testString.length());
-
- // Test 1: readStreamHeader should not throw a StreamCorruptedException.
- // It should get called by the ObjectInputStream constructor.
- try {
- readStreamHeaderCalled = false;
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- bois.close();
- } catch (StreamCorruptedException e) {
- fail("Test 1: Unexpected StreamCorruptedException.");
- }
- assertTrue("Test 1: readStreamHeader() has not been called.",
- readStreamHeaderCalled);
-
- // Test 2: Make the stream magic number invalid and check that
- // readStreamHeader() throws an exception.
- buffer[0] = (byte)magic;
- buffer[1] = (byte)(magic >> 8);
- try {
- readStreamHeaderCalled = false;
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- fail("Test 2: StreamCorruptedException expected.");
- bois.close();
- } catch (StreamCorruptedException e) {
- }
- assertTrue("Test 2: readStreamHeader() has not been called.",
- readStreamHeaderCalled);
-
- // Test 3: Make the stream version invalid and check that
- // readStreamHeader() throws an exception.
- buffer[0] = (byte)(magic >> 8);
- buffer[1] = (byte)magic;
- buffer[2] = (byte)(version);
- buffer[3] = (byte)(version >> 8);
- try {
- readStreamHeaderCalled = false;
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- fail("Test 3: StreamCorruptedException expected.");
- bois.close();
- } catch (StreamCorruptedException e) {
- }
- assertTrue("Test 3: readStreamHeader() has not been called.",
- readStreamHeaderCalled);
- }
-
- public void test_readUnsignedByte() throws IOException {
- oos.writeByte(-1);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Test 1: Incorrect unsigned byte written or read.",
- 255, ois.readUnsignedByte());
-
- try {
- ois.readUnsignedByte();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- ois.close();
- try {
- ois.readUnsignedByte();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- public void test_readUnsignedShort() throws IOException {
- // Test for method int java.io.ObjectInputStream.readUnsignedShort()
- oos.writeShort(-1);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Test 1: Incorrect unsigned short written or read.",
- 65535, ois.readUnsignedShort());
-
- try {
- ois.readUnsignedShort();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- ois.close();
- try {
- ois.readUnsignedShort();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- public void test_resolveProxyClass() throws IOException {
- BasicObjectInputStream bois;
- byte[] buffer = new byte[10];
-
- // Initialize the buffer with the header for object streams
- fillStreamHeader(buffer);
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
-
- // Test 1: Check that a NullPointerException is thrown
- // if null is passed to the method.
- try {
- bois.resolveProxyClass(null);
- fail("Test 1: NullPointerException expected.");
- }
- catch (NullPointerException npe) {
- }
- catch (ClassNotFoundException cnfe) {
- fail("Test 1: Unexpected ClassNotFoundException.");
- }
-
- // Test 2: Check that visible interfaces are found.
- try {
- String[] interfaces = { "java.io.Closeable",
- "java.lang.Cloneable" };
- bois.resolveProxyClass(interfaces);
- }
- catch (ClassNotFoundException cnfe) {
- fail("Test 2: Unexpected ClassNotFoundException.");
- }
-
- // Test 3: Check that a ClassNotFoundException is thrown if the
- // array of interfaces is not valid.
- try {
- String[] interfaces = { "java.io.Closeable",
- "java.io.Closeable" };
- bois.resolveProxyClass(interfaces);
- fail ("Test 3: ClassNotFoundException expected.");
- }
- catch (ClassNotFoundException cnfe) {
- }
-
- bois.close();
- }
-
- public void test_skipBytesI_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.skipBytes(5);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- public static class A implements Serializable {
-
- private static final long serialVersionUID = 11L;
-
- public String name = "name";
- }
-
- public static class B extends A {}
-
- public static class C extends B {
-
- private static final long serialVersionUID = 33L;
- }
-
- public static class A1 implements Serializable {
-
- static final long serialVersionUID = 5942584913446079661L;
-
- B1 b1 = new B1();
-
- B1 b2 = b1;
-
- Vector v = new Vector();
- }
-
- public static class B1 implements Serializable {
-
- int i = 5;
-
- Hashtable h = new Hashtable();
- }
-
- class BasicObjectInputStream extends ObjectInputStream {
- public BasicObjectInputStream() throws IOException, SecurityException {
- super();
- }
-
- public BasicObjectInputStream(InputStream input) throws IOException {
- super(input);
- }
-
- public boolean enableResolveObject(boolean enable)
- throws SecurityException {
- return super.enableResolveObject(enable);
- }
-
- public Object readObjectOverride() throws ClassNotFoundException, IOException {
- return super.readObjectOverride();
- }
-
- public void readStreamHeader() throws IOException {
- readStreamHeaderCalled = true;
- super.readStreamHeader();
- }
-
- public Class<?> resolveProxyClass(String[] interfaceNames)
- throws IOException, ClassNotFoundException {
- return super.resolveProxyClass(interfaceNames);
- }
- }
-
- //Regression Test for JIRA-2249
- public static class ObjectOutputStreamWithWriteDesc extends
- ObjectOutputStream {
- public ObjectOutputStreamWithWriteDesc(OutputStream os)
- throws IOException {
- super(os);
- }
-
- public void writeClassDescriptor(ObjectStreamClass desc)
- throws IOException {
- }
- }
-
- public static class ObjectInputStreamWithReadDesc extends
- ObjectInputStream {
- private Class returnClass;
-
- public ObjectInputStreamWithReadDesc(InputStream is, Class returnClass)
- throws IOException {
- super(is);
- this.returnClass = returnClass;
- }
-
- public ObjectStreamClass readClassDescriptor() throws IOException,
- ClassNotFoundException {
- return ObjectStreamClass.lookup(returnClass);
-
- }
- }
-
- static class TestClassForSerialization implements Serializable {
- private static final long serialVersionUID = 1L;
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- }
-}
-
-class Test implements Serializable {
- private static final long serialVersionUID = 1L;
-
- Class<?> classes[] = new Class[] { byte.class, short.class, int.class,
- long.class, boolean.class, char.class, float.class, double.class };
-
- public boolean equals(Object o) {
- if (!(o instanceof Test)) {
- return false;
- }
- return Arrays.equals(classes, ((Test) o).classes);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationTestClass.java b/luni/src/test/java/tests/api/java/io/SerializationTestClass.java
deleted file mode 100644
index 32c4d0b..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationTestClass.java
+++ /dev/null
@@ -1,335 +0,0 @@
-package tests.api.java.io;
-
-public class SerializationTestClass implements java.io.Serializable {
-
- // Test class names
- public class TestClassName1 implements java.io.Serializable {
- }
-
- public class TestClassName2T_T$T implements java.io.Serializable {
- }
-
- // Test Modifiers
- public class TestClassModifierPublic implements java.io.Serializable {
- }
-
- interface TestClassModifierInterfaceHelper extends java.io.Serializable {
- }
-
- public class TestClassModifierInterface implements
- TestClassModifierInterfaceHelper {
- }
-
- final class TestClassModifierFinal implements java.io.Serializable {
- }
-
- abstract class TestClassModifierAbstractHelper implements
- java.io.Serializable {
- }
-
- public class TestClassModifierAbstract extends
- TestClassModifierAbstractHelper {
- }
-
-
- // TODO Arrays always are abstract
-
- // TODO Non public interface has no abstract modifier
-
-
- // Test interfaces
- interface A extends java.io.Serializable {
- }
-
- interface B extends java.io.Serializable {
- }
-
- interface C extends A {
- }
-
- public class TestIntefaces implements java.io.Serializable {
- }
-
- public class TestIntefacesA implements A {
- }
-
- public class TestIntefacesAB implements A, B {
- }
-
- public class TestIntefacesBA implements B, A {
- }
-
- public class TestIntefacesC implements C {
- }
-
- public class TestIntefacesAC implements A, C {
- }
-
- public class TestIntefacesCA implements C, A {
- }
-
- public class TestIntefacesABC implements A, B, C {
- }
-
- public class TestIntefacesACB implements A, C, B {
- }
-
- public class TestIntefacesBAC implements B, A, C {
- }
-
- public class TestIntefacesBCA implements B, C, A {
- }
-
- public class TestIntefacesCAB implements C, A, B {
- }
-
- public class TestIntefacesCBA implements C, B, A {
- }
-
- /**
- * Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC |
- * Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT
- */
- // Test Fields
- public class TestFieldsNone implements java.io.Serializable {
- }
-
- public class TestFieldsOnePublic implements java.io.Serializable {
- public int one;
- }
-
- public class TestFieldsTwoPublic implements java.io.Serializable {
- public int one;
- public int two;
- }
-
- @SuppressWarnings("unused")
- public class TestFieldsOnePrivate implements java.io.Serializable {
- private int one;
- }
-
- @SuppressWarnings("unused")
- public class TestFieldsTwoPrivate implements java.io.Serializable {
- private int one;
- private int two;
- }
-
- public class TestFieldsOneProtected implements java.io.Serializable {
- protected int one;
- }
-
- public class TestFieldsTwoProtected implements java.io.Serializable {
- protected int one;
- protected int two;
- }
-
- public static class TestFieldsOneStatic implements java.io.Serializable {
- static int one;
- }
-
- public static class TestFieldsTwoStatic implements java.io.Serializable {
- static int one;
- static int two;
- }
-
- public class TestFieldsOneFinal implements java.io.Serializable {
- final int one = 0;
- }
-
- public class TestFieldsTwoFinal implements java.io.Serializable {
- final int one = 0;
- final int two = 0;
- }
-
- public class TestFieldsOneVolatile implements java.io.Serializable {
- volatile int one;
- }
-
- public class TestFieldsTwoVolatile implements java.io.Serializable {
- volatile int one;
- volatile int two;
- }
-
- public class TestFieldsOneTransient implements java.io.Serializable {
- transient int one;
- }
-
- public class TestFieldsTwoTransient implements java.io.Serializable {
- transient int one;
- transient int two;
- }
-
- public class TestFieldSignatures implements java.io.Serializable {
- Object l;
- int i;
- short s;
- long j;
- boolean z;
- char c;
- double d;
- float f;
- byte b;
- }
-
-
- // Test Constructors
- public class TestConstructorNone implements java.io.Serializable {
- }
-
- public class TestConstructorOne implements java.io.Serializable {
- public TestConstructorOne() {
- }
- }
-
- public class TestConstructorTwo implements java.io.Serializable {
- public TestConstructorTwo(byte b) {
- }
-
- public TestConstructorTwo(char c) {
- }
- }
-
- public class TestConstructorTwoReverse implements java.io.Serializable {
- public TestConstructorTwoReverse(char c) {
- }
-
- public TestConstructorTwoReverse(byte b) {
- }
- }
-
-
- // Test Constructor Modifiers
- public class TestConstructorPublic implements java.io.Serializable {
- public TestConstructorPublic() {
- }
- }
-
- public class TestConstructorPrivate implements java.io.Serializable {
- private TestConstructorPrivate() {
- }
-
- public TestConstructorPrivate(int i) {
- this();
- }
- }
-
- public class TestConstructorProtected implements java.io.Serializable {
- protected TestConstructorProtected() {
- }
- }
- // TODO constructor modifier strict?
- // TODO constructor modifier static?
- // TODO constructor modifier final?
- // TODO constructor modifier synchronized?
- // TODO constructor modifier native?
- // TODO constructor modifier abstract?
-
-
- // Test constructor signature
- public class TestConstructorSignature implements java.io.Serializable {
- public TestConstructorSignature(boolean z, byte b, char c, short s,
- int i, float f, double j, Object l) {
- }
- }
-
-
- // Test Method Modifiers
- public class TestMethodPublic implements java.io.Serializable {
- public void method() {
- }
- }
-
- @SuppressWarnings("unused")
- public class TestMehodPrivate implements java.io.Serializable {
- private void method() {
- }
- }
-
- public class TestMethodProtected implements java.io.Serializable {
- protected void method() {
- }
- }
-
- public class TestMethodStrict implements java.io.Serializable {
- strictfp void method() {
- }
- }
-
- public static class TestMethodStatic implements java.io.Serializable {
- static void method() {
- }
- }
-
- public class TestMethodFinal implements java.io.Serializable {
- final void method() {
- }
- }
-
- public class TestMethodSynchronized implements java.io.Serializable {
- synchronized void method() {
- }
- }
-
- public class TestMethodNative implements java.io.Serializable {
- native void method();
- }
-
- public abstract class TestMethodAbstractHelper implements
- java.io.Serializable {
- abstract void method();
- }
-
- public class TestMethodAbstract extends TestMethodAbstractHelper implements
- java.io.Serializable {
- @Override
- void method() {
- }
- }
-
-
- // Test method signature
- public class TestMethodSignature implements java.io.Serializable {
- public void method(boolean z, byte b, char c, short s, int i, float f,
- double j, Object l) {
- }
- }
-
-
- // Test method return signature
- public class TestMethodReturnSignature implements java.io.Serializable {
- public void methodV() {
- }
-
- public boolean methodZ() {
- return false;
- }
-
- public byte methodB() {
- return 0;
- }
-
- public char methodC() {
- return '0';
- }
-
- public short methodS() {
- return 0;
- }
-
- public int methodI() {
- return 0;
- }
-
- public float methodF() {
- return 0F;
- }
-
- public double methodD() {
- return 0D;
- }
-
- public Object methodL() {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/Process2Test.java b/luni/src/test/java/tests/api/java/lang/Process2Test.java
deleted file mode 100644
index 5d18d61..0000000
--- a/luni/src/test/java/tests/api/java/lang/Process2Test.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 tests.api.java.lang;
-
-import dalvik.annotation.AndroidOnly;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import tests.support.Support_Exec;
-import static tests.support.Support_Exec.javaProcessBuilder;
-
-public class Process2Test extends junit.framework.TestCase {
- /**
- * java.lang.Process#getInputStream(),
- * java.lang.Process#getErrorStream()
- * java.lang.Process#getOutputStream()
- * Tests if these methods return buffered streams.
- */
- @AndroidOnly("dalvikvm specific")
- public void test_streams()
- throws IOException, InterruptedException {
- Process p = javaProcessBuilder().start();
- assertNotNull(p.getInputStream());
- assertNotNull(p.getErrorStream());
- assertNotNull(p.getOutputStream());
- }
-
- public void test_getErrorStream() {
- String[] commands = {"ls"};
- Process process = null;
- try {
- process = Runtime.getRuntime().exec(commands, null, null);
- InputStream is = process.getErrorStream();
- StringBuffer msg = new StringBuffer("");
- while (true) {
- int c = is.read();
- if (c == -1)
- break;
- msg.append((char) c);
- }
- assertEquals("", msg.toString());
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- process.destroy();
- }
-
- String[] unknownCommands = {"mkdir", "-u", "test"};
- Process erProcess = null;
- try {
- erProcess = Runtime.getRuntime().exec(unknownCommands, null, null);
- InputStream is = erProcess.getErrorStream();
- StringBuffer msg = new StringBuffer("");
- while (true) {
- int c = is.read();
- if (c == -1)
- break;
- msg.append((char) c);
- }
- assertTrue("Error stream should not be empty",
- !"".equals(msg.toString()));
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- erProcess.destroy();
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java b/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java
deleted file mode 100644
index 99e1df3..0000000
--- a/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.java.lang;
-
-import dalvik.annotation.BrokenTest;
-
-import junit.framework.TestCase;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-
-public class ProcessManagerTest extends TestCase {
-
- Thread thread = null;
- Process process = null;
- boolean isThrown = false;
-
- public void testCat() throws IOException, InterruptedException {
- String[] commands = { "cat" };
- Process process = Runtime.getRuntime().exec(commands, null, null);
-
- OutputStream out = process.getOutputStream();
- String greeting = "Hello, World!";
- out.write(greeting.getBytes());
- out.write('\n');
- out.close();
-
- assertEquals(greeting, readLine(process));
- }
-
- @BrokenTest("Sporadic failures in CTS, but not in CoreTestRunner")
- public void testSleep() throws IOException {
- String[] commands = { "sleep", "1" };
- process = Runtime.getRuntime().exec(commands, null, null);
- try {
- assertEquals(0, process.waitFor());
-
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown.");
- }
-
- isThrown = false;
- thread = new Thread() {
- public void run() {
- String[] commands = { "sleep", "1000"};
- try {
- process = Runtime.getRuntime().exec(commands, null, null);
- } catch (IOException e1) {
- fail("IOException was thrown.");
- }
- try {
- process.waitFor();
- fail("InterruptedException was not thrown.");
- } catch(InterruptedException ie) {
- isThrown = true;
- }
- }
- };
-
- Thread interruptThread = new Thread() {
- public void run() {
- try {
- sleep(10);
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown in " +
- "the interruptThread.");
- }
- thread.interrupt();
- }
- };
- thread.start();
- interruptThread.start();
- try {
- interruptThread.join();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
-
- thread.interrupt();
- //process.destroy();
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
-
- assertTrue(isThrown);
- }
-
- public void testPwd() throws IOException, InterruptedException {
- String[] commands = { "sh", "-c", "pwd" };
- Process process = Runtime.getRuntime().exec(
- commands, null, new File("/"));
- logErrors(process);
- assertEquals("/", readLine(process));
- }
-
- public void testEnvironment() throws IOException, InterruptedException {
- String[] commands = { "sh", "-c", "echo $FOO" };
-
- // Remember to set the path so we can find sh.
- String[] environment = { "FOO=foo", "PATH=" + System.getenv("PATH") };
- Process process = Runtime.getRuntime().exec(
- commands, environment, null);
- logErrors(process);
- assertEquals("foo", readLine(process));
- }
-
- String readLine(Process process) throws IOException {
- InputStream in = process.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- return reader.readLine();
- }
-
- void logErrors(final Process process) throws IOException {
- Thread thread = new Thread() {
- public void run() {
- InputStream in = process.getErrorStream();
- BufferedReader reader
- = new BufferedReader(new InputStreamReader(in));
- String line;
- try {
- while ((line = reader.readLine()) != null) {
- System.err.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- };
- thread.setDaemon(true);
- thread.start();
- }
-
- public void testHeavyLoad() {
- int i;
- for (i = 0; i < 100; i++)
- stuff();
- }
-
- private static void stuff() {
- Runtime rt = Runtime.getRuntime();
- try {
- Process proc = rt.exec("ls");
- proc.waitFor();
- proc = null;
- } catch (Exception ex) {
- System.err.println("Failure: " + ex);
- throw new RuntimeException(ex);
- }
- rt.gc();
- rt = null;
- }
-
- InputStream in;
-
- public void testCloseNonStandardFds()
- throws IOException, InterruptedException {
- String[] commands = { "ls", "/proc/self/fd" };
-
- Process process = Runtime.getRuntime().exec(commands, null, null);
- int before = countLines(process);
-
- // Open a new fd.
- this.in = new FileInputStream("/proc/version");
-
- try {
- process = Runtime.getRuntime().exec(commands, null, null);
- int after = countLines(process);
-
- // Assert that the new fd wasn't open in the second run.
- assertEquals(before, after);
- } finally {
- this.in = null;
- }
- }
-
- /**
- * Counts lines of input from the given process. Equivalent to "wc -l".
- */
- private int countLines(Process process) throws IOException {
- logErrors(process);
- InputStream in = process.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- int count = 0;
- while (reader.readLine() != null) {
- count++;
- }
- return count;
- }
-
- public void testInvalidCommand()
- throws IOException, InterruptedException {
- try {
- String[] commands = { "doesnotexist" };
- Runtime.getRuntime().exec(commands, null, null);
- } catch (IOException e) { /* expected */ }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ProcessTest.java b/luni/src/test/java/tests/api/java/lang/ProcessTest.java
deleted file mode 100644
index 2a8e0bd..0000000
--- a/luni/src/test/java/tests/api/java/lang/ProcessTest.java
+++ /dev/null
@@ -1,135 +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 tests.api.java.lang;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-
-public class ProcessTest extends junit.framework.TestCase {
-
- public void test_55017() throws Exception {
- ArrayList<Process> children = new ArrayList<Process>();
- for (int i = 0; i < 256; ++i) {
- try {
- children.add(Runtime.getRuntime().exec(new String[] { "/system/bin/does-not-exist" }, null, null));
- System.gc();
- } catch (IOException expected) {
- }
- }
- assertEquals(0, children.size());
-
- boolean onDevice = new File("/system/bin").exists();
- String[] psCommand = onDevice ? new String[] { "ps" } : new String[] { "ps", "s" };
- Process ps = Runtime.getRuntime().exec(psCommand, null, null);
- int zombieCount = 0;
- for (String line : readAndCloseStream(ps.getInputStream()).split("\n")) {
- if (line.contains(" Z ") || line.contains(" Z+ ")) {
- ++zombieCount;
- }
- }
- assertEquals(0, zombieCount);
- }
-
- public void test_getOutputStream() throws Exception {
- String[] commands = { "cat", "-"};
- Process p = Runtime.getRuntime().exec(commands, null, null);
- OutputStream os = p.getOutputStream();
- // send data, and check if it is echoed back correctly
- String str1 = "Some data for testing communication between processes\n";
- String str2 = "More data that serves the same purpose.\n";
- String str3 = "Here is some more data.\n";
- os.write(str1.getBytes());
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- os.write(str2.getBytes());
- os.write(str3.getBytes());
- os.close();
-
- String received = readAndCloseStream(p.getInputStream());
- assertEquals(str1 + str2 + str3, received);
-
- String stderr = readAndCloseStream(p.getErrorStream());
- assertEquals("", stderr);
-
- p.waitFor();
- p.destroy();
- }
-
- public void test_getErrorStream() throws Exception {
- String[] commands = { "cat", "--no-such-option"};
- Process p = Runtime.getRuntime().exec(commands, null, null);
-
- p.getOutputStream().close();
-
- String received = readAndCloseStream(p.getInputStream());
- assertEquals("", received);
-
- String stderr = readAndCloseStream(p.getErrorStream());
- assertTrue(stderr, stderr.contains("unrecognized option") || stderr.contains("invalid option"));
-
- p.waitFor();
- p.destroy();
- }
-
- private String readAndCloseStream(InputStream is) throws IOException {
- StringBuffer result = new StringBuffer();
- while (true) {
- int c = is.read();
- if (c == -1) {
- break;
- }
- result.append((char) c);
- }
- is.close();
- return result.toString();
- }
-
- public void test_exitValue() throws Exception {
- String[] commands = { "ls" };
- Process process = Runtime.getRuntime().exec(commands, null, null);
- process.waitFor();
- assertEquals(0, process.exitValue());
-
- String[] commandsSleep = { "sleep", "3000" };
- process = Runtime.getRuntime().exec(commandsSleep, null, null);
- process.destroy();
- process.waitFor(); // destroy is asynchronous.
- assertTrue(process.exitValue() != 0);
-
- process = Runtime.getRuntime().exec(new String[] { "sleep", "3000" }, null, null);
- try {
- process.exitValue();
- fail();
- } catch(IllegalThreadStateException expected) {
- }
- }
-
- public void test_destroy() throws Exception {
- String[] commands = { "ls"};
- Process process = Runtime.getRuntime().exec(commands, null, null);
- process.destroy();
- process.destroy();
- process.destroy();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/StringTest.java b/luni/src/test/java/tests/api/java/lang/StringTest.java
deleted file mode 100644
index 1e9933d..0000000
--- a/luni/src/test/java/tests/api/java/lang/StringTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.java.lang;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for the class {@link String}.
- */
-public class StringTest extends TestCase {
- public void test_contains() {
- assertTrue("aabc".contains("abc"));
- assertTrue("abcd".contains("abc"));
- assertFalse("abcd".contains("cba"));
- }
- public void test_charAt() {
- assertTrue("abcd".charAt(0) == 'a');
- assertTrue("abcd".charAt(3) == 'd');
- }
- public void test_StartsWith() {
- assertTrue("abcd".startsWith("abc"));
- assertFalse("abcd".startsWith("aabc"));
- }
- public void test_EndsWith() {
- assertTrue("abcd".endsWith("bcd"));
- assertFalse("abcd".endsWith("bcde"));
- }
-
- public void test_CASE_INSENSITIVE_ORDER() {
- String s1 = "ABCDEFG";
- String s2 = "abcdefg";
-
- assertTrue(String.CASE_INSENSITIVE_ORDER.compare(s1, s2) == 0);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java
deleted file mode 100644
index 6470579..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java
+++ /dev/null
@@ -1,141 +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 tests.api.java.lang.ref;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import libcore.java.lang.ref.FinalizationTester;
-
-//TODO: write a test to verify that the referent's finalize() happens
-// before the PhantomReference is enqueued.
-
-public class PhantomReferenceTest extends junit.framework.TestCase {
- static Boolean bool;
- public boolean isCalled = false;
- protected void doneSuite() {
- bool = null;
- }
-
- /**
- * java.lang.ref.PhantomReference#get()
- */
- public void test_get() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(false);
- PhantomReference pr = new PhantomReference(bool, rq);
- assertNull("get() should return null.", pr.get());
- pr.enqueue();
- assertNull("get() should return null.", pr.get());
- pr.clear();
- assertNull("get() should return null.", pr.get());
- }
-
- /**
- * java.lang.Runtime#gc()
- */
- public void test_gcInteraction() {
- class TestPhantomReference<T> extends PhantomReference<T> {
- public TestPhantomReference(T referent,
- ReferenceQueue<? super T> q) {
- super(referent, q);
- }
- public boolean enqueue() {
- // Initiate another GC from inside enqueue() to
- // see if it causes any problems inside the VM.
- Runtime.getRuntime().gc();
- return super.enqueue();
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
- final PhantomReference[] tprs = new PhantomReference[4];
-
- class TestThread extends Thread {
- public void run() {
- // Create the object in a separate thread to ensure
- // it will be gc'ed.
- Object obj = new Object();
- tprs[0] = new TestPhantomReference(obj, rq);
- tprs[1] = new TestPhantomReference(obj, rq);
- tprs[2] = new TestPhantomReference(obj, rq);
- tprs[3] = new TestPhantomReference(obj, rq);
- }
- }
-
- try {
- Thread t = new TestThread();
- t.start();
- t.join();
-
- FinalizationTester.induceFinalization();
-
- assertNull("get() should return null.", tprs[0].get());
- assertNull("get() should return null.", tprs[1].get());
- assertNull("get() should return null.", tprs[2].get());
- assertNull("get() should return null.", tprs[3].get());
-
- for (int i = 0; i < 4; i++) {
- Reference r = rq.remove(100L);
- assertNotNull("Reference should have been enqueued.", r);
- }
-
- // These are to make sure that tprs and its elements don't get
- // optimized out.
- assertNull("get() should return null.", tprs[0].get());
- assertNull("get() should return null.", tprs[1].get());
- assertNull("get() should return null.", tprs[2].get());
- assertNull("get() should return null.", tprs[3].get());
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.ref.PhantomReference#PhantomReference(java.lang.Object,
- * java.lang.ref.ReferenceQueue)
- */
- public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(true);
- try {
- PhantomReference pr = new PhantomReference(bool, rq);
- // Allow the finalizer to run to potentially enqueue
- Thread.sleep(1000);
- assertTrue("Initialization failed.", !pr.isEnqueued());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // need a reference to bool so the jit does not optimize it away
- assertTrue("should always pass", bool.booleanValue());
-
- boolean exception = false;
- try {
- new PhantomReference(bool, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Should not throw NullPointerException", !exception);
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java b/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java
deleted file mode 100644
index cad61b3..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java
+++ /dev/null
@@ -1,253 +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 tests.api.java.lang.ref;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
-import libcore.java.lang.ref.FinalizationTester;
-
-public class ReferenceQueueTest extends junit.framework.TestCase {
- static Boolean b;
-
- static Integer integer;
- boolean isThrown = false;
-
- protected void doneSuite() {
- b = null;
- integer = null;
- }
-
- public class ChildThread implements Runnable {
- public ChildThread() {
- }
-
- public void run() {
- try {
- rq.wait(1000);
- } catch (Exception e) {
- }
- synchronized (rq) {
- // store in a static so it won't be gc'ed because the jit
- // optimized it out
- integer = new Integer(667);
- SoftReference sr = new SoftReference(integer, rq);
- sr.enqueue();
- rq.notify();
- }
- }
- }
-
- ReferenceQueue rq;
-
- /**
- * java.lang.ref.ReferenceQueue#poll()
- */
- public void test_poll() {
- // store in a static so it won't be gc'ed because the jit
- // optimized it out
- b = new Boolean(true);
- Object obj = new Object();
- String str = "Test";
-
- SoftReference sr = new SoftReference(b, rq);
- WeakReference wr = new WeakReference(obj, rq);
- PhantomReference pr = new PhantomReference(str, rq);
- assertNull(rq.poll());
- sr.enqueue();
- wr.enqueue();
- pr.enqueue();
-
- try {
- assertNull("Remove failed.", rq.poll().get());
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
-
- try {
- assertEquals("Remove failed.", obj, (rq.poll().get()));
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
-
- try {
- assertTrue("Remove failed.", ((Boolean) rq.poll().get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
- assertNull(rq.poll());
-
- sr.enqueue();
- wr.enqueue();
-
- FinalizationTester.induceFinalization();
-
- assertNull(rq.poll());
- }
-
- /**
- * java.lang.ref.ReferenceQueue#remove()
- */
- public void test_remove() {
- // store in a static so it won't be gc'ed because the jit
- // optimized it out
- b = new Boolean(true);
-
- SoftReference sr = new SoftReference(b, rq);
- sr.enqueue();
- try {
- assertTrue("Remove failed.", ((Boolean) rq.remove().get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
-
- assertNull(rq.poll());
-
- sr.enqueue();
-
- class RemoveThread extends Thread {
- public void run() {
- try {
- rq.remove();
- } catch(InterruptedException ie) {
- isThrown = true;
- }
- }
- }
- RemoveThread rt = new RemoveThread();
- rt.start();
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
- rt.interrupt();
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
- assertTrue(isThrown);
- assertNull(rq.poll());
- }
-
- /**
- * java.lang.ref.ReferenceQueue#remove(long)
- */
- public void test_removeJ() {
- try {
- assertNull("Queue should be empty. (poll)", rq.poll());
- assertNull("Queue should be empty. (remove(1))",
- rq.remove((long) 1));
- Thread ct = new Thread(new ChildThread());
- ct.start();
- Reference ret = rq.remove(0L);
- assertNotNull("Delayed remove failed.", ret);
- } catch (InterruptedException e) {
- fail("InterruptedExeException during test : " + e.getMessage());
- }
- catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- Object obj = new Object();
- WeakReference wr = new WeakReference(obj, rq);
- Boolean b = new Boolean(true);
- SoftReference sr = new SoftReference(b, rq);
- String str = "Test";
- PhantomReference pr = new PhantomReference(str, rq);
-
- pr.enqueue();
- wr.enqueue();
- sr.enqueue();
-
- try {
- Reference result = rq.remove(1L);
- assertTrue((Boolean)result.get());
- result = rq.remove(1L);
- assertEquals(obj, result.get());
- result = rq.remove(1L);
- assertNull(result.get());
- } catch (IllegalArgumentException e1) {
- fail("IllegalArgumentException was thrown.");
- } catch (InterruptedException e1) {
- fail("InterruptedException was thrown.");
- }
- rq = new ReferenceQueue();
- isThrown = false;
- assertNull(rq.poll());
-
- class RemoveThread extends Thread {
- public void run() {
- try {
- rq.remove(1000L);
- } catch(InterruptedException ie) {
- isThrown = true;
- }
- }
- }
- RemoveThread rt = new RemoveThread();
- rt.start();
- try {
- Thread.sleep(10);
- } catch(InterruptedException ie) {
-
- }
- rt.interrupt();
- try {
- Thread.sleep(10);
- } catch(InterruptedException ie) {
-
- }
- assertTrue(isThrown);
- assertNull(rq.poll());
-
- try {
- rq.remove(-1);
- fail("IllegalArgumentException expected.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (InterruptedException e) {
- fail("Unexpected InterruptedException.");
- }
- }
-
- /**
- * java.lang.ref.ReferenceQueue#ReferenceQueue()
- */
- public void test_Constructor() {
- ReferenceQueue rq = new ReferenceQueue();
- assertNull(rq.poll());
- try {
- rq.remove(100L);
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- }
-
- protected void setUp() {
- rq = new ReferenceQueue();
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java
deleted file mode 100644
index 7461b47..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java
+++ /dev/null
@@ -1,340 +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 tests.api.java.lang.ref;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
-import junit.framework.AssertionFailedError;
-import libcore.java.lang.ref.FinalizationTester;
-
-public class ReferenceTest extends junit.framework.TestCase {
- Object tmpA, tmpB, tmpC, obj;
-
- volatile Reference r;
-
- /*
- * For test_subclass().
- */
- static TestWeakReference twr;
- static AssertionFailedError error;
- static boolean testObjectFinalized;
- static class TestWeakReference<T> extends WeakReference<T> {
- public volatile boolean clearSeen = false;
- public volatile boolean enqueueSeen = false;
-
- public TestWeakReference(T referent) {
- super(referent);
- }
-
- public TestWeakReference(T referent, ReferenceQueue<? super T> q) {
- super(referent, q);
- }
-
- public void clear() {
- clearSeen = true;
- if (testObjectFinalized) {
- error = new AssertionFailedError("Clear should happen " +
- "before finalization.");
- throw error;
- }
- if (enqueueSeen) {
- error = new AssertionFailedError("Clear should happen " +
- "before enqueue.");
- throw error;
- }
- super.clear();
- }
-
- public boolean enqueue() {
- enqueueSeen = true;
- if (!clearSeen) {
- error = new AssertionFailedError("Clear should happen " +
- "before enqueue.");
- throw error;
- }
-
- /* Do this last; it may notify the main test thread,
- * and anything we'd do after it (e.g., setting clearSeen)
- * wouldn't be seen.
- */
- return super.enqueue();
- }
- }
-
- protected void doneSuite() {
- tmpA = tmpB = obj = null;
- }
-
- /**
- * java.lang.ref.Reference#clear()
- */
- public void test_clear() {
- tmpA = new Object();
- tmpB = new Object();
- tmpC = new Object();
- SoftReference sr = new SoftReference(tmpA, new ReferenceQueue());
- WeakReference wr = new WeakReference(tmpB, new ReferenceQueue());
- PhantomReference pr = new PhantomReference(tmpC, new ReferenceQueue());
- assertTrue("Start: Object not cleared.", (sr.get() != null)
- && (wr.get() != null));
- assertNull("Referent is not null.", pr.get());
- sr.clear();
- wr.clear();
- pr.clear();
- assertTrue("End: Object cleared.", (sr.get() == null)
- && (wr.get() == null));
- assertNull("Referent is not null.", pr.get());
- // Must reference tmpA and tmpB so the jit does not optimize them away
- assertTrue("should always pass", tmpA != sr.get() && tmpB != wr.get());
- }
-
- /**
- * java.lang.ref.Reference#enqueue()
- */
- public void test_enqueue() {
- ReferenceQueue rq = new ReferenceQueue();
- obj = new Object();
- Reference ref = new SoftReference(obj, rq);
- assertTrue("Enqueue failed.", (!ref.isEnqueued())
- && ((ref.enqueue()) && (ref.isEnqueued())));
- assertTrue("Not properly enqueued.", rq.poll().get() == obj);
- // This fails...
- assertTrue("Should remain enqueued.", !ref.isEnqueued());
- assertTrue("Can not enqueue twice.", (!ref.enqueue())
- && (rq.poll() == null));
-
- rq = new ReferenceQueue();
- obj = new Object();
-
- ref = new WeakReference(obj, rq);
- assertTrue("Enqueue failed2.", (!ref.isEnqueued())
- && ((ref.enqueue()) && (ref.isEnqueued())));
- assertTrue("Not properly enqueued2.", rq.poll().get() == obj);
- assertTrue("Should remain enqueued2.", !ref.isEnqueued()); // This
- // fails.
- assertTrue("Can not enqueue twice2.", (!ref.enqueue())
- && (rq.poll() == null));
-
- ref = new PhantomReference(obj, rq);
- assertTrue("Enqueue failed3.", (!ref.isEnqueued())
- && ((ref.enqueue()) && (ref.isEnqueued())));
- assertNull("Not properly enqueued3.", rq.poll().get());
- assertTrue("Should remain enqueued3.", !ref.isEnqueued()); // This
- // fails.
- assertTrue("Can not enqueue twice3.", (!ref.enqueue())
- && (rq.poll() == null));
- }
-
- public void test_get_WeakReference() throws Exception {
- // Test the general/overall functionality of Reference.
- ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
-
- r = newWeakReference(queue);
- FinalizationTester.induceFinalization();
- Reference ref = queue.remove();
- assertNotNull("Object not enqueued.", ref);
- assertSame("Unexpected ref1", ref, r);
- assertNull("Object could not be reclaimed1.", r.get());
-
- r = newWeakReference(queue);
- FinalizationTester.induceFinalization();
-
- // wait for the reference queue thread to enqueue the newly-finalized object
- Thread.yield();
- Thread.sleep(200);
-
- ref = queue.poll();
- assertNotNull("Object not enqueued.", ref);
- assertSame("Unexpected ref2", ref, r);
- assertNull("Object could not be reclaimed.", ref.get());
- assertNull("Object could not be reclaimed.", r.get());
- }
-
- /**
- * Makes sure that overridden versions of clear() and enqueue()
- * get called, and that clear/enqueue/finalize happen in the
- * right order for WeakReferences.
- *
- * java.lang.ref.Reference#clear()
- * java.lang.ref.Reference#enqueue()
- * java.lang.Object#finalize()
- */
- public void test_subclass() {
- error = null;
- testObjectFinalized = false;
- twr = null;
-
- class TestObject {
- public TestWeakReference testWeakReference = null;
-
- public void setTestWeakReference(TestWeakReference twr) {
- testWeakReference = twr;
- }
-
- protected void finalize() {
- testObjectFinalized = true;
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
-
- class TestThread extends Thread {
- public void run() {
- // Create the object in a separate thread to ensure it will be
- // gc'ed
- TestObject testObj = new TestObject();
- twr = new TestWeakReference(testObj, rq);
- testObj.setTestWeakReference(twr);
- testObj = null;
- }
- }
-
- Reference ref;
-
- try {
- Thread t = new TestThread();
- t.start();
- t.join();
- FinalizationTester.induceFinalization();
- ref = rq.remove(5000L); // Give up after five seconds.
-
- assertNotNull("Object not garbage collected.", ref);
- assertTrue("Unexpected reference.", ref == twr);
- assertNull("Object could not be reclaimed.", twr.get());
- //assertTrue("Overridden clear() should have been called.",
- // twr.clearSeen);
- //assertTrue("Overridden enqueue() should have been called.",
- // twr.enqueueSeen);
- assertTrue("finalize() should have been called.",
- testObjectFinalized);
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
-
- }
-
- /**
- * java.lang.ref.Reference#get()
- */
- public void test_get() {
- WeakReference ref = newWeakReference(null);
-
- FinalizationTester.induceFinalization();
- assertNull("get() doesn't return null after gc for WeakReference", ref.get());
-
- obj = new Object();
- ref = new WeakReference<Object>(obj, new ReferenceQueue<Object>());
- ref.clear();
- assertNull("get() doesn't return null after clear for WeakReference", ref.get());
- }
-
- /**
- * Helper method to prevent live-precise bugs from interfering with analysis
- * of what is reachable. Do not inline this method; otherwise tests may fail
- * on VMs that are not live-precise. http://b/4191345
- */
- private WeakReference<Object> newWeakReference(ReferenceQueue<Object> queue) {
- Object o = new Object();
- WeakReference<Object> ref = new WeakReference<Object>(o, queue);
- assertSame(o, ref.get());
- return ref;
- }
-
- /**
- * java.lang.ref.Reference#isEnqueued()
- */
- public void test_isEnqueued() {
- ReferenceQueue rq = new ReferenceQueue();
- obj = new Object();
- Reference ref = new SoftReference(obj, rq);
- assertTrue("Should start off not enqueued.", !ref.isEnqueued());
- ref.enqueue();
- assertTrue("Should now be enqueued.", ref.isEnqueued());
- ref.enqueue();
- assertTrue("Should still be enqueued.", ref.isEnqueued());
- rq.poll();
- // This fails ...
- assertTrue("Should now be not enqueued.", !ref.isEnqueued());
- }
-
- /* Contrives a situation where the only reference to a string
- * is a WeakReference from an object that is being finalized.
- * Checks to make sure that the referent of the WeakReference
- * is still pointing to a valid object.
- */
- public void test_finalizeReferenceInteraction() {
- error = null;
- testObjectFinalized = false;
-
- class TestObject {
- WeakReference<String> stringRef;
-
- public TestObject(String referent) {
- stringRef = new WeakReference<String>(referent);
- }
-
- protected void finalize() {
- try {
- /* If a VM bug has caused the referent to get
- * freed without the reference getting cleared,
- * looking it up, assigning it to a local and
- * doing a GC should cause some sort of exception.
- */
- String s = stringRef.get();
- System.gc();
- testObjectFinalized = true;
- } catch (Throwable t) {
- error = new AssertionFailedError("something threw '" + t +
- "' in finalize()");
- }
- }
- }
-
- class TestThread extends Thread {
- public void run() {
- // Create the object in a separate thread to ensure it will be
- // gc'ed
- TestObject testObj = new TestObject(new String("sup /b/"));
- }
- }
-
- try {
- Thread t = new TestThread();
- t.start();
- t.join();
- FinalizationTester.induceFinalization();
- Thread.sleep(1000);
- if (error != null) {
- throw error;
- }
- assertTrue("finalize() should have been called.",
- testObjectFinalized);
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
- }
-
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java
deleted file mode 100644
index 197d829..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java
+++ /dev/null
@@ -1,143 +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 tests.api.java.lang.ref;
-
-import dalvik.annotation.SideEffect;
-
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.util.Vector;
-import libcore.java.lang.ref.FinalizationTester;
-
-public class SoftReferenceTest extends junit.framework.TestCase {
- static Boolean bool;
- SoftReference r;
-
- protected void doneSuite() {
- bool = null;
- }
-
- /**
- * java.lang.ref.SoftReference#SoftReference(java.lang.Object,
- * java.lang.ref.ReferenceQueue)
- */
- public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(true);
- try {
- SoftReference sr = new SoftReference(bool, rq);
- assertTrue("Initialization failed.", ((Boolean) sr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- boolean exception = false;
- try {
- new SoftReference(bool, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Should not throw NullPointerException", !exception);
- }
-
- /**
- * java.lang.ref.SoftReference#SoftReference(java.lang.Object)
- */
- public void test_ConstructorLjava_lang_Object() {
- bool = new Boolean(true);
- try {
- SoftReference sr = new SoftReference(bool);
- assertTrue("Initialization failed.", ((Boolean) sr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.ref.SoftReference#get()
- */
- public void test_get() {
- bool = new Boolean(false);
- SoftReference sr = new SoftReference(bool);
- assertTrue("Same object not returned.", bool == sr.get());
- }
-
- @SideEffect("Causes OutOfMemoryError to test finalization")
- public void test_get_SoftReference() {
-
- class TestObject {
- public boolean finalized;
- public TestObject() {
- finalized = false;
- }
-
- protected void finalize() {
- finalized = true;
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
-
- class TestThread extends Thread {
- public void run() {
- Object testObj = new TestObject();
- r = new SoftReference(testObj, rq);
- }
- }
- Reference ref;
- try {
- TestThread t = new TestThread();
- t.start();
- t.join();
- Vector<StringBuffer> v = new Vector<StringBuffer>();
- try {
- while(true) {
- v.add(new StringBuffer(10000));
- }
- } catch(OutOfMemoryError ofme) {
- v = null;
- }
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
-
- assertNull("get() should return null " +
- "if OutOfMemoryError is thrown.", r.get());
-
- try {
- TestThread t = new TestThread();
- t.start();
- t.join();
- FinalizationTester.induceFinalization();
- ref = rq.poll();
- assertNotNull("Object not garbage collected.", ref);
- assertNull("Object is not null.", ref.get());
- assertNotNull("Object could not be reclaimed.", r.get());
- } catch (Exception e) {
- fail("Exception : " + e.getMessage());
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java
deleted file mode 100644
index 2bddc1b..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.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 tests.api.java.lang.ref;
-
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-
-public class WeakReferenceTest extends junit.framework.TestCase {
- static Boolean bool;
-
- protected void doneSuite() {
- bool = null;
- }
-
- /**
- * java.lang.ref.WeakReference#WeakReference(java.lang.Object,
- * java.lang.ref.ReferenceQueue)
- */
- public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(true);
- try {
- // Allow the finalizer to run to potentially enqueue
- WeakReference wr = new WeakReference(bool, rq);
- assertTrue("Initialization failed.", ((Boolean) wr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // need a reference to bool so the jit does not optimize it away
- assertTrue("should always pass", bool.booleanValue());
-
- boolean exception = false;
- try {
- new WeakReference(bool, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Should not throw NullPointerException", !exception);
- }
-
- /**
- * java.lang.ref.WeakReference#WeakReference(java.lang.Object)
- */
- public void test_ConstructorLjava_lang_Object() {
- bool = new Boolean(true);
- try {
- WeakReference wr = new WeakReference(bool);
- // Allow the finalizer to run to potentially enqueue
- Thread.sleep(1000);
- assertTrue("Initialization failed.", ((Boolean) wr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // need a reference to bool so the jit does not optimize it away
- assertTrue("should always pass", bool.booleanValue());
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java b/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java
deleted file mode 100644
index 41c9798..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java
+++ /dev/null
@@ -1,215 +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 tests.api.java.lang.reflect;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.AccessibleObject;
-import java.lang.reflect.Modifier;
-import java.util.HashSet;
-import java.util.Set;
-
-public class AccessibleObjectTest extends junit.framework.TestCase {
-
- public class TestClass {
- public Object aField;
-
- @InheritedRuntime
- public void annotatedMethod(){}
- }
-
- public class SubTestClass extends TestClass{
- @AnnotationRuntime0
- @AnnotationRuntime1
- @AnnotationClass0
- @AnnotationSource0
- public void annotatedMethod(){}
- }
-
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.METHOD})
- static @interface AnnotationRuntime0 {
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( { ElementType.METHOD})
- static @interface AnnotationRuntime1 {
- }
-
- @Retention(RetentionPolicy.CLASS)
- @Target( { ElementType.METHOD})
- static @interface AnnotationClass0 {
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @Target( {ElementType.METHOD})
- static @interface AnnotationSource0 {
- }
-
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.METHOD})
- static @interface InheritedRuntime {
- }
-
- //used for constructor test
- private static class MyAccessibleObject extends AccessibleObject{
- public MyAccessibleObject() {
- super();
- }
- }
-
- /**
- * java.lang.reflect.AccessibleObject#AccessibleObject()
- */
- public void test_Constructor() {
- assertNotNull(new MyAccessibleObject());
- }
-
- /**
- * java.lang.reflect.AccessibleObject#isAccessible()
- */
- public void test_isAccessible() {
- // Test for method boolean
- // java.lang.reflect.AccessibleObject.isAccessible()
- try {
- AccessibleObject ao = TestClass.class.getField("aField");
- ao.setAccessible(true);
- assertTrue("Returned false to isAccessible", ao.isAccessible());
- ao.setAccessible(false);
- assertTrue("Returned true to isAccessible", !ao.isAccessible());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[],
- * boolean)
- */
- public void test_setAccessible$Ljava_lang_reflect_AccessibleObjectZ() {
- try {
- AccessibleObject ao = TestClass.class.getField("aField");
- AccessibleObject[] aoa = new AccessibleObject[] { ao };
- AccessibleObject.setAccessible(aoa, true);
- assertTrue("Returned false to isAccessible", ao.isAccessible());
- AccessibleObject.setAccessible(aoa, false);
- assertTrue("Returned true to isAccessible", !ao.isAccessible());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.AccessibleObject#setAccessible(boolean)
- */
- public void test_setAccessible() throws Exception {
- AccessibleObject ao = TestClass.class.getField("aField");
- ao.setAccessible(true);
- assertTrue("Returned false to isAccessible", ao.isAccessible());
- ao.setAccessible(false);
- assertFalse("Returned true to isAccessible", ao.isAccessible());
- }
-
- public void test_getAnnotation() throws Exception{
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- //test error case
- boolean npeThrown = false;
- try {
- ao.getAnnotation(null);
- fail("NPE expected");
- } catch (NullPointerException e) {
- npeThrown = true;
- }
- assertTrue("NPE expected", npeThrown);
-
- //test inherited on method has no effect
- InheritedRuntime ir = ao.getAnnotation(InheritedRuntime.class);
- assertNull("Inherited Annotations should have no effect", ir);
-
- //test ordinary runtime annotation
- AnnotationRuntime0 rt0 = ao.getAnnotation(AnnotationRuntime0.class);
- assertNotNull("AnnotationRuntime0 instance expected", rt0);
- }
-
- public void test_getAnnotations() throws Exception {
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- Annotation[] annotations = ao.getAnnotations();
- assertEquals(2, annotations.length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing @AnnotationRuntime0",
- ignoreOrder.contains(AnnotationRuntime0.class));
- assertTrue("Missing @AnnotationRuntime1",
- ignoreOrder.contains(AnnotationRuntime1.class));
- }
-
- public void test_getDeclaredAnnotations() throws Exception {
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- Annotation[] annotations = ao.getDeclaredAnnotations();
- assertEquals(2, annotations.length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing @AnnotationRuntime0",
- ignoreOrder.contains(AnnotationRuntime0.class));
- assertTrue("Missing @AnnotationRuntime1",
- ignoreOrder.contains(AnnotationRuntime1.class));
- }
-
- public void test_isAnnotationPresent() throws Exception {
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- assertTrue("Missing @AnnotationRuntime0",
- ao.isAnnotationPresent(AnnotationRuntime0.class));
- assertFalse("AnnotationSource0 should not be visible at runtime",
- ao.isAnnotationPresent(AnnotationSource0.class));
- boolean npeThrown = false;
- try {
- ao.isAnnotationPresent(null);
- fail("NPE expected");
- } catch (NullPointerException e) {
- npeThrown = true;
- }
- assertTrue("NPE expected", npeThrown);
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java
deleted file mode 100644
index d9e05fb..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java
+++ /dev/null
@@ -1,1001 +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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.Array;
-
-public class ArrayTest extends junit.framework.TestCase {
-
- /**
- * java.lang.reflect.Array#get(java.lang.Object, int)
- */
- public void test_getLjava_lang_ObjectI() {
- // Test for method java.lang.Object
- // java.lang.reflect.Array.get(java.lang.Object, int)
-
- int[] x = { 1 };
- Object ret = null;
- boolean thrown = false;
- try {
- ret = Array.get(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value",
- 1, ((Integer) ret).intValue());
- try {
- ret = Array.get(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.get(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- //same test with non primitive component type
- Integer[] y = new Integer[]{ 1 };
- ret = null;
- thrown = false;
- try {
- ret = Array.get(y, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value",
- 1, ((Integer) ret).intValue());
- try {
- ret = Array.get(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.get(y, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- }
-
- /**
- * java.lang.reflect.Array#getBoolean(java.lang.Object, int)
- */
- public void test_getBooleanLjava_lang_ObjectI() {
- // Test for method boolean
- // java.lang.reflect.Array.getBoolean(java.lang.Object, int)
- boolean[] x = { true };
- boolean ret = false;
- boolean thrown = false;
- try {
- ret = Array.getBoolean(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertTrue("Get returned incorrect value", ret);
- try {
- ret = Array.getBoolean(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getBoolean(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getBoolean(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getByte(java.lang.Object, int)
- */
- public void test_getByteLjava_lang_ObjectI() {
- // Test for method byte
- // java.lang.reflect.Array.getByte(java.lang.Object, int)
- byte[] x = { 1 };
- byte ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getByte(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getByte(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getByte(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getByte(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getChar(java.lang.Object, int)
- */
- public void test_getCharLjava_lang_ObjectI() {
- // Test for method char
- // java.lang.reflect.Array.getChar(java.lang.Object, int)
- char[] x = { 1 };
- char ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getChar(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getChar(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getChar(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getChar(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getDouble(java.lang.Object, int)
- */
- public void test_getDoubleLjava_lang_ObjectI() {
- // Test for method double
- // java.lang.reflect.Array.getDouble(java.lang.Object, int)
- double[] x = { 1 };
- double ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getDouble(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret, 0.0);
- try {
- ret = Array.getDouble(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
-
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getDouble(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getDouble(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getFloat(java.lang.Object, int)
- */
- public void test_getFloatLjava_lang_ObjectI() {
- // Test for method float
- // java.lang.reflect.Array.getFloat(java.lang.Object, int)
- float[] x = { 1 };
- float ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getFloat(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret, 0.0);
- try {
- ret = Array.getFloat(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getFloat(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getFloat(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getInt(java.lang.Object, int)
- */
- public void test_getIntLjava_lang_ObjectI() {
- // Test for method int java.lang.reflect.Array.getInt(java.lang.Object,
- // int)
- int[] x = { 1 };
- int ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getInt(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getInt(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getInt(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getInt(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getLength(java.lang.Object)
- */
- public void test_getLengthLjava_lang_Object() {
- // Test for method int
- // java.lang.reflect.Array.getLength(java.lang.Object)
- long[] x = { 1 };
-
- assertEquals("Returned incorrect length", 1, Array.getLength(x));
- assertEquals("Returned incorrect length", 10000, Array
- .getLength(new Object[10000]));
- try {
- Array.getLength(new Object());
- } catch (IllegalArgumentException e) {
- // Correct
- return;
- }
- fail("Failed to throw exception when passed non-array");
- }
-
- /**
- * java.lang.reflect.Array#getLong(java.lang.Object, int)
- */
- public void test_getLongLjava_lang_ObjectI() {
- // Test for method long
- // java.lang.reflect.Array.getLong(java.lang.Object, int)
- long[] x = { 1 };
- long ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getLong(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getLong(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getLong(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getLong(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#getShort(java.lang.Object, int)
- */
- public void test_getShortLjava_lang_ObjectI() {
- // Test for method short
- // java.lang.reflect.Array.getShort(java.lang.Object, int)
- short[] x = { 1 };
- short ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getShort(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getShort(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getShort(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getShort(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#newInstance(java.lang.Class, int[])
- */
- public void test_newInstanceLjava_lang_Class$I() {
- // Test for method java.lang.Object
- // java.lang.reflect.Array.newInstance(java.lang.Class, int [])
- int[][] x;
- int[] y = { 2 };
-
- x = (int[][]) Array.newInstance(int[].class, y);
- assertEquals("Failed to instantiate array properly", 2, x.length);
-
- boolean thrown = false;
- try {
- x = (int[][]) Array.newInstance(null, y);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
-
- thrown = false;
- try {
- Array.newInstance(int[].class, new int[]{1,-1});
- } catch (NegativeArraySizeException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Negative array size failed to throw NegativeArraySizeException");
- }
-
- thrown = false;
- try {
- Array.newInstance(int[].class, new int[]{});
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Zero array size failed to throw IllegalArgumentException");
- }
- }
-
- /**
- * java.lang.reflect.Array#newInstance(java.lang.Class, int)
- */
- public void test_newInstanceLjava_lang_ClassI() {
- // Test for method java.lang.Object
- // java.lang.reflect.Array.newInstance(java.lang.Class, int)
- int[] x;
-
- x = (int[]) Array.newInstance(int.class, 100);
- assertEquals("Failed to instantiate array properly", 100, x.length);
-
- boolean thrown = false;
- try {
- Array.newInstance(null, 100);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
-
- thrown = false;
- try {
- Array.newInstance(int[].class, -1);
- } catch (NegativeArraySizeException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Negative array size failed to throw NegativeArraySizeException");
- }
- }
-
- /**
- * java.lang.reflect.Array#set(java.lang.Object, int,
- * java.lang.Object)
- */
- public void test_setLjava_lang_ObjectILjava_lang_Object() {
- // Test for method void java.lang.reflect.Array.set(java.lang.Object,
- // int, java.lang.Object)
- int[] x = { 0 };
- boolean thrown = false;
- try {
- Array.set(x, 0, new Integer(1));
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ((Integer) Array.get(x, 0))
- .intValue());
- try {
- Array.set(new Object(), 0, new Object());
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.set(x, 4, new Integer(1));
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- // trying to put null in a primitive array causes
- // a IllegalArgumentException in 5.0
- boolean exception = false;
- try {
- Array.set(new int[1], 0, null);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue("expected exception not thrown", exception);
-
- thrown = false;
- try {
- Array.set(null, 0, 2);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setBoolean(java.lang.Object, int, boolean)
- */
- public void test_setBooleanLjava_lang_ObjectIZ() {
- // Test for method void
- // java.lang.reflect.Array.setBoolean(java.lang.Object, int, boolean)
- boolean[] x = { false };
- boolean thrown = false;
- try {
- Array.setBoolean(x, 0, true);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertTrue("Failed to set correct value", Array.getBoolean(x, 0));
- try {
- Array.setBoolean(new Object(), 0, false);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown){
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setBoolean(x, 4, false);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setBoolean(null, 0, true);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setByte(java.lang.Object, int, byte)
- */
- public void test_setByteLjava_lang_ObjectIB() {
- // Test for method void
- // java.lang.reflect.Array.setByte(java.lang.Object, int, byte)
- byte[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setByte(x, 0, (byte) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getByte(x, 0));
- try {
- Array.setByte(new Object(), 0, (byte) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setByte(x, 4, (byte) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setByte(null, 0, (byte)0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setChar(java.lang.Object, int, char)
- */
- public void test_setCharLjava_lang_ObjectIC() {
- // Test for method void
- // java.lang.reflect.Array.setChar(java.lang.Object, int, char)
- char[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setChar(x, 0, (char) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getChar(x, 0));
- try {
- Array.setChar(new Object(), 0, (char) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setChar(x, 4, (char) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setChar(null, 0, (char)0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setDouble(java.lang.Object, int, double)
- */
- public void test_setDoubleLjava_lang_ObjectID() {
- // Test for method void
- // java.lang.reflect.Array.setDouble(java.lang.Object, int, double)
- double[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setDouble(x, 0, 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getDouble(x, 0), 0.0);
- try {
- Array.setDouble(new Object(), 0, 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setDouble(x, 4, 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setDouble(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setFloat(java.lang.Object, int, float)
- */
- public void test_setFloatLjava_lang_ObjectIF() {
- // Test for method void
- // java.lang.reflect.Array.setFloat(java.lang.Object, int, float)
- float[] x = { 0.0f };
- boolean thrown = false;
- try {
- Array.setFloat(x, 0, (float) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getFloat(x, 0), 0.0);
- try {
- Array.setFloat(new Object(), 0, (float) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setFloat(x, 4, (float) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setFloat(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setInt(java.lang.Object, int, int)
- */
- public void test_setIntLjava_lang_ObjectII() {
- // Test for method void java.lang.reflect.Array.setInt(java.lang.Object,
- // int, int)
- int[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setInt(x, 0, (int) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getInt(x, 0));
- try {
- Array.setInt(new Object(), 0, (int) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setInt(x, 4, (int) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setInt(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setLong(java.lang.Object, int, long)
- */
- public void test_setLongLjava_lang_ObjectIJ() {
- // Test for method void
- // java.lang.reflect.Array.setLong(java.lang.Object, int, long)
- long[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setLong(x, 0, 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getLong(x, 0));
- try {
- Array.setLong(new Object(), 0, 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setLong(x, 4, 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setLong(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * java.lang.reflect.Array#setShort(java.lang.Object, int, short)
- */
- public void test_setShortLjava_lang_ObjectIS() {
- // Test for method void
- // java.lang.reflect.Array.setShort(java.lang.Object, int, short)
- short[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setShort(x, 0, (short) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getShort(x, 0));
- try {
- Array.setShort(new Object(), 0, (short) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setShort(x, 4, (short) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setShort(null, 0, (short)0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java b/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java
deleted file mode 100644
index 7949a30..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java
+++ /dev/null
@@ -1,128 +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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Tests bounded type parameters declared on methods.
- */
-public class BoundedGenericMethodsTests extends GenericReflectionTestsBase {
- @SuppressWarnings("unchecked")
- static class BoundedGenericMethods<S> {
-
- public <T extends BoundedGenericMethods> void noParamNoReturn() {}
- public <T extends BoundedGenericMethods> void paramNoReturn(T param) {}
-
- public <T extends BoundedGenericMethods> T noParamReturn() {
- return (T) new Object();
- }
- public <T extends BoundedGenericMethods> T paramReturn(T t) {
- return t;
- }
- }
- @SuppressWarnings("unchecked")
- private static Class<? extends BoundedGenericMethods> clazz = BoundedGenericMethodsTests.BoundedGenericMethods.class;
-
- /**
- * Tests whether the type parameter is upper bounded by BoundedGenericMethods.
- * <T extends BoundedGenericMethods>.
- *
- * @param method
- * the declaring method
- */
- private void checkBoundedTypeParameter(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertEquals("T", typeParameter.getName());
- assertEquals(method, typeParameter.getGenericDeclaration());
-
- Type[] bounds = typeParameter.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
- assertEquals(BoundedGenericMethods.class, bound);
- }
-
- /**
- * Tests whether the specified method declares a parameter with the type of
- * the type parameter.
- *
- * @param method
- * the declaring method
- */
- private void parameterType(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertLenghtOne(method.getGenericParameterTypes());
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertEquals(typeParameter, genericParameterType);
- assertTrue(genericParameterType instanceof TypeVariable);
- TypeVariable<?> typeVariable = (TypeVariable<?>) genericParameterType;
- assertEquals(method, typeVariable.getGenericDeclaration());
-
- Type[] paramBounds = typeVariable.getBounds();
- assertLenghtOne(paramBounds);
- Type paramBound = paramBounds[0];
- assertEquals(BoundedGenericMethods.class, paramBound);
- }
-
- @SuppressWarnings("unchecked")
- private void checkReturnType(Method method) {
- Type genericReturnType = method.getGenericReturnType();
- assertEquals(getTypeParameter(method), genericReturnType);
- assertTrue(genericReturnType instanceof TypeVariable);
-
- TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
- assertEquals(method, returnTypeVariable.getGenericDeclaration());
-
- Type[] bounds = returnTypeVariable.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
-
- assertEquals(BoundedGenericMethods.class, bound);
- }
-
-
-
- /**
- * Tests that there are is one Type Parameter on the Class itself.
- */
- public void testBoundedGenericMethods() {
- assertLenghtOne(clazz.getTypeParameters());
- }
- public void testNoParamNoReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("noParamNoReturn");
- checkBoundedTypeParameter(method);
- }
- public void testUnboundedParamNoReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("paramNoReturn", BoundedGenericMethods.class);
- checkBoundedTypeParameter(method);
- parameterType(method);
- }
- public void testNoParamReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("noParamReturn");
- checkBoundedTypeParameter(method);
- assertLenghtZero(method.getGenericParameterTypes());
- checkReturnType(method);
- }
- public void testUnboundedParamReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("paramReturn", BoundedGenericMethods.class);
- checkBoundedTypeParameter(method);
- parameterType(method);
- checkReturnType(method);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
deleted file mode 100644
index 932315c..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
+++ /dev/null
@@ -1,443 +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 tests.api.java.lang.reflect;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-public class ConstructorTest extends junit.framework.TestCase {
-
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationRuntime0 {
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationRuntime1 {
- }
-
- @Retention(RetentionPolicy.CLASS)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationClass0 {
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationSource0 {
- }
-
- static class ConstructorTestHelper extends Object {
- int cval;
-
- @ConstructorTestAnnotationRuntime0
- @ConstructorTestAnnotationRuntime1
- @ConstructorTestAnnotationClass0
- @ConstructorTestAnnotationSource0
- public ConstructorTestHelper() throws IndexOutOfBoundsException {
- cval = 99;
- }
-
- public ConstructorTestHelper(
- @ConstructorTestAnnotationRuntime0
- @ConstructorTestAnnotationRuntime1
- @ConstructorTestAnnotationClass0
- @ConstructorTestAnnotationSource0 Object x) {
- }
-
- public ConstructorTestHelper(String... x) {
- }
-
- private ConstructorTestHelper(int a) {
- }
-
- protected ConstructorTestHelper(long a) {
- }
-
- public int check() {
- return cval;
- }
- }
-
- static class GenericConstructorTestHelper<T, S extends T, E extends Exception> {
- public GenericConstructorTestHelper(T t, S s) {}
- public GenericConstructorTestHelper() throws E{}
- }
-
- static class NoPublicConstructorTestHelper {
- // This class has no public constructor.
- }
-
-// Used to test synthetic constructor.
-//
-// static class Outer {
-// private Outer(){}
-// class Inner {
-// {new Outer();}
-// }
-// }
-
- public void test_getParameterAnnotations() throws Exception {
- Constructor<ConstructorTestHelper> ctor1 = ConstructorTestHelper.class
- .getConstructor(Object.class);
- Annotation[][] paramAnnotations = ctor1.getParameterAnnotations();
- assertEquals("Annotations for wrong number of parameters returned", 1,
- paramAnnotations.length);
- assertEquals("Wrong number of annotations returned", 2,
- paramAnnotations[0].length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(paramAnnotations[0][0].annotationType());
- ignoreOrder.add(paramAnnotations[0][1].annotationType());
-
- assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime0.class));
- assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime1.class));
- }
-
-
- public void test_getDeclaredAnnotations() throws Exception {
- Constructor<ConstructorTestHelper> ctor1 = null;
- ctor1 = ConstructorTestHelper.class.getConstructor(new Class[0]);
- Annotation[] annotations = ctor1.getDeclaredAnnotations();
- assertEquals("Wrong number of annotations returned", 2,
- annotations.length);
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime0.class));
- assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime1.class));
- }
-
- public void test_isVarArgs() throws Exception {
- Constructor<ConstructorTestHelper> varArgCtor = ConstructorTestHelper.class
- .getConstructor(String[].class);
- assertTrue("Vararg constructor not recognized", varArgCtor.isVarArgs());
-
- Constructor<ConstructorTestHelper> nonVarArgCtor = ConstructorTestHelper.class
- .getConstructor(Object.class);
- assertFalse("Non vararg constructor recognized as vararg constructor",
- nonVarArgCtor.isVarArgs());
- }
-
- public void test_hashCode() throws Exception {
- Constructor<ConstructorTestHelper> constructor = ConstructorTestHelper.class
- .getConstructor();
- assertEquals(
- "The constructor's hashCode is not equal to the hashCode of the name of the declaring class",
- ConstructorTestHelper.class.getName().hashCode(), constructor
- .hashCode());
- }
-
- @SuppressWarnings("unchecked")
- public void test_toGenericString() throws Exception {
- Constructor<GenericConstructorTestHelper> genericCtor = GenericConstructorTestHelper.class
- .getConstructor(Object.class, Object.class);
- assertEquals(
- "Wrong generic string returned",
- "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper(T,S)",
- genericCtor.toGenericString());
- Constructor<GenericConstructorTestHelper> ctor = GenericConstructorTestHelper.class
- .getConstructor();
- assertEquals(
- "Wrong generic string returned",
- "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper() throws E",
- ctor.toGenericString());
- }
-
- public void test_equalsLjava_lang_Object() {
- Constructor<ConstructorTestHelper> ctor1 = null, ctor2 = null;
- try {
- ctor1 = ConstructorTestHelper.class.getConstructor(
- new Class[0]);
- ctor2 = ConstructorTestHelper.class.getConstructor(Object.class);
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- assertTrue("Different Contructors returned equal", !ctor1.equals(ctor2));
- }
-
- public void test_getDeclaringClass() {
- boolean val = false;
- try {
- Class<? extends ConstructorTestHelper> pclass = new ConstructorTestHelper().getClass();
- Constructor<? extends ConstructorTestHelper> ctor = pclass.getConstructor(new Class[0]);
- val = ctor.getDeclaringClass().equals(pclass);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- assertTrue("Returned incorrect declaring class", val);
- }
-
- public void test_getExceptionTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Constructor.getExceptionTypes()
- Class[] exceptions = null;
- Class<? extends IndexOutOfBoundsException> ex = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- exceptions = ctor.getExceptionTypes();
- ex = new IndexOutOfBoundsException().getClass();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- assertEquals("Returned exception list of incorrect length",
- 1, exceptions.length);
- assertTrue("Returned incorrect exception", exceptions[0].equals(ex));
- }
-
- public void test_getModifiers() {
- // Test for method int java.lang.reflect.Constructor.getModifiers()
- int mod = 0;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- mod = ctor.getModifiers();
- assertTrue("Returned incorrect modifers for public ctor",
- ((mod & Modifier.PUBLIC) == Modifier.PUBLIC)
- && ((mod & Modifier.PRIVATE) == 0));
- } catch (NoSuchMethodException e) {
- fail("Exception during test : " + e.getMessage());
- }
- try {
- Class[] cl = { int.class };
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getDeclaredConstructor(cl);
- mod = ctor.getModifiers();
- assertTrue("Returned incorrect modifers for private ctor",
- ((mod & Modifier.PRIVATE) == Modifier.PRIVATE)
- && ((mod & Modifier.PUBLIC) == 0));
- } catch (NoSuchMethodException e) {
- fail("Exception during test : " + e.getMessage());
- }
- try {
- Class[] cl = { long.class };
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getDeclaredConstructor(cl);
- mod = ctor.getModifiers();
- assertTrue("Returned incorrect modifers for private ctor",
- ((mod & Modifier.PROTECTED) == Modifier.PROTECTED)
- && ((mod & Modifier.PUBLIC) == 0));
- } catch (NoSuchMethodException e) {
- fail("NoSuchMethodException during test : " + e.getMessage());
- }
- }
-
- public void test_getName() {
- // Test for method java.lang.String
- // java.lang.reflect.Constructor.getName()
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- assertTrue(
- "Returned incorrect name: " + ctor.getName(),
- ctor
- .getName()
- .equals(
- "tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper"));
- } catch (Exception e) {
- fail("Exception obtaining contructor : " + e.getMessage());
- }
- }
-
- public void test_getParameterTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Constructor.getParameterTypes()
- Class[] types = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- types = ctor.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:"
- + e.toString());
- }
- assertEquals("Incorrect parameter returned", 0, types.length);
-
- Class[] parms = null;
- try {
- parms = new Class[1];
- parms[0] = new Object().getClass();
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(parms);
- types = ctor.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:"
- + e.toString());
- }
- assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
- }
-
- @SuppressWarnings("unchecked")
- public void test_getGenericParameterTypes() {
- Type[] types = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
- .getClass().getConstructor(new Class[0]);
- types = ctor.getGenericParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:" + e.toString());
- }
- assertEquals("Incorrect parameter returned", 0, types.length);
-
- Class<?>[] parms = null;
- try {
- parms = new Class[] {Object.class};
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
- .getClass().getConstructor(parms);
- types = ctor.getGenericParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:" + e.toString());
- }
- assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
-
-
- try {
- Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
- .getConstructor(Object.class, Object.class);
- types = constructor.getGenericParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:" + e.toString());
- }
-
- assertEquals("Wrong number of parameter types returned", 2,
- types.length);
-
- assertEquals("Wrong number of parameter types returned", "T",
- ((TypeVariable)types[0]).getName());
- assertEquals("Wrong number of parameter types returned", "S",
- ((TypeVariable)types[1]).getName());
- }
-
- @SuppressWarnings("unchecked")
- public void test_getGenericExceptionTypes() {
- Type[] types = null;
-
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
- .getClass().getConstructor(new Class[0]);
- types = ctor.getGenericExceptionTypes();
- } catch (Exception e) {
- fail("Exception during getGenericExceptionTypes test:" + e.toString());
- }
- assertEquals("Wrong number of exception types returned", 1, types.length);
-
-
- try {
- Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
- .getConstructor();
- types = constructor.getGenericExceptionTypes();
- } catch (Exception e) {
- fail("Exception during getGenericExceptionTypes test:"
- + e.toString());
- }
-
- assertEquals("Wrong number of exception types returned", 1,
- types.length);
-
- assertEquals("Wrong exception name returned.", "E",
- ((TypeVariable)types[0]).getName());
-
- }
-
-
- public void test_newInstance$Ljava_lang_Object() {
- // Test for method java.lang.Object
- // java.lang.reflect.Constructor.newInstance(java.lang.Object [])
-
- ConstructorTestHelper test = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- test = ctor.newInstance((Object[])null);
- } catch (Exception e) {
- fail("Failed to create instance : " + e.getMessage());
- }
- assertEquals("improper instance created", 99, test.check());
- }
-
- public void test_toString() {
- // Test for method java.lang.String
- // java.lang.reflect.Constructor.toString()
- Class[] parms = null;
- Constructor<? extends ConstructorTestHelper> ctor = null;
- try {
- parms = new Class[1];
- parms[0] = new Object().getClass();
- ctor = new ConstructorTestHelper().getClass().getConstructor(parms);
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:"
- + e.toString());
- }
- assertTrue(
- "Returned incorrect string representation: " + ctor.toString(),
- ctor
- .toString()
- .equals(
- "public tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper(java.lang.Object)"));
- }
-
- public void test_getConstructor() throws Exception {
- // Passing new Class[0] should be equivalent to (Class[]) null.
- Class<ConstructorTestHelper> c2 = ConstructorTestHelper.class;
- assertEquals(c2.getConstructor(new Class[0]), c2.getConstructor((Class[]) null));
- assertEquals(c2.getDeclaredConstructor(new Class[0]),
- c2.getDeclaredConstructor((Class[]) null));
-
- // We can get a non-public constructor via getDeclaredConstructor...
- Class<NoPublicConstructorTestHelper> c1 = NoPublicConstructorTestHelper.class;
- c1.getDeclaredConstructor((Class[]) null);
- // ...but not with getConstructor (which only returns public constructors).
- try {
- c1.getConstructor((Class[]) null);
- fail("Should throw NoSuchMethodException");
- } catch (NoSuchMethodException ex) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java b/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java
deleted file mode 100644
index a1ca151..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java
+++ /dev/null
@@ -1,1868 +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 tests.api.java.lang.reflect;
-
-import tests.support.Support_Field;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.HashSet;
-import java.util.Set;
-
-public class FieldTest extends junit.framework.TestCase {
-
- // BEGIN android-note
- // This test had a couple of bugs in it. Some parts of the code were
- // unreachable before. Also some tests expected the wrong excpetions
- // to be thrown. This version has been validated to pass on a standard
- // JDK 1.5.
- // END android-note
-
- public class TestClass {
- @AnnotationRuntime0
- @AnnotationRuntime1
- @AnnotationClass0
- @AnnotationSource0
- public int annotatedField;
- class Inner{}
- }
-
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.FIELD})
- static @interface AnnotationRuntime0 {
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( { ElementType.FIELD})
- static @interface AnnotationRuntime1 {
- }
-
- @Retention(RetentionPolicy.CLASS)
- @Target( { ElementType.FIELD})
- static @interface AnnotationClass0 {
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @Target( {ElementType.FIELD})
- static @interface AnnotationSource0 {
- }
-
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.FIELD})
- static @interface InheritedRuntime {
- }
-
- public class GenericField<S, T extends Number> {
- S field;
- T boundedField;
- int intField;
- }
-
-
- static class TestField {
- public static int pubfield1;
-
- private static int privfield1 = 123;
-
- protected int intField = Integer.MAX_VALUE;
- protected final int intFField = Integer.MAX_VALUE;
- protected static int intSField = Integer.MAX_VALUE;
- private final int intPFField = Integer.MAX_VALUE;
-
- protected short shortField = Short.MAX_VALUE;
- protected final short shortFField = Short.MAX_VALUE;
- protected static short shortSField = Short.MAX_VALUE;
- private final short shortPFField = Short.MAX_VALUE;
-
- protected boolean booleanField = true;
- protected static boolean booleanSField = true;
- protected final boolean booleanFField = true;
- private final boolean booleanPFField = true;
-
- protected byte byteField = Byte.MAX_VALUE;
- protected static byte byteSField = Byte.MAX_VALUE;
- protected final byte byteFField = Byte.MAX_VALUE;
- private final byte bytePFField = Byte.MAX_VALUE;
-
- protected long longField = Long.MAX_VALUE;
- protected final long longFField = Long.MAX_VALUE;
- protected static long longSField = Long.MAX_VALUE;
- private final long longPFField = Long.MAX_VALUE;
-
- protected double doubleField = Double.MAX_VALUE;
- protected static double doubleSField = Double.MAX_VALUE;
- protected static final double doubleSFField = Double.MAX_VALUE;
- protected final double doubleFField = Double.MAX_VALUE;
- private final double doublePFField = Double.MAX_VALUE;
-
- protected float floatField = Float.MAX_VALUE;
- protected final float floatFField = Float.MAX_VALUE;
- protected static float floatSField = Float.MAX_VALUE;
- private final float floatPFField = Float.MAX_VALUE;
-
- protected char charField = 'T';
- protected static char charSField = 'T';
- private final char charPFField = 'T';
-
- protected final char charFField = 'T';
-
- private static final int x = 1;
-
- public volatile transient int y = 0;
-
- protected static transient volatile int prsttrvol = 99;
- }
-
- public class TestFieldSub1 extends TestField {
- }
-
- public class TestFieldSub2 extends TestField {
- }
-
- static class A {
- protected short shortField = Short.MAX_VALUE;
- }
-
- static enum TestEnum {
- A, B, C;
- int field;
- }
-
- /**
- * java.lang.reflect.Field#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.lang.reflect.Field.equals(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("shortField");
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- try {
- assertTrue("Same Field returned false", f.equals(f));
- assertTrue("Inherited Field returned false", f.equals(x.getClass()
- .getDeclaredField("shortField")));
- assertTrue("Identical Field from different class returned true", !f
- .equals(A.class.getDeclaredField("shortField")));
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#get(java.lang.Object)
- */
- public void test_getLjava_lang_Object() throws Throwable {
- // Test for method java.lang.Object
- // java.lang.reflect.Field.get(java.lang.Object)
- TestField x = new TestField();
- Field f = x.getClass().getDeclaredField("doubleField");
- Double val = (Double) f.get(x);
-
- assertTrue("Returned incorrect double field value",
- val.doubleValue() == Double.MAX_VALUE);
- // Test getting a static field;
- f = x.getClass().getDeclaredField("doubleSField");
- f.set(x, new Double(1.0));
- val = (Double) f.get(x);
- assertEquals("Returned incorrect double field value", 1.0, val
- .doubleValue());
-
- // Try a get on a private field
- boolean thrown = false;
- try {
- f = TestAccess.class.getDeclaredField("xxx");
- assertNotNull(f);
- f.get(null);
- fail("No expected IllegalAccessException");
- } catch (IllegalAccessException ok) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Try a get on a private field in nested member
- // temporarily commented because it breaks J9 VM
- // Regression for HARMONY-1309
- //f = x.getClass().getDeclaredField("privfield1");
- //assertEquals(x.privfield1, f.get(x));
-
- // Try a get using an invalid class.
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.get(new String());
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException exc) {
- // Correct - Passed an Object that does not declare or inherit f
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = TestField.class.getDeclaredField("intField");
- f.get(null);
- fail("Expected NullPointerException not thrown");
- } catch (NullPointerException exc) {
- // Correct - Passed an Object that does not declare or inherit f
- thrown = true;
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static fields
- thrown = false;
- try {
- f = TestField.class.getDeclaredField("doubleSField");
- f.get(null);
- assertTrue("Exception thrown", true);
- } catch (Exception exc) {
- fail("No exception expected");
- }
- }
-
- class SupportSubClass extends Support_Field {
-
- Object getField(char primitiveType, Object o, Field f,
- Class expectedException) {
- Object res = null;
- try {
- primitiveType = Character.toUpperCase(primitiveType);
- switch (primitiveType) {
- case 'I': // int
- res = new Integer(f.getInt(o));
- break;
- case 'J': // long
- res = new Long(f.getLong(o));
- break;
- case 'Z': // boolean
- res = new Boolean(f.getBoolean(o));
- break;
- case 'S': // short
- res = new Short(f.getShort(o));
- break;
- case 'B': // byte
- res = new Byte(f.getByte(o));
- break;
- case 'C': // char
- res = new Character(f.getChar(o));
- break;
- case 'D': // double
- res = new Double(f.getDouble(o));
- break;
- case 'F': // float
- res = new Float(f.getFloat(o));
- break;
- default:
- res = f.get(o);
- }
- if (expectedException != null) {
- fail("expected exception " + expectedException.getName());
- }
- } catch (Exception e) {
- if (expectedException == null) {
- fail("unexpected exception " + e);
- } else {
- assertTrue("expected exception "
- + expectedException.getName() + " and got " + e, e
- .getClass().equals(expectedException));
- }
- }
- return res;
- }
-
- void setField(char primitiveType, Object o, Field f,
- Class expectedException, Object value) {
- try {
- primitiveType = Character.toUpperCase(primitiveType);
- switch (primitiveType) {
- case 'I': // int
- f.setInt(o, ((Integer) value).intValue());
- break;
- case 'J': // long
- f.setLong(o, ((Long) value).longValue());
- break;
- case 'Z': // boolean
- f.setBoolean(o, ((Boolean) value).booleanValue());
- break;
- case 'S': // short
- f.setShort(o, ((Short) value).shortValue());
- break;
- case 'B': // byte
- f.setByte(o, ((Byte) value).byteValue());
- break;
- case 'C': // char
- f.setChar(o, ((Character) value).charValue());
- break;
- case 'D': // double
- f.setDouble(o, ((Double) value).doubleValue());
- break;
- case 'F': // float
- f.setFloat(o, ((Float) value).floatValue());
- break;
- default:
- f.set(o, value);
- }
- if (expectedException != null) {
- fail("expected exception " + expectedException.getName()
- + " for field " + f.getName() + ", value " + value);
- }
- } catch (Exception e) {
- if (expectedException == null) {
- fail("unexpected exception " + e + " for field "
- + f.getName() + ", value " + value);
- } else {
- assertTrue("expected exception "
- + expectedException.getName() + " and got " + e
- + " for field " + f.getName() + ", value " + value,
- e.getClass().equals(expectedException));
- }
- }
- }
- }
-
- /**
- * java.lang.reflect.Field#get(java.lang.Object)
- * java.lang.reflect.Field#getByte(java.lang.Object)
- * java.lang.reflect.Field#getBoolean(java.lang.Object)
- * java.lang.reflect.Field#getShort(java.lang.Object)
- * java.lang.reflect.Field#getInt(java.lang.Object)
- * java.lang.reflect.Field#getLong(java.lang.Object)
- * java.lang.reflect.Field#getFloat(java.lang.Object)
- * java.lang.reflect.Field#getDouble(java.lang.Object)
- * java.lang.reflect.Field#getChar(java.lang.Object)
- * java.lang.reflect.Field#set(java.lang.Object, java.lang.Object)
- * java.lang.reflect.Field#setByte(java.lang.Object, byte)
- * java.lang.reflect.Field#setBoolean(java.lang.Object, boolean)
- * java.lang.reflect.Field#setShort(java.lang.Object, short)
- * java.lang.reflect.Field#setInt(java.lang.Object, int)
- * java.lang.reflect.Field#setLong(java.lang.Object, long)
- * java.lang.reflect.Field#setFloat(java.lang.Object, float)
- * java.lang.reflect.Field#setDouble(java.lang.Object, double)
- * java.lang.reflect.Field#setChar(java.lang.Object, char)
- */
- public void testProtectedFieldAccess() {
- Class fieldClass = new Support_Field().getClass();
- String fieldName = null;
- Field objectField = null;
- Field booleanField = null;
- Field byteField = null;
- Field charField = null;
- Field shortField = null;
- Field intField = null;
- Field longField = null;
- Field floatField = null;
- Field doubleField = null;
- try {
- fieldName = "objectField";
- objectField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "booleanField";
- booleanField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "byteField";
- byteField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "charField";
- charField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "shortField";
- shortField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "intField";
- intField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "longField";
- longField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "floatField";
- floatField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "doubleField";
- doubleField = fieldClass.getDeclaredField(fieldName);
- } catch (NoSuchFieldException e) {
- fail("missing field " + fieldName + " in test support class "
- + fieldClass.getName());
- }
-
- // create the various objects that might or might not have an instance
- // of the field
- Support_Field parentClass = new Support_Field();
- SupportSubClass subclass = new SupportSubClass();
- SupportSubClass otherSubclass = new SupportSubClass();
- Object plainObject = new Object();
-
- Class illegalAccessExceptionClass = new IllegalAccessException()
- .getClass();
- Class illegalArgumentExceptionClass = new IllegalArgumentException()
- .getClass();
-
- // The test will attempt to use pass an object to set for object, byte,
- // short, ..., float and double fields
- // and pass a byte to to setByte for byte, short, ..., float and double
- // fields and so on.
- // It will also test if IllegalArgumentException is thrown when the
- // field does not exist in the given object and that
- // IllegalAccessException is thrown when trying to access an
- // inaccessible protected field.
- // The test will also check that IllegalArgumentException is thrown for
- // all other attempts.
-
- // Ordered by widening conversion, except for 'L' at the beg (which
- // stands for Object).
- // If the object provided to set can be unwrapped to a primitive, then
- // the set method can set
- // primitive fields.
- char types[] = { 'L', 'B', 'S', 'C', 'I', 'J', 'F', 'D' };
- Field fields[] = { objectField, byteField, shortField, charField,
- intField, longField, floatField, doubleField };
- Object values[] = { new Byte((byte) 1), new Byte((byte) 1),
- new Short((short) 1), new Character((char) 1), new Integer(1),
- new Long(1), new Float(1), new Double(1) };
-
- // test set methods
- for (int i = 0; i < types.length; i++) {
- char type = types[i];
- Object value = values[i];
- for (int j = i; j < fields.length; j++) {
- Field field = fields[j];
- fieldName = field.getName();
-
- if (field == charField && type != 'C') {
- // the exception is that bytes and shorts CANNOT be
- // converted into chars even though chars CAN be
- // converted into ints, longs, floats and doubles
- subclass.setField(type, subclass, field,
- illegalArgumentExceptionClass, value);
- } else {
- // setting type into field);
- subclass.setField(type, subclass, field, null, value);
- subclass.setField(type, otherSubclass, field, null, value);
- subclass.setField(type, parentClass, field,
- illegalAccessExceptionClass, value);
- subclass.setField(type, plainObject, field,
- // Failed on JDK.
- illegalAccessExceptionClass, value);
- }
- }
- for (int j = 0; j < i; j++) {
- Field field = fields[j];
- fieldName = field.getName();
- // not setting type into field);
- subclass.setField(type, subclass, field,
- illegalArgumentExceptionClass, value);
- }
- }
-
- // test setBoolean
- Boolean booleanValue = Boolean.TRUE;
- subclass.setField('Z', subclass, booleanField, null, booleanValue);
- subclass.setField('Z', otherSubclass, booleanField, null, booleanValue);
- subclass.setField('Z', parentClass, booleanField,
- illegalAccessExceptionClass, booleanValue);
- subclass.setField('Z', plainObject, booleanField,
- // Failed on JDK
- illegalAccessExceptionClass, booleanValue);
- for (int j = 0; j < fields.length; j++) {
- Field listedField = fields[j];
- fieldName = listedField.getName();
- // not setting boolean into listedField
- subclass.setField('Z', subclass, listedField,
- illegalArgumentExceptionClass, booleanValue);
- }
- for (int i = 0; i < types.length; i++) {
- char type = types[i];
- Object value = values[i];
- subclass.setField(type, subclass, booleanField,
- illegalArgumentExceptionClass, value);
- }
-
- // We perform the analagous test on the get methods.
-
- // ordered by widening conversion, except for 'L' at the end (which
- // stands for Object), to which all primitives can be converted by
- // wrapping
- char newTypes[] = new char[] { 'B', 'S', 'C', 'I', 'J', 'F', 'D', 'L' };
- Field newFields[] = { byteField, shortField, charField, intField,
- longField, floatField, doubleField, objectField };
- fields = newFields;
- types = newTypes;
- // test get methods
- for (int i = 0; i < types.length; i++) {
- char type = types[i];
- for (int j = 0; j <= i; j++) {
- Field field = fields[j];
- fieldName = field.getName();
- if (type == 'C' && field != charField) {
- // the exception is that bytes and shorts CANNOT be
- // converted into chars even though chars CAN be
- // converted into ints, longs, floats and doubles
- subclass.getField(type, subclass, field,
- illegalArgumentExceptionClass);
- } else {
- // getting type from field
- subclass.getField(type, subclass, field, null);
- subclass.getField(type, otherSubclass, field, null);
- subclass.getField(type, parentClass, field,
- illegalAccessExceptionClass);
- subclass.getField(type, plainObject, field,
- illegalAccessExceptionClass);
- }
- }
- for (int j = i + 1; j < fields.length; j++) {
- Field field = fields[j];
- fieldName = field.getName();
- subclass.getField(type, subclass, field,
- illegalArgumentExceptionClass);
- }
- }
-
- // test getBoolean
- subclass.getField('Z', subclass, booleanField, null);
- subclass.getField('Z', otherSubclass, booleanField, null);
- subclass.getField('Z', parentClass, booleanField,
- illegalAccessExceptionClass);
- subclass.getField('Z', plainObject, booleanField,
- illegalAccessExceptionClass);
- for (int j = 0; j < fields.length; j++) {
- Field listedField = fields[j];
- fieldName = listedField.getName();
- // not getting boolean from listedField
- subclass.getField('Z', subclass, listedField,
- illegalArgumentExceptionClass);
- }
- for (int i = 0; i < types.length - 1; i++) {
- char type = types[i];
- subclass.getField(type, subclass, booleanField,
- illegalArgumentExceptionClass);
- }
- Object res = subclass.getField('L', subclass, booleanField, null);
- assertTrue("unexpected object " + res, res instanceof Boolean);
- }
-
- /**
- * java.lang.reflect.Field#getBoolean(java.lang.Object)
- */
- public void test_getBooleanLjava_lang_Object() {
- TestField x = new TestField();
- Field f = null;
- boolean val = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- val = f.getBoolean(x);
- } catch (Exception e) {
- fail("Exception during getBoolean test: " + e.toString());
- }
- assertTrue("Returned incorrect boolean field value", val);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getBoolean(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown");
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanPFField");
- f.getBoolean(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getBoolean(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanSField");
- boolean staticValue = f.getBoolean(null);
- assertTrue("Wrong value returned", staticValue);
- } catch (Exception ex) {
- fail("No exception expected");
- }
- }
-
-
- /**
- * java.lang.reflect.Field#getByte(java.lang.Object)
- */
- public void test_getByteLjava_lang_Object() {
- // Test for method byte
- // java.lang.reflect.Field.getByte(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- byte val = 0;
- try {
- f = x.getClass().getDeclaredField("byteField");
- val = f.getByte(x);
- } catch (Exception e) {
- fail("Exception during getbyte test : " + e.getMessage());
- }
- assertTrue("Returned incorrect byte field value", val == Byte.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getByte(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown");
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("bytePFField");
- f.getByte(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("byteField");
- f.getByte(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("byteSField");
- byte staticValue = f.getByte(null);
- assertEquals("Wrong value returned", Byte.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getChar(java.lang.Object)
- */
- public void test_getCharLjava_lang_Object() {
- // Test for method char
- // java.lang.reflect.Field.getChar(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- char val = 0;
- try {
- f = x.getClass().getDeclaredField("charField");
- val = f.getChar(x);
- } catch (Exception e) {
- fail("Exception during getCharacter test: " + e.toString());
- }
- assertEquals("Returned incorrect char field value", 'T', val);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getChar(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown");
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charPFField");
- f.getChar(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charField");
- f.getChar(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charSField");
- char staticValue = f.getChar(null);
- assertEquals("Wrong value returned", 'T', staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getDeclaringClass()
- */
- public void test_getDeclaringClass() {
- // Test for method java.lang.Class
- // java.lang.reflect.Field.getDeclaringClass()
- Field[] fields;
-
- try {
- fields = new TestField().getClass().getFields();
- assertTrue("Returned incorrect declaring class", fields[0]
- .getDeclaringClass().equals(new TestField().getClass()));
-
- // Check the case where the field is inherited to be sure the parent
- // is returned as the declarator
- fields = new TestFieldSub1().getClass().getFields();
- assertTrue("Returned incorrect declaring class", fields[0]
- .getDeclaringClass().equals(new TestField().getClass()));
- } catch (Exception e) {
- fail("Exception : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getDouble(java.lang.Object)
- */
- public void test_getDoubleLjava_lang_Object() {
- // Test for method double
- // java.lang.reflect.Field.getDouble(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- double val = 0.0;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- val = f.getDouble(x);
- } catch (Exception e) {
- fail("Exception during getDouble test: " + e.toString());
- }
- assertTrue("Returned incorrect double field value",
- val == Double.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getDouble(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doublePFField");
- f.getDouble(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getDouble(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleSFField");
- double staticValue = f.getDouble(null);
- assertEquals("Wrong value returned", Double.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getFloat(java.lang.Object)
- */
- public void test_getFloatLjava_lang_Object() {
- // Test for method float
- // java.lang.reflect.Field.getFloat(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- float val = 0;
- try {
- f = x.getClass().getDeclaredField("floatField");
- val = f.getFloat(x);
- } catch (Exception e) {
- fail("Exception during getFloat test : " + e.getMessage());
- }
- assertTrue("Returned incorrect float field value",
- val == Float.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getFloat(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatPFField");
- f.getFloat(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatField");
- f.getFloat(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatSField");
- float staticValue = f.getFloat(null);
- assertEquals("Wrong value returned", Float.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getInt(java.lang.Object)
- */
- public void test_getIntLjava_lang_Object() {
- // Test for method int java.lang.reflect.Field.getInt(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- int val = 0;
- try {
- f = x.getClass().getDeclaredField("intField");
- val = f.getInt(x);
- } catch (Exception e) {
- fail("Exception during getInt test : " + e.getMessage());
- }
- assertTrue("Returned incorrect Int field value",
- val == Integer.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getInt(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intPFField");
- f.getInt(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intField");
- f.getInt(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intSField");
- int staticValue = f.getInt(null);
- assertEquals("Wrong value returned", Integer.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected " + ex.getMessage());
- }
-
- }
-
- /**
- * java.lang.reflect.Field#getLong(java.lang.Object)
- */
- public void test_getLongLjava_lang_Object() {
- // Test for method long
- // java.lang.reflect.Field.getLong(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- long val = 0;
- try {
- f = x.getClass().getDeclaredField("longField");
- val = f.getLong(x);
- } catch (Exception e) {
- fail("Exception during getLong test : " + e.getMessage());
- }
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getLong(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longPFField");
- f.getLong(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longField");
- f.getLong(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longSField");
- long staticValue = f.getLong(null);
- assertEquals("Wrong value returned", Long.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getModifiers()
- */
- public void test_getModifiers() {
- // Test for method int java.lang.reflect.Field.getModifiers()
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("prsttrvol");
- } catch (Exception e) {
- fail("Exception during getModifiers test: " + e.toString());
- }
- int mod = f.getModifiers();
- int mask = (Modifier.PROTECTED | Modifier.STATIC)
- | (Modifier.TRANSIENT | Modifier.VOLATILE);
- int nmask = (Modifier.PUBLIC | Modifier.NATIVE);
- assertTrue("Returned incorrect field modifiers: ",
- ((mod & mask) == mask) && ((mod & nmask) == 0));
- }
-
- /**
- * java.lang.reflect.Field#getName()
- */
- public void test_getName() {
- // Test for method java.lang.String java.lang.reflect.Field.getName()
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("shortField");
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- assertEquals("Returned incorrect field name",
- "shortField", f.getName());
- }
-
- /**
- * java.lang.reflect.Field#getShort(java.lang.Object)
- */
- public void test_getShortLjava_lang_Object() {
- // Test for method short
- // java.lang.reflect.Field.getShort(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- short val = 0;
- ;
- try {
- f = x.getClass().getDeclaredField("shortField");
- val = f.getShort(x);
- } catch (Exception e) {
- fail("Exception during getShort test : " + e.getMessage());
- }
- assertTrue("Returned incorrect short field value",
- val == Short.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getShort(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortPFField");
- f.getShort(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortField");
- f.getShort(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortSField");
- short staticValue = f.getShort(null);
- assertEquals("Wrong value returned", Short.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.Field#getType()
- */
- public void test_getType() {
- // Test for method java.lang.Class java.lang.reflect.Field.getType()
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("shortField");
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- assertTrue("Returned incorrect field type: " + f.getType().toString(),
- f.getType().equals(short.class));
- }
-
- /**
- * java.lang.reflect.Field#set(java.lang.Object, java.lang.Object)
- */
- public void test_setLjava_lang_ObjectLjava_lang_Object() throws Exception{
- // Test for method void java.lang.reflect.Field.set(java.lang.Object,
- // java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- double val = 0.0;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.set(x, new Double(1.0));
- val = f.getDouble(x);
- } catch (Exception e) {
- fail("Exception during set test : " + e.getMessage());
- }
- assertEquals("Returned incorrect double field value", 1.0, val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.set(x, new Double(1.0));
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleFField");
- assertFalse(f.isAccessible());
- f.set(x, new Double(1.0));
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.set(null, true);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("doubleSField");
- f.set(null, new Double(1.0));
- val = f.getDouble(x);
- assertEquals("Returned incorrect double field value", 1.0, val);
- }
-
- /**
- * java.lang.reflect.Field#setBoolean(java.lang.Object, boolean)
- */
- public void test_setBooleanLjava_lang_ObjectZ() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setBoolean(java.lang.Object, boolean)
- TestField x = new TestField();
- Field f = null;
- boolean val = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setBoolean(x, false);
- val = f.getBoolean(x);
- } catch (Exception e) {
- fail("Exception during setboolean test: " + e.toString());
- }
- assertTrue("Returned incorrect float field value", !val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.setBoolean(x, false);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanPFField");
- assertFalse(f.isAccessible());
- f.setBoolean(x, true);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setBoolean(null, true);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("booleanSField");
- f.setBoolean(null, false);
- val = f.getBoolean(x);
- assertFalse("Returned incorrect boolean field value", val);
- }
-
- /**
- * java.lang.reflect.Field#setByte(java.lang.Object, byte)
- */
- public void test_setByteLjava_lang_ObjectB() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setByte(java.lang.Object, byte)
- TestField x = new TestField();
- Field f = null;
- byte val = 0;
- try {
- f = x.getClass().getDeclaredField("byteField");
- f.setByte(x, (byte) 1);
- val = f.getByte(x);
- } catch (Exception e) {
- fail("Exception during setByte test : " + e.getMessage());
- }
- assertEquals("Returned incorrect float field value", 1, val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setByte(x, Byte.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("bytePFField");
- assertFalse(f.isAccessible());
- f.setByte(x, Byte.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("byteField");
- f.setByte(null, Byte.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("byteSField");
- f.setByte(null, Byte.MIN_VALUE);
- val = f.getByte(x);
- assertEquals("Returned incorrect byte field value", Byte.MIN_VALUE,
- val);
- }
-
- /**
- * java.lang.reflect.Field#setChar(java.lang.Object, char)
- */
- public void test_setCharLjava_lang_ObjectC() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setChar(java.lang.Object, char)
- TestField x = new TestField();
- Field f = null;
- char val = 0;
- try {
- f = x.getClass().getDeclaredField("charField");
- f.setChar(x, (char) 1);
- val = f.getChar(x);
- } catch (Exception e) {
- fail("Exception during setChar test : " + e.getMessage());
- }
- assertEquals("Returned incorrect float field value", 1, val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setChar(x, Character.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charPFField");
- assertFalse(f.isAccessible());
- f.setChar(x, Character.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charField");
- f.setChar(null, Character.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("charSField");
- f.setChar(null, Character.MIN_VALUE);
- val = f.getChar(x);
- assertEquals("Returned incorrect char field value",
- Character.MIN_VALUE, val);
- }
-
- /**
- * java.lang.reflect.Field#setDouble(java.lang.Object, double)
- */
- public void test_setDoubleLjava_lang_ObjectD() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setDouble(java.lang.Object, double)
- TestField x = new TestField();
- Field f = null;
- double val = 0.0;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.setDouble(x, Double.MIN_VALUE);
- val = f.getDouble(x);
- } catch (Exception e) {
- fail("Exception during setDouble test: " + e.toString());
- }
- assertEquals("Returned incorrect double field value", Double.MIN_VALUE,
- val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setDouble(x, Double.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doublePFField");
- assertFalse(f.isAccessible());
- f.setDouble(x, Double.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.setDouble(null, Double.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("doubleSField");
- f.setDouble(null, Double.MIN_VALUE);
- val = f.getDouble(x);
- assertEquals("Returned incorrect double field value",
- Double.MIN_VALUE, val);
- }
-
- /**
- * java.lang.reflect.Field#setFloat(java.lang.Object, float)
- */
- public void test_setFloatLjava_lang_ObjectF() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setFloat(java.lang.Object, float)
- TestField x = new TestField();
- Field f = null;
- float val = 0.0F;
- try {
- f = x.getClass().getDeclaredField("floatField");
- f.setFloat(x, Float.MIN_VALUE);
- val = f.getFloat(x);
- } catch (Exception e) {
- fail("Exception during setFloat test : " + e.getMessage());
- }
- assertEquals("Returned incorrect float field value", Float.MIN_VALUE,
- val, 0.0);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setFloat(x, Float.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatPFField");
- assertFalse(f.isAccessible());
- f.setFloat(x, Float.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatField");
- f.setFloat(null, Float.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("floatSField");
- f.setFloat(null, Float.MIN_VALUE);
- val = f.getFloat(x);
- assertEquals("Returned incorrect float field value",
- Float.MIN_VALUE, val);
- }
-
- /**
- * java.lang.reflect.Field#setInt(java.lang.Object, int)
- */
- public void test_setIntLjava_lang_ObjectI() throws Exception{
- // Test for method void java.lang.reflect.Field.setInt(java.lang.Object,
- // int)
- TestField x = new TestField();
- Field f = null;
- int val = 0;
- try {
- f = x.getClass().getDeclaredField("intField");
- f.setInt(x, Integer.MIN_VALUE);
- val = f.getInt(x);
- } catch (Exception e) {
- fail("Exception during setInteger test: " + e.toString());
- }
- assertEquals("Returned incorrect int field value", Integer.MIN_VALUE,
- val);
-
- // test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setInt(x, Integer.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- // test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intPFField");
- assertFalse(f.isAccessible());
- f.setInt(x, Integer.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intField");
- f.setInt(null, Integer.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("intSField");
- f.setInt(null, Integer.MIN_VALUE);
- val = f.getInt(x);
- assertEquals("Returned incorrect int field value",
- Integer.MIN_VALUE, val);
- }
-
- /**
- * java.lang.reflect.Field#setLong(java.lang.Object, long)
- */
- public void test_setLongLjava_lang_ObjectJ() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setLong(java.lang.Object, long)
- TestField x = new TestField();
- Field f = null;
- long val = 0L;
- try {
- f = x.getClass().getDeclaredField("longField");
- f.setLong(x, Long.MIN_VALUE);
- val = f.getLong(x);
- } catch (Exception e) {
- fail("Exception during setLong test : " + e.getMessage());
- }
- assertEquals("Returned incorrect long field value", Long.MIN_VALUE, val);
-
- // test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setLong(x, Long.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- // test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longPFField");
- assertFalse(f.isAccessible());
- f.setLong(x, Long.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longField");
- f.setLong(null, Long.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("longSField");
- f.setLong(null, Long.MIN_VALUE);
- val = f.getLong(x);
- assertEquals("Returned incorrect long field value",
- Long.MIN_VALUE, val);
- }
-
- /**
- * java.lang.reflect.Field#setShort(java.lang.Object, short)
- */
- public void test_setShortLjava_lang_ObjectS() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setShort(java.lang.Object, short)
- TestField x = new TestField();
- Field f = null;
- short val = 0;
- try {
- f = x.getClass().getDeclaredField("shortField");
- f.setShort(x, Short.MIN_VALUE);
- val = f.getShort(x);
- } catch (Exception e) {
- fail("Exception during setShort test : " + e.getMessage());
- }
- assertEquals("Returned incorrect short field value", Short.MIN_VALUE,
- val);
-
- // test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setShort(x, Short.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- // test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortPFField");
- assertFalse(f.isAccessible());
- f.setShort(x, Short.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortField");
- f.setShort(null, Short.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("shortSField");
- f.setShort(null, Short.MIN_VALUE);
- val = f.getShort(x);
- assertEquals("Returned incorrect short field value",
- Short.MIN_VALUE, val);
- }
-
- /**
- * java.lang.reflect.Field#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.lang.reflect.Field.toString()
- Field f = null;
-
- try {
- f = TestField.class.getDeclaredField("x");
- } catch (Exception e) {
- fail("Exception getting field : " + e.getMessage());
- }
- assertEquals("Field returned incorrect string",
- "private static final int tests.api.java.lang.reflect.FieldTest$TestField.x",
- f.toString());
- }
-
- public void test_getDeclaredAnnotations() throws Exception {
- Field field = TestClass.class.getField("annotatedField");
- Annotation[] annotations = field.getDeclaredAnnotations();
- assertEquals(2, annotations.length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing @AnnotationRuntime0", ignoreOrder
- .contains(AnnotationRuntime0.class));
- assertTrue("Missing @AnnotationRuntime1", ignoreOrder
- .contains(AnnotationRuntime1.class));
- }
-
- public void test_isEnumConstant() throws Exception {
- Field field = TestEnum.class.getDeclaredField("A");
- assertTrue("Enum constant not recognized", field.isEnumConstant());
-
- field = TestEnum.class.getDeclaredField("field");
- assertFalse("Non enum constant wrongly stated as enum constant", field
- .isEnumConstant());
-
- field = TestClass.class.getDeclaredField("annotatedField");
- assertFalse("Non enum constant wrongly stated as enum constant", field
- .isEnumConstant());
- }
-
- public void test_isSynthetic() throws Exception {
- Field[] fields = TestClass.Inner.class.getDeclaredFields();
- assertEquals("Not exactly one field returned", 1, fields.length);
-
- assertTrue("Enum constant not recognized", fields[0].isSynthetic());
-
- Field field = TestEnum.class.getDeclaredField("field");
- assertFalse("Non synthetic field wrongly stated as synthetic", field
- .isSynthetic());
-
- field = TestClass.class.getDeclaredField("annotatedField");
- assertFalse("Non synthetic field wrongly stated as synthetic", field
- .isSynthetic());
- }
-
-
- public void test_getGenericType() throws Exception {
- Field field = GenericField.class.getDeclaredField("field");
- Type type = field.getGenericType();
- @SuppressWarnings("unchecked")
- TypeVariable typeVar = (TypeVariable) type;
- assertEquals("Wrong type name returned", "S", typeVar.getName());
-
- Field boundedField = GenericField.class.getDeclaredField("boundedField");
- Type boundedType = boundedField.getGenericType();
- @SuppressWarnings("unchecked")
- TypeVariable boundedTypeVar = (TypeVariable) boundedType;
- assertEquals("Wrong type name returned", "T", boundedTypeVar.getName());
- assertEquals("More than one bound found", 1,
- boundedTypeVar.getBounds().length);
- assertEquals("Wrong bound returned", Number.class,
- boundedTypeVar.getBounds()[0]);
- }
-
-
- public void test_toGenericString() throws Exception {
- Field field = GenericField.class.getDeclaredField("field");
- assertEquals("Wrong generic string returned",
- "S tests.api.java.lang.reflect.FieldTest$GenericField.field",
- field.toGenericString());
-
- Field boundedField = GenericField.class
- .getDeclaredField("boundedField");
- assertEquals(
- "Wrong generic string returned",
- "T tests.api.java.lang.reflect.FieldTest$GenericField.boundedField",
- boundedField.toGenericString());
-
- Field ordinary = GenericField.class.getDeclaredField("intField");
- assertEquals(
- "Wrong generic string returned",
- "int tests.api.java.lang.reflect.FieldTest$GenericField.intField",
- ordinary.toGenericString());
- }
-
-
- public void test_hashCode() throws Exception {
- Field field = TestClass.class.getDeclaredField("annotatedField");
- assertEquals("Wrong hashCode returned", field.getName().hashCode()
- ^ field.getDeclaringClass().getName().hashCode(), field
- .hashCode());
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
-
-class TestAccess {
- private static int xxx;
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java
deleted file mode 100644
index e48e584..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java
+++ /dev/null
@@ -1,64 +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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.GenericArrayType;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Tests generic reflection on arrays with generic or parameterized component types.
- */
-public class GenericArrayTypeTest extends GenericReflectionTestsBase {
-
- static class A<T> {
- T[] array;
- }
- public void testGetGenericComponentType() throws Exception {
- @SuppressWarnings("unchecked")
- Class<? extends A> clazz = GenericArrayTypeTest.A.class;
- Field field = clazz.getDeclaredField("array");
- Type genericType = field.getGenericType();
- assertInstanceOf(GenericArrayType.class, genericType);
- Type componentType = ((GenericArrayType) genericType).getGenericComponentType();
- assertEquals(getTypeParameter(clazz), componentType);
- assertInstanceOf(TypeVariable.class, componentType);
- TypeVariable<?> componentTypeVariable = (TypeVariable<?>) componentType;
- assertEquals("T", componentTypeVariable.getName());
- assertEquals(clazz, componentTypeVariable.getGenericDeclaration());
- }
-
- static class B<T> {
- B<T>[] array;
- }
- public void testParameterizedComponentType() throws Exception {
- @SuppressWarnings("unchecked")
- Class<? extends B> clazz = GenericArrayTypeTest.B.class;
- Field field = clazz.getDeclaredField("array");
- Type genericType = field.getGenericType();
-
- assertInstanceOf(GenericArrayType.class, genericType);
- GenericArrayType arrayType = (GenericArrayType) genericType;
- Type componentType = arrayType.getGenericComponentType();
- assertInstanceOf(ParameterizedType.class, componentType);
- ParameterizedType parameteriezdType = (ParameterizedType) componentType;
- assertEquals(clazz, parameteriezdType.getRawType());
- assertEquals(clazz.getTypeParameters()[0], parameteriezdType.getActualTypeArguments()[0]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java
deleted file mode 100644
index 0bfc188..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java
+++ /dev/null
@@ -1,121 +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 tests.api.java.lang.reflect;
-
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-
-/**
- * Tests unbounded type parameters declared on methods.
- */
-public class GenericMethodsTests extends GenericReflectionTestsBase{
-
- static class GenericMethods {
-
- public <T> void noParamNoReturn() {}
-
- public <T> void paramNoReturn(T param) {}
-
- @SuppressWarnings("unchecked")
- public <T> T noParamReturn() { return (T) new Object(); }
-
- public <T> T paramReturn(T param) {return param;}
- }
-
- private static Class<? extends GenericMethods> clazz = GenericMethodsTests.GenericMethods.class;
-
- /**
- * Tests that there are no Type Parameters on the Class itself.
- */
- public void testGenericMethods() {
- assertLenghtZero(clazz.getTypeParameters());
- }
-
- /**
- * Tests whether the specified method declares a type parameter T.
- * @param method the method
- */
- private void checkTypeParameter(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertEquals("T", typeParameter.getName());
- assertEquals(method, typeParameter.getGenericDeclaration());
- }
-
- /**
- * Tests whether the specified method declares a parameter with the
- * type of the type parameter.
- * @param method the method
- */
- private void checkParameterType(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertLenghtOne(method.getGenericParameterTypes());
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertEquals(typeParameter, genericParameterType);
- assertInstanceOf(TypeVariable.class, genericParameterType);
- assertEquals(method, ((TypeVariable<?>) genericParameterType).getGenericDeclaration());
- }
-
- /**
- * Tests whether the type of the return type is the declared type parameter.
- * @param method the declaring method
- */
- private void checkReturnType(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- Type genericReturnType = method.getGenericReturnType();
- assertEquals(typeParameter, genericReturnType);
- assertInstanceOf(TypeVariable.class, genericReturnType);
- assertEquals(method, ((TypeVariable<?>) genericReturnType).getGenericDeclaration());
- }
- public void testNoParamNoReturn() throws Exception {
- Method method = clazz.getMethod("noParamNoReturn");
- checkTypeParameter(method);
- }
-
- public void testParamNoReturn() throws Exception {
- Method method = clazz.getMethod("paramNoReturn", Object.class);
- checkTypeParameter(method);
- checkParameterType(method);
- }
-
- public void testNoParamReturn() throws Exception {
- Method method = clazz.getMethod("noParamReturn");
- checkTypeParameter(method);
- assertLenghtZero(method.getGenericParameterTypes());
- checkReturnType(method);
- }
- public void testParamReturn() throws Exception {
- Method method = clazz.getMethod("paramReturn", Object.class);
- checkTypeParameter(method);
- checkParameterType(method);
- checkReturnType(method);
- }
- public void testIndependencyOfMethodTypeParameters() throws Exception {
- Method method0 = clazz.getMethod("paramNoReturn", Object.class);
- TypeVariable<Method> typeParameter0 = method0.getTypeParameters()[0];
-
- Method method1 = clazz.getMethod("noParamNoReturn");
- TypeVariable<Method> typeParameter1 = method1.getTypeParameters()[0];
-
- //Generic method type parameters NAMES are equal
- assertEquals(typeParameter0.getName(), typeParameter1.getName());
- //Generic method type PARAMETERS are not equal
- assertNotEquals(typeParameter0, typeParameter1);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java
deleted file mode 100644
index 095bb72..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java
+++ /dev/null
@@ -1,74 +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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.TypeVariable;
-
-import junit.framework.TestCase;
-
-public class GenericReflectionTestsBase extends TestCase{
-
- /**
- * Returns the type parameter of the declaring method.
- *
- * @param method
- * the declaring method
- * @return the type parameter of the method
- */
- public TypeVariable<Method> getTypeParameter(Method method) {
- TypeVariable<Method>[] typeParameters = method.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Method> typeParameter = typeParameters[0];
- return typeParameter;
- }
-
- /**
- * Returns the type parameter of the declaring class.
- *
- * @param method
- * the declaring method.
- * @return the type parameter of the method.
- */
- @SuppressWarnings("unchecked")
- public TypeVariable<Class> getTypeParameter(Class<?> clazz) {
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Class> typeVariable = typeParameters[0];
- assertEquals(clazz, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- return typeVariable;
- }
-
- public static void assertLenghtOne(Object[] array) {
- TestCase.assertEquals("Array does NOT contain exactly one element.", 1, array.length);
- }
-
- public static void assertLenghtZero(Object[] array) {
- TestCase.assertEquals("Array has more than zero elements.", 0, array.length);
- }
-
- public static void assertInstanceOf(Class<?> expectedClass, Object actual) {
- TestCase.assertTrue(actual.getClass().getName() + " is not instance of :" + expectedClass.getName(), expectedClass
- .isInstance(actual));
- }
-
- public static void assertNotEquals(Object expected, Object actual) {
- TestCase.assertFalse(actual.toString() + " has not to be equal to " + expected.toString(), expected.equals(actual));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java
deleted file mode 100644
index 954073c..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-package tests.api.java.lang.reflect;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.SideEffect;
-import dalvik.system.DexFile;
-
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.GenericSignatureFormatError;
-import java.lang.reflect.TypeVariable;
-
-import tests.support.Support_ClassLoader;
-
-public class GenericSignatureFormatErrorTest extends TestCase{
-
- public void test_Constructor() {
- assertNotNull(new GenericSignatureFormatError());
- }
-
- public void test_readResource() throws Exception {
- File tf = File.createTempFile("classes", ".dex");
- // System.out.println("GenericSignatureFormatErrorTest:"
- // +tf.getAbsolutePath()+", canRead: "+tf.canRead()
- // +", canWrite: "+tf.canWrite());
- InputStream is = this.getClass().getResourceAsStream("dex1.bytes");
- assertNotNull(is);
- }
-
-
- @AndroidOnly("Uses Android specific class dalvik.system.DexFile " +
- "for loading classes.")
- @SideEffect("strange issue (exception: 'could not open dex file', " +
- "dalvikvm: 'waitpid failed' log msg - only occurs when @SideEffect is removed " +
- "and this test is run via running tests.luni.AllTestsLang TestSuite")
- public void test_signatureFormatError() throws Exception {
- /*
- * dex1.bytes is a jar file with a classes.dex in it.
- * the classes.dex was javac'ed, dx'ed and patched
- * with the following java file:
- *
- * package demo;
- * public class HelloWorld<U> {
- * public HelloWorld(U t) {}
- * }
- *
- * patch:
- * the string constant (class generics signature string)
- * "<U:" was changed to "<<:"
- *
- */
-
- File tf = File.createTempFile("classes", ".dex");
- // System.out.println("GenericSignatureFormatErrorTest:" +
- // tf.getAbsolutePath() + ", canRead: " + tf.canRead() +
- // ", canWrite: "+tf.canWrite());
- InputStream is = this.getClass().getResourceAsStream("dex1.bytes");
- assertNotNull(is);
- OutputStream fos = new FileOutputStream(tf);
- copy(is, fos);
- fos.flush();
- fos.close();
-
-
- // class signature string "<U:" was changed to "<<:"
- //System.out.println("file length:"+tf.length());
- try {
- // Was:
- // DexFile df = new DexFile(tf);
- // Class clazz = df.loadClass("demo/HelloWorld", this.getClass().getClassLoader());
-
- ClassLoader cl = Support_ClassLoader.getInstance(tf.toURL(),
- getClass().getClassLoader());
-
- Class clazz = cl.loadClass("demo/HelloWorld");
- TypeVariable[] tvs = clazz.getTypeParameters();
- fail("expecting a GenericSignatureFormatError");
- // for (TypeVariable tv : tvs) {
- // System.out.println("tv:"+tv.toString());
- // }
- } catch (GenericSignatureFormatError gsfe) {
- // expected
- }
- }
-
- private void copy(InputStream is, OutputStream os) {
- try {
- int b;
- while ((b = is.read()) != -1) {
- os.write(b);
- }
- is.close();
- } catch (IOException ex) {
- throw new RuntimeException("io error", ex);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java b/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java
deleted file mode 100644
index 5e699a9..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java
+++ /dev/null
@@ -1,305 +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 tests.api.java.lang.reflect;
-
-import java.io.ByteArrayOutputStream;
-import java.io.CharArrayWriter;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-
-public class InvocationTargetExceptionTest extends junit.framework.TestCase {
-
- static class TestMethod {
- public TestMethod() {
- }
-
- public void voidMethod() throws IllegalArgumentException {
- }
-
- public void parmTest(int x, short y, String s, boolean bool, Object o,
- long l, byte b, char c, double d, float f) {
- }
-
- public int intMethod() {
- return 1;
- }
-
- public static final void printTest(int x, short y, String s,
- boolean bool, Object o, long l, byte b, char c, double d,
- float f) {
- }
-
- public double doubleMethod() {
- return 1.0;
- }
-
- public short shortMethod() {
- return (short) 1;
- }
-
- public byte byteMethod() {
- return (byte) 1;
- }
-
- public float floatMethod() {
- return 1.0f;
- }
-
- public long longMethod() {
- return 1l;
- }
-
- public char charMethod() {
- return 'T';
- }
-
- public Object objectMethod() {
- return new Object();
- }
-
- private static void prstatic() {
- }
-
- public static void pustatic() {
- }
-
- public static synchronized void pustatsynch() {
- }
-
- public static int invokeStaticTest() {
- return 1;
- }
-
- public int invokeInstanceTest() {
- return 1;
- }
-
- private int privateInvokeTest() {
- return 1;
- }
-
- public int invokeExceptionTest() throws NullPointerException {
- throw new NullPointerException();
- }
-
- public static synchronized native void pustatsynchnat();
-
- }
-
- abstract class AbstractTestMethod {
- public abstract void puabs();
- }
-
- class SubInvocationTargetException extends InvocationTargetException {}
-
- /**
- * java.lang.reflect.InvocationTargetException#InvocationTargetException()
- */
- public void test_Constructor() throws Exception {
- Constructor<InvocationTargetException> ctor = InvocationTargetException.class
- .getDeclaredConstructor();
- assertNotNull("Parameterless constructor does not exist.", ctor);
- assertTrue("Constructor is not protected", Modifier.isProtected(ctor
- .getModifiers()));
- //create an instance of a subtype using this constructor
- SubInvocationTargetException subException = new SubInvocationTargetException();
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable)
- */
- public void test_ConstructorLjava_lang_Throwable() {
- // Test for method
- // java.lang.reflect.InvocationTargetException(java.lang.Throwable)
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = { Object.class };
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- return;
- } catch (NoSuchMethodException e) {
- } catch (IllegalAccessException e) {
- }
- fail("Failed to throw exception");
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable,
- * java.lang.String)
- */
- public void test_ConstructorLjava_lang_ThrowableLjava_lang_String() {
- // Test for method
- // java.lang.reflect.InvocationTargetException(java.lang.Throwable,
- // java.lang.String)
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = { Object.class };
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- return;
- } catch (NoSuchMethodException e) {
- ;
- } catch (IllegalAccessException e) {
- }
- fail("Failed to throw exception");
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#getTargetException()
- */
- public void test_getTargetException() {
- // Test for method java.lang.Throwable
- // java.lang.reflect.InvocationTargetException.getTargetException()
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = { Object.class };
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- assertTrue("Returned incorrect target exception", e
- .getTargetException() instanceof NullPointerException);
- return;
- } catch (Exception e) {
- fail("Exception during constructor test : " + e.getMessage());
- }
- fail("Failed to throw exception");
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#getCause()
- */
- public void test_getCause() {
- // java.lang.reflect.InvocationTargetException.getCause()
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = {Object.class};
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- assertTrue("Returned incorrect cause",
- e.getCause() instanceof NullPointerException);
- return;
- } catch (Exception e) {
- fail("Exception during InvocationTargetException test : "
- + e.getMessage());
- }
- fail("Failed to throw exception");
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#printStackTrace()
- */
- public void test_printStackTrace() {
- // Test for method void
- // java.lang.reflect.InvocationTargetException.printStackTrace()
- try {
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- PrintStream oldErr = System.err;
- System.setErr(ps);
- InvocationTargetException ite = new InvocationTargetException(null);
- ite.printStackTrace();
- System.setErr(oldErr);
-
- String s = new String(bao.toByteArray());
-
- assertTrue("Incorrect Stack trace: " + s, s != null
- && s.length() > 300);
- } catch (Exception e) {
- fail("printStackTrace() caused exception : " + e.getMessage());
- }
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintStream)
- */
- public void test_printStackTraceLjava_io_PrintStream() {
- // Test for method void
- // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintStream)
- assertTrue("Tested via test_printStackTrace().", true);
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- InvocationTargetException ite = new InvocationTargetException(
- new InvocationTargetException(null));
- ite.printStackTrace(ps);
- String s = bao.toString();
- assertTrue("printStackTrace failed." + s.length(), s != null
- && s.length() > 400);
- }
-
- /**
- * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintWriter)
- */
- public void test_printStackTraceLjava_io_PrintWriter() {
- // Test for method void
- // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintWriter)
- try {
- PrintWriter pw;
- InvocationTargetException ite;
- String s;
- CharArrayWriter caw = new CharArrayWriter();
- pw = new PrintWriter(caw);
- ite = new InvocationTargetException(new InvocationTargetException(
- null));
- ite.printStackTrace(pw);
-
- s = caw.toString();
- assertTrue("printStackTrace failed." + s.length(), s != null
- && s.length() > 400);
- pw.close();
-
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- pw = new PrintWriter(bao);
- ite = new InvocationTargetException(new InvocationTargetException(
- null));
- ite.printStackTrace(pw);
-
- pw.flush(); // Test will fail if this line removed.
- s = bao.toString();
- assertTrue("printStackTrace failed." + s.length(), s != null
- && s.length() > 400);
-
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java b/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java
deleted file mode 100644
index f86403d..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package tests.api.java.lang.reflect;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.MalformedParameterizedTypeException;
-import java.lang.reflect.Modifier;
-
-public class MalformedParameterizedTypeExceptionTests extends junit.framework.TestCase {
-
- /**
- * java.lang.reflect.MalformedParameterizedTypeException#MalformedParameterizedTypeException()
- */
- public void test_Constructor() throws Exception {
- Constructor<MalformedParameterizedTypeException> ctor = MalformedParameterizedTypeException.class
- .getDeclaredConstructor();
- assertNotNull("Parameterless constructor does not exist.", ctor);
- assertTrue("Constructor is not protected", Modifier.isPublic(ctor
- .getModifiers()));
- assertNotNull(ctor.newInstance());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java b/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java
deleted file mode 100644
index e8288d6..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java
+++ /dev/null
@@ -1,881 +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 tests.api.java.lang.reflect;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.HashSet;
-import java.util.Set;
-
-public class MethodTest extends junit.framework.TestCase {
-
- static class TestMethod {
- public TestMethod() {
- }
-
- public void voidMethod() throws IllegalArgumentException {
- }
-
- public void parmTest(int x, short y, String s, boolean bool, Object o,
- long l, byte b, char c, double d, float f) {
- }
-
- public int intMethod() {
- return 1;
- }
-
- public static final void printTest(int x, short y, String s,
- boolean bool, Object o, long l, byte b, char c, double d,
- float f) {
- }
-
- public double doubleMethod() {
- return 1.0;
- }
-
- public short shortMethod() {
- return (short) 1;
- }
-
- public byte byteMethod() {
- return (byte) 1;
- }
-
- public float floatMethod() {
- return 1.0f;
- }
-
- public long longMethod() {
- return 1l;
- }
-
- public char charMethod() {
- return 'T';
- }
-
- public Object objectMethod() {
- return new Object();
- }
-
- private static void prstatic() {
- }
-
- public static void pustatic() {
- }
-
- public static synchronized void pustatsynch() {
- }
-
- public static int invokeStaticTest() {
- return 1;
- }
-
- public int invokeInstanceTest() {
- return 1;
- }
-
- private int privateInvokeTest() {
- return 1;
- }
-
- public int invokeExceptionTest() throws NullPointerException {
- throw new NullPointerException();
- }
-
- public static synchronized native void pustatsynchnat();
-
- public void publicVoidVarargs(Object... param){}
- public void publicVoidArray(Object[] param){}
-
- public void annotatedParameter(@TestAnno @Deprecated int a,
- @Deprecated int b, int c) {
- }
-
- @Deprecated
- @TestAnno
- public void annotatedMethod(){}
-
- public void hashCodeTest(int i){}
- public void hashCodeTest(String s){}
-
- public void invokeCastTest1(byte param) {
- }
-
- public void invokeCastTest1(short param) {
- }
-
- public void invokeCastTest1(int param) {
- }
-
- public void invokeCastTest1(long param) {
- }
-
- public void invokeCastTest1(float param) {
- }
-
- public void invokeCastTest1(double param) {
- }
-
- public void invokeCastTest1(char param) {
- }
-
- public void invokeCastTest1(boolean param) {
- }
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.PARAMETER, ElementType.METHOD})
- public static @interface TestAnno{
- public static final String DEFAULT_VALUE = "DEFAULT_VALUE";
-
- String value() default DEFAULT_VALUE;
- }
-
- abstract class AbstractTestMethod {
- public abstract void puabs();
- }
-
- class TestMethodSub extends TestMethod {
- public int invokeInstanceTest() {
- return 0;
- }
- }
-
- static interface IBrigeTest<T>{
- T m();
- }
-
- static class BrigeTest implements IBrigeTest<String> {
- public String m(){ return null; }
- }
-
- static class ExceptionTest<T extends Exception>{
- @SuppressWarnings("unused")
- void exceptionTest() throws T{}
- }
-
- static class GenericReturnType<T> {
- T returnGeneric(){return null;}
- }
-
- static class GenericString<T> {
- public static final String GENERIC =
- "T tests.api.java.lang.reflect.MethodTest$GenericString.genericString(T)";
- T genericString(T t) {
- return null;
- }
- }
-
- /**
- * java.lang.reflect.Method#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.lang.reflect.Method.equals(java.lang.Object)
-
- Method m1 = null, m2 = null;
- try {
- m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]);
- m2 = TestMethodSub.class.getMethod("invokeInstanceTest",
- new Class[0]);
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- assertTrue("Overriden method returned equal", !m1.equals(m2));
- assertTrue("Same method returned not-equal", m1.equals(m1));
- try {
- m1 = TestMethod.class.getMethod("invokeStaticTest", new Class[0]);
- m2 = TestMethodSub.class
- .getMethod("invokeStaticTest", new Class[0]);
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- assertTrue("Inherited method returned not-equal", m1.equals(m2));
- }
-
- /**
- * java.lang.Class#getMethod(java.lang.String, java.lang.Class[])
- */
- public void test_getMethod() throws NoSuchMethodException, SecurityException {
- // Check that getMethod treats null parameterTypes the same as an empty array.
- Method m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]);
- Method m2 = TestMethod.class.getMethod("invokeInstanceTest", (Class[]) null);
- assertEquals(m1, m2);
- }
-
- /**
- * java.lang.Class#getDeclaredMethod(java.lang.String, java.lang.Class[])
- */
- public void test_getDeclaredMethod() throws NoSuchMethodException, SecurityException {
- // Check that getDeclaredMethod treats null parameterTypes the same as an empty array.
- Method m1 = TestMethod.class.getDeclaredMethod("invokeInstanceTest", new Class[0]);
- Method m2 = TestMethod.class.getDeclaredMethod("invokeInstanceTest", (Class[]) null);
- assertEquals(m1, m2);
- }
-
- /**
- * java.lang.reflect.Method#getDeclaringClass()
- */
- public void test_getDeclaringClass() {
- // Test for method java.lang.Class
- // java.lang.reflect.Method.getDeclaringClass()
-
- Method[] mths;
-
- try {
- mths = TestMethod.class.getDeclaredMethods();
- assertTrue("Returned incorrect declaring class: "
- + mths[0].getDeclaringClass().toString(), mths[0]
- .getDeclaringClass().equals(TestMethod.class));
- } catch (Exception e) {
- fail("Exception during getDeclaringClass test: "
- + e.toString());
- }
- }
-
- /**
- * java.lang.reflect.Method#getExceptionTypes()
- */
- public void test_getExceptionTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Method.getExceptionTypes()
-
- try {
- Method mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
- Class[] ex = mth.getExceptionTypes();
- assertEquals("Returned incorrect number of exceptions",
- 1, ex.length);
- assertTrue("Returned incorrect exception type", ex[0]
- .equals(IllegalArgumentException.class));
- mth = TestMethod.class.getMethod("intMethod", new Class[0]);
- ex = mth.getExceptionTypes();
- assertEquals("Returned incorrect number of exceptions",
- 0, ex.length);
- } catch (Exception e) {
- fail("Exception during getExceptionTypes: " + e.toString());
- }
-
- }
-
- /**
- * java.lang.reflect.Method#getModifiers()
- */
- public void test_getModifiers() {
- // Test for method int java.lang.reflect.Method.getModifiers()
-
- Class cl = TestMethod.class;
- int mods = 0;
- Method mth = null;
- int mask = 0;
- try {
- mth = cl.getMethod("pustatic", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = Modifier.PUBLIC | Modifier.STATIC;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- try {
- mth = cl.getDeclaredMethod("prstatic", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = Modifier.PRIVATE | Modifier.STATIC;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- try {
- mth = cl.getDeclaredMethod("pustatsynch", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = (Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- try {
- mth = cl.getDeclaredMethod("pustatsynchnat", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = ((Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED)
- | Modifier.NATIVE;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- cl = AbstractTestMethod.class;
- try {
- mth = cl.getDeclaredMethod("puabs", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = Modifier.PUBLIC | Modifier.ABSTRACT;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- }
-
- /**
- * java.lang.reflect.Method#getName()
- */
- public void test_getName() {
- // Test for method java.lang.String java.lang.reflect.Method.getName()
- Method mth = null;
- try {
- mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getMethodName(): " + e.toString());
- }
- assertEquals("Returned incorrect method name",
- "voidMethod", mth.getName());
- }
-
- /**
- * java.lang.reflect.Method#isVarArgs()
- */
- public void test_isVarArgs() throws Exception {
- Method mth = TestMethod.class.getMethod("publicVoidVarargs",
- Object[].class);
- assertTrue("Varargs method stated as non vararg.", mth.isVarArgs());
-
- mth = TestMethod.class.getDeclaredMethod("publicVoidArray",
- Object[].class);
- assertFalse("Non varargs method stated as vararg.", mth.isVarArgs());
- }
-
- /**
- * java.lang.reflect.Method#isBridge()
- */
- public void test_isBridge() throws Exception {
- Method[] declaredMethods = BrigeTest.class.getDeclaredMethods();
- assertEquals("Bridge method not generated.", 2, declaredMethods.length);
- boolean foundBridgeMethod = false;
- for (Method method : declaredMethods) {
- if (method.getReturnType().equals(Object.class)) {
- assertTrue("Bridge method not stated as bridge.", method
- .isBridge());
- foundBridgeMethod = true;
- }
- }
- assertTrue("Bridge method not found.", foundBridgeMethod);
- }
-
- /**
- * java.lang.reflect.Method#isSynthetic()
- */
- public void test_isSynthetic() throws Exception {
- Method[] declaredMethods = BrigeTest.class.getDeclaredMethods();
- assertEquals("Synthetic method not generated.", 2,
- declaredMethods.length);
- boolean foundSyntheticMethod = false;
- for (Method method : declaredMethods) {
- if (method.getReturnType().equals(Object.class)) {
- assertTrue("Synthetic method not stated as synthetic.", method
- .isSynthetic());
- foundSyntheticMethod = true;
- }
- }
- assertTrue("Synthetic method not found.", foundSyntheticMethod);
- }
- /**
- * java.lang.reflect.Method#getParameterAnnotations()
- */
- public void test_getParameterAnnotations() throws Exception {
- Method method = TestMethod.class.getDeclaredMethod(
- "annotatedParameter", new Class[] {
- int.class, int.class, int.class});
- Annotation[][] annotations = method.getParameterAnnotations();
- assertEquals(3, annotations.length);
- assertEquals(
- "Wrong number of annotations returned for first parameter", 2,
- annotations[0].length);
- Set<Class<?>> annotationSet = new HashSet<Class<?>>();
- annotationSet.add(annotations[0][0].annotationType());
- annotationSet.add(annotations[0][1].annotationType());
- assertTrue("Missing TestAnno annotation", annotationSet
- .contains(TestAnno.class));
- assertTrue("Missing Deprecated annotation", annotationSet
- .contains(Deprecated.class));
-
- assertEquals(
- "Wrong number of annotations returned for second parameter",
- 1, annotations[1].length);
- annotationSet = new HashSet<Class<?>>();
- annotationSet.add(annotations[1][0].annotationType());
- assertTrue("Missing Deprecated annotation", annotationSet
- .contains(Deprecated.class));
- assertEquals(
- "Wrong number of annotations returned for third parameter", 0,
- annotations[2].length);
- }
-
- /**
- * java.lang.reflect.Method#getDeclaredAnnotations()
- */
- public void test_getDeclaredAnnotations() throws Exception {
- Method method = TestMethod.class.getDeclaredMethod("annotatedMethod");
- Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
- assertEquals(2, declaredAnnotations.length);
-
- Set<Class<?>> annotationSet = new HashSet<Class<?>>();
- annotationSet.add(declaredAnnotations[0].annotationType());
- annotationSet.add(declaredAnnotations[1].annotationType());
- assertTrue("Missing TestAnno annotation", annotationSet
- .contains(TestAnno.class));
- assertTrue("Missing Deprecated annotation", annotationSet
- .contains(Deprecated.class));
- }
-
- /**
- * java.lang.reflect.Method#getDefaultValue()
- */
- public void test_getDefaultValue() throws Exception {
- Method method = TestAnno.class.getDeclaredMethod("value");
- assertEquals("Wrong default value returned", TestAnno.DEFAULT_VALUE,
- method.getDefaultValue());
- }
-
- /**
- * java.lang.reflect.Method#getDefaultValue()
- */
- public void test_getGenericExceptionTypes() throws Exception {
- Method method = ExceptionTest.class.getDeclaredMethod("exceptionTest");
- Type[] genericExceptionTypes = method.getGenericExceptionTypes();
- assertEquals(1, genericExceptionTypes.length);
- assertTrue(genericExceptionTypes[0] instanceof TypeVariable<?>);
- @SuppressWarnings("unchecked")
- TypeVariable<Class<ExceptionTest<?>>> tv =
- (TypeVariable<Class<ExceptionTest<?>>>) genericExceptionTypes[0];
- assertEquals("T", tv.getName());
- }
-
- /**
- * java.lang.reflect.Method#getGenericReturnType()
- */
- public void test_getGenericReturnType() throws Exception {
- Method method = GenericReturnType.class
- .getDeclaredMethod("returnGeneric");
- Type returnType = method.getGenericReturnType();
- assertNotNull("getGenericReturnType returned null", returnType);
- assertTrue(returnType instanceof TypeVariable<?>);
- @SuppressWarnings("unchecked")
- TypeVariable<Class<ExceptionTest<?>>> tv =
- (TypeVariable<Class<ExceptionTest<?>>>) returnType;
- assertEquals("T", tv.getName());
- }
-
-
- /**
- * java.lang.reflect.Method#toGenericString()
- */
- public void test_toGenericString() throws Exception {
- Method method = GenericString.class.getDeclaredMethod("genericString",
- Object.class);
- assertEquals("Wrong generic String returned", GenericString.GENERIC,
- method.toGenericString());
- }
-
-
-
-
-
-
- /**
- * java.lang.reflect.Method#hashCode()
- */
- public void test_hashCode() throws Exception {
- Method mth0 = TestMethod.class.getMethod("hashCodeTest", String.class);
- Method mth1 = TestMethod.class.getDeclaredMethod("hashCodeTest",
- int.class);
- assertEquals("Methods with same name did not return same hashCode.",
- mth0.hashCode(), mth1.hashCode());
- }
-
- /**
- * java.lang.reflect.Method#getParameterTypes()
- */
- public void test_getParameterTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Method.getParameterTypes()
- Class cl = TestMethod.class;
- Method mth = null;
- Class[] parms = null;
- Method[] methods = null;
- Class[] plist = { int.class, short.class, String.class, boolean.class,
- Object.class, long.class, byte.class, char.class, double.class,
- float.class };
- try {
- mth = cl.getMethod("voidMethod", new Class[0]);
- parms = mth.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test: "
- + e.toString());
- }
- assertEquals("Returned incorrect parameterTypes", 0, parms.length);
- try {
- mth = cl.getMethod("parmTest", plist);
- parms = mth.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test: "
- + e.toString());
- }
- assertTrue("Invalid number of parameters returned",
- plist.length == parms.length);
- for (int i = 0; i < plist.length; i++)
- assertTrue("Incorrect parameter returned", plist[i]
- .equals(parms[i]));
-
- // Test same method. but this time pull it from the list of methods
- // rather than asking for it explicitly
- methods = cl.getDeclaredMethods();
-
- int i;
- for (i = 0; i < methods.length; i++)
- if (methods[i].getName().equals("parmTest")) {
- mth = methods[i];
- i = methods.length + 1;
- }
- if (i < methods.length) {
- parms = mth.getParameterTypes();
- assertTrue("Incorrect number of parameters returned",
- parms.length == plist.length);
- for (i = 0; i < plist.length; i++)
- assertTrue("Incorrect parameter returned", plist[i]
- .equals(parms[i]));
- }
- }
-
- /**
- * java.lang.reflect.Method#getReturnType()
- */
- public void test_getReturnType() {
- // Test for method java.lang.Class
- // java.lang.reflect.Method.getReturnType()
- Class cl = TestMethod.class;
- Method mth = null;
- try {
- mth = cl.getMethod("charMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted char", mth
- .getReturnType().equals(char.class));
- try {
- mth = cl.getMethod("longMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted long", mth
- .getReturnType().equals(long.class));
- try {
- mth = cl.getMethod("shortMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted short", mth
- .getReturnType().equals(short.class));
- try {
- mth = cl.getMethod("intMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted int: "
- + mth.getReturnType(), mth.getReturnType().equals(int.class));
- try {
- mth = cl.getMethod("doubleMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted double", mth
- .getReturnType().equals(double.class));
- try {
- mth = cl.getMethod("byteMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted byte", mth
- .getReturnType().equals(byte.class));
- try {
- mth = cl.getMethod("byteMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test:" + e.toString());
- }
- assertTrue("Gave incorrect returne type, wanted byte", mth
- .getReturnType().equals(byte.class));
- try {
- mth = cl.getMethod("objectMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted Object", mth
- .getReturnType().equals(Object.class));
-
- try {
- mth = cl.getMethod("voidMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted void", mth
- .getReturnType().equals(void.class));
- }
-
- /**
- * java.lang.reflect.Method#invoke(java.lang.Object,
- * java.lang.Object[])
- */
- public void test_invokeLjava_lang_Object$Ljava_lang_Object() throws Exception{
- // Test for method java.lang.Object
- // java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object
- // [])
- Class cl = TestMethod.class;
- Class[] dcl = new Class[0];
-
- // Get and invoke a static method
- Method mth = cl.getDeclaredMethod("invokeStaticTest", dcl);
- Object ret = mth.invoke(null, new Object[0]);
- assertEquals("Invoke returned incorrect value", 1, ((Integer) ret)
- .intValue());
-
- // Get and invoke an instance method
- mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
- ret = mth.invoke(new TestMethod(), new Object[0]);
- assertEquals("Invoke returned incorrect value", 1, ((Integer) ret)
- .intValue());
-
- // Get and attempt to invoke a private method
- mth = cl.getDeclaredMethod("privateInvokeTest", dcl);
- try {
- ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (IllegalAccessException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
- // Generate an IllegalArgumentException
- mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
-
- try {
- Object[] args = { Object.class };
- ret = mth.invoke(new TestMethod(), args);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
-
- // Generate a NullPointerException
- mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
-
- try {
- ret = mth.invoke(null, new Object[0]);
- } catch (NullPointerException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
-
- // Generate an InvocationTargetException
- mth = cl.getDeclaredMethod("invokeExceptionTest", dcl);
- try {
- ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
-
- TestMethod testMethod = new TestMethod();
- Method methods[] = cl.getMethods();
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().startsWith("invokeCastTest1")) {
- Class param = methods[i].getParameterTypes()[0];
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Byte(
- (byte) 1) });
- assertTrue("invalid invoke with Byte: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Byte invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Byte invalid failure: " + methods[i],
- param == Boolean.TYPE || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Short(
- (short) 1) });
- assertTrue("invalid invoke with Short: " + methods[i],
- param == Short.TYPE || param == Integer.TYPE
- || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Short invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Short invalid failure: " + methods[i],
- param == Byte.TYPE || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod,
- new Object[] { new Integer(1) });
- assertTrue("invalid invoke with Integer: " + methods[i],
- param == Integer.TYPE || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Integer invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Integer invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Long(1) });
- assertTrue("invalid invoke with Long: " + methods[i],
- param == Long.TYPE || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Long invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Long invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Character(
- 'a') });
- assertTrue("invalid invoke with Character: " + methods[i],
- param == Character.TYPE || param == Integer.TYPE
- || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Character invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Character invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Boolean.TYPE);
- }
-
- try {
- methods[i]
- .invoke(testMethod, new Object[] { new Float(1) });
- assertTrue("invalid invoke with Float: " + methods[i],
- param == Float.TYPE || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Float invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Float invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod,
- new Object[] { new Double(1) });
- assertTrue("invalid invoke with Double: " + methods[i],
- param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Double invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Double invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE
- || param == Float.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Boolean(
- true) });
- assertTrue("invalid invoke with Boolean: " + methods[i],
- param == Boolean.TYPE);
- } catch (Exception e) {
- assertTrue("Boolean invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Boolean invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Character.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- }
- }
- }
- }
-
- /**
- * java.lang.reflect.Method#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.lang.reflect.Method.toString()
- Method mth = null;
- Class[] parms = { int.class, short.class, String.class, boolean.class,
- Object.class, long.class, byte.class, char.class, double.class,
- float.class };
- try {
-
- mth = TestMethod.class.getDeclaredMethod("printTest", parms);
- } catch (Exception e) {
- fail("Exception during toString test : " + e.getMessage());
- }
-
- assertTrue(
- "Returned incorrect string for method: " + mth.toString(),
- mth
- .toString()
- .equals(
- "public static final void tests.api.java.lang.reflect.MethodTest$TestMethod.printTest(int,short,java.lang.String,boolean,java.lang.Object,long,byte,char,double,float)"));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
deleted file mode 100644
index fcb9042..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
+++ /dev/null
@@ -1,77 +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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-
-/**
- * Tests parameterized types and their properties.
- */
-public class ParameterizedTypeTest extends GenericReflectionTestsBase {
-
- static class A<T>{}
- static class B extends A<String>{}
-
- public void testStringParameterizedSuperClass() {
- Class<? extends B> clazz = B.class;
- Type genericSuperclass = clazz.getGenericSuperclass();
- assertInstanceOf(ParameterizedType.class, genericSuperclass);
- ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
- assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
- assertEquals(A.class, parameterizedType.getRawType());
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertEquals(String.class, actualTypeArguments[0]);
- }
-
- static class C<T>{}
- static class D<T> extends C<T>{}
-
- public void testTypeParameterizedSuperClass() {
- Class<? extends D> clazz = D.class;
- Type genericSuperclass = clazz.getGenericSuperclass();
- assertInstanceOf(ParameterizedType.class, genericSuperclass);
- ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
- assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
- assertEquals(C.class, parameterizedType.getRawType());
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertEquals(getTypeParameter(D.class), actualTypeArguments[0]);
- }
-
- static class E<T>{}
- static class F<T>{
- E<T> e;
- }
-
- public void testParameterizedMemeber() throws Exception{
- Class<? extends F> clazz = F.class;
- Field field = clazz.getDeclaredField("e");
- assertInstanceOf(ParameterizedType.class, field.getGenericType());
- ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
- assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
- assertEquals(E.class, parameterizedType.getRawType());
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertEquals(getTypeParameter(clazz), actualTypeArguments[0]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
deleted file mode 100644
index dd496b1..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
+++ /dev/null
@@ -1,319 +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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.lang.reflect.UndeclaredThrowableException;
-
-import tests.support.Support_Proxy_I1;
-import tests.support.Support_Proxy_I2;
-import tests.support.Support_Proxy_ParentException;
-import tests.support.Support_Proxy_SubException;
-
-public class ProxyTest extends junit.framework.TestCase {
-
- /*
- * When multiple interfaces define the same method, the list of thrown
- * exceptions are those which can be mapped to another exception in the
- * other method:
- *
- * String foo(String s) throws SubException, LinkageError;
- *
- * UndeclaredThrowableException wrappers any checked exception which is not
- * in the merged list. So ParentException would be wrapped, BUT LinkageError
- * would not be since its not an Error/RuntimeException.
- *
- * interface I1 { String foo(String s) throws ParentException, LinkageError; }
- * interface I2 { String foo(String s) throws SubException, Error; }
- */
-
- interface Broken1 {
- public float method(float _number0, float _number1);
- }
-
- class Broken1Invoke implements InvocationHandler {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return args[1];
- }
- }
-
- class ProxyCoonstructorTest extends Proxy {
- protected ProxyCoonstructorTest(InvocationHandler h) {
- super(h);
- }
- }
-
- /**
- * java.lang.reflect.Proxy#getProxyClass(java.lang.ClassLoader,
- * java.lang.Class[])
- */
- public void test_getProxyClassLjava_lang_ClassLoader$Ljava_lang_Class() {
- Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class });
-
- assertTrue("Did not create a Proxy subclass ",
- proxy.getSuperclass() == Proxy.class);
- assertTrue("Does not believe its a Proxy class ", Proxy
- .isProxyClass(proxy));
-
- assertTrue("Does not believe it's a Proxy class ", Proxy
- .isProxyClass(Proxy.getProxyClass(null,
- new Class[] { Comparable.class })));
-
- try {
- Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(),
- (Class<?>[]) null);
- fail("NPE expected");
- } catch (NullPointerException expected) {
- }
-
- try {
- Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(),
- new Class<?>[] {Support_Proxy_I1.class, null});
- fail("NPE expected");
- } catch (NullPointerException expected) {
- }
- }
-
- /**
- * java.lang.reflect.Proxy#Proxy(java.lang.reflect.InvocationHandler)
- */
- public void test_ProxyLjava_lang_reflect_InvocationHandler() {
- assertNotNull(new ProxyCoonstructorTest(new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return null;
- }
- }));
- }
-
-
-
- /**
- * java.lang.reflect.Proxy#newProxyInstance(java.lang.ClassLoader,
- * java.lang.Class[], java.lang.reflect.InvocationHandler)
- */
- public void test_newProxyInstanceLjava_lang_ClassLoader$Ljava_lang_ClassLjava_lang_reflect_InvocationHandler() {
- Object p = Proxy.newProxyInstance(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class,
- Support_Proxy_I2.class }, new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- if (method.getName().equals("equals"))
- return new Boolean(proxy == args[0]);
- if (method.getName().equals("array"))
- return new int[] { (int) ((long[]) args[0])[1], -1 };
- if (method.getName().equals("string")) {
- if ("".equals(args[0]))
- throw new Support_Proxy_SubException();
- if ("clone".equals(args[0]))
- throw new Support_Proxy_ParentException();
- if ("error".equals(args[0]))
- throw new ArrayStoreException();
- if ("any".equals(args[0]))
- throw new IllegalAccessException();
- }
- return null;
- }
- });
-
- Support_Proxy_I1 proxy = (Support_Proxy_I1) p;
- assertTrue("Failed identity test ", proxy.equals(proxy));
- assertTrue("Failed not equals test ", !proxy.equals(""));
- int[] result = (int[]) proxy.array(new long[] { 100L, -200L });
- assertEquals("Failed primitive type conversion test ", -200, result[0]);
-
- boolean worked = false;
- try {
- proxy.string("");
- } catch (Support_Proxy_SubException e) {
- worked = true;
- } catch (Support_Proxy_ParentException e) { // is never thrown
- }
- assertTrue("Problem converting exception ", worked);
-
- worked = false;
- try {
- proxy.string("clone");
- } catch (Support_Proxy_ParentException e) { // is never thrown
- } catch (UndeclaredThrowableException e) {
- worked = true;
- }
- assertTrue("Problem converting exception ", worked);
-
- worked = false;
- try {
- proxy.string("error");
- } catch (Support_Proxy_ParentException e) { // is never thrown
- } catch (UndeclaredThrowableException e) {
- } catch (RuntimeException e) {
- worked = e.getClass() == ArrayStoreException.class;
- }
- assertTrue("Problem converting exception ", worked);
-
- worked = false;
- try {
- proxy.string("any");
- } catch (Support_Proxy_ParentException e) { // is never thrown
- } catch (UndeclaredThrowableException e) {
- worked = true;
- }
- assertTrue("Problem converting exception ", worked);
-
- Broken1 proxyObject = null;
- try {
- proxyObject = (Broken1) Proxy.newProxyInstance(Broken1.class
- .getClassLoader(), new Class[] { Broken1.class },
- new Broken1Invoke());
- } catch (Throwable e) {
- fail("Failed to create proxy for class: " + Broken1.class + " - "
- + e);
- }
- float brokenResult = proxyObject.method(2.1f, 5.8f);
- assertTrue("Invalid invoke result", brokenResult == 5.8f);
- }
-
- /**
- * java.lang.reflect.Proxy#isProxyClass(java.lang.Class)
- */
- public void test_isProxyClassLjava_lang_Class() {
- Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class });
-
- class Fake extends Proxy {
- Fake() {
- super(null);
- }
- }
-
- Proxy fake = new Proxy(new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return null;
- }
- }) {
- };
-
- assertTrue("Does not believe its a Proxy class ", Proxy
- .isProxyClass(proxy));
- assertTrue("Proxy subclasses do not count ", !Proxy
- .isProxyClass(Fake.class));
- assertTrue("Is not a runtime generated Proxy class ", !Proxy
- .isProxyClass(fake.getClass()));
- boolean thrown = false;
- try{
- Proxy.isProxyClass(null);
- } catch (NullPointerException ex){
- thrown = true;
- }
- assertTrue("NPE not thrown.", thrown);
- }
-
- /**
- * java.lang.reflect.Proxy#getInvocationHandler(java.lang.Object)
- */
- public void test_getInvocationHandlerLjava_lang_Object() {
- InvocationHandler handler = new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return null;
- }
- };
-
- Object p = Proxy.newProxyInstance(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class },
- handler);
-
- assertTrue("Did not return invocation handler ", Proxy
- .getInvocationHandler(p) == handler);
- boolean aborted = false;
- try {
- Proxy.getInvocationHandler("");
- } catch (IllegalArgumentException e) {
- aborted = true;
- }
- assertTrue("Did not detect non proxy object ", aborted);
- }
-
- //Regression Test for HARMONY-2355
- public void test_newProxyInstance_withCompatibleReturnTypes() {
- Object o = Proxy
- .newProxyInstance(this.getClass().getClassLoader(),
- new Class[] { ITestReturnObject.class,
- ITestReturnString.class },
- new TestProxyHandler(new TestProxyImpl()));
- assertNotNull(o);
- }
-
- public void test_newProxyInstance_withNonCompatibleReturnTypes() {
- try {
- Proxy.newProxyInstance(this.getClass().getClassLoader(),
- new Class[] { ITestReturnInteger.class,
- ITestReturnString.class }, new TestProxyHandler(
- new TestProxyImpl()));
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- public static interface ITestReturnObject {
- Object f();
- }
-
- public static interface ITestReturnString {
- String f();
- }
-
- public static interface ITestReturnInteger {
- Integer f();
- }
-
- public static class TestProxyImpl implements ITestReturnObject,
- ITestReturnString {
- public String f() {
- // do nothing
- return null;
- }
- }
-
- public static class TestProxyHandler implements InvocationHandler {
- private Object proxied;
-
- public TestProxyHandler(Object object) {
- proxied = object;
- }
-
- public Object invoke(Object object, Method method, Object[] args)
- throws Throwable {
- // do nothing
- return method.invoke(proxied, args);
- }
-
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java b/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java
deleted file mode 100644
index cc22852..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java
+++ /dev/null
@@ -1,150 +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 tests.api.java.lang.reflect;
-
-import java.io.Serializable;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Tests type variables and their properties.
- */
-public class TypeVariableTest extends GenericReflectionTestsBase {
-
- static class A<T>{}
- public void testSimpleTypeVariableOnClass(){
- Class<? extends A> clazz = A.class;
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Class> typeVariable = typeParameters[0];
- assertEquals(clazz, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Object.class, bounds[0]);
- }
-
- static class B{
- <T> void b(){};
- }
- public void testSimpleTypeVariableOnMethod() throws Exception{
- Class<? extends B> clazz = B.class;
- Method method = clazz.getDeclaredMethod("b");
- TypeVariable<Method>[] typeParameters = method.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Method> typeVariable = typeParameters[0];
- assertEquals(method, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Object.class, bounds[0]);
- }
-
- static class C {
- <T>C(){}
- }
- public void testSimpleTypeVariableOnConstructor() throws Exception{
- Class<? extends C> clazz = C.class;
- Constructor<?> constructor = clazz.getDeclaredConstructor();
- TypeVariable<?>[] typeParameters = constructor.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<?> typeVariable = typeParameters[0];
- assertEquals(constructor, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Object.class, bounds[0]);
- }
-
- static class D<Q,R,S>{}
- public void testMultipleTypeVariablesOnClass() throws Exception {
- Class<? extends D> clazz = D.class;
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertEquals(3, typeParameters.length);
- assertEquals("Q", typeParameters[0].getName());
- assertEquals(clazz, typeParameters[0].getGenericDeclaration());
-
- assertEquals("R", typeParameters[1].getName());
- assertEquals(clazz, typeParameters[1].getGenericDeclaration());
-
- assertEquals("S", typeParameters[2].getName());
- assertEquals(clazz, typeParameters[2].getGenericDeclaration());
-
- }
-
- static class E {
- <Q,R,S> void e(){}
- }
- public void testMultipleTypeVariablesOnMethod() throws Exception {
- Class<? extends E> clazz = E.class;
- Method method = clazz.getDeclaredMethod("e");
-
- TypeVariable<?>[] typeParameters = method.getTypeParameters();
- assertEquals(3, typeParameters.length);
- assertEquals("Q", typeParameters[0].getName());
- assertEquals(method, typeParameters[0].getGenericDeclaration());
-
- assertEquals("R", typeParameters[1].getName());
- assertEquals(method, typeParameters[1].getGenericDeclaration());
-
- assertEquals("S", typeParameters[2].getName());
- assertEquals(method, typeParameters[2].getGenericDeclaration());
- }
-
- static class F {
- <Q,R,S> F(){}
- }
- public void testMultipleTypeVariablesOnConstructor() throws Exception {
- Class<? extends F> clazz = F.class;
- Constructor<?> constructor = clazz.getDeclaredConstructor();
-
- TypeVariable<?>[] typeParameters = constructor.getTypeParameters();
- assertEquals(3, typeParameters.length);
- assertEquals("Q", typeParameters[0].getName());
- assertEquals(constructor, typeParameters[0].getGenericDeclaration());
-
- assertEquals("R", typeParameters[1].getName());
- assertEquals(constructor, typeParameters[1].getGenericDeclaration());
-
- assertEquals("S", typeParameters[2].getName());
- assertEquals(constructor, typeParameters[2].getGenericDeclaration());
- }
-
- static class G <T extends Number>{}
-
- public void testSingleBound() throws Exception {
- Class<? extends G> clazz = G.class;
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- TypeVariable<Class> typeVariable = typeParameters[0];
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Number.class, bounds[0]);
- }
-
- static class H <T extends Number & Serializable >{}
- public void testMultipleBound() throws Exception {
- Class<? extends H> clazz = H.class;
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- TypeVariable<Class> typeVariable = typeParameters[0];
- Type[] bounds = typeVariable.getBounds();
- assertEquals(2, bounds.length);
- assertEquals(Number.class, bounds[0]);
- assertEquals(Serializable.class, bounds[1]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java b/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java
deleted file mode 100644
index 8fd2ff3..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package tests.api.java.lang.reflect;
-
-import junit.framework.TestCase;
-
-import java.io.EOFException;
-import java.lang.reflect.UndeclaredThrowableException;
-
-public class UndeclaredThrowableExceptionTests extends TestCase {
-
- private static EOFException throwable = new EOFException();
- private static String msg = "TEST_MSG";
- /**
- * java.lang.reflect.UndeclaredThrowableException#getCause()
- */
- public void test_getCause() throws Exception {
- UndeclaredThrowableException ute = new UndeclaredThrowableException(
- throwable);
- assertSame("Wrong cause returned", throwable, ute.getCause());
- }
-
- /**
- * java.lang.reflect.UndeclaredThrowableException#getUndeclaredThrowable()
- */
- public void test_getUndeclaredThrowable() throws Exception {
- UndeclaredThrowableException ute = new UndeclaredThrowableException(
- throwable);
- assertSame("Wrong undeclared throwable returned", throwable, ute
- .getUndeclaredThrowable());
- }
-
- /**
- * java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable)
- */
- public void test_Constructor_Throwable() throws Exception {
- UndeclaredThrowableException e = new UndeclaredThrowableException(
- throwable);
- assertEquals("Wrong cause returned", throwable, e.getCause());
- assertEquals("Wrong throwable returned", throwable, e
- .getUndeclaredThrowable());
- }
-
- /**
- * java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable, java.lang.String)
- */
- public void test_Constructor_Throwable_String() throws Exception {
- UndeclaredThrowableException e = new UndeclaredThrowableException(
- throwable, msg);
- assertEquals("Wrong cause returned", throwable, e.getCause());
- assertEquals("Wrong throwable returned", throwable, e
- .getUndeclaredThrowable());
- assertEquals("Wrong message returned", msg, e.getMessage());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java
deleted file mode 100644
index 9f8baeb..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java
+++ /dev/null
@@ -1,151 +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 tests.api.java.lang.reflect;
-
-
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.lang.reflect.WildcardType;
-
-/**
- * Tests bounded type parameters declared on methods and bounded wildcards.
- */
-public class WildcardTypeTest extends GenericReflectionTestsBase {
- @SuppressWarnings({"unchecked", "hiding"})
- static class BoundedWildcardsGenericMethods<T> {
-
- public <T extends BoundedWildcardsGenericMethods> void lowerBoundedParamNoReturn( BoundedWildcardsGenericMethods<? super T> param) {}
-
- public <T extends BoundedWildcardsGenericMethods> void upperBoundedParamNoReturn( BoundedWildcardsGenericMethods<? extends T> param) {}
-
- public <T extends BoundedWildcardsGenericMethods> T lowerBoundedParamReturn(BoundedWildcardsGenericMethods<? super T> param) { return (T) new Object(); }
-
- public <T extends BoundedWildcardsGenericMethods> T upperBoundedParamReturn(BoundedWildcardsGenericMethods<? extends T> param) { return (T) new Object();}
- }
-
- @SuppressWarnings("unchecked")
- private static Class<? extends BoundedWildcardsGenericMethods> clazz = BoundedWildcardsGenericMethods.class;
-
- /**
- * Tests that there are is one Type Parameter on the Class itself.
- */
- public void testBoundedGenericMethods() {
- assertLenghtOne(clazz.getTypeParameters());
- }
-
- /**
- * Tests whether the type parameter is bounded by BoundedGenericMethods like:
- * <T extends BoundedGenericMethods>.
- * @param method the declaring method
- */
- private void checkBoundedTypeParameter(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertEquals("T", typeParameter.getName());
- assertEquals(method, typeParameter.getGenericDeclaration());
-
- Type[] bounds = typeParameter.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
- assertEquals(BoundedWildcardsGenericMethods.class, bound);
- }
-
- private void checkLowerBoundedParameter(Method method) {
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertInstanceOf(ParameterizedType.class, genericParameterType);
-
- ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
-
- WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
-
- Type[] lowerBounds = wildcardType.getLowerBounds();
- assertLenghtOne(lowerBounds);
- Type lowerBound = lowerBounds[0];
- assertEquals(getTypeParameter(method), lowerBound);
-
- Type[] upperBounds = wildcardType.getUpperBounds();
- assertEquals(Object.class, upperBounds[0]);
- }
-
- private void checkUpperBoundedParameter(Method method) {
- assertLenghtOne(method.getGenericParameterTypes());
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertInstanceOf(ParameterizedType.class, genericParameterType);
-
- ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
-
- WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
- assertLenghtZero(wildcardType.getLowerBounds());
-
- Type[] upperBounds = wildcardType.getUpperBounds();
- assertLenghtOne(upperBounds);
- Type upperBound = upperBounds[0];
- assertEquals(getTypeParameter(method), upperBound);
- }
-
- @SuppressWarnings("unchecked")
- private void checkReturnType(Method method) {
- Type genericReturnType = method.getGenericReturnType();
- assertEquals(getTypeParameter(method), genericReturnType);
- assertTrue(genericReturnType instanceof TypeVariable);
-
- TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
- assertEquals(method, returnTypeVariable.getGenericDeclaration());
-
- Type[] bounds = returnTypeVariable.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
-
- assertEquals(BoundedWildcardsGenericMethods.class, bound);
- }
-
- public void testUpperBoundedParamNoReturn() throws Exception {
- Method method = clazz.getMethod("upperBoundedParamNoReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- checkUpperBoundedParameter(method);
- }
-
- public void testLowerBoundedParamReturn() throws Exception {
- Method method = clazz.getMethod("lowerBoundedParamReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- checkLowerBoundedParameter(method);
- checkReturnType(method);
- }
-
- public void testUpperBoundedParamReturn() throws Exception {
- Method method = clazz.getMethod("upperBoundedParamReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- checkUpperBoundedParameter(method);
- checkReturnType(method);
- }
-
- public void testLowerBoundedParamNoReturn() throws Exception {
- Method method = clazz.getMethod("lowerBoundedParamNoReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- assertLenghtOne(method.getGenericParameterTypes());
- checkLowerBoundedParameter(method);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/math/MathContextTest.java b/luni/src/test/java/tests/api/java/math/MathContextTest.java
deleted file mode 100644
index 9e04342..0000000
--- a/luni/src/test/java/tests/api/java/math/MathContextTest.java
+++ /dev/null
@@ -1,79 +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 tests.api.java.math;
-
-import java.math.BigDecimal;
-import java.math.MathContext;
-import java.math.RoundingMode;
-
-public class MathContextTest extends junit.framework.TestCase {
-
- /**
- * java.math.MathContext#MathContext(...)
- */
- public void test_MathContextConstruction() {
- String a = "-12380945E+61";
- BigDecimal aNumber = new BigDecimal(a);
- MathContext mcIntRm6hd = new MathContext(6, RoundingMode.HALF_DOWN);
- MathContext mcStr6hd = new MathContext("precision=6 roundingMode=HALF_DOWN");
- MathContext mcInt6 = new MathContext(6);
- MathContext mcInt134 = new MathContext(134);
-
- // getPrecision()
- assertEquals("MathContext.getPrecision() returns incorrect value",
- 6, mcIntRm6hd.getPrecision() );
- assertEquals("MathContext.getPrecision() returns incorrect value",
- 134, mcInt134.getPrecision() );
-
- // getRoundingMode()
- assertEquals("MathContext.getRoundingMode() returns incorrect value",
- RoundingMode.HALF_UP,
- mcInt6.getRoundingMode());
- assertEquals("MathContext.getRoundingMode() returns incorrect value",
- RoundingMode.HALF_DOWN, mcIntRm6hd.getRoundingMode() );
-
- // toString()
- assertEquals("MathContext.toString() returning incorrect value",
- "precision=6 roundingMode=HALF_DOWN", mcIntRm6hd.toString() );
- assertEquals("MathContext.toString() returning incorrect value",
- "precision=6 roundingMode=HALF_UP", mcInt6.toString() );
-
- // equals(.)
- assertEquals("Equal MathContexts are not equal ",
- mcIntRm6hd, mcStr6hd );
- assertFalse("Different MathContexts are reported as equal ",
- mcInt6.equals(mcStr6hd) );
- assertFalse("Different MathContexts are reported as equal ",
- mcInt6.equals(mcInt134) );
-
- // hashCode(.)
- assertEquals("Equal MathContexts have different hashcodes ",
- mcIntRm6hd.hashCode(), mcStr6hd.hashCode() );
- assertFalse("Different MathContexts have equal hashcodes ",
- mcInt6.hashCode() == mcStr6hd.hashCode() );
- assertFalse("Different MathContexts have equal hashcodes ",
- mcInt6.hashCode() == mcInt134.hashCode() );
-
- // other:
- BigDecimal res = aNumber.abs(mcInt6);
- assertEquals("MathContext Constructor with int precision failed",
- new BigDecimal("1.23809E+68"),
- res);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java b/luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java
deleted file mode 100644
index 167ebe8..0000000
--- a/luni/src/test/java/tests/api/java/math/OldBigIntegerTest.java
+++ /dev/null
@@ -1,372 +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 tests.api.java.math;
-
-import java.math.BigInteger;
-import java.util.Random;
-
-public class OldBigIntegerTest extends junit.framework.TestCase {
-
- BigInteger minusOne = new BigInteger("-1", 10);
-
- BigInteger two = new BigInteger("2", 10);
-
- BigInteger aZillion = new BigInteger("100000000000000000000000000000000000000000000000000", 10);
-
- Random rand = new Random();
-
- BigInteger bi;
-
- BigInteger bi2;
-
- BigInteger bi3;
-
- /**
- * java.math.BigInteger#BigInteger(int, java.util.Random)
- */
- public void test_ConstructorILjava_util_Random() {
- // regression test for HARMONY-1047
- try {
- new BigInteger(128, (Random) null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- bi = new BigInteger(70, rand);
- bi2 = new BigInteger(70, rand);
- assertTrue("Random number is negative", bi.compareTo(BigInteger.ZERO) >= 0);
- assertTrue("Random number is too big", bi.compareTo(two.pow(70)) < 0);
- assertTrue(
- "Two random numbers in a row are the same (might not be a bug but it very likely is)",
- !bi.equals(bi2));
- assertTrue("Not zero", new BigInteger(0, rand).equals(BigInteger.ZERO));
-
- try {
- new BigInteger(-1, (Random)null);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // PASSED
- }
- }
-
- /**
- * java.math.BigInteger#BigInteger(int, int, java.util.Random)
- */
- // BIGNUM returns no Primes smaller than 16 bits.
- public void test_ConstructorIILjava_util_Random() {
- BigInteger bi1 = new BigInteger(10, 5, rand);
- BigInteger bi2 = new BigInteger(10, 5, rand);
- assertTrue(bi1 + " is negative", bi1.compareTo(BigInteger.ZERO) >= 0);
- assertTrue(bi1 + " is too big", bi1.compareTo(new BigInteger("1024", 10)) < 0);
- assertTrue(bi2 + " is negative", bi2.compareTo(BigInteger.ZERO) >= 0);
- assertTrue(bi2 + " is too big", bi2.compareTo(new BigInteger("1024", 10)) < 0);
-
- Random rand = new Random();
- BigInteger bi;
- int certainty[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -2, -1 };
- for (int i = 2; i <= 20; i++) {
- for (int c = 0; c < certainty.length; c++) {
- bi = new BigInteger(i, c, rand); // Create BigInteger
- assertEquals(i, bi.bitLength());
- }
- }
-
- try {
- new BigInteger(1, 80, (Random)null);
- fail("ArithmeticException expected");
- } catch (ArithmeticException expected) {
- }
-
- try {
- new BigInteger(-1, (Random)null);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException expected) {
- }
- }
-
-// public void test_SpecialPrimes() {
-// System.out.println("test_SpecialPrimes");
-// final BigInteger TWO = BigInteger.valueOf(2);
-// BigInteger p, q;
-// for (;;) {
-// p = new BigInteger(1024, 23, new Random());
-// q = p.subtract(BigInteger.ONE).divide(TWO);
-// if (q.isProbablePrime(20)) {
-// System.out.println(q);
-// System.out.println(p);
-// break;
-// }
-// System.out.print(".");
-// }
-// fail("isProbablePrime failed for: " + bi);
-// }
-
- /**
- * java.math.BigInteger#isProbablePrime(int)
- */
- public void test_isProbablePrimeI() {
- int fails = 0;
- bi = new BigInteger(20, 20, rand);
- if (!bi.isProbablePrime(17)) {
- fails++;
- }
- bi = new BigInteger("4", 10);
- if (bi.isProbablePrime(17)) {
- fail("isProbablePrime failed for: " + bi);
- }
- bi = BigInteger.valueOf(17L * 13L);
- if (bi.isProbablePrime(17)) {
- fail("isProbablePrime failed for: " + bi);
- }
- for (long a = 2; a < 1000; a++) {
- if (isPrime(a)) {
- assertTrue("false negative on prime number <1000", BigInteger
- .valueOf(a).isProbablePrime(5));
- } else if (BigInteger.valueOf(a).isProbablePrime(17)) {
- System.out.println("isProbablePrime failed for: " + a);
- fails++;
- }
- }
- for (int a = 0; a < 1000; a++) {
- bi = BigInteger.valueOf(rand.nextInt(1000000)).multiply(
- BigInteger.valueOf(rand.nextInt(1000000)));
- if (bi.isProbablePrime(17)) {
- System.out.println("isProbablePrime failed for: " + bi);
- fails++;
- }
- }
- for (int a = 0; a < 200; a++) {
- bi = new BigInteger(70, rand).multiply(new BigInteger(70, rand));
- if (bi.isProbablePrime(17)) {
- System.out.println("isProbablePrime failed for: " + bi);
- fails++;
- }
- }
- assertTrue("Too many false positives - may indicate a problem",
- fails <= 1);
-
- //
- // And now some tests on real big integers:
- //
- bi = new BigInteger("153890972191202256150310830154922163807316525358455215516067727076235016932726922093888770552128767458882963869421440585369743", 10);
- if (!bi.isProbablePrime(80)) {
- fail("isProbablePrime failed for: " + bi);
- }
- bi = new BigInteger("2090575416269141767246491983797422123741252476560371649798066134123893524014911825188890458270426076468664046568752890122415061377308817346303546688282957897504000216241497550243010257911214329646877810655164658470278901030511157372440751259674247310396158238588463284702737181653", 10);
- if (!bi.isProbablePrime(80)) {
- fail("isProbablePrime failed for: " + bi);
- }
- //
- for (int bitLength = 100; bitLength <= 600; bitLength += 100) {
- BigInteger a = BigInteger.probablePrime(bitLength, rand);
- BigInteger b = BigInteger.probablePrime(bitLength, rand);
- BigInteger c = a.multiply(b);
- assertFalse("isProbablePrime failed for product of two large primes" +
- a + " * " + b + " = " + c +
- " (bitLength = " + bitLength + ")",
- c.isProbablePrime(80) );
- }
- }
-
- /**
- * java.math.BigInteger#nextProbablePrime()
- */
- public void test_nextProbablePrime() {
- largePrimesProduct(
- new BigInteger("2537895984043447429238717358455377929009126353874925049325287329295635198252046158619999217453233889378619619008359011789"),
- new BigInteger("1711501451602688337873833423534849678524059393231999670806585630179374689152366029939952735718718709436427337762082614710093"),
- "4343612660706993434504106787562106084038357258130862545477481433639575850237346784798851102536616749334772541987502120552264920040629526028540204698334741815536099373917351194423681128374184971846099257056996626343051832131340568120612204287123"
- );
-
- largePrimesProduct(
- new BigInteger("4617974730611208463200675282934641082129817404749925308887287017217158545765190433369842932770197341032031682222405074564586462802072184047198214312142847809259437477387527466762251087500170588962277514858557309036550499896961735701485020851"),
- new BigInteger("4313158964405728158057980867015758419530142215799386331265837224051830838583266274443105715022196238165196727467066901495701708590167750818040112544031694506528759169669442493029999154074962566165293254671176670719518898684698255068313216294333"),
- "19918059106734861363335842730108905466210762564765297409619920041621379008685530738918145604092111306972524565803236031571858280032420140331838737621152630780261815015157696362550138161774466814661069892975003440654998880587960037013294137372709096788892473385003457361736563927256562678181177287998121131179907762285048659075843995525830945659905573174849006768920618442371027575308854641789533211132313916836205357976988977849024687805212304038260207820679964201211309384057458137851"
- );
- }
-
- static void largePrimesProduct(BigInteger a, BigInteger b, String c) {
- BigInteger wp = a.multiply(b);
- assertFalse("isProbablePrime failed for product of two large primes" +
- a + " * " + b + " = " + c,
- wp.isProbablePrime(80) );
- BigInteger wpMinusOne = wp.subtract(BigInteger.ONE);
- BigInteger next = wpMinusOne.nextProbablePrime();
-// System.out.println(c);
-// System.out.println(next);
- assertTrue("nextProbablePrime returns wrong number: " + next +
- "instead of expected: " + c,
- next.toString().equals(c) );
- }
-
- /**
- * java.math.BigInteger#probablePrime(int, java.util.Random)
- */
- public void test_probablePrime() {
- for (int bitLength = 50; bitLength <= 1050; bitLength += 100) {
- BigInteger a = BigInteger.probablePrime(bitLength, rand);
- assertTrue("isProbablePrime(probablePrime()) failed for: " + bi,
- a.isProbablePrime(80));
-// System.out.println(a);
-// BigInteger prime = a.nextProbablePrime();
-// System.out.print("Next Probable Prime is ");
-// System.out.println(prime);
- }
- }
-
-// BEGIN android-added
-// public void testModPowPerformance() {
-// Random rnd = new Random();
-// for (int i = 0; i < 10; i++) {
-// BigInteger a = new BigInteger(512, rnd);
-// BigInteger m = new BigInteger(1024, rnd);
-// BigInteger p = new BigInteger(256, rnd);
-// BigInteger mp = a.modPow(p, m);
-// System.out.println(mp);
-// }
-// }
-
-// shows factor 20 speed up (BIGNUM to Harmony Java):
-// public void testNextProbablePrime() {
-// Random rnd = new Random();
-// rnd.setSeed(0);
-// for (int i = 1; i <= 32; i += 1) {
-// BigInteger a = new BigInteger(i, rnd);
-// System.out.println(a);
-// BigInteger prime = a.nextProbablePrime();
-// System.out.print("Next Probable Prime is ");
-// System.out.println(prime);
-// }
-// for (int i = 1; i <= 32; i += 4) {
-// BigInteger a = new BigInteger(32 * i, rnd);
-// System.out.println(a);
-// BigInteger prime = a.nextProbablePrime();
-// System.out.print("Next Probable Prime is ");
-// System.out.println(prime);
-// }
-// }
-
-// shows factor 20 speed up (BIGNUM to Harmony Java):
-// shows that certainty 80 is "practically aquivalent" to certainty 100
-// public void testPrimeGenPerformance() {
-// Random rnd = new Random();
-// rnd.setSeed(0);
-// for (int i = 1; i <= 32; i +=8 ) {
-// BigInteger a = new BigInteger(32 * i, 80, rnd);
-// System.out.println(a);
-// System.out.println("Now testing it again:");
-// if (a.isProbablePrime(100)) {
-// System.out.println("************************ PASSED! **************************");
-// } else {
-// System.out.println("************************ FAILED!!! **************************");
-// System.out.println("************************ FAILED!!! **************************");
-// System.out.println("************************ FAILED!!! **************************");
-// System.out.println("************************ FAILED!!! **************************");
-// System.out.println("************************ FAILED!!! **************************");
-// System.out.println("************************ FAILED!!! **************************");
-// }
-// }
-// }
-// END android-added
-
-
-
- /**
- * java.math.BigInteger#add(java.math.BigInteger)
- */
- public void test_addLjava_math_BigInteger() {
- assertTrue("Incorrect sum--wanted a zillion", aZillion.add(aZillion)
- .add(aZillion.negate()).equals(aZillion));
- assertTrue("0+0", BigInteger.ZERO.add(BigInteger.ZERO).equals(BigInteger.ZERO));
- assertTrue("0+1", BigInteger.ZERO.add(BigInteger.ONE).equals(BigInteger.ONE));
- assertTrue("1+0", BigInteger.ONE.add(BigInteger.ZERO).equals(BigInteger.ONE));
- assertTrue("1+1", BigInteger.ONE.add(BigInteger.ONE).equals(two));
- assertTrue("0+(-1)", BigInteger.ZERO.add(minusOne).equals(minusOne));
- assertTrue("(-1)+0", minusOne.add(BigInteger.ZERO).equals(minusOne));
- assertTrue("(-1)+(-1)", minusOne.add(minusOne).equals(new BigInteger("-2", 10)));
- assertTrue("1+(-1)", BigInteger.ONE.add(minusOne).equals(BigInteger.ZERO));
- assertTrue("(-1)+1", minusOne.add(BigInteger.ONE).equals(BigInteger.ZERO));
-
- for (int i = 0; i < 200; i++) {
- BigInteger midbit = BigInteger.ZERO.setBit(i);
- assertTrue("add fails to carry on bit " + i, midbit.add(midbit)
- .equals(BigInteger.ZERO.setBit(i + 1)));
- }
- BigInteger bi2p3 = bi2.add(bi3);
- BigInteger bi3p2 = bi3.add(bi2);
- assertTrue("bi2p3=bi3p2", bi2p3.equals(bi3p2));
-
-
- // BESSER UEBERGREIFENDE TESTS MACHEN IN FORM VON STRESS TEST.
- // add large positive + small positive
- BigInteger sum = aZillion;
- BigInteger increment = BigInteger.ONE;
- for (int i = 0; i < 20; i++) {
-
- }
-
- // add large positive + small negative
-
- // add large negative + small positive
-
- // add large negative + small negative
- }
-
- public void testClone() {
- // Regression test for HARMONY-1770
- MyBigInteger myBigInteger = new MyBigInteger("12345");
- myBigInteger = (MyBigInteger) myBigInteger.clone();
- }
-
- static class MyBigInteger extends BigInteger implements Cloneable {
- public MyBigInteger(String val) {
- super(val);
- }
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
- }
- }
- }
-
- @Override
- protected void setUp() {
- bi2 = new BigInteger("4576829475724387584378543764555", 16);
- bi3 = new BigInteger("43987298363278574365732645872643587624387563245", 16);
- }
-
- private boolean isPrime(long b) {
- if (b == 2) {
- return true;
- }
- // check for div by 2
- if ((b & 1L) == 0) {
- return false;
- }
- long maxlen = ((long) Math.sqrt(b)) + 2;
- for (long x = 3; x < maxlen; x += 2) {
- if (b % x == 0) {
- return false;
- }
- }
- return true;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/math/RoundingModeTest.java b/luni/src/test/java/tests/api/java/math/RoundingModeTest.java
deleted file mode 100644
index 50a77df..0000000
--- a/luni/src/test/java/tests/api/java/math/RoundingModeTest.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 tests.api.java.math;
-
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-
-public class RoundingModeTest extends junit.framework.TestCase {
-
- /**
- * java.math.RoundingMode#valueOf(int)
- */
- public void test_valueOfI() {
- assertEquals("valueOf failed for ROUND_CEILING", RoundingMode.valueOf(BigDecimal.ROUND_CEILING), RoundingMode.CEILING);
- assertEquals("valueOf failed for ROUND_DOWN", RoundingMode.valueOf(BigDecimal.ROUND_DOWN), RoundingMode.DOWN);
- assertEquals("valueOf failed for ROUND_FLOOR", RoundingMode.valueOf(BigDecimal.ROUND_FLOOR), RoundingMode.FLOOR);
- assertEquals("valueOf failed for ROUND_HALF_DOWN", RoundingMode.valueOf(BigDecimal.ROUND_HALF_DOWN), RoundingMode.HALF_DOWN);
- assertEquals("valueOf failed for ROUND_HALF_EVEN", RoundingMode.valueOf(BigDecimal.ROUND_HALF_EVEN), RoundingMode.HALF_EVEN);
- assertEquals("valueOf failed for ROUND_HALF_UP", RoundingMode.valueOf(BigDecimal.ROUND_HALF_UP), RoundingMode.HALF_UP);
- assertEquals("valueOf failed for ROUND_UNNECESSARY", RoundingMode.valueOf(BigDecimal.ROUND_UNNECESSARY), RoundingMode.UNNECESSARY);
- assertEquals("valueOf failed for ROUND_UP", RoundingMode.valueOf(BigDecimal.ROUND_UP), RoundingMode.UP);
- try {
- RoundingMode.valueOf(13);
- fail("IllegalArgumentException expected for RoundingMode(13)");
- } catch (IllegalArgumentException e) {
- }
- try {
- RoundingMode.valueOf(-1);
- fail("IllegalArgumentException expected for RoundingMode(-1)");
- } catch (IllegalArgumentException e) {
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractListTest.java b/luni/src/test/java/tests/api/java/util/AbstractListTest.java
deleted file mode 100644
index 3cda30f..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractListTest.java
+++ /dev/null
@@ -1,293 +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 tests.api.java.util;
-
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.RandomAccess;
-
-public class AbstractListTest extends junit.framework.TestCase {
-
- static class SimpleList extends AbstractList {
- ArrayList arrayList;
-
- SimpleList() {
- this.arrayList = new ArrayList();
- }
-
- public Object get(int index) {
- return this.arrayList.get(index);
- }
-
- public void add(int i, Object o) {
- this.arrayList.add(i, o);
- }
-
- public Object remove(int i) {
- return this.arrayList.remove(i);
- }
-
- public int size() {
- return this.arrayList.size();
- }
- }
-
- /**
- * java.util.AbstractList#hashCode()
- */
- public void test_hashCode() {
-
- List list = new ArrayList();
- list.add(new Integer(3));
- list.add(new Integer(15));
- list.add(new Integer(5));
- list.add(new Integer(1));
- list.add(new Integer(7));
- int hashCode = 1;
- Iterator i = list.iterator();
- while (i.hasNext()) {
- Object obj = i.next();
- hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
- }
- assertTrue("Incorrect hashCode returned. Wanted: " + hashCode
- + " got: " + list.hashCode(), hashCode == list.hashCode());
- }
-
- /**
- * java.util.AbstractList#iterator()
- */
- public void test_iterator() {
- SimpleList list = new SimpleList();
- list.add(new Object());
- list.add(new Object());
- Iterator it = list.iterator();
- it.next();
- it.remove();
- it.next();
- }
-
- /**
- * java.util.AbstractList#listIterator()
- */
- public void test_listIterator() {
- Integer tempValue;
- List list = new ArrayList();
- list.add(new Integer(3));
- list.add(new Integer(15));
- list.add(new Integer(5));
- list.add(new Integer(1));
- list.add(new Integer(7));
- ListIterator lit = list.listIterator();
- assertTrue("Should not have previous", !lit.hasPrevious());
- assertTrue("Should have next", lit.hasNext());
- tempValue = (Integer) lit.next();
- assertTrue("next returned wrong value. Wanted 3, got: " + tempValue,
- tempValue.intValue() == 3);
- tempValue = (Integer) lit.previous();
-
- SimpleList list2 = new SimpleList();
- list2.add(new Object());
- ListIterator lit2 = list2.listIterator();
- lit2.add(new Object());
- lit2.next();
- }
-
- /**
- * java.util.AbstractList#subList(int, int)
- */
- public void test_subListII() {
- // Test each of the SubList operations to ensure a
- // ConcurrentModificationException does not occur on an AbstractList
- // which does not update modCount
- SimpleList mList = new SimpleList();
- mList.add(new Object());
- mList.add(new Object());
- List sList = mList.subList(0, 2);
- sList.add(new Object()); // calls add(int, Object)
- sList.get(0);
-
- sList.add(0, new Object());
- sList.get(0);
-
- sList.addAll(Arrays.asList(new String[] { "1", "2" }));
- sList.get(0);
-
- sList.addAll(0, Arrays.asList(new String[] { "3", "4" }));
- sList.get(0);
-
- sList.remove(0);
- sList.get(0);
-
- ListIterator lit = sList.listIterator();
- lit.add(new Object());
- lit.next();
- lit.remove();
- lit.next();
-
- sList.clear(); // calls removeRange()
- sList.add(new Object());
-
- // test the type of sublist that is returned
- List al = new ArrayList();
- for (int i = 0; i < 10; i++) {
- al.add(new Integer(i));
- }
- assertTrue(
- "Sublist returned should have implemented Random Access interface",
- al.subList(3, 7) instanceof RandomAccess);
-
- List ll = new LinkedList();
- for (int i = 0; i < 10; i++) {
- ll.add(new Integer(i));
- }
- assertTrue(
- "Sublist returned should not have implemented Random Access interface",
- !(ll.subList(3, 7) instanceof RandomAccess));
-
- }
-
- /**
- * java.util.AbstractList#subList(int, int)
- */
- public void test_subList_empty() {
- // Regression for HARMONY-389
- List al = new ArrayList();
- al.add("one");
- List emptySubList = al.subList(0, 0);
-
- try {
- emptySubList.get(0);
- fail("emptySubList.get(0) should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- emptySubList.set(0, "one");
- fail("emptySubList.set(0,Object) should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- emptySubList.remove(0);
- fail("emptySubList.remove(0) should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractList#subList(int, int)
- */
- public void test_subList_addAll() {
- // Regression for HARMONY-390
- List mainList = new ArrayList();
- Object[] mainObjects = { "a", "b", "c" };
- mainList.addAll(Arrays.asList(mainObjects));
- List subList = mainList.subList(1, 2);
- assertFalse("subList should not contain \"a\"", subList.contains("a"));
- assertFalse("subList should not contain \"c\"", subList.contains("c"));
- assertTrue("subList should contain \"b\"", subList.contains("b"));
-
- Object[] subObjects = { "one", "two", "three" };
- subList.addAll(Arrays.asList(subObjects));
- assertFalse("subList should not contain \"a\"", subList.contains("a"));
- assertFalse("subList should not contain \"c\"", subList.contains("c"));
-
- Object[] expected = { "b", "one", "two", "three" };
- ListIterator iter = subList.listIterator();
- for (int i = 0; i < expected.length; i++) {
- assertTrue("subList should contain " + expected[i], subList
- .contains(expected[i]));
- assertTrue("should be more elements", iter.hasNext());
- assertEquals("element in incorrect position", expected[i], iter
- .next());
- }
- }
-
- public void test_indexOfLjava_lang_Object() {
- AbstractList al = new ArrayList();
- al.add(0);
- al.add(1);
- al.add(2);
- al.add(3);
- al.add(4);
-
- assertEquals(-1, al.indexOf(5));
- assertEquals(2, al.indexOf(2));
- }
-
- public void test_lastIndexOfLjava_lang_Object() {
- AbstractList al = new ArrayList();
- al.add(0);
- al.add(1);
- al.add(2);
- al.add(2);
- al.add(2);
- al.add(2);
- al.add(2);
- al.add(3);
- al.add(4);
-
- assertEquals(-1, al.lastIndexOf(5));
- assertEquals(6, al.lastIndexOf(2));
- }
-
- public void test_listIteratorI() {
- AbstractList al1 = new ArrayList();
- AbstractList al2 = new ArrayList();
- al1.add(0);
- al1.add(1);
- al1.add(2);
- al1.add(3);
- al1.add(4);
- al2.add(2);
- al2.add(3);
- al2.add(4);
-
- Iterator li1 = al1.listIterator(2);
- Iterator li2 = al2.listIterator();
-
- while(li1.hasNext()&&li2.hasNext()) {
- assertEquals(li1.next(), li2.next());
- }
- assertSame(li1.hasNext(),li2.hasNext());
-
- try {
- al1.listIterator(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- al1.listIterator(al1.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- protected void doneSuite() {}
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractMapTest.java b/luni/src/test/java/tests/api/java/util/AbstractMapTest.java
deleted file mode 100644
index c8f9ce2..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractMapTest.java
+++ /dev/null
@@ -1,327 +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 tests.api.java.util;
-
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.Vector;
-import java.util.WeakHashMap;
-
-public class AbstractMapTest extends junit.framework.TestCase {
-
- static final String specialKey = "specialKey".intern();
-
- static final String specialValue = "specialValue".intern();
-
- // The impl of MyMap is not realistic, but serves to create a type
- // that uses the default remove behavior.
- class MyMap extends AbstractMap {
- final Set mySet = new HashSet(1);
-
- MyMap() {
- mySet.add(new Map.Entry() {
- public Object getKey() {
- return specialKey;
- }
-
- public Object getValue() {
- return specialValue;
- }
-
- public Object setValue(Object object) {
- return null;
- }
- });
- }
-
- public Object put(Object key, Object value) {
- return null;
- }
-
- public Set entrySet() {
- return mySet;
- }
- }
-
- /**
- * java.util.AbstractMap#keySet()
- */
- public void test_keySet() {
- AbstractMap map1 = new HashMap(0);
- assertSame("HashMap(0)", map1.keySet(), map1.keySet());
-
- AbstractMap map2 = new HashMap(10);
- assertSame("HashMap(10)", map2.keySet(), map2.keySet());
-
- Map map3 = Collections.EMPTY_MAP;
- assertSame("EMPTY_MAP", map3.keySet(), map3.keySet());
-
- AbstractMap map4 = new IdentityHashMap(1);
- assertSame("IdentityHashMap", map4.keySet(), map4.keySet());
-
- AbstractMap map5 = new LinkedHashMap(122);
- assertSame("LinkedHashMap", map5.keySet(), map5.keySet());
-
- AbstractMap map6 = new TreeMap();
- assertSame("TreeMap", map6.keySet(), map6.keySet());
-
- AbstractMap map7 = new WeakHashMap();
- assertSame("WeakHashMap", map7.keySet(), map7.keySet());
- }
-
- /**
- * java.util.AbstractMap#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- Object key = new Object();
- Object value = new Object();
-
- AbstractMap map1 = new HashMap(0);
- map1.put("key", value);
- assertSame("HashMap(0)", map1.remove("key"), value);
-
- AbstractMap map4 = new IdentityHashMap(1);
- map4.put(key, value);
- assertSame("IdentityHashMap", map4.remove(key), value);
-
- AbstractMap map5 = new LinkedHashMap(122);
- map5.put(key, value);
- assertSame("LinkedHashMap", map5.remove(key), value);
-
- AbstractMap map6 = new TreeMap(new Comparator() {
- // Bogus comparator
- public int compare(Object object1, Object object2) {
- return 0;
- }
- });
- map6.put(key, value);
- assertSame("TreeMap", map6.remove(key), value);
-
- AbstractMap map7 = new WeakHashMap();
- map7.put(key, value);
- assertSame("WeakHashMap", map7.remove(key), value);
-
- AbstractMap aSpecialMap = new MyMap();
- aSpecialMap.put(specialKey, specialValue);
- Object valueOut = aSpecialMap.remove(specialKey);
- assertSame("MyMap", valueOut, specialValue);
- }
-
- /**
- * java.util.AbstractMap#values()
- */
- public void test_values() {
- AbstractMap map1 = new HashMap(0);
- assertSame("HashMap(0)", map1.values(), map1.values());
-
- AbstractMap map2 = new HashMap(10);
- assertSame("HashMap(10)", map2.values(), map2.values());
-
- Map map3 = Collections.EMPTY_MAP;
- assertSame("EMPTY_MAP", map3.values(), map3.values());
-
- AbstractMap map4 = new IdentityHashMap(1);
- assertSame("IdentityHashMap", map4.values(), map4.values());
-
- AbstractMap map5 = new LinkedHashMap(122);
- assertSame("IdentityHashMap", map5.values(), map5.values());
-
- AbstractMap map6 = new TreeMap();
- assertSame("TreeMap", map6.values(), map6.values());
-
- AbstractMap map7 = new WeakHashMap();
- assertSame("WeakHashMap", map7.values(), map7.values());
- }
-
- /**
- * java.util.AbstractMap#clone()
- */
- public void test_clone() {
- class MyMap extends AbstractMap implements Cloneable {
- private Map map = new HashMap();
-
- public Set entrySet() {
- return map.entrySet();
- }
-
- public Object put(Object key, Object value) {
- return map.put(key, value);
- }
-
- public Map getMap() {
- return map;
- }
-
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
- }
- }
- }
- ;
- MyMap map = new MyMap();
- map.put("one", "1");
- Map.Entry entry = (Map.Entry) map.entrySet().iterator().next();
- assertTrue("entry not added", entry.getKey() == "one"
- && entry.getValue() == "1");
- MyMap mapClone = (MyMap) map.clone();
- assertTrue("clone not shallow", map.getMap() == mapClone.getMap());
- }
-
- public class AMT extends AbstractMap {
-
- // Very crude AbstractMap implementation
- Vector values = new Vector();
- Vector keys = new Vector();
-
- public Set entrySet() {
- return new AbstractSet() {
- public Iterator iterator() {
- return new Iterator() {
- int index = 0;
-
- public boolean hasNext() {
- return index < values.size();
- }
-
- public Object next() {
- if (index < values.size()) {
- Map.Entry me = new Map.Entry() {
- Object v = values.elementAt(index);
-
- Object k = keys.elementAt(index);
-
- public Object getKey() {
- return k;
- }
-
- public Object getValue() {
- return v;
- }
-
- public Object setValue(Object value) {
- return null;
- }
- };
- index++;
- return me;
- }
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- public int size() {
- return values.size();
- }
- };
- }
-
- public Object put(Object k, Object v) {
- keys.add(k);
- values.add(v);
- return v;
- }
- }
-
- /**
- * {@link java.util.AbstractMap#putAll(Map)}
- */
- public void test_putAllLMap() {
- Hashtable ht = new Hashtable();
- AMT amt = new AMT();
- ht.put("this", "that");
- amt.putAll(ht);
-
- assertEquals("Should be equal", amt, ht);
- }
-
- public void testEqualsWithNullValues() {
- Map<String, String> a = new HashMap<String, String>();
- a.put("a", null);
- a.put("b", null);
-
- Map<String, String> b = new HashMap<String, String>();
- a.put("c", "cat");
- a.put("d", "dog");
-
- assertFalse(a.equals(b));
- assertFalse(b.equals(a));
- }
-
- public void testNullsOnViews() {
- Map<String, String> nullHostile = new Hashtable<String, String>();
-
- nullHostile.put("a", "apple");
- testNullsOnView(nullHostile.entrySet());
-
- nullHostile.put("a", "apple");
- testNullsOnView(nullHostile.keySet());
-
- nullHostile.put("a", "apple");
- testNullsOnView(nullHostile.values());
- }
-
- private void testNullsOnView(Collection<?> view) {
- try {
- assertFalse(view.contains(null));
- } catch (NullPointerException optional) {
- }
-
- try {
- assertFalse(view.remove(null));
- } catch (NullPointerException optional) {
- }
-
- Set<Object> setOfNull = Collections.singleton(null);
- assertFalse(view.equals(setOfNull));
-
- try {
- assertFalse(view.removeAll(setOfNull));
- } catch (NullPointerException optional) {
- }
-
- try {
- assertTrue(view.retainAll(setOfNull)); // destructive
- } catch (NullPointerException optional) {
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java b/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java
deleted file mode 100644
index 5ae490c..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java
+++ /dev/null
@@ -1,323 +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 tests.api.java.util;
-
-import java.util.AbstractQueue;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-
-public class AbstractQueueTest extends TestCase {
-
- private MockAbstractQueue<Object> queue;
-
- private class MockAbstractQueue<E> extends AbstractQueue<E> {
-
- static final int CAPACITY = 10;
-
- private int size = 0;
-
- private Object[] elements = new Object[CAPACITY];
-
- public Iterator<E> iterator() {
- return new Iterator<E>() {
-
- private int currentIndex = -1;
-
- public boolean hasNext() {
- return size > 0 && currentIndex < size;
- }
-
- public E next() {
- if (!hasNext()) {
- throw new NoSuchElementException();
- }
- currentIndex++;
- return (E) elements[currentIndex];
- }
-
- public void remove() {
- if (-1 == currentIndex) {
- throw new IllegalStateException();
- }
- for (int i = currentIndex; i < size - 1; i++) {
- elements[i] = elements[i + 1];
- }
- size--;
- }
- };
- }
-
- public int size() {
- return size;
- }
-
- public boolean offer(E o) {
- if (null == o) {
- throw new NullPointerException();
- }
-
- if (size >= CAPACITY) {
- return false;
- }
-
- elements[size++] = o;
- return true;
- }
-
- public E poll() {
- if (isEmpty()) {
- return null;
- }
- E e = (E) elements[0];
- for (int i = 0; i < size - 1; i++) {
- elements[i] = elements[i + 1];
- }
- size--;
- return e;
- }
-
- public E peek() {
- if (isEmpty()) {
- return null;
- }
- return (E) elements[0];
- }
-
- }
-
- /**
- * java.util.AbstractQueue.add(E)
- */
- public void test_addLE_null() {
- try {
- queue.add(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractQueue.add(E)
- */
- public void test_addLE_Full() {
- Object o = new Object();
-
- for(int i = 0; i < MockAbstractQueue.CAPACITY; i++ ) {
- queue.add(o);
- }
-
- try {
- queue.add(o);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * java.util.AbstractQueue#add(E)
- */
- public void test_addLE() {
- Object o = new Object();
- final int LAST_INDEX = 4;
- for (int i = 0; i < LAST_INDEX; i++) {
- queue.add(o);
- }
- Integer I = new Integer(123456);
- queue.add(I);
- assertTrue(queue.contains(I));
- Iterator iter = queue.iterator();
- for (int i = 0; i < LAST_INDEX; i++) {
- iter.next();
- }
- assertTrue(I == iter.next());
- }
-
- /**
- * java.util.AbstractQueue#addAll(E)
- */
- public void test_addAllLE_null() {
- try {
- queue.addAll(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractQueue#addAll(E)
- */
- public void test_addAllLE_with_null() {
- List list = Arrays.asList("MYTESTSTRING", null, new Float(123.456));
- try {
- queue.addAll(list);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractQueue#addAll(E)
- */
- public void test_addAllLE_full() {
- List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
- try {
- queue.addAll(list);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractQueue#addAll(E)
- */
- public void test_addAllLE_empty() {
- // Regression test for HARMONY-1178
- List list = new ArrayList<Object>(0);
- assertFalse("Non modification to queue should return false", queue.addAll(list));
- }
-
- /**
- * java.util.AbstractQueue#addAll(E)
- */
- public void test_addAllLE_this() {
- try {
- queue.addAll(queue);
- fail("should throw IllegalArgumentException ");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- public void test_addAllLjava_lang_Object() {
- Collection c = new Vector();
-
- c.add(0);
- c.add(1);
- c.add(2);
- c.add(3);
- c.add(4);
- c.add(5);
-
- assertTrue(queue.addAll(c));
- assertEquals(6, queue.size());
- }
-
- /**
- * java.util.AbstractQueue#clear()
- */
- public void test_clear_empty() {
- queue.clear();
- assertTrue(queue.isEmpty());
- assertNull(queue.peek());
- }
-
- /**
- * java.util.AbstractQueue#clear()
- */
- public void test_clear() {
- List list = Arrays.asList(123.456, "MYTESTSTRING", new Object(), 'c');
- queue.addAll(list);
- queue.clear();
- assertTrue(queue.isEmpty());
- assertNull(queue.peek());
- }
-
- /**
- * java.util.AbstractQueue#AbstractQueue()
- */
- public void test_Constructor() {
- MockAbstractQueue queue = new MockAbstractQueue();
- assertNotNull(queue);
- }
-
- /**
- * java.util.AbstractQueue#remove()
- */
- public void test_remove_null() {
- try {
- queue.remove();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- }
-
- /**
- * java.util.AbstractQueue#remove()
- */
- public void test_remove() {
- char c = 'a';
- queue.add(c);
- c = 'b';
- queue.add(c);
- assertEquals('a', queue.remove());
- assertEquals('b', queue.remove());
- try {
- queue.remove();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractQueue#element()
- */
- public void test_element_empty() {
- try {
- queue.element();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- }
-
- /**
- * java.util.AbstractQueue#element()
- */
- public void test_element() {
- String s = "MYTESTSTRING_ONE";
- queue.add(s);
- s = "MYTESTSTRING_TWO";
- queue.add(s);
- assertEquals("MYTESTSTRING_ONE", queue.element());
- // still the first element
- assertEquals("MYTESTSTRING_ONE", queue.element());
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- queue = new MockAbstractQueue<Object>();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- queue = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java b/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java
deleted file mode 100644
index 2068f1b..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java
+++ /dev/null
@@ -1,603 +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 tests.api.java.util;
-
-import java.util.AbstractSequentialList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.ListIterator;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-
-public class AbstractSequentialListTest extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- class ASLT<E> extends AbstractSequentialList<E> {
-
- LinkedList<E> l = new LinkedList<E>();
-
- @Override
- public ListIterator<E> listIterator(int index) {
- return l.listIterator(index);
- }
-
- @Override
- public int size() {
- return l.size();
- }
- }
-
- /**
- * {@link java.util.AbstractSequentialList#addAll(int, java.util.Collection)}
- */
- public void test_addAll_ILCollection() {
- AbstractSequentialList<String> al = new ASLT<String>();
- String[] someList = { "Aardvark" ,
- "Bear" ,
- "Chimpanzee",
- "Duck" };
- Collection<String> c = Arrays.asList(someList);
- al.addAll(c);
- assertTrue("Should return true", al.addAll(2, c));
- }
-
- class Mock_unsupportedListIterator implements ListIterator {
- public void add(Object o) {
- throw new UnsupportedOperationException();
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- }
-
- public void set(Object o) {
- throw new UnsupportedOperationException();
- }
- }
-
- class Mock_ListIterator<E> implements ListIterator<E> {
- final String wrongElement = "String";
- public void add(E o) {
- if (o.equals(wrongElement)) throw new IllegalArgumentException();
- if (o == null) throw new NullPointerException();
- }
-
- public boolean hasNext() {
- return false;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public E next() {
- return null;
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public E previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- }
-
- public void set(E o) {
- }
- }
-
- public void test_addAllILjava_util_Collection() {
- AbstractSequentialList asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
- Collection strV = new Vector<String>();
-
- strV.add("String");
- strV.add("1");
- strV.add("3.14");
-
- try {
- asl.addAll(0, strV);
- fail("UnsupportedOperationException expected.");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
- try {
- asl.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- //ClassCastException can not be checked for this method.
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_ListIterator();
- }
- };
-
- try {
- asl.addAll(0, strV);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- strV.remove("String");
- strV.add(null);
-
- try {
- asl.addAll(0, strV);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- strV.remove(null);
- asl.addAll(0, strV);
-
- asl = new LinkedList();
-
- try {
- asl.addAll(-10, strV);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.addAll(1, strV);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- public void test_addILjava_lang_Object() {
- AbstractSequentialList asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
-
- try {
- asl.add(0, 1);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_ListIterator();
- }
- };
-
- try {
- asl.add(0, "String");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
-
- try {
- asl.add(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- //ClassCastException can not be checked for this method.
-
- asl.add(0, 1);
-
- asl = new LinkedList();
-
- try {
- asl.add(-1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- asl.add(0, 1);
-
- try {
- asl.add(2, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- public void test_getI() {
- final String buff[] = {"0", "1", "2", "3", "4", "5"};
- AbstractSequentialList asl = new AbstractSequentialList() {
- int currPos = 0;
-
- @Override
- public int size() {
- return buff.length;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- currPos = index;
- return new ListIterator() {
- public void add(Object o) {
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return buff[currPos];
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- }
-
- public void set(Object o) {
- }
- };
- }
- };
-
- for (int i = 0; i < buff.length; i++) {
- assertEquals(buff[i], asl.get(i));
- }
-
- try {
- asl.get(asl.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.get(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- public void test_iterrator() {
- AbstractSequentialList asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
-
- assertTrue(asl.iterator().getClass().toString().contains("Mock_unsupportedListIterator"));
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_ListIterator();
- }
- };
-
- assertTrue(asl.iterator().getClass().toString().contains("Mock_ListIterator"));
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return null;
- }
- };
- assertNull(asl.iterator());
- }
-
- public void test_removeI() {
- AbstractSequentialList asl = new AbstractSequentialList() {
- String buff[] = {"0", "1", "2", "3", "4", "5"};
- int currPos = 0;
-
- @Override
- public int size() {
- return buff.length;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- currPos = index;
- return new ListIterator() {
- public void add(Object o) {
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return buff[currPos];
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- buff[currPos] = "removed element";
- }
-
- public void set(Object o) {
- }
- };
- }
- };
-
- try {
- asl.remove(asl.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.remove(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- for(int i = 0; i < asl.size(); i++) {
- assertFalse(asl.get(i).toString().contains("removed element"));
- asl.remove(i);
- assertTrue(asl.get(i).toString().contains("removed element"));
- }
- }
-
- public void test_setILjava_lang_Object() {
- AbstractSequentialList asl = new AbstractSequentialList() {
- String buff[] = {"0", "1", "2", "3", "4", "5"};
- final String illegalStr = "Illegal element";
- int currPos = 0;
-
- @Override
- public int size() {
- return buff.length;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- currPos = index;
- return new ListIterator() {
- public void add(Object o) {
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return buff[currPos];
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- buff[currPos] = "removed element";
- }
-
- public void set(Object o) {
- if (o == null) throw new NullPointerException();
- if (o.equals(illegalStr)) throw new IllegalArgumentException();
- buff[currPos] = (String) o;
- }
- };
- }
- };
-
- try {
- asl.set(asl.size() + 1, "new element");
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.set(-1, "new element");
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- for(int i = 0; i < asl.size(); i++) {
- assertFalse(asl.get(i).toString().contains("new element"));
- asl.set(i, "new element");
- assertTrue(asl.get(i).toString().contains("new element"));
- }
-
- try {
- asl.set(1, new Double(1));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //
- }
-
- try {
- asl.set(1, "Illegal element");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
-
- try {
- asl.set(1, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
-
- try {
- asl.set(0, "New element");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ArrayListTest.java b/luni/src/test/java/tests/api/java/util/ArrayListTest.java
deleted file mode 100644
index 50d9aa3..0000000
--- a/luni/src/test/java/tests/api/java/util/ArrayListTest.java
+++ /dev/null
@@ -1,699 +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 tests.api.java.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.ConcurrentModificationException;
-import java.util.Vector;
-
-import tests.support.Support_ListTest;
-
-public class ArrayListTest extends junit.framework.TestCase {
-
- List alist;
-
- Object[] objArray;
-
- /**
- * java.util.ArrayList#ArrayList()
- */
- public void test_Constructor() {
- // Test for method java.util.ArrayList()
- new Support_ListTest("", alist).runTest();
-
- ArrayList subList = new ArrayList();
- for (int i = -50; i < 150; i++)
- subList.add(new Integer(i));
- new Support_ListTest("", subList.subList(50, 150)).runTest();
- }
-
- /**
- * java.util.ArrayList#ArrayList(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.ArrayList(int)
- ArrayList al = new ArrayList(5);
- assertEquals("Incorrect arrayList created", 0, al.size());
-
- try {
- new ArrayList(-10);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.ArrayList#ArrayList(java.util.Collection)
- */
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.ArrayList(java.util.Collection)
- ArrayList al = new ArrayList(Arrays.asList(objArray));
- assertTrue("arrayList created from collection has incorrect size", al
- .size() == objArray.length);
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue(
- "arrayList created from collection has incorrect elements",
- al.get(counter) == objArray[counter]);
- try {
- new ArrayList(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- }
-
- /**
- * java.util.ArrayList#add(int, java.lang.Object)
- */
- public void test_addILjava_lang_Object() {
- // Test for method void java.util.ArrayList.add(int, java.lang.Object)
- Object o;
- alist.add(50, o = new Object());
- assertTrue("Failed to add Object", alist.get(50) == o);
- assertTrue("Failed to fix up list after insert",
- alist.get(51) == objArray[50]
- && (alist.get(52) == objArray[51]));
- Object oldItem = alist.get(25);
- alist.add(25, null);
- assertNull("Should have returned null", alist.get(25));
- assertTrue("Should have returned the old item from slot 25", alist
- .get(26) == oldItem);
-
- try {
- alist.add(-1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.add(alist.size() + 1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.ArrayList#add(java.lang.Object)
- */
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.ArrayList.add(java.lang.Object)
- Object o = new Object();
- alist.add(o);
- assertTrue("Failed to add Object", alist.get(alist.size() - 1) == o);
- alist.add(null);
- assertNull("Failed to add null", alist.get(alist.size() - 1));
- }
-
- /**
- * java.util.ArrayList#addAll(int, java.util.Collection)
- */
- public void test_addAllILjava_util_Collection() {
- // Test for method boolean java.util.ArrayList.addAll(int,
- // java.util.Collection)
- alist.addAll(50, alist);
- assertEquals("Returned incorrect size after adding to existing list",
- 200, alist.size());
- for (int i = 0; i < 50; i++)
- assertTrue("Manipulated elements < index",
- alist.get(i) == objArray[i]);
- for (int i = 0; i >= 50 && (i < 150); i++)
- assertTrue("Failed to ad elements properly",
- alist.get(i) == objArray[i - 50]);
- for (int i = 0; i >= 150 && (i < 200); i++)
- assertTrue("Failed to ad elements properly",
- alist.get(i) == objArray[i - 100]);
- ArrayList listWithNulls = new ArrayList();
- listWithNulls.add(null);
- listWithNulls.add(null);
- listWithNulls.add("yoink");
- listWithNulls.add("kazoo");
- listWithNulls.add(null);
- alist.addAll(100, listWithNulls);
- assertTrue("Incorrect size: " + alist.size(), alist.size() == 205);
- assertNull("Item at slot 100 should be null", alist.get(100));
- assertNull("Item at slot 101 should be null", alist.get(101));
- assertEquals("Item at slot 102 should be 'yoink'",
- "yoink", alist.get(102));
- assertEquals("Item at slot 103 should be 'kazoo'",
- "kazoo", alist.get(103));
- assertNull("Item at slot 104 should be null", alist.get(104));
- alist.addAll(205, listWithNulls);
- assertTrue("Incorrect size2: " + alist.size(), alist.size() == 210);
-
- try {
- alist.addAll(-1, listWithNulls);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.addAll(alist.size() + 1, listWithNulls);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
-// BEGIN android-removed
-// The spec does not mandate that IndexOutOfBoundsException be thrown in
-// preference to NullPointerException when the caller desserves both.
-//
-// /**
-// * java.util.ArrayList#addAll(int, java.util.Collection)
-// */
-// public void test_addAllILjava_util_Collection_2() {
-// // Regression for HARMONY-467
-// ArrayList obj = new ArrayList();
-// try {
-// obj.addAll((int) -1, (Collection) null);
-// fail("IndexOutOfBoundsException expected");
-// } catch (IndexOutOfBoundsException e) {
-// }
-// }
-// END android-removed
-
- /**
- * java.util.ArrayList#addAll(java.util.Collection)
- */
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.ArrayList.addAll(java.util.Collection)
- List l = new ArrayList();
- l.addAll(alist);
- for (int i = 0; i < alist.size(); i++)
- assertTrue("Failed to add elements properly", l.get(i).equals(
- alist.get(i)));
- alist.addAll(alist);
- assertEquals("Returned incorrect size after adding to existing list",
- 200, alist.size());
- for (int i = 0; i < 100; i++) {
- assertTrue("Added to list in incorrect order", alist.get(i)
- .equals(l.get(i)));
- assertTrue("Failed to add to existing list", alist.get(i + 100)
- .equals(l.get(i)));
- }
- Set setWithNulls = new HashSet();
- setWithNulls.add(null);
- setWithNulls.add(null);
- setWithNulls.add("yoink");
- setWithNulls.add("kazoo");
- setWithNulls.add(null);
- alist.addAll(100, setWithNulls);
- Iterator i = setWithNulls.iterator();
- assertTrue("Item at slot 100 is wrong: " + alist.get(100), alist
- .get(100) == i.next());
- assertTrue("Item at slot 101 is wrong: " + alist.get(101), alist
- .get(101) == i.next());
- assertTrue("Item at slot 103 is wrong: " + alist.get(102), alist
- .get(102) == i.next());
-
-
- // Regression test for Harmony-3481
- ArrayList<Integer> originalList = new ArrayList<Integer>(12);
- for (int j = 0; j < 12; j++) {
- originalList.add(j);
- }
-
- originalList.remove(0);
- originalList.remove(0);
-
- ArrayList<Integer> additionalList = new ArrayList<Integer>(11);
- for (int j = 0; j < 11; j++) {
- additionalList.add(j);
- }
- assertTrue(originalList.addAll(additionalList));
- assertEquals(21, originalList.size());
-
- try {
- alist.addAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.ArrayList#clear()
- */
- public void test_clear() {
- // Test for method void java.util.ArrayList.clear()
- alist.clear();
- assertEquals("List did not clear", 0, alist.size());
- alist.add(null);
- alist.add(null);
- alist.add(null);
- alist.add("bam");
- alist.clear();
- assertEquals("List with nulls did not clear", 0, alist.size());
- /*
- * for (int i = 0; i < alist.size(); i++) assertNull("Failed to clear
- * list", alist.get(i));
- */
-
- }
-
- /**
- * java.util.ArrayList#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.ArrayList.clone()
- ArrayList x = (ArrayList) (((ArrayList) (alist)).clone());
- assertTrue("Cloned list was inequal to original", x.equals(alist));
- for (int i = 0; i < alist.size(); i++)
- assertTrue("Cloned list contains incorrect elements",
- alist.get(i) == x.get(i));
-
- alist.add(null);
- alist.add(25, null);
- x = (ArrayList) (((ArrayList) (alist)).clone());
- assertTrue("nulls test - Cloned list was inequal to original", x
- .equals(alist));
- for (int i = 0; i < alist.size(); i++)
- assertTrue("nulls test - Cloned list contains incorrect elements",
- alist.get(i) == x.get(i));
-
- }
-
- /**
- * java.util.ArrayList#contains(java.lang.Object)
- */
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.ArrayList.contains(java.lang.Object)
- assertTrue("Returned false for valid element", alist
- .contains(objArray[99]));
- assertTrue("Returned false for equal element", alist
- .contains(new Integer(8)));
- assertTrue("Returned true for invalid element", !alist
- .contains(new Object()));
- assertTrue("Returned true for null but should have returned false",
- !alist.contains(null));
- alist.add(null);
- assertTrue("Returned false for null but should have returned true",
- alist.contains(null));
- }
-
- /**
- * java.util.ArrayList#ensureCapacity(int)
- */
- public void test_ensureCapacityI() {
- // Test for method void java.util.ArrayList.ensureCapacity(int)
- // TODO : There is no good way to test this as it only really impacts on
- // the private implementation.
-
- Object testObject = new Object();
- int capacity = 20;
- ArrayList al = new ArrayList(capacity);
- int i;
- for (i = 0; i < capacity / 2; i++) {
- al.add(i, new Object());
- }
- al.add(i, testObject);
- int location = al.indexOf(testObject);
- try {
- al.ensureCapacity(capacity);
- assertTrue("EnsureCapacity moved objects around in array1.",
- location == al.indexOf(testObject));
- al.remove(0);
- al.ensureCapacity(capacity);
- assertTrue("EnsureCapacity moved objects around in array2.",
- --location == al.indexOf(testObject));
- al.ensureCapacity(capacity + 2);
- assertTrue("EnsureCapacity did not change location.",
- location == al.indexOf(testObject));
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * java.util.ArrayList#get(int)
- */
- public void test_getI() {
- // Test for method java.lang.Object java.util.ArrayList.get(int)
- assertTrue("Returned incorrect element", alist.get(22) == objArray[22]);
- try {
- alist.get(8765);
- fail("Failed to throw expected exception for index > size");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * java.util.ArrayList#indexOf(java.lang.Object)
- */
- public void test_indexOfLjava_lang_Object() {
- // Test for method int java.util.ArrayList.indexOf(java.lang.Object)
- assertEquals("Returned incorrect index",
- 87, alist.indexOf(objArray[87]));
- assertEquals("Returned index for invalid Object", -1, alist
- .indexOf(new Object()));
- alist.add(25, null);
- alist.add(50, null);
- assertTrue("Wrong indexOf for null. Wanted 25 got: "
- + alist.indexOf(null), alist.indexOf(null) == 25);
- }
-
- /**
- * java.util.ArrayList#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.ArrayList.isEmpty()
- assertTrue("isEmpty returned false for new list", new ArrayList()
- .isEmpty());
- assertTrue("Returned true for existing list with elements", !alist
- .isEmpty());
- }
-
- /**
- * java.util.ArrayList#lastIndexOf(java.lang.Object)
- */
- public void test_lastIndexOfLjava_lang_Object() {
- // Test for method int java.util.ArrayList.lastIndexOf(java.lang.Object)
- alist.add(new Integer(99));
- assertEquals("Returned incorrect index",
- 100, alist.lastIndexOf(objArray[99]));
- assertEquals("Returned index for invalid Object", -1, alist
- .lastIndexOf(new Object()));
- alist.add(25, null);
- alist.add(50, null);
- assertTrue("Wrong lastIndexOf for null. Wanted 50 got: "
- + alist.lastIndexOf(null), alist.lastIndexOf(null) == 50);
- }
-
- /**
- * java.util.ArrayList#remove(int)
- */
- public void test_removeI() {
- // Test for method java.lang.Object java.util.ArrayList.remove(int)
- alist.remove(10);
- assertEquals("Failed to remove element",
- -1, alist.indexOf(objArray[10]));
- try {
- alist.remove(999);
- fail("Failed to throw exception when index out of range");
- } catch (IndexOutOfBoundsException e) {
- }
-
- ArrayList myList = (ArrayList) (((ArrayList) (alist)).clone());
- alist.add(25, null);
- alist.add(50, null);
- alist.remove(50);
- alist.remove(25);
- assertTrue("Removing nulls did not work", alist.equals(myList));
-
- List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
- "d", "e", "f", "g" }));
- assertTrue("Removed wrong element 1", list.remove(0) == "a");
- assertTrue("Removed wrong element 2", list.remove(4) == "f");
- String[] result = new String[5];
- list.toArray(result);
- assertTrue("Removed wrong element 3", Arrays.equals(result,
- new String[] { "b", "c", "d", "e", "g" }));
-
- List l = new ArrayList(0);
- l.add(new Object());
- l.add(new Object());
- l.remove(0);
- l.remove(0);
- try {
- l.remove(-1);
- fail("-1 should cause exception");
- } catch (IndexOutOfBoundsException e) {
- }
- try {
- l.remove(0);
- fail("0 should case exception");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * java.util.ArrayList#set(int, java.lang.Object)
- */
- public void test_setILjava_lang_Object() {
- // Test for method java.lang.Object java.util.ArrayList.set(int,
- // java.lang.Object)
- Object obj;
- alist.set(65, obj = new Object());
- assertTrue("Failed to set object", alist.get(65) == obj);
- alist.set(50, null);
- assertNull("Setting to null did not work", alist.get(50));
- assertTrue("Setting increased the list's size to: " + alist.size(),
- alist.size() == 100);
-
- try {
- alist.set(-1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.set(alist.size() + 1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.ArrayList#size()
- */
- public void test_size() {
- // Test for method int java.util.ArrayList.size()
- assertEquals("Returned incorrect size for exiting list",
- 100, alist.size());
- assertEquals("Returned incorrect size for new list", 0, new ArrayList()
- .size());
- }
-
- /**
- * java.util.ArrayList#toArray()
- */
- public void test_toArray() {
- // Test for method java.lang.Object [] java.util.ArrayList.toArray()
- alist.set(25, null);
- alist.set(75, null);
- Object[] obj = alist.toArray();
- assertEquals("Returned array of incorrect size", objArray.length,
- obj.length);
-
- for (int i = 0; i < obj.length; i++) {
- if ((i == 25) || (i == 75))
- assertNull("Should be null at: " + i + " but instead got: "
- + obj[i], obj[i]);
- else
- assertTrue("Returned incorrect array: " + i,
- obj[i] == objArray[i]);
- }
-
- }
-
- /**
- * java.util.ArrayList#toArray(java.lang.Object[])
- */
- public void test_toArray$Ljava_lang_Object() {
- // Test for method java.lang.Object []
- // java.util.ArrayList.toArray(java.lang.Object [])
- alist.set(25, null);
- alist.set(75, null);
- Integer[] argArray = new Integer[100];
- Object[] retArray;
- retArray = alist.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- argArray = new Integer[1000];
- retArray = alist.toArray(argArray);
- assertNull("Failed to set first extra element to null", argArray[alist
- .size()]);
- for (int i = 0; i < 100; i++) {
- if ((i == 25) || (i == 75))
- assertNull("Should be null: " + i, retArray[i]);
- else
- assertTrue("Returned incorrect array: " + i,
- retArray[i] == objArray[i]);
- }
-
- String[] strArray = new String[100];
- try {
- alist.toArray(strArray);
- fail("ArrayStoreException expected");
- } catch (ArrayStoreException e) {
- //expected
- }
- }
-
- /**
- * java.util.ArrayList#trimToSize()
- */
- public void test_trimToSize_01() {
- // Test for method void java.util.ArrayList.trimToSize()
- for (int i = 99; i > 24; i--)
- alist.remove(i);
- ((ArrayList) alist).trimToSize();
- assertEquals("Returned incorrect size after trim", 25, alist.size());
- for (int i = 0; i < alist.size(); i++)
- assertTrue("Trimmed list contained incorrect elements", alist
- .get(i) == objArray[i]);
- Vector v = new Vector();
- v.add("a");
- v.add("b");
- ArrayList al = new ArrayList(v);
- Iterator it = al.iterator();
- al.remove(0);
- al.trimToSize();
- try {
- it.next();
- fail("should throw a ConcurrentModificationException");
- } catch (ConcurrentModificationException ioobe) {
- // expected
- }
- }
-
- public void test_trimToSize_02() {
- ArrayList list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
- "d", "e", "f", "g" }));
- list.remove("a");
- list.remove("f");
- list.trimToSize();
- }
-
- /**
- * @test java.util.ArrayList#addAll(int, Collection)
- */
- public void test_addAll() {
- ArrayList list = new ArrayList();
- list.add("one");
- list.add("two");
- assertEquals(2, list.size());
-
- list.remove(0);
- assertEquals(1, list.size());
-
- ArrayList collection = new ArrayList();
- collection.add("1");
- collection.add("2");
- collection.add("3");
- assertEquals(3, collection.size());
-
- list.addAll(0, collection);
- assertEquals(4, list.size());
-
- list.remove(0);
- list.remove(0);
- assertEquals(2, list.size());
-
- collection.add("4");
- collection.add("5");
- collection.add("6");
- collection.add("7");
- collection.add("8");
- collection.add("9");
- collection.add("10");
- collection.add("11");
- collection.add("12");
-
- assertEquals(12, collection.size());
-
- list.addAll(0, collection);
- assertEquals(14, list.size());
- }
-
- public void test_removeLjava_lang_Object() {
- List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
- "d", "e", "f", "g" }));
- assertTrue("Removed wrong element 1", list.remove("a"));
- assertTrue("Removed wrong element 2", list.remove("f"));
- String[] result = new String[5];
- list.toArray(result);
- assertTrue("Removed wrong element 3", Arrays.equals(result,
- new String[] { "b", "c", "d", "e", "g" }));
- }
-
- class Mock_ArrayList extends ArrayList {
- public Mock_ArrayList() {
- }
-
- public void removeRange(int begin, int end) {
- super.removeRange(begin, end);
- }
- }
-
- public void test_removeRangeII() {
- Mock_ArrayList mal = new Mock_ArrayList();
- mal.add("a");
- mal.add("b");
- mal.add("c");
- mal.add("d");
- mal.add("e");
- mal.add("f");
- mal.add("g");
- mal.add("h");
-
- mal.removeRange(2, 4);
-
- String[] result = new String[6];
- mal.toArray(result);
- assertTrue("Removed wrong element 3", Arrays.equals(result,
- new String[] { "a", "b", "e", "f", "g", "h"}));
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
-
- objArray = new Object[100];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- }
-
- alist = new ArrayList();
- for (int i = 0; i < objArray.length; i++) {
- alist.add(objArray[i]);
- }
- }
-
- @Override
- protected void tearDown() throws Exception {
- objArray = null;
- alist = null;
-
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ArraysTest.java b/luni/src/test/java/tests/api/java/util/ArraysTest.java
deleted file mode 100644
index 2ca8e70..0000000
--- a/luni/src/test/java/tests/api/java/util/ArraysTest.java
+++ /dev/null
@@ -1,2403 +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 tests.api.java.util;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Random;
-
-import tests.support.Support_UnmodifiableCollectionTest;
-
-public class ArraysTest extends junit.framework.TestCase {
-
- public static class ReversedIntegerComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return -(((Integer) o1).compareTo((Integer) o2));
- }
-
- public boolean equals(Object o1, Object o2) {
- return ((Integer) o1).compareTo((Integer) o2) == 0;
- }
- }
-
- final static int arraySize = 100;
-
- Object[] objArray;
-
- boolean[] booleanArray;
-
- byte[] byteArray;
-
- char[] charArray;
-
- double[] doubleArray;
-
- float[] floatArray;
-
- int[] intArray;
-
- long[] longArray;
-
- Object[] objectArray;
-
- short[] shortArray;
-
- /**
- * java.util.Arrays#asList(java.lang.Object[])
- */
- public void test_asList$Ljava_lang_Object() {
- // Test for method java.util.List
- // java.util.Arrays.asList(java.lang.Object [])
- List convertedList = Arrays.asList(objectArray);
- for (int counter = 0; counter < arraySize; counter++) {
- assertTrue(
- "Array and List converted from array do not contain identical elements",
- convertedList.get(counter) == objectArray[counter]);
- }
- convertedList.set(50, new Integer(1000));
- assertTrue("set/get did not work on coverted list", convertedList.get(
- 50).equals(new Integer(1000)));
- convertedList.set(50, new Integer(50));
- new Support_UnmodifiableCollectionTest("", convertedList).runTest();
-
- Object[] myArray = (Object[]) (objectArray.clone());
- myArray[30] = null;
- myArray[60] = null;
- convertedList = Arrays.asList(myArray);
- for (int counter = 0; counter < arraySize; counter++) {
- assertTrue(
- "Array and List converted from array do not contain identical elements",
- convertedList.get(counter) == myArray[counter]);
- }
-
- try {
- Arrays.asList((Object[])null);
- fail("asList with null arg didn't throw NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#binarySearch(byte[], byte)
- */
- public void test_binarySearch$BB() {
- // Test for method int java.util.Arrays.binarySearch(byte [], byte)
- for (byte counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on byte[] answered incorrect position",
- Arrays.binarySearch(byteArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(intArray, (byte) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(intArray, (byte) arraySize) == -(arraySize + 1));
- for (byte counter = 0; counter < arraySize; counter++)
- byteArray[counter] -= 50;
- for (byte counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on byte[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(byteArray, (byte) (counter - 50)) == counter);
- }
-
- /**
- * java.util.Arrays#binarySearch(char[], char)
- */
- public void test_binarySearch$CC() {
- // Test for method int java.util.Arrays.binarySearch(char [], char)
- for (char counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on char[] answered incorrect position",
- Arrays.binarySearch(charArray, (char) (counter + 1)) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(charArray, '\u0000'));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(charArray, (char) (arraySize + 1)) == -(arraySize + 1));
- }
-
- /**
- * java.util.Arrays#binarySearch(double[], double)
- */
- public void test_binarySearch$DD() {
- // Test for method int java.util.Arrays.binarySearch(double [], double)
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on double[] answered incorrect position",
- Arrays.binarySearch(doubleArray, (double) counter) == (double) counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(doubleArray, (double) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(doubleArray, (double) arraySize) == -(arraySize + 1));
- for (int counter = 0; counter < arraySize; counter++)
- doubleArray[counter] -= (double) 50;
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on double[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(doubleArray, (double) (counter - 50)) == (double) counter);
-
- double[] specials = new double[] { Double.NEGATIVE_INFINITY,
- -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d,
- Double.MIN_VALUE, 2d, Double.MAX_VALUE,
- Double.POSITIVE_INFINITY, Double.NaN };
- for (int i = 0; i < specials.length; i++) {
- int result = Arrays.binarySearch(specials, specials[i]);
- assertTrue(specials[i] + " invalid: " + result, result == i);
- }
- assertEquals("-1d", -4, Arrays.binarySearch(specials, -1d));
- assertEquals("1d", -8, Arrays.binarySearch(specials, 1d));
-
- }
-
- /**
- * java.util.Arrays#binarySearch(float[], float)
- */
- public void test_binarySearch$FF() {
- // Test for method int java.util.Arrays.binarySearch(float [], float)
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on float[] answered incorrect position",
- Arrays.binarySearch(floatArray, (float) counter) == (float) counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(floatArray, (float) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(floatArray, (float) arraySize) == -(arraySize + 1));
- for (int counter = 0; counter < arraySize; counter++)
- floatArray[counter] -= (float) 50;
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on float[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(floatArray, (float) counter - 50) == (float) counter);
-
- float[] specials = new float[] { Float.NEGATIVE_INFINITY,
- -Float.MAX_VALUE, -2f, -Float.MIN_VALUE, -0f, 0f,
- Float.MIN_VALUE, 2f, Float.MAX_VALUE, Float.POSITIVE_INFINITY,
- Float.NaN };
- for (int i = 0; i < specials.length; i++) {
- int result = Arrays.binarySearch(specials, specials[i]);
- assertTrue(specials[i] + " invalid: " + result, result == i);
- }
- assertEquals("-1f", -4, Arrays.binarySearch(specials, -1f));
- assertEquals("1f", -8, Arrays.binarySearch(specials, 1f));
- }
-
- /**
- * java.util.Arrays#binarySearch(int[], int)
- */
- public void test_binarySearch$II() {
- // Test for method int java.util.Arrays.binarySearch(int [], int)
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on int[] answered incorrect position",
- Arrays.binarySearch(intArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(intArray, -1));
- assertTrue("Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(intArray, arraySize) == -(arraySize + 1));
- for (int counter = 0; counter < arraySize; counter++)
- intArray[counter] -= 50;
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on int[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(intArray, counter - 50) == counter);
- }
-
- /**
- * java.util.Arrays#binarySearch(long[], long)
- */
- public void test_binarySearch$JJ() {
- // Test for method int java.util.Arrays.binarySearch(long [], long)
- for (long counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on long[] answered incorrect position",
- Arrays.binarySearch(longArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(longArray, (long) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(longArray, (long) arraySize) == -(arraySize + 1));
- for (long counter = 0; counter < arraySize; counter++)
- longArray[(int) counter] -= (long) 50;
- for (long counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on long[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(longArray, counter - (long) 50) == counter);
- }
-
- /**
- * java.util.Arrays#binarySearch(java.lang.Object[],
- * java.lang.Object)
- */
- public void test_binarySearch$Ljava_lang_ObjectLjava_lang_Object() {
- // Test for method int java.util.Arrays.binarySearch(java.lang.Object
- // [], java.lang.Object)
- assertEquals(
- "Binary search succeeded for non-comparable value in empty array",
- -1, Arrays.binarySearch(new Object[] {}, new Object()));
- assertEquals(
- "Binary search succeeded for comparable value in empty array",
- -1, Arrays.binarySearch(new Object[] {}, new Integer(-1)));
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on Object[] answered incorrect position",
- Arrays.binarySearch(objectArray, objArray[counter]) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(objectArray, new Integer(-1)));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(objectArray, new Integer(arraySize)) == -(arraySize + 1));
-
- String[] sArray = new String[]{"1", "2", "3", "4", ""};
- Object[] oArray = sArray;
-
- try {
- Arrays.binarySearch(oArray, new Integer(10));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#binarySearch(java.lang.Object[],
- * java.lang.Object, java.util.Comparator)
- */
- public void test_binarySearch$Ljava_lang_ObjectLjava_lang_ObjectLjava_util_Comparator() {
- // Test for method int java.util.Arrays.binarySearch(java.lang.Object
- // [], java.lang.Object, java.util.Comparator)
- Comparator comp = new ReversedIntegerComparator();
- for (int counter = 0; counter < arraySize; counter++)
- objectArray[counter] = objArray[arraySize - counter - 1];
- assertTrue(
- "Binary search succeeded for value not present in array 1",
- Arrays.binarySearch(objectArray, new Integer(-1), comp) == -(arraySize + 1));
- assertEquals("Binary search succeeded for value not present in array 2",
- -1, Arrays.binarySearch(objectArray, new Integer(arraySize), comp));
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on Object[] with custom comparator answered incorrect position",
- Arrays.binarySearch(objectArray, objArray[counter], comp) == arraySize
- - counter - 1);
- }
-
- /**
- * java.util.Arrays#binarySearch(short[], short)
- */
- public void test_binarySearch$SS() {
- // Test for method int java.util.Arrays.binarySearch(short [], short)
- for (short counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on short[] answered incorrect position",
- Arrays.binarySearch(shortArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(intArray, (short) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(intArray, (short) arraySize) == -(arraySize + 1));
- for (short counter = 0; counter < arraySize; counter++)
- shortArray[counter] -= 50;
- for (short counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on short[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(shortArray, (short) (counter - 50)) == counter);
- }
-
- /**
- * java.util.Arrays#fill(byte[], byte)
- */
- public void test_fill$BB() {
- // Test for method void java.util.Arrays.fill(byte [], byte)
-
- byte d[] = new byte[1000];
- Arrays.fill(d, Byte.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill byte array correctly",
- d[i] == Byte.MAX_VALUE);
- }
-
- /**
- * java.util.Arrays#fill(byte[], int, int, byte)
- */
- public void test_fill$BIIB() {
- // Test for method void java.util.Arrays.fill(byte [], int, int, byte)
- byte val = Byte.MAX_VALUE;
- byte d[] = new byte[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill byte array correctly", d[i] == val);
-
- int result;
- try {
- Arrays.fill(new byte[2], 2, 1, (byte) 27);
- result = 0;
- } catch (ArrayIndexOutOfBoundsException e) {
- result = 1;
- } catch (IllegalArgumentException e) {
- result = 2;
- }
- assertEquals("Wrong exception1", 2, result);
- try {
- Arrays.fill(new byte[2], -1, 1, (byte) 27);
- result = 0;
- } catch (ArrayIndexOutOfBoundsException e) {
- result = 1;
- } catch (IllegalArgumentException e) {
- result = 2;
- }
- assertEquals("Wrong exception2", 1, result);
- try {
- Arrays.fill(new byte[2], 1, 4, (byte) 27);
- result = 0;
- } catch (ArrayIndexOutOfBoundsException e) {
- result = 1;
- } catch (IllegalArgumentException e) {
- result = 2;
- }
- assertEquals("Wrong exception", 1, result);
- }
-
- /**
- * java.util.Arrays#fill(short[], short)
- */
- public void test_fill$SS() {
- // Test for method void java.util.Arrays.fill(short [], short)
-
- short d[] = new short[1000];
- Arrays.fill(d, Short.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill short array correctly",
- d[i] == Short.MAX_VALUE);
- }
-
- /**
- * java.util.Arrays#fill(short[], int, int, short)
- */
- public void test_fill$SIIS() {
- // Test for method void java.util.Arrays.fill(short [], int, int, short)
- short val = Short.MAX_VALUE;
- short d[] = new short[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill short array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(char[], char)
- */
- public void test_fill$CC() {
- // Test for method void java.util.Arrays.fill(char [], char)
-
- char d[] = new char[1000];
- Arrays.fill(d, 'V');
- for (int i = 0; i < d.length; i++)
- assertEquals("Failed to fill char array correctly", 'V', d[i]);
- }
-
- /**
- * java.util.Arrays#fill(char[], int, int, char)
- */
- public void test_fill$CIIC() {
- // Test for method void java.util.Arrays.fill(char [], int, int, char)
- char val = 'T';
- char d[] = new char[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill char array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(int[], int)
- */
- public void test_fill$II() {
- // Test for method void java.util.Arrays.fill(int [], int)
-
- int d[] = new int[1000];
- Arrays.fill(d, Integer.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill int array correctly",
- d[i] == Integer.MAX_VALUE);
- }
-
- /**
- * java.util.Arrays#fill(int[], int, int, int)
- */
- public void test_fill$IIII() {
- // Test for method void java.util.Arrays.fill(int [], int, int, int)
- int val = Integer.MAX_VALUE;
- int d[] = new int[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill int array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(long[], long)
- */
- public void test_fill$JJ() {
- // Test for method void java.util.Arrays.fill(long [], long)
-
- long d[] = new long[1000];
- Arrays.fill(d, Long.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill long array correctly",
- d[i] == Long.MAX_VALUE);
- }
-
- /**
- * java.util.Arrays#fill(long[], int, int, long)
- */
- public void test_fill$JIIJ() {
- // Test for method void java.util.Arrays.fill(long [], int, int, long)
- long d[] = new long[1000];
- Arrays.fill(d, 400, d.length, Long.MAX_VALUE);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == Long.MAX_VALUE));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill long array correctly",
- d[i] == Long.MAX_VALUE);
-
- try {
- Arrays.fill(d, 10, 0, Long.MIN_VALUE);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, Long.MAX_VALUE);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, Long.MAX_VALUE);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(float[], float)
- */
- public void test_fill$FF() {
- // Test for method void java.util.Arrays.fill(float [], float)
- float d[] = new float[1000];
- Arrays.fill(d, Float.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill float array correctly",
- d[i] == Float.MAX_VALUE);
- }
-
- /**
- * java.util.Arrays#fill(float[], int, int, float)
- */
- public void test_fill$FIIF() {
- // Test for method void java.util.Arrays.fill(float [], int, int, float)
- float val = Float.MAX_VALUE;
- float d[] = new float[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill float array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(double[], double)
- */
- public void test_fill$DD() {
- // Test for method void java.util.Arrays.fill(double [], double)
-
- double d[] = new double[1000];
- Arrays.fill(d, Double.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill double array correctly",
- d[i] == Double.MAX_VALUE);
- }
-
- /**
- * java.util.Arrays#fill(double[], int, int, double)
- */
- public void test_fill$DIID() {
- // Test for method void java.util.Arrays.fill(double [], int, int,
- // double)
- double val = Double.MAX_VALUE;
- double d[] = new double[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill double array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(boolean[], boolean)
- */
- public void test_fill$ZZ() {
- // Test for method void java.util.Arrays.fill(boolean [], boolean)
-
- boolean d[] = new boolean[1000];
- Arrays.fill(d, true);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill boolean array correctly", d[i]);
- }
-
- /**
- * java.util.Arrays#fill(boolean[], int, int, boolean)
- */
- public void test_fill$ZIIZ() {
- // Test for method void java.util.Arrays.fill(boolean [], int, int,
- // boolean)
- boolean val = true;
- boolean d[] = new boolean[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill boolean array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#fill(java.lang.Object[], java.lang.Object)
- */
- public void test_fill$Ljava_lang_ObjectLjava_lang_Object() {
- // Test for method void java.util.Arrays.fill(java.lang.Object [],
- // java.lang.Object)
- Object val = new Object();
- Object d[] = new Object[1000];
- Arrays.fill(d, 0, d.length, val);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill Object array correctly", d[i] == val);
- }
-
- /**
- * java.util.Arrays#fill(java.lang.Object[], int, int,
- * java.lang.Object)
- */
- public void test_fill$Ljava_lang_ObjectIILjava_lang_Object() {
- // Test for method void java.util.Arrays.fill(java.lang.Object [], int,
- // int, java.lang.Object)
- Object val = new Object();
- Object d[] = new Object[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill Object array correctly", d[i] == val);
-
- Arrays.fill(d, 400, d.length, null);
- for (int i = 400; i < d.length; i++)
- assertNull("Failed to fill Object array correctly with nulls",
- d[i]);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#equals(byte[], byte[])
- */
- public void test_equals$B$B() {
- // Test for method boolean java.util.Arrays.equals(byte [], byte [])
- byte d[] = new byte[1000];
- byte x[] = new byte[1000];
- Arrays.fill(d, Byte.MAX_VALUE);
- Arrays.fill(x, Byte.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Byte.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * java.util.Arrays#equals(short[], short[])
- */
- public void test_equals$S$S() {
- // Test for method boolean java.util.Arrays.equals(short [], short [])
- short d[] = new short[1000];
- short x[] = new short[1000];
- Arrays.fill(d, Short.MAX_VALUE);
- Arrays.fill(x, Short.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Short.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * java.util.Arrays#equals(char[], char[])
- */
- public void test_equals$C$C() {
- // Test for method boolean java.util.Arrays.equals(char [], char [])
- char d[] = new char[1000];
- char x[] = new char[1000];
- char c = 'T';
- Arrays.fill(d, c);
- Arrays.fill(x, 'L');
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, c);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * java.util.Arrays#equals(int[], int[])
- */
- public void test_equals$I$I() {
- // Test for method boolean java.util.Arrays.equals(int [], int [])
- int d[] = new int[1000];
- int x[] = new int[1000];
- Arrays.fill(d, Integer.MAX_VALUE);
- Arrays.fill(x, Integer.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Integer.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("wrong result for null array1", !Arrays.equals(new int[2],
- null));
- assertTrue("wrong result for null array2", !Arrays.equals(null,
- new int[2]));
- }
-
- /**
- * java.util.Arrays#equals(long[], long[])
- */
- public void test_equals$J$J() {
- // Test for method boolean java.util.Arrays.equals(long [], long [])
- long d[] = new long[1000];
- long x[] = new long[1000];
- Arrays.fill(d, Long.MAX_VALUE);
- Arrays.fill(x, Long.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Long.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("should be false", !Arrays.equals(
- new long[] { 0x100000000L }, new long[] { 0x200000000L }));
-
- }
-
- /**
- * java.util.Arrays#equals(float[], float[])
- */
- public void test_equals$F$F() {
- // Test for method boolean java.util.Arrays.equals(float [], float [])
- float d[] = new float[1000];
- float x[] = new float[1000];
- Arrays.fill(d, Float.MAX_VALUE);
- Arrays.fill(x, Float.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Float.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("NaN not equals", Arrays.equals(new float[] { Float.NaN },
- new float[] { Float.NaN }));
- assertTrue("0f equals -0f", !Arrays.equals(new float[] { 0f },
- new float[] { -0f }));
- }
-
- /**
- * java.util.Arrays#equals(double[], double[])
- */
- public void test_equals$D$D() {
- // Test for method boolean java.util.Arrays.equals(double [], double [])
- double d[] = new double[1000];
- double x[] = new double[1000];
- Arrays.fill(d, Double.MAX_VALUE);
- Arrays.fill(x, Double.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Double.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("should be false", !Arrays.equals(new double[] { 1.0 },
- new double[] { 2.0 }));
-
- assertTrue("NaN not equals", Arrays.equals(new double[] { Double.NaN },
- new double[] { Double.NaN }));
- assertTrue("0d equals -0d", !Arrays.equals(new double[] { 0d },
- new double[] { -0d }));
- }
-
- /**
- * java.util.Arrays#equals(boolean[], boolean[])
- */
- public void test_equals$Z$Z() {
- // Test for method boolean java.util.Arrays.equals(boolean [], boolean
- // [])
- boolean d[] = new boolean[1000];
- boolean x[] = new boolean[1000];
- Arrays.fill(d, true);
- Arrays.fill(x, false);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, true);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * java.util.Arrays#equals(java.lang.Object[], java.lang.Object[])
- */
- public void test_equals$Ljava_lang_Object$Ljava_lang_Object() {
- // Test for method boolean java.util.Arrays.equals(java.lang.Object [],
- // java.lang.Object [])
- Object d[] = new Object[1000];
- Object x[] = new Object[1000];
- Object o = new Object();
- Arrays.fill(d, o);
- Arrays.fill(x, new Object());
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, o);
- d[50] = null;
- x[50] = null;
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * java.util.Arrays#sort(byte[])
- */
- public void test_sort$B() {
- // Test for method void java.util.Arrays.sort(byte [])
- byte[] reversedArray = new byte[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (byte) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (byte) counter);
- }
-
- /**
- * java.util.Arrays#sort(byte[], int, int)
- */
- public void test_sort$BII() {
- // Test for method void java.util.Arrays.sort(byte [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- byte[] reversedArray = new byte[arraySize];
- byte[] originalReversedArray = new byte[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (byte) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(char[])
- */
- public void test_sort$C() {
- // Test for method void java.util.Arrays.sort(char [])
- char[] reversedArray = new char[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (char) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (char) counter);
-
- }
-
- /**
- * java.util.Arrays#sort(char[], int, int)
- */
- public void test_sort$CII() {
- // Test for method void java.util.Arrays.sort(char [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- char[] reversedArray = new char[arraySize];
- char[] originalReversedArray = new char[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (char) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(double[])
- */
- public void test_sort$D() {
- // Test for method void java.util.Arrays.sort(double [])
- double[] reversedArray = new double[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (double) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (double) counter);
-
- double[] specials1 = new double[] { Double.NaN, Double.MAX_VALUE,
- Double.MIN_VALUE, 0d, -0d, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY };
- double[] specials2 = new double[] { 0d, Double.POSITIVE_INFINITY, -0d,
- Double.NEGATIVE_INFINITY, Double.MIN_VALUE, Double.NaN,
- Double.MAX_VALUE };
- double[] answer = new double[] { Double.NEGATIVE_INFINITY, -0d, 0d,
- Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY,
- Double.NaN };
-
- Arrays.sort(specials1);
- Object[] print1 = new Object[specials1.length];
- for (int i = 0; i < specials1.length; i++)
- print1[i] = new Double(specials1[i]);
- assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1),
- Arrays.equals(specials1, answer));
-
- Arrays.sort(specials2);
- Object[] print2 = new Object[specials2.length];
- for (int i = 0; i < specials2.length; i++)
- print2[i] = new Double(specials2[i]);
- assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
- }
-
- /**
- * java.util.Arrays#sort(double[], int, int)
- */
- public void test_sort$DII() {
- // Test for method void java.util.Arrays.sort(double [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- double[] reversedArray = new double[arraySize];
- double[] originalReversedArray = new double[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (double) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(float[])
- */
- public void test_sort$F() {
- // Test for method void java.util.Arrays.sort(float [])
- float[] reversedArray = new float[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (float) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (float) counter);
-
- float[] specials1 = new float[] { Float.NaN, Float.MAX_VALUE,
- Float.MIN_VALUE, 0f, -0f, Float.POSITIVE_INFINITY,
- Float.NEGATIVE_INFINITY };
- float[] specials2 = new float[] { 0f, Float.POSITIVE_INFINITY, -0f,
- Float.NEGATIVE_INFINITY, Float.MIN_VALUE, Float.NaN,
- Float.MAX_VALUE };
- float[] answer = new float[] { Float.NEGATIVE_INFINITY, -0f, 0f,
- Float.MIN_VALUE, Float.MAX_VALUE, Float.POSITIVE_INFINITY,
- Float.NaN };
-
- Arrays.sort(specials1);
- Object[] print1 = new Object[specials1.length];
- for (int i = 0; i < specials1.length; i++)
- print1[i] = new Float(specials1[i]);
- assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1),
- Arrays.equals(specials1, answer));
-
- Arrays.sort(specials2);
- Object[] print2 = new Object[specials2.length];
- for (int i = 0; i < specials2.length; i++)
- print2[i] = new Float(specials2[i]);
- assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
- }
-
- /**
- * java.util.Arrays#sort(float[], int, int)
- */
- public void test_sort$FII() {
- // Test for method void java.util.Arrays.sort(float [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- float[] reversedArray = new float[arraySize];
- float[] originalReversedArray = new float[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (float) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(int[])
- */
- public void test_sort$I() {
- // Test for method void java.util.Arrays.sort(int [])
- int[] reversedArray = new int[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = arraySize - counter - 1;
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == counter);
- }
-
- /**
- * java.util.Arrays#sort(int[], int, int)
- */
- public void test_sort$III() {
- // Test for method void java.util.Arrays.sort(int [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- int[] reversedArray = new int[arraySize];
- int[] originalReversedArray = new int[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = arraySize - counter - 1;
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(long[])
- */
- public void test_sort$J() {
- // Test for method void java.util.Arrays.sort(long [])
- long[] reversedArray = new long[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (long) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (long) counter);
-
- }
-
- /**
- * java.util.Arrays#sort(long[], int, int)
- */
- public void test_sort$JII() {
- // Test for method void java.util.Arrays.sort(long [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- long[] reversedArray = new long[arraySize];
- long[] originalReversedArray = new long[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (long) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(java.lang.Object[])
- */
- public void test_sort$Ljava_lang_Object() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [])
- Object[] reversedArray = new Object[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = objectArray[arraySize - counter - 1];
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == objectArray[counter]);
-
- Arrays.fill(reversedArray, 0, reversedArray.length/2, "String");
- Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1));
-
- try {
- Arrays.sort(reversedArray);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#sort(java.lang.Object[], int, int)
- */
- public void test_sort$Ljava_lang_ObjectII() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [], int,
- // int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- Object[] reversedArray = new Object[arraySize];
- Object[] originalReversedArray = new Object[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = objectArray[arraySize - counter - 1];
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- ((Comparable) reversedArray[counter])
- .compareTo(reversedArray[counter + 1]) <= 0);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- Arrays.fill(reversedArray, 0, reversedArray.length/2, "String");
- Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1));
-
- try {
- Arrays.sort(reversedArray, reversedArray.length/4, 3*reversedArray.length/4);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Arrays.sort(reversedArray, 0, reversedArray.length/4);
- Arrays.sort(reversedArray, 3*reversedArray.length/4, reversedArray.length);
- }
-
- /**
- * java.util.Arrays#sort(java.lang.Object[], int, int,
- * java.util.Comparator)
- */
- public void test_sort$Ljava_lang_ObjectIILjava_util_Comparator() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [], int,
- // int, java.util.Comparator)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- ReversedIntegerComparator comp = new ReversedIntegerComparator();
- Object[] originalArray = new Object[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- originalArray[counter] = objectArray[counter];
- Arrays.sort(objectArray, startIndex, endIndex, comp);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- objectArray[counter] == originalArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds", comp.compare(
- objectArray[counter], objectArray[counter + 1]) <= 0);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- objectArray[counter] == originalArray[counter]);
-
- Arrays.fill(originalArray, 0, originalArray.length/2, "String");
- Arrays.fill(originalArray, originalArray.length/2, originalArray.length, new Integer(1));
-
- try {
- Arrays.sort(originalArray, startIndex, endIndex, comp);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Arrays.sort(originalArray, endIndex, originalArray.length, comp);
-
- try {
- Arrays.sort(originalArray, endIndex, originalArray.length + 1, comp);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.sort(originalArray, -1, startIndex, comp);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.sort(originalArray, originalArray.length, endIndex, comp);
- fail("IllegalArgumentException expected");
- } catch(IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#sort(java.lang.Object[], java.util.Comparator)
- */
- public void test_sort$Ljava_lang_ObjectLjava_util_Comparator() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [],
- // java.util.Comparator)
- ReversedIntegerComparator comp = new ReversedIntegerComparator();
- Arrays.sort(objectArray, comp);
- for (int counter = 0; counter < arraySize - 1; counter++)
- assertTrue("Array not sorted correctly with custom comparator",
- comp
- .compare(objectArray[counter],
- objectArray[counter + 1]) <= 0);
-
- Arrays.fill(objectArray, 0, objectArray.length/2, "String");
- Arrays.fill(objectArray, objectArray.length/2, objectArray.length, new Integer(1));
-
- try {
- Arrays.sort(objectArray, comp);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Arrays#sort(short[])
- */
- public void test_sort$S() {
- // Test for method void java.util.Arrays.sort(short [])
- short[] reversedArray = new short[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (short) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (short) counter);
- }
-
- /**
- * java.util.Arrays#sort(short[], int, int)
- */
- public void test_sort$SII() {
- // Test for method void java.util.Arrays.sort(short [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- short[] reversedArray = new short[arraySize];
- short[] originalReversedArray = new short[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (short) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
- }
-
- /**
- * java.util.Arrays#sort(byte[], int, int)
- */
- public void test_java_util_Arrays_sort_byte_array_NPE() {
- byte[] byte_array_null = null;
- try {
- java.util.Arrays.sort(byte_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(byte_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(char[], int, int)
- */
- public void test_java_util_Arrays_sort_char_array_NPE() {
- char[] char_array_null = null;
- try {
- java.util.Arrays.sort(char_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(char_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(double[], int, int)
- */
- public void test_java_util_Arrays_sort_double_array_NPE() {
- double[] double_array_null = null;
- try {
- java.util.Arrays.sort(double_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(double_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(float[], int, int)
- */
- public void test_java_util_Arrays_sort_float_array_NPE() {
- float[] float_array_null = null;
- try {
- java.util.Arrays.sort(float_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(float_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(int[], int, int)
- */
- public void test_java_util_Arrays_sort_int_array_NPE() {
- int[] int_array_null = null;
- try {
- java.util.Arrays.sort(int_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(int_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(Object[], int, int)
- */
- public void test_java_util_Arrays_sort_object_array_NPE() {
- Object[] object_array_null = null;
- try {
- java.util.Arrays.sort(object_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(object_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(object_array_null, (int) -1, (int) 1, null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(long[], int, int)
- */
- public void test_java_util_Arrays_sort_long_array_NPE() {
- long[] long_array_null = null;
- try {
- java.util.Arrays.sort(long_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(long_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Arrays#sort(short[], int, int)
- */
- public void test_java_util_Arrays_sort_short_array_NPE() {
- short[] short_array_null = null;
- try {
- java.util.Arrays.sort(short_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(short_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- // Lenghts of arrays to test in test_sort;
- private static final int[] LENGTHS = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 100, 1000, 10000 };
-
- /**
- * java.util.Arrays#sort()
- */
- public void test_sort() {
- for (int len : LENGTHS) {
- PrimitiveTypeArrayBuilder.reset();
- int[] golden = new int[len];
- for (int m = 1; m < 2 * len; m *= 2) {
- for (PrimitiveTypeArrayBuilder builder : PrimitiveTypeArrayBuilder.values()) {
- builder.build(golden, m);
- int[] test = golden.clone();
-
- for (PrimitiveTypeConverter converter : PrimitiveTypeConverter.values()) {
- Object convertedGolden = converter.convert(golden);
- Object convertedTest = converter.convert(test);
- sort(convertedTest);
- checkSorted(convertedTest);
- assertEquals(checkSum(convertedGolden), checkSum(convertedTest));
- }
- }
- }
- }
- }
-
- private void sort(Object array) {
- if (array instanceof int[]) {
- Arrays.sort((int[]) array);
- }
- else if (array instanceof long[]) {
- Arrays.sort((long[]) array);
- } else if (array instanceof short[]) {
- Arrays.sort((short[]) array);
- } else if (array instanceof byte[]) {
- Arrays.sort((byte[]) array);
- } else if (array instanceof char[]) {
- Arrays.sort((char[]) array);
- } else if (array instanceof float[]) {
- Arrays.sort((float[]) array);
- } else if (array instanceof double[]) {
- Arrays.sort((double[]) array);
- } else {
- fail("Unknow type of array: " + array.getClass());
- }
- }
-
- private void checkSorted(Object array) {
- if (array instanceof int[]) {
- checkSorted((int[]) array);
- } else if (array instanceof long[]) {
- checkSorted((long[]) array);
- } else if (array instanceof short[]) {
- checkSorted((short[]) array);
- } else if (array instanceof byte[]) {
- checkSorted((byte[]) array);
- } else if (array instanceof char[]) {
- checkSorted((char[]) array);
- } else if (array instanceof float[]) {
- checkSorted((float[]) array);
- } else if (array instanceof double[]) {
- checkSorted((double[]) array);
- } else {
- fail("Unknow type of array: " + array.getClass());
- }
- }
-
- private void checkSorted(int[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
- private void checkSorted(long[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
- private void checkSorted(short[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
- private void checkSorted(byte[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
- private void checkSorted(char[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
- private void checkSorted(float[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
- private void checkSorted(double[] a) {
- for (int i = 0; i < a.length - 1; i++) {
- if (a[i] > a[i + 1]) {
- orderFail(i, "" + a[i], "" + a[i + 1]);
- }
- }
- }
-
-
- private void orderFail(int index, String value1, String value2) {
- fail("Array is not sorted at " + index + "-th position: " + value1 + " and " + value2);
- }
-
- private int checkSum(Object array) {
- if (array instanceof int[]) {
- return checkSum((int[]) array);
- } else if (array instanceof long[]) {
- return checkSum((long[]) array);
- } else if (array instanceof short[]) {
- return checkSum((short[]) array);
- } else if (array instanceof byte[]) {
- return checkSum((byte[]) array);
- } else if (array instanceof char[]) {
- return checkSum((char[]) array);
- } else if (array instanceof float[]) {
- return checkSum((float[]) array);
- } else if (array instanceof double[]) {
- return checkSum((double[]) array);
- } else {
- fail("Unknow type of array: " + array.getClass());
- }
- throw new AssertionError(); // Needed to shut up compiler
- }
-
- private int checkSum(int[] a) {
- int checkSum = 0;
-
- for (int e : a) {
- checkSum ^= e; // xor
- }
- return checkSum;
- }
-
- private int checkSum(long[] a) {
- long checkSum = 0;
-
- for (long e : a) {
- checkSum ^= e; // xor
- }
- return (int) checkSum;
- }
-
- private int checkSum(short[] a) {
- short checkSum = 0;
-
- for (short e : a) {
- checkSum ^= e; // xor
- }
- return (int) checkSum;
- }
-
- private int checkSum(byte[] a) {
- byte checkSum = 0;
-
- for (byte e : a) {
- checkSum ^= e; // xor
- }
- return (int) checkSum;
- }
-
- private int checkSum(char[] a) {
- char checkSum = 0;
-
- for (char e : a) {
- checkSum ^= e; // xor
- }
- return (int) checkSum;
- }
-
- private int checkSum(float[] a) {
- int checkSum = 0;
-
- for (float e : a) {
- checkSum ^= (int) e; // xor
- }
- return checkSum;
- }
-
- private int checkSum(double[] a) {
- int checkSum = 0;
-
- for (double e : a) {
- checkSum ^= (int) e; // xor
- }
- return checkSum;
- }
-
- private enum PrimitiveTypeArrayBuilder {
-
- RANDOM {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = ourRandom.nextInt();
- }
- }
- },
-
- ASCENDING {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = m + i;
- }
- }
- },
-
- DESCENDING {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = a.length - m - i;
- }
- }
- },
-
- ALL_EQUAL {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = m;
- }
- }
- },
-
- SAW {
- void build(int[] a, int m) {
- int incCount = 1;
- int decCount = a.length;
- int i = 0;
- int period = m;
- m--;
-
- while (true) {
- for (int k = 1; k <= period; k++) {
- if (i >= a.length) {
- return;
- }
- a[i++] = incCount++;
- }
- period += m;
-
- for (int k = 1; k <= period; k++) {
- if (i >= a.length) {
- return;
- }
- a[i++] = decCount--;
- }
- period += m;
- }
- }
- },
-
- REPEATED {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = i % m;
- }
- }
- },
-
- DUPLICATED {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = ourRandom.nextInt(m);
- }
- }
- },
-
- ORGAN_PIPES {
- void build(int[] a, int m) {
- int middle = a.length / (m + 1);
-
- for (int i = 0; i < middle; i++) {
- a[i] = i;
- }
- for (int i = middle; i < a.length ; i++) {
- a[i] = a.length - i - 1;
- }
- }
- },
-
- STAGGER {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = (i * m + i) % a.length;
- }
- }
- },
-
- PLATEAU {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = Math.min(i, m);
- }
- }
- },
-
- SHUFFLE {
- void build(int[] a, int m) {
- for (int i = 0; i < a.length; i++) {
- a[i] = ourRandom.nextBoolean() ? (ourFirst += 2) : (ourSecond += 2);
- }
- }
- };
-
- abstract void build(int[] a, int m);
-
- static void reset() {
- ourRandom = new Random(666);
- ourFirst = 0;
- ourSecond = 0;
- }
-
- @Override
- public String toString() {
- String name = name();
-
- for (int i = name.length(); i < 12; i++) {
- name += " " ;
- }
- return name;
- }
-
- private static int ourFirst;
- private static int ourSecond;
- private static Random ourRandom = new Random(666);
- }
-
- private enum PrimitiveTypeConverter {
-
- INT {
- Object convert(int[] a) {
- return a;
- }
- },
-
- LONG {
- Object convert(int[] a) {
- long[] b = new long[a.length];
-
- for (int i = 0; i < a.length; i++) {
- b[i] = (int) a[i];
- }
- return b;
- }
- },
-
- BYTE {
- Object convert(int[] a) {
- byte[] b = new byte[a.length];
-
- for (int i = 0; i < a.length; i++) {
- b[i] = (byte) a[i];
- }
- return b;
- }
- },
-
- SHORT {
- Object convert(int[] a) {
- short[] b = new short[a.length];
-
- for (int i = 0; i < a.length; i++) {
- b[i] = (short) a[i];
- }
- return b;
- }
- },
-
- CHAR {
- Object convert(int[] a) {
- char[] b = new char[a.length];
-
- for (int i = 0; i < a.length; i++) {
- b[i] = (char) a[i];
- }
- return b;
- }
- },
-
- FLOAT {
- Object convert(int[] a) {
- float[] b = new float[a.length];
-
- for (int i = 0; i < a.length; i++) {
- b[i] = (float) a[i];
- }
- return b;
- }
- },
-
- DOUBLE {
- Object convert(int[] a) {
- double[] b = new double[a.length];
-
- for (int i = 0; i < a.length; i++) {
- b[i] = (double) a[i];
- }
- return b;
- }
- };
-
- abstract Object convert(int[] a);
-
- public String toString() {
- String name = name();
-
- for (int i = name.length(); i < 9; i++) {
- name += " " ;
- }
- return name;
- }
- }
-
-
- /**
- * java.util.Arrays#deepEquals(Object[], Object[])
- */
- public void test_deepEquals$Ljava_lang_ObjectLjava_lang_Object() {
- int [] a1 = {1, 2, 3};
- short [] a2 = {0, 1};
- Object [] a3 = {new Integer(1), a2};
- int [] a4 = {6, 5, 4};
-
- int [] b1 = {1, 2, 3};
- short [] b2 = {0, 1};
- Object [] b3 = {new Integer(1), b2};
-
- Object a [] = {a1, a2, a3};
- Object b [] = {b1, b2, b3};
-
- assertFalse(Arrays.equals(a, b));
- assertTrue(Arrays.deepEquals(a,b));
-
- a[2] = a4;
-
- assertFalse(Arrays.deepEquals(a, b));
- }
-
- /**
- * java.util.Arrays#deepHashCode(Object[])
- */
- public void test_deepHashCode$Ljava_lang_Object() {
- int [] a1 = {1, 2, 3};
- short [] a2 = {0, 1};
- Object [] a3 = {new Integer(1), a2};
-
- int [] b1 = {1, 2, 3};
- short [] b2 = {0, 1};
- Object [] b3 = {new Integer(1), b2};
-
- Object a [] = {a1, a2, a3};
- Object b [] = {b1, b2, b3};
-
- int deep_hash_a = Arrays.deepHashCode(a);
- int deep_hash_b = Arrays.deepHashCode(b);
-
- assertEquals(deep_hash_a, deep_hash_b);
- }
-
- /**
- * java.util.Arrays#hashCode(boolean[] a)
- */
- public void test_hashCode$LZ() {
- int listHashCode;
- int arrayHashCode;
-
- boolean [] boolArr = {true, false, false, true, false};
- List listOfBoolean = new LinkedList();
- for (int i = 0; i < boolArr.length; i++) {
- listOfBoolean.add(new Boolean(boolArr[i]));
- }
- listHashCode = listOfBoolean.hashCode();
- arrayHashCode = Arrays.hashCode(boolArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * java.util.Arrays#hashCode(int[] a)
- */
- public void test_hashCode$LI() {
- int listHashCode;
- int arrayHashCode;
-
- int [] intArr = {10, 5, 134, 7, 19};
- List listOfInteger = new LinkedList();
-
- for (int i = 0; i < intArr.length; i++) {
- listOfInteger.add(new Integer(intArr[i]));
- }
- listHashCode = listOfInteger.hashCode();
- arrayHashCode = Arrays.hashCode(intArr);
- assertEquals(listHashCode, arrayHashCode);
-
- int [] intArr2 = {10, 5, 134, 7, 19};
- assertEquals(Arrays.hashCode(intArr2), Arrays.hashCode(intArr));
- }
-
- /**
- * java.util.Arrays#hashCode(char[] a)
- */
- public void test_hashCode$LC() {
- int listHashCode;
- int arrayHashCode;
-
- char [] charArr = {'a', 'g', 'x', 'c', 'm'};
- List listOfCharacter = new LinkedList();
- for (int i = 0; i < charArr.length; i++) {
- listOfCharacter.add(new Character(charArr[i]));
- }
- listHashCode = listOfCharacter.hashCode();
- arrayHashCode = Arrays.hashCode(charArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * java.util.Arrays#hashCode(byte[] a)
- */
- public void test_hashCode$LB() {
- int listHashCode;
- int arrayHashCode;
-
- byte [] byteArr = {5, 9, 7, 6, 17};
- List listOfByte = new LinkedList();
- for (int i = 0; i < byteArr.length; i++) {
- listOfByte.add(new Byte(byteArr[i]));
- }
- listHashCode = listOfByte.hashCode();
- arrayHashCode = Arrays.hashCode(byteArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * java.util.Arrays#hashCode(long[] a)
- */
- public void test_hashCode$LJ() {
- int listHashCode;
- int arrayHashCode;
-
- long [] longArr = {67890234512l, 97587236923425l, 257421912912l,
- 6754268100l, 5};
- List listOfLong = new LinkedList();
- for (int i = 0; i < longArr.length; i++) {
- listOfLong.add(new Long(longArr[i]));
- }
- listHashCode = listOfLong.hashCode();
- arrayHashCode = Arrays.hashCode(longArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * java.util.Arrays#hashCode(float[] a)
- */
- public void test_hashCode$LF() {
- int listHashCode;
- int arrayHashCode;
-
- float [] floatArr = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f};
- List listOfFloat = new LinkedList();
- for (int i = 0; i < floatArr.length; i++) {
- listOfFloat.add(new Float(floatArr[i]));
- }
- listHashCode = listOfFloat.hashCode();
- arrayHashCode = Arrays.hashCode(floatArr);
- assertEquals(listHashCode, arrayHashCode);
-
- float [] floatArr2 = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f};
- assertEquals(Arrays.hashCode(floatArr2), Arrays.hashCode(floatArr));
- }
-
- /**
- * java.util.Arrays#hashCode(double[] a)
- */
- public void test_hashCode$LD() {
- int listHashCode;
- int arrayHashCode;
-
- double [] doubleArr = {0.134945657, 0.0038754, 11e-150, -30e-300, 10e-4};
- List listOfDouble = new LinkedList();
- for (int i = 0; i < doubleArr.length; i++) {
- listOfDouble.add(new Double(doubleArr[i]));
- }
- listHashCode = listOfDouble.hashCode();
- arrayHashCode = Arrays.hashCode(doubleArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * java.util.Arrays#hashCode(short[] a)
- */
- public void test_hashCode$LS() {
- int listHashCode;
- int arrayHashCode;
-
- short [] shortArr = {35, 13, 45, 2, 91};
- List listOfShort = new LinkedList();
- for (int i = 0; i < shortArr.length; i++) {
- listOfShort.add(new Short(shortArr[i]));
- }
- listHashCode = listOfShort.hashCode();
- arrayHashCode = Arrays.hashCode(shortArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * java.util.Arrays#hashCode(Object[] a)
- */
- public void test_hashCode$Ljava_lang_Object() {
- int listHashCode;
- int arrayHashCode;
-
- Object[] objectArr = {new Integer(1), new Float(10e-12f), null};
- List listOfObject= new LinkedList();
- for (int i = 0; i < objectArr.length; i++) {
- listOfObject.add(objectArr[i]);
- }
- listHashCode = listOfObject.hashCode();
- arrayHashCode = Arrays.hashCode(objectArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[arraySize];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
-
- booleanArray = new boolean[arraySize];
- byteArray = new byte[arraySize];
- charArray = new char[arraySize];
- doubleArray = new double[arraySize];
- floatArray = new float[arraySize];
- intArray = new int[arraySize];
- longArray = new long[arraySize];
- objectArray = new Object[arraySize];
- shortArray = new short[arraySize];
-
- for (int counter = 0; counter < arraySize; counter++) {
- byteArray[counter] = (byte) counter;
- charArray[counter] = (char) (counter + 1);
- doubleArray[counter] = counter;
- floatArray[counter] = counter;
- intArray[counter] = counter;
- longArray[counter] = counter;
- objectArray[counter] = objArray[counter];
- shortArray[counter] = (short) counter;
- }
- for (int counter = 0; counter < arraySize; counter += 2) {
- booleanArray[counter] = false;
- booleanArray[counter + 1] = true;
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- objArray = null;
- booleanArray = null;
- byteArray = null;
- charArray = null;
- doubleArray = null;
- floatArray = null;
- intArray = null;
- longArray = null;
- objectArray = null;
- shortArray = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/BitSetTest.java b/luni/src/test/java/tests/api/java/util/BitSetTest.java
deleted file mode 100644
index e1abc48..0000000
--- a/luni/src/test/java/tests/api/java/util/BitSetTest.java
+++ /dev/null
@@ -1,1279 +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 tests.api.java.util;
-
-import java.util.BitSet;
-
-public class BitSetTest extends junit.framework.TestCase {
-
- BitSet eightbs;
-
- public void test_Constructor() {
- BitSet bs = new BitSet();
- // Default size for a BitSet should be 64 elements;
- assertEquals("Created BitSet of incorrect size", 64, bs.size());
- assertEquals("New BitSet had invalid string representation", "{}", bs.toString());
- }
-
- public void test_ConstructorI() {
- BitSet bs = new BitSet(128);
- // Default size for a BitSet should be 64 elements;
-
- assertEquals("Created BitSet of incorrect size", 128, bs.size());
- assertTrue("New BitSet had invalid string representation: "
- + bs.toString(), bs.toString().equals("{}"));
-
- // All BitSets are created with elements of multiples of 64
-
- bs = new BitSet(89);
- assertEquals("Failed to round BitSet element size", 128, bs.size());
-
- try {
- bs = new BitSet(-9);
- fail();
- } catch (NegativeArraySizeException expected) {
- }
- }
-
- public void test_clone() {
- BitSet bs = (BitSet) eightbs.clone();
- assertTrue("Clone failed to return equal BitSet", eightbs.equals(bs));
-
- }
-
- public void test_equalsLjava_lang_Object() {
- BitSet bs;
-
- bs = (BitSet) eightbs.clone();
- assertTrue("Same BitSet returned false", eightbs.equals(eightbs));
- assertTrue("Identical BitSets returned false", eightbs.equals(bs));
- bs.clear(6);
- assertTrue("Different BitSets returned true", !eightbs.equals(bs));
- // Grow the BitSet
- bs = (BitSet) eightbs.clone();
- bs.set(128);
- assertFalse(eightbs.equals(bs));
- bs.clear(128);
- assertTrue(eightbs.equals(bs));
- }
-
- public void test_hashCode() {
- BitSet bs = (BitSet) eightbs.clone();
- bs.clear(2);
- bs.clear(6);
- assertEquals("BitSet returns wrong hash value", 1129, bs.hashCode());
- bs.set(10);
- bs.clear(3);
- assertEquals("BitSet returns wrong hash value", 97, bs.hashCode());
- }
-
- public void test_clear() {
- eightbs.clear();
- for (int i = 0; i < 8; i++) {
- assertTrue("Clear didn't clear bit " + i, !eightbs.get(i));
- }
- assertEquals("Test1: Wrong length", 0, eightbs.length());
-
- BitSet bs = new BitSet(3400);
- bs.set(0, bs.size() - 1); // ensure all bits are 1's
- bs.set(bs.size() - 1);
- bs.clear();
- assertEquals(0, bs.length());
- assertTrue(bs.isEmpty());
- assertEquals(0, bs.cardinality());
- }
-
- public void test_clearI() {
- eightbs.clear(7);
- assertFalse("Failed to clear bit", eightbs.get(7));
-
- // Check to see all other bits are still set
- for (int i = 0; i < 7; i++)
- assertTrue("Clear cleared incorrect bits", eightbs.get(i));
-
- eightbs.clear(165);
- assertFalse("Failed to clear bit", eightbs.get(165));
- // Try out of range
- try {
- eightbs.clear(-1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- BitSet bs = new BitSet(0);
- assertEquals("Test1: Wrong length,", 0, bs.length());
- assertEquals("Test1: Wrong size,", 0, bs.size());
-
- bs.clear(0);
- assertEquals("Test2: Wrong length,", 0, bs.length());
- assertEquals("Test2: Wrong size,", 0, bs.size());
-
- bs.clear(60);
- assertEquals("Test3: Wrong length,", 0, bs.length());
- assertEquals("Test3: Wrong size,", 0, bs.size());
-
- bs.clear(120);
- assertEquals("Test4: Wrong size,", 0, bs.size());
- assertEquals("Test4: Wrong length,", 0, bs.length());
-
- bs.set(25);
- assertEquals("Test5: Wrong size,", 64, bs.size());
- assertEquals("Test5: Wrong length,", 26, bs.length());
-
- bs.clear(80);
- assertEquals("Test6: Wrong size,", 64, bs.size());
- assertEquals("Test6: Wrong length,", 26, bs.length());
-
- bs.clear(25);
- assertEquals("Test7: Wrong size,", 64, bs.size());
- assertEquals("Test7: Wrong length,", 0, bs.length());
- }
-
- public void test_clearII() {
- // Regression for HARMONY-98
- BitSet bitset = new BitSet();
- for (int i = 0; i < 20; i++) {
- bitset.set(i);
- }
- bitset.clear(10, 10);
-
- // pos1 and pos2 are in the same bitset element
- BitSet bs = new BitSet(16);
- int initialSize = bs.size();
- assertEquals(64, initialSize);
- bs.set(0, initialSize);
- bs.clear(5);
- bs.clear(15);
- bs.clear(7, 11);
- assertEquals("{0, 1, 2, 3, 4, 6, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, " +
- "26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, " +
- "46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}", bs.toString());
- for (int i = initialSize; i < bs.size(); i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
-
- // pos1 and pos2 is in the same bitset element, boundry testing
- bs = new BitSet(16);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(7, 64);
- assertEquals("Failed to grow BitSet", 64, bs.size());
- for (int i = 0; i < 7; i++) {
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- for (int i = 7; i < 64; i++) {
- assertFalse("Failed to clear bit " + i, bs.get(i));
- }
- for (int i = 64; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
- // more boundary testing
- bs = new BitSet(32);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(0, 64);
- for (int i = 0; i < 64; i++) {
- assertFalse("Failed to clear bit " + i, bs.get(i));
- }
- for (int i = 64; i < bs.size(); i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
-
- bs = new BitSet(32);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(0, 65);
- for (int i = 0; i < 65; i++) {
- assertFalse("Failed to clear bit " + i, bs.get(i));
- }
- for (int i = 65; i < bs.size(); i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
-
- // pos1 and pos2 are in two sequential bitset elements
- bs = new BitSet(128);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(7);
- bs.clear(110);
- bs.clear(9, 74);
- for (int i = 0; i < 9; i++) {
- if (i == 7) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- } else {
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- }
- for (int i = 9; i < 74; i++) {
- assertFalse("Failed to clear bit " + i, bs.get(i));
- }
- for (int i = 74; i < initialSize; i++) {
- if (i == 110) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- } else {
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- }
- for (int i = initialSize; i < bs.size(); i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
-
- // pos1 and pos2 are in two non-sequential bitset elements
- bs = new BitSet(256);
- bs.set(0, 256);
- bs.clear(7);
- bs.clear(255);
- bs.clear(9, 219);
- for (int i = 0; i < 9; i++) {
- if (i == 7) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- } else {
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- }
-
- for (int i = 9; i < 219; i++) {
- assertFalse("failed to clear bit " + i, bs.get(i));
- }
- for (int i = 219; i < 255; i++) {
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- for (int i = 255; i < bs.size(); i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
-
- // test illegal args
- bs = new BitSet(10);
- try {
- bs.clear(-1, 3);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- bs.clear(2, -1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- bs.set(2, 4);
- bs.clear(2, 2);
- assertTrue("Bit got cleared incorrectly ", bs.get(2));
-
- try {
- bs.clear(4, 2);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- bs = new BitSet(0);
- assertEquals("Test1: Wrong length,", 0, bs.length());
- assertEquals("Test1: Wrong size,", 0, bs.size());
-
- bs.clear(0, 2);
- assertEquals("Test2: Wrong length,", 0, bs.length());
- assertEquals("Test2: Wrong size,", 0, bs.size());
-
- bs.clear(60, 64);
- assertEquals("Test3: Wrong length,", 0, bs.length());
- assertEquals("Test3: Wrong size,", 0, bs.size());
-
- bs.clear(64, 120);
- assertEquals("Test4: Wrong length,", 0, bs.length());
- assertEquals("Test4: Wrong size,", 0, bs.size());
-
- bs.set(25);
- assertEquals("Test5: Wrong length,", 26, bs.length());
- assertEquals("Test5: Wrong size,", 64, bs.size());
-
- bs.clear(60, 64);
- assertEquals("Test6: Wrong length,", 26, bs.length());
- assertEquals("Test6: Wrong size,", 64, bs.size());
-
- bs.clear(64, 120);
- assertEquals("Test7: Wrong size,", 64, bs.size());
- assertEquals("Test7: Wrong length,", 26, bs.length());
-
- bs.clear(80);
- assertEquals("Test8: Wrong size,", 64, bs.size());
- assertEquals("Test8: Wrong length,", 26, bs.length());
-
- bs.clear(25);
- assertEquals("Test9: Wrong size,", 64, bs.size());
- assertEquals("Test9: Wrong length,", 0, bs.length());
- }
-
- public void test_getI() {
- BitSet bs = new BitSet();
- bs.set(8);
- assertFalse("Get returned true for index out of range", eightbs.get(99));
- assertTrue("Get returned false for set value", eightbs.get(3));
- assertFalse("Get returned true for a non set value", bs.get(0));
-
- try {
- bs.get(-1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- bs = new BitSet(1);
- assertFalse("Access greater than size", bs.get(64));
-
- bs = new BitSet();
- bs.set(63);
- assertTrue("Test highest bit", bs.get(63));
-
- bs = new BitSet(0);
- assertEquals("Test1: Wrong length,", 0, bs.length());
- assertEquals("Test1: Wrong size,", 0, bs.size());
-
- bs.get(2);
- assertEquals("Test2: Wrong length,", 0, bs.length());
- assertEquals("Test2: Wrong size,", 0, bs.size());
-
- bs.get(70);
- assertEquals("Test3: Wrong length,", 0, bs.length());
- assertEquals("Test3: Wrong size,", 0, bs.size());
-
- }
-
- public void test_getII() {
- BitSet bitset = new BitSet(30);
- bitset.get(3, 3);
-
- BitSet bs, resultbs, correctbs;
- bs = new BitSet(512);
- bs.set(3, 9);
- bs.set(10, 20);
- bs.set(60, 75);
- bs.set(121);
- bs.set(130, 140);
-
- // pos1 and pos2 are in the same bitset element, at index0
- resultbs = bs.get(3, 6);
- correctbs = new BitSet(3);
- correctbs.set(0, 3);
- assertEquals("Test1: Returned incorrect BitSet", correctbs, resultbs);
-
- // pos1 and pos2 are in the same bitset element, at index 1
- resultbs = bs.get(100, 125);
- correctbs = new BitSet(25);
- correctbs.set(21);
- assertEquals("Test2: Returned incorrect BitSet", correctbs, resultbs);
-
- // pos1 in bitset element at index 0, and pos2 in bitset element at
- // index 1
- resultbs = bs.get(15, 125);
- correctbs = new BitSet(25);
- correctbs.set(0, 5);
- correctbs.set(45, 60);
- correctbs.set(121 - 15);
- assertEquals("Test3: Returned incorrect BitSet", correctbs, resultbs);
-
- // pos1 in bitset element at index 1, and pos2 in bitset element at
- // index 2
- resultbs = bs.get(70, 145);
- correctbs = new BitSet(75);
- correctbs.set(0, 5);
- correctbs.set(51);
- correctbs.set(60, 70);
- assertEquals("Test4: Returned incorrect BitSet", correctbs, resultbs);
-
- // pos1 in bitset element at index 0, and pos2 in bitset element at
- // index 2
- resultbs = bs.get(5, 145);
- correctbs = new BitSet(140);
- correctbs.set(0, 4);
- correctbs.set(5, 15);
- correctbs.set(55, 70);
- correctbs.set(116);
- correctbs.set(125, 135);
- assertEquals("Test5: Returned incorrect BitSet", correctbs, resultbs);
-
- // pos1 in bitset element at index 0, and pos2 in bitset element at
- // index 3
- resultbs = bs.get(5, 250);
- correctbs = new BitSet(200);
- correctbs.set(0, 4);
- correctbs.set(5, 15);
- correctbs.set(55, 70);
- correctbs.set(116);
- correctbs.set(125, 135);
- assertEquals("Test6: Returned incorrect BitSet", correctbs, resultbs);
-
- assertEquals("equality principle 1 ", bs.get(0, bs.size()), bs);
-
- // more tests
- BitSet bs2 = new BitSet(129);
- bs2.set(0, 20);
- bs2.set(62, 65);
- bs2.set(121, 123);
- resultbs = bs2.get(1, 124);
- correctbs = new BitSet(129);
- correctbs.set(0, 19);
- correctbs.set(61, 64);
- correctbs.set(120, 122);
- assertEquals("Test7: Returned incorrect BitSet", correctbs, resultbs);
-
- // equality principle with some boundary conditions
- bs2 = new BitSet(128);
- bs2.set(2, 20);
- bs2.set(62);
- bs2.set(121, 123);
- bs2.set(127);
- resultbs = bs2.get(0, bs2.size());
- assertEquals("equality principle 2 ", resultbs, bs2);
-
- bs2 = new BitSet(128);
- bs2.set(2, 20);
- bs2.set(62);
- bs2.set(121, 123);
- bs2.set(127);
- bs2.flip(0, 128);
- resultbs = bs2.get(0, bs.size());
- assertEquals("equality principle 3 ", resultbs, bs2);
-
- bs = new BitSet(0);
- assertEquals("Test1: Wrong length,", 0, bs.length());
- assertEquals("Test1: Wrong size,", 0, bs.size());
-
- bs.get(0, 2);
- assertEquals("Test2: Wrong length,", 0, bs.length());
- assertEquals("Test2: Wrong size,", 0, bs.size());
-
- bs.get(60, 64);
- assertEquals("Test3: Wrong length,", 0, bs.length());
- assertEquals("Test3: Wrong size,", 0, bs.size());
-
- bs.get(64, 120);
- assertEquals("Test4: Wrong length,", 0, bs.length());
- assertEquals("Test4: Wrong size,", 0, bs.size());
-
- bs.set(25);
- assertEquals("Test5: Wrong length,", 26, bs.length());
- assertEquals("Test5: Wrong size,", 64, bs.size());
-
- bs.get(60, 64);
- assertEquals("Test6: Wrong length,", 26, bs.length());
- assertEquals("Test6: Wrong size,", 64, bs.size());
-
- bs.get(64, 120);
- assertEquals("Test7: Wrong size,", 64, bs.size());
- assertEquals("Test7: Wrong length,", 26, bs.length());
-
- bs.get(80);
- assertEquals("Test8: Wrong size,", 64, bs.size());
- assertEquals("Test8: Wrong length,", 26, bs.length());
-
- bs.get(25);
- assertEquals("Test9: Wrong size,", 64, bs.size());
- assertEquals("Test9: Wrong length,", 26, bs.length());
-
- try {
- bs2.get(-1, 0);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- bs2.get(bs2.size()/2, 0);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- bs2.get(bs2.size()/2, -1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- }
-
- public void test_setI() {
- BitSet bs = new BitSet();
- bs.set(8);
- assertTrue("Failed to set bit", bs.get(8));
-
- try {
- bs.set(-1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- // Try setting a bit on a 64 boundary
- bs.set(128);
- assertEquals("Failed to grow BitSet", 192, bs.size());
- assertTrue("Failed to set bit", bs.get(128));
-
- bs = new BitSet(64);
- for (int i = bs.size(); --i >= 0;) {
- bs.set(i);
- assertTrue("Incorrectly set", bs.get(i));
- assertTrue("Incorrect length", bs.length() == (i + 1));
- for (int j = bs.size(); --j > i;)
- assertTrue("Incorrectly set bit " + j, !bs.get(j));
- for (int j = i; --j >= 0;)
- assertTrue("Incorrectly set bit " + j, !bs.get(j));
- bs.clear(i);
- }
-
- bs = new BitSet(0);
- assertTrue("Test1: Wrong length, " + bs.size(), bs.length() == 0);
- bs.set(0);
- assertTrue("Test2: Wrong length" + bs.size(), bs.length() == 1);
- }
-
- public void test_setIZ() {
- eightbs.set(5, false);
- assertTrue("Should have set bit 5 to true", !eightbs.get(5));
-
- eightbs.set(5, true);
- assertTrue("Should have set bit 5 to false", eightbs.get(5));
-
- try {
- eightbs.set(-5, false);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- }
-
- public void test_setII() {
- BitSet bitset = new BitSet(30);
- bitset.set(29, 29);
-
- // pos1 and pos2 are in the same bitset element
- BitSet bs = new BitSet(16);
- bs.set(5);
- bs.set(15);
- bs.set(7, 11);
- assertEquals("{5, 7, 8, 9, 10, 15}", bs.toString());
- for (int i = 16; i < bs.size(); i++) {
- assertFalse("Shouldn't have set bit " + i, bs.get(i));
- }
-
- // pos1 and pos2 is in the same bitset element, boundry testing
- bs = new BitSet(16);
- bs.set(7, 64);
- assertEquals("Failed to grow BitSet", 64, bs.size());
- for (int i = 0; i < 7; i++) {
- assertFalse("Shouldn't have set bit " + i, bs.get(i));
- }
- for (int i = 7; i < 64; i++) {
- assertTrue("Failed to set bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have set bit 64", bs.get(64));
-
- // more boundary testing
- bs = new BitSet(32);
- bs.set(0, 64);
- for (int i = 0; i < 64; i++) {
- assertTrue("Failed to set bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have set bit 64", bs.get(64));
-
- bs = new BitSet(32);
- bs.set(0, 65);
- for (int i = 0; i < 65; i++) {
- assertTrue("Failed to set bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have set bit 65", bs.get(65));
-
- // pos1 and pos2 are in two sequential bitset elements
- bs = new BitSet(128);
- bs.set(7);
- bs.set(110);
- bs.set(9, 74);
- for (int i = 0; i < 9; i++) {
- if (i == 7) {
- assertTrue("Shouldn't have flipped bit " + i, bs.get(i));
- } else {
- assertFalse("Shouldn't have set bit " + i, bs.get(i));
- }
- }
- for (int i = 9; i < 74; i++) {
- assertTrue("Failed to set bit " + i, bs.get(i));
- }
- for (int i = 74; i < bs.size(); i++) {
- if (i == 110) {
- assertTrue("Shouldn't have flipped bit " + i, bs.get(i));
- } else {
- assertFalse("Shouldn't have set bit " + i, bs.get(i));
- }
- }
-
- // pos1 and pos2 are in two non-sequential bitset elements
- bs = new BitSet(256);
- bs.set(7);
- bs.set(255);
- bs.set(9, 219);
- for (int i = 0; i < 9; i++) {
- if (i == 7) {
- assertTrue("Shouldn't have set flipped " + i, bs.get(i));
- } else {
- assertFalse("Shouldn't have set bit " + i, bs.get(i));
- }
- }
-
- for (int i = 9; i < 219; i++) {
- assertTrue("failed to set bit " + i, bs.get(i));
- }
-
- for (int i = 219; i < 255; i++) {
- assertFalse("Shouldn't have set bit " + i, bs.get(i));
- }
-
- assertTrue("Shouldn't have flipped bit 255", bs.get(255));
-
- // test illegal args
- bs = new BitSet(10);
- try {
- bs.set(-1, 3);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- bs.set(2, -1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- bs.set(2, 2);
- assertFalse("Bit got set incorrectly ", bs.get(2));
-
- try {
- bs.set(4, 2);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- }
-
- public void test_setIIZ() {
- eightbs.set(3, 6, false);
- assertTrue("Should have set bits 3, 4, and 5 to false", !eightbs.get(3)
- && !eightbs.get(4) && !eightbs.get(5));
-
- eightbs.set(3, 6, true);
- assertTrue("Should have set bits 3, 4, and 5 to true", eightbs.get(3)
- && eightbs.get(4) && eightbs.get(5));
-
- try {
- eightbs.set(-3, 6, false);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- eightbs.set(3, -6, false);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- eightbs.set(6, 3, false);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- }
-
- public void test_flipI() {
- BitSet bs = new BitSet();
- bs.clear(8);
- bs.clear(9);
- bs.set(10);
- bs.flip(9);
- assertFalse("Failed to flip bit", bs.get(8));
- assertTrue("Failed to flip bit", bs.get(9));
- assertTrue("Failed to flip bit", bs.get(10));
-
- bs.set(8);
- bs.set(9);
- bs.clear(10);
- bs.flip(9);
- assertTrue("Failed to flip bit", bs.get(8));
- assertFalse("Failed to flip bit", bs.get(9));
- assertFalse("Failed to flip bit", bs.get(10));
-
- try {
- bs.flip(-1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- // Try setting a bit on a 64 boundary
- bs.flip(128);
- assertEquals("Failed to grow BitSet", 192, bs.size());
- assertTrue("Failed to flip bit", bs.get(128));
-
- bs = new BitSet(64);
- for (int i = bs.size(); --i >= 0;) {
- bs.flip(i);
- assertTrue("Test1: Incorrectly flipped bit" + i, bs.get(i));
- assertEquals("Incorrect length", i+1, bs.length());
- for (int j = bs.size(); --j > i;) {
- assertTrue("Test2: Incorrectly flipped bit" + j, !bs.get(j));
- }
- for (int j = i; --j >= 0;) {
- assertTrue("Test3: Incorrectly flipped bit" + j, !bs.get(j));
- }
- bs.flip(i);
- }
-
- BitSet bs0 = new BitSet(0);
- assertEquals("Test1: Wrong size", 0, bs0.size());
- assertEquals("Test1: Wrong length", 0, bs0.length());
-
- bs0.flip(0);
- assertEquals("Test2: Wrong size", 64, bs0.size());
- assertEquals("Test2: Wrong length", 1, bs0.length());
-
- bs0.flip(63);
- assertEquals("Test3: Wrong size", 64, bs0.size());
- assertEquals("Test3: Wrong length", 64, bs0.length());
-
- eightbs.flip(7);
- assertTrue("Failed to flip bit 7", !eightbs.get(7));
-
- // Check to see all other bits are still set
- for (int i = 0; i < 7; i++) {
- assertTrue("Flip flipped incorrect bits", eightbs.get(i));
- }
-
- eightbs.flip(127);
- assertTrue("Failed to flip bit 127", eightbs.get(127));
-
- eightbs.flip(127);
- assertTrue("Failed to flip bit 127", !eightbs.get(127));
- }
-
- public void test_flipII() {
- BitSet bitset = new BitSet();
- for (int i = 0; i < 20; i++) {
- bitset.set(i);
- }
- bitset.flip(10, 10);
-
- // pos1 and pos2 are in the same bitset element
- BitSet bs = new BitSet(16);
- bs.set(7);
- bs.set(10);
- bs.flip(7, 11);
- for (int i = 0; i < 7; i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
- assertFalse("Failed to flip bit 7", bs.get(7));
- assertTrue("Failed to flip bit 8", bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertFalse("Failed to flip bit 10", bs.get(10));
- for (int i = 11; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
-
- // pos1 and pos2 is in the same bitset element, boundry testing
- bs = new BitSet(16);
- bs.set(7);
- bs.set(10);
- bs.flip(7, 64);
- assertEquals("Failed to grow BitSet", 64, bs.size());
- for (int i = 0; i < 7; i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
- assertFalse("Failed to flip bit 7", bs.get(7));
- assertTrue("Failed to flip bit 8", bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertFalse("Failed to flip bit 10", bs.get(10));
- for (int i = 11; i < 64; i++) {
- assertTrue("failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have flipped bit 64", bs.get(64));
-
- // more boundary testing
- bs = new BitSet(32);
- bs.flip(0, 64);
- for (int i = 0; i < 64; i++) {
- assertTrue("Failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have flipped bit 64", bs.get(64));
-
- bs = new BitSet(32);
- bs.flip(0, 65);
- for (int i = 0; i < 65; i++) {
- assertTrue("Failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have flipped bit 65", bs.get(65));
-
- // pos1 and pos2 are in two sequential bitset elements
- bs = new BitSet(128);
- bs.set(7);
- bs.set(10);
- bs.set(72);
- bs.set(110);
- bs.flip(9, 74);
- for (int i = 0; i < 7; i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
- assertTrue("Shouldn't have flipped bit 7", bs.get(7));
- assertFalse("Shouldn't have flipped bit 8", bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertFalse("Failed to flip bit 10", bs.get(10));
- for (int i = 11; i < 72; i++) {
- assertTrue("failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Failed to flip bit 72", bs.get(72));
- assertTrue("Failed to flip bit 73", bs.get(73));
- for (int i = 74; i < 110; i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
- assertTrue("Shouldn't have flipped bit 110", bs.get(110));
- for (int i = 111; i < bs.size(); i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
-
- // pos1 and pos2 are in two non-sequential bitset elements
- bs = new BitSet(256);
- bs.set(7);
- bs.set(10);
- bs.set(72);
- bs.set(110);
- bs.set(181);
- bs.set(220);
- bs.flip(9, 219);
- for (int i = 0; i < 7; i++) {
- assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
- }
- assertTrue("Shouldn't have flipped bit 7", bs.get(7));
- assertFalse("Shouldn't have flipped bit 8", bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertFalse("Failed to flip bit 10", bs.get(10));
- for (int i = 11; i < 72; i++) {
- assertTrue("failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Failed to flip bit 72", bs.get(72));
- for (int i = 73; i < 110; i++) {
- assertTrue("failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Failed to flip bit 110", bs.get(110));
- for (int i = 111; i < 181; i++) {
- assertTrue("failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Failed to flip bit 181", bs.get(181));
- for (int i = 182; i < 219; i++) {
- assertTrue("failed to flip bit " + i, bs.get(i));
- }
- assertFalse("Shouldn't have flipped bit 219", bs.get(219));
- assertTrue("Shouldn't have flipped bit 220", bs.get(220));
- for (int i = 221; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
-
- // test illegal args
- bs = new BitSet(10);
- try {
- bs.flip(-1, 3);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- bs.flip(2, -1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
-
- try {
- bs.flip(4, 2);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- }
-
- public void test_111478() throws Exception {
- // BitSet shouldn't be modified by any of the operations below,
- // since the affected bits for these methods are defined as inclusive of
- // pos1, exclusive of pos2.
- eightbs.flip(0, 0);
- assertTrue("Bit got flipped incorrectly ", eightbs.get(0));
-
- BitSet bsnew = eightbs.get(2, 2);
- assertEquals(0, bsnew.cardinality());
-
- eightbs.set(10, 10);
- assertTrue("Bit got set incorrectly ", !eightbs.get(10));
-
- eightbs.clear(3, 3);
- assertTrue("Bit cleared incorrectly ", eightbs.get(3));
- }
-
- public void test_intersectsLjava_util_BitSet() {
- BitSet bs = new BitSet(500);
- bs.set(5);
- bs.set(63);
- bs.set(64);
- bs.set(71, 110);
- bs.set(127, 130);
- bs.set(192);
- bs.set(450);
-
- BitSet bs2 = new BitSet(8);
- assertFalse("Test1: intersects() returned incorrect value", bs.intersects(bs2));
- assertFalse("Test1: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.set(4);
- assertFalse("Test2: intersects() returned incorrect value", bs.intersects(bs2));
- assertFalse("Test2: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(5);
- assertTrue("Test3: intersects() returned incorrect value", bs.intersects(bs2));
- assertTrue("Test3: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(63);
- assertTrue("Test4: intersects() returned incorrect value", bs.intersects(bs2));
- assertTrue("Test4: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(80);
- assertTrue("Test5: intersects() returned incorrect value", bs.intersects(bs2));
- assertTrue("Test5: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(127);
- assertTrue("Test6: intersects() returned incorrect value", bs.intersects(bs2));
- assertTrue("Test6: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(192);
- assertTrue("Test7: intersects() returned incorrect value", bs.intersects(bs2));
- assertTrue("Test7: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(450);
- assertTrue("Test8: intersects() returned incorrect value", bs.intersects(bs2));
- assertTrue("Test8: intersects() returned incorrect value", bs2.intersects(bs));
-
- bs2.clear();
- bs2.set(500);
- assertFalse("Test9: intersects() returned incorrect value", bs.intersects(bs2));
- assertFalse("Test9: intersects() returned incorrect value", bs2.intersects(bs));
- }
-
- public void test_andLjava_util_BitSet() {
- BitSet bs = new BitSet(128);
- // Initialize the bottom half of the BitSet
- for (int i = 64; i < 128; i++) {
- bs.set(i);
- }
- eightbs.and(bs);
- assertTrue("AND failed to clear bits", !eightbs.equals(bs));
- eightbs.set(3);
- bs.set(3);
- eightbs.and(bs);
- assertTrue("AND failed to maintain set bits", bs.get(3));
- bs.and(eightbs);
- for (int i = 64; i < 128; i++) {
- assertTrue("Failed to clear extra bits in the receiver BitSet", !bs.get(i));
- }
- }
-
- public void test_andNotLjava_util_BitSet() {
- BitSet bs = (BitSet) eightbs.clone();
- bs.clear(5);
- BitSet bs2 = new BitSet();
- bs2.set(2);
- bs2.set(3);
- bs.andNot(bs2);
- assertEquals("Incorrect bitset after andNot",
- "{0, 1, 4, 6, 7}", bs.toString());
-
- bs = new BitSet(0);
- bs.andNot(bs2);
- assertEquals("Incorrect size", 0, bs.size());
- }
-
- public void test_orLjava_util_BitSet() {
- BitSet bs = new BitSet(128);
- bs.or(eightbs);
- for (int i = 0; i < 8; i++) {
- assertTrue("OR failed to set bits", bs.get(i));
- }
- bs = new BitSet(0);
- bs.or(eightbs);
- for (int i = 0; i < 8; i++) {
- assertTrue("OR(0) failed to set bits", bs.get(i));
- }
- eightbs.clear(5);
- bs = new BitSet(128);
- bs.or(eightbs);
- assertTrue("OR set a bit which should be off", !bs.get(5));
- }
-
- public void test_xorLjava_util_BitSet() {
- BitSet bs = (BitSet) eightbs.clone();
- bs.xor(eightbs);
- for (int i = 0; i < 8; i++) {
- assertTrue("XOR failed to clear bit " + i + bs, !bs.get(i));
- }
- bs.xor(eightbs);
- for (int i = 0; i < 8; i++) {
- assertTrue("XOR failed to set bit " + i + bs, bs.get(i));
- }
- bs = new BitSet(0);
- bs.xor(eightbs);
- for (int i = 0; i < 8; i++) {
- assertTrue("XOR(0) failed to set bit " + i + bs, bs.get(i));
- }
- bs = new BitSet();
- bs.set(63);
- assertEquals("{63}", bs.toString());
- }
-
- public void test_size() {
- assertEquals("Returned incorrect size", 64, eightbs.size());
- eightbs.set(129);
- assertTrue("Returned incorrect size", eightbs.size() >= 129);
-
- }
-
- public void test_toString() {
- assertEquals("Returned incorrect string representation", "{0, 1, 2, 3, 4, 5, 6, 7}", eightbs.toString());
- eightbs.clear(2);
- assertEquals("Returned incorrect string representation", "{0, 1, 3, 4, 5, 6, 7}", eightbs.toString());
- }
-
- public void test_length() {
- BitSet bs = new BitSet();
- assertEquals(bs.toString(), 0, bs.length());
- bs.set(5);
- assertEquals(bs.toString(), 6, bs.length());
- bs.set(10);
- assertEquals(bs.toString(), 11, bs.length());
- bs.set(432);
- assertEquals(bs.toString(), 433, bs.length());
- bs.set(300);
- assertEquals(bs.toString(), 433, bs.length());
- }
-
- public void test_nextSetBitI() {
- BitSet bs = new BitSet(500);
- bs.set(5);
- bs.set(32);
- bs.set(63);
- bs.set(64);
- bs.set(71, 110);
- bs.set(127, 130);
- bs.set(193);
- bs.set(450);
- try {
- bs.nextSetBit(-1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- assertEquals(5, bs.nextSetBit(0));
- assertEquals(5, bs.nextSetBit(5));
- assertEquals(32, bs.nextSetBit(6));
- assertEquals(32, bs.nextSetBit(32));
- assertEquals(63, bs.nextSetBit(33));
-
- // boundary tests
- assertEquals(63, bs.nextSetBit(63));
- assertEquals(64, bs.nextSetBit(64));
-
- // at bitset element 1
- assertEquals(71, bs.nextSetBit(65));
- assertEquals(71, bs.nextSetBit(71));
- assertEquals(72, bs.nextSetBit(72));
- assertEquals(127, bs.nextSetBit(110));
-
- // boundary tests
- assertEquals(127, bs.nextSetBit(127));
- assertEquals(128, bs.nextSetBit(128));
-
- // at bitset element 2
- assertEquals(193, bs.nextSetBit(130));
-
- assertEquals(193, bs.nextSetBit(191));
- assertEquals(193, bs.nextSetBit(192));
- assertEquals(193, bs.nextSetBit(193));
- assertEquals(450, bs.nextSetBit(194));
- assertEquals(450, bs.nextSetBit(255));
- assertEquals(450, bs.nextSetBit(256));
- assertEquals(450, bs.nextSetBit(450));
-
- assertEquals(-1, bs.nextSetBit(451));
- assertEquals(-1, bs.nextSetBit(511));
- assertEquals(-1, bs.nextSetBit(512));
- assertEquals(-1, bs.nextSetBit(800));
- }
-
- public void test_nextClearBitI() {
- BitSet bs = new BitSet(500);
- // ensure all the bits from 0 to bs.size() - 1 are set to true
- bs.set(0, bs.size() - 1);
- bs.set(bs.size() - 1);
- bs.clear(5);
- bs.clear(32);
- bs.clear(63);
- bs.clear(64);
- bs.clear(71, 110);
- bs.clear(127, 130);
- bs.clear(193);
- bs.clear(450);
- try {
- bs.nextClearBit(-1);
- fail();
- } catch (IndexOutOfBoundsException expected) {
- }
- assertEquals(5, bs.nextClearBit(0));
- assertEquals(5, bs.nextClearBit(5));
- assertEquals(32, bs.nextClearBit(6));
- assertEquals(32, bs.nextClearBit(32));
- assertEquals(63, bs.nextClearBit(33));
-
- // boundary tests
- assertEquals(63, bs.nextClearBit(63));
- assertEquals(64, bs.nextClearBit(64));
-
- // at bitset element 1
- assertEquals(71, bs.nextClearBit(65));
- assertEquals(71, bs.nextClearBit(71));
- assertEquals(72, bs.nextClearBit(72));
- assertEquals(127, bs.nextClearBit(110));
-
- // boundary tests
- assertEquals(127, bs.nextClearBit(127));
- assertEquals(128, bs.nextClearBit(128));
-
- // at bitset element 2
- assertEquals(193, bs.nextClearBit(130));
- assertEquals(193, bs.nextClearBit(191));
-
- assertEquals(193, bs.nextClearBit(192));
- assertEquals(193, bs.nextClearBit(193));
- assertEquals(450, bs.nextClearBit(194));
- assertEquals(450, bs.nextClearBit(255));
- assertEquals(450, bs.nextClearBit(256));
- assertEquals(450, bs.nextClearBit(450));
-
- // bitset has 1 still the end of bs.size() -1, but calling nextClearBit
- // with any index value after the last true bit should return bs.size()
- assertEquals(512, bs.nextClearBit(451));
- assertEquals(512, bs.nextClearBit(511));
- assertEquals(512, bs.nextClearBit(512));
-
- // if the index is larger than bs.size(), nextClearBit should return index
- assertEquals(513, bs.nextClearBit(513));
- assertEquals(800, bs.nextClearBit(800));
-
- bs.clear();
- assertEquals(0, bs.nextClearBit(0));
- assertEquals(3, bs.nextClearBit(3));
- assertEquals(64, bs.nextClearBit(64));
- assertEquals(128, bs.nextClearBit(128));
- }
-
- // http://code.google.com/p/android/issues/detail?id=31036
- public void test_31036_clear() {
- BitSet bs = new BitSet(500);
- for (int i = 0; i < 500; ++i) {
- int nextClear = bs.nextClearBit(0);
- assertEquals(i, nextClear);
- bs.set(i);
- }
- }
-
- // http://code.google.com/p/android/issues/detail?id=31036
- public void test_31036_set() {
- BitSet bs = new BitSet(500);
- bs.set(0, 511);
- for (int i = 0; i < 500; ++i) {
- int nextSet = bs.nextSetBit(0);
- assertEquals(i, nextSet);
- bs.clear(i);
- }
- }
-
- public void test_isEmpty() {
- BitSet bs = new BitSet(500);
- assertTrue("Test: isEmpty() returned wrong value", bs.isEmpty());
-
- // at bitset element 0
- bs.set(3);
- assertFalse("Test0: isEmpty() returned wrong value", bs.isEmpty());
-
- // at bitset element 1
- bs.clear();
- bs.set(12);
- assertFalse("Test1: isEmpty() returned wrong value", bs.isEmpty());
-
- // at bitset element 2
- bs.clear();
- bs.set(128);
- assertFalse("Test2: isEmpty() returned wrong value", bs.isEmpty());
-
- // boundary testing
- bs.clear();
- bs.set(459);
- assertFalse("Test3: isEmpty() returned wrong value", bs.isEmpty());
-
- bs.clear();
- bs.set(511);
- assertFalse("Test4: isEmpty() returned wrong value", bs.isEmpty());
- }
-
- public void test_cardinality() {
- BitSet bs = new BitSet(500);
- bs.set(5);
- bs.set(32);
- bs.set(63);
- bs.set(64);
- assertEquals(bs.toString(), 4, bs.cardinality());
- bs.set(71, 110);
- bs.set(127, 130);
- bs.set(193);
- bs.set(450);
- assertEquals(bs.toString(), 48, bs.cardinality());
-
- bs.flip(0, 500);
- assertEquals("cardinality() returned wrong value", 452, bs
- .cardinality());
-
- bs.clear();
- assertEquals("cardinality() returned wrong value", 0, bs.cardinality());
-
- bs.set(0, 500);
- assertEquals("cardinality() returned wrong value", 500, bs
- .cardinality());
- }
-
- private static void printBitset(BitSet bs) {
- System.out.println();
- for (int i = bs.size() - 1; i >= 0; i--) {
- if (bs.get(i))
- System.out.print(1);
- else
- System.out.print(0);
- }
- }
-
- protected void setUp() {
- eightbs = new BitSet();
- for (int i = 0; i < 8; i++) {
- eightbs.set(i);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/CalendarTest.java b/luni/src/test/java/tests/api/java/util/CalendarTest.java
deleted file mode 100644
index 54524ad..0000000
--- a/luni/src/test/java/tests/api/java/util/CalendarTest.java
+++ /dev/null
@@ -1,1099 +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 tests.api.java.util;
-
-import java.text.DateFormatSymbols;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.TimeZone;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-public class CalendarTest extends junit.framework.TestCase {
-
- Locale defaultLocale;
-
- /**
- * java.util.Calendar#set(int, int)
- */
- public void test_setII() {
- // Test for correct result defined by the last set field
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- assertTrue("Incorrect result 0: " + cal.getTime().getTime(), cal
- .getTime().getTime() == 1009861200000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 0a: " + cal.getTime(), cal.getTime()
- .getTime() == 1014958800000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 24);
- assertTrue("Incorrect result 0b: " + cal.getTime(), cal.getTime()
- .getTime() == 1011848400000L);
-
- cal.set(Calendar.MONTH, Calendar.OCTOBER);
- cal.set(Calendar.DATE, 31);
- cal.set(Calendar.MONTH, Calendar.NOVEMBER);
- cal.set(Calendar.DATE, 26);
- assertTrue("Incorrect month: " + cal.get(Calendar.MONTH), cal
- .get(Calendar.MONTH) == Calendar.NOVEMBER);
-
- int dow = cal.get(Calendar.DAY_OF_WEEK);
- cal.set(Calendar.DATE, 27);
- assertTrue("Incorrect DAY_OF_WEEK: " + cal.get(Calendar.DAY_OF_WEEK)
- + " expected: " + dow, cal.get(Calendar.DAY_OF_WEEK) != dow);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 0c1: " + cal.getTime().getTime(), cal
- .getTime().getTime() == 1010379600000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertTrue("Incorrect result 0c2: " + cal.getTime().getTime(), cal
- .getTime().getTime() == 1009861200000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
- assertTrue("Incorrect result 0c3: " + cal.getTime(), cal.getTime()
- .getTime() == 1010034000000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_MONTH, 2);
- assertTrue("Incorrect result 0d: " + cal.getTime(), cal.getTime()
- .getTime() == 1010293200000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
- assertTrue("Incorrect result 0e: " + cal.getTime(), cal.getTime()
- .getTime() == 1010898000000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 0f: " + cal.getTime(), cal.getTime()
- .getTime() == 1015736400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 24);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 0g: " + cal.getTime(), cal.getTime()
- .getTime() == 1011848400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.get(Calendar.WEEK_OF_YEAR); // Force fields to compute
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 0h: " + cal.getTime(), cal.getTime()
- .getTime() == 1015909200000L);
-
- // WEEK_OF_YEAR has priority over MONTH/DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 170);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 1: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_YEAR has priority over MONTH/DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_YEAR, 170);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 1a: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_WEEK has no effect when other fields not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertTrue("Incorrect result 1b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
- // Regression for HARMONY-4384
- // Set DAY_OF_WEEK without DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertEquals("Incorrect result 1b: " + cal.getTime(), 1015304400000L, cal.getTime()
- .getTime());
-
-
- // WEEK_OF_MONTH has priority
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- cal.set(Calendar.WEEK_OF_MONTH, 3);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 2: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_WEEK_IN_MONTH has priority over WEEK_OF_YEAR
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 3: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_MONTH has priority, MONTH not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- cal.set(Calendar.WEEK_OF_MONTH, 3);
- cal.set(Calendar.DATE, 25);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 4: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- // WEEK_OF_YEAR has priority when MONTH set last and DAY_OF_WEEK set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- cal.set(Calendar.DATE, 25);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- assertTrue("Incorrect result 5: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // Use MONTH/DATE when WEEK_OF_YEAR set but not DAY_OF_WEEK
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 5a: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // Use MONTH/DATE when DAY_OF_WEEK is not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.WEEK_OF_MONTH, 1);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 5b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_MONTH has priority
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.WEEK_OF_MONTH, 3);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 5c: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DATE has priority when set last
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 11);
- assertTrue("Incorrect result 6: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DATE has priority when set last, MONTH not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.DATE, 14);
- assertTrue("Incorrect result 7: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- // DAY_OF_YEAR has priority when MONTH set last and DATE not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- assertTrue("Incorrect result 8: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY/MONTH has priority when DATE set after DAY_OF_YEAR
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 170);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 8a: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_YEAR has priority when set after DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 15);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- assertTrue("Incorrect result 8b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DATE has priority when set last
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.DATE, 14);
- assertTrue("Incorrect result 9: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- // DATE has priority when set last
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 15);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
- cal.set(Calendar.DATE, 14);
- assertTrue("Incorrect result 9a: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.DATE, 14);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 9b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 14);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 9c: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_MONTH, 1);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 11);
- assertTrue("Incorrect result 9d: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_YEAR has priority when DAY_OF_MONTH set last and other fields
- // not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertTrue("Incorrect result 10: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // MONTH/DATE has priority when DAY_OF_WEEK_IN_MONTH set last but
- // DAY_OF_WEEK not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- assertTrue("Incorrect result 11: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // MONTH/DATE has priority when WEEK_OF_YEAR set last but DAY_OF_WEEK
- // not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.WEEK_OF_YEAR, 15);
- assertTrue("Incorrect result 12: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // MONTH/DATE has priority when WEEK_OF_MONTH set last but DAY_OF_WEEK
- // not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.WEEK_OF_MONTH, 1);
- assertTrue("Incorrect result 13: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // Ensure last date field set is reset after computing
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 111);
- cal.get(Calendar.YEAR);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.AM_PM, Calendar.AM);
- assertTrue("Incorrect result 14: " + cal.getTime(), cal.getTime()
- .getTime() == 1016686800000L);
-
- int hour = cal.get(Calendar.HOUR);
- cal.set(Calendar.HOUR, hour);
- cal.set(Calendar.AM_PM, Calendar.PM);
- assertEquals("AM_PM not changed", Calendar.PM, cal.get(Calendar.AM_PM));
- // setting AM_PM without HOUR should not have any affect
- cal.set(Calendar.AM_PM, Calendar.AM);
- assertEquals("AM_PM was changed 1",
- Calendar.AM, cal.get(Calendar.AM_PM));
- int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
- hour = cal.get(Calendar.HOUR);
- cal.set(Calendar.AM_PM, Calendar.PM);
- assertEquals("AM_PM was changed 2",
- Calendar.PM, cal.get(Calendar.AM_PM));
- assertEquals(hour, cal.get(Calendar.HOUR));
- assertEquals(hourOfDay + 12, cal.get(Calendar.HOUR_OF_DAY));
-
- // regression test for Harmony-2122
- cal = Calendar.getInstance();
- int oldValue = cal.get(Calendar.AM_PM);
- int newValue = (oldValue == Calendar.AM) ? Calendar.PM : Calendar.AM;
- cal.set(Calendar.AM_PM, newValue);
- newValue = cal.get(Calendar.AM_PM);
- assertTrue(newValue != oldValue);
- }
-
- /**
- * java.util.Calendar#setTime(java.util.Date)
- */
- public void test_setTimeLjava_util_Date() {
- Calendar cal = Calendar.getInstance();
- // Use millisecond time for testing in Core
- cal.setTime(new Date(884581200000L)); // (98, Calendar.JANUARY, 12)
- assertEquals("incorrect millis", 884581200000L, cal.getTime().getTime());
- cal.setTimeZone(TimeZone.getTimeZone("EST"));
- cal.setTime(new Date(943506000000L)); // (99, Calendar.NOVEMBER, 25)
- assertTrue("incorrect fields", cal.get(Calendar.YEAR) == 1999
- && cal.get(Calendar.MONTH) == Calendar.NOVEMBER
- && cal.get(Calendar.DATE) == 25);
- }
-
- /**
- * java.util.Calendar#compareTo(Calendar)
- */
- public void test_compareToLjava_util_Calendar_null() {
- Calendar cal = Calendar.getInstance();
- try {
- cal.compareTo(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * java.util.Calendar#compareTo(Calendar)
- */
- public void test_compareToLjava_util_Calendar() {
- Calendar cal = Calendar.getInstance();
- cal.clear();
- cal.set(1997, 12, 13, 23, 57);
-
- Calendar anotherCal = Calendar.getInstance();
- anotherCal.clear();
- anotherCal.set(1997, 12, 13, 23, 57);
- assertEquals(0, cal.compareTo(anotherCal));
-
- anotherCal = Calendar.getInstance();
- anotherCal.clear();
- anotherCal.set(1997, 11, 13, 24, 57);
- assertEquals(1, cal.compareTo(anotherCal));
-
- anotherCal = Calendar.getInstance();
- anotherCal.clear();
- anotherCal.set(1997, 12, 13, 23, 58);
- assertEquals(-1, cal.compareTo(anotherCal));
- }
-
- /**
- * java.util.Calendar#clone()
- */
- public void test_clone() {
- // Regression for HARMONY-475
- Calendar cal = Calendar.getInstance();
- cal.set(2006, 5, 6, 11, 35);
- Calendar anotherCal = (Calendar) cal.clone();
- // should be deep clone
- assertNotSame("getTimeZone", cal.getTimeZone(), anotherCal
- .getTimeZone());
- }
-
- /**
- * java.util.Calendar#getTimeInMillis()
- */
- public void test_getTimeInMillis() {
- Calendar cal = Calendar.getInstance();
-
- int year = Integer.MIN_VALUE + 71;
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.set(Calendar.YEAR, year + 1900);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.DATE, 1);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
-
- assertEquals(6017546357372606464L, cal.getTimeInMillis());
- }
-
- private static final Locale[] locales = new Locale[] { Locale.getDefault(),
- Locale.US, Locale.UK, Locale.TAIWAN, Locale.PRC, Locale.KOREA,
- Locale.JAPAN, Locale.ITALIAN, Locale.GERMAN, Locale.ENGLISH,
- Locale.CHINA, Locale.CANADA, Locale.FRANCE };
-
- /**
- * java.util.Calendar#before(Object)
- * java.util.Calendar#after(Object)
- */
- public void test_before_after() {
- Calendar early = Calendar.getInstance();
- Calendar late = Calendar.getInstance();
- // test by second
- early.set(2008, 3, 20, 17, 28, 12);
- late.set(2008, 3, 20, 17, 28, 22);
- // test before()
- assertTrue(early.before(late));
- assertFalse(early.before(early));
- assertFalse(late.before(early));
- // test after();
- assertTrue(late.after(early));
- assertFalse(late.after(late));
- assertFalse(early.after(late));
-
- // test by minute
- early.set(2008, 3, 20, 17, 18, 12);
- late.set(2008, 3, 20, 17, 28, 12);
- // test before()
- assertTrue(early.before(late));
- assertFalse(early.before(early));
- assertFalse(late.before(early));
- // test after();
- assertTrue(late.after(early));
- assertFalse(late.after(late));
- assertFalse(early.after(late));
-
- // test by hour
- early.set(2008, 3, 20, 17, 28, 12);
- late.set(2008, 3, 20, 27, 28, 12);
- // test before()
- assertTrue(early.before(late));
- assertFalse(early.before(early));
- assertFalse(late.before(early));
- // test after();
- assertTrue(late.after(early));
- assertFalse(late.after(late));
- assertFalse(early.after(late));
-
- // test by day
- early.set(2008, 3, 10, 17, 28, 12);
- late.set(2008, 3, 20, 17, 28, 12);
- // test before()
- assertTrue(early.before(late));
- assertFalse(early.before(early));
- assertFalse(late.before(early));
- // test after();
- assertTrue(late.after(early));
- assertFalse(late.after(late));
- assertFalse(early.after(late));
-
- // test by month
- early.set(2008, 2, 20, 17, 28, 12);
- late.set(2008, 3, 20, 17, 28, 12);
- // test before()
- assertTrue(early.before(late));
- assertFalse(early.before(early));
- assertFalse(late.before(early));
- // test after();
- assertTrue(late.after(early));
- assertFalse(late.after(late));
- assertFalse(early.after(late));
-
- // test by year
- early.set(2007, 3, 20, 17, 28, 12);
- late.set(2008, 3, 20, 17, 28, 12);
- // test before()
- assertTrue(early.before(late));
- assertFalse(early.before(early));
- assertFalse(late.before(early));
- // test after();
- assertTrue(late.after(early));
- assertFalse(late.after(late));
- assertFalse(early.after(late));
- }
-
- /**
- * java.util.Calendar#clear()
- * java.util.Calendar#clear(int)
- */
- public void test_clear() {
- Calendar calendar = Calendar.getInstance();
-
- int count = 6;
- int[] fields = new int[count];
- int[] defaults = new int[count];
-
- fields[0] = Calendar.YEAR;
- fields[1] = Calendar.MONTH;
- fields[2] = Calendar.DATE;
- fields[3] = Calendar.HOUR_OF_DAY;
- fields[4] = Calendar.MINUTE;
- fields[5] = Calendar.SECOND;
-
- defaults[0] = 1970;
- defaults[1] = 0;
- defaults[2] = 1;
- defaults[3] = 0;
- defaults[4] = 0;
- defaults[5] = 0;
-
- calendar.set(2008, 3, 20, 17, 28, 12);
-
- // test clear(int)
- for (int i = 0; i < fields.length; i++) {
- int index = fields[i];
- calendar.clear(index);
- if (5 == index) {
- // RI also doesn't change the value of DATE
- assertEquals("Field " + index + " Should equal to 20.", 20,
- calendar.get(index));
- } else if (11 == index) {
- // RI also doesn't change the value of HOUR
- assertEquals("Field " + index + " Should equal to 17.", 17,
- calendar.get(index));
- } else {
- // Other have been set to default values
- assertEquals("Field " + index + " Should equal to "
- + defaults[i] + ".", defaults[i], calendar.get(index));
- }
- }
-
- // test clear()
- calendar.set(2008, 3, 20, 17, 28, 12);
-
- calendar.clear();
-
- for (int i = 0; i < fields.length; i++) {
- int index = fields[i];
- assertEquals("Field " + index + " Should equal to "
- + defaults[i] + ".", defaults[i], calendar.get(index));
- }
- }
-
- /**
- * java.util.Calendar#isSet(int)
- */
- public void test_isSet() {
- Calendar calendar = Calendar.getInstance();
- calendar.clear();
- for (int i = 0; i < Calendar.FIELD_COUNT; i++) {
- assertFalse(calendar.isSet(i));
- }
- }
-
- /**
- * java.util.Calendar#getAvailableLocales()
- */
- public void test_getAvailableLocales() {
- Locale[] locales = Calendar.getAvailableLocales();
- boolean exist = false;
- for (int i = 0; i < locales.length; i++) {
- Locale l = locales[i];
- if (Locale.US.equals(l)) {
- exist = true;
- break;
- }
- }
- assertTrue(exist);
- }
-
- /**
- * java.util.Calendar#getInstance(Locale)
- * java.util.Calendar#getInstance(TimeZone, Locale)
- */
- public void test_getInstance() {
- // test getInstance(Locale)
- Calendar us_calendar = Calendar.getInstance(Locale.US);
- Calendar de_calendar = Calendar.getInstance(Locale.GERMAN);
- assertEquals(Calendar.SUNDAY, us_calendar
- .getFirstDayOfWeek());
- assertEquals(Calendar.MONDAY, de_calendar
- .getFirstDayOfWeek());
-
- // test getInstance(Locale, TimeZone)
- Calendar gmt_calendar = Calendar.getInstance(TimeZone
- .getTimeZone("GMT"), Locale.US);
- assertEquals(TimeZone.getTimeZone("GMT"),
- gmt_calendar.getTimeZone());
- Calendar est_calendar = Calendar.getInstance(TimeZone
- .getTimeZone("EST"), Locale.US);
- assertEquals(TimeZone.getTimeZone("EST")
- .getID(), est_calendar.getTimeZone().getID());
- }
-
- /**
- * java.util.Calendar#internalGet(int)
- */
- public void test_internalGet() {
- MockGregorianCalendar c = new MockGregorianCalendar();
- c.clear(Calendar.YEAR);
- assertEquals(0, c.internal_get(Calendar.YEAR));
- }
-
- /**
- * java.util.Calendar#hashCode()
- */
- public void test_hashcode() {
- Calendar calendar = Calendar.getInstance(Locale.JAPAN);
- assertTrue(calendar.hashCode() == calendar.hashCode());
- }
-
- /**
- * java.util.Calendar#roll(int, int)
- */
- public void test_roll() {
- Calendar calendar = Calendar.getInstance();
- calendar.set(2008, 3, 20, 17, 28, 12);
-
- // roll up
- calendar.roll(Calendar.DATE, 5);
- assertEquals(25, calendar.get(Calendar.DATE));
-
- // roll down
- calendar.roll(Calendar.DATE, -5);
- assertEquals(20, calendar.get(Calendar.DATE));
-
- // roll 0
- calendar.roll(Calendar.DATE, 0);
- assertEquals(20, calendar.get(Calendar.DATE));
-
- // roll overweight
- calendar.set(2008, 1, 31, 17, 28, 12);
- calendar.roll(Calendar.MONTH, 1);
- assertEquals(2, calendar.get(Calendar.DATE));
-
- }
-
- /**
- * java.util.Calendar#toString()
- */
- public void test_toString() {
- Calendar calendar = Calendar.getInstance();
- //Should be the current time with no interrogation in the string.
- assertTrue(calendar.toString() instanceof String);
- assertEquals(-1, calendar.toString().indexOf("?"));
- calendar.clear();
- assertTrue(calendar.toString() instanceof String);
- assertTrue(0 <= calendar.toString().indexOf("?"));
- }
-
- /**
- * serialization/deserialization.
- */
- public void testSerializationSelf() throws Exception {
- Calendar calendar = Calendar.getInstance();
- calendar.set(2008, 3, 20, 17, 28, 12);
-
- SerializationTest.verifySelf(calendar);
- }
-
-
- private class MockGregorianCalendar extends GregorianCalendar {
- public int internal_get(int field) {
- return super.internalGet(field);
- }
- }
-
- private class MockCalendar extends Calendar {
-
- public MockCalendar() {
- super();
- }
-
- @Override
- public void add(int field, int value) {
- }
-
- @Override
- protected void computeFields() {
- }
-
- @Override
- protected void computeTime() {
- }
-
- @Override
- public int getGreatestMinimum(int field) {
- return 0;
- }
-
- @Override
- public int getLeastMaximum(int field) {
- return 0;
- }
-
- @Override
- public int getMaximum(int field) {
- return 0;
- }
-
- @Override
- public int getMinimum(int field) {
- return 0;
- }
-
- @Override
- public void roll(int field, boolean increment) {
- }
- }
-
- /**
- * {@link java.util.Calendar#getDisplayName(int, int, Locale)}
- * @since 1.6
- */
- public void test_getDisplayNameIILjava_util_Locale() {
- Calendar cal = Calendar.getInstance();
- for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
- for (Locale locale : locales) {
- DateFormatSymbols symbols = new DateFormatSymbols(locale);
- String value = null;
- switch (field) {
- case Calendar.AM_PM:
- cal.set(Calendar.AM_PM, Calendar.AM);
- value = symbols.getAmPmStrings()[0];
- assertEquals(cal.getDisplayName(field, Calendar.SHORT,
- locale), value);
- assertEquals(cal.getDisplayName(field, Calendar.LONG,
- locale), value);
- cal.set(Calendar.AM_PM, Calendar.PM);
- value = symbols.getAmPmStrings()[1];
- assertEquals(cal.getDisplayName(field, Calendar.SHORT,
- locale), value);
- assertEquals(cal.getDisplayName(field, Calendar.LONG,
- locale), value);
- break;
- case Calendar.ERA:
- cal.set(Calendar.ERA, GregorianCalendar.BC);
- value = symbols.getEras()[0];
- assertEquals(cal.getDisplayName(field, Calendar.SHORT,
- locale), value);
- assertEquals(cal.getDisplayName(field, Calendar.LONG,
- locale), value);
- cal.set(Calendar.ERA, GregorianCalendar.AD);
- value = symbols.getEras()[1];
- assertEquals(cal.getDisplayName(field, Calendar.SHORT,
- locale), value);
- assertEquals(cal.getDisplayName(field, Calendar.LONG,
- locale), value);
- break;
- case Calendar.MONTH:
- cal.set(Calendar.DAY_OF_MONTH, 1);
- for (int month = 0; month <= 11; month++) {
- cal.set(Calendar.MONTH, month);
- value = symbols.getShortMonths()[month];
- assertEquals(cal.getDisplayName(field, Calendar.SHORT,
- locale), value);
- value = symbols.getMonths()[month];
- assertEquals(cal.getDisplayName(field, Calendar.LONG,
- locale), value);
- }
- break;
- case Calendar.DAY_OF_WEEK:
- for (int day = 1; day <= 7; day++) {
- cal.set(Calendar.DAY_OF_WEEK, day);
- value = symbols.getShortWeekdays()[day];
- assertEquals(cal.getDisplayName(field, Calendar.SHORT,
- locale), value);
- value = symbols.getWeekdays()[day];
- assertEquals(cal.getDisplayName(field, Calendar.LONG,
- locale), value);
- }
- break;
- default:
- assertNull(cal
- .getDisplayName(field, Calendar.SHORT, locale));
- assertNull(cal.getDisplayName(field, Calendar.LONG, locale));
- }
- }
- }
-
- cal.setLenient(true);
-
- try {
- cal.getDisplayName(-1, Calendar.SHORT, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayName(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayName(Calendar.MONTH, -1, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayName(Calendar.MONTH, 3, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- cal.getDisplayName(-1, Calendar.SHORT, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayName(Calendar.MONTH, -1, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // in lenient mode, following cases pass
- cal.set(Calendar.SECOND, 999);
- cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
- // test for ALL_STYLES, it is equal to use SHORT
- for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
- for (Locale locale : locales) {
- String result = cal.getDisplayName(field, Calendar.ALL_STYLES,
- locale);
- if (field == Calendar.AM_PM || field == Calendar.ERA
- || field == Calendar.MONTH
- || field == Calendar.DAY_OF_WEEK) {
- assertEquals(result, cal.getDisplayName(field,
- Calendar.SHORT, locale));
- } else {
- assertNull(result);
- }
- }
- }
-
- // invalid value for an un-related field when the calendar is not
- // lenient
- cal.setLenient(false);
- assertNotNull(cal.getDisplayName(Calendar.MONTH, Calendar.SHORT,
- Locale.US));
- cal.set(Calendar.SECOND, 999);
- try {
- cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayName(Calendar.MONTH, Calendar.ALL_STYLES, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * {@link java.util.Calendar#getDisplayNames(int, int, Locale)}
- * @since 1.6
- */
- public void test_getDisplayNamesIILjava_util_Locale() {
- assertEquals(0, Calendar.ALL_STYLES);
- assertEquals(1, Calendar.SHORT);
- assertEquals(2, Calendar.LONG);
-
- Calendar cal = Calendar.getInstance(Locale.US);
-
- for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
- for (Locale locale : locales) {
- Map<String, Integer> shortResult = cal.getDisplayNames(field,
- Calendar.SHORT, locale);
- Map<String, Integer> longResult = cal.getDisplayNames(field,
- Calendar.LONG, locale);
- Map<String, Integer> allResult = cal.getDisplayNames(field,
- Calendar.ALL_STYLES, locale);
- DateFormatSymbols symbols = new DateFormatSymbols(locale);
- String[] values = null;
- switch (field) {
- case Calendar.AM_PM:
- case Calendar.ERA:
- values = (field == Calendar.AM_PM) ? symbols
- .getAmPmStrings() : symbols.getEras();
- assertDisplayNameMap(values, shortResult, 0);
- assertDisplayNameMap(values, longResult, 0);
- assertDisplayNameMap(values, allResult, 0);
- break;
- case Calendar.MONTH:
- values = symbols.getShortMonths();
- assertDisplayNameMap(values, shortResult, 0);
- values = symbols.getMonths();
- assertDisplayNameMap(values, longResult, 0);
- assertTrue(allResult.size() >= shortResult.size());
- assertTrue(allResult.size() >= longResult.size());
- assertTrue(allResult.size() <= shortResult.size()
- + longResult.size());
- break;
- case Calendar.DAY_OF_WEEK:
- values = symbols.getShortWeekdays();
- assertDisplayNameMap(values, shortResult, 1);
- values = symbols.getWeekdays();
- assertDisplayNameMap(values, longResult, 1);
- assertTrue(allResult.size() >= shortResult.size());
- assertTrue(allResult.size() >= longResult.size());
- assertTrue(allResult.size() <= shortResult.size()
- + longResult.size());
- break;
- default:
- assertNull(shortResult);
- assertNull(longResult);
- assertNull(allResult);
- }
- }
- }
-
- cal.setLenient(true);
-
- try {
- cal.getDisplayNames(-1, Calendar.SHORT, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayNames(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayNames(Calendar.MONTH, -1, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayNames(Calendar.MONTH, 3, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- cal.getDisplayNames(-1, Calendar.SHORT, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- cal.getDisplayNames(Calendar.MONTH, -1, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- cal.set(Calendar.SECOND, 999);
- cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US);
-
- // RI fails here
- // invalid value for an un-related field when the calendar is not
- // lenient
- cal.setLenient(false);
- cal.set(Calendar.SECOND, 999);
- try {
- cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- private void assertDisplayNameMap(String[] values,
- Map<String, Integer> result, int shift) {
- List<String> trimValue = new ArrayList<String>();
- for (String value : values) {
- if (value.trim().length() > 0) {
- trimValue.add(value);
- }
- }
- assertEquals(trimValue.size(), result.size());
- for (int i = 0; i < trimValue.size(); i++) {
- assertEquals(i + shift, result.get(trimValue.get(i)).intValue());
- }
- }
-
- /**
- * {@link java.util.Calendar#getActualMaximum(int)}
- */
- public void test_getActualMaximum_I() {
- Calendar c = new MockCalendar();
- assertEquals("should be equal to 0", 0, c.getActualMaximum(0));
- }
-
- /**
- * {@link java.util.Calendar#getActualMinimum(int)}
- */
- public void test_getActualMinimum_I() {
- Calendar c = new MockCalendar();
- assertEquals("should be equal to 0", 0, c.getActualMinimum(0));
- }
-
- protected void setUp() {
- defaultLocale = Locale.getDefault();
- Locale.setDefault(Locale.US);
- }
-
- protected void tearDown() {
- Locale.setDefault(defaultLocale);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/CollectionsTest.java b/luni/src/test/java/tests/api/java/util/CollectionsTest.java
deleted file mode 100644
index c308cf9..0000000
--- a/luni/src/test/java/tests/api/java/util/CollectionsTest.java
+++ /dev/null
@@ -1,2226 +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 tests.api.java.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Random;
-import java.util.RandomAccess;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import java.util.Arrays;
-
-import tests.support.Support_CollectionTest;
-import tests.support.Support_ListTest;
-import tests.support.Support_SetTest;
-import tests.support.Support_UnmodifiableCollectionTest;
-import tests.support.Support_UnmodifiableMapTest;
-
-public class CollectionsTest extends junit.framework.TestCase {
-
- private LinkedList ll;
-
- private LinkedList myll;
-
- private LinkedList reversedLinkedList;
-
- private LinkedList myReversedLinkedList;
-
- private Set s;
-
- private Set mys;
-
- private HashMap hm;
-
- private Object[] objArray;
-
- private Object[] myobjArray;
-
- public static class ReversedMyIntComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return -((MyInt) o1).compareTo((MyInt) o2);
- }
-
- public int equals(Object o1, Object o2) {
- return ((MyInt) o1).compareTo((MyInt) o2);
- }
- }
-
- public static class SynchCollectionChecker implements Runnable {
- Collection col;
-
- int colSize;
-
- int totalToRun;
-
- boolean offset;
-
- volatile int numberOfChecks = 0;
-
- boolean result = true;
-
- ArrayList normalCountingList;
-
- ArrayList offsetCountingList;
-
- public void run() {
- // ensure the list either contains the numbers from 0 to size-1 or
- // the numbers from size to 2*size -1
- while (numberOfChecks < totalToRun) {
- synchronized (col) {
- if (!(col.isEmpty() || col.containsAll(normalCountingList) || col
- .containsAll(offsetCountingList)))
- result = false;
- col.clear();
- }
- if (offset)
- col.addAll(offsetCountingList);
- else
- col.addAll(normalCountingList);
- numberOfChecks++;
- }
- }
-
- public SynchCollectionChecker(Collection c, boolean offset,
- int totalChecks) {
- // The collection to test, whether to offset the filler values by
- // size or not, and the min number of iterations to run
- totalToRun = totalChecks;
- col = c;
- colSize = c.size();
- normalCountingList = new ArrayList(colSize);
- offsetCountingList = new ArrayList(colSize);
- for (int counter = 0; counter < colSize; counter++)
- normalCountingList.add(new Integer(counter));
- for (int counter = 0; counter < colSize; counter++)
- offsetCountingList.add(new Integer(counter + colSize));
- col.clear();
- if (offset)
- col.addAll(offsetCountingList);
- else
- col.addAll(normalCountingList);
- }
-
- public boolean offset() {
- // answer true iff the list is filled with a counting sequence
- // starting at the value size to 2*size - 1
- // else the list with be filled starting at 0 to size - 1
- return offset;
- }
-
- public boolean getResult() {
- // answer true iff no corruption has been found in the collection
- return result;
- }
-
- public int getNumberOfChecks() {
- // answer the number of checks that have been performed on the list
- return numberOfChecks;
- }
- }
-
- public static class SynchMapChecker implements Runnable {
- Map map;
-
- int mapSize;
-
- int totalToRun;
-
- boolean offset;
-
- volatile int numberOfChecks = 0;
-
- boolean result = true;
-
- Map normalCountingMap;
-
- Map offsetCountingMap;
-
- public void run() {
- Object firstNormalValue = normalCountingMap.get(new Integer(0));
- Object lastNormalValue = normalCountingMap.get(new Integer(
- mapSize - 1));
- Object firstOffsetValue = offsetCountingMap
- .get(new Integer(mapSize));
- Object lastOffsetValue = offsetCountingMap.get(new Integer(
- 2 * mapSize - 1));
- // ensure the list either contains the numbers from 0 to size-1 or
- // the numbers from size to 2*size -1
- while (numberOfChecks < totalToRun) {
- synchronized (map) {
- if (!(map.isEmpty()
- || (map.containsValue(firstNormalValue) && map
- .containsValue(lastNormalValue)) || (map
- .containsValue(firstOffsetValue) && map
- .containsValue(lastOffsetValue))))
- result = false;
- map.clear();
- }
- if (offset)
- map.putAll(offsetCountingMap);
- else
- map.putAll(normalCountingMap);
- numberOfChecks++;
- }
- }
-
- public SynchMapChecker(Map m, boolean offset, int totalChecks) {
- // The collection to test, whether to offset the filler values by
- // size or not, and the min number of iterations to run
- Integer myInt;
- totalToRun = totalChecks;
- map = m;
- mapSize = m.size();
- normalCountingMap = new HashMap(mapSize);
- offsetCountingMap = new HashMap(mapSize);
- for (int counter = 0; counter < mapSize; counter++) {
- myInt = new Integer(counter);
- normalCountingMap.put(myInt, myInt);
- }
- for (int counter = 0; counter < mapSize; counter++) {
- myInt = new Integer(counter + mapSize);
- offsetCountingMap.put(myInt, myInt);
- }
- map.clear();
- if (offset)
- map.putAll(offsetCountingMap);
- else
- map.putAll(normalCountingMap);
- }
-
- public boolean offset() {
- // answer true iff the list is filled with a counting sequence
- // starting at the value size to 2*size - 1
- // else the list with be filled starting at 0 to size - 1
- return offset;
- }
-
- public boolean getResult() {
- // answer true iff no corruption has been found in the collection
- return result;
- }
-
- public int getNumberOfChecks() {
- // answer the number of checks that have been performed on the list
- return numberOfChecks;
- }
- }
-
- public static class CollectionTest extends junit.framework.TestCase {
-
- Collection col; // must contain the Integers 0 to 99
-
- public CollectionTest(String p1) {
- super(p1);
- }
-
- public CollectionTest(String p1, Collection c) {
- super(p1);
- col = c;
- }
-
- }
-
- static class MyInt {
- int data;
-
- public MyInt(int value) {
- data = value;
- }
-
- public int compareTo(MyInt object) {
- return data > object.data ? 1 : (data < object.data ? -1 : 0);
- }
- }
-
- /**
- * java.util.Collections#binarySearch(java.util.List,
- * java.lang.Object)
- */
- public void test_binarySearchLjava_util_ListLjava_lang_Object() {
- // Test for method int
- // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
- // assumes ll is sorted and has no duplicate keys
- final int llSize = ll.size();
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.binarySearch(null, new Object());
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- for (int counter = 0; counter < llSize; counter++) {
- assertTrue("Returned incorrect binary search item position", ll
- .get(Collections.binarySearch(ll, ll.get(counter))) == ll
- .get(counter));
- }
- }
-
- /**
- * java.util.Collections#binarySearch(java.util.List,
- * java.lang.Object, java.util.Comparator)
- */
- public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
- // Test for method int
- // java.util.Collections.binarySearch(java.util.List, java.lang.Object,
- // java.util.Comparator)
- // assumes reversedLinkedList is sorted in reversed order and has no
- // duplicate keys
- final int rSize = myReversedLinkedList.size();
- ReversedMyIntComparator comp = new ReversedMyIntComparator();
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.binarySearch(null, new Object(), comp);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- for (int counter = 0; counter < rSize; counter++) {
- assertTrue(
- "Returned incorrect binary search item position using custom comparator",
- myReversedLinkedList.get(Collections.binarySearch(
- myReversedLinkedList, myReversedLinkedList
- .get(counter), comp)) == myReversedLinkedList
- .get(counter));
- }
- }
-
- class Mock_ArrayList extends ArrayList {
- @Override
- public
- Object set (int index, Object o){
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * java.util.Collections#copy(java.util.List, java.util.List)
- */
- public void test_copyLjava_util_ListLjava_util_List() {
- // Test for method void java.util.Collections.copy(java.util.List,
- // java.util.List)
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.copy(null, ll);
- fail("Expected NullPointerException for null list first parameter");
- } catch (NullPointerException e) {
- }
- try {
- Collections.copy(ll, null);
- fail("Expected NullPointerException for null list second parameter");
- } catch (NullPointerException e) {
- }
- final int llSize = ll.size();
- ll.set(25, null);
- ArrayList al = new ArrayList();
- Integer extraElement = new Integer(1);
- Integer extraElement2 = new Integer(2);
- al.addAll(myReversedLinkedList);
- al.add(extraElement);
- al.add(extraElement2);
- Collections.copy(al, ll);
- for (int counter = 0; counter < llSize; counter++) {
- assertTrue("Elements do not match after copying collection", al
- .get(counter) == ll.get(counter));
- }
- assertTrue("Elements after copied elements affected by copy",
- extraElement == al.get(llSize)
- && extraElement2 == al.get(llSize + 1));
-
- ArrayList ar1 = new ArrayList();
- ArrayList ar2 = new ArrayList();
-
- int i;
-
- for(i = 0; i < 5; i ++) {
- ar2.add(new Integer(i));
- }
-
- for(i = 0; i < 10; i ++) {
- ar1.add(new Integer(i));
- }
-
- try {
- Collections.copy(ar2, ar1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- Mock_ArrayList mal1 = new Mock_ArrayList();
- Mock_ArrayList mal2 = new Mock_ArrayList();
-
- for(i = 0; i < 10; i ++) {
- mal1.add(new Integer(i));
- mal2.add(new Integer(10 - i));
- }
-
- try {
- Collections.copy(mal1, mal2);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#copy(java.util.List, java.util.List)
- */
- public void test_copy_check_index() {
- ArrayList a1 = new ArrayList();
- a1.add("one");
- a1.add("two");
-
- ArrayList a2 = new ArrayList();
- a2.add("aa");
-
- try {
- Collections.copy(a2, a1);
- fail("Expected IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- assertEquals("aa", a2.get(0));
- }
-
- /**
- * java.util.Collections#enumeration(java.util.Collection)
- */
- public void test_enumerationLjava_util_Collection() {
- // Test for method java.util.Enumeration
- // java.util.Collections.enumeration(java.util.Collection)
- TreeSet ts = new TreeSet();
- ts.addAll(s);
- Enumeration e = Collections.enumeration(ts);
- int count = 0;
- while (e.hasMoreElements())
- assertTrue("Returned incorrect enumeration",
- e.nextElement() == objArray[count++]);
- assertTrue("Enumeration missing elements: " + count,
- count == objArray.length);
- }
-
- /**
- * java.util.Collections#fill(java.util.List, java.lang.Object)
- */
- public void test_fillLjava_util_ListLjava_lang_Object() {
- // Test for method void java.util.Collections.fill(java.util.List,
- // java.lang.Object)
- try {
- Collections.fill(null, new Object());
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- final int size = ll.size();
- Collections.fill(ll, "k");
- assertTrue("Fill modified list size", size == ll.size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertEquals("Failed to fill elements", "k", i.next());
-
- Collections.fill(ll, null);
- assertTrue("Fill with nulls modified list size", size == ll.size());
- i = ll.iterator();
- while (i.hasNext())
- assertNull("Failed to fill with nulls", i.next());
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("one");
- mal.add("two");
-
- try {
- Collections.fill(mal, "value");
- fail("UnsupportedOperationException ecpected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#max(java.util.Collection)
- */
- public void test_maxLjava_util_Collection() {
- // Test for method java.lang.Object
- // java.util.Collections.max(java.util.Collection)
- // assumes s, objArray are sorted
- assertTrue("Returned incorrect max element",
- Collections.max(s) == objArray[objArray.length - 1]);
-
- ArrayList al = new ArrayList();
-
- try {
- Collections.max(al);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.max(al);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#max(java.util.Collection,
- * java.util.Comparator)
- */
- public void test_maxLjava_util_CollectionLjava_util_Comparator() {
- // Test for method java.lang.Object
- // java.util.Collections.max(java.util.Collection, java.util.Comparator)
- // assumes s, objArray are sorted
-
- // With this custom (backwards) comparator the 'max' element should be
- // the smallest in the list
- ReversedMyIntComparator rmic = new ReversedMyIntComparator();
- assertTrue(
- "Returned incorrect max element using custom comparator",
- Collections.max(mys, rmic) == myobjArray[0]);
-
- ArrayList al = new ArrayList();
-
- try {
- Collections.max(al, rmic);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.max(al, rmic);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#min(java.util.Collection)
- */
- public void test_minLjava_util_Collection() {
- // Test for method java.lang.Object
- // java.util.Collections.min(java.util.Collection)
- // assumes s, objArray are sorted
- assertTrue("Returned incorrect min element",
- Collections.min(s) == objArray[0]);
- ArrayList al = new ArrayList();
-
- try {
- Collections.min(al);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.min(al);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#min(java.util.Collection,
- * java.util.Comparator)
- */
- public void test_minLjava_util_CollectionLjava_util_Comparator() {
- // Test for method java.lang.Object
- // java.util.Collections.min(java.util.Collection, java.util.Comparator)
- // assumes s, objArray are sorted
-
- // With this custom (backwards) comparator the 'min' element should be
- // the largest in the list
- ReversedMyIntComparator rmic = new ReversedMyIntComparator();
-
- assertTrue(
- "Returned incorrect min element using custom comparator",
- Collections.min(mys, rmic) == myobjArray[objArray.length - 1]);
-
- ArrayList al = new ArrayList();
-
- try {
- Collections.min(al, rmic);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.min(al, rmic);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#nCopies(int, java.lang.Object)
- */
- public void test_nCopiesILjava_lang_Object() {
- // Test for method java.util.List java.util.Collections.nCopies(int,
- // java.lang.Object)
- Object o = new Object();
- List l = Collections.nCopies(100, o);
- Iterator i = l.iterator();
- Object first = i.next();
- assertTrue("Returned list consists of copies not refs", first == o);
- assertEquals("Returned list of incorrect size", 100, l.size());
- assertTrue("Contains", l.contains(o));
- assertTrue("Contains null", !l.contains(null));
- assertTrue("null nCopies contains", !Collections.nCopies(2, null)
- .contains(o));
- assertTrue("null nCopies contains null", Collections.nCopies(2, null)
- .contains(null));
- l = Collections.nCopies(20, null);
- i = l.iterator();
- for (int counter = 0; i.hasNext(); counter++) {
- assertTrue("List is too large", counter < 20);
- assertNull("Element should be null: " + counter, i.next());
- }
- try {
- l.add(o);
- fail("Returned list is not immutable");
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- try {
- Collections.nCopies(-2, new HashSet());
- fail("nCopies with negative arg didn't throw IAE");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- /**
- * java.util.Collections#reverse(java.util.List)
- */
- public void test_reverseLjava_util_List() {
- // Test for method void java.util.Collections.reverse(java.util.List)
- try {
- Collections.reverse(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- Collections.reverse(ll);
- Iterator i = ll.iterator();
- int count = objArray.length - 1;
- while (i.hasNext()) {
- assertTrue("Failed to reverse collection",
- i.next() == objArray[count]);
- --count;
- }
- ArrayList myList = new ArrayList();
- myList.add(null);
- myList.add(new Integer(20));
- Collections.reverse(myList);
- assertTrue("Did not reverse correctly--first element is: "
- + myList.get(0), myList.get(0).equals(new Integer(20)));
- assertNull("Did not reverse correctly--second element is: "
- + myList.get(1), myList.get(1));
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.reverse(mal);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#reverseOrder()
- */
- public void test_reverseOrder() {
- // Test for method java.util.Comparator
- // java.util.Collections.reverseOrder()
- // assumes no duplicates in ll
- Comparator comp = Collections.reverseOrder();
- LinkedList list2 = new LinkedList(ll);
- Collections.sort(list2, comp);
- final int llSize = ll.size();
- for (int counter = 0; counter < llSize; counter++)
- assertTrue("New comparator does not reverse sorting order", ll
- .get(counter) == list2.get(llSize - counter - 1));
- }
-
- /**
- * java.util.Collections#shuffle(java.util.List)
- */
- public void test_shuffleLjava_util_List() {
- // Test for method void java.util.Collections.shuffle(java.util.List)
- // Assumes ll is sorted and has no duplicate keys and is large ( > 20
- // elements)
-
- // test shuffling a Sequential Access List
- try {
- Collections.shuffle(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- ArrayList al = new ArrayList();
- al.addAll(ll);
- testShuffle(al, "Sequential Access", false);
-
- // test shuffling a Random Access List
- LinkedList ll2 = new LinkedList();
- ll2.addAll(ll);
- testShuffle(ll2, "Random Access", false);
- }
-
- public void testShuffleRandomAccessWithSeededRandom() {
- List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
- Collections.shuffle(list, new Random(0));
- assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list);
- }
-
- public void testShuffleWithSeededRandom() {
- List<String> list = new LinkedList<String>(Arrays.asList(
- "A", "B", "C", "D", "E", "F", "G"));
- Collections.shuffle(list, new Random(0));
- assertEquals(Arrays.asList("B", "A", "D", "C", "G", "E", "F"), list);
- }
-
- private void testShuffle(List list, String type, boolean random) {
- boolean sorted = true;
- boolean allMatch = true;
- int index = 0;
- final int size = list.size();
-
- if (random)
- Collections.shuffle(list);
- else
- Collections.shuffle(list, new Random(200));
-
- for (int counter = 0; counter < size - 1; counter++) {
- if (((Integer) list.get(counter)).compareTo((Integer)list.get(counter + 1)) > 0) {
- sorted = false;
- }
- }
- assertFalse("Shuffling sorted " + type
- + " list resulted in sorted list (should be unlikely)", sorted);
- for (int counter = 0; counter < 20; counter++) {
- index = 30031 * counter % (size + 1); // 30031 is a large prime
- if (list.get(index) != ll.get(index))
- allMatch = false;
- }
- assertFalse("Too many element positions match in shuffled " + type
- + " list", allMatch);
- }
-
- /**
- * java.util.Collections#shuffle(java.util.List, java.util.Random)
- */
- public void test_shuffleLjava_util_ListLjava_util_Random() {
- // Test for method void java.util.Collections.shuffle(java.util.List,
- // java.util.Random)
- // Assumes ll is sorted and has no duplicate keys and is large ( > 20
- // elements)
-
- // test shuffling a Sequential Access List
- try {
- Collections.shuffle(null, new Random(200));
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- ArrayList al = new ArrayList();
- al.addAll(ll);
- testShuffle(al, "Sequential Access", true);
-
- // test shuffling a Random Access List
- LinkedList ll2 = new LinkedList();
- ll2.addAll(ll);
- testShuffle(ll2, "Random Access", true);
-
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.shuffle(mal, new Random(200));
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-}
-
- /**
- * java.util.Collections#singleton(java.lang.Object)
- */
- public void test_singletonLjava_lang_Object() {
- // Test for method java.util.Set
- // java.util.Collections.singleton(java.lang.Object)
- Object o = new Object();
- Set single = Collections.singleton(o);
- assertEquals("Wrong size", 1, single.size());
- assertTrue("Contains", single.contains(o));
- assertTrue("Contains null", !single.contains(null));
- assertTrue("null nCopies contains", !Collections.singleton(null)
- .contains(o));
- assertTrue("null nCopies contains null", Collections.singleton(null)
- .contains(null));
- try {
- single.add("l");
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- fail("Allowed modification of singleton");
- }
-
- /**
- * java.util.Collections#sort(java.util.List)
- */
- public void test_sortLjava_util_List() {
- // Test for method void java.util.Collections.sort(java.util.List)
- // assumes no duplicate keys in ll
- final int llSize = ll.size();
- final int rllSize = reversedLinkedList.size();
- try {
- Collections.sort((List)null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- Collections.shuffle(ll);
- Collections.sort(ll);
- Collections.sort(reversedLinkedList);
- for (int counter = 0; counter < llSize - 1; counter++) {
- assertTrue(
- "Sorting shuffled list resulted in unsorted list",
- ((Integer) ll.get(counter)).compareTo((Integer)ll.get(counter + 1)) < 0);
- }
-
- for (int counter = 0; counter < rllSize - 1; counter++) {
- assertTrue("Sorting reversed list resulted in unsorted list",
- ((Integer) reversedLinkedList.get(counter))
- .compareTo((Integer)reversedLinkedList.get(counter + 1)) < 0);
- }
-
- ArrayList al = new ArrayList();
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.sort(al);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.sort(mal);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#sort(java.util.List, java.util.Comparator)
- */
- public void test_sortLjava_util_ListLjava_util_Comparator() {
- // Test for method void java.util.Collections.sort(java.util.List,
- // java.util.Comparator)
- Comparator comp = new ReversedMyIntComparator();
- try {
- Collections.sort(null, comp);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- Collections.shuffle(myll);
- Collections.sort(myll, comp);
- final int llSize = myll.size();
-
- for (int counter = 0; counter < llSize - 1; counter++) {
- assertTrue(
- "Sorting shuffled list with custom comparator resulted in unsorted list",
- ((MyInt) myll.get(counter)).compareTo((MyInt) myll
- .get(counter + 1)) >= 0);
- }
-
- ArrayList al = new ArrayList();
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.sort(al, comp);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add(new MyInt(1));
- mal.add(new MyInt(2));
-
- try {
- Collections.sort(mal, comp);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#swap(java.util.List, int, int)
- */
- public void test_swapLjava_util_ListII() {
- // Test for method swap(java.util.List, int, int)
-
- LinkedList smallList = new LinkedList();
- for (int i = 0; i < 10; i++) {
- smallList.add(objArray[i]);
- }
-
- // test exception cases
- try {
- Collections.swap(smallList, -1, 6);
- fail("Expected IndexOutOfBoundsException for -1");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Collections.swap(smallList, 6, -1);
- fail("Expected IndexOutOfBoundsException for -1");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Collections.swap(smallList, 6, 11);
- fail("Expected IndexOutOfBoundsException for 11");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Collections.swap(smallList, 11, 6);
- fail("Expected IndexOutOfBoundsException for 11");
- } catch (IndexOutOfBoundsException e) {
- }
-
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.swap(null, 1, 1);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // test with valid parameters
- Collections.swap(smallList, 4, 7);
- assertEquals("Didn't Swap the element at position 4 ", new Integer(7),
- smallList.get(4));
- assertEquals("Didn't Swap the element at position 7 ", new Integer(4),
- smallList.get(7));
-
- // make sure other elements didn't get swapped by mistake
- for (int i = 0; i < 10; i++) {
- if (i != 4 && i != 7)
- assertEquals("shouldn't have swapped the element at position "
- + i, new Integer(i), smallList.get(i));
- }
- }
-
- /**
- * java.util.Collections#replaceAll(java.util.List, java.lang.Object,
- * java.lang.Object)
- */
- public void test_replaceAllLjava_util_ListLjava_lang_ObjectLjava_lang_Object() {
- // Test for method replaceAll(java.util.List, java.lang.Object,
- // java.lang.Object)
-
- String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
- char[] chars = string1.toCharArray();
- List list = new ArrayList();
- for (int i = 0; i < chars.length; i++) {
- list.add(new Character(chars[i]));
- }
-
- try {
- Collections.replaceAll(null, new Object(), new Object());
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // test replace for an element that is not in the list
- boolean result = Collections.replaceAll(list, new Character('1'),
- new Character('Z'));
- assertFalse("Test1: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test2 : ReplaceAll modified the list incorrectly",
- string1, getString(list));
-
- // test replace for an element that is in the list
- result = Collections.replaceAll(list, new Character('S'),
- new Character('K'));
- assertTrue("Test3: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test4: ReplaceAll modified the list incorrectly",
- (string1 = string1.replace('S', 'K')), getString(list));
-
- // test replace for the last element in the list
- result = Collections.replaceAll(list, new Character('Z'),
- new Character('N'));
- assertTrue("Test5: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test6: ReplaceAll modified the list incorrectly",
- (string1 = string1.replace('Z', 'N')), getString(list));
-
- // test replace for the first element in the list
- result = Collections.replaceAll(list, new Character('A'),
- new Character('B'));
- assertTrue("Test7: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test8: ReplaceAll modified the list incorrectly",
- (string1 = string1.replace('A', 'B')), getString(list));
-
- // test replacing elements with null
- LinkedList smallList = new LinkedList();
- for (int i = 0; i < 10; i++) {
- smallList.add(objArray[i]);
- }
- smallList.set(4, new Integer(5));
- result = Collections.replaceAll(smallList, new Integer(5), null);
- assertTrue("Test9: Collections.replaceAll() returned wrong result",
- result);
- for (int i = 0; i < smallList.size(); i++) {
- if (i == 4 || i == 5)
- assertSame("Test9: ReplaceAll didn't replace element at " + i,
- null, smallList.get(i));
- else
- assertEquals(
- "Test9: ReplaceAll shouldn't have replaced element at "
- + i, new Integer(i), smallList.get(i));
- }
-
- // test replacing null elements with another value
- result = Collections.replaceAll(smallList, null, new Integer(99));
- assertTrue("Test10: Collections.replaceAll() returned wrong result",
- result);
-
- for (int i = 0; i < smallList.size(); i++) {
- if (i == 4 || i == 5)
- assertEquals("Test10: ReplaceAll didn't replace element at "
- + i, new Integer(99), smallList.get(i));
- else
- assertEquals(
- "Test10: ReplaceAll shouldn't have replaced element at "
- + i, new Integer(i), smallList.get(i));
- }
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.replaceAll(mal, "Second", null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * java.util.Collections#rotate(java.util.List, int)
- */
- public void test_rotateLjava_util_ListI() {
- // Test for method rotate(java.util.List, int)
-
- try {
- Collections.rotate(null, 0);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // Test rotating a Sequential Access List
- LinkedList list1 = new LinkedList();
- for (int i = 0; i < 10; i++) {
- list1.add(objArray[i]);
- }
- testRotate(list1, "Sequential Access");
-
- // Test rotating a Random Access List
- ArrayList list2 = new ArrayList();
- for (int i = 0; i < 10; i++) {
- list2.add(objArray[i]);
- }
- testRotate(list2, "Random Access");
- }
-
- private void testRotate(List list, String type) {
- // rotate with positive distance
- Collections.rotate(list, 7);
- assertEquals("Test1: rotate modified the " + type
- + " list incorrectly,", "3456789012", getString(list));
-
- // rotate with negative distance
- Collections.rotate(list, -2);
- assertEquals("Test2: rotate modified the " + type
- + " list incorrectly,", "5678901234", getString(list));
-
- // rotate sublist with negative distance
- List subList = list.subList(1, 5);
- Collections.rotate(subList, -1);
- assertEquals("Test3: rotate modified the " + type
- + " list incorrectly,", "5789601234", getString(list));
-
- // rotate sublist with positive distance
- Collections.rotate(subList, 2);
- assertEquals("Test4: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- // rotate with positive distance that is larger than list size
- Collections.rotate(list, 23);
- assertEquals("Test5: rotate modified the " + type
- + " list incorrectly,", "2345967801", getString(list));
-
- // rotate with negative distance that is larger than list size
- Collections.rotate(list, -23);
- assertEquals("Test6: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- // rotate with 0 and equivalent distances, this should make no
- // modifications to the list
- Collections.rotate(list, 0);
- assertEquals("Test7: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- Collections.rotate(list, -30);
- assertEquals("Test8: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- Collections.rotate(list, 30);
- assertEquals("Test9: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
- }
-
- private String getString(List list) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < list.size(); i++) {
- buffer.append(list.get(i));
- }
- return buffer.toString();
- }
-
- /**
- * java.util.Collections#rotate(java.util.List, int)
- */
- public void test_rotate2() {
- List list = new ArrayList();
- try {
- Collections.rotate(list, 5);
- } catch (UnsupportedOperationException e) {
- fail("Unexpected UnsupportedOperationException for empty list, "
- + e);
- }
-
- list.add(0, "zero");
- list.add(1, "one");
- list.add(2, "two");
- list.add(3, "three");
- list.add(4, "four");
-
- Collections.rotate(list, Integer.MIN_VALUE);
- assertEquals("Rotated incorrectly at position 0, ", "three",
- (String) list.get(0));
- assertEquals("Rotated incorrectly at position 1, ", "four",
- (String) list.get(1));
- assertEquals("Rotated incorrectly at position 2, ", "zero",
- (String) list.get(2));
- assertEquals("Rotated incorrectly at position 3, ", "one",
- (String) list.get(3));
- assertEquals("Rotated incorrectly at position 4, ", "two",
- (String) list.get(4));
- }
-
- /**
- * java.util.Collections#indexOfSubList(java.util.List,
- * java.util.List)
- */
- public void test_indexOfSubListLjava_util_ListLjava_util_List() {
- // Test for method int indexOfSubList(java.util.List, java.util.List)
- List list = new ArrayList();
- try {
- Collections.indexOfSubList(null, list);
- fail("Expected NullPointerException for null list first parameter");
- } catch (NullPointerException e) {
- }
- try {
- Collections.indexOfSubList(list, null);
- fail("Expected NullPointerException for null list second parameter");
- } catch (NullPointerException e) {
- }
-
- String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
-
- testwithCharList(1, string1, "B", true);
- testwithCharList(2, string1, "LIST", true);
- testwithCharList(3, string1, "SUBLIST", true);
- testwithCharList(4, string1, "NONE", true);
- testwithCharList(5, string1, "END", true);
-
- // test boundary conditions:
- testwithCharList(6, "", "", true);
- testwithCharList(7, "LIST", "", true);
- testwithCharList(8, "", "SUBLIST", true);
- }
-
- /**
- * java.util.Collections#indexOfSubList(java.util.List,
- * java.util.List)
- */
- public void test_indexOfSubList2() {
- ArrayList sub = new ArrayList();
- sub.add(new Integer(1));
- sub.add(new Integer(2));
- sub.add(new Integer(3));
-
- ArrayList sub2 = new ArrayList();
- sub2.add(new Integer(7));
- sub2.add(new Integer(8));
-
- ArrayList src = new ArrayList();
- src.addAll(sub);
- src.addAll(sub);
- src.addAll(sub);
- src.add(new Integer(5));
- src.add(new Integer(6));
-
- // so src becomes a list like this:
- // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
-
- sub = new ArrayList(src.subList(3, 11));
- // [1, 2, 3, 1, 2, 3, 5, 6]
- assertEquals("TestA : Returned wrong indexOfSubList, ", 3, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(6, 11));
- // [1, 2, 3, 5, 6]
- assertEquals("TestB : Returned wrong indexOfSubList, ", 6, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 3));
- // [1, 2, 3]
- assertEquals("TestCC : Returned wrong indexOfSubList, ", 0, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(9, 11));
- // [5, 6]
- assertEquals("TestD : Returned wrong indexOfSubList, ", 9, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(10, 11));
- // [6]
- assertEquals("TestE : Returned wrong indexOfSubList, ", 10, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 11));
- // the whole list
- assertEquals("TestH : Returned wrong indexIndexOfSubList, ", 0,
- Collections.indexOfSubList(src, sub));
-
- // a non-matching list
- assertEquals("TestI : Returned wrong indexOfSubList, ", -1, Collections
- .indexOfSubList(src, sub2));
- }
-
-
- private void testwithCharList(int count, String string1, String string2,
- boolean first) {
- char[] chars = string1.toCharArray();
- List list = new ArrayList();
- for (int i = 0; i < chars.length; i++) {
- list.add(new Character(chars[i]));
- }
- chars = string2.toCharArray();
- List sublist = new ArrayList();
- for (int i = 0; i < chars.length; i++) {
- sublist.add(new Character(chars[i]));
- }
-
- if (first)
- assertEquals("Test " + count + ": Returned wrong index:", string1
- .indexOf(string2), Collections
- .indexOfSubList(list, sublist));
- else
- assertEquals("Test " + count + ": Returned wrong index:", string1
- .lastIndexOf(string2), Collections.lastIndexOfSubList(list,
- sublist));
- }
-
- /**
- * java.util.Collections#lastIndexOfSubList(java.util.List,
- * java.util.List)
- */
- public void test_lastIndexOfSubListLjava_util_ListLjava_util_List() {
- // Test for method int lastIndexOfSubList(java.util.List,
- // java.util.List)
- String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z-END";
-
- List list = new ArrayList();
- try {
- Collections.lastIndexOfSubList(null, list);
- fail("Expected NullPointerException for null list first parameter");
- } catch (NullPointerException e) {
- }
- try {
- Collections.lastIndexOfSubList(list, null);
- fail("Expected NullPointerException for null list second parameter");
- } catch (NullPointerException e) {
- }
-
- testwithCharList(1, string1, "B", false);
- testwithCharList(2, string1, "LIST", false);
- testwithCharList(3, string1, "SUBLIST", false);
- testwithCharList(4, string1, "END", false);
- testwithCharList(5, string1, "NONE", false);
-
- // test boundary conditions
- testwithCharList(6, "", "", false);
- testwithCharList(7, "LIST", "", false);
- testwithCharList(8, "", "SUBLIST", false);
- }
-
- /**
- * java.util.Collections#lastIndexOfSubList(java.util.List,
- * java.util.List)
- */
- public void test_lastIndexOfSubList2() {
- ArrayList sub = new ArrayList();
- sub.add(new Integer(1));
- sub.add(new Integer(2));
- sub.add(new Integer(3));
-
- ArrayList sub2 = new ArrayList();
- sub2.add(new Integer(7));
- sub2.add(new Integer(8));
-
- ArrayList src = new ArrayList();
- src.addAll(sub);
- src.addAll(sub);
- src.addAll(sub);
- src.add(new Integer(5));
- src.add(new Integer(6));
-
- // so src is a list like this:
- // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
-
- Collections.reverse(src);
- // it becomes like this :
- // [6, 5, 3, 2, 1, 3, 2, 1, 3, 2, 1]
-
- sub = new ArrayList(src.subList(0, 8));
- // [6, 5, 3, 2, 1, 3, 2, 1]
- assertEquals("TestA : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 5));
- // [6, 5, 3, 2, 1]
- assertEquals("TestB : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(2, 5));
- // [3, 2, 1]
- assertEquals("TestC : Returned wrong lastIndexOfSubList, ", 8,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(9, 11));
- // [2, 1]
- assertEquals("TestD : Returned wrong lastIndexOfSubList, ", 9,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(10, 11));
- // [1]
- assertEquals("TestE : Returned wrong lastIndexOfSubList, ", 10,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 2));
- // [6, 5]
- assertEquals("TestF : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 1));
- // [6]
- assertEquals("TestG : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 11));
- // the whole list
- assertEquals("TestH : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- // a non-matching list
- assertEquals("TestI : Returned wrong lastIndexOfSubList, ", -1,
- Collections.lastIndexOfSubList(src, sub2));
- }
-
- /**
- * java.util.Collections#list(java.util.Enumeration)
- */
- public void test_listLjava_util_Enumeration() {
- // Test for method java.util.ArrayList list(java.util.Enumeration)
-
- Enumeration e = Collections.enumeration(ll);
- ArrayList al = Collections.list(e);
-
- int size = al.size();
- assertEquals("Wrong size", ll.size(), size);
-
- for (int i = 0; i < size; i++) {
- assertEquals("wrong element at position " + i + ",", ll.get(i), al
- .get(i));
- }
- }
-
- /**
- * java.util.Collections#synchronizedCollection(java.util.Collection)
- */
- public void test_synchronizedCollectionLjava_util_Collection() {
- // Test for method java.util.Collection
- // java.util.Collections.synchronizedCollection(java.util.Collection)
-
- LinkedList smallList = new LinkedList();
- for (int i = 0; i < 50; i++) {
- smallList.add(objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Collection synchCol = Collections.synchronizedCollection(smallList);
- // Replacing the previous line with the line below *should* cause the
- // test to fail--the collecion below isn't synchronized
- // Collection synchCol = smallList;
-
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchCol, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchCol, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned collection corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- synchCol.add(null);
- assertTrue("Trying to use nulls in collection failed", synchCol
- .contains(null));
-
- smallList = new LinkedList();
- for (int i = 0; i < 100; i++) {
- smallList.add(objArray[i]);
- }
- new Support_CollectionTest("", Collections
- .synchronizedCollection(smallList)).runTest();
- }
-
- /**
- * java.util.Collections#synchronizedList(java.util.List)
- */
- public void test_synchronizedListLjava_util_List() {
- try {
- Collections.synchronizedList(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // test with a Sequential Access List
- List smallList = new LinkedList();
- testSynchronizedList(smallList, "Sequential Access");
-
- smallList = new LinkedList();
- List myList;
- for (int i = 0; i < 100; i++) {
- smallList.add(objArray[i]);
- }
- myList = Collections.synchronizedList(smallList);
- new Support_ListTest("", myList).runTest();
-
- // test with a Random Access List
- smallList = new ArrayList();
- testSynchronizedList(smallList, "Random Access");
-
- smallList = new ArrayList();
- for (int i = 0; i < 100; i++) {
- smallList.add(objArray[i]);
- }
- myList = Collections.synchronizedList(smallList);
- new Support_ListTest("", myList).runTest();
- }
-
- private void testSynchronizedList(List smallList, String type) {
- for (int i = 0; i < 50; i++) {
- smallList.add(objArray[i]);
- }
- final int numberOfLoops = 200;
- List synchList = Collections.synchronizedList(smallList);
- if (type.equals("Random Access"))
- assertTrue(
- "Returned synchronized list should implement the Random Access interface",
- synchList instanceof RandomAccess);
- else
- assertTrue(
- "Returned synchronized list should not implement the Random Access interface",
- !(synchList instanceof RandomAccess));
-
- // Replacing the previous line with the line below *should* cause the
- // test to fail--the list below isn't synchronized
- // List synchList = smallList;
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchList, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchList, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue(
- type
- + " list tests: Returned list corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail(type + " list tests: join() interrupted");
- }
- synchList.set(25, null);
- assertNull(type + " list tests: Trying to use nulls in list failed",
- synchList.get(25));
- }
-
- /**
- * java.util.Collections#synchronizedMap(java.util.Map)
- */
- public void test_synchronizedMapLjava_util_Map() {
- // Test for method java.util.Map
- // java.util.Collections.synchronizedMap(java.util.Map)
- HashMap smallMap = new HashMap();
- for (int i = 0; i < 50; i++) {
- smallMap.put(objArray[i], objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Map synchMap = Collections.synchronizedMap(smallMap);
- // Replacing the previous line with the line below should cause the test
- // to fail--the list below isn't synchronized
- // Map synchMap = smallMap;
-
- SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
- false, numberOfLoops);
- SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
- true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned map corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- // synchronized map does not have to permit null keys or values
- synchMap.put(new Long(25), null);
- synchMap.put(null, new Long(30));
- assertNull("Trying to use a null value in map failed", synchMap
- .get(new Long(25)));
- assertTrue("Trying to use a null key in map failed", synchMap.get(null)
- .equals(new Long(30)));
-
- smallMap = new HashMap();
- for (int i = 0; i < 100; i++) {
- smallMap.put(objArray[i].toString(), objArray[i]);
- }
- synchMap = Collections.synchronizedMap(smallMap);
- new Support_UnmodifiableMapTest("", synchMap).runTest();
- synchMap.keySet().remove(objArray[50].toString());
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map: ",
- synchMap.get(objArray[50].toString()));
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the original map",
- smallMap.get(objArray[50].toString()));
- }
-
- /**
- * java.util.Collections#synchronizedSet(java.util.Set)
- */
- public void test_synchronizedSetLjava_util_Set() {
- // Test for method java.util.Set
- // java.util.Collections.synchronizedSet(java.util.Set)
- HashSet smallSet = new HashSet();
- for (int i = 0; i < 50; i++) {
- smallSet.add(objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Set synchSet = Collections.synchronizedSet(smallSet);
- // Replacing the previous line with the line below should cause the test
- // to fail--the set below isn't synchronized
- // Set synchSet = smallSet;
-
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchSet, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchSet, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned set corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- Set mySet = Collections.synchronizedSet(smallSet);
- mySet.add(null);
- assertTrue("Trying to use nulls in list failed", mySet.contains(null));
-
- smallSet = new HashSet();
- for (int i = 0; i < 100; i++) {
- smallSet.add(objArray[i]);
- }
- new Support_SetTest("", Collections.synchronizedSet(smallSet))
- .runTest();
- }
-
- /**
- * java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
- */
- public void test_synchronizedSortedMapLjava_util_SortedMap() {
- // Test for method java.util.SortedMap
- // java.util.Collections.synchronizedSortedMap(java.util.SortedMap)
- TreeMap smallMap = new TreeMap();
- for (int i = 0; i < 50; i++) {
- smallMap.put(objArray[i], objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Map synchMap = Collections.synchronizedMap(smallMap);
- // Replacing the previous line with the line below should cause the test
- // to fail--the list below isn't synchronized
- // Map synchMap = smallMap;
-
- SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
- false, numberOfLoops);
- SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
- true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned map corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- smallMap = new TreeMap();
- for (int i = 0; i < 100; i++) {
- smallMap.put(objArray[i].toString(), objArray[i]);
- }
- synchMap = Collections.synchronizedSortedMap(smallMap);
- new Support_UnmodifiableMapTest("", synchMap).runTest();
- synchMap.keySet().remove(objArray[50].toString());
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map",
- synchMap.get(objArray[50].toString()));
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the original map",
- smallMap.get(objArray[50].toString()));
- }
-
- /**
- * java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
- */
- public void test_synchronizedSortedSetLjava_util_SortedSet() {
- // Test for method java.util.SortedSet
- // java.util.Collections.synchronizedSortedSet(java.util.SortedSet)
- TreeSet smallSet = new TreeSet();
- for (int i = 0; i < 50; i++) {
- smallSet.add(objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Set synchSet = Collections.synchronizedSet(smallSet);
- // Replacing the previous line with the line below should cause the test
- // to fail--the list below isn't synchronized
- // Set synchSet = smallSet;
-
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchSet, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchSet, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned set corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
- }
-
- /**
- * java.util.Collections#unmodifiableCollection(java.util.Collection)
- */
- public void test_unmodifiableCollectionLjava_util_Collection() {
- // Test for method java.util.Collection
- // java.util.Collections.unmodifiableCollection(java.util.Collection)
- boolean exception = false;
- Collection c = Collections.unmodifiableCollection(ll);
- assertTrue("Returned collection is of incorrect size", c.size() == ll
- .size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned list missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of collection");
- }
-
- try {
- c.remove(new Object());
- fail("Allowed modification of collection");
- } catch (UnsupportedOperationException e) {
- // Correct
- }
-
- Collection myCollection = new ArrayList();
- myCollection.add(new Integer(20));
- myCollection.add(null);
- c = Collections.unmodifiableCollection(myCollection);
- assertTrue("Collection should contain null", c.contains(null));
- assertTrue("Collection should contain Integer(20)", c
- .contains(new Integer(20)));
-
- myCollection = new ArrayList();
- for (int counter = 0; counter < 100; counter++) {
- myCollection.add(objArray[counter]);
- }
- new Support_UnmodifiableCollectionTest("", Collections
- .unmodifiableCollection(myCollection)).runTest();
- }
-
- /**
- * java.util.Collections#unmodifiableList(java.util.List)
- */
- public void test_unmodifiableListLjava_util_List() {
- // Test for method java.util.List
- // java.util.Collections.unmodifiableList(java.util.List)
-
- // test with a Sequential Access List
- boolean exception = false;
- List c = Collections.unmodifiableList(ll);
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.unmodifiableList(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- assertTrue("Returned list is of incorrect size", c.size() == ll.size());
- assertTrue(
- "Returned List should not implement Random Access interface",
- !(c instanceof RandomAccess));
-
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned list missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of list");
- }
-
- try {
- c.remove(new Object());
- fail("Allowed modification of list");
- } catch (UnsupportedOperationException e) {
- // Correct
- }
-
- // test with a Random Access List
- List smallList = new ArrayList();
- smallList.add(null);
- smallList.add("yoink");
- c = Collections.unmodifiableList(smallList);
- assertNull("First element should be null", c.get(0));
- assertTrue("List should contain null", c.contains(null));
- assertTrue(
- "T1. Returned List should implement Random Access interface",
- c instanceof RandomAccess);
-
- smallList = new ArrayList();
- for (int counter = 0; counter < 100; counter++) {
- smallList.add(objArray[counter]);
- }
- List myList = Collections.unmodifiableList(smallList);
- assertTrue("List should not contain null", !myList.contains(null));
- assertTrue(
- "T2. Returned List should implement Random Access interface",
- myList instanceof RandomAccess);
-
- assertTrue("get failed on unmodifiable list", myList.get(50).equals(
- new Integer(50)));
- ListIterator listIterator = myList.listIterator();
- for (int counter = 0; listIterator.hasNext(); counter++) {
- assertTrue("List has wrong elements", ((Integer) listIterator
- .next()).intValue() == counter);
- }
- new Support_UnmodifiableCollectionTest("", smallList).runTest();
- }
-
- /**
- * java.util.Collections#unmodifiableMap(java.util.Map)
- */
- public void test_unmodifiableMapLjava_util_Map() {
- // Test for method java.util.Map
- // java.util.Collections.unmodifiableMap(java.util.Map)
- boolean exception = false;
- Map c = Collections.unmodifiableMap(hm);
- assertTrue("Returned map is of incorrect size", c.size() == hm.size());
- Iterator i = hm.keySet().iterator();
- while (i.hasNext()) {
- Object x = i.next();
- assertTrue("Returned map missing elements", c.get(x).equals(
- hm.get(x)));
- }
- try {
- c.put(new Object(), "");
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- assertTrue("Allowed modification of map", exception);
-
- exception = false;
- try {
- c.remove(new Object());
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of map", exception);
-
- exception = false;
- Iterator it = c.entrySet().iterator();
- Map.Entry entry = (Map.Entry) it.next();
- try {
- entry.setValue("modified");
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of entry", exception);
-
- exception = false;
- Object[] array = c.entrySet().toArray();
- try {
- ((Map.Entry) array[0]).setValue("modified");
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of array entry", exception);
-
- exception = false;
- Map.Entry[] array2 = (Map.Entry[]) c.entrySet().toArray(
- new Map.Entry[0]);
- try {
- array2[0].setValue("modified");
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of array entry2", exception);
-
- HashMap smallMap = new HashMap();
- smallMap.put(null, new Long(30));
- smallMap.put(new Long(25), null);
- Map unmodMap = Collections.unmodifiableMap(smallMap);
-
- assertNull("Trying to use a null value in map failed", unmodMap
- .get(new Long(25)));
- assertTrue("Trying to use a null key in map failed", unmodMap.get(null)
- .equals(new Long(30)));
-
- smallMap = new HashMap();
- for (int counter = 0; counter < 100; counter++) {
- smallMap.put(objArray[counter].toString(), objArray[counter]);
- }
- unmodMap = Collections.unmodifiableMap(smallMap);
- new Support_UnmodifiableMapTest("", unmodMap).runTest();
-
- }
-
- /**
- * java.util.Collections#unmodifiableSet(java.util.Set)
- */
- public void test_unmodifiableSetLjava_util_Set() {
- // Test for method java.util.Set
- // java.util.Collections.unmodifiableSet(java.util.Set)
- boolean exception = false;
- Set c = Collections.unmodifiableSet(s);
- assertTrue("Returned set is of incorrect size", c.size() == s.size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned set missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of set");
- }
- try {
- c.remove(new Object());
- fail("Allowed modification of set");
- } catch (UnsupportedOperationException e) {
- // Correct
- }
-
- Set mySet = Collections.unmodifiableSet(new HashSet());
- assertTrue("Should not contain null", !mySet.contains(null));
- mySet = Collections.unmodifiableSet(Collections.singleton(null));
- assertTrue("Should contain null", mySet.contains(null));
-
- mySet = new TreeSet();
- for (int counter = 0; counter < 100; counter++) {
- mySet.add(objArray[counter]);
- }
- new Support_UnmodifiableCollectionTest("", Collections
- .unmodifiableSet(mySet)).runTest();
- }
-
- /**
- * java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
- */
- public void test_unmodifiableSortedMapLjava_util_SortedMap() {
- // Test for method java.util.SortedMap
- // java.util.Collections.unmodifiableSortedMap(java.util.SortedMap)
- boolean exception = false;
- TreeMap tm = new TreeMap();
- tm.putAll(hm);
- Map c = Collections.unmodifiableSortedMap(tm);
- assertTrue("Returned map is of incorrect size", c.size() == tm.size());
- Iterator i = hm.keySet().iterator();
- while (i.hasNext()) {
- Object x = i.next();
- assertTrue("Returned map missing elements", c.get(x).equals(
- tm.get(x)));
- }
- try {
- c.put(new Object(), "");
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
-
- if (!exception) {
- fail("Allowed modification of map");
- }
- try {
- c.remove(new Object());
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- fail("Allowed modification of map");
- }
-
- /**
- * java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
- */
- public void test_unmodifiableSortedSetLjava_util_SortedSet() {
- // Test for method java.util.SortedSet
- // java.util.Collections.unmodifiableSortedSet(java.util.SortedSet)
- boolean exception = false;
- SortedSet ss = new TreeSet();
- ss.addAll(s);
- SortedSet c = Collections.unmodifiableSortedSet(ss);
- assertTrue("Returned set is of incorrect size", c.size() == ss.size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned set missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of set");
- }
- try {
- c.remove(new Object());
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- fail("Allowed modification of set");
- }
-
- /**
- * Test unmodifiable objects toString methods
- */
- public void test_unmodifiable_toString_methods() {
- // Regression for HARMONY-552
- ArrayList al = new ArrayList();
- al.add("a");
- al.add("b");
- Collection uc = Collections.unmodifiableCollection(al);
- assertEquals("[a, b]", uc.toString());
- HashMap m = new HashMap();
- m.put("one", "1");
- m.put("two", "2");
- Map um = Collections.unmodifiableMap(m);
- assertTrue("{one=1, two=2}".equals(um.toString()) ||
- "{two=2, one=1}".equals(um.toString()));
- }
-
-
- public void test_singletonListLjava_lang_Object() {
- // Test for method java.util.Set
- // java.util.Collections.singleton(java.lang.Object)
- String str = "Singleton";
-
- List single = Collections.singletonList(str);
- assertEquals(1, single.size());
- assertTrue(single.contains(str));
- assertFalse(single.contains(null));
- assertFalse(Collections.singletonList(null).contains(str));
- assertTrue(Collections.singletonList(null).contains(null));
-
- try {
- single.add("New element");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- public void test_singletonMapLjava_lang_Object() {
- // Test for method java.util.Set
- // java.util.Collections.singleton(java.lang.Object)
- Double key = new Double (3.14);
- String value = "Fundamental constant";
-
- Map single = Collections.singletonMap(key, value);
- assertEquals(1, single.size());
- assertTrue(single.containsKey(key));
- assertTrue(single.containsValue(value));
- assertFalse(single.containsKey(null));
- assertFalse(single.containsValue(null));
- assertFalse(Collections.singletonMap(null, null).containsKey(key));
- assertFalse(Collections.singletonMap(null, null).containsValue(value));
- assertTrue(Collections.singletonMap(null, null).containsKey(null));
- assertTrue(Collections.singletonMap(null, null).containsValue(null));
-
- try {
- single.clear();
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- try {
- single.put(new Double(1), "one wrong value");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[1000];
- myobjArray = new Object[1000];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- myobjArray[i] = new MyInt(i);
- }
-
- ll = new LinkedList();
- myll = new LinkedList();
- s = new HashSet();
- mys = new HashSet();
- reversedLinkedList = new LinkedList(); // to be sorted in reverse order
- myReversedLinkedList = new LinkedList(); // to be sorted in reverse
- // order
- hm = new HashMap();
- for (int i = 0; i < objArray.length; i++) {
- ll.add(objArray[i]);
- myll.add(myobjArray[i]);
- s.add(objArray[i]);
- mys.add(myobjArray[i]);
- reversedLinkedList.add(objArray[objArray.length - i - 1]);
- myReversedLinkedList.add(myobjArray[myobjArray.length - i - 1]);
- hm.put(objArray[i].toString(), objArray[i]);
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- objArray = null;
- myobjArray = null;
-
- ll = null;
- myll = null;
- reversedLinkedList = null;
- myReversedLinkedList = null;
- s = null;
- mys = null;
- hm = null;
- }
-
- protected void doneSuite() {
- objArray = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java b/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java
deleted file mode 100644
index 3750e81..0000000
--- a/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java
+++ /dev/null
@@ -1,667 +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 tests.api.java.util;
-
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.List;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-
-public class ConcurrentModTest extends TestCase {
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- public void testGet() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method get(int).
- sub.get(1);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
-
- try {
- al.get(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- al.get(al.size()+1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- public void testSet() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method set(int,Object).
- sub.set(1, two);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- public void testAdd() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method Add(int,Object).
- sub.add(1, two);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- public void testRemove() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method remove(int).
- sub.remove(1);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
-
- try {
- sub.remove(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- sub.remove(sub.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- al = new AbstractList() {
-
- @Override
- public Object get(int index) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int size() {
- // TODO Auto-generated method stub
- return 0;
- }
- };
-
- try {
- al.remove(1);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- public void testAddAll() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method addAll(int,Collection).
- Collection c = new Vector();
- Double five = new Double(5.0);
- c.add(five);
- sub.addAll(1, c);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
- }
-
- public void test_addLjava_lang_Object() {
- AbstractList abstr = new AbstractList() {
-
- @Override
- public Object get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
-
- };
-
- try {
- abstr.add(null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //ecpected
- }
- abstr = new AbstractList<Double>() {
- @Override
- public boolean add(Double value) {
- return true;
- }
-
- @Override
- public Double get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.add(1);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public boolean add(Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- return true;
- }
-
- @Override
- public Integer get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- abstr.add(1);
- try {
- abstr.add(33);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
- }
-
- public void test_addILjava_lang_Object() {
- AbstractList abstr = new AbstractList() {
-
- @Override
- public Object get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
-
- };
-
- try {
- abstr.add(1, null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //ecpected
- }
- abstr = new AbstractList<Double>() {
- @Override
- public void add(int index, Double value) {
- }
-
- @Override
- public Double get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.add(1, 1);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public void add(int index, Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- }
-
- @Override
- public Integer get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- abstr.add(1, 1);
- try {
- abstr.add(1, 33);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
-
- abstr = new ArrayList();
-
- abstr.add(0, "element");
- abstr.add(1, null);
- abstr.add(2, 1);
- abstr.add(3, new Double(33));
-
- try {
- abstr.add(-3, new Double(33));
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- abstr.add(abstr.size() + 1, new Double(33));
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- public void test_addAllILjava_util_Collection() {
- Collection c = new Vector();
- c.add(new Double(33));
- c.add(10);
- c.add("String");
-
- AbstractList abstr = new AbstractList() {
- @Override
- public Object get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- abstr.addAll(0, c);
- fail("UnsuportedOperationException expected");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
-
- abstr = new AbstractList<Double>() {
- @Override
- public void add(int index, Double value) {
- }
-
- @Override
- public Double get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.addAll(0, c);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expectd
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public void add(int index, Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- }
-
- @Override
- public Integer get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
- c.clear();
- c.add(new Integer(1));
- c.add(new Integer(2));
- c.add(new Integer(3));
- c.add(new Integer(4));
- c.add(new Integer(5));
-
- abstr.addAll(0, c);
-
- c.add(new Integer(33));
-
- try {
- abstr.addAll(0, c);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
- abstr = new ArrayList();
- abstr.addAll(0, c);
-
- try {
- abstr.addAll(-1, c);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- abstr.addAll(abstr.size() + 1, c);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- public void test_clear() {
- AbstractList abstr = new ArrayList();
-
- assertEquals(0, abstr.size());
- abstr.add("String");
- abstr.add("1");
- abstr.add(2);
- abstr.add(new Double(3));
- assertEquals(4, abstr.size());
- abstr.clear();
- assertEquals(0, abstr.size());
- }
-
- public void test_equalsLjava_lang_Object() {
- Collection c = new Vector();
- c.add(new Double(33));
- c.add(10);
- c.add("String");
-
- AbstractList abstr = new ArrayList();
- AbstractList abstr1 = new ArrayList();
-
- assertFalse(abstr.equals(this));
- abstr.add(new Double(33));
- abstr.add(10);
- abstr.add("String");
- assertTrue(abstr.equals(c));
- abstr1.addAll(c);
- assertTrue(abstr.equals(abstr1));
- }
-
- public void test_setILjava_lang_Object() {
- Collection c = new Vector();
- c.add(new Double(33));
- c.add(10);
- c.add("String");
-
- AbstractList abstr1 = new ArrayList();
- AbstractList abstr2 = new ArrayList();
-
- abstr1.addAll(c);
- abstr2.addAll(c);
- assertTrue(abstr1.equals(abstr2));
- abstr1.set(1, 1);
- assertFalse(abstr1.equals(abstr2));
-
- try {
- abstr1.set(abstr1.size() + 1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- abstr1.set(-1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- AbstractList abstr = new AbstractList() {
-
- @Override
- public Object get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
-
- };
-
- try {
- abstr.set(0, null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
-
- abstr = new AbstractList<Double>() {
- @Override
- public Double set(int index, Double value) {
- return value;
- }
-
- @Override
- public Double get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.set(0, 1);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public Integer set(int index, Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- return value;
- }
-
- @Override
- public Integer get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.set(0, 33);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
- }
- class Mock_ArrayList extends ArrayList {
- @Override
- public void removeRange(int fromIndex, int toIndex) {
- super.removeRange(fromIndex, toIndex);
- }
- }
-
- public void test_removeRangeII() {
- Mock_ArrayList al1 = new Mock_ArrayList();
- al1.add(1);
- al1.add(2);
- al1.add(3);
- al1.add(4);
- al1.add(5);
- Mock_ArrayList al2 = new Mock_ArrayList();
-
- al2.add(1);
- al2.add(5);
- assertNotSame(al1,al2);
- al1.removeRange(1, 4);
- assertEquals(al1,al2);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java b/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java
deleted file mode 100644
index 0cd4076..0000000
--- a/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java
+++ /dev/null
@@ -1,107 +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 tests.api.java.util;
-
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.Iterator;
-import java.util.LinkedList;
-
-public class ConcurrentModificationExceptionTest extends
- junit.framework.TestCase {
-
- static public class CollectionModifier implements Runnable {
- Collection col;
-
- boolean keepGoing = true;
-
- public CollectionModifier(Collection c) {
- col = c;
- }
-
- public void stopNow() {
- keepGoing = false;
- }
-
- public void run() {
- Object someItem = new Integer(-1);
- while (keepGoing) {
- col.add(someItem);
- col.remove(someItem);
- }
- }
- }
-
- /**
- * java.util.ConcurrentModificationException#ConcurrentModificationException()
- */
- public void test_Constructor() {
- // Test for method java.util.ConcurrentModificationException()
- Collection myCollection = new LinkedList();
- Iterator myIterator = myCollection.iterator();
- for (int counter = 0; counter < 50; counter++)
- myCollection.add(new Integer(counter));
- CollectionModifier cm = new CollectionModifier(myCollection);
- Thread collectionSlapper = new Thread(cm);
- try {
- collectionSlapper.start();
- while (myIterator.hasNext())
- myIterator.next();
- } catch (ConcurrentModificationException e) {
- cm.stopNow();
- return;
- }
- cm.stopNow();
- // The exception should have been thrown--if the code flow makes it here
- // the test has failed
- fail("Failed to throw expected ConcurrentModificationException");
- }
-
- /**
- * java.util.ConcurrentModificationException#ConcurrentModificationException(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method
- // java.util.ConcurrentModificationException(java.lang.String)
- String errorMessage = "This is an error message";
- try {
- // This is here to stop "unreachable code" unresolved problem
- if (true)
- throw new ConcurrentModificationException(errorMessage);
- } catch (ConcurrentModificationException e) {
- assertTrue("Exception thrown without error message", e.getMessage()
- .equals(errorMessage));
- return;
- }
- fail("Failed to throw expected ConcurrentModificationException");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/CurrencyTest.java b/luni/src/test/java/tests/api/java/util/CurrencyTest.java
deleted file mode 100644
index 82fd7cf..0000000
--- a/luni/src/test/java/tests/api/java/util/CurrencyTest.java
+++ /dev/null
@@ -1,428 +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 tests.api.java.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Currency;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-public class CurrencyTest extends junit.framework.TestCase {
-
- private static Locale defaultLocale = Locale.getDefault();
-
- /**
- * java.util.Currency#getInstance(java.lang.String)
- */
- public void test_getInstanceLjava_lang_String() {
- // see test_getInstanceLjava_util_Locale() tests
- }
-
- /**
- * java.util.Currency#getInstance(java.util.Locale)
- */
- public void test_getInstanceLjava_util_Locale() {
- /*
- * the behaviour in all these three cases should be the same since this
- * method ignores language and variant component of the locale.
- */
- Currency c0 = Currency.getInstance("CAD");
- Currency c1 = Currency.getInstance(new Locale("en", "CA"));
- assertTrue(
- "Currency.getInstance(new Locale(\"en\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
- c1 == c0);
- Currency c2 = Currency.getInstance(new Locale("fr", "CA"));
- assertTrue(
- "Currency.getInstance(new Locale(\"fr\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
- c2 == c0);
- Currency c3 = Currency.getInstance(new Locale("", "CA"));
- assertTrue(
- "Currency.getInstance(new Locale(\"\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
- c3 == c0);
-
- c0 = Currency.getInstance("JPY");
- c1 = Currency.getInstance(new Locale("ja", "JP"));
- assertTrue(
- "Currency.getInstance(new Locale(\"ja\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
- c1 == c0);
- c2 = Currency.getInstance(new Locale("", "JP"));
- assertTrue(
- "Currency.getInstance(new Locale(\"\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
- c2 == c0);
- c3 = Currency.getInstance(new Locale("bogus", "JP"));
- assertTrue(
- "Currency.getInstance(new Locale(\"bogus\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
- c3 == c0);
-
- Locale localeGu = new Locale("gu", "IN");
- Currency cGu = Currency.getInstance(localeGu);
- Locale localeKn = new Locale("kn", "IN");
- Currency cKn = Currency.getInstance(localeKn);
- assertTrue("Currency.getInstance(Locale_" + localeGu.toString() + "))"
- + "isn't equal to " + "Currency.getInstance(Locale_"
- + localeKn.toString() + "))", cGu == cKn);
-
- // some teritories do not have currencies, like Antarctica
- Locale loc = new Locale("", "AQ");
- try {
- Currency curr = Currency.getInstance(loc);
- assertNull(
- "Currency.getInstance(new Locale(\"\", \"AQ\")) did not return null",
- curr);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException " + e);
- }
-
- // unsupported/legacy iso3 countries
- loc = new Locale("", "ZR");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
- loc = new Locale("", "ZAR");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
- loc = new Locale("", "FX");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
- loc = new Locale("", "FXX");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * java.util.Currency#getSymbol()
- */
- public void test_getSymbol() {
- Currency currK = Currency.getInstance("KRW");
- Currency currI = Currency.getInstance("IEP");
- Currency currUS = Currency.getInstance("USD");
-
- Locale.setDefault(Locale.US);
- // BEGIN android-changed
- // KRW currency symbol is \u20a9 since CLDR1.7 release.
- assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
- // IEP currency symbol is IEP since CLDR2.0 release.
- assertEquals("currI.getSymbol()", "IEP", currI.getSymbol());
- // END android-changed
- assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
-
- Locale.setDefault(new Locale("en", "IE"));
- // BEGIN android-changed
- assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
- assertEquals("currI.getSymbol()", "IEP", currI.getSymbol());
- assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
- // END android-changed
-
- // test what happens if this is an invalid locale,
- // one with Korean country but an India language
- Locale.setDefault(new Locale("kr", "KR"));
- // BEGIN android-changed
- assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
- assertEquals("currI.getSymbol()", "IEP", currI.getSymbol());
- // END android-changed
- assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
- }
-
- /**
- * java.util.Currency#getSymbol(java.util.Locale)
- */
- public void test_getSymbolLjava_util_Locale() {
- //Tests was simplified because java specification not
- // includes strong requirements for returnig symbol.
- // on android platform used wrong character for yen
- // sign: \u00a5 instead of \uffe5
- Locale[] desiredLocales = new Locale[]{
- Locale.JAPAN, Locale.JAPANESE,
- Locale.FRANCE, Locale.FRENCH,
- Locale.US, Locale.UK,
- Locale.CANADA, Locale.CANADA_FRENCH,
- Locale.ENGLISH,
- new Locale("ja", "JP"), new Locale("", "JP"),
-
- new Locale("fr", "FR"), new Locale("", "FR"),
-
- new Locale("en", "US"), new Locale("", "US"),
- new Locale("es", "US"), new Locale("ar", "US"),
- new Locale("ja", "US"),
-
- new Locale("en", "CA"), new Locale("fr", "CA"),
- new Locale("", "CA"), new Locale("ar", "CA"),
-
- new Locale("ja", "JP"), new Locale("", "JP"),
- new Locale("ar", "JP"),
-
- new Locale("ja", "AE"), new Locale("en", "AE"),
- new Locale("ar", "AE"),
-
- new Locale("da", "DK"), new Locale("", "DK"),
-
- new Locale("da", ""), new Locale("ja", ""),
- new Locale("en", "")};
-
- Set<Locale> availableLocales = new HashSet<Locale>(Arrays.asList(Locale.getAvailableLocales()));
-
- ArrayList<Locale> locales = new ArrayList<Locale>();
- for (Locale desiredLocale : desiredLocales) {
- if (availableLocales.contains(desiredLocale)) {
- locales.add(desiredLocale);
- }
- }
-
- Locale[] loc1 = locales.toArray(new Locale[locales.size()]);
-
- String[] euro = new String[] {"EUR", "\u20ac"};
- // \u00a5 and \uffe5 are actually the same symbol, just different code points.
- // But the RI returns the \uffe5 and Android returns those with \u00a5
- String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
- String[] dollar = new String[] {"USD", "$", "US$", "$US"};
- // BEGIN android-changed
- // Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
- String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"};
- // END android-changed
-
- Currency currE = Currency.getInstance("EUR");
- Currency currJ = Currency.getInstance("JPY");
- Currency currUS = Currency.getInstance("USD");
- Currency currCA = Currency.getInstance("CAD");
-
- int i, j, k;
- boolean flag;
-
- for(k = 0; k < loc1.length; k++) {
- Locale.setDefault(loc1[k]);
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < euro.length; j++) {
- if (currE.getSymbol(loc1[i]).equals(euro[j])) {
- flag = true;
- break;
- }
- }
- assertTrue("Default Locale is: " + Locale.getDefault()
- + ". For locale " + loc1[i]
- + " the Euro currency returned "
- + currE.getSymbol(loc1[i])
- + ". Expected was one of these: "
- + Arrays.toString(euro), flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < yen.length; j++) {
- byte[] b1 = null;
- byte[] b2 = null;
- if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
- flag = true;
- break;
- }
- }
- assertTrue("Default Locale is: " + Locale.getDefault()
- + ". For locale " + loc1[i]
- + " the Yen currency returned "
- + currJ.getSymbol(loc1[i])
- + ". Expected was one of these: "
- + Arrays.toString(yen), flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < dollar.length; j++) {
- if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
- flag = true;
- break;
- }
- }
- assertTrue("Default Locale is: " + Locale.getDefault()
- + ". For locale " + loc1[i]
- + " the Dollar currency returned "
- + currUS.getSymbol(loc1[i])
- + ". Expected was one of these: "
- + Arrays.toString(dollar), flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < cDollar.length; j++) {
- if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
- flag = true;
- break;
- }
- }
- assertTrue("Default Locale is: " + Locale.getDefault()
- + ". For locale " + loc1[i]
- + " the Canadian Dollar currency returned "
- + currCA.getSymbol(loc1[i])
- + ". Expected was one of these: "
- + Arrays.toString(cDollar), flag);
- }
- }
- }
-
- /**
- * java.util.Currency#getDefaultFractionDigits()
- */
- public void test_getDefaultFractionDigits() {
-
- Currency c1 = Currency.getInstance("TND");
- c1.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c1
- + "\") returned incorrect number of digits. ", 3, c1
- .getDefaultFractionDigits());
-
- Currency c2 = Currency.getInstance("EUR");
- c2.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c2
- + "\") returned incorrect number of digits. ", 2, c2
- .getDefaultFractionDigits());
-
- Currency c3 = Currency.getInstance("JPY");
- c3.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c3
- + "\") returned incorrect number of digits. ", 0, c3
- .getDefaultFractionDigits());
-
- Currency c4 = Currency.getInstance("XXX");
- c4.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c4
- + "\") returned incorrect number of digits. ", -1, c4
- .getDefaultFractionDigits());
- }
-
- /**
- * java.util.Currency#getCurrencyCode() Note: lines under remarks
- * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
- * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
- * on SUN VM
- */
- public void test_getCurrencyCode() {
- final Collection<Locale> locVal = Arrays.asList(
- Locale.CANADA,
- Locale.CANADA_FRENCH,
- Locale.CHINA,
- // Locale.CHINESE,
- // Locale.ENGLISH,
- Locale.FRANCE,
- // Locale.FRENCH,
- // Locale.GERMAN,
- Locale.GERMANY,
- // Locale.ITALIAN,
- Locale.ITALY, Locale.JAPAN,
- // Locale.JAPANESE,
- Locale.KOREA,
- // Locale.KOREAN,
- Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
- Locale.UK, Locale.US);
- final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
- "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
-
- Iterator<String> dat = locDat.iterator();
- for (Locale l : locVal) {
- String d = dat.next().trim();
- assertEquals("For locale " + l + " currency code wrong", Currency.getInstance(l)
- .getCurrencyCode(), d);
- }
- }
-
- /**
- * java.util.Currency#toString() Note: lines under remarks
- * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
- * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
- * on SUN VM
- */
- public void test_toString() {
- final Collection<Locale> locVal = Arrays.asList(
- Locale.CANADA,
- Locale.CANADA_FRENCH,
- Locale.CHINA,
- // Locale.CHINESE,
- // Locale.ENGLISH,
- Locale.FRANCE,
- // Locale.FRENCH,
- // Locale.GERMAN,
- Locale.GERMANY,
- // Locale.ITALIAN,
- Locale.ITALY, Locale.JAPAN,
- // Locale.JAPANESE,
- Locale.KOREA,
- // Locale.KOREAN,
- Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
- Locale.UK, Locale.US);
- final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
- "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
-
- Iterator<String> dat = locDat.iterator();
- for (Locale l : locVal) {
- String d = dat.next().trim();
- assertEquals("For locale " + l + " Currency.toString method returns wrong value",
- Currency.getInstance(l).toString(), d);
- }
- }
-
- protected void setUp() {
- Locale.setDefault(defaultLocale);
- }
-
- protected void tearDown() {
- }
-
- /**
- * Helper method to display Currency info
- *
- * @param c
- */
- private void printCurrency(Currency c) {
- System.out.println();
- System.out.println(c.getCurrencyCode());
- System.out.println(c.getSymbol());
- System.out.println(c.getDefaultFractionDigits());
- }
-
- /**
- * helper method to display Locale info
- */
- private static void printLocale(Locale loc) {
- System.out.println();
- System.out.println(loc.getDisplayName());
- System.out.println(loc.getCountry());
- System.out.println(loc.getLanguage());
- System.out.println(loc.getDisplayCountry());
- System.out.println(loc.getDisplayLanguage());
- System.out.println(loc.getDisplayName());
- System.out.println(loc.getISO3Country());
- System.out.println(loc.getISO3Language());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/DateTest.java b/luni/src/test/java/tests/api/java/util/DateTest.java
deleted file mode 100644
index 6100527..0000000
--- a/luni/src/test/java/tests/api/java/util/DateTest.java
+++ /dev/null
@@ -1,514 +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 tests.api.java.util;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.TimeZone;
-
-public class DateTest extends junit.framework.TestCase {
-
- /**
- * java.util.Date#Date()
- */
- public void test_Constructor() {
- // Test for method java.util.Date()
- GregorianCalendar gc = new GregorianCalendar(1998, Calendar.OCTOBER,
- 13, 19, 9);
- long oldTime = gc.getTime().getTime();
- long now = new Date().getTime();
- assertTrue("Created incorrect date: " + oldTime + " now: " + now,
- oldTime < now);
- }
-
- /**
- * java.util.Date#Date(int, int, int)
- */
- public void test_ConstructorIII() {
- // Test for method java.util.Date(int, int, int)
- Date d1 = new Date(70, 0, 1); // the epoch + local time
-
- // the epoch + local time
- Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000);
-
- assertTrue("Created incorrect date", d1.equals(d2));
-
- Date date = new Date(99, 5, 22);
- Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 22);
- assertTrue("Wrong time zone", date.equals(cal.getTime()));
- }
-
- /**
- * java.util.Date#Date(int, int, int, int, int)
- */
- public void test_ConstructorIIIII() {
- // Test for method java.util.Date(int, int, int, int, int)
-
- // the epoch + local time + (1 hour and 1 minute)
- Date d1 = new Date(70, 0, 1, 1, 1);
-
- // the epoch + local time + (1 hour and 1 minute)
- Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60
- * 1000 + 60 * 1000);
-
- assertTrue("Created incorrect date", d1.equals(d2));
- }
-
- /**
- * java.util.Date#Date(int, int, int, int, int, int)
- */
- public void test_ConstructorIIIIII() {
- // Test for method java.util.Date(int, int, int, int, int, int)
-
- // the epoch + local time + (1 hour and 1 minute + 1 second)
- Date d1 = new Date(70, 0, 1, 1, 1, 1);
-
- // the epoch + local time + (1 hour and 1 minute + 1 second)
- Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60
- * 1000 + 60 * 1000 + 1000);
-
- assertTrue("Created incorrect date", d1.equals(d2));
- }
-
- /**
- * java.util.Date#Date(long)
- */
- public void test_ConstructorJ() {
- // Test for method java.util.Date(long)
- assertTrue("Used to test", true);
- }
-
- /**
- * java.util.Date#Date(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.Date(java.lang.String)
- Date d1 = new Date("January 1, 1970, 00:00:00 GMT"); // the epoch
- Date d2 = new Date(0); // the epoch
- assertTrue("Created incorrect date", d1.equals(d2));
-
- try {
- // Regression for HARMONY-238
- new Date(null);
- fail("Constructor Date((String)null) should "
- + "throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * java.util.Date#after(java.util.Date)
- */
- public void test_afterLjava_util_Date() {
- // Test for method boolean java.util.Date.after(java.util.Date)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertTrue("Older was returned as newer", d2.after(d1));
- assertTrue("Newer was returned as older", !d1.after(d2));
-
- try {
- d1.after(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Date#before(java.util.Date)
- */
- public void test_beforeLjava_util_Date() {
- // Test for method boolean java.util.Date.before(java.util.Date)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertTrue("Older was returned as newer", !d2.before(d1));
- assertTrue("Newer was returned as older", d1.before(d2));
-
- try {
- d1.before(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Date#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.Date.clone()
- Date d1 = new Date(100000);
- Date d2 = (Date) d1.clone();
- assertTrue(
- "Cloning date results in same reference--new date is equivalent",
- d1 != d2);
- assertTrue("Cloning date results unequal date", d1.equals(d2));
- }
-
- /**
- * java.util.Date#compareTo(java.util.Date)
- */
- public void test_compareToLjava_util_Date() {
- // Test for method int java.util.Date.compareTo(java.util.Date)
- final int someNumber = 10000;
- Date d1 = new Date(someNumber);
- Date d2 = new Date(someNumber);
- Date d3 = new Date(someNumber + 1);
- Date d4 = new Date(someNumber - 1);
- assertEquals("Comparing a date to itself did not answer zero", 0, d1
- .compareTo(d1));
- assertEquals("Comparing equal dates did not answer zero", 0, d1
- .compareTo(d2));
- assertEquals("date1.compareTo(date2), where date1 > date2, did not result in 1",
- 1, d1.compareTo(d4));
- assertEquals("date1.compareTo(date2), where date1 < date2, did not result in -1",
- -1, d1.compareTo(d3));
-
- try {
- d1.compareTo(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Date#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Date.equals(java.lang.Object)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- Date d3 = new Date(1900000);
- assertTrue("Equality test failed", d2.equals(d3));
- assertTrue("Equality test failed", !d1.equals(d2));
- }
-
- /**
- * java.util.Date#getDate()
- */
- public void test_getDate() {
- // Test for method int java.util.Date.getDate()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect date", 13, d.getDate());
- }
-
- /**
- * java.util.Date#getDay()
- */
- public void test_getDay() {
- // Test for method int java.util.Date.getDay()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect day", 2, d.getDay());
- }
-
- /**
- * java.util.Date#getHours()
- */
- public void test_getHours() {
- // Test for method int java.util.Date.getHours()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect hours", 19, d.getHours());
- }
-
- /**
- * java.util.Date#getMinutes()
- */
- public void test_getMinutes() {
- // Test for method int java.util.Date.getMinutes()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect minutes", 9, d.getMinutes());
- }
-
- /**
- * java.util.Date#getMonth()
- */
- public void test_getMonth() {
- // Test for method int java.util.Date.getMonth()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect month", 9, d.getMonth());
- }
-
- /**
- * java.util.Date#getSeconds()
- */
- public void test_getSeconds() {
- // Test for method int java.util.Date.getSeconds()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect seconds", 0, d.getSeconds());
- }
-
- /**
- * java.util.Date#getTime()
- */
- public void test_getTime() {
- // Test for method long java.util.Date.getTime()
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertEquals("Returned incorrect time", 1900000, d2.getTime());
- assertEquals("Returned incorrect time", 0, d1.getTime());
- }
-
- /**
- * java.util.Date#getTimezoneOffset()
- */
- public void test_getTimezoneOffset() {
- // Test for method int java.util.Date.getTimezoneOffset()
- assertTrue("Used to test", true);
- int offset = new Date(96, 1, 14).getTimezoneOffset();
- assertTrue(offset > -720 && offset < 720);
- }
-
- /**
- * java.util.Date#getYear()
- */
- public void test_getYear() {
- // Test for method int java.util.Date.getYear()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect year", 98, d.getYear());
- }
-
- /**
- * java.util.Date#hashCode()
- */
- public void test_hashCode() {
- // Test for method int java.util.Date.hashCode()
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertEquals("Returned incorrect hash", 1900000, d2.hashCode());
- assertEquals("Returned incorrect hash", 0, d1.hashCode());
- }
-
- /**
- * java.util.Date#parse(java.lang.String)
- */
- public void test_parseLjava_lang_String() {
- // Test for method long java.util.Date.parse(java.lang.String)
- Date d = new Date(Date.parse("13 October 1998"));
- GregorianCalendar cal = new GregorianCalendar();
- cal.setTime(d);
- assertEquals("Parsed incorrect month", 9, cal.get(Calendar.MONTH));
- assertEquals("Parsed incorrect year", 1998, cal.get(Calendar.YEAR));
- assertEquals("Parsed incorrect date", 13, cal.get(Calendar.DATE));
-
- d = new Date(Date.parse("Jan-12 1999"));
- assertTrue("Wrong parsed date 1", d.equals(new GregorianCalendar(1999,
- 0, 12).getTime()));
- d = new Date(Date.parse("Jan12-1999"));
- assertTrue("Wrong parsed date 2", d.equals(new GregorianCalendar(1999,
- 0, 12).getTime()));
- d = new Date(Date.parse("Jan12 69-1"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.clear();
- cal.set(1969, Calendar.JANUARY, 12, 1, 0);
- assertTrue("Wrong parsed date 3", d.equals(cal.getTime()));
- d = new Date(Date.parse("6:45:13 3/2/1200 MST"));
- cal.setTimeZone(TimeZone.getTimeZone("MST"));
- cal.clear();
- cal.set(1200, 2, 2, 6, 45, 13);
- assertTrue("Wrong parsed date 4", d.equals(cal.getTime()));
- d = new Date(Date.parse("Mon, 22 Nov 1999 12:52:06 GMT"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.clear();
- cal.set(1999, Calendar.NOVEMBER, 22, 12, 52, 06);
- assertTrue("Wrong parsed date 5", d.equals(cal.getTime()));
-
- try {
- // Regression for HARMONY-259
- Date.parse(null);
- fail("Date.parse(null) should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * java.util.Date#setDate(int)
- */
- public void test_setDateI() {
- // Test for method void java.util.Date.setDate(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setDate(23);
- assertEquals("Set incorrect date", 23, d.getDate());
- }
-
- /**
- * java.util.Date#setHours(int)
- */
- public void test_setHoursI() {
- // Test for method void java.util.Date.setHours(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setHours(23);
- assertEquals("Set incorrect hours", 23, d.getHours());
- }
-
- /**
- * java.util.Date#setMinutes(int)
- */
- public void test_setMinutesI() {
- // Test for method void java.util.Date.setMinutes(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setMinutes(45);
- assertEquals("Set incorrect mins", 45, d.getMinutes());
- }
-
- /**
- * java.util.Date#setMonth(int)
- */
- public void test_setMonthI() {
- // Test for method void java.util.Date.setMonth(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setMonth(0);
- assertEquals("Set incorrect month", 0, d.getMonth());
- }
-
- /**
- * java.util.Date#setSeconds(int)
- */
- public void test_setSecondsI() {
- // Test for method void java.util.Date.setSeconds(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setSeconds(13);
- assertEquals("Set incorrect seconds", 13, d.getSeconds());
- }
-
- /**
- * java.util.Date#setTime(long)
- */
- public void test_setTimeJ() {
- // Test for method void java.util.Date.setTime(long)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- d1.setTime(900);
- d2.setTime(890000);
- assertEquals("Returned incorrect time", 890000, d2.getTime());
- assertEquals("Returned incorrect time", 900, d1.getTime());
- }
-
- /**
- * java.util.Date#setYear(int)
- */
- public void test_setYearI() {
- // Test for method void java.util.Date.setYear(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setYear(8);
- assertEquals("Set incorrect year", 8, d.getYear());
- }
-
- /**
- * java.util.Date#toGMTString()
- */
- public void test_toGMTString() {
- // Test for method java.lang.String java.util.Date.toGMTString()
- assertEquals("Did not convert epoch to GMT string correctly", "1 Jan 1970 00:00:00 GMT", new Date(0)
- .toGMTString());
- assertEquals("Did not convert epoch + 1yr to GMT string correctly",
- "1 Jan 1971 00:00:00 GMT", new Date((long) 365 * 24 * 60 * 60 * 1000).toGMTString()
- );
- }
-
- /**
- * java.util.Date#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.util.Date.toString()
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.DATE, 1);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.YEAR, 1970);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- Date d = cal.getTime();
- String result = d.toString();
- assertTrue("Incorrect result: " + d, result
- .startsWith("Thu Jan 01 00:00:00")
- && result.endsWith("1970"));
-
- TimeZone tz = TimeZone.getDefault();
- TimeZone.setDefault(TimeZone.getTimeZone("GMT-5"));
- try {
- Date d1 = new Date(0);
- assertTrue("Returned incorrect string: " + d1, d1.toString()
- .equals("Wed Dec 31 19:00:00 GMT-05:00 1969"));
- } finally {
- TimeZone.setDefault(tz);
- }
- }
-
- /**
- * java.util.Date#UTC(int, int, int, int, int, int)
- */
- public void test_UTCIIIIII() {
- // Test for method long java.util.Date.UTC(int, int, int, int, int, int)
- assertTrue("Returned incorrect UTC value for epoch", Date.UTC(70, 0, 1,
- 0, 0, 0) == (long) 0);
- assertTrue("Returned incorrect UTC value for epoch +1yr", Date.UTC(71,
- 0, 1, 0, 0, 0) == (long) 365 * 24 * 60 * 60 * 1000);
- }
- /**
- * java.util.Date#toLocaleString() Test for method java.lang.String
- * java.util.Date.toGMTString()
- */
- public void test_toLocaleString() {
- Locale loc = Locale.getDefault();
- Locale.setDefault(Locale.US);
- TimeZone tz = TimeZone.getDefault();
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
- try {
- assertEquals("Did not convert epoch to GMT string correctly", "Jan 1, 1970 12:00:00 AM",
- new Date(0).toLocaleString());
- assertEquals("Did not convert epoch + 1yr to GMT string correctly",
- "Jan 1, 1971 12:00:00 AM", new Date((long)365 * 24 * 60 * 60 * 1000)
- .toLocaleString());
- } finally {
- Locale.setDefault(loc);
- TimeZone.setDefault(tz);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java b/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java
deleted file mode 100644
index 31ee1e2..0000000
--- a/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.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 tests.api.java.util;
-
-import java.util.EmptyStackException;
-import java.util.Stack;
-
-public class EmptyStackExceptionTest extends junit.framework.TestCase {
-
- Object[] objArray = new Object[10];
- Stack s;
-
- /**
- * java.util.EmptyStackException#EmptyStackException()
- */
- public void test_Constructor() {
- // Test for method java.util.EmptyStackException()
- try {
- for (int counter = 0; counter < objArray.length + 1; counter++)
- s.pop();
- } catch (EmptyStackException e) {
- return;
- }
- fail("Expected EmptyStackException not thrown");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- for (int counter = 0; counter < objArray.length; counter++) {
- objArray[counter] = new Integer(counter);
- }
-
- s = new Stack();
- for (int counter = 0; counter < objArray.length; counter++) {
- s.push(objArray[counter]);
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- objArray = null;
- s = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EnumMapTest.java b/luni/src/test/java/tests/api/java/util/EnumMapTest.java
deleted file mode 100644
index 05826d1..0000000
--- a/luni/src/test/java/tests/api/java/util/EnumMapTest.java
+++ /dev/null
@@ -1,1175 +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 tests.api.java.util;
-
-import dalvik.annotation.AndroidOnly;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import junit.framework.TestCase;
-
-public class EnumMapTest extends TestCase {
- enum Size {
- Small, Middle, Big {};
- }
-
- enum Color {
- Red, Green, Blue {};
- }
-
- enum Empty {
- //Empty
- }
-
- private static class MockEntry<K, V> implements Map.Entry<K, V> {
- private K key;
-
- private V value;
-
- public MockEntry(K key, V value) {
- this.key = key;
- this.value = value;
- }
-
- @Override
- public int hashCode() {
- return (key == null ? 0 : key.hashCode())
- ^ (value == null ? 0 : value.hashCode());
- }
-
- public K getKey() {
- return key;
- }
-
- public V getValue() {
- return value;
- }
-
- public V setValue(V object) {
- V oldValue = value;
- value = object;
- return oldValue;
- }
- }
-
- /**
- * java.util.EnumMap#EnumMap(Class)
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_ConstructorLjava_lang_Class() {
- try {
- new EnumMap((Class) null);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
-
- try {
- new EnumMap(Size.Big.getClass());
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- new EnumMap(Integer.class);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- assertNull("Return non-null for non mapped key", enumColorMap.put(
- Color.Green, 2));
- assertEquals("Get returned incorrect value for given key", 2,
- enumColorMap.get(Color.Green));
-
- EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class);
- try {
- enumEmptyMap.put(Color.Red, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
-
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertNull("Return non-null for non mapped key", enumSizeMap.put(
- Size.Big, 2));
- assertEquals("Get returned incorrect value for given key", 2,
- enumSizeMap.get(Size.Big));
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
-
- enumSizeMap = new EnumMap(Size.Middle.getClass());
- assertNull("Return non-null for non mapped key", enumSizeMap.put(
- Size.Small, 1));
- assertEquals("Get returned incorrect value for given key", 1,
- enumSizeMap.get(Size.Small));
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * java.util.EnumMap#EnumMap(EnumMap)
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_ConstructorLjava_util_EnumMap() {
- EnumMap enumMap;
- EnumMap enumColorMap = null;
- try {
- enumMap = new EnumMap(enumColorMap);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- Double double1 = new Double(1);
- enumColorMap.put(Color.Green, 2);
- enumColorMap.put(Color.Blue, double1);
-
- enumMap = new EnumMap(enumColorMap);
- assertEquals("Constructor fails", 2, enumMap.get(Color.Green));
- assertSame("Constructor fails", double1, enumMap.get(Color.Blue));
- assertNull("Constructor fails", enumMap.get(Color.Red));
- enumMap.put(Color.Red, 1);
- assertEquals("Wrong value", 1, enumMap.get(Color.Red));
-
- try {
- enumMap.put(Size.Middle, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * java.util.EnumMap#EnumMap(Map)
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_ConstructorLjava_util_Map() {
- EnumMap enumMap;
- Map enumColorMap = null;
- try {
- enumMap = new EnumMap(enumColorMap);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumMap = new EnumMap(enumColorMap);
- enumColorMap.put(Color.Blue, 3);
- enumMap = new EnumMap(enumColorMap);
-
- HashMap hashColorMap = null;
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- hashColorMap.put(Color.Green, 2);
- enumMap = new EnumMap(hashColorMap);
- assertEquals("Constructor fails", 2, enumMap.get(Color.Green));
- assertNull("Constructor fails", enumMap.get(Color.Red));
- enumMap.put(Color.Red, 1);
- assertEquals("Wrong value", 1, enumMap.get(Color.Red));
- hashColorMap.put(Size.Big, 3);
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- hashColorMap.put(new Integer(1), 1);
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * java.util.EnumMap#clear()
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_clear() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Small, 1);
- enumSizeMap.clear();
- assertNull("Failed to clear all elements", enumSizeMap.get(Size.Small));
- }
-
- /**
- * java.util.EnumMap#containsKey(Object)
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_containsKeyLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertFalse("Returned true for uncontained key", enumSizeMap
- .containsKey(Size.Small));
- enumSizeMap.put(Size.Small, 1);
- assertTrue("Returned false for contained key", enumSizeMap
- .containsKey(Size.Small));
-
- enumSizeMap.put(Size.Big, null);
- assertTrue("Returned false for contained key", enumSizeMap
- .containsKey(Size.Big));
-
- assertFalse("Returned true for uncontained key", enumSizeMap
- .containsKey(Color.Red));
- assertFalse("Returned true for uncontained key", enumSizeMap
- .containsKey(new Integer("3")));
- assertFalse("Returned true for uncontained key", enumSizeMap
- .containsKey(null));
- }
-
- /**
- * java.util.EnumMap#clone()
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_clone() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- Integer integer = new Integer("3");
- enumSizeMap.put(Size.Small, integer);
- EnumMap enumSizeMapClone = enumSizeMap.clone();
- assertNotSame("Should not be same", enumSizeMap, enumSizeMapClone);
- assertEquals("Clone answered unequal EnumMap", enumSizeMap,
- enumSizeMapClone);
-
- assertSame("Should be same", enumSizeMap.get(Size.Small),
- enumSizeMapClone.get(Size.Small));
- assertSame("Clone is not shallow clone", integer, enumSizeMapClone
- .get(Size.Small));
- enumSizeMap.remove(Size.Small);
- assertSame("Clone is not shallow clone", integer, enumSizeMapClone
- .get(Size.Small));
- }
-
- /**
- * java.util.EnumMap#containsValue(Object)
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_containsValueLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- Double double1 = new Double(3);
- Double double2 = new Double(3);
-
- assertFalse("Returned true for uncontained value", enumSizeMap
- .containsValue(double1));
- enumSizeMap.put(Size.Middle, 2);
- enumSizeMap.put(Size.Small, double1);
- assertTrue("Returned false for contained value", enumSizeMap
- .containsValue(double1));
- assertTrue("Returned false for contained value", enumSizeMap
- .containsValue(double2));
- assertTrue("Returned false for contained value", enumSizeMap
- .containsValue(2));
- assertFalse("Returned true for uncontained value", enumSizeMap
- .containsValue(1));
-
- assertFalse("Returned true for uncontained value", enumSizeMap
- .containsValue(null));
- enumSizeMap.put(Size.Big, null);
- assertTrue("Returned false for contained value", enumSizeMap
- .containsValue(null));
- }
-
- /**
- * java.util.EnumMap#entrySet()
- */
- @AndroidOnly("Map.Entry is indirectly modified on RI when Iterator.next() is invoked")
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_entrySet() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- MockEntry mockEntry = new MockEntry(Size.Middle, 1);
- Set set = enumSizeMap.entrySet();
-
- Set set1 = enumSizeMap.entrySet();
- assertSame("Should be same", set1, set);
- try {
- set.add(mockEntry);
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- assertTrue("Returned false for contained object", set
- .contains(mockEntry));
- mockEntry = new MockEntry(Size.Middle, null);
- assertFalse("Returned true for uncontained object", set
- .contains(mockEntry));
- assertFalse("Returned true for uncontained object", set
- .contains(Size.Small));
- mockEntry = new MockEntry(new Integer(1), 1);
- assertFalse("Returned true for uncontained object", set
- .contains(mockEntry));
- assertFalse("Returned true for uncontained object", set
- .contains(new Integer(1)));
-
- mockEntry = new MockEntry(Size.Big, null);
- assertTrue("Returned false for contained object", set
- .contains(mockEntry));
- assertTrue("Returned false when the object can be removed", set
- .remove(mockEntry));
- assertFalse("Returned true for uncontained object", set
- .contains(mockEntry));
- assertFalse("Returned true when the object can not be removed", set
- .remove(mockEntry));
- mockEntry = new MockEntry(new Integer(1), 1);
- assertFalse("Returned true when the object can not be removed", set
- .remove(mockEntry));
- assertFalse("Returned true when the object can not be removed", set
- .remove(new Integer(1)));
-
- // The set is backed by the map so changes to one are reflected by the
- // other.
- enumSizeMap.put(Size.Big, 3);
- mockEntry = new MockEntry(Size.Big, 3);
- assertTrue("Returned false for contained object", set
- .contains(mockEntry));
- enumSizeMap.remove(Size.Big);
- assertFalse("Returned true for uncontained object", set
- .contains(mockEntry));
-
- assertEquals("Wrong size", 1, set.size());
- set.clear();
- assertEquals("Wrong size", 0, set.size());
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- Collection c = new ArrayList();
- c.add(new MockEntry(Size.Middle, 1));
- assertTrue("Return wrong value", set.containsAll(c));
- assertTrue("Remove does not success", set.removeAll(c));
-
- enumSizeMap.put(Size.Middle, 1);
- c.add(new MockEntry(Size.Big, 3));
- assertTrue("Remove does not success", set.removeAll(c));
- assertFalse("Should return false", set.removeAll(c));
- assertEquals("Wrong size", 1, set.size());
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- c = new ArrayList();
- c.add(new MockEntry(Size.Middle, 1));
- c.add(new MockEntry(Size.Big, 3));
-
- assertTrue("Retain does not success", set.retainAll(c));
- assertEquals("Wrong size", 1, set.size());
- assertFalse("Should return false", set.retainAll(c));
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
-
- set = enumSizeMap.entrySet();
- Object[] array = set.toArray();
- assertEquals("Wrong length", 2, array.length);
- Map.Entry entry = (Map.Entry) array[0];
- assertEquals("Wrong key", Size.Middle, entry.getKey());
- assertEquals("Wrong value", 1, entry.getValue());
-
- Object[] array1 = new Object[10];
- array1 = set.toArray();
- assertEquals("Wrong length", 2, array1.length);
- entry = (Map.Entry) array[0];
- assertEquals("Wrong key", Size.Middle, entry.getKey());
- assertEquals("Wrong value", 1, entry.getValue());
-
- array1 = new Object[10];
- array1 = set.toArray(array1);
- assertEquals("Wrong length", 10, array1.length);
- entry = (Map.Entry) array[1];
- assertEquals("Wrong key", Size.Big, entry.getKey());
- assertNull("Should be null", array1[2]);
-
- set = enumSizeMap.entrySet();
- Integer integer = new Integer("1");
- assertFalse("Returned true when the object can not be removed", set
- .remove(integer));
- assertTrue("Returned false when the object can be removed", set
- .remove(entry));
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- Iterator iter = set.iterator();
- entry = (Map.Entry) iter.next();
- assertTrue("Returned false for contained object", set.contains(entry));
- mockEntry = new MockEntry(Size.Middle, 2);
- assertFalse("Returned true for uncontained object", set
- .contains(mockEntry));
- mockEntry = new MockEntry(new Integer(2), 2);
- assertFalse("Returned true for uncontained object", set
- .contains(mockEntry));
- entry = (Map.Entry) iter.next();
- assertTrue("Returned false for contained object", set.contains(entry));
-
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.remove(Size.Big);
- mockEntry = new MockEntry(Size.Big, null);
- assertEquals("Wrong size", 1, set.size());
- assertFalse("Returned true for uncontained object", set.contains(mockEntry));
- enumSizeMap.put(Size.Big, 2);
- mockEntry = new MockEntry(Size.Big, 2);
- assertTrue("Returned false for contained object", set
- .contains(mockEntry));
-
- iter.remove();
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- try {
- entry.setValue(2);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- try {
- set.contains(entry);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- iter = set.iterator();
- entry = (Map.Entry) iter.next();
- assertEquals("Wrong key", Size.Middle, entry.getKey());
-
- assertTrue("Returned false for contained object", set.contains(entry));
- enumSizeMap.put(Size.Middle, 3);
- assertTrue("Returned false for contained object", set.contains(entry));
- entry.setValue(2);
- assertTrue("Returned false for contained object", set.contains(entry));
- assertFalse("Returned true for uncontained object", set
- .remove(new Integer(1)));
-
- iter.next();
- assertEquals("Wrong key", Size.Middle, entry.getKey());
- set.clear();
- assertEquals("Wrong size", 0, set.size());
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- iter = set.iterator();
- mockEntry = new MockEntry(Size.Middle, 1);
-
- assertFalse("Wrong result", entry.equals(mockEntry));
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- entry = (Map.Entry) iter.next();
- assertEquals("Wrong key", Size.Middle, entry.getKey());
- assertTrue("Should return true", entry.equals(mockEntry));
- assertEquals("Should be equal", mockEntry.hashCode(), entry.hashCode());
- mockEntry = new MockEntry(Size.Big, 1);
- assertFalse("Wrong result", entry.equals(mockEntry));
-
- entry = (Map.Entry) iter.next();
- assertFalse("Wrong result", entry.equals(mockEntry));
- assertEquals("Wrong key", Size.Big, entry.getKey());
- iter.remove();
- assertFalse("Wrong result", entry.equals(mockEntry));
- assertEquals("Wrong size", 1, set.size());
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- try {
- iter.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * java.util.EnumMap#equals(Object)
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_equalsLjava_lang_Object() {
- EnumMap enumMap = new EnumMap(Size.class);
- enumMap.put(Size.Small, 1);
-
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap
- .equals(enumMap));
- enumSizeMap.put(Size.Small, 1);
- assertTrue("Returned false for equal EnumMap", enumSizeMap
- .equals(enumMap));
- enumSizeMap.put(Size.Big, null);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap
- .equals(enumMap));
-
- enumMap.put(Size.Middle, null);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap
- .equals(enumMap));
- enumMap.remove(Size.Middle);
- enumMap.put(Size.Big, 3);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap
- .equals(enumMap));
- enumMap.put(Size.Big, null);
- assertTrue("Returned false for equal EnumMap", enumSizeMap
- .equals(enumMap));
-
- HashMap hashMap = new HashMap();
- hashMap.put(Size.Small, 1);
- assertFalse("Returned true for unequal EnumMap", hashMap
- .equals(enumMap));
- hashMap.put(Size.Big, null);
- assertTrue("Returned false for equal EnumMap", enumMap.equals(hashMap));
-
- assertFalse("Should return false", enumSizeMap
- .equals(new Integer(1)));
- }
-
- /**
- * java.util.EnumMap#keySet()
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_keySet() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 2);
- enumSizeMap.put(Size.Big, null);
- Set set = enumSizeMap.keySet();
-
- Set set1 = enumSizeMap.keySet();
- assertSame("Should be same", set1, set);
- try {
- set.add(Size.Big);
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- assertTrue("Returned false for contained object", set
- .contains(Size.Middle));
- assertTrue("Returned false for contained object", set
- .contains(Size.Big));
- assertFalse("Returned true for uncontained object", set
- .contains(Size.Small));
- assertFalse("Returned true for uncontained object", set
- .contains(new Integer(1)));
- assertTrue("Returned false when the object can be removed", set
- .remove(Size.Big));
- assertFalse("Returned true for uncontained object", set
- .contains(Size.Big));
- assertFalse("Returned true when the object can not be removed", set
- .remove(Size.Big));
- assertFalse("Returned true when the object can not be removed", set
- .remove(new Integer(1)));
-
- // The set is backed by the map so changes to one are reflected by the
- // other.
- enumSizeMap.put(Size.Big, 3);
- assertTrue("Returned false for contained object", set
- .contains(Size.Big));
- enumSizeMap.remove(Size.Big);
- assertFalse("Returned true for uncontained object", set
- .contains(Size.Big));
-
- assertEquals("Wrong size", 1, set.size());
- set.clear();
- assertEquals("Wrong size", 0, set.size());
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
- Collection c = new ArrayList();
- c.add(Size.Big);
- assertTrue("Should return true", set.containsAll(c));
- c.add(Size.Small);
- assertFalse("Should return false", set.containsAll(c));
- assertTrue("Should return true", set.removeAll(c));
- assertEquals("Wrong size", 1, set.size());
- assertFalse("Should return false", set.removeAll(c));
- assertEquals("Wrong size", 1, set.size());
- try {
- set.addAll(c);
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- enumSizeMap.put(Size.Big, null);
- assertEquals("Wrong size", 2, set.size());
- assertTrue("Should return true", set.retainAll(c));
- assertEquals("Wrong size", 1, set.size());
- assertFalse("Should return false", set.retainAll(c));
- assertEquals(1, set.size());
- Object[] array = set.toArray();
- assertEquals("Wrong length", 1, array.length);
- assertEquals("Wrong key", Size.Big, array[0]);
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
- c = new ArrayList();
- c.add(Color.Blue);
- assertFalse("Should return false", set.remove(c));
- assertEquals("Wrong size", 2, set.size());
- assertTrue("Should return true", set.retainAll(c));
- assertEquals("Wrong size", 0, set.size());
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
-
- Iterator iter = set.iterator();
- Enum enumKey = (Enum) iter.next();
- assertTrue("Returned false for contained object", set.contains(enumKey));
- enumKey = (Enum) iter.next();
- assertTrue("Returned false for contained object", set.contains(enumKey));
-
- enumSizeMap.remove(Size.Big);
- assertFalse("Returned true for uncontained object", set
- .contains(enumKey));
- iter.remove();
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- assertFalse("Returned true for uncontained object", set
- .contains(enumKey));
-
- iter = set.iterator();
- enumKey = (Enum) iter.next();
- assertTrue("Returned false for contained object", set.contains(enumKey));
- enumSizeMap.put(Size.Middle, 3);
- assertTrue("Returned false for contained object", set.contains(enumKey));
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
- iter = set.iterator();
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- enumKey = (Enum) iter.next();
- assertEquals("Wrong key", Size.Middle, enumKey);
- assertSame("Wrong key", Size.Middle, enumKey);
- assertFalse("Returned true for unequal object", iter.equals(enumKey));
- iter.remove();
- assertFalse("Returned true for uncontained object", set
- .contains(enumKey));
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
-
- assertEquals("Wrong size", 1, set.size());
- enumKey = (Enum) iter.next();
- assertEquals("Wrong key", Size.Big, enumKey);
- iter.remove();
- try {
- iter.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * java.util.EnumMap#get(Object)
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_getLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertNull("Get returned non-null for non mapped key", enumSizeMap
- .get(Size.Big));
- enumSizeMap.put(Size.Big, 1);
- assertEquals("Get returned incorrect value for given key", 1,
- enumSizeMap.get(Size.Big));
-
- assertNull("Get returned non-null for non mapped key", enumSizeMap
- .get(Size.Small));
- assertNull("Get returned non-null for non existent key", enumSizeMap
- .get(Color.Red));
- assertNull("Get returned non-null for non existent key", enumSizeMap
- .get(new Integer(1)));
- assertNull("Get returned non-null for non existent key", enumSizeMap
- .get(null));
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- assertNull("Get returned non-null for non mapped key", enumColorMap
- .get(Color.Green));
- enumColorMap.put(Color.Green, 2);
- assertEquals("Get returned incorrect value for given key", 2,
- enumColorMap.get(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap
- .get(Color.Blue));
-
- enumColorMap.put(Color.Green, new Double(4));
- assertEquals("Get returned incorrect value for given key",
- new Double(4), enumColorMap.get(Color.Green));
- enumColorMap.put(Color.Green, new Integer("3"));
- assertEquals("Get returned incorrect value for given key", new Integer(
- "3"), enumColorMap.get(Color.Green));
- enumColorMap.put(Color.Green, null);
- assertNull("Can not handle null value", enumColorMap.get(Color.Green));
- Float f = new Float("3.4");
- enumColorMap.put(Color.Green, f);
- assertSame("Get returned incorrect value for given key", f,
- enumColorMap.get(Color.Green));
- }
-
- /**
- * java.util.EnumMap#put(Object,Object)
- */
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- assertNull("Return non-null for non mapped key", enumSizeMap.put(
- Size.Small, 1));
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- try {
- enumColorMap.put(Size.Big, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- try {
- enumColorMap.put(null, 2);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- assertNull("Return non-null for non mapped key", enumColorMap.put(
- Color.Green, 2));
- assertEquals("Return wrong value", 2, enumColorMap.put(Color.Green,
- new Double(4)));
- assertEquals("Return wrong value", new Double(4), enumColorMap.put(
- Color.Green, new Integer("3")));
- assertEquals("Return wrong value", new Integer("3"), enumColorMap.put(
- Color.Green, null));
- Float f = new Float("3.4");
- assertNull("Return non-null for non mapped key", enumColorMap.put(
- Color.Green, f));
- assertNull("Return non-null for non mapped key", enumColorMap.put(
- Color.Blue, 2));
- assertEquals("Return wrong value", 2, enumColorMap.put(Color.Blue,
- new Double(4)));
- }
-
- /**
- * java.util.EnumMap#putAll(Map)
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_putAllLjava_util_Map() {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Green, 2);
-
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumColorMap.putAll(enumSizeMap);
-
- enumSizeMap.put(Size.Big, 1);
- try {
- enumColorMap.putAll(enumSizeMap);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
-
- EnumMap enumColorMap1 = new EnumMap<Color, Double>(Color.class);
- enumColorMap1.put(Color.Blue, 3);
- enumColorMap.putAll(enumColorMap1);
- assertEquals("Get returned incorrect value for given key", 3,
- enumColorMap.get(Color.Blue));
- assertEquals("Wrong Size", 2, enumColorMap.size());
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
-
- HashMap hashColorMap = null;
- try {
- enumColorMap.putAll(hashColorMap);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- enumColorMap.putAll(hashColorMap);
-
- hashColorMap.put(Color.Green, 2);
- enumColorMap.putAll(hashColorMap);
- assertEquals("Get returned incorrect value for given key", 2,
- enumColorMap.get(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap
- .get(Color.Red));
- hashColorMap.put(Color.Red, new Integer(1));
- enumColorMap.putAll(hashColorMap);
- assertEquals("Get returned incorrect value for given key", new Integer(
- 2), enumColorMap.get(Color.Green));
- hashColorMap.put(Size.Big, 3);
- try {
- enumColorMap.putAll(hashColorMap);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- hashColorMap.put(new Integer(1), 1);
- try {
- enumColorMap.putAll(hashColorMap);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * java.util.EnumMap#remove(Object)
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_removeLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertNull("Remove of non-mapped key returned non-null", enumSizeMap
- .remove(Size.Big));
- enumSizeMap.put(Size.Big, 3);
- enumSizeMap.put(Size.Middle, 2);
-
- assertNull("Get returned non-null for non mapped key", enumSizeMap
- .get(Size.Small));
- assertEquals("Remove returned incorrect value", 3, enumSizeMap
- .remove(Size.Big));
- assertNull("Get returned non-null for non mapped key", enumSizeMap
- .get(Size.Big));
- assertNull("Remove of non-mapped key returned non-null", enumSizeMap
- .remove(Size.Big));
- assertNull("Remove of non-existent key returned non-null", enumSizeMap
- .remove(Color.Red));
- assertNull("Remove of non-existent key returned non-null", enumSizeMap
- .remove(new Double(4)));
- assertNull("Remove of non-existent key returned non-null", enumSizeMap
- .remove(null));
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- assertNull("Get returned non-null for non mapped key", enumColorMap
- .get(Color.Green));
- enumColorMap.put(Color.Green, new Double(4));
- assertEquals("Remove returned incorrect value", new Double(4),
- enumColorMap.remove(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap
- .get(Color.Green));
- enumColorMap.put(Color.Green, null);
- assertNull("Can not handle null value", enumColorMap
- .remove(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap
- .get(Color.Green));
- }
-
- /**
- * java.util.EnumMap#size()
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_size() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertEquals("Wrong size", 0, enumSizeMap.size());
- enumSizeMap.put(Size.Small, 1);
- assertEquals("Wrong size", 1, enumSizeMap.size());
- enumSizeMap.put(Size.Small, 0);
- assertEquals("Wrong size", 1, enumSizeMap.size());
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException");
- } catch (ClassCastException e) {
- // Expected
- }
- assertEquals("Wrong size", 1, enumSizeMap.size());
-
- enumSizeMap.put(Size.Middle, null);
- assertEquals("Wrong size", 2, enumSizeMap.size());
- enumSizeMap.remove(Size.Big);
- assertEquals("Wrong size", 2, enumSizeMap.size());
- enumSizeMap.remove(Size.Middle);
- assertEquals("Wrong size", 1, enumSizeMap.size());
- enumSizeMap.remove(Color.Green);
- assertEquals("Wrong size", 1, enumSizeMap.size());
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Green, 2);
- assertEquals("Wrong size", 1, enumColorMap.size());
- enumColorMap.remove(Color.Green);
- assertEquals("Wrong size", 0, enumColorMap.size());
-
- EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class);
- assertEquals("Wrong size", 0, enumEmptyMap.size());
- }
-
- /**
- * java.util.EnumMap#values()
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_values() {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, null);
- Collection collection = enumColorMap.values();
-
- Collection collection1 = enumColorMap.values();
- assertSame("Should be same", collection1, collection);
- try {
- collection.add(new Integer(1));
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- assertTrue("Returned false for contained object", collection
- .contains(1));
- assertTrue("Returned false for contained object", collection
- .contains(null));
- assertFalse("Returned true for uncontained object", collection
- .contains(2));
-
- assertTrue("Returned false when the object can be removed", collection
- .remove(null));
- assertFalse("Returned true for uncontained object", collection
- .contains(null));
- assertFalse("Returned true when the object can not be removed",
- collection.remove(null));
-
- // The set is backed by the map so changes to one are reflected by the
- // other.
- enumColorMap.put(Color.Blue, 3);
- assertTrue("Returned false for contained object", collection
- .contains(3));
- enumColorMap.remove(Color.Blue);
- assertFalse("Returned true for uncontained object", collection
- .contains(3));
-
- assertEquals("Wrong size", 1, collection.size());
- collection.clear();
- assertEquals("Wrong size", 0, collection.size());
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, null);
- collection = enumColorMap.values();
- Collection c = new ArrayList();
- c.add(new Integer(1));
- assertTrue("Should return true", collection.containsAll(c));
- c.add(new Double(3.4));
- assertFalse("Should return false", collection.containsAll(c));
- assertTrue("Should return true", collection.removeAll(c));
- assertEquals("Wrong size", 1, collection.size());
- assertFalse("Should return false", collection.removeAll(c));
- assertEquals("Wrong size", 1, collection.size());
- try {
- collection.addAll(c);
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- enumColorMap.put(Color.Red, 1);
- assertEquals("Wrong size", 2, collection.size());
- assertTrue("Should return true", collection.retainAll(c));
- assertEquals("Wrong size", 1, collection.size());
- assertFalse("Should return false", collection.retainAll(c));
- assertEquals(1, collection.size());
- Object[] array = collection.toArray();
- assertEquals("Wrong length", 1, array.length);
- assertEquals("Wrong key", 1, array[0]);
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, null);
- collection = enumColorMap.values();
-
- assertEquals("Wrong size", 2, collection.size());
- assertFalse("Returned true when the object can not be removed",
- collection.remove(new Integer("10")));
-
- Iterator iter = enumColorMap.values().iterator();
- Object value = iter.next();
- assertTrue("Returned false for contained object", collection
- .contains(value));
- value = iter.next();
- assertTrue("Returned false for contained object", collection
- .contains(value));
-
- enumColorMap.put(Color.Green, 1);
- enumColorMap.remove(Color.Blue);
- assertFalse("Returned true for uncontained object", collection
- .contains(value));
- iter.remove();
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- assertFalse("Returned true for uncontained object", collection
- .contains(value));
-
- iter = enumColorMap.values().iterator();
- value = iter.next();
- assertTrue("Returned false for contained object", collection
- .contains(value));
- enumColorMap.put(Color.Green, 3);
- assertTrue("Returned false for contained object", collection
- .contains(value));
- assertTrue("Returned false for contained object", collection
- .remove(new Integer("1")));
- assertEquals("Wrong size", 1, collection.size());
- collection.clear();
- assertEquals("Wrong size", 0, collection.size());
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- Integer integer1 = new Integer(1);
- enumColorMap.put(Color.Green, integer1);
- enumColorMap.put(Color.Blue, null);
- collection = enumColorMap.values();
- iter = enumColorMap.values().iterator();
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- value = iter.next();
- assertEquals("Wrong value", integer1, value);
- assertSame("Wrong value", integer1, value);
- assertFalse("Returned true for unequal object", iter.equals(value));
- iter.remove();
- assertFalse("Returned true for unequal object", iter.equals(value));
- try {
- iter.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- assertEquals("Wrong size", 1, collection.size());
- value = iter.next();
- assertFalse("Returned true for unequal object", iter.equals(value));
- iter.remove();
- try {
- iter.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * serialization/deserialization.
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void testSerializationSelf() throws Exception {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Blue, 3);
- SerializationTest.verifySelf(enumColorMap);
- }
-
- /**
- * serialization/deserialization compatibility with RI.
- */
- @SuppressWarnings({ "unchecked", "boxing" })
- public void testSerializationCompatibility() throws Exception {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, 3);
- SerializationTest.verifyGolden(this, enumColorMap);
- }
-
- /**
- * Sets up the fixture.
- */
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- /**
- * Tears down the fixture.
- */
- @Override
- protected void tearDown() throws Exception{
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EnumSetTest.java b/luni/src/test/java/tests/api/java/util/EnumSetTest.java
deleted file mode 100644
index 2b33877..0000000
--- a/luni/src/test/java/tests/api/java/util/EnumSetTest.java
+++ /dev/null
@@ -1,2003 +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 tests.api.java.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-public class EnumSetTest extends TestCase {
- static final boolean disableRIBugs = true;
-
- static enum EnumWithInnerClass {
- a, b, c, d, e, f {
- },
- }
-
- enum EnumWithAllInnerClass {
- a {},
- b {},
- }
-
- static enum EnumFoo {
- 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, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll,
- }
-
- static enum EmptyEnum {
- // expected
- }
-
- static enum HugeEnumWithInnerClass {
- 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{}, aa{}, bb{}, cc{}, dd{}, ee{}, ff{}, gg{}, hh{}, ii{}, jj{}, kk{}, ll{}, mm{},
- }
-
- static enum HugeEnum {
- 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, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, mm,
- }
-
- static enum HugeEnumCount {
- NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, NO10, NO11, NO12, NO13, NO14, NO15, NO16, NO17, NO18, NO19, NO20,
- NO21, NO22, NO23, NO24, NO25, NO26, NO27, NO28, NO29, NO30, NO31, NO32, NO33, NO34, NO35, NO36, NO37, NO38, NO39, NO40,
- NO41, NO42, NO43, NO44, NO45, NO46, NO47, NO48, NO49, NO50, NO51, NO52, NO53, NO54, NO55, NO56, NO57, NO58, NO59, NO60,
- NO61, NO62, NO63, NO64, NO65, NO66, NO67, NO68, NO69, NO70, NO71, NO72, NO73, NO74, NO75, NO76, NO77, NO78, NO79, NO80,
- NO81, NO82, NO83, NO84, NO85, NO86, NO87, NO88, NO89, NO90, NO91, NO92, NO93, NO94, NO95, NO96, NO97, NO98, NO99, NO100,
- NO101, NO102, NO103, NO104, NO105, NO106, NO107, NO108, NO109, NO110, NO111, NO112, NO113, NO114, NO115, NO116, NO117, NO118, NO119, NO120,
- NO121, NO122, NO123, NO124, NO125, NO126, NO127, NO128, NO129, NO130,
- }
-
- /**
- * java.util.EnumSet#noneOf(java.lang.Class)
- */
- @SuppressWarnings("unchecked")
- public void test_NoneOf_LClass() {
- try {
- EnumSet.noneOf((Class) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.noneOf(Enum.class);
- fail("Should throw ClassCastException");
- } catch (ClassCastException cce) {
- // expected
- }
-
- Class<EnumWithAllInnerClass> c = (Class<EnumWithAllInnerClass>) EnumWithAllInnerClass.a
- .getClass();
- try {
- EnumSet.noneOf(c);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- EnumSet<EnumWithAllInnerClass> setWithInnerClass = EnumSet
- .noneOf(EnumWithAllInnerClass.class);
- assertNotNull(setWithInnerClass);
-
- // test enum type with more than 64 elements
- Class<HugeEnumWithInnerClass> hc = (Class<HugeEnumWithInnerClass>) HugeEnumWithInnerClass.a
- .getClass();
- try {
- EnumSet.noneOf(hc);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- EnumSet<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- assertNotNull(hugeSetWithInnerClass);
- }
-
- /**
- * java.util.HugeEnumSet#iterator()
- */
- public void test_iterator_HugeEnumSet() {
- EnumSet<HugeEnumCount> set;
- Object[] array;
-
- // Test HugeEnumSet with 65 elements
- // which is more than the bits of Long
- set = EnumSet.range(HugeEnumCount.NO1, HugeEnumCount.NO65);
- array = set.toArray();
- for (HugeEnumCount count : set) {
- assertEquals(count, (HugeEnumCount) array[count.ordinal()]);
- }
-
- // Test HugeEnumSet with 130 elements
- // which is more than twice of the bits of Long
- set = EnumSet.range(HugeEnumCount.NO1, HugeEnumCount.NO130);
- array = set.toArray();
- for (HugeEnumCount count : set) {
- assertEquals(count, (HugeEnumCount) array[count.ordinal()]);
- }
- }
-
- public void testRemoveIteratorRemoveFromHugeEnumSet() {
- EnumSet<HugeEnumCount> set = EnumSet.noneOf(HugeEnumCount.class);
- set.add(HugeEnumCount.NO64);
- set.add(HugeEnumCount.NO65);
- set.add(HugeEnumCount.NO128);
- Iterator<HugeEnumCount> iterator = set.iterator();
- assertTrue(iterator.hasNext());
- assertEquals(HugeEnumCount.NO64, iterator.next());
- assertTrue(iterator.hasNext());
- iterator.remove();
- assertEquals(HugeEnumCount.NO65, iterator.next());
- assertTrue(iterator.hasNext());
- assertEquals(HugeEnumCount.NO128, iterator.next());
- assertFalse(iterator.hasNext());
- assertEquals(EnumSet.of(HugeEnumCount.NO65, HugeEnumCount.NO128), set);
- iterator.remove();
- assertEquals(EnumSet.of(HugeEnumCount.NO65), set);
- }
-
- /**
- * java.util.EnumSet#allOf(java.lang.Class)
- */
- @SuppressWarnings("unchecked")
- public void test_AllOf_LClass() {
- try {
- EnumSet.allOf((Class) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.allOf(Enum.class);
- fail("Should throw ClassCastException");
- } catch (ClassCastException cce) {
- // expected
- }
-
- EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class);
- assertEquals("Size of enumSet should be 64", 64, enumSet.size());
-
- assertFalse(
- "enumSet should not contain null value", enumSet.contains(null));
- assertTrue(
- "enumSet should contain EnumFoo.a", enumSet.contains(EnumFoo.a));
- assertTrue(
- "enumSet should contain EnumFoo.b", enumSet.contains(EnumFoo.b));
-
- enumSet.add(EnumFoo.a);
- assertEquals("Should be equal", 64, enumSet.size());
-
- EnumSet<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class);
- assertEquals("Should be equal", enumSet, anotherSet);
- assertNotSame("Should not be identical", enumSet, anotherSet);
-
- // test enum with more than 64 elements
- EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class);
- assertEquals(65, hugeEnumSet.size());
-
- assertFalse(hugeEnumSet.contains(null));
- assertTrue(hugeEnumSet.contains(HugeEnum.a));
- assertTrue(hugeEnumSet.contains(HugeEnum.b));
-
- hugeEnumSet.add(HugeEnum.a);
- assertEquals(65, hugeEnumSet.size());
-
- EnumSet<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
- assertEquals(hugeEnumSet, anotherHugeSet);
- assertNotSame(hugeEnumSet, anotherHugeSet);
-
- }
-
- /**
- * java.util.EnumSet#add(E)
- */
- @SuppressWarnings("unchecked")
- public void test_add_E() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
-
- try {
- set.add(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // test enum type with more than 64 elements
- Set rawSet = set;
- try {
- rawSet.add(HugeEnumWithInnerClass.b);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- set.clear();
- try {
- set.add(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- boolean result = set.add(EnumFoo.a);
- assertEquals("Size should be 1:", 1, set.size());
- assertTrue("Return value should be true", result);
-
- result = set.add(EnumFoo.a);
- assertEquals("Size should be 1:", 1, set.size());
- assertFalse("Return value should be false", result);
-
- set.add(EnumFoo.b);
- assertEquals("Size should be 2:", 2, set.size());
-
- rawSet = set;
- try {
- rawSet.add(EnumWithAllInnerClass.a);
- fail("Should throw ClassCastException");
- } catch(ClassCastException e) {
- // expected
- }
-
- try {
- rawSet.add(EnumWithInnerClass.a);
- fail("Should throw ClassCastException");
- } catch(ClassCastException e) {
- // expected
- }
-
- try {
- rawSet.add(new Object());
- fail("Should throw ClassCastException");
- } catch(ClassCastException e) {
- // expected
- }
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- result = hugeSet.add(HugeEnum.a);
- assertTrue(result);
-
- result = hugeSet.add(HugeEnum.a);
- assertFalse(result);
-
- try {
- hugeSet.add(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- rawSet = hugeSet;
- try {
- rawSet.add(HugeEnumWithInnerClass.b);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- try {
- rawSet.add(new Object());
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- result = hugeSet.add(HugeEnum.mm);
- assertTrue(result);
- result = hugeSet.add(HugeEnum.mm);
- assertFalse(result);
- assertEquals(2, hugeSet.size());
-
- }
-
- /**
- * java.util.EnumSet#addAll(Collection)
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_addAll_LCollection() {
-
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- assertEquals("Size should be 0:", 0, set.size());
-
- try {
- set.addAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- Set emptySet = EnumSet.noneOf(EmptyEnum.class);
- Enum[] elements = EmptyEnum.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- emptySet.add(elements[i]);
- }
- boolean result = set.addAll(emptySet);
- assertFalse(result);
-
- Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
- collection.add(EnumFoo.a);
- collection.add(EnumFoo.b);
- result = set.addAll(collection);
- assertTrue("addAll should be successful", result);
- assertEquals("Size should be 2:", 2, set.size());
-
- set = EnumSet.noneOf(EnumFoo.class);
-
- Collection rawCollection = new ArrayList<Integer>();
- result = set.addAll(rawCollection);
- assertFalse(result);
- rawCollection.add(1);
- try {
- set.addAll(rawCollection);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- Set<EnumFoo> fullSet = EnumSet.noneOf(EnumFoo.class);
- fullSet.add(EnumFoo.a);
- fullSet.add(EnumFoo.b);
- result = set.addAll(fullSet);
- assertTrue("addAll should be successful", result);
- assertEquals("Size of set should be 2", 2, set.size());
-
- try {
- fullSet.addAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- Set fullSetWithSubclass = EnumSet.noneOf(EnumWithInnerClass.class);
- elements = EnumWithInnerClass.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- fullSetWithSubclass.add(elements[i]);
- }
- try {
- set.addAll(fullSetWithSubclass);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- Set<EnumWithInnerClass> setWithSubclass = fullSetWithSubclass;
- result = setWithSubclass.addAll(setWithSubclass);
- assertFalse("Should return false", result);
-
- Set<EnumWithInnerClass> anotherSetWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- elements = EnumWithInnerClass.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- anotherSetWithSubclass.add((EnumWithInnerClass) elements[i]);
- }
- result = setWithSubclass.addAll(anotherSetWithSubclass);
- assertFalse("Should return false", result);
-
- anotherSetWithSubclass.remove(EnumWithInnerClass.a);
- result = setWithSubclass.addAll(anotherSetWithSubclass);
- assertFalse("Should return false", result);
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- assertEquals(0, hugeSet.size());
-
- try {
- hugeSet.addAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- result = hugeSet.addAll(hugeSet);
- assertFalse(result);
-
- hugeSet = EnumSet.noneOf(HugeEnum.class);
- Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
- hugeCollection.add(HugeEnum.a);
- hugeCollection.add(HugeEnum.b);
- result = hugeSet.addAll(hugeCollection);
- assertTrue(result);
- assertEquals(2, set.size());
-
- hugeSet = EnumSet.noneOf(HugeEnum.class);
-
- rawCollection = new ArrayList<Integer>();
- result = hugeSet.addAll(rawCollection);
- assertFalse(result);
- rawCollection.add(1);
- try {
- hugeSet.addAll(rawCollection);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- EnumSet<HugeEnum> aHugeSet = EnumSet.noneOf(HugeEnum.class);
- aHugeSet.add(HugeEnum.a);
- aHugeSet.add(HugeEnum.b);
- result = hugeSet.addAll(aHugeSet);
- assertTrue(result);
- assertEquals(2, hugeSet.size());
-
- try {
- aHugeSet.addAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- Set hugeSetWithSubclass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- try {
- hugeSet.addAll(hugeSetWithSubclass);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- Set<HugeEnumWithInnerClass> hugeSetWithInnerSubclass = hugeSetWithSubclass;
- result = hugeSetWithInnerSubclass.addAll(hugeSetWithInnerSubclass);
- assertFalse(result);
-
- Set<HugeEnumWithInnerClass> anotherHugeSetWithSubclass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- result = hugeSetWithSubclass.addAll(anotherHugeSetWithSubclass);
- assertFalse(result);
-
- anotherHugeSetWithSubclass.remove(HugeEnumWithInnerClass.a);
- result = setWithSubclass.addAll(anotherSetWithSubclass);
- assertFalse(result);
-
- }
-
- /**
- * java.util.EnumSet#remove(Object)
- */
- public void test_remove_LOject() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo) elements[i]);
- }
-
- boolean result = set.remove(null);
- assertFalse("'set' does not contain null", result);
-
- result = set.remove(EnumFoo.a);
- assertTrue("Should return true", result);
- result = set.remove(EnumFoo.a);
- assertFalse("Should return false", result);
-
- assertEquals("Size of set should be 63:", 63, set.size());
-
- result = set.remove(EnumWithInnerClass.a);
- assertFalse("Should return false", result);
- result = set.remove(EnumWithInnerClass.f);
- assertFalse("Should return false", result);
-
- // test enum with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
-
- result = hugeSet.remove(null);
- assertFalse("'set' does not contain null", result);
-
- result = hugeSet.remove(HugeEnum.a);
- assertTrue("Should return true", result);
- result = hugeSet.remove(HugeEnum.a);
- assertFalse("Should return false", result);
-
- assertEquals("Size of set should be 64:", 64, hugeSet.size());
-
- result = hugeSet.remove(HugeEnumWithInnerClass.a);
- assertFalse("Should return false", result);
- result = hugeSet.remove(HugeEnumWithInnerClass.f);
- assertFalse("Should return false", result);
- }
-
- /**
- * java.util.EnumSet#equals(Object)
- */
- public void test_equals_LObject() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo) elements[i]);
- }
-
- assertFalse("Should return false", set.equals(null));
- assertFalse(
- "Should return false", set.equals(new Object()));
-
- Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class);
- elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- anotherSet.add((EnumFoo) elements[i]);
- }
- assertTrue("Should return true", set.equals(anotherSet));
-
- anotherSet.remove(EnumFoo.a);
- assertFalse(
- "Should return false", set.equals(anotherSet));
-
- Set<EnumWithInnerClass> setWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- elements = EnumWithInnerClass.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- setWithInnerClass.add((EnumWithInnerClass) elements[i]);
- }
-
- assertFalse(
- "Should return false", set.equals(setWithInnerClass));
-
- setWithInnerClass.clear();
- set.clear();
- assertTrue("Should be equal", set.equals(setWithInnerClass));
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- assertTrue(hugeSet.equals(set));
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- assertFalse(hugeSet.equals(null));
- assertFalse(hugeSet.equals(new Object()));
-
- Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
- anotherHugeSet.remove(HugeEnum.a);
- assertFalse(hugeSet.equals(anotherHugeSet));
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- assertFalse(hugeSet.equals(hugeSetWithInnerClass));
- hugeSetWithInnerClass.clear();
- hugeSet.clear();
- assertTrue(hugeSet.equals(hugeSetWithInnerClass));
- }
-
- /**
- * java.util.EnumSet#clear()
- */
- public void test_clear() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
- assertEquals("Size should be 2", 2, set.size());
-
- set.clear();
-
- assertEquals("Size should be 0", 0, set.size());
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
- assertEquals(65, hugeSet.size());
-
- boolean result = hugeSet.contains(HugeEnum.aa);
- assertTrue(result);
-
- hugeSet.clear();
- assertEquals(0, hugeSet.size());
- result = hugeSet.contains(HugeEnum.aa);
- assertFalse(result);
- }
-
- /**
- * java.util.EnumSet#size()
- */
- public void test_size() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
- assertEquals("Size should be 2", 2, set.size());
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.bb);
- assertEquals("Size should be 2", 2, hugeSet.size());
- }
-
- /**
- * java.util.EnumSet#complementOf(java.util.EnumSet)
- */
- public void test_ComplementOf_LEnumSet() {
-
- try {
- EnumSet.complementOf((EnumSet<EnumFoo>) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- EnumSet<EnumWithInnerClass> set = EnumSet
- .noneOf(EnumWithInnerClass.class);
- set.add(EnumWithInnerClass.d);
- set.add(EnumWithInnerClass.e);
- set.add(EnumWithInnerClass.f);
-
- assertEquals("Size should be 3:", 3, set.size());
-
- EnumSet<EnumWithInnerClass> complementOfE = EnumSet.complementOf(set);
- assertTrue(set.contains(EnumWithInnerClass.d));
- assertEquals(
- "complementOfE should have size 3", 3, complementOfE.size());
- assertTrue("complementOfE should contain EnumWithSubclass.a:",
- complementOfE.contains(EnumWithInnerClass.a));
- assertTrue("complementOfE should contain EnumWithSubclass.b:",
- complementOfE.contains(EnumWithInnerClass.b));
- assertTrue("complementOfE should contain EnumWithSubclass.c:",
- complementOfE.contains(EnumWithInnerClass.c));
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- assertEquals(0, hugeSet.size());
- Set<HugeEnum> complementHugeSet = EnumSet.complementOf(hugeSet);
- assertEquals(65, complementHugeSet.size());
-
- hugeSet.add(HugeEnum.A);
- hugeSet.add(HugeEnum.mm);
- complementHugeSet = EnumSet.complementOf(hugeSet);
- assertEquals(63, complementHugeSet.size());
-
- try {
- EnumSet.complementOf((EnumSet<HugeEnum>) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * java.util.EnumSet#contains(Object)
- */
- public void test_contains_LObject() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo)elements[i]);
- }
- boolean result = set.contains(null);
- assertFalse("Should not contain null:", result);
-
- result = set.contains(EnumFoo.a);
- assertTrue("Should contain EnumFoo.a", result);
- result = set.contains(EnumFoo.ll);
- assertTrue("Should contain EnumFoo.ll", result);
-
- result = set.contains(EnumFoo.b);
- assertTrue("Should contain EnumFoo.b", result);
-
- result = set.contains(new Object());
- assertFalse("Should not contain Object instance", result);
-
- result = set.contains(EnumWithInnerClass.a);
- assertFalse("Should not contain EnumWithSubclass.a", result);
-
- set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.aa);
- set.add(EnumFoo.bb);
- set.add(EnumFoo.cc);
-
- assertEquals("Size of set should be 3", 3, set.size());
- assertTrue("set should contain EnumFoo.aa", set.contains(EnumFoo.aa));
-
- Set<EnumWithInnerClass> setWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- setWithSubclass.add(EnumWithInnerClass.a);
- setWithSubclass.add(EnumWithInnerClass.b);
- setWithSubclass.add(EnumWithInnerClass.c);
- setWithSubclass.add(EnumWithInnerClass.d);
- setWithSubclass.add(EnumWithInnerClass.e);
- setWithSubclass.add(EnumWithInnerClass.f);
- result = setWithSubclass.contains(EnumWithInnerClass.f);
- assertTrue("Should contain EnumWithSubclass.f", result);
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- result = hugeSet.contains(HugeEnum.a);
- assertTrue(result);
-
- result = hugeSet.contains(HugeEnum.b);
- assertTrue(result);
-
- result = hugeSet.contains(null);
- assertFalse(result);
-
- result = hugeSet.contains(HugeEnum.a);
- assertTrue(result);
-
- result = hugeSet.contains(HugeEnum.ll);
- assertTrue(result);
-
- result = hugeSet.contains(new Object());
- assertFalse(result);
-
- result = hugeSet.contains(Enum.class);
- assertFalse(result);
-
- }
-
- /**
- * java.util.EnumSet#containsAll(Collection)
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_containsAll_LCollection() {
- EnumSet<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo)elements[i]);
- }
- try {
- set.containsAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- EnumSet<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class);
- elements = EmptyEnum.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- emptySet.add((EmptyEnum)elements[i]);
- }
- boolean result = set.containsAll(emptySet);
- assertTrue("Should return true", result);
-
- Collection rawCollection = new ArrayList();
- result = set.containsAll(rawCollection);
- assertTrue("Should contain empty collection:", result);
-
- rawCollection.add(1);
- result = set.containsAll(rawCollection);
- assertFalse("Should return false", result);
-
- rawCollection.add(EnumWithInnerClass.a);
- result = set.containsAll(rawCollection);
- assertFalse("Should return false", result);
-
- EnumSet rawSet = EnumSet.noneOf(EnumFoo.class);
- result = set.containsAll(rawSet);
- assertTrue("Should contain empty set", result);
-
- emptySet = EnumSet.noneOf(EmptyEnum.class);
- result = set.containsAll(emptySet);
- assertTrue("No class cast should be performed on empty set", result);
-
- Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
- collection.add(EnumFoo.a);
- result = set.containsAll(collection);
- assertTrue("Should contain all elements in collection", result);
-
- EnumSet<EnumFoo> fooSet = EnumSet.noneOf(EnumFoo.class);
- fooSet.add(EnumFoo.a);
- result = set.containsAll(fooSet);
- assertTrue("Should return true", result);
-
- set.clear();
- try {
- set.containsAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- Collection<EnumWithInnerClass> collectionWithSubclass = new ArrayList<EnumWithInnerClass>();
- collectionWithSubclass.add(EnumWithInnerClass.a);
- result = set.containsAll(collectionWithSubclass);
- assertFalse("Should return false", result);
-
- EnumSet<EnumWithInnerClass> setWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- setWithSubclass.add(EnumWithInnerClass.a);
- result = set.containsAll(setWithSubclass);
- assertFalse("Should return false", result);
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.b);
- hugeSet.add(HugeEnum.aa);
- hugeSet.add(HugeEnum.bb);
- hugeSet.add(HugeEnum.cc);
- hugeSet.add(HugeEnum.dd);
-
- Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.b);
- hugeSet.add(HugeEnum.cc);
- result = hugeSet.containsAll(anotherHugeSet);
- assertTrue(result);
-
- try {
- hugeSet.containsAll(null);
- fail("Should throw NullPointerException");
- } catch(NullPointerException e) {
- // expected
- }
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b);
- result = hugeSetWithInnerClass.containsAll(hugeSetWithInnerClass);
- assertTrue(result);
- result = hugeSet.containsAll(hugeSetWithInnerClass);
- assertFalse(result);
-
- rawCollection = new ArrayList();
- result = hugeSet.containsAll(rawCollection);
- assertTrue("Should contain empty collection:", result);
-
- rawCollection.add(1);
- result = hugeSet.containsAll(rawCollection);
- assertFalse("Should return false", result);
-
- rawCollection.add(EnumWithInnerClass.a);
- result = set.containsAll(rawCollection);
- assertFalse("Should return false", result);
-
- rawSet = EnumSet.noneOf(HugeEnum.class);
- result = hugeSet.containsAll(rawSet);
- assertTrue("Should contain empty set", result);
-
- EnumSet<HugeEnumWithInnerClass> emptyHugeSet
- = EnumSet.noneOf(HugeEnumWithInnerClass.class);
- result = hugeSet.containsAll(emptyHugeSet);
- assertTrue("No class cast should be performed on empty set", result);
-
- Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
- hugeCollection.add(HugeEnum.a);
- result = hugeSet.containsAll(hugeCollection);
- assertTrue("Should contain all elements in collection", result);
-
- hugeSet.clear();
- try {
- hugeSet.containsAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- Collection<HugeEnumWithInnerClass> hugeCollectionWithSubclass = new ArrayList<HugeEnumWithInnerClass>();
- hugeCollectionWithSubclass.add(HugeEnumWithInnerClass.a);
- result = hugeSet.containsAll(hugeCollectionWithSubclass);
- assertFalse("Should return false", result);
-
- EnumSet<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeSetWithSubclass.add(HugeEnumWithInnerClass.a);
- result = hugeSet.containsAll(hugeSetWithSubclass);
- assertFalse("Should return false", result);
- }
-
- /**
- * java.util.EnumSet#copyOf(java.util.Collection)
- */
- @SuppressWarnings("unchecked")
- public void test_CopyOf_LCollection() {
- try {
- EnumSet.copyOf((Collection) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- Collection collection = new ArrayList();
- try {
- EnumSet.copyOf(collection);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- collection.add(new Object());
- try {
- EnumSet.copyOf(collection);
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- Collection<EnumFoo> enumCollection = new ArrayList<EnumFoo>();
- enumCollection.add(EnumFoo.b);
-
- EnumSet<EnumFoo> copyOfEnumCollection = EnumSet.copyOf(enumCollection);
- assertEquals("Size of copyOfEnumCollection should be 1:",
- 1, copyOfEnumCollection.size());
- assertTrue("copyOfEnumCollection should contain EnumFoo.b:",
- copyOfEnumCollection.contains(EnumFoo.b));
-
- enumCollection.add(null);
- assertEquals("Size of enumCollection should be 2:",
- 2, enumCollection.size());
-
- try {
- copyOfEnumCollection = EnumSet.copyOf(enumCollection);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- Collection rawEnumCollection = new ArrayList();
- rawEnumCollection.add(EnumFoo.a);
- rawEnumCollection.add(EnumWithInnerClass.a);
- try {
- EnumSet.copyOf(rawEnumCollection);
- fail("Should throw ClassCastException");
- } catch(ClassCastException e) {
- // expected
- }
-
- // test enum type with more than 64 elements
- Collection<HugeEnum> hugeEnumCollection = new ArrayList<HugeEnum>();
- hugeEnumCollection.add(HugeEnum.b);
-
- EnumSet<HugeEnum> copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection);
- assertEquals(1, copyOfHugeEnumCollection.size());
- assertTrue(copyOfHugeEnumCollection.contains(HugeEnum.b));
-
- hugeEnumCollection.add(null);
- assertEquals(2, hugeEnumCollection.size());
-
- try {
- copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- rawEnumCollection = new ArrayList();
- rawEnumCollection.add(HugeEnum.a);
- rawEnumCollection.add(HugeEnumWithInnerClass.a);
- try {
- EnumSet.copyOf(rawEnumCollection);
- fail("Should throw ClassCastException");
- } catch(ClassCastException e) {
- // expected
- }
- }
-
- /**
- * java.util.EnumSet#copyOf(java.util.EnumSet)
- */
- @SuppressWarnings("unchecked")
- public void test_CopyOf_LEnumSet() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet
- .noneOf(EnumWithInnerClass.class);
- enumSet.add(EnumWithInnerClass.a);
- enumSet.add(EnumWithInnerClass.f);
- EnumSet<EnumWithInnerClass> copyOfE = EnumSet.copyOf(enumSet);
- assertEquals("Size of enumSet and copyOfE should be equal",
- enumSet.size(), copyOfE.size());
-
- assertTrue("EnumWithSubclass.a should be contained in copyOfE",
- copyOfE.contains(EnumWithInnerClass.a));
- assertTrue("EnumWithSubclass.f should be contained in copyOfE",
- copyOfE.contains(EnumWithInnerClass.f));
-
- Object[] enumValue = copyOfE.toArray();
- assertSame("enumValue[0] should be identical with EnumWithSubclass.a",
- enumValue[0], EnumWithInnerClass.a);
- assertSame("enumValue[1] should be identical with EnumWithSubclass.f",
- enumValue[1], EnumWithInnerClass.f);
-
- try {
- EnumSet.copyOf((EnumSet) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeEnumSet.add(HugeEnumWithInnerClass.a);
- hugeEnumSet.add(HugeEnumWithInnerClass.f);
- EnumSet<HugeEnumWithInnerClass> copyOfHugeEnum = EnumSet.copyOf(hugeEnumSet);
- assertEquals(enumSet.size(), copyOfE.size());
-
- assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.a));
- assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.f));
-
- Object[] hugeEnumValue = copyOfHugeEnum.toArray();
- assertSame(hugeEnumValue[0], HugeEnumWithInnerClass.a);
- assertSame(hugeEnumValue[1], HugeEnumWithInnerClass.f);
- }
-
- /**
- * java.util.EnumSet#removeAll(Collection)
- */
- @SuppressWarnings("unchecked")
- public void test_removeAll_LCollection() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- try {
- set.removeAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- set = EnumSet.allOf(EnumFoo.class);
- assertEquals("Size of set should be 64:", 64, set.size());
-
- try {
- set.removeAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
- collection.add(EnumFoo.a);
-
- boolean result = set.removeAll(collection);
- assertTrue("Should return true", result);
- assertEquals("Size of set should be 63", 63, set.size());
-
- collection = new ArrayList();
- result = set.removeAll(collection);
- assertFalse("Should return false", result);
-
- Set<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class);
- result = set.removeAll(emptySet);
- assertFalse("Should return false", result);
-
- EnumSet<EnumFoo> emptyFooSet = EnumSet.noneOf(EnumFoo.class);
- result = set.removeAll(emptyFooSet);
- assertFalse("Should return false", result);
-
- emptyFooSet.add(EnumFoo.a);
- result = set.removeAll(emptyFooSet);
- assertFalse("Should return false", result);
-
- Set<EnumWithInnerClass> setWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- result = set.removeAll(setWithSubclass);
- assertFalse("Should return false", result);
-
- setWithSubclass.add(EnumWithInnerClass.a);
- result = set.removeAll(setWithSubclass);
- assertFalse("Should return false", result);
-
- Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class);
- anotherSet.add(EnumFoo.a);
-
- set = EnumSet.allOf(EnumFoo.class);
- result = set.removeAll(anotherSet);
- assertTrue("Should return true", result);
- assertEquals("Size of set should be 63:", 63, set.size());
-
- Set<EnumWithInnerClass> setWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- setWithInnerClass.add(EnumWithInnerClass.a);
- setWithInnerClass.add(EnumWithInnerClass.b);
-
- Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- anotherSetWithInnerClass.add(EnumWithInnerClass.c);
- anotherSetWithInnerClass.add(EnumWithInnerClass.d);
- result = anotherSetWithInnerClass.removeAll(setWithInnerClass);
- assertFalse("Should return false", result);
-
- anotherSetWithInnerClass.add(EnumWithInnerClass.a);
- result = anotherSetWithInnerClass.removeAll(setWithInnerClass);
- assertTrue("Should return true", result);
- assertEquals("Size of anotherSetWithInnerClass should remain 2",
- 2, anotherSetWithInnerClass.size());
-
- anotherSetWithInnerClass.remove(EnumWithInnerClass.c);
- anotherSetWithInnerClass.remove(EnumWithInnerClass.d);
- result = anotherSetWithInnerClass.remove(setWithInnerClass);
- assertFalse("Should return false", result);
-
- Set rawSet = EnumSet.allOf(EnumWithAllInnerClass.class);
- result = rawSet.removeAll(EnumSet.allOf(EnumFoo.class));
- assertFalse("Should return false", result);
-
- setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- setWithInnerClass.remove(EnumWithInnerClass.a);
- anotherSetWithInnerClass.remove(EnumWithInnerClass.f);
- result = setWithInnerClass.removeAll(anotherSetWithInnerClass);
- assertTrue("Should return true", result);
- assertEquals("Size of setWithInnerClass should be 1", 1, setWithInnerClass.size());
-
- result = setWithInnerClass.contains(EnumWithInnerClass.f);
- assertTrue("Should return true", result);
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
-
- Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
- hugeCollection.add(HugeEnum.a);
-
- result = hugeSet.removeAll(hugeCollection);
- assertTrue(result);
- assertEquals(64, hugeSet.size());
-
- collection = new ArrayList();
- result = hugeSet.removeAll(collection);
- assertFalse(result);
-
- Set<HugeEnum> emptyHugeSet = EnumSet.noneOf(HugeEnum.class);
- result = hugeSet.removeAll(emptyHugeSet);
- assertFalse(result);
-
- Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- result = hugeSet.removeAll(hugeSetWithSubclass);
- assertFalse(result);
-
- hugeSetWithSubclass.add(HugeEnumWithInnerClass.a);
- result = hugeSet.removeAll(hugeSetWithSubclass);
- assertFalse(result);
-
- Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
- anotherHugeSet.add(HugeEnum.a);
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- result = hugeSet.removeAll(anotherHugeSet);
- assertTrue(result);
- assertEquals(63, set.size());
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b);
-
- Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.c);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.d);
- result = anotherHugeSetWithInnerClass.removeAll(setWithInnerClass);
- assertFalse("Should return false", result);
-
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
- result = anotherHugeSetWithInnerClass.removeAll(hugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(2, anotherHugeSetWithInnerClass.size());
-
- anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.c);
- anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.d);
- result = anotherHugeSetWithInnerClass.remove(hugeSetWithInnerClass);
- assertFalse(result);
-
- rawSet = EnumSet.allOf(HugeEnumWithInnerClass.class);
- result = rawSet.removeAll(EnumSet.allOf(HugeEnum.class));
- assertFalse(result);
-
- hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.a);
- anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f);
- result = hugeSetWithInnerClass.removeAll(anotherHugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(1, hugeSetWithInnerClass.size());
-
- result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.f);
- assertTrue(result);
- }
-
- /**
- * java.util.EnumSet#retainAll(Collection)
- */
- @SuppressWarnings("unchecked")
- public void test_retainAll_LCollection() {
- Set<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
-
- try {
- set.retainAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- set.clear();
- boolean result = set.retainAll(null);
- assertFalse("Should return false", result);
-
- Collection rawCollection = new ArrayList();
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result);
-
- rawCollection.add(EnumFoo.a);
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result);
-
- rawCollection.add(EnumWithInnerClass.a);
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result);
- assertEquals("Size of set should be 0:", 0, set.size());
-
- rawCollection.remove(EnumFoo.a);
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result);
-
- Set<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class);
- result = set.retainAll(anotherSet);
- assertFalse("Should return false", result);
- assertEquals("Size of set should be 0", 0, set.size());
-
- Set<EnumWithInnerClass> setWithInnerClass = EnumSet
- .allOf(EnumWithInnerClass.class);
- result = set.retainAll(setWithInnerClass);
- assertFalse("Should return false", result);
- assertEquals("Size of set should be 0", 0, set.size());
-
- setWithInnerClass = EnumSet.noneOf(EnumWithInnerClass.class);
- result = set.retainAll(setWithInnerClass);
- assertFalse("Should return false", result);
-
- Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class);
- result = set.retainAll(emptySet);
- assertFalse("Should return false", result);
-
- Set<EnumWithAllInnerClass> setWithAllInnerClass = EnumSet
- .allOf(EnumWithAllInnerClass.class);
- result = set.retainAll(setWithAllInnerClass);
- assertFalse("Should return false", result);
-
- set.add(EnumFoo.a);
- result = set.retainAll(setWithInnerClass);
- assertTrue("Should return true", result);
- assertEquals("Size of set should be 0", 0, set.size());
-
- setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- setWithInnerClass.remove(EnumWithInnerClass.f);
- Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- anotherSetWithInnerClass.add(EnumWithInnerClass.e);
- anotherSetWithInnerClass.add(EnumWithInnerClass.f);
-
- result = setWithInnerClass.retainAll(anotherSetWithInnerClass);
- assertTrue("Should return true", result);
- result = setWithInnerClass.contains(EnumWithInnerClass.e);
- assertTrue("Should contain EnumWithInnerClass.e", result);
- result = setWithInnerClass.contains(EnumWithInnerClass.b);
- assertFalse("Should not contain EnumWithInnerClass.b", result);
- assertEquals("Size of set should be 1:", 1, setWithInnerClass.size());
-
- anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- result = setWithInnerClass.retainAll(anotherSetWithInnerClass);
-
- assertFalse("Return value should be false", result);
-
- rawCollection = new ArrayList();
- rawCollection.add(EnumWithInnerClass.e);
- rawCollection.add(EnumWithInnerClass.f);
- result = setWithInnerClass.retainAll(rawCollection);
- assertFalse("Should return false", result);
-
- set = EnumSet.allOf(EnumFoo.class);
- set.remove(EnumFoo.a);
- anotherSet = EnumSet.noneOf(EnumFoo.class);
- anotherSet.add(EnumFoo.a);
- result = set.retainAll(anotherSet);
- assertTrue("Should return true", result);
- assertEquals("size should be 0", 0, set.size());
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
-
- try {
- hugeSet.retainAll(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- hugeSet.clear();
- result = hugeSet.retainAll(null);
- assertFalse(result);
-
- rawCollection = new ArrayList();
- result = hugeSet.retainAll(rawCollection);
- assertFalse(result);
-
- rawCollection.add(HugeEnum.a);
- result = hugeSet.retainAll(rawCollection);
- assertFalse(result);
-
- rawCollection.add(HugeEnumWithInnerClass.a);
- result = hugeSet.retainAll(rawCollection);
- assertFalse(result);
- assertEquals(0, set.size());
-
- rawCollection.remove(HugeEnum.a);
- result = set.retainAll(rawCollection);
- assertFalse(result);
-
- Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
- result = hugeSet.retainAll(anotherHugeSet);
- assertFalse(result);
- assertEquals(0, hugeSet.size());
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- result = hugeSet.retainAll(hugeSetWithInnerClass);
- assertFalse(result);
- assertEquals(0, hugeSet.size());
-
- hugeSetWithInnerClass = EnumSet.noneOf(HugeEnumWithInnerClass.class);
- result = hugeSet.retainAll(hugeSetWithInnerClass);
- assertFalse(result);
-
- Set<HugeEnumWithInnerClass> hugeSetWithAllInnerClass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- result = hugeSet.retainAll(hugeSetWithAllInnerClass);
- assertFalse(result);
-
- hugeSet.add(HugeEnum.a);
- result = hugeSet.retainAll(hugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(0, hugeSet.size());
-
- hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f);
- Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.e);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.f);
-
- result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass);
- assertTrue(result);
- result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.e);
- assertTrue("Should contain HugeEnumWithInnerClass.e", result);
- result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.b);
- assertFalse("Should not contain HugeEnumWithInnerClass.b", result);
- assertEquals("Size of hugeSet should be 1:", 1, hugeSetWithInnerClass.size());
-
- anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass);
-
- assertFalse("Return value should be false", result);
-
- rawCollection = new ArrayList();
- rawCollection.add(HugeEnumWithInnerClass.e);
- rawCollection.add(HugeEnumWithInnerClass.f);
- result = hugeSetWithInnerClass.retainAll(rawCollection);
- assertFalse(result);
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- hugeSet.remove(HugeEnum.a);
- anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
- anotherHugeSet.add(HugeEnum.a);
- result = hugeSet.retainAll(anotherHugeSet);
- assertTrue(result);
- assertEquals(0, hugeSet.size());
- }
-
- /**
- * java.util.EnumSet#iterator()
- */
- public void test_iterator() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
-
- Iterator<EnumFoo> iterator = set.iterator();
- Iterator<EnumFoo> anotherIterator = set.iterator();
- assertNotSame("Should not be same", iterator, anotherIterator);
- try {
- iterator.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expectedd
- }
-
- assertTrue("Should has next element:", iterator.hasNext());
- assertSame("Should be identical", EnumFoo.a, iterator.next());
- iterator.remove();
- assertTrue("Should has next element:", iterator.hasNext());
- assertSame("Should be identical", EnumFoo.b, iterator.next());
- assertFalse("Should not has next element:", iterator.hasNext());
- assertFalse("Should not has next element:", iterator.hasNext());
-
- assertEquals("Size should be 1:", 1, set.size());
-
- try {
- iterator.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- iterator = set.iterator();
- assertEquals("Should be equal", EnumFoo.a, iterator.next());
- iterator.remove();
- try {
- iterator.remove();
- fail("Should throw IllegalStateException");
- } catch(IllegalStateException e) {
- // expected
- }
-
- Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class);
- Iterator<EmptyEnum> emptyIterator = emptySet.iterator();
- try {
- emptyIterator.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- Set<EnumWithInnerClass> setWithSubclass = EnumSet
- .allOf(EnumWithInnerClass.class);
- setWithSubclass.remove(EnumWithInnerClass.e);
- Iterator<EnumWithInnerClass> iteratorWithSubclass = setWithSubclass
- .iterator();
- assertSame("Should be same", EnumWithInnerClass.a, iteratorWithSubclass.next());
-
- assertTrue("Should return true", iteratorWithSubclass.hasNext());
- assertSame("Should be same", EnumWithInnerClass.b, iteratorWithSubclass.next());
-
- setWithSubclass.remove(EnumWithInnerClass.c);
- assertTrue("Should return true", iteratorWithSubclass.hasNext());
- assertSame("Should be same", EnumWithInnerClass.c, iteratorWithSubclass.next());
-
- assertTrue("Should return true", iteratorWithSubclass.hasNext());
- assertSame("Should be same", EnumWithInnerClass.d, iteratorWithSubclass.next());
-
- setWithSubclass.add(EnumWithInnerClass.e);
- assertTrue("Should return true", iteratorWithSubclass.hasNext());
- assertSame("Should be same", EnumWithInnerClass.f, iteratorWithSubclass.next());
-
- set = EnumSet.noneOf(EnumFoo.class);
- iterator = set.iterator();
- try {
- iterator.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- set.add(EnumFoo.a);
- iterator = set.iterator();
- assertEquals("Should return EnumFoo.a", EnumFoo.a, iterator.next());
- assertEquals("Size of set should be 1", 1, set.size());
- iterator.remove();
- assertEquals("Size of set should be 0", 0, set.size());
- assertFalse("Should return false", set.contains(EnumFoo.a));
-
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
- iterator = set.iterator();
- assertEquals("Should be equals", EnumFoo.a, iterator.next());
- iterator.remove();
- try {
- iterator.remove();
- fail("Should throw IllegalStateException");
- } catch(IllegalStateException e) {
- // expected
- }
-
- assertTrue("Should have next element", iterator.hasNext());
- try {
- iterator.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals("Size of set should be 1", 1, set.size());
- assertTrue("Should have next element", iterator.hasNext());
- assertEquals("Should return EnumFoo.b", EnumFoo.b, iterator.next());
- set.remove(EnumFoo.b);
- assertEquals("Size of set should be 0", 0, set.size());
- iterator.remove();
- assertFalse("Should return false", set.contains(EnumFoo.a));
-
- // RI's bug, EnumFoo.b should not exist at the moment.
- if (!disableRIBugs) {
- assertFalse("Should return false", set.contains(EnumFoo.b));
- }
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.b);
-
- Iterator<HugeEnum> hIterator = hugeSet.iterator();
- Iterator<HugeEnum> anotherHugeIterator = hugeSet.iterator();
- assertNotSame(hIterator, anotherHugeIterator);
- try {
- hIterator.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expectedd
- }
-
- assertTrue(hIterator.hasNext());
- assertSame(HugeEnum.a, hIterator.next());
- hIterator.remove();
- assertTrue(hIterator.hasNext());
- assertSame(HugeEnum.b, hIterator.next());
- assertFalse(hIterator.hasNext());
- assertFalse(hIterator.hasNext());
-
- assertEquals(1, hugeSet.size());
-
- try {
- hIterator.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- hugeSetWithSubclass.remove(HugeEnumWithInnerClass.e);
- Iterator<HugeEnumWithInnerClass> hugeIteratorWithSubclass = hugeSetWithSubclass
- .iterator();
- assertSame(HugeEnumWithInnerClass.a, hugeIteratorWithSubclass.next());
-
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.b, hugeIteratorWithSubclass.next());
-
- setWithSubclass.remove(HugeEnumWithInnerClass.c);
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.c, hugeIteratorWithSubclass.next());
-
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.d, hugeIteratorWithSubclass.next());
-
- hugeSetWithSubclass.add(HugeEnumWithInnerClass.e);
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.f, hugeIteratorWithSubclass.next());
-
- hugeSet = EnumSet.noneOf(HugeEnum.class);
- hIterator = hugeSet.iterator();
- try {
- hIterator.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- hugeSet.add(HugeEnum.a);
- hIterator = hugeSet.iterator();
- assertEquals(HugeEnum.a, hIterator.next());
- assertEquals(1, hugeSet.size());
- hIterator.remove();
- assertEquals(0, hugeSet.size());
- assertFalse(hugeSet.contains(HugeEnum.a));
-
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.b);
- hIterator = hugeSet.iterator();
- hIterator.next();
- hIterator.remove();
-
- assertTrue(hIterator.hasNext());
- try {
- hIterator.remove();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals(1, hugeSet.size());
- assertTrue(hIterator.hasNext());
- assertEquals(HugeEnum.b, hIterator.next());
- hugeSet.remove(HugeEnum.b);
- assertEquals(0, hugeSet.size());
- hIterator.remove();
- assertFalse(hugeSet.contains(HugeEnum.a));
- // RI's bug, EnumFoo.b should not exist at the moment.
- if(!disableRIBugs) {
- assertFalse("Should return false", set.contains(EnumFoo.b));
- }
- }
-
- /**
- * java.util.EnumSet#of(E)
- */
- public void test_Of_E() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a);
- assertEquals("enumSet should have length 1:", 1, enumSet.size());
-
- assertTrue("enumSet should contain EnumWithSubclass.a:",
- enumSet.contains(EnumWithInnerClass.a));
-
- try {
- EnumSet.of((EnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a);
- assertEquals(1, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- }
-
- /**
- * java.util.EnumSet#of(E, E)
- */
- public void test_Of_EE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b);
- assertEquals("enumSet should have length 2:", 2, enumSet.size());
-
- assertTrue("enumSet should contain EnumWithSubclass.a:",
- enumSet.contains(EnumWithInnerClass.a));
- assertTrue("enumSet should contain EnumWithSubclass.b:",
- enumSet.contains(EnumWithInnerClass.b));
-
- try {
- EnumSet.of((EnumWithInnerClass) null, EnumWithInnerClass.a);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( EnumWithInnerClass.a, (EnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( (EnumWithInnerClass) null, (EnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.a);
- assertEquals("Size of enumSet should be 1",
- 1, enumSet.size());
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b);
- assertEquals(2, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.b));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, HugeEnumWithInnerClass.a);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( (HugeEnumWithInnerClass) null, (HugeEnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a);
- assertEquals(1, hugeEnumSet.size());
- }
-
- /**
- * java.util.EnumSet#of(E, E, E)
- */
- public void test_Of_EEE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b, EnumWithInnerClass.c);
- assertEquals("Size of enumSet should be 3:", 3, enumSet.size());
-
- assertTrue(
- "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a));
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c));
-
- try {
- EnumSet.of((EnumWithInnerClass) null, null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.b,
- EnumWithInnerClass.b);
- assertEquals("enumSet should contain 2 elements:", 2, enumSet.size());
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c);
- assertEquals(3, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.b,
- HugeEnumWithInnerClass.b);
- assertEquals(2, hugeEnumSet.size());
- }
-
- /**
- * java.util.EnumSet#of(E, E, E, E)
- */
- public void test_Of_EEEE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b, EnumWithInnerClass.c,
- EnumWithInnerClass.d);
- assertEquals("Size of enumSet should be 4", 4, enumSet.size());
-
- assertTrue(
- "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a));
- assertTrue("enumSet should contain EnumWithSubclass.d:", enumSet
- .contains(EnumWithInnerClass.d));
-
- try {
- EnumSet.of((EnumWithInnerClass) null, null, null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c,
- HugeEnumWithInnerClass.d);
- assertEquals(4, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.d));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, null, null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * java.util.EnumSet#of(E, E, E, E, E)
- */
- public void test_Of_EEEEE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b, EnumWithInnerClass.c,
- EnumWithInnerClass.d, EnumWithInnerClass.e);
- assertEquals("Size of enumSet should be 5:", 5, enumSet.size());
-
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a));
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.e));
-
- try {
- EnumSet.of((EnumWithInnerClass) null, null, null, null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c,
- HugeEnumWithInnerClass.d, HugeEnumWithInnerClass.e);
- assertEquals(5, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.e));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, null, null, null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * java.util.EnumSet#of(E, E...)
- */
- public void test_Of_EEArray() {
- EnumWithInnerClass[] enumArray = new EnumWithInnerClass[] {
- EnumWithInnerClass.b, EnumWithInnerClass.c };
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- enumArray);
- assertEquals("Should be equal", 3, enumSet.size());
-
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a));
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c));
-
- try {
- EnumSet.of(EnumWithInnerClass.a, (EnumWithInnerClass[])null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- EnumFoo[] foos = {EnumFoo.a, EnumFoo.c, EnumFoo.d};
- EnumSet<EnumFoo> set = EnumSet.of(EnumFoo.c, foos);
- assertEquals("size of set should be 1", 3, set.size());
- assertTrue("Should contain EnumFoo.a", set.contains(EnumFoo.a));
- assertTrue("Should contain EnumFoo.c", set.contains(EnumFoo.c));
- assertTrue("Should contain EnumFoo.d", set.contains(EnumFoo.d));
-
- // test enum type with more than 64 elements
- HugeEnumWithInnerClass[] hugeEnumArray = new HugeEnumWithInnerClass[] {
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c };
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- hugeEnumArray);
- assertEquals(3, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c));
-
- try {
- EnumSet.of(HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass[])null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException npe) {
- // expected
- }
-
- HugeEnumWithInnerClass[] huges = {HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.d};
- EnumSet<HugeEnumWithInnerClass> hugeSet = EnumSet.of(HugeEnumWithInnerClass.c, huges);
- assertEquals(3, hugeSet.size());
- assertTrue(hugeSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeSet.contains(HugeEnumWithInnerClass.c));
- assertTrue(hugeSet.contains(HugeEnumWithInnerClass.d));
- }
-
- /**
- * java.util.EnumSet#range(E, E)
- */
- public void test_Range_EE() {
- try {
- EnumSet.range(EnumWithInnerClass.c, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, EnumWithInnerClass.c);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, (EnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(EnumWithInnerClass.b, EnumWithInnerClass.a);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.range(
- EnumWithInnerClass.a, EnumWithInnerClass.a);
- assertEquals("Size of enumSet should be 1", 1, enumSet.size());
-
- enumSet = EnumSet.range(
- EnumWithInnerClass.a, EnumWithInnerClass.c);
- assertEquals("Size of enumSet should be 3", 3, enumSet.size());
-
- // test enum with more than 64 elements
- try {
- EnumSet.range(HugeEnumWithInnerClass.c, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, HugeEnumWithInnerClass.c);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, (HugeEnumWithInnerClass) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.a);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a);
- assertEquals(1, hugeEnumSet.size());
-
- hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.aa);
- assertEquals(51, hugeEnumSet.size());
-
- hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.mm);
- assertEquals(65, hugeEnumSet.size());
-
- hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.mm);
- assertEquals(64, hugeEnumSet.size());
- }
-
- /**
- * java.util.EnumSet#clone()
- */
- public void test_Clone() {
- EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class);
- EnumSet<EnumFoo> clonedEnumSet = enumSet.clone();
- assertEquals(enumSet, clonedEnumSet);
- assertNotSame(enumSet, clonedEnumSet);
- assertTrue(clonedEnumSet.contains(EnumFoo.a));
- assertTrue(clonedEnumSet.contains(EnumFoo.b));
- assertEquals(64, clonedEnumSet.size());
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class);
- EnumSet<HugeEnum> hugeClonedEnumSet = hugeEnumSet.clone();
- assertEquals(hugeEnumSet, hugeClonedEnumSet);
- assertNotSame(hugeEnumSet, hugeClonedEnumSet);
- assertTrue(hugeClonedEnumSet.contains(HugeEnum.a));
- assertTrue(hugeClonedEnumSet.contains(HugeEnum.b));
- assertEquals(65, hugeClonedEnumSet.size());
-
- hugeClonedEnumSet.remove(HugeEnum.a);
- assertEquals(64, hugeClonedEnumSet.size());
- assertFalse(hugeClonedEnumSet.contains(HugeEnum.a));
- assertEquals(65, hugeEnumSet.size());
- assertTrue(hugeEnumSet.contains(HugeEnum.a));
- }
-
- /**
- * java.util.EnumSet#Serialization()
- */
- public void test_serialization() throws Exception {
- EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
- SerializationTest.verifySelf(set);
- }
-
- /**
- * serialization/deserialization compatibility with RI.
- */
- @SuppressWarnings( { "unchecked", "boxing" })
- public void testSerializationCompatibility() throws Exception {
- EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
- SerializationTest.verifyGolden(this, set);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java b/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java
deleted file mode 100644
index 2aa4954..0000000
--- a/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java
+++ /dev/null
@@ -1,31 +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 tests.api.java.util;
-
-import java.util.FormattableFlags;
-import junit.framework.TestCase;
-
-public class FormattableFlagsTest extends TestCase {
-
- /**
- * @test java.util.FormattableFlags ConstantFieldValues
- */
- public void test_ConstantFieldValues() {
- assertEquals(1, FormattableFlags.LEFT_JUSTIFY);
- assertEquals(2, FormattableFlags.UPPERCASE);
- assertEquals(4, FormattableFlags.ALTERNATE);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/HashMapTest.java b/luni/src/test/java/tests/api/java/util/HashMapTest.java
deleted file mode 100644
index b37e813..0000000
--- a/luni/src/test/java/tests/api/java/util/HashMapTest.java
+++ /dev/null
@@ -1,558 +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 tests.api.java.util;
-
-import java.util.*;
-
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-public class HashMapTest extends junit.framework.TestCase {
- class MockMap extends AbstractMap {
- public Set entrySet() {
- return Collections.EMPTY_SET;
- }
- public int size(){
- return 0;
- }
- }
-
- private static class MockMapNull extends AbstractMap {
- public Set entrySet() {
- return null;
- }
-
- public int size() {
- return 10;
- }
- }
-
- HashMap hm;
-
- final static int hmSize = 1000;
-
- Object[] objArray;
-
- Object[] objArray2;
-
- /**
- * java.util.HashMap#HashMap()
- */
- public void test_Constructor() {
- // Test for method java.util.HashMap()
- new Support_MapTest2(new HashMap()).runTest();
-
- HashMap hm2 = new HashMap();
- assertEquals("Created incorrect HashMap", 0, hm2.size());
- }
-
- /**
- * java.util.HashMap#HashMap(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.HashMap(int)
- HashMap hm2 = new HashMap(5);
- assertEquals("Created incorrect HashMap", 0, hm2.size());
- try {
- new HashMap(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- HashMap empty = new HashMap(0);
- assertNull("Empty hashmap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * java.util.HashMap#HashMap(int, float)
- */
- public void test_ConstructorIF() {
- // Test for method java.util.HashMap(int, float)
- HashMap hm2 = new HashMap(5, (float) 0.5);
- assertEquals("Created incorrect HashMap", 0, hm2.size());
- try {
- new HashMap(0, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- HashMap empty = new HashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * java.util.HashMap#HashMap(java.util.Map)
- */
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.HashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- HashMap hm2 = new HashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct HashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- Map mockMap = new MockMap();
- hm = new HashMap(mockMap);
- assertEquals(hm, mockMap);
- }
-
- /**
- * java.util.HashMap#clear()
- */
- public void test_clear() {
- // Test for method void java.util.HashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * java.util.HashMap#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.HashMap.clone()
- HashMap hm2 = (HashMap) hm.clone();
- assertTrue("Clone answered equivalent HashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal HashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- HashMap map = new HashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
-
- // regresion test for HARMONY-4603
- HashMap hashmap = new HashMap();
- MockClonable mock = new MockClonable(1);
- hashmap.put(1, mock);
- assertEquals(1, ((MockClonable) hashmap.get(1)).i);
- HashMap hm3 = (HashMap)hashmap.clone();
- assertEquals(1, ((MockClonable) hm3.get(1)).i);
- mock.i = 0;
- assertEquals(0, ((MockClonable) hashmap.get(1)).i);
- assertEquals(0, ((MockClonable) hm3.get(1)).i);
- }
-
- /**
- * java.util.HashMap#containsKey(java.lang.Object)
- */
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.HashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm.containsKey(new Integer(
- 876).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * java.util.HashMap#containsValue(java.lang.Object)
- */
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.HashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(new Integer(875)));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * java.util.HashMap#entrySet()
- */
- public void test_entrySet() {
- // Test for method java.util.Set java.util.HashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- /**
- * java.util.HashMap#entrySet()
- */
- public void test_entrySetEquals() {
- Set s1 = hm.entrySet();
- Set s2 = new HashMap(hm).entrySet();
- assertEquals(s1, s2);
- }
-
- /**
- * java.util.HashMap#entrySet()
- */
- public void test_removeFromViews() {
- hm.put("A", null);
- hm.put("B", null);
- assertTrue(hm.keySet().remove("A"));
-
- Map<String, String> m2 = new HashMap<String, String>();
- m2.put("B", null);
- assertTrue(hm.entrySet().remove(m2.entrySet().iterator().next()));
- }
-
- /**
- * java.util.HashMap#get(java.lang.Object)
- */
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.HashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorrect value for existing key", "HELLO", hm.get("T")
- );
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
-
- // Regression for HARMONY-206
- ReusableKey k = new ReusableKey();
- HashMap map = new HashMap();
- k.setKey(1);
- map.put(k, "value1");
-
- k.setKey(18);
- assertNull(map.get(k));
-
- k.setKey(17);
- assertNull(map.get(k));
- }
-
- /**
- * java.util.HashMap#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.HashMap.isEmpty()
- assertTrue("Returned false for new map", new HashMap().isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * java.util.HashMap#keySet()
- */
- public void test_keySet() {
- // Test for method java.util.Set java.util.HashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray[i].toString()));
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new HashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new HashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * java.util.HashMap#put(java.lang.Object, java.lang.Object)
- */
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.HashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- HashMap m = new HashMap();
- m.put(new Short((short) 0), "short");
- m.put(null, "test");
- m.put(new Integer(0), "int");
- assertEquals("Failed adding to bucket containing null", "short", m.get(
- new Short((short) 0)));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(
- new Integer(0)));
- }
-
- /**
- * java.util.HashMap#putAll(java.util.Map)
- */
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.HashMap.putAll(java.util.Map)
- HashMap hm2 = new HashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(
- new Integer(i).toString()).equals((new Integer(i))));
-
- Map mockMap = new MockMap();
- hm2 = new HashMap();
- hm2.putAll(mockMap);
- assertEquals("Size should be 0", 0, hm2.size());
- }
-
- /**
- * java.util.HashMap#putAll(java.util.Map)
- */
- public void test_putAllLjava_util_Map_Null() {
- HashMap hashMap = new HashMap();
- try {
- hashMap.putAll(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
-
- try {
- hashMap = new HashMap(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
- }
-
- public void test_putAllLjava_util_Map_Resize() {
- Random rnd = new Random(666);
-
- Map<Integer,Integer> m1 = new HashMap<Integer, Integer>();
- int MID = 10000;
- for (int i = 0; i < MID; i++) {
- Integer j = rnd.nextInt();
- m1.put(j, j);
- }
-
- Map<Integer,Integer> m2 = new HashMap<Integer, Integer>();
- int HI = 30000;
- for (int i = MID; i < HI; i++) {
- Integer j = rnd.nextInt();
- m2.put(j, j);
- }
-
- m1.putAll(m2);
-
- rnd = new Random(666);
- for (int i = 0; i < HI; i++) {
- Integer j = rnd.nextInt();
- assertEquals(j, m1.get(j));
- }
- }
-
- /**
- * java.util.HashMap#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.HashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer y = new Integer(9);
- Integer x = ((Integer) hm.remove(y.toString()));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(new Integer(9)));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(new Integer(0)));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * java.util.HashMap#size()
- */
- public void test_size() {
- // Test for method int java.util.HashMap.size()
- assertTrue("Returned incorrect size",
- hm.size() == (objArray.length + 2));
- }
-
- /**
- * java.util.HashMap#values()
- */
- public void test_values() {
- // Test for method java.util.Collection java.util.HashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- HashMap myHashMap = new HashMap();
- for (int i = 0; i < 100; i++)
- myHashMap.put(objArray2[i], objArray[i]);
- Collection values = myHashMap.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From HashMap.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myHashMap.containsValue(new Integer(0)));
-
- }
-
- static class ReusableKey {
- private int key = 0;
-
- public void setKey(int key) {
- this.key = key;
- }
-
- public int hashCode() {
- return key;
- }
-
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof ReusableKey)) {
- return false;
- }
- return key == ((ReusableKey) o).key;
- }
- }
- public void test_Map_Entry_hashCode() {
- //Related to HARMONY-403
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(10);
- Integer key = new Integer(1);
- Integer val = new Integer(2);
- map.put(key, val);
- int expected = key.hashCode() ^ val.hashCode();
- assertEquals(expected, map.hashCode());
- key = new Integer(4);
- val = new Integer(8);
- map.put(key, val);
- expected += key.hashCode() ^ val.hashCode();
- assertEquals(expected, map.hashCode());
- }
-
- class MockClonable implements Cloneable{
- public int i;
-
- public MockClonable(int i) {
- this.i = i;
- }
-
- @Override
- protected Object clone() throws CloneNotSupportedException {
- return new MockClonable(i);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- objArray2[i] = objArray[i].toString();
- }
-
- hm = new HashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- hm = null;
- objArray = null;
- objArray2 = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/HashSetTest.java b/luni/src/test/java/tests/api/java/util/HashSetTest.java
deleted file mode 100644
index e4a65b7..0000000
--- a/luni/src/test/java/tests/api/java/util/HashSetTest.java
+++ /dev/null
@@ -1,253 +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 tests.api.java.util;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.io.ObjectOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-public class HashSetTest extends junit.framework.TestCase {
-
- HashSet hs;
-
- Object[] objArray;
-
- /**
- * java.util.HashSet#HashSet()
- */
- public void test_Constructor() {
- // Test for method java.util.HashSet()
- HashSet hs2 = new HashSet();
- assertEquals("Created incorrect HashSet", 0, hs2.size());
- }
-
- /**
- * java.util.HashSet#HashSet(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.HashSet(int)
- HashSet hs2 = new HashSet(5);
- assertEquals("Created incorrect HashSet", 0, hs2.size());
- try {
- new HashSet(-1);
- } catch (IllegalArgumentException e) {
- return;
- }
- fail(
- "Failed to throw IllegalArgumentException for capacity < 0");
- }
-
- /**
- * java.util.HashSet#HashSet(int, float)
- */
- public void test_ConstructorIF() {
- // Test for method java.util.HashSet(int, float)
- HashSet hs2 = new HashSet(5, (float) 0.5);
- assertEquals("Created incorrect HashSet", 0, hs2.size());
- try {
- new HashSet(0, 0);
- } catch (IllegalArgumentException e) {
- return;
- }
- fail(
- "Failed to throw IllegalArgumentException for initial load factor <= 0");
- }
-
- /**
- * java.util.HashSet#HashSet(java.util.Collection)
- */
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.HashSet(java.util.Collection)
- HashSet hs2 = new HashSet(Arrays.asList(objArray));
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("HashSet does not contain correct elements", hs
- .contains(objArray[counter]));
- assertTrue("HashSet created from collection incorrect size",
- hs2.size() == objArray.length);
-
- try {
- new HashSet(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.HashSet#add(java.lang.Object)
- */
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.HashSet.add(java.lang.Object)
- int size = hs.size();
- hs.add(new Integer(8));
- assertTrue("Added element already contained by set", hs.size() == size);
- hs.add(new Integer(-9));
- assertTrue("Failed to increment set size after add",
- hs.size() == size + 1);
- assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
- }
-
- /**
- * java.util.HashSet#clear()
- */
- public void test_clear() {
- // Test for method void java.util.HashSet.clear()
- Set orgSet = (Set) hs.clone();
- hs.clear();
- Iterator i = orgSet.iterator();
- assertEquals("Returned non-zero size after clear", 0, hs.size());
- while (i.hasNext())
- assertTrue("Failed to clear set", !hs.contains(i.next()));
- }
-
- /**
- * java.util.HashSet#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.HashSet.clone()
- HashSet hs2 = (HashSet) hs.clone();
- assertTrue("clone returned an equivalent HashSet", hs != hs2);
- assertTrue("clone did not return an equal HashSet", hs.equals(hs2));
- }
-
- /**
- * java.util.HashSet#contains(java.lang.Object)
- */
- public void test_containsLjava_lang_Object() {
- // Test for method boolean java.util.HashSet.contains(java.lang.Object)
- assertTrue("Returned false for valid object", hs.contains(objArray[90]));
- assertTrue("Returned true for invalid Object", !hs
- .contains(new Object()));
-
- HashSet s = new HashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.contains(null));
- }
-
- /**
- * java.util.HashSet#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.HashSet.isEmpty()
- assertTrue("Empty set returned false", new HashSet().isEmpty());
- assertTrue("Non-empty set returned true", !hs.isEmpty());
- }
-
- /**
- * java.util.HashSet#iterator()
- */
- public void test_iterator() {
- // Test for method java.util.Iterator java.util.HashSet.iterator()
- Iterator i = hs.iterator();
- int x = 0;
- while (i.hasNext()) {
- assertTrue("Failed to iterate over all elements", hs.contains(i
- .next()));
- ++x;
- }
- assertTrue("Returned iteration of incorrect size", hs.size() == x);
-
- HashSet s = new HashSet();
- s.add(null);
- assertNull("Cannot handle null", s.iterator().next());
- }
-
- /**
- * java.util.HashSet#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.HashSet.remove(java.lang.Object)
- int size = hs.size();
- hs.remove(new Integer(98));
- assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
- assertTrue("Failed to decrement set size", hs.size() == size - 1);
-
- HashSet s = new HashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.remove(null));
- assertFalse(hs.remove(new Integer(-98)));
- }
-
- /**
- * java.util.HashSet#size()
- */
- public void test_size() {
- // Test for method int java.util.HashSet.size()
- assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
- hs.clear();
- assertEquals("Cleared set returned non-zero size", 0, hs.size());
- }
-
- /**
- * java.util.HashSet#SerializationTest
- */
- public void test_Serialization() throws Exception{
- HashSet<String> hs = new HashSet<String>();
- hs.add("hello");
- hs.add("world");
- SerializationTest.verifySelf(hs, comparator);
- SerializationTest.verifyGolden(this, hs, comparator);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[1000];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- }
-
- hs = new HashSet();
- for (int i = 0; i < objArray.length; i++) {
- hs.add(objArray[i]);
- }
-
- hs.add(null);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- hs = null;
- objArray = null;
- }
-
- private static final SerializationTest.SerializableAssert comparator = new
- SerializationTest.SerializableAssert() {
- public void assertDeserialized(Serializable initial, Serializable deserialized) {
- HashSet<String> initialHs = (HashSet<String>) initial;
- HashSet<String> deseriaHs = (HashSet<String>) deserialized;
- assertEquals("should be equal", initialHs.size(), deseriaHs.size());
- assertEquals("should be equal", initialHs, deseriaHs);
- }
-
- };
-}
diff --git a/luni/src/test/java/tests/api/java/util/HashtableTest.java b/luni/src/test/java/tests/api/java/util/HashtableTest.java
deleted file mode 100644
index 9c97c7b..0000000
--- a/luni/src/test/java/tests/api/java/util/HashtableTest.java
+++ /dev/null
@@ -1,838 +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 tests.api.java.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.Vector;
-import java.util.Collections;
-
-import tests.api.java.util.HashMapTest.ReusableKey;
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-public class HashtableTest extends junit.framework.TestCase {
-
- private Hashtable ht10;
-
- private Hashtable ht100;
-
- private Hashtable htfull;
-
- private Vector keyVector;
-
- private Vector elmVector;
-
- private String h10sVal;
-
- /**
- * java.util.Hashtable#Hashtable()
- */
- public void test_Constructor() {
- // Test for method java.util.Hashtable()
- new Support_MapTest2(new Hashtable()).runTest();
-
- Hashtable h = new Hashtable();
-
- assertEquals("Created incorrect hashtable", 0, h.size());
- }
-
- /**
- * java.util.Hashtable#Hashtable(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.Hashtable(int)
- Hashtable h = new Hashtable(9);
-
- assertEquals("Created incorrect hashtable", 0, h.size());
-
- Hashtable empty = new Hashtable(0);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new Hashtable(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#Hashtable(int, float)
- */
- public void test_ConstructorIF() {
- // Test for method java.util.Hashtable(int, float)
- Hashtable h = new java.util.Hashtable(10, 0.5f);
- assertEquals("Created incorrect hashtable", 0, h.size());
-
- Hashtable empty = new Hashtable(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new Hashtable(-1, 0.75f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new Hashtable(0, -0.75f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#Hashtable(java.util.Map)
- */
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.Hashtable(java.util.Map)
- Map map = new TreeMap();
- Object firstVal = "Gabba";
- Object secondVal = new Integer(5);
- map.put("Gah", firstVal);
- map.put("Ooga", secondVal);
- Hashtable ht = new Hashtable(map);
- assertTrue("a) Incorrect Hashtable constructed",
- ht.get("Gah") == firstVal);
- assertTrue("b) Incorrect Hashtable constructed",
- ht.get("Ooga") == secondVal);
-
- try {
- new Hashtable(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#Hashtable(java.util.Map)
- */
- public void test_ConversionConstructorNullValue() {
- Map<String, Void> map = Collections.singletonMap("Dog", null);
- try {
- new Hashtable<String, Void>(map);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
- /**
- * java.util.Hashtable#clear()
- */
- public void test_clear() {
- // Test for method void java.util.Hashtable.clear()
- Hashtable h = hashtableClone(htfull);
- h.clear();
- assertEquals("Hashtable was not cleared", 0, h.size());
- Enumeration el = h.elements();
- Enumeration keys = h.keys();
- assertTrue("Hashtable improperly cleared", !el.hasMoreElements()
- && !(keys.hasMoreElements()));
- }
-
- /**
- * java.util.Hashtable#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.Hashtable.clone()
-
- Hashtable h = (Hashtable) htfull.clone();
- assertTrue("Clone different size than original", h.size() == htfull
- .size());
-
- Enumeration org = htfull.keys();
- Enumeration cpy = h.keys();
-
- String okey, ckey;
- while (org.hasMoreElements()) {
- assertTrue("Key comparison failed", (okey = (String) org
- .nextElement()).equals(ckey = (String) cpy.nextElement()));
- assertTrue("Value comparison failed", ((String) htfull.get(okey))
- .equals((String) h.get(ckey)));
- }
- assertTrue("Copy has more keys than original", !cpy.hasMoreElements());
- }
-
- /**
- * java.util.Hashtable#contains(java.lang.Object)
- */
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.Hashtable.contains(java.lang.Object)
- assertTrue("Element not found", ht10.contains("Val 7"));
- assertTrue("Invalid element found", !ht10.contains("ZZZZZZZZZZZZZZZZ"));
-
- try {
- ht10.contains(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#containsKey(java.lang.Object)
- */
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.Hashtable.containsKey(java.lang.Object)
-
- assertTrue("Failed to find key", htfull.containsKey("FKey 4"));
- assertTrue("Failed to find key", !htfull.containsKey("FKey 99"));
-
- try {
- htfull.containsKey(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#containsValue(java.lang.Object)
- */
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.Hashtable.containsValue(java.lang.Object)
- Enumeration e = elmVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned false for valid value", ht10.containsValue(e
- .nextElement()));
- assertTrue("Returned true for invalid value", !ht10
- .containsValue(new Object()));
-
- try {
- ht10.containsValue(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#elements()
- */
- public void test_elements() {
- // Test for method java.util.Enumeration java.util.Hashtable.elements()
- Enumeration elms = ht10.elements();
- int i = 0;
- while (elms.hasMoreElements()) {
- String s = (String) elms.nextElement();
- assertTrue("Missing key from enumeration", elmVector.contains(s));
- ++i;
- }
-
- assertEquals("All keys not retrieved", 10, ht10.size());
- }
-
-// BEGIN android-removed
-// implementation dependent
-// /**
-// * java.util.Hashtable#elements()
-// */
-// public void test_elements_subtest0() {
-// // this is the reference implementation behavior
-// final Hashtable ht = new Hashtable(7);
-// ht.put("1", "a");
-// // these three elements hash to the same bucket in a 7 element Hashtable
-// ht.put("2", "b");
-// ht.put("9", "c");
-// ht.put("12", "d");
-// // Hashtable looks like:
-// // 0: "1"
-// // 1: "12" -> "9" -> "2"
-// Enumeration en = ht.elements();
-// // cache the first entry
-// en.hasMoreElements();
-// ht.remove("12");
-// ht.remove("9");
-// boolean exception = false;
-// try {
-// // cached "12"
-// Object result = en.nextElement();
-// assertNull("unexpected: " + result, result);
-// // next is removed "9"
-// result = en.nextElement();
-// assertNull("unexpected: " + result, result);
-// result = en.nextElement();
-// assertTrue("unexpected: " + result, "b".equals(result));
-// } catch (NoSuchElementException e) {
-// exception = true;
-// }
-// assertTrue("unexpected NoSuchElementException", !exception);
-// }
-// END android-removed
-
- /**
- * java.util.Hashtable#entrySet()
- */
- public void test_entrySet() {
- // Test for method java.util.Set java.util.Hashtable.entrySet()
- Set s = ht10.entrySet();
- Set s2 = new HashSet();
- Iterator i = s.iterator();
- while (i.hasNext())
- s2.add(((Map.Entry) i.next()).getValue());
- Enumeration e = elmVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned incorrect entry set", s2.contains(e
- .nextElement()));
-// BEGIN android-removed
-// implementation dependent
-// assertEquals("Not synchronized",
-// "java.util.Collections$SynchronizedSet", s.getClass().getName());
-// END android-removed
-
- boolean exception = false;
- try {
- ((Map.Entry) ht10.entrySet().iterator().next()).setValue(null);
- } catch (NullPointerException e1) {
- exception = true;
- }
- assertTrue(
- "Should not be able to assign null to a Hashtable entrySet() Map.Entry",
- exception);
- }
-
- /**
- * java.util.Hashtable#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Hashtable.equals(java.lang.Object)
- Hashtable h = hashtableClone(ht10);
- assertTrue("Returned false for equal tables", ht10.equals(h));
- assertTrue("Returned true for unequal tables", !ht10.equals(htfull));
- }
-
- /**
- * java.util.Hashtable#get(java.lang.Object)
- */
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.Hashtable.get(java.lang.Object)
- Hashtable h = hashtableClone(htfull);
- assertEquals("Could not retrieve element", "FVal 2", ((String) h.get("FKey 2"))
- );
-
-// BEGIN android-removed
-// implementation dependent
-// // Regression for HARMONY-262
-// ReusableKey k = new ReusableKey();
-// Hashtable h2 = new Hashtable();
-// k.setKey(1);
-// h2.put(k, "value1");
-//
-// k.setKey(13);
-// assertNull(h2.get(k));
-//
-// k.setKey(12);
-// assertNull(h2.get(k));
-//
-// try {
-// h2.get(null);
-// fail("NullPointerException expected");
-// } catch (NullPointerException e) {
-// //expected
-// }
-// END android-removed
- }
-
- /**
- * java.util.Hashtable#hashCode()
- */
- public void test_hashCode() {
- // Test for method int java.util.Hashtable.hashCode()
- Set entrySet = ht10.entrySet();
- Iterator iterator = entrySet.iterator();
- int expectedHash;
- for (expectedHash = 0; iterator.hasNext(); expectedHash += iterator
- .next().hashCode())
- ;
- assertTrue("Incorrect hashCode returned. Wanted: " + expectedHash
- + " got: " + ht10.hashCode(), expectedHash == ht10.hashCode());
- }
-
- /**
- * java.util.Hashtable#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.Hashtable.isEmpty()
-
- assertTrue("isEmpty returned incorrect value", !ht10.isEmpty());
- assertTrue("isEmpty returned incorrect value",
- new java.util.Hashtable().isEmpty());
-
- final Hashtable ht = new Hashtable();
- ht.put("0", "");
- Thread t1 = new Thread() {
- public void run() {
- while (!ht.isEmpty())
- ;
- ht.put("final", "");
- }
- };
- t1.start();
- for (int i = 1; i < 10000; i++) {
- synchronized (ht) {
- ht.remove(String.valueOf(i - 1));
- ht.put(String.valueOf(i), "");
- }
- int size;
- if ((size = ht.size()) != 1) {
- String result = "Size is not 1: " + size + " " + ht;
- // terminate the thread
- ht.clear();
- fail(result);
- }
- }
- // terminate the thread
- ht.clear();
- }
-
- /**
- * java.util.Hashtable#keys()
- */
- public void test_keys() {
- // Test for method java.util.Enumeration java.util.Hashtable.keys()
-
- Enumeration keys = ht10.keys();
- int i = 0;
- while (keys.hasMoreElements()) {
- String s = (String) keys.nextElement();
- assertTrue("Missing key from enumeration", keyVector.contains(s));
- ++i;
- }
-
- assertEquals("All keys not retrieved", 10, ht10.size());
- }
-
- /**
- * java.util.Hashtable#keys()
- */
- public void test_keys_subtest0() {
- // this is the reference implementation behavior
- final Hashtable ht = new Hashtable(3);
- ht.put("initial", "");
- Enumeration en = ht.keys();
- en.hasMoreElements();
- ht.remove("initial");
- boolean exception = false;
- try {
- Object result = en.nextElement();
- assertTrue("unexpected: " + result, "initial".equals(result));
- } catch (NoSuchElementException e) {
- exception = true;
- }
- assertTrue("unexpected NoSuchElementException", !exception);
- }
-
- /**
- * java.util.Hashtable#keySet()
- */
- public void test_keySet() {
- // Test for method java.util.Set java.util.Hashtable.keySet()
- Set s = ht10.keySet();
- Enumeration e = keyVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned incorrect key set", s
- .contains(e.nextElement()));
-
-// BEGIN android-removed
-// implementation dependent
-// assertEquals("Not synchronized",
-// "java.util.Collections$SynchronizedSet", s.getClass().getName());
-// END android-removed
-
- Map map = new Hashtable(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new Hashtable(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * java.util.Hashtable#keySet()
- */
- public void test_keySet_subtest0() {
- Set s1 = ht10.keySet();
- assertTrue("should contain key", s1.remove("Key 0"));
- assertTrue("should not contain key", !s1.remove("Key 0"));
-
- final int iterations = 10000;
- final Hashtable ht = new Hashtable();
- Thread t1 = new Thread() {
- public void run() {
- for (int i = 0; i < iterations; i++) {
- ht.put(String.valueOf(i), "");
- ht.remove(String.valueOf(i));
- }
- }
- };
- t1.start();
- Set set = ht.keySet();
- for (int i = 0; i < iterations; i++) {
- Iterator it = set.iterator();
- try {
- it.next();
- it.remove();
- int size;
- // ensure removing with the iterator doesn't corrupt the
- // Hashtable
- if ((size = ht.size()) < 0) {
- fail("invalid size: " + size);
- }
- } catch (NoSuchElementException e) {
- } catch (ConcurrentModificationException e) {
- }
- }
- }
-
-// BEGIN android-removed
-// implementation dependent
-// /**
-// * java.util.Hashtable#keySet()
-// */
-// public void test_keySet_subtest1() {
-// // this is the reference implementation behavior
-// final Hashtable ht = new Hashtable(7);
-// ht.put("1", "a");
-// // these three elements hash to the same bucket in a 7 element Hashtable
-// ht.put("2", "b");
-// ht.put("9", "c");
-// ht.put("12", "d");
-// // Hashtable looks like:
-// // 0: "1"
-// // 1: "12" -> "9" -> "2"
-// Enumeration en = ht.elements();
-// // cache the first entry
-// en.hasMoreElements();
-// Iterator it = ht.keySet().iterator();
-// // this is mostly a copy of the test in test_elements_subtest0()
-// // test removing with the iterator does not null the values
-// while (it.hasNext()) {
-// String key = (String) it.next();
-// if ("12".equals(key) || "9".equals(key)) {
-// it.remove();
-// }
-// }
-// it.remove();
-// boolean exception = false;
-// try {
-// // cached "12"
-// Object result = en.nextElement();
-// assertTrue("unexpected: " + result, "d".equals(result));
-// // next is removed "9"
-// result = en.nextElement();
-// assertTrue("unexpected: " + result, "c".equals(result));
-// result = en.nextElement();
-// assertTrue("unexpected: " + result, "b".equals(result));
-// } catch (NoSuchElementException e) {
-// exception = true;
-// }
-// assertTrue("unexpected NoSuchElementException", !exception);
-// }
-// END android-removed
-
- /**
- * java.util.Hashtable#put(java.lang.Object, java.lang.Object)
- */
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.Hashtable.put(java.lang.Object, java.lang.Object)
- Hashtable h = hashtableClone(ht100);
- Integer key = new Integer(100);
- h.put("Value 100", key);
- assertTrue("Key/Value not inserted", h.size() == 1 && (h.contains(key)));
-
- // Put into "full" table
- h = hashtableClone(htfull);
- h.put("Value 100", key);
- assertTrue("Key/Value not inserted into full table", h.size() == 8
- && (h.contains(key)));
-
- try {
- h.put(null, key);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- h.put("Value 100", null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#putAll(java.util.Map)
- */
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.Hashtable.putAll(java.util.Map)
- Hashtable h = new Hashtable();
- h.putAll(ht10);
- Enumeration e = keyVector.elements();
- while (e.hasMoreElements()) {
- Object x = e.nextElement();
- assertTrue("Failed to put all elements", h.get(x).equals(
- ht10.get(x)));
- }
-
- try {
- h.putAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.Hashtable.remove(java.lang.Object)
- Hashtable h = hashtableClone(htfull);
- Object k = h.remove("FKey 0");
- assertTrue("Remove failed", !h.containsKey("FKey 0") || k == null);
- assertNull(h.remove("FKey 0"));
-
- try {
- h.remove(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Hashtable#size()
- */
- public void test_size() {
- // Test for method int java.util.Hashtable.size()
- assertTrue("Returned invalid size", ht10.size() == 10
- && (ht100.size() == 0));
-
- final Hashtable ht = new Hashtable();
- ht.put("0", "");
- Thread t1 = new Thread() {
- public void run() {
- while (ht.size() > 0)
- ;
- ht.put("final", "");
- }
- };
- t1.start();
- for (int i = 1; i < 10000; i++) {
- synchronized (ht) {
- ht.remove(String.valueOf(i - 1));
- ht.put(String.valueOf(i), "");
- }
- int size;
- if ((size = ht.size()) != 1) {
- String result = "Size is not 1: " + size + " " + ht;
- // terminate the thread
- ht.clear();
- fail(result);
- }
- }
- // terminate the thread
- ht.clear();
- }
-
- /**
- * java.util.Hashtable#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.util.Hashtable.toString()
- Hashtable h = new Hashtable();
- assertEquals("Incorrect toString for Empty table",
- "{}", h.toString());
-
- h.put("one", "1");
- h.put("two", h);
- h.put(h, "3");
- h.put(h, h);
- String result = h.toString();
- assertTrue("should contain self ref", result.indexOf("(this") > -1);
- }
-
- /**
- * java.util.Hashtable#values()
- */
- public void test_values() {
- // Test for method java.util.Collection java.util.Hashtable.values()
- Collection c = ht10.values();
- Enumeration e = elmVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned incorrect values", c.contains(e.nextElement()));
-
-// BEGIN android-removed
-// implementation dependent
-// assertEquals("Not synchronized",
-// "java.util.Collections$SynchronizedCollection", c.getClass().getName());
-// END android-removed
-
- Hashtable myHashtable = new Hashtable();
- for (int i = 0; i < 100; i++)
- myHashtable.put(new Integer(i), new Integer(i));
- Collection values = myHashtable.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From Hashtable.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myHashtable.containsValue(new Integer(0)));
- }
-
- /**
- * Regression Test for JIRA 2181
- */
- public void test_entrySet_remove()
- {
- Hashtable<String,String> hashtable = new Hashtable<String,String>();
- hashtable.put("my.nonexistent.prop", "AAA");
- hashtable.put( "parse.error", "BBB" );
- Iterator<Map.Entry<String,String>> iterator =
- hashtable.entrySet().iterator();
- while(iterator.hasNext())
- {
- Map.Entry entry = iterator.next();
- final Object value = entry.getValue();
- if(value.equals("AAA"))
- {
- iterator.remove();
- }
- }
- assertFalse(hashtable.containsKey("my.nonexistent.prop"));
- }
-
- class Mock_Hashtable extends Hashtable {
- boolean flag = false;
-
- public Mock_Hashtable(int i) {
- super(i);
- }
-
- @Override
- protected void rehash() {
- flag = true;
- super.rehash();
- }
-
- public boolean isRehashed() {
- return flag;
- }
- }
-
- public void test_rehash() {
- Mock_Hashtable mht = new Mock_Hashtable(5);
-
- assertFalse(mht.isRehashed());
- for(int i = 0; i < 10; i++) {
- mht.put(i, "New value");
- }
- assertTrue(mht.isRehashed());
- }
-
- protected Hashtable hashtableClone(Hashtable s) {
- return (Hashtable) s.clone();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- ht10 = new Hashtable(10);
- ht100 = new Hashtable(100);
- htfull = new Hashtable(10);
- keyVector = new Vector(10);
- elmVector = new Vector(10);
-
- for (int i = 0; i < 10; i++) {
- ht10.put("Key " + i, "Val " + i);
- keyVector.addElement("Key " + i);
- elmVector.addElement("Val " + i);
- }
-
- for (int i = 0; i < 7; i++)
- htfull.put("FKey " + i, "FVal " + i);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- ht10 = null;
- ht100 = null;
- htfull = null;
- keyVector = null;
- elmVector = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java b/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java
deleted file mode 100644
index 3bf1257..0000000
--- a/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java
+++ /dev/null
@@ -1,494 +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 tests.api.java.util;
-
-import java.io.Serializable;
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import tests.support.Support_MapTest2;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-public class IdentityHashMapTest extends junit.framework.TestCase {
- private static final String ID = "hello";
-
- class MockMap extends AbstractMap {
- public Set entrySet() {
- return null;
- }
- public int size(){
- return 0;
- }
- }
- /*
- * TODO: change all the statements testing the keys and values with equals()
- * method to check for reference equality instead
- */
-
- IdentityHashMap hm;
-
- final static int hmSize = 1000;
-
- Object[] objArray;
-
- Object[] objArray2;
-
- /**
- * java.util.IdentityHashMap#IdentityHashMap()
- */
- public void test_Constructor() {
- // Test for method java.util.IdentityHashMap()
- new Support_MapTest2(new IdentityHashMap()).runTest();
-
- IdentityHashMap hm2 = new IdentityHashMap();
- assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
- }
-
- /**
- * java.util.IdentityHashMap#IdentityHashMap(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.IdentityHashMap(int)
- IdentityHashMap hm2 = new IdentityHashMap(5);
- assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
- try {
- new IdentityHashMap(-1);
- fail("Failed to throw IllegalArgumentException for initial capacity < 0");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- IdentityHashMap empty = new IdentityHashMap(0);
- assertNull("Empty IdentityHashMap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * java.util.IdentityHashMap#IdentityHashMap(java.util.Map)
- */
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.IdentityHashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- IdentityHashMap hm2 = new IdentityHashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct IdentityHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- Map mockMap = new MockMap();
- hm2 = new IdentityHashMap(mockMap);
- assertEquals("Size should be 0", 0, hm2.size());
-
- try {
- new IdentityHashMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.IdentityHashMap#clear()
- */
- public void test_clear() {
- // Test for method void java.util.IdentityHashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * java.util.IdentityHashMap#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.IdentityHashMap.clone()
- IdentityHashMap hm2 = (IdentityHashMap) hm.clone();
- assertTrue("Clone answered equivalent IdentityHashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal IdentityHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- IdentityHashMap map = new IdentityHashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
- }
-
- /**
- * java.util.IdentityHashMap#containsKey(java.lang.Object)
- */
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.IdentityHashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm
- .containsKey(objArray2[23]));
- assertTrue("Returned true for copy of valid key", !hm
- .containsKey(new Integer(23).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * java.util.IdentityHashMap#containsValue(java.lang.Object)
- */
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.IdentityHashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(objArray[19]));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * java.util.IdentityHashMap#entrySet()
- */
- public void test_entrySet() {
- // Test for method java.util.Set java.util.IdentityHashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- /**
- * java.util.IdentityHashMap#get(java.lang.Object)
- */
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.IdentityHashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
- );
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
- }
-
- /**
- * java.util.IdentityHashMap#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.IdentityHashMap.isEmpty()
- assertTrue("Returned false for new map", new IdentityHashMap()
- .isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * java.util.IdentityHashMap#keySet()
- */
- public void test_keySet() {
- // Test for method java.util.Set java.util.IdentityHashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++) {
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray2[i]));
- }
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new IdentityHashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new IdentityHashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
- */
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.IdentityHashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- IdentityHashMap m = new IdentityHashMap();
- Short s0 = new Short((short) 0);
- m.put(s0, "short");
- m.put(null, "test");
- Integer i0 = new Integer(0);
- m.put(i0, "int");
- assertEquals("Failed adding to bucket containing null",
- "short", m.get(s0));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(i0)
- );
- }
-
- /**
- * java.util.IdentityHashMap#putAll(java.util.Map)
- */
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.IdentityHashMap.putAll(java.util.Map)
- IdentityHashMap hm2 = new IdentityHashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(objArray2[i])
- .equals((new Integer(i))));
-
- hm2 = new IdentityHashMap();
- Map mockMap = new MockMap();
- hm2.putAll(mockMap);
- assertEquals("Size should be 0", 0, hm2.size());
-
- try {
- hm2.putAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.IdentityHashMap#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.IdentityHashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer x = ((Integer) hm.remove(objArray2[9]));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(objArray2[9]));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(objArray[0]));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * java.util.IdentityHashMap#size()
- */
- public void test_size() {
- // Test for method int java.util.IdentityHashMap.size()
- assertEquals("Returned incorrect size, ", (objArray.length + 2), hm
- .size());
- }
-
- /**
- * java.util.IdentityHashMap#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- IdentityHashMap mapOne = new IdentityHashMap();
- IdentityHashMap mapTwo = new IdentityHashMap();
- IdentityHashMap mapThree = new IdentityHashMap();
- IdentityHashMap mapFour = new IdentityHashMap();
-
- String one = "one";
- String alsoOne = new String(one); // use the new operator to ensure a
- // new reference is constructed
- String two = "two";
- String alsoTwo = new String(two); // use the new operator to ensure a
- // new reference is constructed
-
- mapOne.put(one, two);
- mapFour.put(one, two);
-
- // these two are not equal to the above two
- mapTwo.put(alsoOne, two);
- mapThree.put(one, alsoTwo);
-
- assertEquals("failure of equality of IdentityHashMaps", mapOne, mapFour);
- assertTrue("failure of non-equality of IdentityHashMaps one and two",
- !mapOne.equals(mapTwo));
- assertTrue("failure of non-equality of IdentityHashMaps one and three",
- !mapOne.equals(mapThree));
- assertTrue("failure of non-equality of IdentityHashMaps two and three",
- !mapTwo.equals(mapThree));
-
- HashMap hashMapTwo = new HashMap();
- HashMap hashMapThree = new HashMap();
- hashMapTwo.put(alsoOne, two);
- hashMapThree.put(one, alsoTwo);
-
- assertTrue(
- "failure of non-equality of IdentityHashMaps one and Hashmap two",
- !mapOne.equals(hashMapTwo));
- assertTrue(
- "failure of non-equality of IdentityHashMaps one and Hashmap three",
- !mapOne.equals(hashMapThree));
- }
-
- /**
- * java.util.IdentityHashMap#values()
- */
- public void test_values() {
- // Test for method java.util.Collection
- // java.util.IdentityHashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- IdentityHashMap myIdentityHashMap = new IdentityHashMap();
- for (int i = 0; i < 100; i++)
- myIdentityHashMap.put(objArray2[i], objArray[i]);
- Collection values = myIdentityHashMap.values();
- values.remove(objArray[0]);
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myIdentityHashMap.containsValue(objArray2[0]));
-
- }
-
- /**
- * java.util.IdentityHashMap#Serialization()
- */
- public void test_Serialization() throws Exception {
- IdentityHashMap<String, String> map = new IdentityHashMap<String, String>();
- map.put(ID, "world");
- // BEGIN android-added
- // Regression test for null key in serialized IdentityHashMap (1178549)
- // Together with this change the IdentityHashMap.golden.ser resource
- // was replaced by a version that contains a map with a null key.
- map.put(null, "null");
- // END android-added
- SerializationTest.verifySelf(map, comparator);
- SerializationTest.verifyGolden(this, map, comparator);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- // android-changed: the containsKey test requires unique strings.
- objArray2[i] = new String(objArray[i].toString());
- }
-
- hm = new IdentityHashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- objArray = null;
- objArray2 = null;
- hm = null;
- }
-
- private static final SerializationTest.SerializableAssert comparator = new
- SerializationTest.SerializableAssert() {
-
- public void assertDeserialized(Serializable initial, Serializable deserialized) {
- IdentityHashMap<String, String> initialMap = (IdentityHashMap<String, String>) initial;
- IdentityHashMap<String, String> deseriaMap = (IdentityHashMap<String, String>) deserialized;
- assertEquals("should be equal", initialMap.size(), deseriaMap.size());
- }
-
- };
-}
diff --git a/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java b/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java
deleted file mode 100644
index 0b144a4..0000000
--- a/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java
+++ /dev/null
@@ -1,39 +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 tests.api.java.util;
-
-import java.io.NotSerializableException;
-import java.util.InvalidPropertiesFormatException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-public class InvalidPropertiesFormatExceptionTest extends
- junit.framework.TestCase {
-
- /**
- * java.util.InvalidPropertiesFormatException#SerializationTest()
- */
- public void test_Serialization() throws Exception {
- InvalidPropertiesFormatException ipfe = new InvalidPropertiesFormatException(
- "Hey, this is InvalidPropertiesFormatException");
- try {
- SerializationTest.verifySelf(ipfe);
- } catch (NotSerializableException e) {
- // expected
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java b/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java
deleted file mode 100644
index eff9493..0000000
--- a/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java
+++ /dev/null
@@ -1,736 +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 tests.api.java.util;
-
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-/**
- * java.util.LinkedHashMap
- */
-public class LinkedHashMapTest extends junit.framework.TestCase {
-
- LinkedHashMap hm;
-
- final static int hmSize = 1000;
-
- Object[] objArray;
-
- Object[] objArray2;
-
- static final class CacheMap extends LinkedHashMap {
- protected boolean removeEldestEntry(Map.Entry e) {
- return size() > 5;
- }
- }
-
- private static class MockMapNull extends AbstractMap {
- @Override
- public Set entrySet() {
- return null;
- }
-
- @Override
- public int size() {
- return 10;
- }
- }
-
- /**
- * java.util.LinkedHashMap#LinkedHashMap()
- */
- public void test_Constructor() {
- // Test for method java.util.LinkedHashMap()
- new Support_MapTest2(new LinkedHashMap()).runTest();
-
- LinkedHashMap hm2 = new LinkedHashMap();
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- }
-
- /**
- * java.util.LinkedHashMap#LinkedHashMap(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.LinkedHashMap(int)
- LinkedHashMap hm2 = new LinkedHashMap(5);
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- try {
- new LinkedHashMap(-1);
- fail("Failed to throw IllegalArgumentException for initial " +
- "capacity < 0");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- LinkedHashMap empty = new LinkedHashMap(0);
- assertNull("Empty LinkedHashMap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * java.util.LinkedHashMap#LinkedHashMap(int, float)
- */
- public void test_ConstructorIF() {
- // Test for method java.util.LinkedHashMap(int, float)
- LinkedHashMap hm2 = new LinkedHashMap(5, (float) 0.5);
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- try {
- new LinkedHashMap(0, 0);
- fail("Failed to throw IllegalArgumentException for initial " +
- "load factor <= 0");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- LinkedHashMap empty = new LinkedHashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * java.util.LinkedHashMap#LinkedHashMap(java.util.Map)
- */
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.LinkedHashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- LinkedHashMap hm2 = new LinkedHashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct LinkedHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
- }
-
- /**
- * java.util.LinkedHashMap#get(java.lang.Object)
- */
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
- );
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
- }
-
- /**
- * java.util.LinkedHashMap#put(java.lang.Object, java.lang.Object)
- */
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(new Short((short) 0), "short");
- m.put(null, "test");
- m.put(new Integer(0), "int");
- assertEquals("Failed adding to bucket containing null", "short", m.get(
- new Short((short) 0)));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(
- new Integer(0)));
- }
-
-
- public void test_putPresent() {
- Map<String, String> m = new LinkedHashMap<String, String>(8, .75f, true);
- m.put("KEY", "VALUE");
- m.put("WOMBAT", "COMBAT");
- m.put("KEY", "VALUE");
- Map.Entry newest = null;
- for (Map.Entry<String, String> e : m.entrySet()) {
- newest = e;
- }
- assertEquals("KEY", newest.getKey());
- assertEquals("VALUE", newest.getValue());
- }
-
- /**
- * java.util.LinkedHashMap#putAll(java.util.Map)
- */
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.LinkedHashMap.putAll(java.util.Map)
- LinkedHashMap hm2 = new LinkedHashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(
- new Integer(i).toString()).equals((new Integer(i))));
- }
-
- /**
- * java.util.LinkedHashMap#putAll(java.util.Map)
- */
- public void test_putAll_Ljava_util_Map_Null() {
- LinkedHashMap linkedHashMap = new LinkedHashMap();
- try {
- linkedHashMap.putAll(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
-
- try {
- linkedHashMap = new LinkedHashMap(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
- }
-
- /**
- * java.util.LinkedHashMap#entrySet()
- */
- public void test_entrySet() {
- // Test for method java.util.Set java.util.LinkedHashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- public void test_entrySetRemove() {
- entrySetRemoveHelper("military", "intelligence");
- entrySetRemoveHelper(null, "hypothesis");
- }
- private void entrySetRemoveHelper(String key, String value) {
- Map<String, String> m1 = new LinkedHashMap<String, String>();
- m1.put(key, value);
- m1.put("jumbo", "shrimp");
- LinkedHashMap<String, String> m2 = new LinkedHashMap<String, String>(m1);
- Set<Map.Entry<String, String>> s1 = m1.entrySet();
- s1.remove(m2.entrySet().iterator().next());
- assertEquals("jumbo", s1.iterator().next().getKey());
- }
-
- /**
- * java.util.LinkedHashMap#keySet()
- */
- public void test_keySet() {
- // Test for method java.util.Set java.util.LinkedHashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray[i].toString()));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new LinkedHashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new LinkedHashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * java.util.LinkedHashMap#values()
- */
- public void test_values() {
- // Test for method java.util.Collection java.util.LinkedHashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- LinkedHashMap myLinkedHashMap = new LinkedHashMap();
- for (int i = 0; i < 100; i++)
- myLinkedHashMap.put(objArray2[i], objArray[i]);
- Collection values = myLinkedHashMap.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From LinkedHashMap.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myLinkedHashMap.containsValue(new Integer(0)));
-
- }
-
- /**
- * java.util.LinkedHashMap#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer y = new Integer(9);
- Integer x = ((Integer) hm.remove(y.toString()));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(new Integer(9)));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(new Integer(0)));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * java.util.LinkedHashMap#clear()
- */
- public void test_clear() {
- // Test for method void java.util.LinkedHashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * java.util.LinkedHashMap#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedHashMap.clone()
- LinkedHashMap hm2 = (LinkedHashMap) hm.clone();
- assertTrue("Clone answered equivalent LinkedHashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal LinkedHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- LinkedHashMap map = new LinkedHashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
-
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
- }
-
- /**
- * java.util.LinkedHashMap#clone()
- */
- public void test_clone_ordered() {
- // Test for method java.lang.Object java.util.LinkedHashMap.clone()
- LinkedHashMap<String, String> hm1 = new LinkedHashMap<String, String>(10, 0.75f, true);
- hm1.put("a", "a");
- hm1.put("b", "b");
- hm1.put("c", "c");
- LinkedHashMap<String, String> hm2 = (LinkedHashMap<String, String>) hm1.clone();
- hm1.get("a");
-
- Map.Entry<String, String>[] set = new Map.Entry[3];
- Iterator<Map.Entry<String,String>> iterator = hm1.entrySet().iterator();
-
- assertEquals("b", iterator.next().getKey());
- assertEquals("c", iterator.next().getKey());
- assertEquals("a", iterator.next().getKey());
-
- iterator = hm2.entrySet().iterator();
- assertEquals("a", iterator.next().getKey());
- assertEquals("b", iterator.next().getKey());
- assertEquals("c", iterator.next().getKey());
- }
-
- // regresion test for HARMONY-4603
- public void test_clone_Mock() {
- LinkedHashMap hashMap = new MockMap();
- String value = "value a";
- hashMap.put("key", value);
- MockMap cloneMap = (MockMap) hashMap.clone();
- assertEquals(value, cloneMap.get("key"));
- assertEquals(hashMap, cloneMap);
- assertEquals(1, cloneMap.num);
-
- hashMap.put("key", "value b");
- assertFalse(hashMap.equals(cloneMap));
- }
-
- class MockMap extends LinkedHashMap {
- int num;
-
- public Object put(Object k, Object v) {
- num++;
- return super.put(k, v);
- }
-
- protected boolean removeEldestEntry(Map.Entry e) {
- return num > 1;
- }
- }
-
- /**
- * put/get interaction in access-order map where removeEldest
- * returns true.
- */
- public void test_removeEldestFromSameBucketAsNewEntry() {
- LinkedHashMap<String, String> map
- = new LinkedHashMap<String, String>(6, 0.75F, true) {
- @Override
- protected boolean removeEldestEntry(Entry<String, String> e) {
- return true;
- }
- };
- map.put("N", "E");
- map.put("F", "I");
- assertEquals(null, map.get("N"));
- }
-
- /**
- * java.util.LinkedHashMap#containsKey(java.lang.Object)
- */
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm.containsKey(new Integer(
- 876).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * java.util.LinkedHashMap#containsValue(java.lang.Object)
- */
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(new Integer(875)));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * java.util.LinkedHashMap#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.LinkedHashMap.isEmpty()
- assertTrue("Returned false for new map", new LinkedHashMap().isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * java.util.LinkedHashMap#size()
- */
- public void test_size() {
- // Test for method int java.util.LinkedHashMap.size()
- assertTrue("Returned incorrect size",
- hm.size() == (objArray.length + 2));
- }
-
- /**
- * java.util.LinkedHashMap#entrySet()
- */
- public void test_ordered_entrySet() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, ii.toString());
- }
-
- Set s1 = lhm.entrySet();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Map.Entry m = (Map.Entry) it1.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, ii.toString());
- }
-
- Set s3 = lruhm.entrySet();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size 2", lruhm.size() == s3
- .size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Map.Entry m = (Map.Entry) it3.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 2", jj.intValue() == i);
- }
-
- /* fetch the even numbered entries to affect traversal order */
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- String ii = (String) lruhm.get(new Integer(i));
- p = p + Integer.parseInt(ii);
- }
- assertEquals("invalid sum of even numbers", 2450, p);
-
- Set s2 = lruhm.entrySet();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size 3", lruhm.size() == s2
- .size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Map.Entry m = (Map.Entry) it2.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 3", jj.intValue() == i);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Map.Entry m = (Map.Entry) it2.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 4", jj.intValue() == i);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * java.util.LinkedHashMap#keySet()
- */
- public void test_ordered_keySet() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, ii.toString());
- }
-
- Set s1 = lhm.keySet();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, ii.toString());
- }
-
- Set s3 = lruhm.keySet();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Integer jj = (Integer) it3.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
-
- /* fetch the even numbered entries to affect traversal order */
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- String ii = (String) lruhm.get(new Integer(i));
- p = p + Integer.parseInt(ii);
- }
- assertEquals("invalid sum of even numbers", 2450, p);
-
- Set s2 = lruhm.keySet();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * java.util.LinkedHashMap#values()
- */
- public void test_ordered_values() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, new Integer(i * 2));
- }
-
- Collection s1 = lhm.values();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, new Integer(i * 2));
- }
-
- Collection s3 = lruhm.values();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Integer jj = (Integer) it3.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
-
- // fetch the even numbered entries to affect traversal order
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- Integer ii = (Integer) lruhm.get(new Integer(i));
- p = p + ii.intValue();
- }
- assertTrue("invalid sum of even numbers", p == 2450 * 2);
-
- Collection s2 = lruhm.values();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * java.util.LinkedHashMap#removeEldestEntry(java.util.Map$Entry)
- */
- public void test_remove_eldest() {
- int i;
- int sz = 10;
- CacheMap lhm = new CacheMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, new Integer(i * 2));
- }
-
- Collection s1 = lhm.values();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 5; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
- }
- assertTrue("Entries left in map", !it1.hasNext());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- objArray2[i] = objArray[i].toString();
- }
-
- hm = new LinkedHashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- objArray = null;
- objArray2 = null;
- hm = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java b/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java
deleted file mode 100644
index f54d01d..0000000
--- a/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java
+++ /dev/null
@@ -1,351 +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 tests.api.java.util;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.Set;
-import java.util.Vector;
-
-/**
- * java.util.LinkedHashSet
- */
-
-public class LinkedHashSetTest extends junit.framework.TestCase {
-
- LinkedHashSet hs;
-
- Object[] objArray;
-
- /**
- * java.util.LinkedHashSet#LinkedHashSet()
- */
- public void test_Constructor() {
- // Test for method java.util.LinkedHashSet()
- LinkedHashSet hs2 = new LinkedHashSet();
- assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
- }
-
- /**
- * java.util.LinkedHashSet#LinkedHashSet(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.LinkedHashSet(int)
- LinkedHashSet hs2 = new LinkedHashSet(5);
- assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
- try {
- new LinkedHashSet(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedHashSet#LinkedHashSet(int, float)
- */
- public void test_ConstructorIF() {
- // Test for method java.util.LinkedHashSet(int, float)
- LinkedHashSet hs2 = new LinkedHashSet(5, (float) 0.5);
- assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
-
- try {
- new LinkedHashSet(-1, 0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new LinkedHashSet(1, -0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new LinkedHashSet(1, 0f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedHashSet#LinkedHashSet(java.util.Collection)
- */
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.LinkedHashSet(java.util.Collection)
- LinkedHashSet hs2 = new LinkedHashSet(Arrays.asList(objArray));
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("LinkedHashSet does not contain correct elements", hs
- .contains(objArray[counter]));
- assertTrue("LinkedHashSet created from collection incorrect size", hs2
- .size() == objArray.length);
-
- try {
- new LinkedHashSet(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedHashSet#add(java.lang.Object)
- */
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.LinkedHashSet.add(java.lang.Object)
- int size = hs.size();
- hs.add(new Integer(8));
- assertTrue("Added element already contained by set", hs.size() == size);
- hs.add(new Integer(-9));
- assertTrue("Failed to increment set size after add",
- hs.size() == size + 1);
- assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
- }
-
- /**
- * java.util.LinkedHashSet#clear()
- */
- public void test_clear() {
- // Test for method void java.util.LinkedHashSet.clear()
- Set orgSet = (Set) hs.clone();
- hs.clear();
- Iterator i = orgSet.iterator();
- assertEquals("Returned non-zero size after clear", 0, hs.size());
- while (i.hasNext())
- assertTrue("Failed to clear set", !hs.contains(i.next()));
- }
-
- /**
- * java.util.LinkedHashSet#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedHashSet.clone()
- LinkedHashSet hs2 = (LinkedHashSet) hs.clone();
- assertTrue("clone returned an equivalent LinkedHashSet", hs != hs2);
- assertTrue("clone did not return an equal LinkedHashSet", hs
- .equals(hs2));
- }
-
- /**
- * java.util.LinkedHashSet#contains(java.lang.Object)
- */
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashSet.contains(java.lang.Object)
- assertTrue("Returned false for valid object", hs.contains(objArray[90]));
- assertTrue("Returned true for invalid Object", !hs
- .contains(new Object()));
-
- LinkedHashSet s = new LinkedHashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.contains(null));
- }
-
- /**
- * java.util.LinkedHashSet#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.LinkedHashSet.isEmpty()
- assertTrue("Empty set returned false", new LinkedHashSet().isEmpty());
- assertTrue("Non-empty set returned true", !hs.isEmpty());
- }
-
- /**
- * java.util.LinkedHashSet#iterator()
- */
- public void test_iterator() {
- // Test for method java.util.Iterator java.util.LinkedHashSet.iterator()
- Iterator i = hs.iterator();
- int x = 0;
- int j;
- for (j = 0; i.hasNext(); j++) {
- Object oo = i.next();
- if (oo != null) {
- Integer ii = (Integer) oo;
- assertTrue("Incorrect element found", ii.intValue() == j);
- } else {
- assertTrue("Cannot find null", hs.contains(oo));
- }
- ++x;
- }
- assertTrue("Returned iteration of incorrect size", hs.size() == x);
-
- LinkedHashSet s = new LinkedHashSet();
- s.add(null);
- assertNull("Cannot handle null", s.iterator().next());
- }
-
- /**
- * java.util.LinkedHashSet#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashSet.remove(java.lang.Object)
- int size = hs.size();
- hs.remove(new Integer(98));
- assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
- assertTrue("Failed to decrement set size", hs.size() == size - 1);
-
- LinkedHashSet s = new LinkedHashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.remove(null));
- }
-
- /**
- * java.util.LinkedHashSet#size()
- */
- public void test_size() {
- // Test for method int java.util.LinkedHashSet.size()
- assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
- hs.clear();
- assertEquals("Cleared set returned non-zero size", 0, hs.size());
- }
-
- class Mock_LinkedHashSet extends LinkedHashSet {
- @Override
- public boolean retainAll(Collection c) {
- throw new UnsupportedOperationException();
- }
- }
-
- public void test_retainAllLjava_util_Collection() {
- LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
- Vector v = new Vector<Float>();
- v.add(new Float(3.14));
- lhs.add(new Integer(1));
- assertEquals(1, lhs.size());
- lhs.retainAll(v);
- assertEquals(0, lhs.size());
- v = new Vector<Integer>();
- v.add(new Integer(1));
- v.add(new Integer(2));
- v.add(new Integer(3));
- v.add(new Integer(4));
- v.add(new Integer(5));
- v.add(new Integer(6));
- lhs.add(new Integer(1));
- lhs.add(new Integer(6));
- lhs.add(new Integer(7));
- lhs.add(new Integer(8));
- lhs.add(new Integer(9));
- lhs.add(new Integer(10));
- lhs.add(new Integer(11));
- lhs.add(new Integer(12));
- lhs.add(new Integer(13));
- assertEquals(9, lhs.size());
- lhs.retainAll(v);
- assertEquals(2, lhs.size());
-
- try {
- lhs.retainAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- lhs = new Mock_LinkedHashSet();
-
- try {
- lhs.retainAll(v);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- public void test_toArray() {
- LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
- lhs.add(new Integer(1));
- lhs.add(new Integer(6));
- lhs.add(new Integer(7));
- lhs.add(new Integer(8));
- lhs.add(new Integer(9));
- lhs.add(new Integer(10));
- lhs.add(new Integer(11));
- lhs.add(new Integer(12));
- lhs.add(new Integer(13));
-
- Object[] o = lhs.toArray();
- for (int i = 0; i < o.length; i++) {
- assertTrue(lhs.contains(o[i]));
- }
- assertEquals(lhs.size(), o.length);
- }
-
- public void test_toArray$Ljava_lang_Object() {
- LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
- lhs.add(new Integer(1));
- lhs.add(new Integer(6));
- lhs.add(new Integer(7));
- lhs.add(new Integer(8));
- lhs.add(new Integer(9));
- lhs.add(new Integer(10));
- lhs.add(new Integer(11));
- lhs.add(new Integer(12));
- lhs.add(new Integer(13));
-
- Object[] o1 = new Object[lhs.size()];
- Object[] o2 = new Double[lhs.size()];
- lhs.toArray(o1);
- for (int i = 0; i < o1.length; i++) {
- assertTrue(lhs.contains(o1[i]));
- }
-
- try {
- lhs.toArray(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- lhs.toArray(o2);
- fail("ArrayStoreException expected");
- } catch (ArrayStoreException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- objArray = new Object[1000];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
-
- hs = new LinkedHashSet();
- for (int i = 0; i < objArray.length; i++)
- hs.add(objArray[i]);
- hs.add(null);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- objArray = null;
- hs = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/LinkedListTest.java b/luni/src/test/java/tests/api/java/util/LinkedListTest.java
deleted file mode 100644
index c0cec45..0000000
--- a/luni/src/test/java/tests/api/java/util/LinkedListTest.java
+++ /dev/null
@@ -1,658 +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 tests.api.java.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
-
-
-import tests.support.Support_ListTest;
-
-public class LinkedListTest extends junit.framework.TestCase {
-
- LinkedList ll;
-
- Object[] objArray;
-
- /**
- * java.util.LinkedList#LinkedList()
- */
- public void test_Constructor() {
- // Test for method java.util.LinkedList()
- new Support_ListTest("", ll).runTest();
-
- LinkedList subList = new LinkedList();
- for (int i = -50; i < 150; i++)
- subList.add(new Integer(i));
- new Support_ListTest("", subList.subList(50, 150)).runTest();
- }
-
- /**
- * java.util.LinkedList#LinkedList(java.util.Collection)
- */
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.LinkedList(java.util.Collection)
- assertTrue("Incorrect LinkedList constructed", new LinkedList(ll)
- .equals(ll));
-
- try {
- new LinkedList(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#add(int, java.lang.Object)
- */
- public void test_addILjava_lang_Object() {
- // Test for method void java.util.LinkedList.add(int, java.lang.Object)
- Object o;
- ll.add(50, o = "Test");
- assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll
- .get(50) == o);
- assertTrue("Failed to fix up list after insert",
- ll.get(51) == objArray[50] && (ll.get(52) == objArray[51]));
- ll.add(50, null);
- assertNull("Did not add null correctly", ll.get(50));
- }
-
- /**
- * java.util.LinkedList#add(java.lang.Object)
- */
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.LinkedList.add(java.lang.Object)
- Object o;
- ll.add(o = new Object());
- assertTrue("Failed to add Object", ll.getLast() == o);
- ll.add(null);
- assertNull("Did not add null correctly", ll.get(ll.size() - 1));
- }
-
- /**
- * java.util.LinkedList#addAll(int, java.util.Collection)
- */
- public void test_addAllILjava_util_Collection() {
- // Test for method boolean java.util.LinkedList.addAll(int,
- // java.util.Collection)
- ll.addAll(50, (Collection) ll.clone());
- assertEquals("Returned incorrect size after adding to existing list", 200, ll
- .size());
- for (int i = 0; i < 50; i++)
- assertTrue("Manipulated elements < index", ll.get(i) == objArray[i]);
- for (int i = 0; i >= 50 && (i < 150); i++)
- assertTrue("Failed to ad elements properly",
- ll.get(i) == objArray[i - 50]);
- for (int i = 0; i >= 150 && (i < 200); i++)
- assertTrue("Failed to ad elements properly",
- ll.get(i) == objArray[i - 100]);
- List myList = new LinkedList();
- myList.add(null);
- myList.add("Blah");
- myList.add(null);
- myList.add("Booga");
- myList.add(null);
- ll.addAll(50, myList);
- assertNull("a) List w/nulls not added correctly", ll.get(50));
- assertEquals("b) List w/nulls not added correctly",
- "Blah", ll.get(51));
- assertNull("c) List w/nulls not added correctly", ll.get(52));
- assertEquals("d) List w/nulls not added correctly",
- "Booga", ll.get(53));
- assertNull("e) List w/nulls not added correctly", ll.get(54));
-
- try {
- ll.addAll(-1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.addAll(ll.size() + 1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#addAll(int, java.util.Collection)
- */
- public void test_addAllILjava_util_Collection_2() {
- // Regression for HARMONY-467
- LinkedList obj = new LinkedList();
- try {
- obj.addAll(-1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * java.util.LinkedList#addAll(java.util.Collection)
- */
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.LinkedList.addAll(java.util.Collection)
- List l = new ArrayList();
- l.addAll((Collection) ll.clone());
- for (int i = 0; i < ll.size(); i++)
- assertTrue("Failed to add elements properly", l.get(i).equals(
- ll.get(i)));
- ll.addAll((Collection) ll.clone());
- assertEquals("Returned incorrect siZe after adding to existing list", 200, ll
- .size());
- for (int i = 0; i < 100; i++) {
- assertTrue("Added to list in incorrect order", ll.get(i).equals(
- l.get(i)));
- assertTrue("Failed to add to existing list", ll.get(i + 100)
- .equals(l.get(i)));
- }
- List myList = new LinkedList();
- myList.add(null);
- myList.add("Blah");
- myList.add(null);
- myList.add("Booga");
- myList.add(null);
- ll.addAll(myList);
- assertNull("a) List w/nulls not added correctly", ll.get(200));
- assertEquals("b) List w/nulls not added correctly",
- "Blah", ll.get(201));
- assertNull("c) List w/nulls not added correctly", ll.get(202));
- assertEquals("d) List w/nulls not added correctly",
- "Booga", ll.get(203));
- assertNull("e) List w/nulls not added correctly", ll.get(204));
-
- try {
- ll.addAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#addFirst(java.lang.Object)
- */
- public void test_addFirstLjava_lang_Object() {
- // Test for method void java.util.LinkedList.addFirst(java.lang.Object)
- Object o;
- ll.addFirst(o = new Object());
- assertTrue("Failed to add Object", ll.getFirst() == o);
- ll.addFirst(null);
- assertNull("Failed to add null", ll.getFirst());
- }
-
- /**
- * java.util.LinkedList#addLast(java.lang.Object)
- */
- public void test_addLastLjava_lang_Object() {
- // Test for method void java.util.LinkedList.addLast(java.lang.Object)
- Object o;
- ll.addLast(o = new Object());
- assertTrue("Failed to add Object", ll.getLast() == o);
- ll.addLast(null);
- assertNull("Failed to add null", ll.getLast());
- }
-
- /**
- * java.util.LinkedList#clear()
- */
- public void test_clear() {
- // Test for method void java.util.LinkedList.clear()
- ll.clear();
- for (int i = 0; i < ll.size(); i++)
- assertNull("Failed to clear list", ll.get(i));
- }
-
- /**
- * java.util.LinkedList#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedList.clone()
- Object x = ll.clone();
- assertTrue("Cloned list was inequal to cloned", x.equals(ll));
- for (int i = 0; i < ll.size(); i++)
- assertTrue("Cloned list contains incorrect elements", ll.get(i)
- .equals(((LinkedList) x).get(i)));
- ll.addFirst(null);
- x = ll.clone();
- assertTrue("List with a null did not clone properly", ll.equals(x));
- }
-
- /**
- * java.util.LinkedList#contains(java.lang.Object)
- */
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedList.contains(java.lang.Object)
- assertTrue("Returned false for valid element", ll
- .contains(objArray[99]));
- assertTrue("Returned false for equal element", ll.contains(new Integer(
- 8)));
- assertTrue("Returned true for invalid element", !ll
- .contains(new Object()));
- assertTrue("Should not contain null", !ll.contains(null));
- ll.add(25, null);
- assertTrue("Should contain null", ll.contains(null));
- }
-
- /**
- * java.util.LinkedList#get(int)
- */
- public void test_getI() {
- // Test for method java.lang.Object java.util.LinkedList.get(int)
- assertTrue("Returned incorrect element", ll.get(22) == objArray[22]);
- try {
- ll.get(8765);
- fail("Failed to throw expected exception for index > size");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * java.util.LinkedList#getFirst()
- */
- public void test_getFirst() {
- // Test for method java.lang.Object java.util.LinkedList.getFirst()
- assertTrue("Returned incorrect first element", ll.getFirst().equals(
- objArray[0]));
-
- ll.clear();
- try {
- ll.getFirst();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#getLast()
- */
- public void test_getLast() {
- // Test for method java.lang.Object java.util.LinkedList.getLast()
- assertTrue("Returned incorrect first element", ll.getLast().equals(
- objArray[objArray.length - 1]));
-
- ll.clear();
- try {
- ll.getLast();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#indexOf(java.lang.Object)
- */
- public void test_indexOfLjava_lang_Object() {
- // Test for method int java.util.LinkedList.indexOf(java.lang.Object)
- assertEquals("Returned incorrect index", 87, ll.indexOf(objArray[87]));
- assertEquals("Returned index for invalid Object", -1, ll
- .indexOf(new Object()));
- ll.add(20, null);
- ll.add(24, null);
- assertTrue("Index of null should be 20, but got: " + ll.indexOf(null),
- ll.indexOf(null) == 20);
- }
-
- /**
- * java.util.LinkedList#lastIndexOf(java.lang.Object)
- */
- public void test_lastIndexOfLjava_lang_Object() {
- // Test for method int
- // java.util.LinkedList.lastIndexOf(java.lang.Object)
- ll.add(new Integer(99));
- assertEquals("Returned incorrect index",
- 100, ll.lastIndexOf(objArray[99]));
- assertEquals("Returned index for invalid Object", -1, ll
- .lastIndexOf(new Object()));
- ll.add(20, null);
- ll.add(24, null);
- assertTrue("Last index of null should be 20, but got: "
- + ll.lastIndexOf(null), ll.lastIndexOf(null) == 24);
- }
-
- /**
- * java.util.LinkedList#listIterator(int)
- */
- public void test_listIteratorI() {
- // Test for method java.util.ListIterator
- // java.util.LinkedList.listIterator(int)
- ListIterator i1 = ll.listIterator();
- ListIterator i2 = ll.listIterator(0);
- Object elm;
- int n = 0;
- while (i2.hasNext()) {
- if (n == 0 || n == objArray.length - 1) {
- if (n == 0)
- assertTrue("First element claimed to have a previous", !i2
- .hasPrevious());
- if (n == objArray.length)
- assertTrue("Last element claimed to have next", !i2
- .hasNext());
- }
- elm = i2.next();
- assertTrue("Iterator returned elements in wrong order",
- elm == objArray[n]);
- if (n > 0 && n < objArray.length - 1) {
- assertTrue("Next index returned incorrect value",
- i2.nextIndex() == n + 1);
- assertTrue("previousIndex returned incorrect value : "
- + i2.previousIndex() + ", n val: " + n, i2
- .previousIndex() == n);
- }
- elm = i1.next();
- assertTrue("Iterator returned elements in wrong order",
- elm == objArray[n]);
- ++n;
- }
-
- i2 = ll.listIterator(ll.size()/2);
- assertTrue((Integer)i2.next() == ll.size()/2);
- List myList = new LinkedList();
- myList.add(null);
- myList.add("Blah");
- myList.add(null);
- myList.add("Booga");
- myList.add(null);
- ListIterator li = myList.listIterator();
- assertTrue("li.hasPrevious() should be false", !li.hasPrevious());
- assertNull("li.next() should be null", li.next());
- assertTrue("li.hasPrevious() should be true", li.hasPrevious());
- assertNull("li.prev() should be null", li.previous());
- assertNull("li.next() should be null", li.next());
- assertEquals("li.next() should be Blah", "Blah", li.next());
- assertNull("li.next() should be null", li.next());
- assertEquals("li.next() should be Booga", "Booga", li.next());
- assertTrue("li.hasNext() should be true", li.hasNext());
- assertNull("li.next() should be null", li.next());
- assertTrue("li.hasNext() should be false", !li.hasNext());
-
- try {
- ll.listIterator(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.listIterator(ll.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#remove(int)
- */
- public void test_removeI() {
- // Test for method java.lang.Object java.util.LinkedList.remove(int)
- ll.remove(10);
- assertEquals("Failed to remove element", -1, ll.indexOf(objArray[10]));
- try {
- ll.remove(999);
- fail("Failed to throw expected exception when index out of range");
- } catch (IndexOutOfBoundsException e) {
- // Correct
- }
-
- ll.add(20, null);
- ll.remove(20);
- assertNotNull("Should have removed null", ll.get(20));
- }
-
- /**
- * java.util.LinkedList#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.LinkedList.remove(java.lang.Object)
- assertTrue("Failed to remove valid Object", ll.remove(objArray[87]));
- assertTrue("Removed invalid object", !ll.remove(new Object()));
- assertEquals("Found Object after removal", -1, ll.indexOf(objArray[87]));
- ll.add(null);
- ll.remove(null);
- assertTrue("Should not contain null afrer removal", !ll.contains(null));
- }
-
- /**
- * java.util.LinkedList#removeFirst()
- */
- public void test_removeFirst() {
- // Test for method java.lang.Object java.util.LinkedList.removeFirst()
- ll.removeFirst();
- assertTrue("Failed to remove first element",
- ll.getFirst() != objArray[0]);
-
- ll.clear();
- try {
- ll.removeFirst();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#removeLast()
- */
- public void test_removeLast() {
- // Test for method java.lang.Object java.util.LinkedList.removeLast()
- ll.removeLast();
- assertTrue("Failed to remove last element",
- ll.getLast() != objArray[objArray.length - 1]);
-
- ll.clear();
- try {
- ll.removeLast();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#set(int, java.lang.Object)
- */
- public void test_setILjava_lang_Object() {
- // Test for method java.lang.Object java.util.LinkedList.set(int,
- // java.lang.Object)
- Object obj;
- ll.set(65, obj = new Object());
- assertTrue("Failed to set object", ll.get(65) == obj);
-
- try {
- ll.set(-1, obj = new Object());
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.set(ll.size() + 1, obj = new Object());
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.LinkedList#size()
- */
- public void test_size() {
- // Test for method int java.util.LinkedList.size()
- assertTrue("Returned incorrect size", ll.size() == objArray.length);
- ll.removeFirst();
- assertTrue("Returned incorrect size", ll.size() == objArray.length - 1);
- }
-
- /**
- * java.util.LinkedList#toArray()
- */
- public void test_toArray() {
- // Test for method java.lang.Object [] java.util.LinkedList.toArray()
- ll.add(null);
- Object[] obj = ll.toArray();
- assertEquals("Returned array of incorrect size", objArray.length + 1, obj.length);
-
- for (int i = 0; i < obj.length - 1; i++)
- assertTrue("Returned incorrect array: " + i, obj[i] == objArray[i]);
- assertNull("Returned incorrect array--end isn't null",
- obj[obj.length - 1]);
- }
-
- /**
- * java.util.LinkedList#toArray(java.lang.Object[])
- */
- public void test_toArray$Ljava_lang_Object() {
- // Test for method java.lang.Object []
- // java.util.LinkedList.toArray(java.lang.Object [])
- Integer[] argArray = new Integer[100];
- Object[] retArray;
- retArray = ll.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- List retList = new LinkedList(Arrays.asList(retArray));
- Iterator li = ll.iterator();
- Iterator ri = retList.iterator();
- while (li.hasNext())
- assertTrue("Lists are not equal", li.next() == ri.next());
- argArray = new Integer[1000];
- retArray = ll.toArray(argArray);
- assertNull("Failed to set first extra element to null", argArray[ll
- .size()]);
- for (int i = 0; i < ll.size(); i++)
- assertTrue("Returned incorrect array: " + i,
- retArray[i] == objArray[i]);
- ll.add(50, null);
- argArray = new Integer[101];
- retArray = ll.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- retArray = ll.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- retList = new LinkedList(Arrays.asList(retArray));
- li = ll.iterator();
- ri = retList.iterator();
- while (li.hasNext())
- assertTrue("Lists are not equal", li.next() == ri.next());
-
- try {
- ll.toArray(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- LinkedList<String> lls = new LinkedList<String>();
- lls.add("First");
- lls.add("Second");
-
- try {
- lls.toArray(argArray);
- fail("ArrayStoreException expected");
- } catch (ArrayStoreException e) {
- //expected
- }
- }
- public void test_offer() {
- int origSize = ll.size();
- assertTrue("offer() should return true'", ll.offer(objArray[0]));
- assertEquals("offer() should add an element as the last one", origSize, ll.lastIndexOf(objArray[0]));
- }
- public void test_poll() {
- for (int i = 0; i < objArray.length; i++) {
- assertEquals("should remove the head", objArray[i], ll.poll());
- }
- assertEquals("should be empty", 0, ll.size());
- assertNull("should return 'null' if list is empty", ll.poll());
- }
- public void test_remove() {
- for (int i = 0; i < objArray.length; i++) {
- assertEquals("should remove the head", objArray[i], ll.remove());
- }
- assertEquals("should be empty", 0, ll.size());
- try {
- ll.remove();
- fail("NoSuchElementException is expected when removing from the empty list");
- } catch (NoSuchElementException e) {
- //-- expected
- }
- }
- public void test_element() {
- assertEquals("should return the head", objArray[0], ll.element());
- assertEquals("element() should remove nothing", objArray.length, ll.size());
- try {
- new LinkedList().remove();
- fail("NoSuchElementException is expected when the list is empty");
- } catch (NoSuchElementException e) {
- //-- expected
- }
- }
-
- public void test_peek() {
- assertEquals("should remove the head", objArray[0], ll.peek());
- assertEquals("should remove the head", objArray[0], ll.peek());
-
- ll.clear();
-
- assertNull("should return 'null' if list is empty", ll.peek());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
-
- objArray = new Object[100];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- }
-
- ll = new LinkedList();
- for (int i = 0; i < objArray.length; i++) {
- ll.add(objArray[i]);
- }
- }
-
- @Override
- protected void tearDown() throws Exception {
- objArray = null;
- ll = null;
-
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java
deleted file mode 100644
index 8be04db..0000000
--- a/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.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 tests.api.java.util;
-
-import java.util.Enumeration;
-import java.util.ListResourceBundle;
-import java.util.Locale;
-import java.util.ResourceBundle;
-import java.util.Vector;
-
-public class ListResourceBundleTest extends junit.framework.TestCase {
-
- /**
- * java.util.ListResourceBundle#getKeys()
- */
- public void test_getKeys() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- Enumeration keys = bundle.getKeys();
- Vector result = new Vector();
- while (keys.hasMoreElements()) {
- result.addElement(keys.nextElement());
- }
- assertTrue("Missing key parent1", result.contains("parent1"));
- assertTrue("Missing key parent2", result.contains("parent2"));
- assertTrue("Missing key parent3", result.contains("parent3"));
- assertTrue("Missing key parent4", result.contains("parent4"));
- assertTrue("Missing key child1", result.contains("child1"));
- assertTrue("Missing key child2", result.contains("child2"));
- assertTrue("Missing key child3", result.contains("child3"));
- }
-
-
- public void test_handleGetObjectLjava_lang_String() {
- ListResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = (ListResourceBundle)ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- Enumeration keys = bundle.getKeys();
- String keyValue = null;
- Vector result = new Vector();
- while (keys.hasMoreElements()) {
- result.addElement(bundle.handleGetObject((String)keys.nextElement()));
- }
- assertEquals(9, result.size());
- assertTrue(result.contains(null));
- assertTrue(result.contains("frFRVARValue4"));
- assertTrue(result.contains("frFRVARChildValue1"));
- assertTrue(result.contains("frFRVARChildValue2"));
- assertTrue(result.contains("frFRVARChildValue3"));
- assertTrue(result.remove(null));
- assertTrue(result.remove(null));
- assertTrue(result.remove(null));
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/LocaleTest.java b/luni/src/test/java/tests/api/java/util/LocaleTest.java
deleted file mode 100644
index 7615a76..0000000
--- a/luni/src/test/java/tests/api/java/util/LocaleTest.java
+++ /dev/null
@@ -1,416 +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 tests.api.java.util;
-
-import java.security.Permission;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.Set;
-
-public class LocaleTest extends junit.framework.TestCase {
-
- Locale testLocale;
-
- Locale l;
-
- Locale defaultLocale;
-
- /**
- * java.util.Locale#Locale(java.lang.String, java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.Locale(java.lang.String)
- Locale x = new Locale("xx");
- assertTrue("Failed to create Locale", x.getVariant().equals(""));
-
- try {
- new Locale(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Locale#Locale(java.lang.String, java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.Locale(java.lang.String, java.lang.String)
- Locale x = new Locale("xx", "CV");
- assertTrue("Failed to create Locale", x.getCountry().equals("CV")
- && x.getVariant().equals(""));
-
- try {
- new Locale("xx", null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- new Locale(null, "CV");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Locale#Locale(java.lang.String, java.lang.String,
- * java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.Locale(java.lang.String, java.lang.String,
- // java.lang.String)
- Locale x = new Locale("xx", "CV", "ZZ");
- assertTrue("Failed to create Locale", x.getLanguage().equals("xx")
- && (x.getCountry().equals("CV") && x.getVariant().equals("ZZ")));
- try {
- new Locale(null, "CV", "ZZ");
- fail("expected NullPointerException with 1st parameter == null");
- } catch(NullPointerException e) {
- }
-
- try {
- new Locale("xx", null, "ZZ");
- fail("expected NullPointerException with 2nd parameter == null");
- } catch(NullPointerException e) {
- }
-
- try {
- new Locale("xx", "CV", null);
- fail("expected NullPointerException with 3rd parameter == null");
- } catch(NullPointerException e) {
- }
- }
-
- /**
- * java.util.Locale#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.Locale.clone()
- assertTrue("Clone failed", l.clone().equals(l));
- }
-
- /**
- * java.util.Locale#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Locale.equals(java.lang.Object)
- Locale l2 = new Locale("en", "CA", "WIN32");
- assertTrue("Same object returned false", testLocale.equals(testLocale));
- assertTrue("Same values returned false", testLocale.equals(l2));
- assertTrue("Different locales returned true", !testLocale.equals(l));
-
- }
-
- /**
- * java.util.Locale#getAvailableLocales()
- */
- public void test_getAvailableLocales() {
-// BEGIN android-changed
- // Test for method java.util.Locale []
- // java.util.Locale.getAvailableLocales()
- // Assumes there will generally be about 10+ available locales...
- // even in minimal configurations for android
- try {
- Locale[] locales = Locale.getAvailableLocales();
- assertTrue("Wrong number of locales: " + locales.length, locales.length > 10);
- // regression test for HARMONY-1514
- // HashSet can filter duplicate locales
- Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales));
- assertEquals(localesSet.size(), locales.length);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-// END android-changed
- }
-
- /**
- * java.util.Locale#getCountry()
- */
- public void test_getCountry() {
- // Test for method java.lang.String java.util.Locale.getCountry()
- assertTrue("Returned incorrect country: " + testLocale.getCountry(),
- testLocale.getCountry().equals("CA"));
- }
-
- /**
- * java.util.Locale#getDefault()
- */
- public void test_getDefault() {
- // Test for method java.util.Locale java.util.Locale.getDefault()
- assertTrue("returns copy", Locale.getDefault() == Locale.getDefault());
- Locale org = Locale.getDefault();
- Locale.setDefault(l);
- Locale x = Locale.getDefault();
- Locale.setDefault(org);
- assertEquals("Failed to get locale", "fr_CA_WIN32", x.toString());
- }
-
- /**
- * java.util.Locale#getDisplayCountry()
- */
- public void test_getDisplayCountry() {
- // Test for method java.lang.String java.util.Locale.getDisplayCountry()
- assertTrue("Returned incorrect country: "
- + testLocale.getDisplayCountry(), testLocale
- .getDisplayCountry().equals("Canada"));
-
- // Regression for Harmony-1146
- Locale l_countryCD = new Locale("", "CD");
- assertEquals("Congo [DRC]",
- l_countryCD.getDisplayCountry());
- }
-
- public void test_getDisplayCountryLjava_util_Locale() {
- assertEquals("Italie", Locale.ITALY.getDisplayCountry(new Locale("fr", "CA", "WIN32")));
- }
-
- /**
- * java.util.Locale#getDisplayLanguage()
- */
- public void test_getDisplayLanguage() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayLanguage()
- assertTrue("Returned incorrect language: "
- + testLocale.getDisplayLanguage(), testLocale
- .getDisplayLanguage().equals("English"));
-
- // Regression for Harmony-1146
- Locale l_languageAE = new Locale("ae", "");
- assertEquals("Avestan", l_languageAE.getDisplayLanguage());
- }
-
- public void test_getDisplayLanguageLjava_util_Locale() {
- assertEquals("anglais", new Locale("en", "CA", "WIN32").getDisplayLanguage(l));
- }
-
- public void test_getDisplayName() {
- assertEquals("English (Canada,WIN32)", new Locale("en", "CA", "WIN32").getDisplayName());
- }
-
- public void test_getDisplayNameLjava_util_Locale() {
- assertEquals("anglais (Canada,WIN32)", new Locale("en", "CA", "WIN32").getDisplayName(l));
- }
-
- /**
- * java.util.Locale#getDisplayVariant()
- */
- public void test_getDisplayVariant() {
- // Test for method java.lang.String java.util.Locale.getDisplayVariant()
- assertTrue("Returned incorrect variant: "
- + testLocale.getDisplayVariant(), testLocale
- .getDisplayVariant().equals("WIN32"));
- }
-
- /**
- * java.util.Locale#getDisplayVariant(java.util.Locale)
- */
- public void test_getDisplayVariantLjava_util_Locale() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayVariant(java.util.Locale)
- assertTrue("Returned incorrect variant: "
- + testLocale.getDisplayVariant(l), testLocale
- .getDisplayVariant(l).equals("WIN32"));
- }
-
- public void test_getISO3Language() {
- Locale l = new Locale("ae");
- assertEquals("ave", l.getISO3Language());
-
- // Regression for Harmony-1146
- Locale l_CountryCS = new Locale("", "CS");
- assertEquals("SCG", l_CountryCS.getISO3Country());
-
- // Regression for Harmony-1129
- l = new Locale("ak", "");
- assertEquals("aka", l.getISO3Language());
- }
-
- /**
- * java.util.Locale#getISOCountries()
- */
- public void test_getISOCountries() {
- // Test for method java.lang.String []
- // java.util.Locale.getISOCountries()
- // Assumes all countries are 2 digits, and that there will always be
- // 230 countries on the list...
- String[] isoCountries = Locale.getISOCountries();
- int length = isoCountries.length;
- int familiarCount = 0;
- for (int i = 0; i < length; i++) {
- if (isoCountries[i].length() != 2) {
- fail("Wrong format for ISOCountries.");
- }
- if (isoCountries[i].equals("CA") || isoCountries[i].equals("BB")
- || isoCountries[i].equals("US")
- || isoCountries[i].equals("KR"))
- familiarCount++;
- }
- assertTrue("ISOCountries missing.", familiarCount == 4 && length > 230);
- }
-
- /**
- * java.util.Locale#getISOLanguages()
- */
- public void test_getISOLanguages() {
- // Test for method java.lang.String []
- // java.util.Locale.getISOLanguages()
- // Assumes always at least 131 ISOlanguages...
- String[] isoLang = Locale.getISOLanguages();
- int length = isoLang.length;
-
- // BEGIN android-changed
- // Language codes are 2- and 3-letter, with preference given
- // to 2-letter codes where possible. 3-letter codes are used
- // when lack a 2-letter equivalent.
- assertTrue("Random element in wrong format.",
- (isoLang[length / 2].length() == 2 || isoLang[length / 2].length() == 3)
- && isoLang[length / 2].toLowerCase().equals(isoLang[length / 2]));
- // END android-changed
-
- assertTrue("Wrong number of ISOLanguages.", length > 130);
- }
-
- /**
- * java.util.Locale#getLanguage()
- */
- public void test_getLanguage() {
- // Test for method java.lang.String java.util.Locale.getLanguage()
- assertTrue("Returned incorrect language: " + testLocale.getLanguage(),
- testLocale.getLanguage().equals("en"));
- }
-
- /**
- * java.util.Locale#getVariant()
- */
- public void test_getVariant() {
- // Test for method java.lang.String java.util.Locale.getVariant()
- assertTrue("Returned incorrect variant: " + testLocale.getVariant(),
- testLocale.getVariant().equals("WIN32"));
- }
-
- SecurityManager sm = new SecurityManager() {
- final String forbidenPermissionName = "user.language";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
- };
- /**
- * java.util.Locale#setDefault(java.util.Locale)
- */
- public void test_setDefaultLjava_util_Locale() {
- // Test for method void java.util.Locale.setDefault(java.util.Locale)
-
- Locale org = Locale.getDefault();
- Locale.setDefault(l);
- Locale x = Locale.getDefault();
- Locale.setDefault(org);
- assertEquals("Failed to set locale", "fr_CA_WIN32", x.toString());
-
- Locale.setDefault(new Locale("tr", ""));
- String res1 = "\u0069".toUpperCase();
- String res2 = "\u0049".toLowerCase();
- Locale.setDefault(org);
- assertEquals("Wrong toUppercase conversion", "\u0130", res1);
- assertEquals("Wrong toLowercase conversion", "\u0131", res2);
-
- try {
- Locale.setDefault(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Locale#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.util.Locale.toString()
- assertEquals("en_CA_WIN32", new Locale("en", "CA", "WIN32").toString());
-
- Locale l = new Locale("en", "");
- assertEquals("Wrong representation 1", "en", l.toString());
- l = new Locale("", "CA");
- assertEquals("Wrong representation 2", "_CA", l.toString());
- l = new Locale("", "CA", "var");
- assertEquals("Wrong representation 2.5", "_CA_var", l.toString());
- l = new Locale("en", "", "WIN");
- assertEquals("Wrong representation 4", "en__WIN", l.toString());
- l = new Locale("en", "CA");
- assertEquals("Wrong representation 6", "en_CA", l.toString());
- l = new Locale("en", "CA", "VAR");
- assertEquals("Wrong representation 7", "en_CA_VAR", l.toString());
-
- l = new Locale("", "", "var");
- assertEquals("Wrong representation 8", "", l.toString());
-
- }
-
- public void test_hashCode() {
- Locale l1 = new Locale("en", "US");
- Locale l2 = new Locale("fr", "CA");
-
- assertTrue(l1.hashCode() != l2.hashCode());
- }
-
-// BEGIN android-removed
-// These locales are not part of the android reference impl
-// // Regression Test for HARMONY-2953
-// public void test_getISO() {
-// Locale locale = new Locale("an");
-// assertEquals("arg", locale.getISO3Language());
-//
-// locale = new Locale("PS");
-// assertEquals("pus", locale.getISO3Language());
-//
-// List<String> languages = Arrays.asList(Locale.getISOLanguages());
-// assertTrue(languages.contains("ak"));
-//
-// List<String> countries = Arrays.asList(Locale.getISOCountries());
-// assertTrue(countries.contains("CS"));
-// }
-// END android-removed
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- defaultLocale = Locale.getDefault();
- Locale.setDefault(Locale.US);
- testLocale = new Locale("en", "CA", "WIN32");
- l = new Locale("fr", "CA", "WIN32");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- Locale.setDefault(defaultLocale);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java b/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java
deleted file mode 100644
index fc7189e..0000000
--- a/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java
+++ /dev/null
@@ -1,85 +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 tests.api.java.util;
-
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-public class MissingResourceExceptionTest extends junit.framework.TestCase {
-
- /**
- * java.util.MissingResourceException#MissingResourceException(java.lang.String,
- * java.lang.String, java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.MissingResourceException(java.lang.String,
- // java.lang.String, java.lang.String)
- assertNotNull(new MissingResourceException("Detail string", "Class name string", "Key string"));
- assertNotNull(new MissingResourceException(null, "Class name string", "Key string"));
- assertNotNull(new MissingResourceException("Detail string", null, "Key string"));
- assertNotNull(new MissingResourceException("Detail string", "Class name string", null));
- try {
- ResourceBundle.getBundle("Non-ExistentBundle");
- } catch (MissingResourceException e) {
- return;
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * java.util.MissingResourceException#getClassName()
- */
- public void test_getClassName() {
- // Test for method java.lang.String
- // java.util.MissingResourceException.getClassName()
- try {
- ResourceBundle.getBundle("Non-ExistentBundle");
- } catch (MissingResourceException e) {
- assertEquals("Returned incorrect class name", "Non-ExistentBundle"
- + '_' + Locale.getDefault(), e.getClassName());
- }
- }
-
- /**
- * java.util.MissingResourceException#getKey()
- */
- public void test_getKey() {
- // Test for method java.lang.String
- // java.util.MissingResourceException.getKey()
- try {
- ResourceBundle.getBundle("Non-ExistentBundle");
- } catch (MissingResourceException e) {
- assertTrue("Returned incorrect class name", e.getKey().equals(""));
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java b/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java
deleted file mode 100644
index cfda941..0000000
--- a/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.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 tests.api.java.util;
-
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
-public class NoSuchElementExceptionTest extends junit.framework.TestCase {
-
- /**
- * java.util.NoSuchElementException#NoSuchElementException()
- */
- public void test_Constructor() {
- // Test for method java.util.NoSuchElementException()
-
- assertNotNull(new NoSuchElementException());
-
- try {
- Vector v = new Vector();
- v.elements().nextElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.NoSuchElementException#NoSuchElementException(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.NoSuchElementException(java.lang.String)
-
- assertNotNull(new NoSuchElementException("String"));
- assertNotNull(new NoSuchElementException(null));
-
- try {
- Vector v = new Vector();
- v.firstElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ObservableTest.java b/luni/src/test/java/tests/api/java/util/ObservableTest.java
deleted file mode 100644
index 3a0d31c..0000000
--- a/luni/src/test/java/tests/api/java/util/ObservableTest.java
+++ /dev/null
@@ -1,246 +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 tests.api.java.util;
-
-import java.util.Observable;
-import java.util.Observer;
-import java.util.Vector;
-
-public class ObservableTest extends junit.framework.TestCase {
-
- static class TestObserver implements Observer {
- public Vector objv = new Vector();
-
- int updateCount = 0;
-
- public void update(Observable observed, Object arg) {
- ++updateCount;
- objv.add(arg);
- }
-
- public int updateCount() {
- return updateCount;
- }
-
- }
-
- static class DeleteTestObserver implements Observer {
- int updateCount = 0;
-
- boolean deleteAll = false;
-
- public DeleteTestObserver(boolean all) {
- deleteAll = all;
- }
-
- public void update(Observable observed, Object arg) {
- ++updateCount;
- if (deleteAll)
- observed.deleteObservers();
- else
- observed.deleteObserver(this);
- }
-
- public int updateCount() {
- return updateCount;
- }
-
- }
-
- static class TestObservable extends Observable {
- public void doChange() {
- setChanged();
- }
-
- public void clearChange() {
- clearChanged();
- }
- }
-
- Observer observer;
-
- TestObservable observable;
-
- /**
- * java.util.Observable#Observable()
- */
- public void test_Constructor() {
- // Test for method java.util.Observable()
- try {
- Observable ov = new Observable();
- assertTrue("Wrong initial values.", !ov.hasChanged());
- assertEquals("Wrong initial values.", 0, ov.countObservers());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * java.util.Observable#addObserver(java.util.Observer)
- */
- public void test_addObserverLjava_util_Observer() {
- // Test for method void
- // java.util.Observable.addObserver(java.util.Observer)
- TestObserver test = new TestObserver();
- observable.addObserver(test);
- assertEquals("Failed to add observer", 1, observable.countObservers());
- observable.addObserver(test);
- assertEquals("Duplicate observer", 1, observable.countObservers());
-
- Observable o = new Observable();
- try {
- o.addObserver(null);
- fail("Expected adding a null observer to throw a NPE.");
- } catch (NullPointerException ex) {
- // expected;
- } catch (Throwable ex) {
- fail("Did not expect adding a new observer to throw a "
- + ex.getClass().getName());
- }
- }
-
- /**
- * java.util.Observable#countObservers()
- */
- public void test_countObservers() {
- // Test for method int java.util.Observable.countObservers()
- assertEquals("New observable had > 0 observers", 0, observable
- .countObservers());
- observable.addObserver(new TestObserver());
- assertEquals("Observable with observer returned other than 1", 1, observable
- .countObservers());
- }
-
- /**
- * java.util.Observable#deleteObserver(java.util.Observer)
- */
- public void test_deleteObserverLjava_util_Observer() {
- // Test for method void
- // java.util.Observable.deleteObserver(java.util.Observer)
- observable.addObserver(observer = new TestObserver());
- observable.deleteObserver(observer);
- assertEquals("Failed to delete observer",
- 0, observable.countObservers());
- observable.deleteObserver(observer);
- observable.deleteObserver(null);
- }
-
- /**
- * java.util.Observable#deleteObservers()
- */
- public void test_deleteObservers() {
- // Test for method void java.util.Observable.deleteObservers()
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.deleteObservers();
- assertEquals("Failed to delete observers",
- 0, observable.countObservers());
- }
-
- /**
- * java.util.Observable#hasChanged()
- */
- public void test_hasChanged() {
- assertFalse(observable.hasChanged());
- observable.addObserver(observer = new TestObserver());
- observable.doChange();
- assertTrue(observable.hasChanged());
- }
-
- public void test_clearChanged() {
- assertFalse(observable.hasChanged());
- observable.addObserver(observer = new TestObserver());
- observable.doChange();
- assertTrue(observable.hasChanged());
- observable.clearChange();
- assertFalse(observable.hasChanged());
- }
-
- /**
- * java.util.Observable#notifyObservers()
- */
- public void test_notifyObservers() {
- // Test for method void java.util.Observable.notifyObservers()
- observable.addObserver(observer = new TestObserver());
- observable.notifyObservers();
- assertEquals("Notified when unchnaged", 0, ((TestObserver) observer)
- .updateCount());
- ((TestObservable) observable).doChange();
- observable.notifyObservers();
- assertEquals("Failed to notify",
- 1, ((TestObserver) observer).updateCount());
-
- DeleteTestObserver observer1, observer2;
- observable.deleteObservers();
- observable.addObserver(observer1 = new DeleteTestObserver(false));
- observable.addObserver(observer2 = new DeleteTestObserver(false));
- observable.doChange();
- observable.notifyObservers();
- assertTrue("Failed to notify all", observer1.updateCount() == 1
- && observer2.updateCount() == 1);
- assertEquals("Failed to delete all", 0, observable.countObservers());
-
- observable.addObserver(observer1 = new DeleteTestObserver(false));
- observable.addObserver(observer2 = new DeleteTestObserver(false));
- observable.doChange();
- observable.notifyObservers();
- assertTrue("Failed to notify all 2", observer1.updateCount() == 1
- && observer2.updateCount() == 1);
- assertEquals("Failed to delete all 2", 0, observable.countObservers());
- }
-
- /**
- * java.util.Observable#notifyObservers(java.lang.Object)
- */
- public void test_notifyObserversLjava_lang_Object() {
- // Test for method void
- // java.util.Observable.notifyObservers(java.lang.Object)
- Object obj;
- observable.addObserver(observer = new TestObserver());
- observable.notifyObservers();
- assertEquals("Notified when unchanged", 0, ((TestObserver) observer)
- .updateCount());
- ((TestObservable) observable).doChange();
- observable.notifyObservers(obj = new Object());
- assertEquals("Failed to notify",
- 1, ((TestObserver) observer).updateCount());
- assertTrue("Failed to pass Object arg", ((TestObserver) observer).objv
- .elementAt(0).equals(obj));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- observable = new TestObservable();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java
deleted file mode 100644
index bc6a4fe..0000000
--- a/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java
+++ /dev/null
@@ -1,98 +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 tests.api.java.util;
-
-import java.util.Enumeration;
-import java.util.MissingResourceException;
-import java.util.PropertyResourceBundle;
-import java.util.Vector;
-
-public class PropertyResourceBundleTest extends junit.framework.TestCase {
-
- static PropertyResourceBundle prb;
-
- /**
- * java.util.PropertyResourceBundle#PropertyResourceBundle(java.io.InputStream)
- */
- public void test_ConstructorLjava_io_InputStream() {
- // Test for method java.util.PropertyResourceBundle(java.io.InputStream)
- assertTrue("Used to test", true);
- }
-
- /**
- * java.util.PropertyResourceBundle#getKeys()
- */
- public void test_getKeys() {
- Enumeration keyEnum = prb.getKeys();
- Vector test = new Vector();
- int keyCount = 0;
- while (keyEnum.hasMoreElements()) {
- test.addElement(keyEnum.nextElement());
- keyCount++;
- }
-
- assertEquals("Returned the wrong number of keys", 2, keyCount);
- assertTrue("Returned the wrong keys", test.contains("p1")
- && test.contains("p2"));
- }
-
- /**
- * java.util.PropertyResourceBundle#handleGetObject(java.lang.String)
- */
- public void test_handleGetObjectLjava_lang_String() {
- // Test for method java.lang.Object
- // java.util.PropertyResourceBundle.handleGetObject(java.lang.String)
- try {
- assertTrue("Returned incorrect objects", prb.getObject("p1")
- .equals("one")
- && prb.getObject("p2").equals("two"));
- } catch (MissingResourceException e) {
- fail(
- "Threw MisingResourceException for a key contained in the bundle");
- }
- try {
- prb.getObject("Not in the bundle");
- } catch (MissingResourceException e) {
- return;
- }
- fail(
- "Failed to throw MissingResourceException for object not in the bundle");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- java.io.InputStream propertiesStream = new java.io.ByteArrayInputStream(
- "p1=one\np2=two".getBytes());
- try {
- prb = new PropertyResourceBundle(propertiesStream);
- } catch (java.io.IOException e) {
- fail(
- "Contruction of PropertyResourceBundle threw IOException");
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/RandomTest.java b/luni/src/test/java/tests/api/java/util/RandomTest.java
deleted file mode 100644
index bb72191..0000000
--- a/luni/src/test/java/tests/api/java/util/RandomTest.java
+++ /dev/null
@@ -1,298 +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 tests.api.java.util;
-
-import java.util.Random;
-
-public class RandomTest extends junit.framework.TestCase {
-
- Random r;
-
- /**
- * java.util.Random#Random()
- */
- public void test_Constructor() {
- // Test for method java.util.Random()
- assertTrue("Used to test", true);
- }
-
- /**
- * java.util.Random#Random(long)
- */
- public void test_ConstructorJ() {
- Random r = new Random(8409238L);
- Random r2 = new Random(8409238L);
- for (int i = 0; i < 100; i++)
- assertTrue("Values from randoms with same seed don't match", r
- .nextInt() == r2.nextInt());
- }
-
- /**
- * java.util.Random#nextBoolean()
- */
- public void test_nextBoolean() {
- // Test for method boolean java.util.Random.nextBoolean()
- boolean falseAppeared = false, trueAppeared = false;
- for (int counter = 0; counter < 100; counter++)
- if (r.nextBoolean())
- trueAppeared = true;
- else
- falseAppeared = true;
- assertTrue("Calling nextBoolean() 100 times resulted in all trues",
- falseAppeared);
- assertTrue("Calling nextBoolean() 100 times resulted in all falses",
- trueAppeared);
- }
-
- /**
- * java.util.Random#nextBytes(byte[])
- */
- public void test_nextBytes$B() {
- // Test for method void java.util.Random.nextBytes(byte [])
- boolean someDifferent = false;
- byte[] randomBytes = new byte[100];
- r.nextBytes(randomBytes);
- byte firstByte = randomBytes[0];
- for (int counter = 1; counter < randomBytes.length; counter++)
- if (randomBytes[counter] != firstByte)
- someDifferent = true;
- assertTrue(
- "nextBytes() returned an array of length 100 of the same byte",
- someDifferent);
- }
-
- /**
- * java.util.Random#nextDouble()
- */
- public void test_nextDouble() {
- // Test for method double java.util.Random.nextDouble()
- double lastNum = r.nextDouble();
- double nextNum;
- boolean someDifferent = false;
- boolean inRange = true;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextDouble();
- if (nextNum != lastNum)
- someDifferent = true;
- if (!(0 <= nextNum && nextNum < 1.0))
- inRange = false;
- lastNum = nextNum;
- }
- assertTrue("Calling nextDouble 100 times resulted in same number",
- someDifferent);
- assertTrue(
- "Calling nextDouble resulted in a number out of range [0,1)",
- inRange);
- }
-
- /**
- * java.util.Random#nextFloat()
- */
- public void test_nextFloat() {
- // Test for method float java.util.Random.nextFloat()
- float lastNum = r.nextFloat();
- float nextNum;
- boolean someDifferent = false;
- boolean inRange = true;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextFloat();
- if (nextNum != lastNum)
- someDifferent = true;
- if (!(0 <= nextNum && nextNum < 1.0))
- inRange = false;
- lastNum = nextNum;
- }
- assertTrue("Calling nextFloat 100 times resulted in same number",
- someDifferent);
- assertTrue("Calling nextFloat resulted in a number out of range [0,1)",
- inRange);
- }
-
- /**
- * java.util.Random#nextGaussian()
- */
- public void test_nextGaussian() {
- // Test for method double java.util.Random.nextGaussian()
- double lastNum = r.nextGaussian();
- double nextNum;
- boolean someDifferent = false;
- boolean someInsideStd = false;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextGaussian();
- if (nextNum != lastNum)
- someDifferent = true;
- if (-1.0 <= nextNum && nextNum <= 1.0)
- someInsideStd = true;
- lastNum = nextNum;
- }
- assertTrue("Calling nextGaussian 100 times resulted in same number",
- someDifferent);
- assertTrue(
- "Calling nextGaussian 100 times resulted in no number within 1 std. deviation of mean",
- someInsideStd);
- }
-
- /**
- * java.util.Random#nextInt()
- */
- public void test_nextInt() {
- // Test for method int java.util.Random.nextInt()
- int lastNum = r.nextInt();
- int nextNum;
- boolean someDifferent = false;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextInt();
- if (nextNum != lastNum)
- someDifferent = true;
- lastNum = nextNum;
- }
- assertTrue("Calling nextInt 100 times resulted in same number",
- someDifferent);
- }
-
- /**
- * java.util.Random#nextInt(int)
- */
- public void test_nextIntI() {
- // Test for method int java.util.Random.nextInt(int)
- final int range = 10;
- int lastNum = r.nextInt(range);
- int nextNum;
- boolean someDifferent = false;
- boolean inRange = true;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextInt(range);
- if (nextNum != lastNum)
- someDifferent = true;
- if (!(0 <= nextNum && nextNum < range))
- inRange = false;
- lastNum = nextNum;
- }
- assertTrue("Calling nextInt (range) 100 times resulted in same number",
- someDifferent);
- assertTrue(
- "Calling nextInt (range) resulted in a number outside of [0, range)",
- inRange);
-
- }
-
- /**
- * java.util.Random#nextLong()
- */
- public void test_nextLong() {
- // Test for method long java.util.Random.nextLong()
- long lastNum = r.nextLong();
- long nextNum;
- boolean someDifferent = false;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextLong();
- if (nextNum != lastNum)
- someDifferent = true;
- lastNum = nextNum;
- }
- assertTrue("Calling nextLong 100 times resulted in same number",
- someDifferent);
- }
-
- /**
- * java.util.Random#setSeed(long)
- */
- public void test_setSeedJ() {
- // Test for method void java.util.Random.setSeed(long)
- long[] randomArray = new long[100];
- boolean someDifferent = false;
- final long firstSeed = 1000;
- long aLong, anotherLong, yetAnotherLong;
- Random aRandom = new Random();
- Random anotherRandom = new Random();
- Random yetAnotherRandom = new Random();
- aRandom.setSeed(firstSeed);
- anotherRandom.setSeed(firstSeed);
- for (int counter = 0; counter < randomArray.length; counter++) {
- aLong = aRandom.nextLong();
- anotherLong = anotherRandom.nextLong();
- assertTrue(
- "Two randoms with same seeds gave differing nextLong values",
- aLong == anotherLong);
- yetAnotherLong = yetAnotherRandom.nextLong();
- randomArray[counter] = aLong;
- if (aLong != yetAnotherLong)
- someDifferent = true;
- }
- assertTrue(
- "Two randoms with the different seeds gave the same chain of values",
- someDifferent);
- aRandom.setSeed(firstSeed);
- for (int counter = 0; counter < randomArray.length; counter++)
- assertTrue(
- "Reseting a random to its old seed did not result in the same chain of values as it gave before",
- aRandom.nextLong() == randomArray[counter]);
- }
-
- class Mock_Random extends Random {
- boolean nextCalled = false;
-
- public boolean getFlag () {
- boolean retVal = nextCalled;
- nextCalled = false;
- return retVal;
- }
-
- @Override
- protected int next(int bits) {
- nextCalled = true;
- return super.next(bits);
- }
- }
-
- public void test_next() {
- Mock_Random mr = new Mock_Random();
- assertFalse(mr.getFlag());
- mr.nextBoolean();
- assertTrue(mr.getFlag());
- mr.nextBytes(new byte[10]);
- assertTrue(mr.getFlag());
- mr.nextDouble();
- assertTrue(mr.getFlag());
- mr.nextFloat();
- assertTrue(mr.getFlag());
- mr.nextGaussian();
- assertTrue(mr.getFlag());
- mr.nextInt();
- assertTrue(mr.getFlag());
- mr.nextInt(10);
- assertTrue(mr.getFlag());
- mr.nextLong();
- assertTrue(mr.getFlag());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- r = new Random();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java
deleted file mode 100644
index 587a549..0000000
--- a/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java
+++ /dev/null
@@ -1,398 +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 tests.api.java.util;
-
-import dalvik.annotation.KnownFailure;
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Enumeration;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.StringTokenizer;
-import java.util.Vector;
-import tests.api.java.util.support.B;
-import tests.support.resource.Support_Resources;
-
-public class ResourceBundleTest extends junit.framework.TestCase {
-
- public void test_getCandidateLocales() throws Exception {
- ResourceBundle.Control c = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT);
- assertEquals("[en_US, en, ]", c.getCandidateLocales("base", Locale.US).toString());
- assertEquals("[de_CH, de, ]", c.getCandidateLocales("base", new Locale("de", "CH")).toString());
- }
-
- /**
- * java.util.ResourceBundle#getBundle(java.lang.String,
- * java.util.Locale)
- */
- public void test_getBundleLjava_lang_StringLjava_util_Locale() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale defLocale = Locale.getDefault();
-
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("Wrong bundle fr_FR_VAR", "frFRVARValue4", bundle.getString("parent4"));
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
- assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4"));
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
- assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4"));
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
- assertEquals("Wrong bundle de_FR_var", "enUSValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("fr", "FR", "VAR"));
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
- assertEquals("Wrong bundle de_FR_var 2", "frFRVARValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("de", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
- assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")
- );
-
- try {
- ResourceBundle.getBundle(null, Locale.US);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
- try {
- ResourceBundle.getBundle("blah", (Locale) null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
-
- try {
- ResourceBundle.getBundle("", new Locale("xx", "yy"));
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
- }
-
- /**
- * java.util.ResourceBundle#getBundle(java.lang.String,
- * java.util.Locale, java.lang.ClassLoader)
- */
- @KnownFailure("It's not allowed to pass null as parent class loader to"
- + " a new ClassLoader anymore. Maybe we need to change"
- + " URLClassLoader to allow this? It's not specified.")
- public void test_getBundleLjava_lang_StringLjava_util_LocaleLjava_lang_ClassLoader() {
- String classPath = System.getProperty("java.class.path");
- StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
- Vector<URL> urlVec = new Vector<URL>();
- String resPackage = Support_Resources.RESOURCE_PACKAGE;
- try {
- while (tok.hasMoreTokens()) {
- String path = tok.nextToken();
- String url;
- if (new File(path).isDirectory())
- url = "file:" + path + resPackage + "subfolder/";
- else
- url = "jar:file:" + path + "!" + resPackage + "subfolder/";
- urlVec.addElement(new URL(url));
- }
- } catch (MalformedURLException e) {
- }
- URL[] urls = new URL[urlVec.size()];
- for (int i = 0; i < urlVec.size(); i++)
- urls[i] = urlVec.elementAt(i);
- URLClassLoader loader = new URLClassLoader(urls, null);
-
- String name = Support_Resources.RESOURCE_PACKAGE_NAME
- + ".hyts_resource";
- ResourceBundle bundle = ResourceBundle.getBundle(name, Locale
- .getDefault());
- assertEquals("Wrong value read", "parent", bundle.getString("property"));
- bundle = ResourceBundle.getBundle(name, Locale.getDefault(), loader);
- assertEquals("Wrong cached value",
- "resource", bundle.getString("property"));
-
- try {
- ResourceBundle.getBundle(null, Locale.getDefault(), loader);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle(name, null, loader);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle(name, Locale.getDefault(), (ClassLoader) null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle("", Locale.getDefault(), loader);
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- // Regression test for Harmony-3823
- B bb = new B();
- String s = bb.find("nonexistent");
- s = bb.find("name");
- assertEquals("Wrong property got", "Name", s);
- }
-
- /**
- * java.util.ResourceBundle#getString(java.lang.String)
- */
- public void test_getStringLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("Wrong value parent4",
- "frFRVARValue4", bundle.getString("parent4"));
- assertEquals("Wrong value parent3",
- "frFRValue3", bundle.getString("parent3"));
- assertEquals("Wrong value parent2",
- "frValue2", bundle.getString("parent2"));
- assertEquals("Wrong value parent1",
- "parentValue1", bundle.getString("parent1"));
- assertEquals("Wrong value child3",
- "frFRVARChildValue3", bundle.getString("child3"));
- assertEquals("Wrong value child2",
- "frFRVARChildValue2", bundle.getString("child2"));
- assertEquals("Wrong value child1",
- "frFRVARChildValue1", bundle.getString("child1"));
-
- try {
- bundle.getString(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- bundle.getString("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- try {
- bundle.getString("IntegerVal");
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
- }
- public void test_getBundle_getClassName() {
- // Regression test for Harmony-1759
- Locale locale = Locale.GERMAN;
- String nonExistentBundle = "Non-ExistentBundle";
- try {
- ResourceBundle.getBundle(nonExistentBundle, locale, this.getClass()
- .getClassLoader());
- fail("MissingResourceException expected!");
- } catch (MissingResourceException e) {
- assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
- }
-
- try {
- ResourceBundle.getBundle(nonExistentBundle, locale);
- fail("MissingResourceException expected!");
- } catch (MissingResourceException e) {
- assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
- }
-
- locale = Locale.getDefault();
- try {
- ResourceBundle.getBundle(nonExistentBundle);
- fail("MissingResourceException expected!");
- } catch (MissingResourceException e) {
- assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
- }
- }
-
- class Mock_ResourceBundle extends ResourceBundle {
- @Override
- public Enumeration<String> getKeys() {
- return null;
- }
-
- @Override
- protected Object handleGetObject(String key) {
- return null;
- }
- }
-
- public void test_constructor() {
- assertNotNull(new Mock_ResourceBundle());
- }
-
- public void test_getLocale() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale loc = Locale.getDefault();
- Locale.setDefault(new Locale("en", "US"));
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("fr_FR_VAR", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
- assertEquals("fr_FR", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
- assertEquals("fr", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
- assertEquals("en_US", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
- assertEquals("en_US", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
- assertEquals("en_US", bundle.getLocale().toString());
-
- Locale.setDefault(loc);
- }
-
- public void test_getObjectLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("Wrong value parent4",
- "frFRVARValue4", (String)bundle.getObject("parent4"));
- assertEquals("Wrong value parent3",
- "frFRValue3", (String)bundle.getObject("parent3"));
- assertEquals("Wrong value parent2",
- "frValue2", (String) bundle.getObject("parent2"));
- assertEquals("Wrong value parent1",
- "parentValue1", (String)bundle.getObject("parent1"));
- assertEquals("Wrong value child3",
- "frFRVARChildValue3", (String)bundle.getObject("child3"));
- assertEquals("Wrong value child2",
- "frFRVARChildValue2", (String) bundle.getObject("child2"));
- assertEquals("Wrong value child1",
- "frFRVARChildValue1", (String)bundle.getObject("child1"));
- assertEquals("Wrong value IntegerVal",
- 1, bundle.getObject("IntegerVal"));
-
- try {
- bundle.getObject(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- bundle.getObject("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
- }
-
- public void test_getStringArrayLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
-
- String[] array = bundle.getStringArray("StringArray");
- for(int i = 0; i < array.length; i++) {
- assertEquals("Str" + (i + 1), array[i]);
- }
-
- try {
- bundle.getStringArray(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- bundle.getStringArray("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- try {
- bundle.getStringArray("IntegerVal");
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
- }
-
- public void test_getBundleLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale defLocale = Locale.getDefault();
-
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("enUSValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("fr", "FR", "v1"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("fr", "US", "VAR"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("de", "FR", "VAR"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle de_FR_var", "parentValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("de", "FR", "v1"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4"));
-
- Locale.setDefault(new Locale("de", "FR", "var"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4"));
-
- try {
- ResourceBundle.getBundle(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- Locale.setDefault(defLocale);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/SampleBundleClass.java b/luni/src/test/java/tests/api/java/util/SampleBundleClass.java
deleted file mode 100644
index ceb0901..0000000
--- a/luni/src/test/java/tests/api/java/util/SampleBundleClass.java
+++ /dev/null
@@ -1,43 +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 tests.api.java.util;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-/**
- * Part of the ResourceBundleTest
- */
-public class SampleBundleClass {
-
- private static SampleBundleClass singleton;
- private static ResourceBundle bundle;
-
- public SampleBundleClass() {
- super();
- if (singleton != null) {
- throw new RuntimeException();
- }
- singleton = this;
- try {
- bundle = ResourceBundle.getBundle("tests.api.simple.SampleBundleClass");
- } catch (MissingResourceException x) {
- System.out.println("Missing resource");
- bundle = null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java b/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java
deleted file mode 100644
index eeb5b30..0000000
--- a/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java
+++ /dev/null
@@ -1,838 +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 tests.api.java.util;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.SimpleTimeZone;
-import java.util.TimeZone;
-
-public class SimpleTimeZoneTest extends junit.framework.TestCase {
-
- SimpleTimeZone st1;
-
- SimpleTimeZone st2;
-
- /**
- * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String)
- */
- public void test_ConstructorILjava_lang_String() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String)
-
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST");
- assertEquals("Incorrect TZ constructed", "TEST", st.getID());
- assertTrue("Incorrect TZ constructed: " + "returned wrong offset", st
- .getRawOffset() == 1000);
- assertTrue("Incorrect TZ constructed" + "using daylight savings", !st
- .useDaylightTime());
- }
-
- /**
- * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
- * int, int, int, int, int, int, int, int)
- */
- public void test_ConstructorILjava_lang_StringIIIIIIII() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
- // int, int, int, int, int, int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- assertTrue("Incorrect TZ constructed", st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("Incorrect TZ constructed", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
- assertEquals("Incorrect TZ constructed", "TEST", st.getID());
- assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset());
- assertTrue("Incorrect TZ constructed", st.useDaylightTime());
-
- try {
- new SimpleTimeZone(1000, "TEST", 12,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
- * int, int, int, int, int, int, int, int, int)
- */
- public void test_ConstructorILjava_lang_StringIIIIIIIII() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
- // int, int, int, int, int, int, int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- assertTrue("Incorrect TZ constructed", st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("Incorrect TZ constructed", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
- assertEquals("Incorrect TZ constructed", "TEST", st.getID());
- assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset());
- assertTrue("Incorrect TZ constructed", st.useDaylightTime());
- assertTrue("Incorrect TZ constructed",
- st.getDSTSavings() == 1000 * 60 * 60);
-
- try {
- new SimpleTimeZone(1000, "TEST", 12,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
- * int, int, int, int, int, int, int, int, int, int, int)
- */
- public void test_ConstructorILjava_lang_StringIIIIIIIIIII() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
- // int, int, int, int, int, int, int, int, int, int)
- // TODO : Implement test
- //Regression for HARMONY-1241
- assertNotNull(new SimpleTimeZone(
- TimeZone.LONG,
- "Europe/Paris",
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.UTC_TIME,
- SimpleTimeZone.WALL_TIME,
- SimpleTimeZone.WALL_TIME,
- TimeZone.SHORT,
- SimpleTimeZone.STANDARD_TIME,
- TimeZone.LONG,
- SimpleTimeZone.UTC_TIME,
- SimpleTimeZone.STANDARD_TIME,
- TimeZone.LONG));
- //seems RI doesn't check the startTimeMode and endTimeMode at all
- //this behavior is contradicts with spec
- assertNotNull(new SimpleTimeZone(
- TimeZone.LONG,
- "Europe/Paris",
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.UTC_TIME,
- SimpleTimeZone.WALL_TIME,
- Integer.MAX_VALUE,
- TimeZone.SHORT,
- SimpleTimeZone.STANDARD_TIME,
- TimeZone.LONG,
- SimpleTimeZone.UTC_TIME,
- Integer.MIN_VALUE,
- TimeZone.LONG));
-
- try {
- new SimpleTimeZone(1000, "TEST", 12,
- 1, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 10, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, 10, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -1, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -10, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.SimpleTimeZone.clone()
- SimpleTimeZone st1 = new SimpleTimeZone(1000, "TEST",
- Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
- -1, Calendar.SUNDAY, 0);
- SimpleTimeZone stA = new SimpleTimeZone(1, "Gah");
- assertTrue("Clone resulted in same reference", st1.clone() != st1);
- assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) st1
- .clone()).equals(st1));
- assertTrue("Clone resulted in same reference", stA.clone() != stA);
- assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) stA
- .clone()).equals(stA));
- }
-
- /**
- * java.util.SimpleTimeZone#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.util.SimpleTimeZone.equals(java.lang.Object)
- TimeZone tz = TimeZone.getTimeZone("EST");
- st1 = new SimpleTimeZone(tz.getRawOffset(), "EST");
- st2 = new SimpleTimeZone(0, "EST");
- assertFalse(st1.equals(st2));
- st1.setRawOffset(st2.getRawOffset());
- assertTrue(st1.equals(st2));
- }
-
- /**
- * java.util.SimpleTimeZone#getDSTSavings()
- */
- public void test_getDSTSavings() {
- // Test for method int java.util.SimpleTimeZone.getDSTSavings()
- st1 = new SimpleTimeZone(0, "TEST");
-
- assertEquals("Non-zero default daylight savings",
- 0, st1.getDSTSavings());
- st1.setStartRule(0, 1, 1, 1);
- st1.setEndRule(11, 1, 1, 1);
-
- assertEquals("Incorrect default daylight savings",
- 3600000, st1.getDSTSavings());
- st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1,
- -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1,
- Calendar.SUNDAY, 2 * 3600000, 7200000);
- assertEquals("Incorrect daylight savings from constructor", 7200000, st1
- .getDSTSavings());
-
- }
-
- /**
- * java.util.SimpleTimeZone#getOffset(int, int, int, int, int, int)
- */
- public void test_getOffsetIIIIII() {
- // Test for method int java.util.SimpleTimeZone.getOffset(int, int, int,
- // int, int, int)
-// TimeZone st1 = TimeZone.getTimeZone("EST");
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- assertTrue("Incorrect offset returned", st1.getOffset(
- GregorianCalendar.AD, 1998, Calendar.NOVEMBER, 11,
- Calendar.WEDNESDAY, 0) == -(5 * 60 * 60 * 1000));
-
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1
- .getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 11,
- Calendar.THURSDAY, 0));
-
- // Regression for HARMONY-5459
- st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID());
- int fourHours = 4*60*60*1000;
- st1.setRawOffset(fourHours);
- assertEquals(fourHours, st1.getOffset(1, 2099, 01, 1, 5, 0));
-
- try {
- st1.getOffset(-1, 2099, 01, 1, 5, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 15, 1, 5, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 01, 100, 5, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 01, 1, 50, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 01, 1, 5, -10);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#getRawOffset()
- */
- public void test_getRawOffset() {
- // Test for method int java.util.SimpleTimeZone.getRawOffset()
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- assertTrue("Incorrect offset returned",
- st1.getRawOffset() == -(5 * 60 * 60 * 1000));
-
- }
-
- /**
- * java.util.SimpleTimeZone#hashCode()
- */
- public void test_hashCode() {
- // Test for method int java.util.SimpleTimeZone.hashCode()
- // For lack of a better test.
- st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1,
- -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1,
- Calendar.SUNDAY, 2 * 3600000);
- assertTrue(TimeZone.getTimeZone("EST").hashCode() != 0);
- assertTrue(st1.hashCode() != 0);
- }
-
- /**
- * java.util.SimpleTimeZone#hasSameRules(java.util.TimeZone)
- */
- public void test_hasSameRulesLjava_util_TimeZone() {
- // Test for method boolean
- // java.util.SimpleTimeZone.hasSameRules(java.util.TimeZone)
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- SimpleTimeZone sameAsSt = new SimpleTimeZone(1000, "REST",
- Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
- -1, Calendar.SUNDAY, 0);
- SimpleTimeZone notSameAsSt = new SimpleTimeZone(1000, "PEST",
- Calendar.NOVEMBER, 2, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
- -1, Calendar.SUNDAY, 0);
- assertTrue("Time zones have same rules but return false", st
- .hasSameRules(sameAsSt));
- assertTrue("Time zones have different rules but return true", !st
- .hasSameRules(notSameAsSt));
- }
-
- /**
- * java.util.SimpleTimeZone#inDaylightTime(java.util.Date)
- */
- public void test_inDaylightTimeLjava_util_Date() {
- // Test for method boolean
- // java.util.SimpleTimeZone.inDaylightTime(java.util.Date)
- TimeZone tz = TimeZone.getTimeZone("EST");
- SimpleTimeZone zone = new SimpleTimeZone(tz.getRawOffset(), "EST",
- Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000, Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000, 3600000);
- GregorianCalendar gc = new GregorianCalendar(1998, Calendar.JUNE, 11);
-
- assertTrue("Returned incorrect daylight value1", zone.inDaylightTime(gc
- .getTime()));
- gc = new GregorianCalendar(1998, Calendar.NOVEMBER, 11);
- assertTrue("Returned incorrect daylight value2", !(zone
- .inDaylightTime(gc.getTime())));
- gc = new GregorianCalendar(zone);
- gc.set(1999, Calendar.APRIL, 4, 1, 59, 59);
- assertTrue("Returned incorrect daylight value3", !(zone
- .inDaylightTime(gc.getTime())));
- Date date = new Date(gc.getTime().getTime() + 1000);
- assertTrue("Returned incorrect daylight value4", zone
- .inDaylightTime(date));
- gc.set(1999, Calendar.OCTOBER, 31, 1, 0, 0);
- assertTrue("Returned incorrect daylight value5", !(zone
- .inDaylightTime(gc.getTime())));
- date = new Date(gc.getTime().getTime() - 1000);
- assertTrue("Returned incorrect daylight value6", zone
- .inDaylightTime(date));
-
- assertTrue("Returned incorrect daylight value7", !zone
- .inDaylightTime(new Date(891752400000L + 7200000 - 1)));
- assertTrue("Returned incorrect daylight value8", zone
- .inDaylightTime(new Date(891752400000L + 7200000)));
- assertTrue("Returned incorrect daylight value9", zone
- .inDaylightTime(new Date(909288000000L + 7200000 - 1)));
- assertTrue("Returned incorrect daylight value10", !zone
- .inDaylightTime(new Date(909288000000L + 7200000)));
- }
-
- /**
- * java.util.SimpleTimeZone#setDSTSavings(int)
- */
- public void test_setDSTSavingsI() {
- // Test for method void java.util.SimpleTimeZone.setDSTSavings(int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- st.setStartRule(0, 1, 1, 1);
- st.setEndRule(11, 1, 1, 1);
- st.setDSTSavings(1);
- assertEquals(1, st.getDSTSavings());
- try {
- st.setDSTSavings(0);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- try {
- st.setDSTSavings(-1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setEndRule(int, int, int)
- */
- public void test_setEndRuleIII() {
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- st.setStartRule(Calendar.NOVEMBER, 1, 0);
- st.setEndRule(Calendar.NOVEMBER, 20, 0);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st.inDaylightTime(
- new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("StartRule improperly set3", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setEndRule(13, 20, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(1, 32, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(1, 30, 10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setEndRule(int, int, int, int)
- */
- public void test_setEndRuleIIII() {
- // Test for method void java.util.SimpleTimeZone.setEndRule(int, int,
- // int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("StartRule improperly set3", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setEndRule(12, -1, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, -1, 8, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setEndRule(int, int, int, int, boolean)
- */
- public void test_setEndRuleIIIIZ() {
- // Test for method void java.util.SimpleTimeZone.setEndRule(int, int,
- // int, int, boolean)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 8, Calendar.SUNDAY, 1, false);
- st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, true);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 7, 12, 0).getTime())));
- assertTrue("StartRule improperly set3", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 20, 12, 0).getTime())));
- assertTrue("StartRule improperly set4", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 6, 12, 0).getTime())));
- assertTrue("StartRule improperly set5", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 21, 12, 0).getTime())));
-
- try {
- st.setEndRule(20, 15, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 15, 12, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setRawOffset(int)
- */
- public void test_setRawOffsetI() {
- // Test for method void java.util.SimpleTimeZone.setRawOffset(int)
-
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- int off = st1.getRawOffset();
- st1.setRawOffset(1000);
- boolean val = st1.getRawOffset() == 1000;
- st1.setRawOffset(off);
- assertTrue("Incorrect offset set", val);
- }
-
- /**
- * java.util.SimpleTimeZone#setStartRule(int, int, int)
- */
- public void test_setStartRuleIII() {
- // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
- // int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, 1);
- st.setEndRule(Calendar.DECEMBER, 1, 1);
- assertTrue("StartRule improperly set", st.useDaylightTime());
- assertTrue("StartRule improperly set", st
- .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime())));
- assertTrue("StartRule improperly set", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setStartRule(13, 20, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(1, 32, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(1, 30, 10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setStartRule(int, int, int, int)
- */
- public void test_setStartRuleIIII() {
- // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
- // int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime())));
- assertTrue("StartRule improperly set3", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setStartRule(12, -1, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, -1, 8, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setStartRule(int, int, int, int, boolean)
- */
- public void test_setStartRuleIIIIZ() {
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
- // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
- // int, int, boolean)
- SimpleTimeZone st = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 1, true);
- st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, false);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 7, 12, 0).getTime())));
- assertTrue("StartRule improperly set3", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 13, 12, 0).getTime())));
- assertTrue("StartRule improperly set4", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 6, 12, 0).getTime())));
- assertTrue("StartRule improperly set5", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 14, 12, 0).getTime())));
-
- try {
- st.setStartRule(20, 15, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 15, 12, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * java.util.SimpleTimeZone#setStartYear(int)
- */
- public void test_setStartYearI() {
- // Test for method void java.util.SimpleTimeZone.setStartYear(int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- st.setStartYear(1999);
- assertTrue("set year improperly set1", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.JULY, 12)
- .getTime())));
- assertTrue("set year improperly set2", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
- assertTrue("set year improperly set3", (st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 13).getTime())));
- }
-
- /**
- * java.util.SimpleTimeZone#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.util.SimpleTimeZone.toString()
- String string = TimeZone.getTimeZone("EST").toString();
- assertNotNull("toString() returned null", string);
- assertTrue("toString() is empty", string.length() != 0);
- }
-
- /**
- * java.util.SimpleTimeZone#useDaylightTime()
- */
- public void test_useDaylightTime() {
- // Test for method boolean java.util.SimpleTimeZone.useDaylightTime()
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- assertTrue("useDaylightTime returned incorrect value", !st
- .useDaylightTime());
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- assertTrue("useDaylightTime returned incorrect value", st
- .useDaylightTime());
- }
-
- public void test_getOffsetJ() {
- Calendar cal = Calendar.getInstance();
- cal.set(1998, Calendar.NOVEMBER, 11, 0, 0);
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
-
- assertTrue("Incorrect offset returned", st1.getOffset(cal.getTimeInMillis()) ==
- -(5 * 60 * 60 * 1000));
-
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- cal.set(1998, Calendar.JUNE, 11, 0, 0);
- assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1
- .getOffset(cal.getTimeInMillis()));
-
- // Regression for HARMONY-5459
- st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID());
- int fourHours = 4*60*60*1000;
- st1.setRawOffset(fourHours);
- cal.set(2099, 01, 1, 0, 0);
-
- assertEquals(fourHours, st1.getOffset(cal.getTimeInMillis()));
-
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/StackTest.java b/luni/src/test/java/tests/api/java/util/StackTest.java
deleted file mode 100644
index 465df13..0000000
--- a/luni/src/test/java/tests/api/java/util/StackTest.java
+++ /dev/null
@@ -1,188 +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 tests.api.java.util;
-
-import java.util.EmptyStackException;
-import java.util.Stack;
-
-public class StackTest extends junit.framework.TestCase {
-
- Stack s;
-
- /**
- * java.util.Stack#Stack()
- */
- public void test_Constructor() {
- // Test for method java.util.Stack()
- assertEquals("Stack creation failed", 0, s.size());
- }
-
- /**
- * java.util.Stack#empty()
- */
- public void test_empty() {
- // Test for method boolean java.util.Stack.empty()
- assertTrue("New stack answers non-empty", s.empty());
- s.push("blah");
- assertTrue("Stack should not be empty but answers empty", !s.empty());
- s.pop();
- assertTrue("Stack should be empty but answers non-empty", s.empty());
- s.push(null);
- assertTrue("Stack with null should not be empty but answers empty", !s
- .empty());
- }
-
- /**
- * java.util.Stack#peek()
- */
- public void test_peek() {
- // Test for method java.lang.Object java.util.Stack.peek()
- String item1 = "Ichi";
- String item2 = "Ni";
- String item3 = "San";
- s.push(item1);
- assertTrue("Peek did not return top item when it was the only item", s
- .peek() == item1);
- s.push(item2);
- s.push(item3);
- assertTrue("Peek did not return top item amoung many other items", s
- .peek() == item3);
- s.pop();
- assertTrue("Peek did not return top item after a pop", s.pop() == item2);
- s.push(null);
- assertNull("Peek did not return top item (wanted: null)",
- s.peek());
- s.pop();
- s.pop();
- try {
- s.pop();
- fail("EmptyStackException expected");
- } catch (EmptyStackException e) {
- //expected
- }
- }
-
- /**
- * java.util.Stack#pop()
- */
- public void test_pop() {
- // Test for method java.lang.Object java.util.Stack.pop()
- String item1 = "Ichi";
- String item2 = "Ni";
- Object lastPopped;
- s.push(item1);
- s.push(item2);
-
- try {
- lastPopped = s.pop();
- assertTrue("a) Pop did not return top item", lastPopped == item2);
- } catch (EmptyStackException e) {
- fail(
- "a) Pop threw EmptyStackException when stack should not have been empty");
- }
-
- try {
- lastPopped = s.pop();
- assertTrue("b) Pop did not return top item", lastPopped == item1);
- } catch (EmptyStackException e) {
- fail(
- "b) Pop threw EmptyStackException when stack should not have been empty");
- }
-
- s.push(null);
- try {
- lastPopped = s.pop();
- assertNull("c) Pop did not return top item", lastPopped);
- } catch (EmptyStackException e) {
- fail(
- "c) Pop threw EmptyStackException when stack should not have been empty");
- }
-
- try {
- lastPopped = s.pop();
- fail(
- "d) Pop did not throw EmptyStackException when stack should have been empty");
- } catch (EmptyStackException e) {
- return;
- }
-
- }
-
- /**
- * java.util.Stack#push(java.lang.Object)
- */
- public void test_pushLjava_lang_Object() {
- Object [] array = {new Integer(0), new Object(),
- new Float(0), new String()};
-
- Stack<Object> stack = new Stack<Object>();
- for(int i = 0; i < array.length; i++) {
- stack.push(array[i]);
- }
- for(int i = 0; i < array.length; i++) {
- assertEquals(array.length - i, stack.search(array[i]));
- }
- }
-
- /**
- * java.util.Stack#search(java.lang.Object)
- */
- public void test_searchLjava_lang_Object() {
- // Test for method int java.util.Stack.search(java.lang.Object)
- String item1 = "Ichi";
- String item2 = "Ni";
- String item3 = "San";
- s.push(item1);
- s.push(item2);
- s.push(item3);
- assertEquals("Search returned incorrect value for equivalent object", 3, s
- .search(item1));
- assertEquals("Search returned incorrect value for equal object", 3, s
- .search("Ichi"));
- s.pop();
- assertEquals("Search returned incorrect value for equivalent object at top of stack",
- 1, s.search(item2));
- assertEquals("Search returned incorrect value for equal object at top of stack",
- 1, s.search("Ni"));
- s.push(null);
- assertEquals("Search returned incorrect value for search for null at top of stack",
- 1, s.search(null));
- s.push("Shi");
- assertEquals("Search returned incorrect value for search for null", 2, s
- .search(null));
- s.pop();
- s.pop();
- assertEquals("Search returned incorrect value for search for null--wanted -1",
- -1, s.search(null));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- s = new Stack();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java b/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java
deleted file mode 100644
index 809ed99..0000000
--- a/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java
+++ /dev/null
@@ -1,225 +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 tests.api.java.util;
-
-import java.util.NoSuchElementException;
-import java.util.StringTokenizer;
-
-public class StringTokenizerTest extends junit.framework.TestCase {
-
- /**
- * java.util.StringTokenizer#StringTokenizer(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.StringTokenizer(java.lang.String)
- try {
- new StringTokenizer(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * java.util.StringTokenizer#StringTokenizer(java.lang.String,
- * java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.StringTokenizer(java.lang.String,
- // java.lang.String)
- StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":");
- assertTrue("Created incorrect tokenizer", st.countTokens() == 5
- && (st.nextElement().equals("This")));
- st = new StringTokenizer("This:is:a:test:String", null);
-
- try {
- new StringTokenizer(null, ":");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.StringTokenizer#StringTokenizer(java.lang.String,
- * java.lang.String, boolean)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_StringZ() {
- // Test for method java.util.StringTokenizer(java.lang.String,
- // java.lang.String, boolean)
- StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":",
- true);
- st.nextElement();
- assertTrue("Created incorrect tokenizer", st.countTokens() == 8
- && (st.nextElement().equals(":")));
- st = new StringTokenizer("This:is:a:test:String", null, true);
- st = new StringTokenizer("This:is:a:test:String", null, false);
-
- try {
- new StringTokenizer(null, ":", true);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.StringTokenizer#countTokens()
- */
- public void test_countTokens() {
- // Test for method int java.util.StringTokenizer.countTokens()
- StringTokenizer st = new StringTokenizer("This is a test String");
-
- assertEquals("Incorrect token count returned", 5, st.countTokens());
- }
-
- /**
- * java.util.StringTokenizer#hasMoreElements()
- */
- public void test_hasMoreElements() {
- // Test for method boolean java.util.StringTokenizer.hasMoreElements()
-
- StringTokenizer st = new StringTokenizer("This is a test String");
- st.nextElement();
- assertTrue("hasMoreElements returned incorrect value", st
- .hasMoreElements());
- st.nextElement();
- st.nextElement();
- st.nextElement();
- st.nextElement();
- assertTrue("hasMoreElements returned incorrect value", !st
- .hasMoreElements());
- }
-
- /**
- * java.util.StringTokenizer#hasMoreTokens()
- */
- public void test_hasMoreTokens() {
- // Test for method boolean java.util.StringTokenizer.hasMoreTokens()
- StringTokenizer st = new StringTokenizer("This is a test String");
- for (int counter = 0; counter < 5; counter++) {
- assertTrue(
- "StringTokenizer incorrectly reports it has no more tokens",
- st.hasMoreTokens());
- st.nextToken();
- }
- assertTrue("StringTokenizer incorrectly reports it has more tokens",
- !st.hasMoreTokens());
- }
-
- /**
- * java.util.StringTokenizer#nextElement()
- */
- public void test_nextElement() {
- // Test for method java.lang.Object
- // java.util.StringTokenizer.nextElement()
- StringTokenizer st = new StringTokenizer("This is a test String");
- assertEquals("nextElement returned incorrect value", "This", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "is", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "a", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "test", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "String", ((String) st
- .nextElement()));
- try {
- st.nextElement();
- fail(
- "nextElement failed to throw a NoSuchElementException when it should have been out of elements");
- } catch (NoSuchElementException e) {
- return;
- }
- }
-
- /**
- * java.util.StringTokenizer#nextToken()
- */
- public void test_nextToken() {
- // Test for method java.lang.String
- // java.util.StringTokenizer.nextToken()
- StringTokenizer st = new StringTokenizer("This is a test String");
- assertEquals("nextToken returned incorrect value",
- "This", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "is", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "a", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "test", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "String", st.nextToken());
- try {
- st.nextToken();
- fail(
- "nextToken failed to throw a NoSuchElementException when it should have been out of elements");
- } catch (NoSuchElementException e) {
- return;
- }
- }
-
- /**
- * java.util.StringTokenizer#nextToken(java.lang.String)
- */
- public void test_nextTokenLjava_lang_String() {
- // Test for method java.lang.String
- // java.util.StringTokenizer.nextToken(java.lang.String)
- StringTokenizer st = new StringTokenizer("This is a test String");
- assertEquals("nextToken(String) returned incorrect value with normal token String",
- "This", st.nextToken(" "));
- assertEquals("nextToken(String) returned incorrect value with custom token String",
- " is a ", st.nextToken("tr"));
- assertEquals("calling nextToken() did not use the new default delimiter list",
- "es", st.nextToken());
- st = new StringTokenizer("This:is:a:test:String", " ");
- assertTrue(st.nextToken(":").equals("This"));
- assertTrue(st.nextToken(":").equals("is"));
- assertTrue(st.nextToken(":").equals("a"));
- assertTrue(st.nextToken(":").equals("test"));
- assertTrue(st.nextToken(":").equals("String"));
-
- try {
- st.nextToken(":");
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- try {
- st.nextToken(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TimerTaskTest.java b/luni/src/test/java/tests/api/java/util/TimerTaskTest.java
deleted file mode 100644
index 97ff8ea..0000000
--- a/luni/src/test/java/tests/api/java/util/TimerTaskTest.java
+++ /dev/null
@@ -1,248 +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 tests.api.java.util;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-public class TimerTaskTest extends junit.framework.TestCase {
- /**
- * Warning: These tests have the possibility to leave a VM hanging if the
- * Timer is not cancelled.
- */
- class TimerTestTask extends TimerTask {
-
- private final Object sync = new Object();
- private final Object start = new Object();
-
- private int wasRun = 0;
-
- // Set this to true to see normal tests fail (or hang possibly)
- // The default is false and needs to be set by some tests
- private boolean sleepInRun = false;
-
- public void run() {
- synchronized (this) {
- wasRun++;
- }
- synchronized (start) {
- start.notify();
- }
- if (sleepInRun) {
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- }
- synchronized (sync) {
- sync.notify();
- }
- }
-
- public synchronized int wasRun() {
- return wasRun;
- }
-
- public void sleepInRun(boolean value) {
- sleepInRun = value;
- }
- }
-
- /**
- * java.util.TimerTask#TimerTask()
- */
- public void test_Constructor() {
- // Ensure the constructor does not fail
- new TimerTestTask();
- }
-
- /**
- * java.util.TimerTask#cancel()
- */
- public void test_cancel() {
- Timer t = null;
- try {
- // Ensure cancel returns false if never scheduled
- TimerTestTask testTask = new TimerTestTask();
- assertTrue("Unsheduled tasks should return false for cancel()",
- !testTask.cancel());
-
- // Ensure cancelled task never runs
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 500);
- assertTrue("TimerTask should not have run yet", testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a task which has already run returns true
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 50);
- while (testTask.wasRun() == 0) {
- try {
- Thread.sleep(150);
- } catch (InterruptedException e) {
- }
- }
- assertFalse(
- "TimerTask.cancel() should return false if task has run",
- testTask.cancel());
- assertFalse(
- "TimerTask.cancel() should return false if called a second time",
- testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a repeated execution task which has never run
- // returns true
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 500, 500); // should never run
- assertTrue(
- "TimerTask.cancel() should return true if sheduled for repeated execution even if not run",
- testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a repeated execution task which HAS run returns
- // true
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 50, 50);
- while (testTask.wasRun() == 0) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- }
- assertTrue(
- "TimerTask.cancel() should return true if sheduled for repeated execution and run",
- testTask.cancel());
- t.cancel();
-
- // Ensure calling cancel a second returns false
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 5000); // Should never run
- assertTrue(
- "TimerTask.cancel() should return true if task has never run",
- testTask.cancel());
- assertFalse(
- "TimerTask.cancel() should return false if called a second time",
- testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a task won't cause deadlock
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.sleepInRun(true);
- synchronized (testTask.start) {
- t.schedule(testTask, 0);
- try {
- testTask.start.wait();
- Thread.sleep(50);
- } catch (InterruptedException e) {
- }
- }
- assertFalse("TimerTask should have been cancelled", testTask
- .cancel());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * java.util.TimerTask#scheduledExecutionTime()
- */
- public void test_scheduledExecutionTime() {
- Timer t = null;
- try {
- // Ensure scheduledExecutionTime is roughly right
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 100);
- long time = System.currentTimeMillis() + 100;
- synchronized (testTask.sync) {
- try {
- testTask.sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- long scheduledExecutionTime = testTask.scheduledExecutionTime();
- assertTrue(scheduledExecutionTime <= time);
- t.cancel();
-
- // Ensure scheduledExecutionTime is the last scheduled time
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 500);
- long estNow = System.currentTimeMillis() + 100;
- // Will wake in 100, and every 500 run again
- // We want to try to get it after it's run at least once but not
- // twice
- synchronized (testTask.sync) {
- try {
- testTask.sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- scheduledExecutionTime = testTask.scheduledExecutionTime();
- assertTrue(scheduledExecutionTime <= estNow);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * java.util.TimerTask#run()
- */
- public void test_run() {
- Timer t = null;
- try {
- // Ensure a new task is never run
- TimerTestTask testTask = new TimerTestTask();
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- assertEquals("TimerTask.run() method should not have been called",
- 0, testTask.wasRun());
-
- // Ensure a task is run
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- while(testTask.wasRun() < 1) {
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- }
- assertFalse(testTask.cancel());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TimerTest.java b/luni/src/test/java/tests/api/java/util/TimerTest.java
deleted file mode 100644
index 739c018..0000000
--- a/luni/src/test/java/tests/api/java/util/TimerTest.java
+++ /dev/null
@@ -1,986 +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 tests.api.java.util;
-
-import java.lang.Thread.UncaughtExceptionHandler;
-import java.util.Date;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.atomic.AtomicReference;
-import junit.framework.TestCase;
-
-public class TimerTest extends TestCase {
-
- int timerCounter = 0;
-
- private final Object sync = new Object();
-
- /**
- * Warning: These tests have the possibility to leave a VM hanging if the
- * Timer is not cancelled.
- */
- class TimerTestTask extends TimerTask {
- int wasRun = 0;
-
- // Should we sleep for 200 ms each run()?
- boolean sleepInRun = false;
-
- // Should we increment the timerCounter?
- boolean incrementCount = false;
-
- // Should we terminate the timer at a specific timerCounter?
- int terminateCount = -1;
-
- // The timer we belong to
- Timer timer = null;
-
- public TimerTestTask() {
- }
-
- public TimerTestTask(Timer t) {
- timer = t;
- }
-
- public void run() {
- synchronized (this) {
- wasRun++;
- }
- if (incrementCount) {
- timerCounter++;
- }
- if (terminateCount == timerCounter && timer != null) {
- timer.cancel();
- }
- if (sleepInRun) {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- synchronized (sync) {
- sync.notify();
- }
- }
-
- public synchronized int wasRun() {
- return wasRun;
- }
-
- public void sleepInRun(boolean sleepInRun) {
- this.sleepInRun = sleepInRun;
- }
-
- public void incrementCount(boolean incrementCount) {
- this.incrementCount = incrementCount;
- }
-
- public void terminateCount(int terminateCount) {
- this.terminateCount = terminateCount;
- }
- }
-
- private void awaitRun(TimerTestTask task) throws Exception {
- while (task.wasRun() == 0) {
- Thread.sleep(150);
- }
- }
-
- /**
- * java.util.Timer#Timer(boolean)
- */
- public void test_ConstructorZ() throws Exception {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer(true);
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- awaitRun(testTask);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * java.util.Timer#Timer()
- */
- public void test_Constructor() throws Exception {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- awaitRun(testTask);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * java.util.Timer#Timer(String, boolean)
- */
- public void test_ConstructorSZ() throws Exception {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer("test_ConstructorSZThread", true);
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- awaitRun(testTask);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- try {
- new Timer(null, true);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- new Timer(null, false);
- fail();
- } catch (NullPointerException expected) {
- }
- }
-
- /**
- * java.util.Timer#Timer(String)
- */
- public void test_ConstructorS() throws Exception {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer("test_ConstructorSThread");
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- awaitRun(testTask);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- try {
- new Timer(null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
-
- /**
- * java.util.Timer#cancel()
- */
- public void test_cancel() throws Exception {
- Timer t = null;
- try {
- // Ensure a task throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- try {
- t.schedule(testTask, 100, 200);
- fail("Scheduling a task after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a task is run but not after cancel
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 500);
- awaitRun(testTask);
- t.cancel();
- synchronized (sync) {
- sync.wait(500);
- }
- assertEquals("TimerTask.run() method should not have been called after cancel",
- 1, testTask.wasRun());
-
- // Ensure you can call cancel more than once
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 500);
- awaitRun(testTask);
- t.cancel();
- t.cancel();
- t.cancel();
- synchronized (sync) {
- sync.wait(500);
- }
- assertEquals("TimerTask.run() method should not have been called after cancel",
- 1, testTask.wasRun());
-
- // Ensure that a call to cancel from within a timer ensures no more
- // run
- t = new Timer();
- testTask = new TimerTestTask(t);
- testTask.incrementCount(true);
- testTask.terminateCount(5); // Terminate after 5 runs
- t.schedule(testTask, 100, 100);
- synchronized (sync) {
- sync.wait(200);
- assertEquals(1, testTask.wasRun());
- sync.wait(200);
- assertEquals(2, testTask.wasRun());
- sync.wait(200);
- assertEquals(3, testTask.wasRun());
- sync.wait(200);
- assertEquals(4, testTask.wasRun());
- sync.wait(200);
- assertEquals(5, testTask.wasRun());
- sync.wait(200);
- assertEquals(5, testTask.wasRun());
- }
- t.cancel();
- Thread.sleep(200);
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * java.util.Timer#purge()
- */
- public void test_purge() throws Exception {
- Timer t = null;
- try {
- t = new Timer();
- assertEquals(0, t.purge());
-
- TimerTestTask[] tasks = new TimerTestTask[100];
- int[] delayTime = { 50, 80, 20, 70, 40, 10, 90, 30, 60 };
-
- int j = 0;
- for (int i = 0; i < 100; i++) {
- tasks[i] = new TimerTestTask();
- t.schedule(tasks[i], delayTime[j++], 200);
- if (j == 9) {
- j = 0;
- }
- }
-
- for (int i = 0; i < 50; i++) {
- tasks[i].cancel();
- }
-
- assertTrue(t.purge() <= 50);
- assertEquals(0, t.purge());
- } finally {
- if (t != null) {
- t.cancel();
- }
- }
- }
-
- /**
- * java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
- */
- public void test_scheduleLjava_util_TimerTaskLjava_util_Date() throws Exception {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- Date d = new Date(System.currentTimeMillis() + 100);
- t.cancel();
- try {
- t.schedule(testTask, d);
- fail("Scheduling a task after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(System.currentTimeMillis() + 100);
- testTask.cancel();
- try {
- t.schedule(testTask, d);
- fail("Scheduling a task after cancelling it should throw exception");
- } catch (IllegalStateException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(-100);
- try {
- t.schedule(testTask, d);
- fail("Scheduling a task with negative date should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- try {
- t.schedule(null, d);
- fail("Scheduling a null task should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the date is null
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, null);
- fail("Scheduling a null date should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- d = new Date(-100);
- try {
- t.schedule(null, d);
- fail("Scheduling a null task with negative date should throw IllegalArgumentException first");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a task is run
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(System.currentTimeMillis() + 200);
- t.schedule(testTask, d);
- awaitRun(testTask);
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 100);
- t.schedule(testTask, d);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 150);
- t.schedule(testTask, d);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 70);
- t.schedule(testTask, d);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 10);
- t.schedule(testTask, d);
- Thread.sleep(400);
- assertTrue("Multiple tasks should have incremented counter 4 times not "
- + timerCounter, timerCounter == 4);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * java.util.Timer#schedule(java.util.TimerTask, long)
- */
- public void test_scheduleLjava_util_TimerTaskJ() throws Exception {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- try {
- t.schedule(testTask, 100);
- fail("Scheduling a task after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.cancel();
- try {
- t.schedule(testTask, 100);
- fail("Scheduling a task after cancelling it should throw exception");
- } catch (IllegalStateException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, -100);
- fail("Scheduling a task with negative delay should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- try {
- t.schedule(null, 10);
- fail("Scheduling a null task should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- try {
- t.schedule(null, -10);
- fail("Scheduling a null task with negative delays should throw IllegalArgumentException first");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a task is run
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- awaitRun(testTask);
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 100);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 150);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 70);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 10);
- Thread.sleep(400);
- assertTrue("Multiple tasks should have incremented counter 4 times not "
- + timerCounter, timerCounter == 4);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * java.util.Timer#schedule(java.util.TimerTask, long, long)
- */
- public void test_scheduleLjava_util_TimerTaskJJ() throws Exception {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- try {
- t.schedule(testTask, 100, 100);
- fail("Scheduling a task after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.cancel();
- try {
- t.schedule(testTask, 100, 100);
- fail("Scheduling a task after cancelling it should throw exception");
- } catch (IllegalStateException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, -100, 100);
- fail("Scheduling a task with negative delay should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, 100, -100);
- fail("Scheduling a task with negative period should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // zero
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, 100, 0);
- fail("Scheduling a task with 0 period should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- try {
- t.schedule(null, 10, 10);
- fail("Scheduling a null task should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- try {
- t.schedule(null, -10, -10);
- fail("Scheduling a null task with negative delays should throw IllegalArgumentException first");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 100);
- Thread.sleep(400);
- assertTrue("TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 100, 100); // at least 9 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 200, 100); // at least 7 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 300, 200); // at least 4 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 100, 200); // at least 4 times
- Thread.sleep(1200); // Allowed more room for error
- assertTrue("Multiple tasks should have incremented counter 24 times not "
- + timerCounter, timerCounter >= 24);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * java.util.Timer#schedule(java.util.TimerTask, java.util.Date,
- * long)
- */
- public void test_scheduleLjava_util_TimerTaskLjava_util_DateJ() throws Exception {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- Date d = new Date(System.currentTimeMillis() + 100);
- t.cancel();
- try {
- t.schedule(testTask, d, 100);
- fail("Scheduling a task after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- testTask = new TimerTestTask();
- testTask.cancel();
- try {
- t.schedule(testTask, d, 100);
- fail("Scheduling a task after cancelling it should throw exception");
- } catch (IllegalStateException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- d = new Date(-100);
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, d, 100);
- fail("Scheduling a task with negative delay should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, d, -100);
- fail("Scheduling a task with negative period should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- try {
- t.schedule(null, d, 10);
- fail("Scheduling a null task should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the date is null
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.schedule(testTask, null, 10);
- fail("Scheduling a null task should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- d = new Date(-100);
- try {
- t.schedule(null, d, 10);
- fail("Scheduling a null task with negative dates should throw IllegalArgumentException first");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- testTask = new TimerTestTask();
- t.schedule(testTask, d, 100);
- Thread.sleep(800);
- assertTrue("TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 100);
- t.schedule(testTask, d, 100); // at least 9 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 200);
- t.schedule(testTask, d, 100); // at least 7 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 300);
- t.schedule(testTask, d, 200); // at least 4 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 100);
- t.schedule(testTask, d, 200); // at least 4 times
- Thread.sleep(3000);
- assertTrue("Multiple tasks should have incremented counter 24 times not "
- + timerCounter, timerCounter >= 24);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long,
- * long)
- */
- public void test_scheduleAtFixedRateLjava_util_TimerTaskJJ() throws Exception {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- try {
- t.scheduleAtFixedRate(testTask, 100, 100);
- fail("scheduleAtFixedRate after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.scheduleAtFixedRate(testTask, -100, 100);
- fail("scheduleAtFixedRate with negative delay should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.scheduleAtFixedRate(testTask, 100, -100);
- fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- testTask = new TimerTestTask();
- t.scheduleAtFixedRate(testTask, 100, 100);
- Thread.sleep(400);
- assertTrue("TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- class SlowThenFastTask extends TimerTask {
- int wasRun = 0;
-
- long startedAt;
-
- long lastDelta;
-
- public void run() {
- if (wasRun == 0)
- startedAt = System.currentTimeMillis();
- lastDelta = System.currentTimeMillis()
- - (startedAt + (100 * wasRun));
- wasRun++;
- if (wasRun == 2) {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- public long lastDelta() {
- return lastDelta;
- }
-
- public int wasRun() {
- return wasRun;
- }
- }
-
- // Ensure multiple tasks are run
- t = new Timer();
- SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
-
- // at least 9 times even when asleep
- t.scheduleAtFixedRate(slowThenFastTask, 100, 100);
- Thread.sleep(1000);
- long lastDelta = slowThenFastTask.lastDelta();
- assertTrue("Fixed Rate Schedule should catch up, but is off by "
- + lastDelta + " ms", slowThenFastTask.lastDelta < 300);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask,
- * java.util.Date, long)
- */
- public void test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ() throws Exception {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- Date d = new Date(System.currentTimeMillis() + 100);
- try {
- t.scheduleAtFixedRate(testTask, d, 100);
- fail("scheduleAtFixedRate after Timer.cancel() should throw exception");
- } catch (IllegalStateException expected) {
- }
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(-100);
- try {
- t.scheduleAtFixedRate(testTask, d, 100);
- fail("scheduleAtFixedRate with negative Date should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.scheduleAtFixedRate(testTask, d, -100);
- fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a Timer throws an NullPointerException if date is Null
- t = new Timer();
- testTask = new TimerTestTask();
- try {
- t.scheduleAtFixedRate(testTask, null, 100);
- fail("scheduleAtFixedRate with null date should throw NullPointerException");
- } catch (NullPointerException expected) {
- }
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- d = new Date(-100);
- try {
- t.scheduleAtFixedRate(null, d, 10);
- fail("Scheduling a null task with negative date should throw IllegalArgumentException first");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- try {
- t.scheduleAtFixedRate(null, null, -10);
- fail("Scheduling a null task & null date & negative period should throw IllegalArgumentException first");
- } catch (IllegalArgumentException expected) {
- }
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(System.currentTimeMillis() + 100);
- t.scheduleAtFixedRate(testTask, d, 100);
- Thread.sleep(400);
- assertTrue("TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- class SlowThenFastTask extends TimerTask {
- int wasRun = 0;
-
- long startedAt;
-
- long lastDelta;
-
- public void run() {
- if (wasRun == 0)
- startedAt = System.currentTimeMillis();
- lastDelta = System.currentTimeMillis()
- - (startedAt + (100 * wasRun));
- wasRun++;
- if (wasRun == 2) {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- public long lastDelta() {
- return lastDelta;
- }
-
- public int wasRun() {
- return wasRun;
- }
- }
-
- // Ensure multiple tasks are run
- t = new Timer();
- SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
- d = new Date(System.currentTimeMillis() + 100);
-
- // at least 9 times even when asleep
- t.scheduleAtFixedRate(slowThenFastTask, d, 100);
- Thread.sleep(1000);
- long lastDelta = slowThenFastTask.lastDelta();
- assertTrue("Fixed Rate Schedule should catch up, but is off by "
- + lastDelta + " ms", lastDelta < 300);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * We used to swallow RuntimeExceptions thrown by tasks. Instead, we need to
- * let those exceptions bubble up, where they will both notify the thread's
- * uncaught exception handler and terminate the timer's thread.
- */
- public void testThrowingTaskKillsTimerThread() throws Exception {
- final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
- new Timer().schedule(new TimerTask() {
- @Override public void run() {
- Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
- public void uncaughtException(Thread thread, Throwable ex) {}
- });
- threadRef.set(Thread.currentThread());
- throw new RuntimeException("task failure!");
- }
- }, 1);
-
- Thread.sleep(400);
- Thread timerThread = threadRef.get();
- assertFalse(timerThread.isAlive());
- }
-
- protected void setUp() {
- timerCounter = 0;
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java b/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java
deleted file mode 100644
index 48df5fd..0000000
--- a/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java
+++ /dev/null
@@ -1,64 +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 tests.api.java.util;
-
-import java.util.TooManyListenersException;
-
-public class TooManyListenersExceptionTest extends junit.framework.TestCase {
-
- /**
- * java.util.TooManyListenersException#TooManyListenersException()
- */
- public void test_Constructor() {
- // Test for method java.util.TooManyListenersException()
- try {
- throw new TooManyListenersException();
- } catch (TooManyListenersException e) {
- assertNull(
- "Message thrown with exception constructed with no message",
- e.getMessage());
- }
- }
-
- /**
- * java.util.TooManyListenersException#TooManyListenersException(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.TooManyListenersException(java.lang.String)
- try {
- throw new TooManyListenersException("Gah");
- } catch (TooManyListenersException e) {
- assertEquals("Incorrect message thrown with exception", "Gah", e
- .getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/VectorTest.java b/luni/src/test/java/tests/api/java/util/VectorTest.java
deleted file mode 100644
index 6228cb3..0000000
--- a/luni/src/test/java/tests/api/java/util/VectorTest.java
+++ /dev/null
@@ -1,1198 +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 tests.api.java.util;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
-import tests.support.Support_ListTest;
-
-public class VectorTest extends junit.framework.TestCase {
-
- private Vector tVector = new Vector();
-
- Object[] objArray;
-
- private String vString = "[Test 0, Test 1, Test 2, Test 3, Test 4, Test 5, Test 6, Test 7, Test 8, Test 9, Test 10, Test 11, Test 12, Test 13, Test 14, Test 15, Test 16, Test 17, Test 18, Test 19, Test 20, Test 21, Test 22, Test 23, Test 24, Test 25, Test 26, Test 27, Test 28, Test 29, Test 30, Test 31, Test 32, Test 33, Test 34, Test 35, Test 36, Test 37, Test 38, Test 39, Test 40, Test 41, Test 42, Test 43, Test 44, Test 45, Test 46, Test 47, Test 48, Test 49, Test 50, Test 51, Test 52, Test 53, Test 54, Test 55, Test 56, Test 57, Test 58, Test 59, Test 60, Test 61, Test 62, Test 63, Test 64, Test 65, Test 66, Test 67, Test 68, Test 69, Test 70, Test 71, Test 72, Test 73, Test 74, Test 75, Test 76, Test 77, Test 78, Test 79, Test 80, Test 81, Test 82, Test 83, Test 84, Test 85, Test 86, Test 87, Test 88, Test 89, Test 90, Test 91, Test 92, Test 93, Test 94, Test 95, Test 96, Test 97, Test 98, Test 99]";
-
- /**
- * java.util.Vector#Vector()
- */
- public void test_Constructor() {
- // Test for method java.util.Vector()
-
- Vector tv = new Vector(100);
- for (int i = 0; i < 100; i++)
- tv.addElement(new Integer(i));
- new Support_ListTest("", tv).runTest();
-
- tv = new Vector(200);
- for (int i = -50; i < 150; i++)
- tv.addElement(new Integer(i));
- new Support_ListTest("", tv.subList(50, 150)).runTest();
-
- Vector v = new Vector();
- assertEquals("Vector creation failed", 0, v.size());
- assertEquals("Wrong capacity", 10, v.capacity());
- }
-
- /**
- * java.util.Vector#Vector(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.Vector(int)
-
- Vector v = new Vector(100);
- assertEquals("Vector creation failed", 0, v.size());
- assertEquals("Wrong capacity", 100, v.capacity());
-
- try {
- new Vector(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#Vector(int, int)
- */
- public void test_ConstructorII() {
- // Test for method java.util.Vector(int, int)
-
- Vector v = new Vector(2, 10);
- v.addElement(new Object());
- v.addElement(new Object());
- v.addElement(new Object());
-
- assertEquals("Failed to inc capacity by proper amount",
- 12, v.capacity());
-
- Vector grow = new Vector(3, -1);
- grow.addElement("one");
- grow.addElement("two");
- grow.addElement("three");
- grow.addElement("four");
- assertEquals("Wrong size", 4, grow.size());
- assertEquals("Wrong capacity", 6, grow.capacity());
-
- try {
- new Vector(-1, 1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#Vector(java.util.Collection)
- */
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.Vector(java.util.Collection)
- Collection l = new LinkedList();
- for (int i = 0; i < 100; i++)
- l.add("Test " + i);
- Vector myVector = new Vector(l);
- assertTrue("Vector is not correct size",
- myVector.size() == objArray.length);
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("Vector does not contain correct elements", myVector
- .contains(((List) l).get(counter)));
-
- try {
- new Vector(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#add(int, java.lang.Object)
- */
- public void test_addILjava_lang_Object() {
- // Test for method void java.util.Vector.add(int, java.lang.Object)
- Object o = new Object();
- Object prev = tVector.get(45);
- tVector.add(45, o);
- assertTrue("Failed to add Object", tVector.get(45) == o);
- assertTrue("Failed to fix-up existing indices", tVector.get(46) == prev);
- assertEquals("Wrong size after add", 101, tVector.size());
-
- prev = tVector.get(50);
- tVector.add(50, null);
- assertNull("Failed to add null", tVector.get(50));
- assertTrue("Failed to fix-up existing indices after adding null",
- tVector.get(51) == prev);
- assertEquals("Wrong size after add", 102, tVector.size());
-
- try {
- tVector.add(-5, null);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.add(tVector.size() + 1, null);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#add(java.lang.Object)
- */
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.Vector.add(java.lang.Object)
- Object o = new Object();
- tVector.add(o);
- assertTrue("Failed to add Object", tVector.lastElement() == o);
- assertEquals("Wrong size after add", 101, tVector.size());
-
- tVector.add(null);
- assertNull("Failed to add null", tVector.lastElement());
- assertEquals("Wrong size after add", 102, tVector.size());
- }
-
- /**
- * java.util.Vector#addAll(int, java.util.Collection)
- */
- public void test_addAllILjava_util_Collection() {
- // Test for method boolean java.util.Vector.addAll(int,
- // java.util.Collection)
- Collection l = new LinkedList();
- for (int i = 0; i < 100; i++)
- l.add("Test " + i);
- Vector v = new Vector();
- tVector.addAll(50, l);
- for (int i = 50; i < 100; i++)
- assertTrue("Failed to add all elements",
- tVector.get(i) == ((List) l).get(i - 50));
- v = new Vector();
- v.add("one");
- int r = 0;
- try {
- v.addAll(3, Arrays.asList(new String[] { "two", "three" }));
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- } catch (IndexOutOfBoundsException e) {
- r = 2;
- }
- assertTrue("Invalid add: " + r, r == 1);
- l = new LinkedList();
- l.add(null);
- l.add("gah");
- l.add(null);
- tVector.addAll(50, l);
- assertNull("Wrong element at position 50--wanted null",
- tVector.get(50));
- assertEquals("Wrong element at position 51--wanted 'gah'", "gah", tVector
- .get(51));
- assertNull("Wrong element at position 52--wanted null",
- tVector.get(52));
-
- try {
- tVector.addAll(-5, Arrays.asList(new String[] { "two", "three" }));
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.addAll(tVector.size() + 1, Arrays.asList(new String[] { "two", "three" }));
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.addAll(tVector.size() / 2, null);
- fail("NullPointerException expected");
- } catch(NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#addAll(java.util.Collection)
- */
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean java.util.Vector.addAll(java.util.Collection)
- Vector v = new Vector();
- Collection l = new LinkedList();
- for (int i = 0; i < 100; i++)
- l.add("Test " + i);
- v.addAll(l);
- assertTrue("Failed to add all elements", tVector.equals(v));
-
- v.addAll(l);
- int vSize = tVector.size();
- for (int counter = vSize - 1; counter >= 0; counter--)
- assertTrue("Failed to add elements correctly", v.get(counter) == v
- .get(counter + vSize));
-
- l = new LinkedList();
- l.add(null);
- l.add("gah");
- l.add(null);
- tVector.addAll(l);
- assertNull("Wrong element at 3rd last position--wanted null", tVector
- .get(vSize));
- assertEquals("Wrong element at 2nd last position--wanted 'gah'", "gah", tVector
- .get(vSize + 1));
- assertNull("Wrong element at last position--wanted null", tVector
- .get(vSize + 2));
-
- try {
- tVector.addAll(tVector.size() / 2, null);
- fail("NullPointerException expected");
- } catch(NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#addElement(java.lang.Object)
- */
- public void test_addElementLjava_lang_Object() {
- // Test for method void java.util.Vector.addElement(java.lang.Object)
- Vector v = vectorClone(tVector);
- v.addElement("Added Element");
- assertTrue("Failed to add element", v.contains("Added Element"));
- assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100))
- );
- v.addElement(null);
- assertTrue("Failed to add null", v.contains(null));
- assertNull("Added null to wrong slot", v.elementAt(101));
- }
-
- /**
- * java.util.Vector#addElement(java.lang.Object)
- */
- public void test_addElementLjava_lang_Object_subtest0() {
- // Test for method void java.util.Vector.addElement(java.lang.Object)
- Vector v = vectorClone(tVector);
- v.addElement("Added Element");
- assertTrue("Failed to add element", v.contains("Added Element"));
- assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100))
- );
- v.addElement(null);
- assertTrue("Failed to add null", v.contains(null));
- assertNull("Added null to wrong slot", v.elementAt(101));
- }
-
- /**
- * java.util.Vector#capacity()
- */
- public void test_capacity() {
- // Test for method int java.util.Vector.capacity()
-
- Vector v = new Vector(9);
- assertEquals("Incorrect capacity returned", 9, v.capacity());
- }
-
- /**
- * java.util.Vector#clear()
- */
- public void test_clear() {
- // Test for method void java.util.Vector.clear()
- Vector orgVector = vectorClone(tVector);
- tVector.clear();
- assertEquals("a) Cleared Vector has non-zero size", 0, tVector.size());
- Enumeration e = orgVector.elements();
- while (e.hasMoreElements())
- assertTrue("a) Cleared vector contained elements", !tVector
- .contains(e.nextElement()));
-
- tVector.add(null);
- tVector.clear();
- assertEquals("b) Cleared Vector has non-zero size", 0, tVector.size());
- e = orgVector.elements();
- while (e.hasMoreElements())
- assertTrue("b) Cleared vector contained elements", !tVector
- .contains(e.nextElement()));
- }
-
- /**
- * java.util.Vector#clone()
- */
- public void test_clone() {
- // Test for method java.lang.Object java.util.Vector.clone()
- tVector.add(25, null);
- tVector.add(75, null);
- Vector v = (Vector) tVector.clone();
- Enumeration orgNum = tVector.elements();
- Enumeration cnum = v.elements();
-
- while (orgNum.hasMoreElements()) {
- assertTrue("Not enough elements copied", cnum.hasMoreElements());
- assertTrue("Vector cloned improperly, elements do not match",
- orgNum.nextElement() == cnum.nextElement());
- }
- assertTrue("Not enough elements copied", !cnum.hasMoreElements());
-
- }
-
- /**
- * java.util.Vector#contains(java.lang.Object)
- */
- public void test_containsLjava_lang_Object() {
- // Test for method boolean java.util.Vector.contains(java.lang.Object)
- assertTrue("Did not find element", tVector.contains("Test 42"));
- assertTrue("Found bogus element", !tVector.contains("Hello"));
- assertTrue(
- "Returned true looking for null in vector without null element",
- !tVector.contains(null));
- tVector.insertElementAt(null, 20);
- assertTrue(
- "Returned false looking for null in vector with null element",
- tVector.contains(null));
- }
-
- /**
- * java.util.Vector#containsAll(java.util.Collection)
- */
- public void test_containsAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.Vector.containsAll(java.util.Collection)
- Collection s = new HashSet();
- for (int i = 0; i < 100; i++)
- s.add("Test " + i);
-
- assertTrue("Returned false for valid collection", tVector
- .containsAll(s));
- s.add(null);
- assertTrue("Returned true for invlaid collection containing null",
- !tVector.containsAll(s));
- tVector.add(25, null);
- assertTrue("Returned false for valid collection containing null",
- tVector.containsAll(s));
- s = new HashSet();
- s.add(new Object());
- assertTrue("Returned true for invalid collection", !tVector
- .containsAll(s));
-
- try {
- tVector.containsAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#copyInto(java.lang.Object[])
- */
- public void test_copyInto$Ljava_lang_Object() {
- // Test for method void java.util.Vector.copyInto(java.lang.Object [])
-
- Object[] a = new Object[100];
- tVector.setElementAt(null, 20);
- tVector.copyInto(a);
-
- for (int i = 0; i < 100; i++)
- assertTrue("copyInto failed", a[i] == tVector.elementAt(i));
-
- try {
- tVector.copyInto(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#elementAt(int)
- */
- public void test_elementAtI() {
- // Test for method java.lang.Object java.util.Vector.elementAt(int)
- assertEquals("Incorrect element returned", "Test 18", ((String) tVector
- .elementAt(18)));
- tVector.setElementAt(null, 20);
- assertNull("Incorrect element returned--wanted null", tVector
- .elementAt(20));
-
- try {
- tVector.elementAt(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.elementAt(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#elements()
- */
- public void test_elements() {
- // Test for method java.util.Enumeration java.util.Vector.elements()
- tVector.insertElementAt(null, 20);
- Enumeration e = tVector.elements();
- int i = 0;
- while (e.hasMoreElements()) {
- assertTrue("Enumeration returned incorrect element at pos: " + i, e
- .nextElement() == tVector.elementAt(i));
- i++;
- }
- assertTrue("Invalid enumeration", i == tVector.size());
- }
-
- /**
- * java.util.Vector#elements()
- */
- public void test_elements_subtest0() {
- final int iterations = 10000;
- final Vector v = new Vector();
- Thread t1 = new Thread() {
- public void run() {
- for (int i = 0; i < iterations; i++) {
- synchronized (v) {
- v.addElement(String.valueOf(i));
- v.removeElementAt(0);
- }
- }
- }
- };
- t1.start();
- for (int i = 0; i < iterations; i++) {
- Enumeration en = v.elements();
- try {
- while (true) {
- Object result = en.nextElement();
- if (result == null) {
- fail("Null result: " + i);
- }
- }
- } catch (NoSuchElementException e) {
- }
- }
- }
-
- /**
- * java.util.Vector#ensureCapacity(int)
- */
- public void test_ensureCapacityI() {
- // Test for method void java.util.Vector.ensureCapacity(int)
-
- Vector v = new Vector(9);
- v.ensureCapacity(20);
- assertEquals("ensureCapacity failed to set correct capacity", 20, v
- .capacity());
- v = new Vector(100);
- assertEquals("ensureCapacity reduced capacity", 100, v.capacity());
- }
-
- /**
- * java.util.Vector#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Vector.equals(java.lang.Object)
- Vector v = new Vector();
- for (int i = 0; i < 100; i++)
- v.addElement("Test " + i);
- assertTrue("a) Equal vectors returned false", tVector.equals(v));
- v.addElement(null);
- assertTrue("b) UnEqual vectors returned true", !tVector.equals(v));
- tVector.addElement(null);
- assertTrue("c) Equal vectors returned false", tVector.equals(v));
- tVector.removeElementAt(22);
- assertTrue("d) UnEqual vectors returned true", !tVector.equals(v));
- }
-
- /**
- * java.util.Vector#firstElement()
- */
- public void test_firstElement() {
- // Test for method java.lang.Object java.util.Vector.firstElement()
- assertEquals("Returned incorrect firstElement", "Test 0", tVector.firstElement()
- );
- tVector.insertElementAt(null, 0);
- assertNull("Returned incorrect firstElement--wanted null", tVector
- .firstElement());
-
- tVector = new Vector(10);
-
- try {
- tVector.firstElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#get(int)
- */
- public void test_getI() {
- // Test for method java.lang.Object java.util.Vector.get(int)
- assertEquals("Get returned incorrect object",
- "Test 80", tVector.get(80));
- tVector.add(25, null);
- assertNull("Returned incorrect element--wanted null",
- tVector.get(25));
-
- try {
- tVector.get(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.get(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#hashCode()
- */
- public void test_hashCode() {
- // Test for method int java.util.Vector.hashCode()
- int hashCode = 1; // one
- tVector.insertElementAt(null, 20);
- for (int i = 0; i < tVector.size(); i++) {
- Object obj = tVector.elementAt(i);
- hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
- }
- assertTrue("Incorrect hashCode returned. Wanted: " + hashCode
- + " got: " + tVector.hashCode(), tVector.hashCode() == hashCode);
- }
-
- /**
- * java.util.Vector#indexOf(java.lang.Object)
- */
- public void test_indexOfLjava_lang_Object() {
- // Test for method int java.util.Vector.indexOf(java.lang.Object)
- assertEquals("Incorrect index returned", 10, tVector.indexOf("Test 10"));
- assertEquals("Index returned for invalid Object", -1, tVector
- .indexOf("XXXXXXXXXXX"));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- assertTrue("Incorrect indexOf returned for null: "
- + tVector.indexOf(null), tVector.indexOf(null) == 20);
- }
-
- /**
- * java.util.Vector#indexOf(java.lang.Object, int)
- */
- public void test_indexOfLjava_lang_ObjectI() {
- // Test for method int java.util.Vector.indexOf(java.lang.Object, int)
- assertTrue("Failed to find correct index", (tVector.indexOf("Test 98",
- 50) == 98));
- assertTrue("Found index of bogus element", (tVector.indexOf(
- "Test 1001", 50) == -1));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- tVector.setElementAt(null, 60);
- assertTrue("a) Incorrect indexOf returned for null: "
- + tVector.indexOf(null, 25), tVector.indexOf(null, 25) == 40);
- assertTrue("b) Incorrect indexOf returned for null: "
- + tVector.indexOf(null, 20), tVector.indexOf(null, 20) == 20);
-
- try {
- tVector.indexOf(null, -1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#insertElementAt(java.lang.Object, int)
- */
- public void test_insertElementAtLjava_lang_ObjectI() {
- // Test for method void
- // java.util.Vector.insertElementAt(java.lang.Object, int)
- Vector v = vectorClone(tVector);
- String prevElement = (String) v.elementAt(99);
- v.insertElementAt("Inserted Element", 99);
- assertEquals("Element not inserted", "Inserted Element", ((String) v.elementAt(99))
- );
- assertTrue("Elements shifted incorrectly", ((String) v.elementAt(100))
- .equals(prevElement));
- v.insertElementAt(null, 20);
- assertNull("null not inserted", v.elementAt(20));
-
- try {
- tVector.insertElementAt(null, -5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.insertElementAt(null, tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.Vector.isEmpty()Vector
- Vector v = new java.util.Vector();
- assertTrue("Empty vector returned false", v.isEmpty());
- v.addElement(new Object());
- assertTrue("non-Empty vector returned true", !v.isEmpty());
- }
-
- /**
- * java.util.Vector#isEmpty()
- */
- public void test_isEmpty_subtest0() {
- final Vector v = new Vector();
- v.addElement("initial");
- Thread t1 = new Thread() {
- public void run() {
- while (!v.isEmpty())
- ;
- v.addElement("final");
- }
- };
- t1.start();
- for (int i = 0; i < 10000; i++) {
- synchronized (v) {
- v.removeElementAt(0);
- v.addElement(String.valueOf(i));
- }
- int size;
- if ((size = v.size()) != 1) {
- String result = "Size is not 1: " + size + " " + v;
- // terminate the thread
- v.removeAllElements();
- fail(result);
- }
- }
- // terminate the thread
- v.removeElementAt(0);
- }
-
- /**
- * java.util.Vector#lastElement()
- */
- public void test_lastElement() {
- // Test for method java.lang.Object java.util.Vector.lastElement()
- assertEquals("Incorrect last element returned", "Test 99", tVector.lastElement()
- );
- tVector.addElement(null);
- assertNull("Incorrect last element returned--wanted null", tVector
- .lastElement());
-
- tVector = new Vector(10);
-
- try {
- tVector.lastElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#lastIndexOf(java.lang.Object)
- */
- public void test_lastIndexOfLjava_lang_Object() {
- // Test for method int java.util.Vector.lastIndexOf(java.lang.Object)
- Vector v = new Vector(9);
- for (int i = 0; i < 9; i++)
- v.addElement("Test");
- v.addElement("z");
- assertEquals("Failed to return correct index", 8, v.lastIndexOf("Test"));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- assertTrue("Incorrect lastIndexOf returned for null: "
- + tVector.lastIndexOf(null), tVector.lastIndexOf(null) == 40);
- }
-
- /**
- * java.util.Vector#lastIndexOf(java.lang.Object, int)
- */
- public void test_lastIndexOfLjava_lang_ObjectI() {
- // Test for method int java.util.Vector.lastIndexOf(java.lang.Object,
- // int)
- assertEquals("Failed to find object",
- 0, tVector.lastIndexOf("Test 0", 0));
- assertTrue("Found Object outside of index", (tVector.lastIndexOf(
- "Test 0", 10) > -1));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- tVector.setElementAt(null, 60);
- assertTrue("Incorrect lastIndexOf returned for null: "
- + tVector.lastIndexOf(null, 15),
- tVector.lastIndexOf(null, 15) == -1);
- assertTrue("Incorrect lastIndexOf returned for null: "
- + tVector.lastIndexOf(null, 45),
- tVector.lastIndexOf(null, 45) == 40);
-
- try {
- tVector.lastIndexOf(null, tVector.size());
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#remove(int)
- */
- public void test_removeI() {
- // Test for method java.lang.Object java.util.Vector.remove(int)
- tVector.remove(36);
- assertTrue("Contained element after remove", !tVector
- .contains("Test 36"));
- assertEquals("Failed to decrement size after remove",
- 99, tVector.size());
- tVector.add(20, null);
- tVector.remove(19);
- assertNull("Didn't move null element over", tVector.get(19));
- tVector.remove(19);
- assertNotNull("Didn't remove null element", tVector.get(19));
- assertEquals("Failed to decrement size after removing null", 98, tVector
- .size());
-
- try {
- tVector.remove(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.remove(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.Vector.remove(java.lang.Object)
- tVector.remove("Test 0");
- assertTrue("Contained element after remove", !tVector
- .contains("Test 0"));
- assertEquals("Failed to decrement size after remove",
- 99, tVector.size());
- tVector.add(null);
- tVector.remove(null);
- assertTrue("Contained null after remove", !tVector.contains(null));
- assertEquals("Failed to decrement size after removing null", 99, tVector
- .size());
- }
-
- /**
- * java.util.Vector#removeAll(java.util.Collection)
- */
- public void test_removeAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.Vector.removeAll(java.util.Collection)
- Vector v = new Vector();
- Collection l = new LinkedList();
- for (int i = 0; i < 5; i++)
- l.add("Test " + i);
- v.addElement(l);
-
- Collection s = new HashSet();
- Object o;
- s.add(o = v.firstElement());
- v.removeAll(s);
- assertTrue("Failed to remove items in collection", !v.contains(o));
- v.removeAll(l);
- assertTrue("Failed to remove all elements", v.isEmpty());
-
- v.add(null);
- v.add(null);
- v.add("Boom");
- v.removeAll(s);
- assertEquals("Should not have removed any elements", 3, v.size());
- l = new LinkedList();
- l.add(null);
- v.removeAll(l);
- assertEquals("Should only have one element", 1, v.size());
- assertEquals("Element should be 'Boom'", "Boom", v.firstElement());
-
- try {
- v.removeAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#removeAllElements()
- */
- public void test_removeAllElements() {
- // Test for method void java.util.Vector.removeAllElements()
- Vector v = vectorClone(tVector);
- v.removeAllElements();
- assertEquals("Failed to remove all elements", 0, v.size());
- }
-
- /**
- * java.util.Vector#removeElement(java.lang.Object)
- */
- public void test_removeElementLjava_lang_Object() {
- // Test for method boolean
- // java.util.Vector.removeElement(java.lang.Object)
- Vector v = vectorClone(tVector);
- v.removeElement("Test 98");
- assertEquals("Element not removed", "Test 99", ((String) v.elementAt(98))
- );
- assertTrue("Vector is wrong size after removal: " + v.size(),
- v.size() == 99);
- tVector.addElement(null);
- v.removeElement(null);
- assertTrue("Vector is wrong size after removing null: " + v.size(), v
- .size() == 99);
- }
-
- /**
- * java.util.Vector#removeElementAt(int)
- */
- public void test_removeElementAtI() {
- // Test for method void java.util.Vector.removeElementAt(int)
- Vector v = vectorClone(tVector);
- v.removeElementAt(50);
- assertEquals("Failed to remove element", -1, v.indexOf("Test 50", 0));
- tVector.insertElementAt(null, 60);
- tVector.removeElementAt(60);
- assertNotNull("Element at 60 should not be null after removal", tVector
- .elementAt(60));
-
- try {
- tVector.elementAt(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.elementAt(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#retainAll(java.util.Collection)
- */
- public void test_retainAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.Vector.retainAll(java.util.Collection)
- Object o = tVector.firstElement();
- tVector.add(null);
- Collection s = new HashSet();
- s.add(o);
- s.add(null);
- tVector.retainAll(s);
- assertTrue("Retained items other than specified", tVector.size() == 2
- && tVector.contains(o) && tVector.contains(null));
-
- Iterator i = s.iterator();
-
- while (i.hasNext()) {
- assertTrue(tVector.contains(i.next()));
- }
-
- try {
- tVector.retainAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#set(int, java.lang.Object)
- */
- public void test_setILjava_lang_Object() {
- // Test for method java.lang.Object java.util.Vector.set(int,
- // java.lang.Object)
- Object o = new Object();
- tVector.set(23, o);
- assertTrue("Failed to set Object", tVector.get(23) == o);
-
- try {
- tVector.set(-5, "Wrong position");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.set(tVector.size() + 1, "Wrong position");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#setElementAt(java.lang.Object, int)
- */
- public void test_setElementAtLjava_lang_ObjectI() {
- // Test for method void java.util.Vector.setElementAt(java.lang.Object,
- // int)
- Vector v = vectorClone(tVector);
- v.setElementAt("Inserted Element", 99);
- assertEquals("Element not set", "Inserted Element", ((String) v.elementAt(99))
- );
-
- try {
- tVector.setElementAt("Wrong position", -5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.setElementAt("Wrong position", tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#setSize(int)
- */
- public void test_setSizeI() {
- // Test for method void java.util.Vector.setSize(int)
- Vector v = vectorClone(tVector);
- v.setSize(10);
- assertEquals("Failed to set size", 10, v.size());
-
- try {
- tVector.setSize(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#size()
- */
- public void test_size() {
- // Test for method int java.util.Vector.size()
- assertEquals("Returned incorrect size", 100, tVector.size());
-
- final Vector v = new Vector();
- v.addElement("initial");
- Thread t1 = new Thread() {
- public void run() {
- while (v.size() > 0)
- ;
- v.addElement("final");
- }
- };
- t1.start();
- for (int i = 0; i < 10000; i++) {
- synchronized (v) {
- v.removeElementAt(0);
- v.addElement(String.valueOf(i));
- }
- int size;
- if ((size = v.size()) != 1) {
- String result = "Size is not 1: " + size + " " + v;
- // terminate the thread
- v.removeAllElements();
- fail(result);
- }
- }
- // terminate the thread
- v.removeElementAt(0);
- }
-
- /**
- * java.util.Vector#subList(int, int)
- */
- public void test_subListII() {
- // Test for method java.util.List java.util.Vector.subList(int, int)
- List sl = tVector.subList(10, 25);
- assertEquals("Returned sublist of incorrect size", 15, sl.size());
- for (int i = 10; i < 25; i++)
- assertTrue("Returned incorrect sublist", sl
- .contains(tVector.get(i)));
-
- assertEquals("Not synchronized random access", "java.util.Collections$SynchronizedRandomAccessList", sl.getClass().getName()
- );
-
- try {
- tVector.subList(-10, 25);
- fail("IndexOutOfBoundsException expected");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.subList(10, tVector.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.subList(25, 10);
- fail("IllegalArgumentException expected");
- } catch(IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#toArray()
- */
- public void test_toArray() {
- // Test for method java.lang.Object [] java.util.Vector.toArray()
- assertTrue("Returned incorrect array", Arrays.equals(objArray, tVector
- .toArray()));
- }
-
- /**
- * java.util.Vector#toArray(java.lang.Object[])
- */
- public void test_toArray$Ljava_lang_Object() {
- // Test for method java.lang.Object []
- // java.util.Vector.toArray(java.lang.Object [])
- Object[] o = new Object[1000];
- Object f = new Object();
- for (int i = 0; i < o.length; i++)
- o[i] = f;
- tVector.toArray(o);
- assertNull("Failed to set slot to null", o[100]);
- for (int i = 0; i < tVector.size(); i++)
- assertTrue("Returned incorrect array", tVector.elementAt(i) == o[i]);
-
- try {
- tVector.toArray(null);
- fail("NullPointerException expected");
- } catch(NullPointerException e) {
- //expected
- }
- tVector = new Vector<Integer>();
- tVector.add(new Integer(1));
- tVector.add(new Integer(2));
- tVector.add(new Integer(3));
- try {
- tVector.toArray(new String[tVector.size()]);
- fail("ArrayStoreException expected");
- } catch(ArrayStoreException e) {
- //expected
- }
- }
-
- /**
- * java.util.Vector#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.util.Vector.toString()
- assertTrue("Incorrect String returned", tVector.toString().equals(
- vString));
-
- Vector v = new Vector();
- v.addElement("one");
- v.addElement(v);
- v.addElement("3");
- // test last element
- v.addElement(v);
- String result = v.toString();
- assertTrue("should contain self ref", result.indexOf("(this") > -1);
- }
-
- /**
- * java.util.Vector#trimToSize()
- */
- public void test_trimToSize() {
- // Test for method void java.util.Vector.trimToSize()
- Vector v = new Vector(10);
- v.addElement(new Object());
- v.trimToSize();
- assertEquals("Failed to trim capacity", 1, v.capacity());
- }
-
- class Mock_Vector extends Vector {
- @Override
- protected void removeRange(int from, int to) {
- super.removeRange(from, to);
- }
- }
-
- public void test_removeRangeII() {
- Mock_Vector mv = new Mock_Vector();
- mv.add("First");
- mv.add("Second");
- mv.add("One more");
- mv.add("Last");
- mv.removeRange(1, 3);
- assertTrue(mv.contains("First"));
- assertFalse(mv.contains("Second"));
- assertFalse(mv.contains("One more"));
- assertTrue(mv.contains("Last"));
- }
-
- protected Vector vectorClone(Vector s) {
- return (Vector) s.clone();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- for (int i = 0; i < 100; i++) {
- tVector.addElement("Test " + i);
- }
- objArray = new Object[100];
- for (int i = 0; i < 100; i++) {
- objArray[i] = "Test " + i;
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java b/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java
deleted file mode 100644
index d1a43e5..0000000
--- a/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java
+++ /dev/null
@@ -1,383 +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 tests.api.java.util;
-
-import java.util.AbstractMap;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-import libcore.java.lang.ref.FinalizationTester;
-
-import tests.support.Support_MapTest2;
-
-public class WeakHashMapTest extends junit.framework.TestCase {
- class MockMap extends AbstractMap {
- public Set entrySet() {
- return null;
- }
- public int size(){
- return 0;
- }
- }
-
- Object[] keyArray = new Object[100];
-
- Object[] valueArray = new Object[100];
-
- WeakHashMap whm;
-
- /**
- * java.util.WeakHashMap#WeakHashMap()
- */
- public void test_Constructor() {
- // Test for method java.util.WeakHashMap()
- new Support_MapTest2(new WeakHashMap()).runTest();
-
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Incorrect value retrieved",
- whm.get(keyArray[i]) == valueArray[i]);
-
- }
-
- /**
- * java.util.WeakHashMap#WeakHashMap(int)
- */
- public void test_ConstructorI() {
- // Test for method java.util.WeakHashMap(int)
- whm = new WeakHashMap(50);
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Incorrect value retrieved",
- whm.get(keyArray[i]) == valueArray[i]);
-
- WeakHashMap empty = new WeakHashMap(0);
- assertNull("Empty weakhashmap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new WeakHashMap(-50);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.WeakHashMap#WeakHashMap(int, float)
- */
- public void test_ConstructorIF() {
- // Test for method java.util.WeakHashMap(int, float)
- whm = new WeakHashMap(50, 0.5f);
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Incorrect value retrieved",
- whm.get(keyArray[i]) == valueArray[i]);
-
- WeakHashMap empty = new WeakHashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new WeakHashMap(50, -0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new WeakHashMap(-50, 0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * java.util.WeakHashMap#WeakHashMap(java.util.Map)
- */
- public void test_ConstructorLjava_util_Map() {
- Map mockMap = new MockMap();
- WeakHashMap map = new WeakHashMap(mockMap);
- assertEquals("Size should be 0", 0, map.size());
-
- try {
- new WeakHashMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.WeakHashMap#clear()
- */
- public void test_clear() {
- // Test for method boolean java.util.WeakHashMap.clear()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- whm.clear();
- assertTrue("Cleared map should be empty", whm.isEmpty());
- for (int i = 0; i < 100; i++)
- assertNull("Cleared map should only return null", whm
- .get(keyArray[i]));
-
- }
-
- /**
- * java.util.WeakHashMap#containsKey(java.lang.Object)
- */
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean java.util.WeakHashMap.containsKey()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Should contain referenced key", whm
- .containsKey(keyArray[i]));
- keyArray[25] = null;
- keyArray[50] = null;
- }
-
- /**
- * java.util.WeakHashMap#containsValue(java.lang.Object)
- */
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean java.util.WeakHashMap.containsValue()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Should contain referenced value", whm
- .containsValue(valueArray[i]));
- keyArray[25] = null;
- keyArray[50] = null;
- }
-
- /**
- * java.util.WeakHashMap#entrySet()
- */
- public void test_entrySet() {
- // Test for method java.util.Set java.util.WeakHashMap.entrySet()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- List keys = Arrays.asList(keyArray);
- List values = Arrays.asList(valueArray);
- Set entrySet = whm.entrySet();
- assertTrue("Incorrect number of entries returned--wanted 100, got: "
- + entrySet.size(), entrySet.size() == 100);
- Iterator it = entrySet.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- assertTrue("Invalid map entry returned--bad key", keys
- .contains(entry.getKey()));
- assertTrue("Invalid map entry returned--bad key", values
- .contains(entry.getValue()));
- }
- keys = null;
- values = null;
- keyArray[50] = null;
-
- int count = 0;
- do {
- System.gc();
- System.gc();
- FinalizationTester.induceFinalization();
- count++;
- } while (count <= 5 && entrySet.size() == 100);
-
- assertTrue(
- "Incorrect number of entries returned after gc--wanted 99, got: "
- + entrySet.size(), entrySet.size() == 99);
- }
-
- /**
- * java.util.WeakHashMap#isEmpty()
- */
- public void test_isEmpty() {
- // Test for method boolean java.util.WeakHashMap.isEmpty()
- whm = new WeakHashMap();
- assertTrue("New map should be empty", whm.isEmpty());
- Object myObject = new Object();
- whm.put(myObject, myObject);
- assertTrue("Map should not be empty", !whm.isEmpty());
- whm.remove(myObject);
- assertTrue("Map with elements removed should be empty", whm.isEmpty());
- }
-
- /**
- * java.util.WeakHashMap#put(java.lang.Object, java.lang.Object)
- */
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.WeakHashMap.put(java.lang.Object, java.lang.Object)
- WeakHashMap map = new WeakHashMap();
- map.put(null, "value"); // add null key
- System.gc();
- System.gc();
- FinalizationTester.induceFinalization();
- map.remove("nothing"); // Cause objects in queue to be removed
- assertEquals("null key was removed", 1, map.size());
- }
-
- /**
- * java.util.WeakHashMap#putAll(java.util.Map)
- */
- public void test_putAllLjava_util_Map() {
- Map mockMap=new MockMap();
- WeakHashMap map = new WeakHashMap();
- map.putAll(mockMap);
- assertEquals("Size should be 0", 0, map.size());
-
- try {
- map.putAll(null);
- fail("NullPointerException exected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * java.util.WeakHashMap#remove(java.lang.Object)
- */
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.WeakHashMap.remove(java.lang.Object)
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
-
- assertTrue("Remove returned incorrect value",
- whm.remove(keyArray[25]) == valueArray[25]);
- assertNull("Remove returned incorrect value",
- whm.remove(keyArray[25]));
- assertEquals("Size should be 99 after remove", 99, whm.size());
- }
-
- /**
- * java.util.WeakHashMap#size()
- */
- public void test_size() {
- whm = new WeakHashMap();
- assertEquals(0, whm.size());
- }
-
- /**
- * java.util.WeakHashMap#keySet()
- */
- public void test_keySet() {
- // Test for method java.util.Set java.util.WeakHashMap.keySet()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
-
- List keys = Arrays.asList(keyArray);
- List values = Arrays.asList(valueArray);
-
- Set keySet = whm.keySet();
- assertEquals("Incorrect number of keys returned,", 100, keySet.size());
- Iterator it = keySet.iterator();
- while (it.hasNext()) {
- Object key = it.next();
- assertTrue("Invalid map entry returned--bad key", keys
- .contains(key));
- }
- keys = null;
- values = null;
- keyArray[50] = null;
-
- int count = 0;
- do {
- System.gc();
- System.gc();
- FinalizationTester.induceFinalization();
- count++;
- } while (count <= 5 && keySet.size() == 100);
-
- assertEquals("Incorrect number of keys returned after gc,", 99, keySet
- .size());
- }
-
- /**
- * java.util.WeakHashMap#values()
- */
- public void test_values() {
- // Test for method java.util.Set java.util.WeakHashMap.values()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
-
- List keys = Arrays.asList(keyArray);
- List values = Arrays.asList(valueArray);
-
- Collection valuesCollection = whm.values();
- assertEquals("Incorrect number of keys returned,", 100,
- valuesCollection.size());
- Iterator it = valuesCollection.iterator();
- while (it.hasNext()) {
- Object value = it.next();
- assertTrue("Invalid map entry returned--bad value", values
- .contains(value));
- }
- keys = null;
- values = null;
- keyArray[50] = null;
-
- int count = 0;
- do {
- System.gc();
- System.gc();
- FinalizationTester.induceFinalization();
- count++;
- } while (count <= 5 && valuesCollection.size() == 100);
-
- assertEquals("Incorrect number of keys returned after gc,", 99,
- valuesCollection.size());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- for (int i = 0; i < 100; i++) {
- keyArray[i] = new Object();
- valueArray[i] = new Object();
- }
-
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/A.java b/luni/src/test/java/tests/api/java/util/support/A.java
deleted file mode 100644
index c2b43b5..0000000
--- a/luni/src/test/java/tests/api/java/util/support/A.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package tests.api.java.util.support;
-
-public class A implements I {
- private static P pp = new P();
-
- public A() {
- pp.setClazz(getClass());
- }
-
- public String find(String key) {
- return pp.findProp(key);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/B.java b/luni/src/test/java/tests/api/java/util/support/B.java
deleted file mode 100644
index baafdbe..0000000
--- a/luni/src/test/java/tests/api/java/util/support/B.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package tests.api.java.util.support;
-
-public class B extends A {
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/I.java b/luni/src/test/java/tests/api/java/util/support/I.java
deleted file mode 100644
index a1cd73a..0000000
--- a/luni/src/test/java/tests/api/java/util/support/I.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package tests.api.java.util.support;
-
-public interface I {
- String find(String key);
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/P.java b/luni/src/test/java/tests/api/java/util/support/P.java
deleted file mode 100644
index 6883936..0000000
--- a/luni/src/test/java/tests/api/java/util/support/P.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package tests.api.java.util.support;
-
-import java.util.ResourceBundle;
-
-public class P {
- private Class c;
-
- public void setClazz(Class c) {
- this.c = c;
- }
-
- public String findProp(String key) {
- return findProp(this.c, key);
- }
-
- private String findProp(Class cls, String key) {
- String ret = null;
- try {
- ResourceBundle b = ResourceBundle.getBundle(cls.getName());
- ret = (String)b.getObject(key);
- } catch (Exception e) {
- }
- if (ret == null && !cls.equals(Object.class) && !cls.isPrimitive()) {
- ret = findProp(cls.getSuperclass(), key);
- }
- return ret;
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java
deleted file mode 100644
index 34d7aed..0000000
--- a/luni/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.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.
- */
-
-/**
-* @author Boris V. Kuznetsov
-* @version $Revision$
-*/
-
-package tests.api.javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-import javax.net.ServerSocketFactory;
-
-import junit.framework.TestCase;
-
-public class ServerSocketFactoryTest extends TestCase {
-
- public void test_Constructor() {
- ServerSocketFactory sf = new MyServerSocketFactory();
- }
-
- public final void test_createServerSocket() throws Exception {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- ServerSocket ss = sf.createServerSocket();
- assertNotNull(ss);
- ss.close();
- }
-
- public final void test_createServerSocket_I() throws Exception {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- ServerSocket ss = sf.createServerSocket(0);
- assertNotNull(ss);
-
- try {
- sf.createServerSocket(ss.getLocalPort());
- fail("IOException wasn't thrown");
- } catch (IOException expected) {
- }
-
- ss.close();
-
- try {
- sf.createServerSocket(-1);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- public final void test_createServerSocket_II() throws Exception {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- ServerSocket ss = sf.createServerSocket(0, 0);
- assertNotNull(ss);
-
- try {
- sf.createServerSocket(ss.getLocalPort(), 0);
- fail("IOException wasn't thrown");
- } catch (IOException expected) {
- }
-
- ss.close();
-
- try {
- sf.createServerSocket(65536, 0);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- public final void test_createServerSocket_IIInetAddress() throws Exception {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
-
- ServerSocket ss = sf.createServerSocket(0, 0, InetAddress.getLocalHost());
- assertNotNull(ss);
-
- try {
- sf.createServerSocket(ss.getLocalPort(), 0, InetAddress.getLocalHost());
- fail("IOException wasn't thrown");
- } catch (IOException expected) {
- }
-
- ss.close();
-
- try {
- sf.createServerSocket(Integer.MAX_VALUE, 0, InetAddress.getLocalHost());
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-}
-class MyServerSocketFactory extends ServerSocketFactory {
-
- public MyServerSocketFactory() {
- super();
- }
-
- @Override
- public ServerSocket createServerSocket(int port) throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog)
- throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog,
- InetAddress address) throws IOException {
- return null;
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java
deleted file mode 100644
index e939a9b..0000000
--- a/luni/src/test/java/tests/api/javax/net/SocketFactoryTest.java
+++ /dev/null
@@ -1,267 +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.
- */
-
-/**
-* @author Boris V. Kuznetsov
-* @version $Revision$
-*/
-
-package tests.api.javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-import javax.net.SocketFactory;
-
-import junit.framework.TestCase;
-
-public class SocketFactoryTest extends TestCase {
-
- public void test_Constructor() throws Exception {
- new MySocketFactory();
- }
-
- public final void test_createSocket() throws Exception {
- SocketFactory sf = SocketFactory.getDefault();
-
- Socket s = sf.createSocket();
- assertNotNull(s);
- assertEquals(-1, s.getLocalPort());
- assertEquals(0, s.getPort());
-
- MySocketFactory msf = new MySocketFactory();
- try {
- msf.createSocket();
- fail("No expected SocketException");
- } catch (SocketException expected) {
- }
- }
-
- public final void test_createSocket_StringI() throws Exception {
- SocketFactory sf = SocketFactory.getDefault();
- int sport = new ServerSocket(0).getLocalPort();
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport);
- assertNotNull(s);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- try {
- sf.createSocket("bla-bla", sport);
- fail("UnknownHostException wasn't thrown");
- } catch (UnknownHostException expected) {
- }
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- sf.createSocket(InetAddress.getLocalHost().getHostName(), s.getLocalPort());
- fail("IOException wasn't thrown");
- } catch (IOException expected) {
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- f.createSocket(InetAddress.getLocalHost().getHostName(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException expected) {
- }
- }
-
- public final void test_createSocket_InetAddressI() throws Exception {
- SocketFactory sf = SocketFactory.getDefault();
- int sport = new ServerSocket(0).getLocalPort();
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- Socket s = sf.createSocket(InetAddress.getLocalHost(), sport);
- assertNotNull(s);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- sf.createSocket(InetAddress.getLocalHost(), s.getLocalPort());
- fail("IOException wasn't thrown");
- } catch (IOException expected) {
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- f.createSocket(InetAddress.getLocalHost(), 8081);
- fail("IOException wasn't thrown ...");
- } catch (IOException expected) {
- }
- }
-
- public final void test_createSocket_InetAddressIInetAddressI() throws Exception {
- SocketFactory sf = SocketFactory.getDefault();
- int sport = new ServerSocket(0).getLocalPort();
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- Socket s = sf.createSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), 0);
- assertNotNull(s);
- assertTrue("1: Failed to create socket", s.getPort() == sport);
- int portNumber = s.getLocalPort();
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i],
- InetAddress.getLocalHost(), portNumber);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException expected) {
- }
-
- try {
- sf.createSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- sf.createSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), portNumber);
- fail("IOException wasn't thrown");
- } catch (IOException expected) {
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- f.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException expected) {
- }
- }
-
- /**
- * javax.net.SocketFactory#createSocket(String host, int port,
- * InetAddress localHost, int localPort)
- */
- public final void test_createSocket_05() throws Exception {
- SocketFactory sf = SocketFactory.getDefault();
- int sport = new ServerSocket(0).getLocalPort();
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), 0);
- assertNotNull(s);
- assertTrue("1: Failed to create socket", s.getPort() == sport);
-
- try {
- sf.createSocket("bla-bla", sport, InetAddress.getLocalHost(), 0);
- fail("UnknownHostException wasn't thrown");
- } catch (UnknownHostException expected) {
- }
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i],
- InetAddress.getLocalHost(), 0);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException expected) {
- }
- try {
- sf.createSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- sf.createSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException expected) {
- }
- }
-
- /**
- * javax.net.SocketFactory#getDefault()
- */
- public final void test_getDefault() {
- SocketFactory sf = SocketFactory.getDefault();
- Socket s;
- try {
- s = sf.createSocket(InetAddress.getLocalHost().getHostName(), 8082);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createSocket(InetAddress.getLocalHost(), 8081);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
- s.close();
- } catch (IOException e) {
- }
- }
-}
-
-class MySocketFactory extends SocketFactory {
-
- public MySocketFactory() {
- super();
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- return null;
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- return null;
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return null;
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port,
- InetAddress localAddress, int localPort) throws IOException {
- return null;
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java b/luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java
deleted file mode 100644
index 41407e8..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.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 tests.api.javax.net.ssl;
-
-import java.security.cert.CertPathParameters;
-import javax.net.ssl.CertPathTrustManagerParameters;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>CertPathTrustManagerParameters</code> class constructors
- * and methods.
- *
- */
-public class CertPathTrustManagerParametersTest extends TestCase {
-
- /**
- * javax.net.ssl.CertPathTrustManagerParameters#
- * CertPathTrustManagerParameters(java.security.cert.CertPathParameters)
- * Case 1: Try to construct object.
- * Case 2: Check NullPointerException.
- */
- public void test_ConstructorLjava_security_cert_CertPathParameters() {
- // case 1: Try to construct object.
- try {
- CertPathParameters parameters = new MyCertPathParameters();
- CertPathTrustManagerParameters p =
- new CertPathTrustManagerParameters(parameters);
- assertNotSame("Parameters were cloned incorrectly",
- parameters, p.getParameters());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
-
- // case 2: Check NullPointerException.
- try {
- new CertPathTrustManagerParameters(null);
- fail("Expected CertPathTrustManagerParameters was not thrown");
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * javax.net.ssl.CertPathTrustManagerParameters#getParameters()
- */
- public void test_getParameters() {
- CertPathParameters parameters = new MyCertPathParameters();
- CertPathTrustManagerParameters p = new CertPathTrustManagerParameters(
- parameters);
- if (!(p.getParameters() instanceof MyCertPathParameters)) {
- fail("incorrect parameters");
- }
- assertNotSame("Parameters were cloned incorrectly",
- parameters, p.getParameters());
- }
-}
-
-class MyCertPathParameters implements CertPathParameters {
- public Object clone() {
- return new MyCertPathParameters();
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java b/luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java
deleted file mode 100644
index 5bb6f06..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java
+++ /dev/null
@@ -1,478 +0,0 @@
-/*
- * $HeadURL$
- * $Revision$
- * $Date$
- *
- * ====================================================================
- * 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.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-
-package tests.api.javax.net.ssl;
-
-/**
- * Some X509 certificates to test against.
- * <p/>
- * Note: some of these certificates have Japanese Kanji in the "subjectAlt"
- * field (UTF8). Not sure how realistic that is since international characters
- * in DNS names usually get translated into ASCII using "xn--" style DNS
- * entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to
- * find &#x82b1;&#x5b50;.co.jp. So would the CN in the certificate contain
- * "xn--i8s592g.co.jp" in ASCII, or "&#x82b1;&#x5b50;.co.jp" in UTF8? (Both?)
- *
- * @since 11-Dec-2006
- */
-public interface CertificatesToPlayWith {
-
- /**
- * CN=foo.com
- */
- public final static byte[] X509_FOO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
- "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
- "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
- "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" +
- "fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" +
- "c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" +
- "815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" +
- "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" +
- "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=&#x82b1;&#x5b50;.co.jp
- */
- public final static byte[] X509_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" +
- "FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" +
- "MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" +
- "g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" +
- "wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" +
- "7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" +
- "AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" +
- "qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" +
- "CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" +
- "HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" +
- "rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" +
- "ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" +
- "spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" +
- "a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" +
- "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" +
- "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=foo.com, subjectAlt=bar.com
- */
- public final static byte[] X509_FOO_BAR = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" +
- "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
- "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
- "A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" +
- "dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" +
- "zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" +
- "3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" +
- "88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" +
- "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" +
- "VbWx/uETImUu+NZg22ewEw==\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=foo.com, subjectAlt=bar.com, subjectAlt=&#x82b1;&#x5b50;.co.jp
- * (hanako.co.jp in kanji)
- */
- public final static byte[] X509_FOO_BAR_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" +
- "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
- "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
- "A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" +
- "SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" +
- "++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" +
- "PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" +
- "12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" +
- "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" +
- "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=*.foo.com
- */
- public final static byte[] X509_WILD_FOO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
- "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
- "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
- "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
- "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
- "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
- "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
- "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" +
- "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
- "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
- "A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" +
- "N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" +
- "A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" +
- "yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" +
- "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" +
- "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=*.co.jp
- */
- public final static byte[] X509_WILD_CO_JP = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
- "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
- "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
- "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" +
- "CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" +
- "1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" +
- "S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" +
- "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" +
- "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.&#x82b1;&#x5b50;.co.jp
- * (*.hanako.co.jp in kanji)
- */
- public final static byte[] X509_WILD_FOO_BAR_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
- "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
- "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
- "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
- "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
- "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
- "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
- "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" +
- "YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" +
- "DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" +
- "27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" +
- "MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" +
- "DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" +
- "WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" +
- "hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" +
- "qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" +
- "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=foo.com, CN=bar.com, CN=&#x82b1;&#x5b50;.co.jp
- */
- public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" +
- "MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" +
- "loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" +
- "bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" +
- "Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" +
- "h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" +
- "TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" +
- "3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" +
- "Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" +
- "tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" +
- "DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" +
- "y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" +
- "uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" +
- "EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" +
- "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" +
- "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * subjectAlt=foo.com
- */
- public final static byte[] X509_NO_CNS_FOO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" +
- "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" +
- "fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" +
- "xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" +
- "Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" +
- "ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" +
- "jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" +
- "5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" +
- "IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" +
- "0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" +
- "CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" +
- "tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" +
- "Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" +
- "yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" +
- "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" +
- "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * Intermediate CA for all of these.
- */
- public final static byte[] X509_INTERMEDIATE_CA = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
- "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
- "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" +
- "WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" +
- "EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" +
- "BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" +
- "MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" +
- "hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" +
- "XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" +
- "Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" +
- "KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" +
- "qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" +
- "9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" +
- "6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" +
- "rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" +
- "VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" +
- "c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" +
- "KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" +
- "Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" +
- "e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" +
- "1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" +
- "XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" +
- "aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * Root CA for all of these.
- */
- public final static byte[] X509_ROOT_CA = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
- "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
- "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" +
- "WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" +
- "FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" +
- "A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" +
- "Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" +
- "79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" +
- "w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" +
- "mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" +
- "jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" +
- "JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" +
- "EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" +
- "9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" +
- "hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" +
- "Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" +
- "MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" +
- "rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" +
- "S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" +
- "VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" +
- "lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" +
- "hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" +
- "Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" +
- "2dDk0g==\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * Below is the private key for all the server certificates above (but
- * not the intermediate CA or the root CA). All of those server certs
- * came from the same private key.
- */
- public final static String RSA_PUBLIC_MODULUS =
- "00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" +
- "8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" +
- "41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" +
- "f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" +
- "9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" +
- "56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" +
- "713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" +
- "cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" +
- "4caab29bddf085893dde5de87047b9e5cd";
-
- public final static String RSA_PUBLIC_EXPONENT = "65537";
-
- public final static String RSA_PRIVATE_EXPONENT =
- "577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" +
- "7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" +
- "8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" +
- "f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" +
- "a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" +
- "d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" +
- "a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" +
- "c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" +
- "44e6b355c1df581f50997175166eef39";
-
- public final static String RSA_PRIME1 =
- "00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" +
- "a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" +
- "b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" +
- "350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" +
- "fef7d8b532608d2513";
-
- public final static String RSA_PRIME2 =
- "00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" +
- "db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" +
- "af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" +
- "529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" +
- "c18d320510d79f859f";
-
- public final static String RSA_EXPONENT1 =
- "029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" +
- "47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" +
- "6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" +
- "c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" +
- "106467da112ce389";
-
- public final static String RSA_EXPONENT2 =
- "00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" +
- "7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" +
- "4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" +
- "9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" +
- "e997f079b0f6314eb7";
-
- public final static String RSA_COEFFICIENT =
- "00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" +
- "1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" +
- "a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" +
- "001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" +
- "2b8a9c7d91c7d175ae";
-
- /**
- * cat cert.cnf
- * [req]
- * distinguished_name=distinguished_name
- * req_extensions=req_extensions
- * x509_extensions=x509_extensions
- * [distinguished_name]
- * [req_extensions]
- * [x509_extensions]
- * subjectAltName=DNS:localhost.localdomain,DNS:localhost,IP:127.0.0.1
- *
- * $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \
- * -newkey rsa:512 -out cert.pem
- */
- public final static byte[] X509_MULTIPLE_SUBJECT_ALT = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n" +
- "BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow\n" +
- "FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt\n" +
- "atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg\n" +
- "PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv\n" +
- "Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL\n" +
- "DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n" +
- "X8YKH52fnHsCrhSD\n" +
- "-----END CERTIFICATE-----").getBytes();
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java b/luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java
deleted file mode 100644
index c075cea..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java
+++ /dev/null
@@ -1,613 +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 tests.api.javax.net.ssl;
-
-import dalvik.annotation.AndroidOnly;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.security.KeyStore;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import javax.net.ssl.HandshakeCompletedEvent;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import javax.security.cert.X509Certificate;
-import junit.framework.TestCase;
-import libcore.io.Base64;
-import org.apache.harmony.xnet.tests.support.mySSLSession;
-
-/**
- * Tests for <code>HandshakeCompletedEvent</code> class constructors and methods.
- *
- */
-public class HandshakeCompletedEventTest extends TestCase {
-
- private String certificate = "-----BEGIN CERTIFICATE-----\n"
- + "MIICZTCCAdICBQL3AAC2MA0GCSqGSIb3DQEBAgUAMF8xCzAJBgNVBAYTAlVTMSAw\n"
- + "HgYDVQQKExdSU0EgRGF0YSBTZWN1cml0eSwgSW5jLjEuMCwGA1UECxMlU2VjdXJl\n"
- + "IFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05NzAyMjAwMDAwMDBa\n"
- + "Fw05ODAyMjAyMzU5NTlaMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZv\n"
- + "cm5pYTESMBAGA1UEBxMJUGFsbyBBbHRvMR8wHQYDVQQKExZTdW4gTWljcm9zeXN0\n"
- + "ZW1zLCBJbmMuMSEwHwYDVQQLExhUZXN0IGFuZCBFdmFsdWF0aW9uIE9ubHkxGjAY\n"
- + "BgNVBAMTEWFyZ29uLmVuZy5zdW4uY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n"
- + "iQKBgQCofmdY+PiUWN01FOzEewf+GaG+lFf132UpzATmYJkA4AEA/juW7jSi+LJk\n"
- + "wJKi5GO4RyZoyimAL/5yIWDV6l1KlvxyKslr0REhMBaD/3Z3EsLTTEf5gVrQS6sT\n"
- + "WMoSZAyzB39kFfsB6oUXNtV8+UKKxSxKbxvhQn267PeCz5VX2QIDAQABMA0GCSqG\n"
- + "SIb3DQEBAgUAA34AXl3at6luiV/7I9MN5CXYoPJYI8Bcdc1hBagJvTMcmlqL2uOZ\n"
- + "H9T5hNMEL9Tk6aI7yZPXcw/xI2K6pOR/FrMp0UwJmdxX7ljV6ZtUZf7pY492UqwC\n"
- + "1777XQ9UEZyrKJvF5ntleeO0ayBqLGVKCWzWZX9YsXCpv47FNLZbupE=\n"
- + "-----END CERTIFICATE-----\n";
-
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#HandshakeCompletedEvent(SSLSocket sock, SSLSession s)
- */
- public final void test_Constructor() throws Exception {
- mySSLSession session = new mySSLSession();
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- new HandshakeCompletedEvent(null, null);
- fail("Any exception wasn't thrown for null parameters");
- } catch (Exception expected) {
- }
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getCipherSuite()
- */
- public final void test_getCipherSuite() throws Exception {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- assertEquals("SuiteName", event.getCipherSuite());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getLocalCertificates()
- */
- public final void test_getLocalCertificates() throws Exception {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- assertNull(event.getLocalCertificates());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getLocalPrincipal()
- */
- public final void test_getLocalPrincipal() throws Exception {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- assertNull(event.getLocalPrincipal());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificateChain()
- */
- public final void test_getPeerCertificateChain() throws Exception {
- ByteArrayInputStream bis = new ByteArrayInputStream(certificate.getBytes());
- mySSLSession session = new mySSLSession((X509Certificate[]) null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- event.getPeerCertificateChain();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException expected) {
- }
-
- X509Certificate xc = X509Certificate.getInstance(bis);
- X509Certificate[] xcs = {xc};
- session = new mySSLSession(xcs);
- event = new HandshakeCompletedEvent(socket, session);
-
- X509Certificate[] res = event.getPeerCertificateChain();
- assertEquals(1, res.length);
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getPeerCertificates()
- */
- public final void test_getPeerCertificates() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- event.getPeerCertificates();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException expected) {
- }
-
- session = new mySSLSession((X509Certificate[]) null);
- event = new HandshakeCompletedEvent(socket, session);
- Certificate[] res = event.getPeerCertificates();
- assertEquals(3, res.length);
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getPeerPrincipal()
- */
- public final void test_getPeerPrincipal() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- assertNull(event.getPeerPrincipal());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getSession()
- */
- public final void test_getSession() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- SSLSession ss = event.getSession();
- assertNotNull(ss);
- assertEquals(session, ss);
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.HandshakeCompletedEvent#getSocket()
- */
- public final void test_getSocket() throws IOException {
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, null);
- SSLSocket ss = event.getSocket();
- assertNotNull(ss);
- assertEquals(socket, ss);
- }
-
-
- // Regression test for CompletedHandshakeEvent not firing with a custom
- // TrustManager
-
-
- private SSLSocket socket;
- private SSLServerSocket serverSocket;
- private MyHandshakeListener listener;
- private String host = "localhost";
-
- private String PASSWORD = "android";
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
- + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
- + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
- + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
- + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
- + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
- + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
- + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
- + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
- + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
- + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
- + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
- + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
- + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
- + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
- + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
- + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
- + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
- + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
- + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
- + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
- + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
- + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
- + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
- + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
- + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
- + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
- + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
- + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
- + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
- + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
- + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
- + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
- + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
- + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
- + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
- + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
- + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
- + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
- + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
- + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
- + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
- + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
- + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
- + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
- + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
- + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- /**
- * Defines the keystore contents for the client, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC"
- + "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5"
- + "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw"
- + "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY"
- + "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4"
- + "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit"
- + "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY"
- + "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O"
- + "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS"
- + "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4"
- + "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi"
- + "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL"
- + "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41"
- + "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV"
- + "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB"
- + "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5"
- + "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN"
- + "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w"
- + "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR"
- + "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5"
- + "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE"
- + "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng"
- + "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp"
- + "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
-
- /**
- * Defines the keystore contents for the client, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_BKS =
- "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41"
- + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
- + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
- + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw"
- + "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
- + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu"
- + "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva"
- + "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD"
- + "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG"
- + "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F"
- + "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg"
- + "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx"
- + "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi"
- + "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD"
- + "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO"
- + "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz"
- + "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5"
- + "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8"
- + "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1"
- + "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9"
- + "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB"
- + "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9"
- + "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef"
- + "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";
-
-
- /**
- * Implements the actual test case. Launches a server and a client, requires
- * client authentication and checks the certificates afterwards (not in the
- * usual sense, we just make sure that we got the expected certificates,
- * because our self-signed test certificates are not valid.)
- */
-
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void testClientAuth() throws Exception {
-
- boolean useBKS = true;
-
- listener = new MyHandshakeListener();
- String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
- String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS);
- TestServer server = new TestServer(true,
- TestServer.CLIENT_AUTH_WANTED, serverKeys);
- TestClient client = new TestClient(true, clientKeys);
-
- Thread serverThread = new Thread(server);
- Thread clientThread = new Thread(client);
-
- serverThread.start();
- Thread.currentThread().sleep(3000);
- clientThread.start();
-
- serverThread.join();
- clientThread.join();
-
- // The server must have completed without an exception.
- Exception e = server.getException();
- if (e != null) {
- e.printStackTrace();
- }
-
- // The client must have completed without an exception.
- e = client.getException();
- if (e != null) {
- e.printStackTrace();
- }
-
- assertNull(e);
-
- assertTrue(listener.completeDone);
- }
-
- /**
- * Implements a test SSL socket server. It wait for a connection on a given
- * port, requests client authentication (if specified), reads 256 bytes
- * from the socket, and writes 256 bytes to the socket.
- */
- class TestServer implements Runnable {
-
- public static final int CLIENT_AUTH_NONE = 0;
-
- public static final int CLIENT_AUTH_WANTED = 1;
-
- public static final int CLIENT_AUTH_NEEDED = 2;
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- String keys;
-
- private int clientAuth;
-
- private boolean provideKeys;
-
- public TestServer(boolean provideKeys, int clientAuth, String keys) throws Exception {
- this.keys = keys;
- this.clientAuth = clientAuth;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
-
- KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
-
- if (clientAuth == CLIENT_AUTH_WANTED) {
- serverSocket.setWantClientAuth(true);
- } else if (clientAuth == CLIENT_AUTH_NEEDED) {
- serverSocket.setNeedClientAuth(true);
- } else {
- serverSocket.setWantClientAuth(false);
- }
-
- serverSocket.bind(new InetSocketAddress(0));
- }
-
- public void run() {
- try {
- SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
-
- InputStream istream = clientSocket.getInputStream();
-
- for (int i = 0; i < 256; i++) {
- int j = istream.read();
- assertEquals(i, j);
- }
-
- istream.close();
-
- OutputStream ostream = clientSocket.getOutputStream();
-
- for (int i = 0; i < 256; i++) {
- ostream.write(i);
- }
-
- ostream.flush();
- ostream.close();
-
- clientSocket.close();
- serverSocket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- }
-
- /**
- * Implements a test SSL socket client. It open a connection to localhost on
- * a given port, writes 256 bytes to the socket, and reads 256 bytes from the
- * socket.
- */
- class TestClient implements Runnable {
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- private String keys;
-
- private boolean provideKeys;
-
- public TestClient(boolean provideKeys, String keys) {
- this.keys = keys;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket();
-
- socket.connect(serverSocket.getLocalSocketAddress());
- socket.addHandshakeCompletedListener(listener);
- socket.startHandshake();
-
- OutputStream ostream = socket.getOutputStream();
-
- for (int i = 0; i < 256; i++) {
- ostream.write(i);
- }
-
- ostream.flush();
- ostream.close();
-
- InputStream istream = socket.getInputStream();
-
- for (int i = 0; i < 256; i++) {
- int j = istream.read();
- assertEquals(i, j);
- }
-
- istream.close();
-
- socket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers(String keys) throws Exception {
- byte[] bytes = Base64.decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
-
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-
-
- /**
- * Implements basically a dummy TrustManager. It stores the certificate
- * chain it sees, so it can later be queried.
- */
- public static class TestTrustManager implements X509TrustManager {
-
- private X509Certificate[] chain;
-
- private String authType;
-
- public void checkClientTrusted(X509Certificate[] chain, String authType) {
- this.chain = chain;
- this.authType = authType;
- }
-
- public void checkServerTrusted(X509Certificate[] chain, String authType) {
- this.chain = chain;
- this.authType = authType;
- }
-
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return new java.security.cert.X509Certificate[0];
- }
-
- public X509Certificate[] getChain() {
- return chain;
- }
-
- public String getAuthType() {
- return authType;
- }
-
- public void checkClientTrusted(
- java.security.cert.X509Certificate[] chain, String authType)
- throws CertificateException {
-
- }
-
- public void checkServerTrusted(
- java.security.cert.X509Certificate[] chain, String authType)
- throws CertificateException {
-
- }
-
- }
-
- class MyHandshakeListener implements HandshakeCompletedListener {
-
- public boolean completeDone;
-
- MyHandshakeListener() {
- completeDone = false;
- }
-
- public void handshakeCompleted(HandshakeCompletedEvent event) {
- if (event != null) completeDone = true;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java b/luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java
deleted file mode 100644
index 839f3b5..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java
+++ /dev/null
@@ -1,290 +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 tests.api.javax.net.ssl;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.security.auth.x500.X500Principal;
-import junit.framework.TestCase;
-import org.apache.harmony.xnet.tests.support.mySSLSession;
-
-public class HostnameVerifierTest extends TestCase implements
- CertificatesToPlayWith {
-
- /**
- * javax.net.ssl.HostnameVerifier#verify(String hostname, SSLSession
- * session)
- */
- public final void test_verify() throws Exception {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
- assertFalse(hv.verify("localhost", session));
- }
-
- // copied and modified from apache http client test suite.
- public void testVerify() throws Exception {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in;
- X509Certificate x509;
- in = new ByteArrayInputStream(X509_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] {x509});
-
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertFalse(verifier.verify("bar.com", session));
-
- in = new ByteArrayInputStream(X509_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
- assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_FOO_BAR);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertFalse(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertTrue(verifier.verify("bar.com", session));
- assertFalse(verifier.verify("a.bar.com", session));
-
- in = new ByteArrayInputStream(X509_FOO_BAR_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- // these checks test alternative subjects. The test data contains an
- // alternative subject starting with a japanese kanji character. This is
- // not supported by Android because the underlying implementation from
- // harmony follows the definition from rfc 1034 page 10 for alternative
- // subject names. This causes the code to drop all alternative subjects.
- // assertTrue(verifier.verify("bar.com", session));
- // assertFalse(verifier.verify("a.bar.com", session));
- // assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_NO_CNS_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
-
- in = new ByteArrayInputStream(X509_NO_CNS_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
-
- in = new ByteArrayInputStream(X509_THREE_CNS_FOO_BAR_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertFalse(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertFalse(verifier.verify("bar.com", session));
- assertFalse(verifier.verify("a.bar.com", session));
- assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
- assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_WILD_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertTrue(verifier.verify("www.foo.com", session));
- assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session));
- assertFalse(verifier.verify("a.b.foo.com", session));
-
- in = new ByteArrayInputStream(X509_WILD_CO_JP);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.co.jp", session));
- assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_WILD_FOO_BAR_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- // try the foo.com variations
- assertTrue(verifier.verify("foo.com", session));
- assertTrue(verifier.verify("www.foo.com", session));
- assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session));
- assertFalse(verifier.verify("a.b.foo.com", session));
- // these checks test alternative subjects. The test data contains an
- // alternative subject starting with a japanese kanji character. This is
- // not supported by Android because the underlying implementation from
- // harmony follows the definition from rfc 1034 page 10 for alternative
- // subject names. This causes the code to drop all alternative subjects.
- // assertFalse(verifier.verify("bar.com", session));
- // assertTrue(verifier.verify("www.bar.com", session));
- // assertTrue(verifier.verify("\u82b1\u5b50.bar.com", session));
- // assertTrue(verifier.verify("a.b.bar.com", session));
- }
-
- public void testSubjectAlt() throws Exception {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT);
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] {x509});
-
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
- assertEquals(new X500Principal("CN=localhost"), x509.getSubjectX500Principal());
-
- assertTrue(verifier.verify("localhost", session));
- assertTrue(verifier.verify("localhost.localdomain", session));
- assertFalse(verifier.verify("local.host", session));
- }
-
- public void testVerifyIpAddress() throws Exception {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT);
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
-
- assertTrue(verifier.verify("127.0.0.1", session));
- assertFalse(verifier.verify("127.0.0.2", session));
- }
-
- public void testWildcardsCannotMatchIpAddresses() throws Exception {
- // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem
- String cert = "-----BEGIN CERTIFICATE-----\n"
- + "MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV\n"
- + "BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx\n"
- + "EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt\n"
- + "YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+\n"
- + "cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt\n"
- + "JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV\n"
- + "BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB\n"
- + "BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n"
- + "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n"
- + "-----END CERTIFICATE-----";
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
-
- assertFalse(verifier.verify("127.0.0.1", session));
- }
-
- /**
- * Earlier implementations of Android's hostname verifier required that
- * wildcard names wouldn't match "*.com" or similar. This was a nonstandard
- * check that we've since dropped. It is the CA's responsibility to not hand
- * out certificates that match so broadly.
- */
- public void testWildcardsDoesNotNeedTwoDots() throws Exception {
- // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem
- String cert = "-----BEGIN CERTIFICATE-----\n"
- + "MIIBjDCCATagAwIBAgIJAOVulXCSu6HuMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV\n"
- + "BAMUBSouY29tMCAXDTEwMTIyMDE2NDkzOFoYDzIxMTAxMTI2MTY0OTM4WjAQMQ4w\n"
- + "DAYDVQQDFAUqLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDJd8xqni+h7Iaz\n"
- + "ypItivs9kPuiJUqVz+SuJ1C05SFc3PmlRCvwSIfhyD67fHcbMdl+A/LrIjhhKZJe\n"
- + "1joO0+pFAgMBAAGjcTBvMB0GA1UdDgQWBBS4Iuzf5w8JdCp+EtBfdFNudf6+YzBA\n"
- + "BgNVHSMEOTA3gBS4Iuzf5w8JdCp+EtBfdFNudf6+Y6EUpBIwEDEOMAwGA1UEAxQF\n"
- + "Ki5jb22CCQDlbpVwkruh7jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA\n"
- + "U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d\n"
- + "qUYo4ES548JdpQtcLrW2sA==\n"
- + "-----END CERTIFICATE-----";
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
-
- assertTrue(verifier.verify("google.com", session));
- }
-
- public void testSubjectAltName() throws Exception {
- /*
- * $ cat ./cert.cnf
- * [req]
- * distinguished_name=distinguished_name
- * req_extensions=req_extensions
- * x509_extensions=x509_extensions
- * [distinguished_name]
- * [req_extensions]
- * [x509_extensions]
- * subjectAltName=DNS:bar.com,DNS:baz.com
- *
- * $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \
- * -newkey rsa:512 -out cert.pem
- */
- String cert = "-----BEGIN CERTIFICATE-----\n"
- + "MIIBPTCB6KADAgECAgkA7zoHaaqNGHQwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n"
- + "AxMHZm9vLmNvbTAgFw0xMDEyMjAxODM5MzZaGA8yMTEwMTEyNjE4MzkzNlowEjEQ\n"
- + "MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC+gmoSxF+8\n"
- + "hbV+rgRQqHIJd50216OWQJbU3BvdlPbca779NYO4+UZWTFdBM8BdQqs3H4B5Agvp\n"
- + "y7HeSff1F7XRAgMBAAGjHzAdMBsGA1UdEQQUMBKCB2Jhci5jb22CB2Jhei5jb20w\n"
- + "DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI\n"
- + "oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm\n"
- + "-----END CERTIFICATE-----";
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
-
- assertFalse(verifier.verify("foo.com", session));
- assertTrue(verifier.verify("bar.com", session));
- assertTrue(verifier.verify("baz.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertFalse(verifier.verify("quux.com", session));
- }
-
- public void testSubjectAltNameWithWildcard() throws Exception {
- /*
- * $ cat ./cert.cnf
- * [req]
- * distinguished_name=distinguished_name
- * req_extensions=req_extensions
- * x509_extensions=x509_extensions
- * [distinguished_name]
- * [req_extensions]
- * [x509_extensions]
- * subjectAltName=DNS:bar.com,DNS:*.baz.com
- *
- * $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \
- * -newkey rsa:512 -out cert.pem
- */
- String cert = "-----BEGIN CERTIFICATE-----\n"
- + "MIIBPzCB6qADAgECAgkAnv/7Jv5r7pMwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n"
- + "AxMHZm9vLmNvbTAgFw0xMDEyMjAxODQ2MDFaGA8yMTEwMTEyNjE4NDYwMVowEjEQ\n"
- + "MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDAz2YXnyog\n"
- + "YdYLSFr/OEgSumtwqtZKJTB4wqTW/eKbBCEzxnyUMxWZIqUGu353PzwfOuWp2re3\n"
- + "nvVV+QDYQlh9AgMBAAGjITAfMB0GA1UdEQQWMBSCB2Jhci5jb22CCSouYmF6LmNv\n"
- + "bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO\n"
- + "Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI=\n"
- + "-----END CERTIFICATE-----";
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] { x509 });
- HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
-
- assertFalse(verifier.verify("foo.com", session));
- assertTrue(verifier.verify("bar.com", session));
- assertTrue(verifier.verify("a.baz.com", session));
- assertTrue(verifier.verify("baz.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertFalse(verifier.verify("a.bar.com", session));
- assertFalse(verifier.verify("quux.com", session));
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java
deleted file mode 100644
index e2ebdbd..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java
+++ /dev/null
@@ -1,341 +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 tests.api.javax.net.ssl;
-
-import java.io.ByteArrayInputStream;
-import java.net.URL;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocketFactory;
-
-import org.apache.harmony.security.tests.support.cert.TestUtils;
-
-import junit.framework.TestCase;
-
-
-
-/**
- * Tests for <code>HttpsURLConnection</code> class constructors and methods.
- *
- */
-public class HttpsURLConnectionTest extends TestCase {
-
- /**
- * javax.net.ssl.HttpsURLConnection#HttpsURLConnection(java_net_URL)
- */
- public final void test_Constructor() throws Exception {
- new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
- new MyHttpsURLConnection(null);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getCipherSuite()
- */
- public final void test_getCipherSuite() throws Exception {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getCipherSuite();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException expected) {
- }
-
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
- assertEquals("CipherSuite", con.getCipherSuite());
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getLocalCertificates()
- */
- public final void test_getLocalCertificates() throws Exception {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getLocalCertificates();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException expected) {
- }
-
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- assertNull(con.getLocalCertificates());
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- Certificate[] cert = con.getLocalCertificates();
- assertNotNull(cert);
- assertEquals(1, cert.length);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier()
- */
- public final void test_getDefaultHostnameVerifier() {
- HostnameVerifier verifyer =
- HttpsURLConnection.getDefaultHostnameVerifier();
- assertNotNull("Default hostname verifyer is null", verifyer);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getDefaultSSLSocketFactory()
- */
- public final void test_getDefaultSSLSocketFactory() {
- SSLSocketFactory sf = HttpsURLConnection.getDefaultSSLSocketFactory();
- if (!sf.equals(SSLSocketFactory.getDefault())) {
- fail("incorrect DefaultSSLSocketFactory");
- }
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getHostnameVerifier()
- */
- public final void test_getHostnameVerifier()
- throws Exception {
- HttpsURLConnection con = new MyHttpsURLConnection(
- new URL("https://www.fortify.net/"));
- HostnameVerifier verifyer = con.getHostnameVerifier();
- assertNotNull("Hostname verifyer is null", verifyer);
- assertEquals("Incorrect value of hostname verirfyer",
- HttpsURLConnection.getDefaultHostnameVerifier(), verifyer);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getLocalPrincipal()
- */
- public final void test_getLocalPrincipal() throws Exception {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getLocalPrincipal();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException expected) {
- }
-
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- assertNull(con.getLocalPrincipal());
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- assertNotNull("Local principal is null", con.getLocalPrincipal());
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getPeerPrincipal()
- */
- public final void test_getPeerPrincipal() throws Exception {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getPeerPrincipal();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException expected) {
- }
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- try {
- Principal p = con.getPeerPrincipal();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException expected) {
- }
-
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- Principal p = con.getPeerPrincipal();
- assertNotNull(p);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getServerCertificates()
- */
- public final void test_getServerCertificates() throws Exception {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getServerCertificates();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException expected) {
- }
-
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- try {
- con.getServerCertificates();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException expected) {
- }
-
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- Certificate[] cert = con.getServerCertificates();
- assertNotNull(cert);
- assertEquals(1, cert.length);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#getSSLSocketFactory()
- */
- public final void test_getSSLSocketFactory() {
- HttpsURLConnection con = new MyHttpsURLConnection(null);
- SSLSocketFactory sf = con.getSSLSocketFactory();
- if (!sf.equals(SSLSocketFactory.getDefault())) {
- fail("incorrect DefaultSSLSocketFactory");
- }
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier()
- */
- public final void test_setDefaultHostnameVerifier() {
- try {
- HttpsURLConnection.setDefaultHostnameVerifier(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- HostnameVerifier def = HttpsURLConnection.getDefaultHostnameVerifier();
- try {
- myHostnameVerifier hnv = new myHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
- assertEquals(hnv, HttpsURLConnection.getDefaultHostnameVerifier());
- } finally {
- HttpsURLConnection.setDefaultHostnameVerifier(def);
- }
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#setHostnameVerifier()
- */
- public final void test_setHostnameVerifier() {
- HttpsURLConnection con = new MyHttpsURLConnection(null);
- try {
- con.setHostnameVerifier(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- myHostnameVerifier hnv = new myHostnameVerifier();
- con.setHostnameVerifier(hnv);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory()
- */
- public final void test_setDefaultSSLSocketFactory() {
- try {
- HttpsURLConnection.setDefaultSSLSocketFactory(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
- .getDefault();
- HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
- }
-
- /**
- * javax.net.ssl.HttpsURLConnection#setSSLSocketFactory()
- */
- public final void test_setSSLSocketFactory() {
- HttpsURLConnection con = new MyHttpsURLConnection(null);
- try {
- con.setSSLSocketFactory(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
- SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
- .getDefault();
- con.setSSLSocketFactory(ssf);
- }
-}
-
-class MyHttpsURLConnection extends javax.net.ssl.HttpsURLConnection {
-
- private String typeDone;
-
- public MyHttpsURLConnection(URL url) {
- super(url);
- }
-
- public MyHttpsURLConnection(URL url, String type) {
- super(url);
- typeDone = type;
- }
-
- /*
- * @see javax.net.ssl.HttpsURLConnection#getCipherSuite()
- */
- public String getCipherSuite() {
- return "CipherSuite";
- }
-
- /*
- * @see javax.net.ssl.HttpsURLConnection#getLocalCertificates()
- */
- public Certificate[] getLocalCertificates() {
- try {
- CertificateFactory cf = CertificateFactory.getInstance(typeDone);
- byte[] barr = TestUtils.getX509Certificate_v1();
- ByteArrayInputStream bis = new ByteArrayInputStream(barr);
- Certificate cert = cf.generateCertificate(bis);
- return new Certificate[] { cert };
- } catch (CertificateException se) {
- return null;
- }
- }
-
- /*
- * @see javax.net.ssl.HttpsURLConnection#getServerCertificates()
- */
- public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
- try {
- CertificateFactory cf = CertificateFactory.getInstance(typeDone);
- byte[] barr = TestUtils.getX509Certificate_v3();
- ByteArrayInputStream bis = new ByteArrayInputStream(barr);
- Certificate cert = cf.generateCertificate(bis);
- return new Certificate[] { cert };
- } catch (CertificateException se) {
- throw new SSLPeerUnverifiedException("No server's end-entity certificate");
- }
- }
-
- /*
- * @see java.net.HttpURLConnection#disconnect()
- */
- public void disconnect() {
- }
-
- /*
- * @see java.net.HttpURLConnection#usingProxy()
- */
- public boolean usingProxy() {
- return false;
- }
-
- public void connect() {
- }
-
-}
-
-class myHostnameVerifier implements HostnameVerifier {
-
- myHostnameVerifier() {
- }
-
- public boolean verify(String hostname, SSLSession session) {
- if (hostname == session.getPeerHost()) {
- return true;
- } else return false;
- }
-}
-
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java
deleted file mode 100644
index b369ed9..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java
+++ /dev/null
@@ -1,532 +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 tests.api.javax.net.ssl;
-
-import java.io.IOException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.KeyStoreBuilderParameters;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.KeyManagerFactorySpi;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>KeyManagerFactory</code> class constructors and methods.
- *
- */
-public class KeyManagerFactory1Test extends TestCase {
-
- private static final String srvKeyManagerFactory = "KeyManagerFactory";
-
- private static String defaultAlgorithm = null;
-
- private static String defaultProviderName = null;
-
- private static Provider defaultProvider = null;
-
- private static boolean DEFSupported = false;
-
- private static final String NotSupportedMsg = "There is no suitable provider for KeyManagerFactory";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static String[] validValues = new String[3];
- static {
- defaultAlgorithm = Security
- .getProperty("ssl.KeyManagerFactory.algorithm");
- if (defaultAlgorithm != null) {
- defaultProvider = SpiEngUtils.isSupport(defaultAlgorithm,
- srvKeyManagerFactory);
- DEFSupported = (defaultProvider != null);
- defaultProviderName = (DEFSupported ? defaultProvider.getName()
- : null);
- validValues[0] = defaultAlgorithm;
- validValues[1] = defaultAlgorithm.toUpperCase();
- validValues[2] = defaultAlgorithm.toLowerCase();
- }
- }
-
- protected KeyManagerFactory[] createKMFac() {
- if (!DEFSupported) {
- fail(defaultAlgorithm + " algorithm is not supported");
- return null;
- }
- KeyManagerFactory[] kMF = new KeyManagerFactory[3];
- try {
- kMF[0] = KeyManagerFactory.getInstance(defaultAlgorithm);
- kMF[1] = KeyManagerFactory.getInstance(defaultAlgorithm,
- defaultProvider);
- kMF[2] = KeyManagerFactory.getInstance(defaultAlgorithm,
- defaultProviderName);
- return kMF;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * avax.net.ssl.KeyManagerFactory#getAlgorithm()
- */
- public void test_getAlgorithm()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportedMsg);
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- KeyManagerFactory
- .getInstance(defaultAlgorithm).getAlgorithm());
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- KeyManagerFactory
- .getInstance(defaultAlgorithm, defaultProviderName)
- .getAlgorithm());
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
- .getAlgorithm());
- }
-
- /**
- * Test for <code>getDefaultAlgorithm()</code> method
- * Assertion: returns value which is specifoed in security property
- */
- public void test_getDefaultAlgorithm() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- String def = KeyManagerFactory.getDefaultAlgorithm();
- if (defaultAlgorithm == null) {
- assertNull("DefaultAlgorithm must be null", def);
- } else {
- assertEquals("Invalid default algorithm", def, defaultAlgorithm);
- }
- String defA = "Proba.keymanagerfactory.defaul.type";
- Security.setProperty("ssl.KeyManagerFactory.algorithm", defA);
- assertEquals("Incorrect defaultAlgorithm",
- KeyManagerFactory.getDefaultAlgorithm(), defA);
- if (def == null) {
- def = "";
- }
- Security.setProperty("ssl.KeyManagerFactory.algorithm", def);
- assertEquals("Incorrect defaultAlgorithm",
- KeyManagerFactory.getDefaultAlgorithm(), def);
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions:
- * returns security property "ssl.KeyManagerFactory.algorithm";
- * returns instance of KeyManagerFactory
- */
- public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i]);
- assertNotNull("No KeyManagerFactory created", keyMF);
- assertEquals("Invalid algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- public void test_getInstanceLjava_lang_String02() {
- try {
- KeyManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
- .concat(invalidValues[i]));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null or empty
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- String provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], provider);
- fail("Expected IllegalArgumentException was not thrown for null provider");
- } catch (IllegalArgumentException e) {
- }
- try {
- KeyManagerFactory.getInstance(validValues[i], "");
- fail("Expected IllegalArgumentException was not thrown for empty provider");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- try {
- KeyManagerFactory.getInstance(null, defaultProviderName);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i],
- defaultProviderName);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws NoSuchProviderException when provider has
- * invalid value
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String03()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- KeyManagerFactory.getInstance(validValues[i],
- invalidValues[j]);
- fail("NuSuchProviderException must be thrown (algorithm: "
- + validValues[i] + " provider: " + invalidValues[j]
- + ")");
- } catch (NoSuchProviderException e) {
- }
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method Assertion: returns instance of KeyManagerFactory
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String04()
- throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory kMF;
- for (int i = 0; i < validValues.length; i++) {
- kMF = KeyManagerFactory.getInstance(validValues[i],
- defaultProviderName);
- assertNotNull("No KeyManagerFactory created", kMF);
- assertEquals("Incorrect algorithm", kMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", kMF.getProvider().getName(),
- defaultProviderName);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider01()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- Provider provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], provider);
- fail("Expected IllegalArgumentException was not thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- try {
- KeyManagerFactory.getInstance(null, defaultProvider);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory
- .getInstance(invalidValues[i], defaultProvider);
- fail("Expected NuSuchAlgorithmException was not thrown");
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: returns instance of KeyManagerFactory
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider03()
- throws NoSuchAlgorithmException,
- IllegalArgumentException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory kMF;
- for (int i = 0; i < validValues.length; i++) {
- kMF = KeyManagerFactory
- .getInstance(validValues[i], defaultProvider);
- assertNotNull("No KeyManagerFactory created", kMF);
- assertEquals(kMF.getAlgorithm(), validValues[i]);
- assertEquals(kMF.getProvider(), defaultProvider);
- }
- }
-
- /**
- * Test for <code>KeyManagerFactory</code> constructor
- * Assertion: returns KeyManagerFactory object
- */
- public void test_Constructor() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactorySpi spi = new MyKeyManagerFactorySpi();
- KeyManagerFactory keyMF = new myKeyManagerFactory(spi, defaultProvider,
- defaultAlgorithm);
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- defaultAlgorithm);
- assertEquals("Incorrect provider", keyMF.getProvider(), defaultProvider);
- try {
- keyMF.init(null, new char[1]);
- fail("UnrecoverableKeyException must be thrown");
- } catch (UnrecoverableKeyException e) {
- } catch (Exception e) {
- fail("Unexpected: "+e.toString()+" was thrown");
- }
- keyMF = new myKeyManagerFactory(null, null, null);
- assertNull("Aalgorithm must be null", keyMF.getAlgorithm());
- assertNull("Provider must be null", keyMF.getProvider());
- try {
- keyMF.getKeyManagers();
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * avax.net.ssl.KeyManagerFactory#getKeyManagers()
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * @throws IOException
- * @throws CertificateException
- * @throws UnrecoverableKeyException
- */
- public void test_getKeyManagers()
- throws Exception {
- if (!DEFSupported) fail(NotSupportedMsg);
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- char[] pass = "password".toCharArray();
- kmf.init(null, pass);
- assertNotNull("Key manager array is null", kmf.getKeyManagers());
- assertEquals("Incorrect size of array",
- 1, kmf.getKeyManagers().length);
- }
-
- /**
- * avax.net.ssl.KeyManagerFactory#getProvider()
- */
- public void test_getProvider()
- throws Exception {
- if (!DEFSupported) fail(NotSupportedMsg);
- assertEquals("Incorrect provider",
- defaultProvider,
- KeyManagerFactory
- .getInstance(defaultAlgorithm).getProvider());
- assertEquals("Incorrect provider",
- defaultProvider,
- KeyManagerFactory
- .getInstance(defaultAlgorithm, defaultProviderName)
- .getProvider());
- assertEquals("Incorrect provider",
- defaultProvider,
- KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
- .getProvider());
- }
-
- /**
- * Test for <code>init(KeyStore keyStore, char[] password)</code> and
- * <code>getKeyManagers()</code>
- * Assertion: returns not empty KeyManager array
- */
- public void test_initLjava_security_KeyStore$C()
- throws NoSuchAlgorithmException,
- KeyStoreException, UnrecoverableKeyException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory[] keyMF = createKMFac();
- assertNotNull("KeyManagerFactory object were not created", keyMF);
- KeyStore ksNull = null;
- KeyManager[] km;
- for (int i = 0; i < keyMF.length; i++) {
- keyMF[i].init(ksNull, new char[10]);
- km = keyMF[i].getKeyManagers();
- assertNotNull("Result should not be null", km);
- assertTrue("Length of result KeyManager array should not be 0",
- (km.length > 0));
- }
- KeyStore ks;
- try {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- } catch (KeyStoreException e) {
- fail(e.toString() + "default KeyStore type is not supported");
- return;
- } catch (Exception e) {
- fail("Unexpected: " + e.toString());
- return;
- }
- for (int i = 0; i < keyMF.length; i++) {
- try {
- keyMF[i].init(ks, new char[10]);
- } catch (KeyStoreException e) {
- }
- km = keyMF[i].getKeyManagers();
- assertNotNull("Result has not be null", km);
- assertTrue("Length of result KeyManager array should not be 0",
- (km.length > 0));
- }
-
- }
-
- /**
- * Test for <code>init(ManagerFactoryParameters params)</code>
- * Assertion:
- * throws InvalidAlgorithmParameterException when params is null
- */
- public void test_initLjavax_net_ssl_ManagerFactoryParameters()
- throws NoSuchAlgorithmException {
-
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- ManagerFactoryParameters par = null;
- KeyManagerFactory[] keyMF = createKMFac();
- assertNotNull("KeyManagerFactory object were not created", keyMF);
- for (int i = 0; i < keyMF.length; i++) {
- try {
- keyMF[i].init(par);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- }
-
- KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
- KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp);
- assertNotNull("Null object KeyStore.Builder", bld);
-
- try {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
- assertNotNull(ksp.getParameters());
- kmf.init(ksp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- }
-
-}
-
-/**
- * Additional class for KeyManagerFactory constructor verification
- */
-class myKeyManagerFactory extends KeyManagerFactory {
- public myKeyManagerFactory(KeyManagerFactorySpi spi, Provider prov,
- String alg) {
- super(spi, prov, alg);
- }
-}
-
-class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
- ProtectionParameterImpl(){}
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java
deleted file mode 100644
index 3d44396..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java
+++ /dev/null
@@ -1,263 +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 tests.api.javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.ManagerFactoryParameters;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
-import junit.framework.TestCase;
-
-/**
- * Tests for KeyManagerFactory class constructors and methods
- *
- */
-public class KeyManagerFactory2Test extends TestCase {
- private static final String srvKeyManagerFactory = "KeyManagerFactory";
-
- private static final String defaultAlg = "KeyMF";
-
- private static final String KeyManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static final String[] validValues;
-
- static {
- validValues = new String[4];
- validValues[0] = defaultAlg;
- validValues[1] = defaultAlg.toLowerCase();
- validValues[2] = "Keymf";
- validValues[3] = "kEYMF";
- }
-
- Provider mProv;
-
- protected void setUp() throws Exception {
- super.setUp();
- mProv = (new SpiEngUtils()).new MyProvider("MyKMFProvider",
- "Provider for testing", srvKeyManagerFactory.concat(".")
- .concat(defaultAlg), KeyManagerFactoryProviderClass);
- Security.insertProviderAt(mProv, 2);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- Security.removeProvider(mProv.getName());
- }
-
- private void checkResult(KeyManagerFactory keyMF)
- throws Exception {
- KeyStore kStore = null;
- ManagerFactoryParameters mfp = null;
-
- char[] pass = { 'a', 'b', 'c' };
-
- try {
- keyMF.init(kStore, null);
- fail("KeyStoreException must be thrown");
- } catch (KeyStoreException e) {
- }
- try {
- keyMF.init(kStore, pass);
- fail("UnrecoverableKeyException must be thrown");
- } catch (UnrecoverableKeyException e) {
- }
- try {
- keyMF.init(mfp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- assertNull("getKeyManagers() should return null object", keyMF
- .getKeyManagers());
-
- try {
- kStore = KeyStore.getInstance(KeyStore.getDefaultType());
- kStore.load(null, null);
- } catch (KeyStoreException e) {
- fail("default keystore is not supported");
- return;
- }
- keyMF.init(kStore, pass);
-
- mfp = new MyKeyManagerFactorySpi.Parameters(kStore, null);
- try {
- keyMF.init(mfp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- mfp = new MyKeyManagerFactorySpi.Parameters(kStore, pass);
- keyMF.init(mfp);
- }
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * returns KeyManagerFactory object
- */
- public void test_getInstanceLjava_lang_String() throws Exception {
- try {
- KeyManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i]);
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", keyMF.getProvider(), mProv);
- checkResult(keyMF);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null or empty;
- * throws NoSuchProviderException when provider is available;
- * returns KeyManagerFactory object
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String()
- throws Exception
- {
- try {
- KeyManagerFactory.getInstance(null, mProv.getName());
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory
- .getInstance(invalidValues[i], mProv.getName());
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- String prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- try {
- KeyManagerFactory.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- KeyManagerFactory.getInstance(validValues[i],
- invalidValues[j]);
- fail("NoSuchProviderException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(" provider: ")
- .concat(invalidValues[j]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i], mProv
- .getName());
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", keyMF.getProvider().getName(),
- mProv.getName());
- checkResult(keyMF);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null;
- * returns KeyManagerFactory object
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider()
- throws Exception
- {
- try {
- KeyManagerFactory.getInstance(null, mProv);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i], mProv);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- Provider prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i], mProv);
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", keyMF.getProvider(), mProv);
- checkResult(keyMF);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java
deleted file mode 100644
index fd44fda..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactorySpi;
-import javax.net.ssl.ManagerFactoryParameters;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.xnet.tests.support.KeyManagerFactorySpiImpl;
-
-public class KeyManagerFactorySpiTest extends TestCase {
-
- /**
- * javax.net.ssl.KeyManagerFactorySpi#KeyManagerFactorySpi()
- */
- public void test_Constructor() {
- try {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
- assertTrue(kmf instanceof KeyManagerFactorySpi);
- } catch (Exception e) {
- fail("Unexpected Exception " + e.toString());
- }
- }
-
- /**
- * javax.net.ssl.KeyManagerFactorySpi#KengineInit(KeyStore ks, char[] password)
- */
- public void test_engineInit_01() {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
- KeyStore ks;
- char[] psw = "password".toCharArray();
-
- try {
- kmf.engineInit(null, null);
- fail("NoSuchAlgorithmException wasn't thrown");
- } catch (NoSuchAlgorithmException kse) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of NoSuchAlgorithmException");
- }
-
- try {
- kmf.engineInit(null, psw);
- fail("KeyStoreException wasn't thrown");
- } catch (KeyStoreException uke) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of KeyStoreException");
- }
-
- try {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- kmf.engineInit(ks, null);
- fail("UnrecoverableKeyException wasn't thrown");
- } catch (UnrecoverableKeyException uke) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnrecoverableKeyException");
- }
-
- try {
- KeyStore kst = KeyStore.getInstance(KeyStore.getDefaultType());
- kst.load(null, null);
- kmf.engineInit(kst, psw);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * javax.net.ssl.KeyManagerFactorySpi#KengineInit(ManagerFactoryParameters spec)
- */
- public void test_engineInit_02() {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
-
- try {
- kmf.engineInit(null);
- fail("InvalidAlgorithmParameterException wasn't thrown");
- } catch (InvalidAlgorithmParameterException iape) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of InvalidAlgorithmParameterException");
- }
-
- try {
- char[] psw = "password".toCharArray();
- Parameters pr = new Parameters(psw);
- kmf.engineInit(pr);
- } catch (Exception e) {
- fail(e + " unexpected exception was thrown");
- }
- }
-
- /**
- * javax.net.ssl.KeyManagerFactorySpi#engineGetKeyManagers()
- */
- public void test_engineGetKeyManagers() {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
-
- try {
- KeyManager[] km = kmf.engineGetKeyManagers();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
-
- try {
- char[] psw = "password".toCharArray();
- Parameters pr = new Parameters(psw);
- kmf.engineInit(pr);
- KeyManager[] km = kmf.engineGetKeyManagers();
- assertNull("Object is not NULL", km);
- } catch (Exception e) {
- fail(e + " unexpected exception was thrown");
- }
- }
-
- public class Parameters implements ManagerFactoryParameters {
- private char[] passWD;
-
- public Parameters (char[] pass) {
- this.passWD = pass;
- }
- public char[] getPassword() {
- return passWD;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java b/luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java
deleted file mode 100644
index a2fe49c..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.KeyManagerFactorySpi;
-import javax.net.ssl.KeyStoreBuilderParameters;
-import java.security.KeyStore;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-public class KeyStoreBuilderParametersTest extends TestCase {
-
- /**
- * javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(KeyStore.Builder builder)
- */
- public void test_Constructor01() {
- // Null parameter
- try {
- new KeyStoreBuilderParameters((KeyStore.Builder) null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- // Not null parameter
- KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
- KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp);
- assertNotNull("Null object KeyStore.Builder", bld);
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
- assertNotNull(ksp.getParameters());
- }
-
- /**
- * javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(List parameters)
- */
- public void test_Constructor02() {
-
- // Null parameter
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters((List) null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- // Empty parameter
- List lsEmpty = new ArrayList<String>();
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(lsEmpty);
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- // Not null parameter
- List lsFiled = new ArrayList<String>();
- lsFiled.add("Parameter1");
- lsFiled.add("Parameter2");
- new KeyStoreBuilderParameters(lsFiled);
- }
-
- /**
- * javax.net.ssl.KeyStoreBuilderParameters#getParameters()
- */
- public void test_getParameters() {
- String[] param = {"Parameter1", "Parameter2", "Parameter3"};
- List ls = new ArrayList<String>();
- for (int i = 0; i < param.length; i++) {
- ls.add(param[i]);
- }
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(ls);
- List res_list = ksp.getParameters();
- try {
- res_list.add("test");
- fail();
- } catch (UnsupportedOperationException expected) {
- }
- Object[] res = res_list.toArray();
- assertEquals(res.length, param.length);
- for (int i = 0; i < res.length; i++) {
- assertEquals(param[i], res[i]);
- }
- }
-
- private static class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
- private ProtectionParameterImpl() {}
- }
-}
-
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java
deleted file mode 100644
index ee51cc0..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java
+++ /dev/null
@@ -1,599 +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 tests.api.javax.net.ssl;
-
-import java.io.FileNotFoundException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLContextSpi;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MySSLContextSpi;
-
-/**
- * Tests for <code>SSLContext</code> class constructors and methods.
- *
- */
-public class SSLContext1Test extends TestCase {
-
- private static String srvSSLContext = "SSLContext";
- public static String defaultProtocol = "TLS";
- private static final String NotSupportMsg = "Default protocol is not supported";
- private static String defaultProviderName = null;
- private static Provider defaultProvider = null;
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
- private static boolean DEFSupported = false;
- private static String[] validValues = new String[3];
- static {
- defaultProvider = SpiEngUtils.isSupport(defaultProtocol, srvSSLContext);
- DEFSupported = (defaultProvider != null);
- if (DEFSupported) {
- defaultProviderName = (DEFSupported ? defaultProvider.getName()
- : null);
- validValues[0] = defaultProtocol;
- validValues[1] = defaultProtocol.toUpperCase();
- validValues[2] = defaultProtocol.toLowerCase();
- } else {
- defaultProtocol = null;
- }
- }
-
- protected SSLContext[] createSSLCon() {
- if (!DEFSupported) {
- fail(defaultProtocol + " protocol is not supported");
- return null;
- }
- SSLContext[] sslC = new SSLContext[3];
- try {
- sslC[0] = SSLContext.getInstance(defaultProtocol);
- sslC[1] = SSLContext.getInstance(defaultProtocol, defaultProvider);
- sslC[2] = SSLContext.getInstance(defaultProtocol,
- defaultProviderName);
- return sslC;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Test for <code>SSLContext</code> constructor Assertion: returns
- * SSLContext object
- */
- public void test_ConstructorLjavax_net_ssl_SSLContextSpiLjava_security_ProviderLjava_lang_String()
- throws NoSuchAlgorithmException,
- KeyManagementException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- assertEquals("Incorrect protocol", defaultProtocol,
- sslContext.getProtocol());
- assertEquals("Incorrect provider", defaultProvider,
- sslContext.getProvider());
- TrustManager[] tm = null;
- KeyManager[] km = null;
- sslContext.init(km, tm, new SecureRandom());
- assertNotNull("No SSLEngine created",
- sslContext.createSSLEngine());
- assertNotNull("No SSLEngine created",
- sslContext.createSSLEngine("host", 8888));
- try {
- sslContext.init(km, tm, null);
- fail("KeyManagementException should be thrown for null "
- + "SecureRandom");
- } catch (KeyManagementException e) {
- }
-
- sslContext = new MySslContext(null, null, null);
- assertNull("Incorrect protocol", sslContext.getProtocol());
- assertNull("Incorrect provider", sslContext.getProvider());
- try {
- sslContext.createSSLEngine();
- fail("NullPointerException should be thrown");
- } catch (NullPointerException e) {
- }
- try {
- sslContext.getSocketFactory();
- fail("NullPointerException should be thrown");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @throws KeyManagementException
- * javax.net.ssl.SSLContext#createSSLEngine()
- */
- public void test_createSSLEngine() throws KeyManagementException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- sslContext.init(null, null, new SecureRandom());
- SSLEngine sslEngine = sslContext.createSSLEngine();
- assertNotNull("SSL engine is null", sslEngine);
- }
-
- /**
- * @throws KeyManagementException
- * javax.net.ssl.SSLContext#createSSLEngine(java.lang.String, int)
- */
- public void test_createSSLEngineLjava_lang_StringI()
- throws KeyManagementException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- sslContext.init(null, null, new SecureRandom());
- SSLEngine sslEngine = sslContext.createSSLEngine("www.fortify.net", 80);
- assertNotNull("SSL engine is null", sslEngine);
- }
-
- /**
- * Test for <code>getClientSessionContext()</code>
- * <code>getServiceSessionContext()</code>
- * methods Assertion: returns correspondent object
- * @throws KeyManagementException
- */
- public void test_getClientSessionContext() throws NoSuchAlgorithmException, KeyManagementException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- for (int i = 0; i < sslC.length; i++) {
- sslC[i].init(null, null, null);
- assertNotNull("Client session is incorrectly instantiated: " + i,
- sslC[i].getClientSessionContext());
- assertNotNull("Server session is incorrectly instantiated: " + i,
- sslC[i].getServerSessionContext());
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol)</code> method Assertion:
- * returns SSLContext object
- */
- public void test_getInstanceLjava_lang_String01()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext sslContext;
- for (int i = 0; i < validValues.length; i++) {
- sslContext = SSLContext.getInstance(validValues[i]);
- assertNotNull("No SSLContext created", sslContext);
- assertEquals("Invalid protocol", validValues[i],
- sslContext.getProtocol());
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol)</code> method Assertion:
- * throws NullPointerException when protocol is null; throws
- * NoSuchAlgorithmException when protocol is not correct;
- */
- public void test_getInstanceLjava_lang_String02() {
- try {
- SSLContext.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException was not thrown as expected for provider: "
- .concat(invalidValues[i]));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: throws IllegalArgumentException when provider is null
- * or empty
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- String provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(defaultProtocol, provider);
- fail("IllegalArgumentException must be thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- try {
- SSLContext.getInstance(defaultProtocol, "");
- fail("IllegalArgumentException must be thrown when provider is empty");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- try {
- SSLContext.getInstance(null, defaultProviderName);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], defaultProviderName);
- fail("NoSuchAlgorithmException was not thrown as expected (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: throws NoSuchProviderException when provider has
- * invalid value
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- for (int i = 1; i < invalidValues.length; i++) {
- for (int j = 0; j < validValues.length; j++) {
- try {
- SSLContext.getInstance(validValues[j], invalidValues[i]);
- fail("NuSuchProviderException must be thrown (protocol: "
- .concat(validValues[j]).concat(" provider: ")
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: returns instance of SSLContext
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws NoSuchAlgorithmException,
- NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext sslContext;
- for (int i = 0; i < validValues.length; i++) {
- sslContext = SSLContext.getInstance(validValues[i],
- defaultProviderName);
- assertNotNull("Not SSLContext created", sslContext);
- assertEquals("Invalid protocol",
- validValues[i], sslContext.getProtocol());
- assertEquals("Invalid provider",
- defaultProvider, sslContext.getProvider());
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method Assertion: throws IllegalArgumentException when provider is null
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- Provider provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(validValues[i], provider);
- fail("IllegalArgumentException must be thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method Assertion: throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- try {
- SSLContext.getInstance(null, defaultProvider);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], defaultProvider);
- fail("Expected NoSuchAlgorithmException was not thrown as expected");
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method Assertion: returns instance of SSLContext
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext sslContext;
- for (int i = 0; i < validValues.length; i++) {
- sslContext = SSLContext
- .getInstance(validValues[i], defaultProvider);
- assertNotNull("Not SSLContext created", sslContext);
- assertEquals("Invalid protocol", validValues[i], sslContext.getProtocol());
- assertEquals("Invalid provider", defaultProvider, sslContext.getProvider());
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- * javax.net.ssl.SSLContext#getProtocol()
- */
- public void test_getProtocol()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- sslContext = new MySslContext(spi, defaultProvider,
- null);
- assertNull("Incorrect protocol", sslContext.getProtocol());
- sslContext = SSLContext.getInstance(defaultProtocol);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- * javax.net.ssl.SSLContext#getProvider()
- */
- public void test_getProvider()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- assertEquals("Incorrect provider",
- defaultProvider, sslContext.getProvider());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider);
- assertEquals("Incorrect provider",
- defaultProvider, sslContext.getProvider());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName);
- assertEquals("Incorrect provider",
- defaultProvider, sslContext.getProvider());
- }
-
- /**
- * javax.net.ssl.SSLContext#getServletSessionContext()
- */
- public void test_getServerSessionContext() throws NoSuchAlgorithmException,
- KeyManagementException, KeyStoreException,
- UnrecoverableKeyException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null)
- fail("TrustManagerFactory default algorithm is not defined");
- if (kAlg == null)
- fail("KeyManagerFactory default algorithm is not defined");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- kmf.init(null, new char[11]);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- for (SSLContext sslCi : sslC) {
- sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom());
- assertNotNull("Server context is incorrectly instantiated", sslCi
- .getServerSessionContext());
- }
- }
-
- /**
- * Test for <code>getServerSocketFactory()</code>
- * <code>getSocketFactory()</code>
- * <code>init(KeyManager[] km, TrustManager[] tm, SecureRandom random)</code>
- * methods Assertion: returns correspondent object
- *
- */
- public void test_getServerSocketFactory() throws NoSuchAlgorithmException,
- KeyManagementException, KeyStoreException,
- UnrecoverableKeyException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null) {
- fail("TrustManagerFactory default algorithm is not defined");
- return;
- }
- if (kAlg == null) {
- fail("KeyManagerFactory default algorithm is not defined");
- return;
- }
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- try {
- ks.load(null, null);
- } catch (Exception e) {
- fail(e + " was thrown for method load(null, null)");
- }
- kmf.init(ks, new char[10]);
- KeyManager[] kms = kmf.getKeyManagers();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- for (int i = 0; i < sslC.length; i++) {
- sslC[i].init(kms, tms, new SecureRandom());
- assertNotNull("No SSLServerSocketFactory available",
- sslC[i].getServerSocketFactory());
- assertNotNull("No SSLSocketFactory available",
- sslC[i].getSocketFactory());
- }
- }
-
- /**
- * javax.net.ssl.SSLContext#getSocketFactory()
- */
- public void test_getSocketFactory() throws NoSuchAlgorithmException,
- KeyManagementException, KeyStoreException,
- UnrecoverableKeyException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null)
- fail("TrustManagerFactory default algorithm is not defined");
- if (kAlg == null)
- fail("KeyManagerFactory default algorithm is not defined");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- kmf.init(null, new char[11]);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- for (SSLContext sslCi : sslC) {
- sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom());
- assertNotNull("Socket factory is incorrectly instantiated",
- sslCi.getSocketFactory());
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * @throws FileNotFoundException
- * @throws KeyManagementException
- * javax.net.ssl.SSLContext#
- * init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[],
- * java.security.SecureRandom)
- */
- public void test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom()
- throws Exception {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- try {
- sslContext.createSSLEngine();
- fail("Expected RuntimeException was not thrown");
- } catch (RuntimeException rte) {
- // expected
- }
-
- try {
- sslContext.init(null, null, null);
- fail("KeyManagementException wasn't thrown");
- } catch (KeyManagementException kme) {
- //expected
- }
-
- try {
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null)
- fail("TrustManagerFactory default algorithm is not defined");
- if (kAlg == null)
- fail("KeyManagerFactory default algorithm is not defined");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- kmf.init(null, new char[11]);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
- } catch (Exception e) {
- System.out.println("EE = " + e);
- }
- }
-}
-
-/**
- * Addifional class to verify SSLContext constructor
- */
-
-class MySslContext extends SSLContext {
- public MySslContext(SSLContextSpi spi, Provider prov, String alg) {
- super(spi, prov, alg);
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java
deleted file mode 100644
index 0881615..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java
+++ /dev/null
@@ -1,293 +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 tests.api.javax.net.ssl;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.Security;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.TrustManager;
-import junit.framework.TestCase;
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MySSLContextSpi;
-
-/**
- * Tests for SSLContext class constructors and methods
- *
- */
-public class SSLContext2Test extends TestCase {
-
- private static String srvSSLContext = "SSLContext";
-
- private static final String defaultProtocol = "S+S+L";
-
- public static final String SSLContextProviderClass = MySSLContextSpi.class.getName();
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static final String[] validValues;
- static {
- validValues = new String[4];
- validValues[0] = defaultProtocol;
- validValues[1] = defaultProtocol.toLowerCase();
- validValues[2] = "s+S+L";
- validValues[3] = "S+s+L";
- }
-
- Provider mProv;
-
- protected void setUp() throws Exception {
- super.setUp();
- mProv = (new SpiEngUtils()).new MyProvider("MySSLContextProvider", "Provider for testing",
- srvSSLContext.concat(".").concat(defaultProtocol),
- SSLContextProviderClass);
- Security.insertProviderAt(mProv, 1);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- Security.removeProvider(mProv.getName());
- }
-
- private void checkSSLContext(SSLContext sslC)
- throws KeyManagementException {
-
- try {
- sslC.getSocketFactory();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.getServerSocketFactory();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.getServerSessionContext();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.getClientSessionContext();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.createSSLEngine();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.createSSLEngine("host",1);
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- TrustManager [] tm = new TManager[10];
- KeyManager [] km = new KManager[5];
- try {
- sslC.init(km, tm, null);
- fail("KeyManagementException must be thrown");
- } catch (KeyManagementException e) {
- }
- sslC.init(km, tm, new SecureRandom());
-
- SSLEngine sslE = sslC.createSSLEngine();
- assertTrue("Not null result",sslE instanceof SSLEngine);
- assertNull("Incorrect host", sslE.getPeerHost());
- assertEquals("Incorrect port", 0, sslE.getPeerPort());
- String host = "ZZZ";
- int port = 8080;
- sslE = sslC.createSSLEngine(host, port);
- assertTrue("Not null result",sslE instanceof SSLEngine);
- assertEquals("Incorrect host", sslE.getPeerHost(), host);
- assertEquals("Incorrect port", sslE.getPeerPort(), port);
- try {
- assertNull("Not null result", sslC.getServerSessionContext());
- } catch (NullPointerException e) {
- }
- try {
- assertNull("Not null result", sslC.getClientSessionContext());
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol)</code> method
- * Assertions:
- * throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- * returns SSLContext object
- */
- public void test_getInstanceLjava_lang_String() throws NoSuchAlgorithmException,
- KeyManagementException {
- try {
- SSLContext.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown "
- + "(protocol is null)");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- SSLContext sslC;
- for (int i = 0; i < validValues.length; i++) {
- sslC = SSLContext.getInstance(validValues[i]);
- assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext);
- assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]);
- assertEquals("Incorrect provider", sslC.getProvider(), mProv);
- checkSSLContext(sslC);
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- * throws IllegalArgumentException when provider is null or empty;
- * throws NoSuchProviderException when provider is available;
- * returns SSLContext object
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String()
- throws NoSuchAlgorithmException, NoSuchProviderException,
- IllegalArgumentException, KeyManagementException {
- try {
- SSLContext.getInstance(null, mProv.getName());
- fail("NoSuchAlgorithmException or NullPointerException should be thrown "
- + "(protocol is null)");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], mProv.getName());
- fail("NoSuchAlgorithmException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- String prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- try {
- SSLContext.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- SSLContext.getInstance(validValues[i], invalidValues[j]);
- fail("NoSuchProviderException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(" provider: ")
- .concat(invalidValues[j]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- SSLContext sslC;
- for (int i = 0; i < validValues.length; i++) {
- sslC = SSLContext.getInstance(validValues[i], mProv.getName());
- assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext);
- assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]);
- assertEquals("Incorrect provider", sslC.getProvider().getName(), mProv.getName());
- checkSSLContext(sslC);
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- * throws IllegalArgumentException when provider is null;
- * returns SSLContext object
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider()
- throws NoSuchAlgorithmException,
- IllegalArgumentException, KeyManagementException {
- try {
- SSLContext.getInstance(null, mProv);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown "
- + "(protocol is null)");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], mProv);
- fail("NoSuchAlgorithmException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- Provider prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- SSLContext sslC;
- for (int i = 0; i < validValues.length; i++) {
- sslC = SSLContext.getInstance(validValues[i], mProv);
- assertTrue("Not instanceof SSLContext object", sslC instanceof SSLContext);
- assertEquals("Incorrect protocol", sslC.getProtocol(), validValues[i]);
- assertEquals("Incorrect provider", sslC.getProvider(), mProv);
- checkSSLContext(sslC);
- }
- }
-
- class TManager implements TrustManager {
-
- }
- class KManager implements KeyManager {
-
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java
deleted file mode 100644
index 45a1c14..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContextSpi;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import java.security.KeyManagementException;
-
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.security.Security;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.xnet.tests.support.SSLContextSpiImpl;
-
-public class SSLContextSpiTest extends TestCase {
-
- /**
- * javax.net.ssl.SSLContextSpi#SSLContextSpi()
- */
- public void test_Constructor() {
- try {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- assertTrue(ssl instanceof SSLContextSpi);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine()
- * Verify exception when SSLContextSpi object wasn't initialiazed.
- */
- public void test_engineCreateSSLEngine_01() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- try {
- SSLEngine sleng = ssl.engineCreateSSLEngine();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
- }
-
- /**
- * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine(String host, int port)
- * Verify exception when SSLContextSpi object wasn't initialiazed.
- */
- public void test_engineCreateSSLEngine_02() {
- int[] invalid_port = {Integer.MIN_VALUE, -65535, -1, 65536, Integer.MAX_VALUE};
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- try {
- SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- for (int i = 0; i < invalid_port.length; i++) {
- try {
- SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", invalid_port[i]);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
- }
-
- /**
- * SSLContextSpi#engineGetClientSessionContext()
- * SSLContextSpi#engineGetServerSessionContext()
- * SSLContextSpi#engineGetServerSocketFactory()
- * SSLContextSpi#engineGetSocketFactory()
- * Verify exception when SSLContextSpi object wasn't initialiazed.
- */
- public void test_commonTest_01() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
-
- try {
- SSLSessionContext slsc = ssl.engineGetClientSessionContext();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- try {
- SSLSessionContext slsc = ssl.engineGetServerSessionContext();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- try {
- SSLServerSocketFactory sssf = ssl.engineGetServerSocketFactory();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- try {
- SSLSocketFactory ssf = ssl.engineGetSocketFactory();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
- }
-
- /**
- * SSLContextSpi#engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
- */
- public void test_engineInit() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
- try {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- char[] pass = "password".toCharArray();
- kmf.init(null, pass);
- KeyManager[] km = kmf.getKeyManagers();
- defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- trustMF.init(ks);
- TrustManager[] tm = trustMF.getTrustManagers();
- SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
- try {
- ssl.engineInit(km, tm, sr);
- } catch (KeyManagementException kme) {
- fail(kme + " was throw for engineInit method");
- }
- try {
- ssl.engineInit(km, tm, null);
- fail("KeyManagementException wasn't thrown");
- } catch (KeyManagementException kme) {
- //expected
- }
- } catch (Exception ex) {
- fail(ex + " unexpected exception");
- }
- }
-
- /**
- * SSLContextSpi#engineCreateSSLEngine()
- * SSLContextSpi#engineCreateSSLEngine(String host, int port)
- * SSLContextSpi#engineGetClientSessionContext()
- * SSLContextSpi#engineGetServerSessionContext()
- * SSLContextSpi#engineGetServerSocketFactory()
- * SSLContextSpi#engineGetSocketFactory()
- */
- public void test_commonTest_02() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
- try {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- char[] pass = "password".toCharArray();
- kmf.init(null, pass);
- KeyManager[] km = kmf.getKeyManagers();
- defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- trustMF.init(ks);
- TrustManager[] tm = trustMF.getTrustManagers();
- SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
- ssl.engineInit(km, tm, sr);
- } catch (Exception ex) {
- fail(ex + " unexpected exception");
- }
-
- try {
- assertNotNull("Subtest_01: Object is NULL", ssl.engineCreateSSLEngine());
- SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
- assertNotNull("Subtest_02: Object is NULL", sleng);
- assertEquals(sleng.getPeerPort(), 1080);
- assertEquals(sleng.getPeerHost(), "localhost");
- assertNull("Subtest_03: Object not NULL", ssl.engineGetClientSessionContext());
- assertNull("Subtest_04: Object not NULL", ssl.engineGetServerSessionContext());
- assertNull("Subtest_05: Object not NULL", ssl.engineGetServerSocketFactory());
- assertNull("Subtest_06: Object not NULL", ssl.engineGetSocketFactory());
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java
deleted file mode 100644
index 3b13673..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java
+++ /dev/null
@@ -1,83 +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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLEngineResult;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLEngineResult.Status class
- *
- */
-public class SSLEngineResultHandshakeStatusTest extends TestCase {
-
- /**
- * Test for <code> SSLEngineResult.HandshakeStatus.values() </code>
- */
- public void test_SSLEngineResultHandshakeStatus_values() {
- String[] str = {"NOT_HANDSHAKING", "FINISHED", "NEED_TASK", "NEED_WRAP", "NEED_UNWRAP"};
- SSLEngineResult.HandshakeStatus[] enS = SSLEngineResult.HandshakeStatus.values();
- if (enS.length == str.length) {
- for (int i = 0; i < enS.length; i++) {
- //System.out.println("enS[" + i + "] = " + enS[i]);
- assertEquals("Incorrect Status", enS[i].toString(), str[i]);
- }
- } else {
- fail("Incorrect number of enum constant was returned");
- }
- }
-
- /**
- * Test for <code> SSLEngineResult.HandshakeStatus.valueOf(String name) </code>
- */
- public void test_SSLEngineResultStatus_valueOf() {
- String[] str = {"FINISHED", "NEED_TASK", "NEED_UNWRAP", "NEED_WRAP", "NOT_HANDSHAKING"};
- String[] str_invalid = {"", "FINISHED1", "NEED_task", "NEED_UN",
- "NEED_WRAP_WRAP", "not_HANDSHAKING", "Bad string for verification valueOf method"};
- SSLEngineResult.HandshakeStatus enS;
-
- //Correct parameter
- for (int i = 0; i < str.length; i++) {
- try {
- enS = SSLEngineResult.HandshakeStatus.valueOf(str[i]);
- assertEquals("Incorrect Status", enS.toString(), str[i]);
- } catch (Exception e) {
- fail("Unexpected exception " + e + " was thrown for " + str[i]);
- }
- }
-
- //Incorrect parameter
- for (int i = 0; i < str_invalid.length; i++) {
- try {
- enS = SSLEngineResult.HandshakeStatus.valueOf(str_invalid[i]);
- fail("IllegalArgumentException should be thrown for " + str_invalid[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- //Null parameter
- try {
- enS = SSLEngineResult.HandshakeStatus.valueOf(null);
- fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter");
- } catch (NullPointerException npe) {
- //expected
- } catch (IllegalArgumentException iae) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java
deleted file mode 100644
index 05c8f03..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java
+++ /dev/null
@@ -1,90 +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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLEngineResult;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLEngineResult.Status class
- *
- */
-public class SSLEngineResultStatusTest extends TestCase {
-
- /**
- * Test for <code> SSLEngineResult.Status.values() </code>
- */
- public void test_SSLEngineResultStatus_values() {
- boolean flag = false;
- String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"};
- SSLEngineResult.Status[] enS = SSLEngineResult.Status.values();
- if (enS.length == str.length) {
- for (int i = 0; i < enS.length; i++) {
- flag = false;
- for (int j = 0; j < str.length; j++) {
- if (enS[i].toString() == str[j]) {
- flag = true;
- break;
- }
- }
- }
- assertTrue("Incorrect Status", flag);
- } else {
- fail("Incorrect number of enum constant was returned");
- }
- }
-
- /**
- * Test for <code> SSLEngineResult.Status.valueOf(String name) </code>
- */
- public void test_SSLEngineResultStatus_valueOf() {
- String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"};
- String[] str_invalid = {"", "OK1", "BUFFER_overflow", "BUFFER_UND",
- "CLOSED_CLOSED", "Bad string for verification valueOf method"};
- SSLEngineResult.Status enS;
-
- //Correct parameter
- for (int i = 0; i < str.length; i++) {
- try {
- enS = SSLEngineResult.Status.valueOf(str[i]);
- assertEquals("Incorrect Status", enS.toString(), str[i]);
- } catch (Exception e) {
- fail("Unexpected exception " + e + " was thrown for " + str[i]);
- }
- }
-
- //Incorrect parameter
- for (int i = 0; i < str_invalid.length; i++) {
- try {
- enS = SSLEngineResult.Status.valueOf(str_invalid[i]);
- fail("IllegalArgumentException should be thrown for " + str_invalid[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- //Null parameter
- try {
- enS = SSLEngineResult.Status.valueOf(null);
- fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter");
- } catch (NullPointerException npe) {
- //expected
- } catch (IllegalArgumentException iae) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java
deleted file mode 100644
index 7a2ac78..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java
+++ /dev/null
@@ -1,217 +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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLEngineResult;
-import junit.framework.TestCase;
-
-
-/**
- * Tests for SSLEngineResult class
- *
- */
-public class SSLEngineResultTest extends TestCase {
-
- /**
- * Test for <code>SSLEngineResult(SSLEngineResult.Status status,
- * SSLEngineResult.HandshakeStatus handshakeStatus,
- * int bytesConsumed,
- * int bytesProduced) </code> constructor and
- * <code>getHandshakeStatus()</code>
- * <code>getStatus()</code>
- * <code>bytesConsumed()</code>
- * <code>bytesProduced()</code>
- * <code>toString()</code>
- * methods
- * Assertions:
- * constructor throws IllegalArgumentException when bytesConsumed
- * or bytesProduced is negative or when status or handshakeStatus
- * is null
- *
- */
- public void test_ConstructorLjavax_net_ssl_SSLEngineResult_StatusLjavax_net_ssl_SSLEngineResult_HandshakeStatusII() {
-
- int[] neg = { -1, -10, -1000, Integer.MIN_VALUE,
- (Integer.MIN_VALUE + 1) };
- try {
- new SSLEngineResult(null, SSLEngineResult.HandshakeStatus.FINISHED,
- 1, 1);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, null,
- 1, 1);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- for (int i = 0; i < neg.length; i++) {
- try {
- new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- SSLEngineResult.HandshakeStatus.FINISHED, neg[i], 1);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < neg.length; i++) {
- try {
- new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- SSLEngineResult.HandshakeStatus.FINISHED, 1, neg[i]);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- try {
- SSLEngineResult res = new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- SSLEngineResult.HandshakeStatus.FINISHED, 1, 2);
- assertNotNull("Null object", res);
- assertEquals(1, res.bytesConsumed());
- assertEquals(2, res.bytesProduced());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * Test for <code>bytesConsumed()</code> method
- */
- public void test_bytesConsumed() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; l++) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect bytesConsumed", pos[n],
- res.bytesConsumed());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>bytesProduced()</code> method
- */
- public void test_bytesProduced() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect bytesProduced", pos[l],
- res.bytesProduced());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>getHandshakeStatus()</code> method
- */
- public void test_getHandshakeStatus() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect HandshakeStatus", enHS[j],
- res.getHandshakeStatus());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>getStatus()</code> method
- */
- public void test_getStatus() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect Status", enS[i],
- res.getStatus());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>toString()</code> method
- */
- public void test_toString() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertNotNull("Result of toSring() method is null",
- res.toString());
- }
- }
- }
- }
- }
-
- private boolean findEl(Object[] arr, Object el) {
- boolean ok = false;
- for (int i = 0; i < arr.length; i++) {
- if (arr[i].equals(el)) {
- ok = true;
- break;
- }
- }
- return ok;
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
deleted file mode 100644
index 30a1a9c..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
+++ /dev/null
@@ -1,1482 +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 tests.api.javax.net.ssl;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ReadOnlyBufferException;
-import java.nio.channels.Pipe;
-import java.nio.channels.Pipe.SinkChannel;
-import java.nio.channels.Pipe.SourceChannel;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-
-import junit.framework.TestCase;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-
-
-/**
- * Tests for SSLEngine class
- *
- */
-public class SSLEngineTest extends TestCase {
-
- private HandshakeHandler clientEngine;
- private HandshakeHandler serverEngine;
-
- @Override protected void setUp() throws Exception {
- super.setUp();
- }
-
- /**
- * Test for <code>SSLEngine()</code> constructor Assertion: creates
- * SSLEngine object with null host and -1 port
- * @throws NoSuchAlgorithmException
- */
- public void test_Constructor() throws NoSuchAlgorithmException {
- SSLEngine e = getEngine();
- assertNull(e.getPeerHost());
- assertEquals(-1, e.getPeerPort());
- String[] suites = e.getSupportedCipherSuites();
- e.setEnabledCipherSuites(suites);
- assertEquals(e.getEnabledCipherSuites().length, suites.length);
- }
-
- /**
- * Test for <code>SSLEngine(String host, int port)</code> constructor
- * @throws NoSuchAlgorithmException
- */
- public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException {
- int port = 1010;
- SSLEngine e = getEngine(null, port);
- assertNull(e.getPeerHost());
- assertEquals(e.getPeerPort(), port);
- try {
- e.beginHandshake();
- } catch (IllegalStateException ex) {
- // expected
- } catch (SSLException ex) {
- fail("unexpected SSLException was thrown.");
- }
- e = getEngine(null, port);
- e.setUseClientMode(true);
- try {
- e.beginHandshake();
- } catch (SSLException ex) {
- // expected
- }
- e = getEngine(null, port);
- e.setUseClientMode(false);
- try {
- e.beginHandshake();
- } catch (SSLException ex) {
- // expected
- }
- }
-
- /**
- * Test for <code>SSLEngine(String host, int port)</code> constructor
- * @throws NoSuchAlgorithmException
- */
- public void test_ConstructorLjava_lang_StringI02() throws NoSuchAlgorithmException {
- String host = "new host";
- int port = 8080;
- SSLEngine e = getEngine(host, port);
- assertEquals(e.getPeerHost(), host);
- assertEquals(e.getPeerPort(), port);
- String[] suites = e.getSupportedCipherSuites();
- e.setEnabledCipherSuites(suites);
- assertEquals(e.getEnabledCipherSuites().length, suites.length);
- e.setUseClientMode(true);
- assertTrue(e.getUseClientMode());
- }
-
- /**
- * Test for <code>getPeerHost()</code> method
- * @throws NoSuchAlgorithmException
- */
- public void test_getPeerHost() throws NoSuchAlgorithmException {
- SSLEngine e = getEngine();
- assertNull(e.getPeerHost());
- e = getEngine("www.fortify.net", 80);
- assertEquals("Incorrect host name", "www.fortify.net", e.getPeerHost());
- }
-
- /**
- * Test for <code>getPeerPort()</code> method
- * @throws NoSuchAlgorithmException
- */
- public void test_getPeerPort() throws NoSuchAlgorithmException {
- SSLEngine e = getEngine();
- assertEquals("Incorrect default value of peer port",
- -1 ,e.getPeerPort());
- e = getEngine("www.fortify.net", 80);
- assertEquals("Incorrect peer port", 80, e.getPeerPort());
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#getSupportedProtocols()
- */
- public void test_getSupportedProtocols() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- String[] res = sse.getSupportedProtocols();
- assertNotNull(res);
- assertTrue(res.length > 0);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#setEnabledProtocols(String[] protocols)
- * javax.net.ssl.SSLEngine#getEnabledProtocols()
- */
- public void test_EnabledProtocols() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- String[] pr = sse.getSupportedProtocols();
- try {
- sse.setEnabledProtocols(pr);
- String[] res = sse.getEnabledProtocols();
- assertNotNull("Null array was returned", res);
- assertEquals("Incorrect array length", res.length, pr.length);
- assertTrue("Incorrect array was returned", Arrays.equals(res, pr));
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- sse.setEnabledProtocols(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#getSupportedCipherSuites()
- */
- public void test_getSupportedCipherSuites() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- String[] res = sse.getSupportedCipherSuites();
- assertNotNull(res);
- assertTrue(res.length > 0);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#setEnabledCipherSuites(String[] suites)
- * javax.net.ssl.SSLEngine#getEnabledCipherSuites()
- */
- public void test_EnabledCipherSuites() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- String[] st = sse.getSupportedCipherSuites();
- try {
- sse.setEnabledCipherSuites(st);
- String[] res = sse.getEnabledCipherSuites();
- assertNotNull("Null array was returned", res);
- assertEquals("Incorrect array length", res.length, st.length);
- assertTrue("Incorrect array was returned", Arrays.equals(res, st));
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- sse.setEnabledCipherSuites(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#setEnableSessionCreation(boolean flag)
- * javax.net.ssl.SSLEngine#getEnableSessionCreation()
- */
- public void test_EnableSessionCreation() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertTrue(sse.getEnableSessionCreation());
- sse.setEnableSessionCreation(false);
- assertFalse(sse.getEnableSessionCreation());
- sse.setEnableSessionCreation(true);
- assertTrue(sse.getEnableSessionCreation());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#setNeedClientAuth(boolean need)
- * javax.net.ssl.SSLEngine#getNeedClientAuth()
- */
- public void test_NeedClientAuth() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.setNeedClientAuth(false);
- assertFalse(sse.getNeedClientAuth());
- sse.setNeedClientAuth(true);
- assertTrue(sse.getNeedClientAuth());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#setWantClientAuth(boolean want)
- * javax.net.ssl.SSLEngine#getWantClientAuth()
- */
- public void test_WantClientAuth() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.setWantClientAuth(false);
- assertFalse(sse.getWantClientAuth());
- sse.setWantClientAuth(true);
- assertTrue(sse.getWantClientAuth());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#beginHandshake()
- */
- public void test_beginHandshake() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.beginHandshake();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException se) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- sse = getEngine("new host", 1080);
- try {
- sse.beginHandshake();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- sse = getEngine();
- try {
- sse.setUseClientMode(true);
- sse.beginHandshake();
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#setUseClientMode(boolean mode)
- * javax.net.ssl.SSLEngine#getUseClientMode()
- */
- @AndroidOnly("The RI doesn't throw the expected IllegalStateException.")
- public void test_UseClientMode() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.setUseClientMode(false);
- assertFalse(sse.getUseClientMode());
- sse.setUseClientMode(true);
- assertTrue(sse.getUseClientMode());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
-
- try {
- sse = getEngine(null, 1080);
- sse.setUseClientMode(true);
- sse.beginHandshake();
- try {
- sse.setUseClientMode(false);
- fail("IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#getSession()
- */
- public void test_getSession() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertNotNull(sse.getSession());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#getHandshakeStatus()
- */
- public void test_getHandshakeStatus() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertEquals(sse.getHandshakeStatus().toString(), "NOT_HANDSHAKING");
- sse.setUseClientMode(true);
- sse.beginHandshake();
- assertEquals(sse.getHandshakeStatus().toString(), "NEED_WRAP");
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#getDelegatedTask()
- */
- @KnownFailure("com.android.org.conscrypt.SSLEngineImpl#getDelegatedTask() throws NPE instead of returning null")
- public void test_getDelegatedTask() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertNull(sse.getDelegatedTask());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: SSLException should be thrown.
- */
- public void test_unwrap_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
-
- ByteBuffer bbs = ByteBuffer.wrap(new byte[] {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,31,2,3,1,2,3,1,2,3,1,2,3});
- ByteBuffer bbd = ByteBuffer.allocate(100);
- try {
- clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd }, 0, 1);
- fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: IndexOutOfBoundsException should be thrown.
- */
- @KnownFailure("Fixed in DonutBurger, boundary checks missing")
- public void test_unwrap_02() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bb, bbA, -1, 3);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.unwrap(bb, bbA, 0, -3);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.unwrap(bb, bbA, bbA.length + 1, bbA.length);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.unwrap(bb, bbA, 0, bbA.length + 1);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: ReadOnlyBufferException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
- ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bb, bbA, 0, bbA.length);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: IllegalArgumentException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
- ByteBuffer[] bbAN = {ByteBuffer.allocate(100), null, ByteBuffer.allocate(100)};
- ByteBuffer[] bbN = null;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer bN = null;
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bN, bbA, 0, 3);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- try {
- sse.unwrap(bb, bbAN, 0, 3);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- try {
- sse.unwrap(bb, bbN, 0, 0);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- try {
- sse.unwrap(bN, bbN, 0, 0);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: IllegalStateException should be thrown.
- */
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_unwrap_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.unwrap(bb, bbA, 0, bbA.length);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- */
- public void test_unwrap_06() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.unwrap(bb, bbA, 0, bbA.length);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- public void test_wrap_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(20000);
- clientEngine.engine.wrap(new ByteBuffer[] { bbs }, 0, 1, bbd);
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: IndexOutOfBoundsException should be thrown.
- */
- @KnownFailure("Fixed in DonutBurger, boundary checks missing")
- public void test_wrap_02() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, -1, 3, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.wrap(bbA, 0, -3, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.wrap(bbA, bbA.length + 1, bbA.length, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.wrap(bbA, 0, bbA.length + 1, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: ReadOnlyBufferException should be thrown.
- */
- public void test_wrap_03() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer();
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, 0, bbA.length, bb);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: IllegalArgumentException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_wrap_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
- ByteBuffer[] bbN = null;
- ByteBuffer bN = null;
- SSLEngine e = getEngine(host, port);
- e.setUseClientMode(true);
-
- try {
- e.wrap(bbA, 0, 3, bN);
- fail("IllegalArgumentException must be thrown for null srcs byte buffer array");
- } catch (NullPointerException npe) {
- } catch (IllegalArgumentException ex) {
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- e.wrap(bbN, 0, 0, bN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException ex) {
- } catch (NullPointerException npe) {
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: IllegalStateException should be thrown.
- */
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_wrap_05() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.wrap(bbA, 0, bbA.length, bb);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- */
- public void test_wrap_06() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, 0, bbA.length, bb);
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#closeOutbound()
- * javax.net.ssl.SSLEngine#isOutboundDone()
- */
- public void test_closeOutbound() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
-
- try {
- assertFalse(sse.isOutboundDone());
- sse.closeOutbound();
- assertTrue(sse.isOutboundDone());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.SSLEngine#closeInbound()
- * javax.net.ssl.SSLEngine#isInboundDone()
- */
- public void test_closeInbound() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
-
- try {
- assertFalse(sse.isInboundDone());
- sse.closeInbound();
- assertTrue(sse.isInboundDone());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * SSLException should be thrown.
- */
- public void test_unwrap_ByteBuffer_ByteBuffer_01() throws InterruptedException, IOException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(100);
-
- try {
- SSLEngineResult unwrap = clientEngine.engine.unwrap(bbs, bbd);
- fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * ReadOnlyBufferException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer_ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer();
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bbs, bbd);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * IllegalArgumentException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer_ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbsN = null;
- ByteBuffer bbdN = null;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bbsN, bbd);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bbs, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bbsN, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * IllegalStateException should be thrown.
- */
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_unwrap_ByteBuffer_ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.unwrap(bbs, bbd);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- */
- public void test_unwrap_ByteBuffer_ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.unwrap(bbs, bbd);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * SSLException should be thrown.
- */
- public void test_unwrap_ByteBuffer$ByteBuffer_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
-
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(100);
-
- try {
- clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd });
- fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * ReadOnlyBufferException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer$ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
- ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bbs, bbA);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * IllegalArgumentException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer$ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- ByteBuffer[] bbN = { ByteBuffer.allocate(100), null, ByteBuffer.allocate(100) };
- ByteBuffer[] bbAN = null;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer bN = null;
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bN, bbA);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bb, bbAN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bb, bbN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bN, bbAN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * IllegalStateException should be thrown.
- */
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_unwrap_ByteBuffer$ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.unwrap(bbs, bbd);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- */
- public void test_unwrap_ByteBuffer$ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.unwrap(bbs, bbd);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- public void test_wrap_ByteBuffer_ByteBuffer_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(20);
- ByteBuffer bbd = ByteBuffer.allocate(20000);
- clientEngine.engine.wrap(bbs, bbd);
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * ReadOnlyBufferException should be thrown.
- */
- public void test_wrap_ByteBuffer_ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer();
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbs, bbd);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * IllegalArgumentException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_wrap_ByteBuffer_ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbsN = null;
- ByteBuffer bbdN = null;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbsN, bbd);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbs, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbsN, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * IllegalStateException should be thrown.
- */
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_wrap_ByteBuffer_ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.wrap(bbs, bbd);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- */
- public void test_wrap_ByteBuffer_ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.wrap(bb, ByteBuffer.allocate(10));
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * SSLException should be thrown.
- */
- public void test_wrap_ByteBuffer$ByteBuffer_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(20000);
-
- try {
- clientEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd);
- serverEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd);
- //fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * ReadOnlyBufferException should be thrown.
- */
- public void test_wrap_ByteBuffer$ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer();
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, bb);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * IllegalArgumentException should be thrown.
- */
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_wrap_ByteBuffer$ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
- ByteBuffer[] bbAN = null;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer bN = null;
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, bN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbAN, bb);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbAN, bN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * IllegalStateException should be thrown.
- */
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_wrap_ByteBuffer$ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.wrap(bbA, bb);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- */
- public void test_wrap_ByteBuffer$ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.wrap(bbA, bb);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- private SSLEngine getEngine() {
- SSLContext context = null;
- try {
- context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- } catch (KeyManagementException e) {
- fail("Could not get SSLEngine: key management exception "
- + e.getMessage());
- } catch (NoSuchAlgorithmException e) {
- fail("Could not get SSLEngine: no such algorithm " + e.getMessage());
- }
- return context.createSSLEngine();
- }
-
- private SSLEngine getEngine(String host, int port) {
- SSLContext context = null;
- try {
- context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- } catch (KeyManagementException e) {
- fail("Could not get SSLEngine: key management exception "
- + e.getMessage());
- } catch (NoSuchAlgorithmException e) {
- fail("Could not get SSLEngine: no such algorithm " + e.getMessage());
- }
- return context.createSSLEngine(host, port);
- }
-
- class HandshakeHandler implements Runnable {
-
- private final SSLEngine engine;
-
- private final SourceChannel in;
-
- private final SinkChannel out;
-
- private final ByteBuffer EMPTY = ByteBuffer.allocate(0);
-
- @SuppressWarnings("unused")
- private final String LOGTAG;
-
- private SSLEngineResult.HandshakeStatus status;
-
- private ByteBuffer readBuffer;
-
- private ByteBuffer writeBuffer;
-
- HandshakeHandler(boolean clientMode, SourceChannel in, SinkChannel out)
- throws SSLException {
- this.in = in;
- this.out = out;
- engine = getEngine();
- engine.setUseClientMode(clientMode);
- String[] cipherSuites = engine.getSupportedCipherSuites();
- Set<String> enabledSuites = new HashSet<String>();
- for (String cipherSuite : cipherSuites) {
- if (cipherSuite.contains("anon")) {
- enabledSuites.add(cipherSuite);
- }
- }
- engine.setEnabledCipherSuites((String[]) enabledSuites.toArray(
- new String[enabledSuites.size()]));
-
- engine.beginHandshake();
- status = engine.getHandshakeStatus();
-
- if (clientMode) {
- LOGTAG = "CLIENT: ";
- } else {
- LOGTAG = "SERVER: ";
- }
-
- log("CipherSuites: " + Arrays.toString(engine.getEnabledCipherSuites()));
- log(status);
-
- readBuffer = ByteBuffer.allocate(200000);
- writeBuffer = ByteBuffer.allocate(20000);
- }
-
- public SSLEngineResult.HandshakeStatus getStatus() {
- return status;
- }
-
- private void log(Object o) {
- //System.out.print(LOGTAG);
- //System.out.println(o);
- }
-
- private ByteBuffer read() throws IOException {
- if (readBuffer == null || readBuffer.remaining() == 0 || readBuffer.position() == 0) {
- readBuffer.clear();
- int read = in.read(readBuffer);
- log("read: " + read);
- readBuffer.rewind();
- readBuffer.limit(read);
- }
- return readBuffer;
- }
-
- public void run() {
- try {
- while (true) {
- switch (status) {
- case FINISHED: {
- log(status);
- return;
- }
- case NEED_TASK: {
- log(status);
- Runnable task;
- while ((task = engine.getDelegatedTask()) != null) {
- task.run();
- }
- status = engine.getHandshakeStatus();
- break;
- }
- case NEED_UNWRAP: {
- log(status);
- ByteBuffer source = read();
- writeBuffer.clear();
-
- while (status == HandshakeStatus.NEED_UNWRAP) {
- SSLEngineResult result = engine.unwrap(source, writeBuffer);
- status = result.getHandshakeStatus();
- log(result);
- }
- break;
- }
- case NEED_WRAP: {
- log(status);
- writeBuffer.clear();
-
- int produced = 0;
- SSLEngineResult result = null;
- while (status == HandshakeStatus.NEED_WRAP) {
- result = engine.wrap(EMPTY, writeBuffer);
- status = result.getHandshakeStatus();
- produced += result.bytesProduced();
- log(result);
- }
- writeBuffer.rewind();
- writeBuffer.limit(produced);
- log("write: " + produced);
- out.write(writeBuffer);
- break;
- }
- case NOT_HANDSHAKING: {
- log("Not Handshaking");
- return;
- }
- }
- }
- } catch (IOException e) {
- log(e);
- } catch (RuntimeException e) {
- // ignore;
- }
- }
- }
-
- @KnownFailure("Handshake Status is never finished. NPE in "
- + "ClientSessionContext$HostAndPort.hashCode() when host is null")
- public void testHandshake() throws IOException, InterruptedException {
-
- prepareEngines();
-
- assertTrue("handshake failed", doHandshake());
-
- System.out.println(clientEngine.engine.getSession().getCipherSuite());
-
- assertEquals("Handshake not finished",
- SSLEngineResult.HandshakeStatus.FINISHED,
- clientEngine.getStatus());
- assertEquals("Handshake not finished",
- SSLEngineResult.HandshakeStatus.FINISHED,
- serverEngine.getStatus());
- }
-
- void prepareEngines() throws IOException {
- Pipe clientSendPipe = Pipe.open();
- Pipe serverSendPipe = Pipe.open();
-
- SinkChannel clientSink = clientSendPipe.sink();
- SourceChannel serverSource = clientSendPipe.source();
- SinkChannel serverSink = serverSendPipe.sink();
- SourceChannel clientSource = serverSendPipe.source();
-
- clientEngine = new HandshakeHandler(true, clientSource, clientSink);
- serverEngine = new HandshakeHandler(false, serverSource, serverSink);
- }
-
- boolean doHandshake() throws InterruptedException {
- Thread clientThread = new Thread(clientEngine);
- clientThread.start();
-
- Thread serverThread = new Thread(serverEngine);
- serverThread.start();
-
- int i = 0;
- while (clientThread.isAlive() && serverThread.isAlive() && i < 20) {
- Thread.sleep(500);
- i++;
- }
-
- if (clientThread.isAlive()) {
- clientThread.interrupt();
- }
-
- if (serverThread.isAlive()) {
- serverThread.interrupt();
- }
-
- return clientEngine.getStatus() == HandshakeStatus.FINISHED && serverEngine.getStatus() == HandshakeStatus.FINISHED;
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java
deleted file mode 100644
index 9b4ae35..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLException;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>SSLException</code> class constructors and methods.
- *
- */
-public class SSLExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- private static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>SSLException(String)</code> constructor Assertion:
- * constructs SSLException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- public void testSSLException01() {
- SSLException sE;
- for (int i = 0; i < msgs.length; i++) {
- sE = new SSLException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLException(String)</code> constructor Assertion:
- * constructs SSLException when <code>msg</code> is null
- */
- public void testSSLException02() {
- String msg = null;
- SSLException sE = new SSLException(msg);
- assertNull("getMessage() must return null.", sE.getMessage());
- assertNull("getCause() must return null", sE.getCause());
- }
-
- /**
- * Test for <code>SSLException(Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is null
- */
- public void testSSLException03() {
- Throwable cause = null;
- SSLException sE = new SSLException(cause);
- assertNull("getMessage() must return null.", sE.getMessage());
- assertNull("getCause() must return null", sE.getCause());
- }
-
- /**
- * Test for <code>SSLException(Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is not
- * null
- */
- public void testSSLException04() {
- SSLException sE = new SSLException(tCause);
- if (sE.getMessage() != null) {
- String toS = tCause.toString();
- String getM = sE.getMessage();
- assertTrue("getMessage() should contain ".concat(toS), (getM
- .indexOf(toS) != -1));
- }
- assertNotNull("getCause() must not return null", sE.getCause());
- assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is null
- * <code>msg</code> is null
- */
- public void testSSLException05() {
- SSLException sE = new SSLException(null, null);
- assertNull("getMessage() must return null", sE.getMessage());
- assertNull("getCause() must return null", sE.getCause());
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is null
- * <code>msg</code> is not null
- */
- public void testSSLException06() {
- SSLException sE;
- for (int i = 0; i < msgs.length; i++) {
- sE = new SSLException(msgs[i], null);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", sE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is not
- * null <code>msg</code> is null
- */
- public void testSSLException07() {
- SSLException sE = new SSLException(null, tCause);
- if (sE.getMessage() != null) {
- String toS = tCause.toString();
- String getM = sE.getMessage();
- assertTrue("getMessage() must should ".concat(toS), (getM
- .indexOf(toS) != -1));
- }
- assertNotNull("getCause() must not return null", sE.getCause());
- assertEquals("getCause() must return ".concat(tCause.toString()), sE
- .getCause(), tCause);
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is not
- * null <code>msg</code> is not null
- */
- public void testSSLException08() {
- SSLException sE;
- for (int i = 0; i < msgs.length; i++) {
- sE = new SSLException(msgs[i], tCause);
- String getM = sE.getMessage();
- String toS = tCause.toString();
- if (msgs[i].length() > 0) {
- assertTrue("getMessage() must contain ".concat(msgs[i]), getM
- .indexOf(msgs[i]) != -1);
- if (!getM.equals(msgs[i])) {
- assertTrue("getMessage() should contain ".concat(toS), getM
- .indexOf(toS) != -1);
- }
- }
- assertNotNull("getCause() must not return null", sE.getCause());
- assertEquals("getCause() must return ".concat(tCause.toString()),
- sE.getCause(), tCause);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java
deleted file mode 100644
index a2d0ec5..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLHandshakeException;
-
-import junit.framework.TestCase;
-
-public class SSLHandshakeExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLHandshakeException(String)</code> constructor Assertion:
- * constructs SSLHandshakeException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- public void test_Constructor01() {
- SSLHandshakeException sslE;
- for (int i = 0; i < msgs.length; i++) {
- sslE = new SSLHandshakeException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sslE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLHandshakeException(String)</code> constructor Assertion:
- * constructs SSLHandshakeException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- public void test_Constructor02() {
- String msg = null;
- SSLHandshakeException sslE = new SSLHandshakeException(msg);
- assertNull("getMessage() must return null.", sslE.getMessage());
- assertNull("getCause() must return null", sslE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java
deleted file mode 100644
index d6ba998..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLKeyException;
-
-import junit.framework.TestCase;
-
-public class SSLKeyExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLKeyException(String)</code> constructor Assertion:
- * constructs SSLKeyException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- public void test_Constructor01() {
- SSLKeyException skE;
- for (int i = 0; i < msgs.length; i++) {
- skE = new SSLKeyException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), skE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", skE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
- * constructs SSLPeerUnverifiedException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- public void test_Constructor02() {
- String msg = null;
- SSLKeyException skE = new SSLKeyException(msg);
- assertNull("getMessage() must return null.", skE.getMessage());
- assertNull("getCause() must return null", skE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java
deleted file mode 100644
index a8b9ac4..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-
-import junit.framework.TestCase;
-
-public class SSLPeerUnverifiedExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
- * constructs SSLPeerUnverifiedException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- public void test_Constructor01() {
- SSLPeerUnverifiedException sslE;
- for (int i = 0; i < msgs.length; i++) {
- sslE = new SSLPeerUnverifiedException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sslE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
- * constructs SSLPeerUnverifiedException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- public void test_Constructor02() {
- String msg = null;
- SSLPeerUnverifiedException sslE = new SSLPeerUnverifiedException(msg);
- assertNull("getMessage() must return null.", sslE.getMessage());
- assertNull("getCause() must return null", sslE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java
deleted file mode 100644
index 14b562d..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLProtocolException;
-
-import junit.framework.TestCase;
-
-public class SSLProtocolExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLProtocolException(String)</code> constructor Assertion:
- * constructs SSLProtocolException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- public void test_Constructor01() {
- SSLProtocolException sslE;
- for (int i = 0; i < msgs.length; i++) {
- sslE = new SSLProtocolException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sslE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLProtocolException(String)</code> constructor Assertion:
- * constructs SSLProtocolException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- public void test_Constructor02() {
- String msg = null;
- SSLProtocolException sslE = new SSLProtocolException(msg);
- assertNull("getMessage() must return null.", sslE.getMessage());
- assertNull("getCause() must return null", sslE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java
deleted file mode 100644
index 5958ecb..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-
-import javax.net.ssl.SSLServerSocketFactory;
-
-import junit.framework.TestCase;
-
-public class SSLServerSocketFactoryTest extends TestCase {
-
- private class MockSSLServerSocketFactory extends SSLServerSocketFactory {
- public MockSSLServerSocketFactory() {
- super();
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return null;
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int arg0) throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int arg0, int arg1)
- throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int arg0, int arg1,
- InetAddress arg2) throws IOException {
- return null;
- }
- }
-
- /**
- * javax.net.ssl.SSLServerSocketFactory#SSLServerSocketFactory()
- */
- public void test_Constructor() {
- try {
- MockSSLServerSocketFactory ssf = new MockSSLServerSocketFactory();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.net.ssl.SSLServerSocketFactory#getDefault()
- */
- public void test_getDefault() {
- assertNotNull("Incorrect default socket factory",
- SSLServerSocketFactory.getDefault());
- }
-
- /**
- * javax.net.ssl.SSLServerSocketFactory#getDefaultCipherSuites()
- */
- public void test_getDefaultCipherSuites() {
- SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory
- .getDefault();
- try {
- assertTrue(ssf.getDefaultCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * javax.net.ssl.SSLServerSocketFactory#getSupportedCipherSuites()
- */
- public void test_getSupportedCipherSuites() {
- SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory
- .getDefault();
- try {
- assertTrue(ssf.getSupportedCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java
deleted file mode 100644
index 5086f65..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import junit.framework.TestCase;
-
-import libcore.io.Base64;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.util.Arrays;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-
-public class SSLServerSocketTest extends TestCase {
-
- // set to true if on Android, false if on RI
- boolean useBKS = true;
-
- /**
- * Additional class for SSLServerSocket constructor verification
- */
- class mySSLServerSocket extends SSLServerSocket {
-
- public mySSLServerSocket() throws IOException{
- super();
- }
-
- public mySSLServerSocket(int port) throws IOException{
- super(port);
- }
-
- public mySSLServerSocket(int port, int backlog) throws IOException{
- super(port, backlog);
- }
-
- public mySSLServerSocket(int port, int backlog, InetAddress address) throws IOException{
- super(port, backlog, address);
- }
-
- public String[] getSupportedCipherSuites() {
- return null;
- }
-
- public void setEnabledCipherSuites(String[] suites) {
-
- }
-
- public String[] getEnabledCipherSuites() {
- return null;
- }
-
- public String[] getSupportedProtocols() {
- return null;
- }
-
- public String[] getEnabledProtocols() {
- return null;
- }
-
- public void setEnabledProtocols(String[] protocols) {
-
- }
-
- public void setEnableSessionCreation(boolean flag) {
-
- }
-
- public boolean getEnableSessionCreation() {
- return false;
- }
-
- public void setNeedClientAuth(boolean need) {
-
- }
-
- public boolean getNeedClientAuth() {
- return false;
- }
-
- public boolean getUseClientMode() {
- return false;
- }
-
- public void setUseClientMode(boolean mode) {
-
- }
-
- public boolean getWantClientAuth() {
- return false;
- }
- public void setWantClientAuth(boolean mode) {
-
- }
- }
-
- /**
- * javax.net.ssl.SSLServerSocket#SSLServerSocket()
- */
- public void testConstructor() throws Exception {
- SSLServerSocket ssl = new mySSLServerSocket();
- }
-
- /**
- * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
- */
- public void testConstructor_I() throws Exception {
- int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE};
-
- SSLServerSocket ssl = new mySSLServerSocket(0);
-
- for (int i = 0; i < port_invalid.length; i++) {
- try {
- new mySSLServerSocket(port_invalid[i]);
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- new mySSLServerSocket(ssl.getLocalPort());
- fail("IOException Expected when opening an already opened port");
- } catch (IOException expected) {
- }
- }
-
- /**
- * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog)
- */
- public void testConstructor_II() throws Exception {
- mySSLServerSocket ssl = new mySSLServerSocket(0, 1);
- int[] port_invalid = {-1, Integer.MIN_VALUE, Integer.MAX_VALUE};
-
- for (int i = 0; i < port_invalid.length; i++) {
- try {
- new mySSLServerSocket(port_invalid[i], 1);
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- new mySSLServerSocket(ssl.getLocalPort(), 1);
- fail("IOException should be thrown");
- } catch (IOException expected) {
- }
- }
-
- /**
- * javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog, InetAddress address)
- */
- public void testConstructor_IIInetAddress() throws Exception {
- // A null InetAddress is okay.
- new mySSLServerSocket(0, 0, null);
-
- int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE};
-
- mySSLServerSocket ssl = new mySSLServerSocket(0, 0, InetAddress.getLocalHost());
-
- for (int i = 0; i < port_invalid.length; i++) {
- try {
- new mySSLServerSocket(port_invalid[i], 1, InetAddress.getLocalHost());
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- new mySSLServerSocket(ssl.getLocalPort(), 0, InetAddress.getLocalHost());
- fail("IOException should be thrown for");
- } catch (IOException expected) {
- }
- }
-
- /**
- * @throws Exception
- * javax.net.ssl.SSLServerSocket#getSupportedCipherSuites()
- */
- public void test_getSupportedCipherSuites() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- String[] res = sss.getSupportedCipherSuites();
- assertNotNull("NULL result", res);
- assertTrue("no supported cipher suites available.", res.length > 0);
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#getEnabledCipherSuites()
- * javax.net.ssl.SSLServerSocket#setEnabledCipherSuites(String[] suites)
- */
- public void test_EnabledCipherSuites() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- try {
- sss.setEnabledCipherSuites(null);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- String[] unsupportedCipherSuites = {"unsupported"};
- try {
- sss.setEnabledCipherSuites(unsupportedCipherSuites);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- int count = sss.getSupportedCipherSuites().length;
- assertTrue("No supported cipher suites", count > 0);
- sss.setEnabledCipherSuites(sss.getSupportedCipherSuites());
- String[] res = sss.getEnabledCipherSuites();
- assertNotNull("NULL result", res);
- assertEquals("not all supported cipher suites were enabled",
- Arrays.asList(sss.getSupportedCipherSuites()),
- Arrays.asList(res));
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#getSupportedProtocols()
- */
- public void test_getSupportedProtocols() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- String[] res = sss.getSupportedCipherSuites();
- assertNotNull("NULL result", res);
- assertTrue("no supported protocols available.", res.length > 0);
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#getEnabledProtocols()
- * javax.net.ssl.SSLServerSocket#setEnabledProtocols(String[] protocols)
- */
- public void test_EnabledProtocols() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- try {
- sss.setEnabledProtocols(null);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- String[] unsupportedProtocols = {"unsupported"};
- try {
- sss.setEnabledProtocols(unsupportedProtocols);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- int count = sss.getSupportedProtocols().length;
- assertTrue("No supported protocols", count > 0);
- sss.setEnabledProtocols(sss.getSupportedProtocols());
- String[] res = sss.getEnabledProtocols();
- assertNotNull("NULL result", res);
- assertTrue("no enabled protocols.", res.length == count);
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#setEnableSessionCreation(boolean flag)
- * javax.net.ssl.SSLServerSocket#getEnableSessionCreation()
- */
- public void test_EnableSessionCreation() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- assertTrue(sss.getEnableSessionCreation());
- sss.setEnableSessionCreation(false);
- assertFalse(sss.getEnableSessionCreation());
- sss.setEnableSessionCreation(true);
- assertTrue(sss.getEnableSessionCreation());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#setNeedClientAuth(boolean need)
- * javax.net.ssl.SSLServerSocket#getNeedClientAuthCreation()
- */
- public void test_NeedClientAuth() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- sss.setNeedClientAuth(true);
- assertTrue(sss.getNeedClientAuth());
- sss.setNeedClientAuth(false);
- assertFalse(sss.getNeedClientAuth());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#getUseClientMode()
- * javax.net.ssl.SSLServerSocket#setUseClientMode(boolean mode)
- */
- public void test_UseClientMode() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- sss.setUseClientMode(false);
- assertFalse(sss.getUseClientMode());
- sss.setUseClientMode(true);
- assertTrue(sss.getUseClientMode());
- }
-
- /**
- * @throws IOException
- * javax.net.ssl.SSLServerSocket#setWantClientAuth(boolean want)
- * javax.net.ssl.SSLServerSocket#getWantClientAuthCreation()
- */
- public void test_WantClientAuth() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- sss.setWantClientAuth(true);
- assertTrue(sss.getWantClientAuth());
- sss.setWantClientAuth(false);
- assertFalse(sss.getWantClientAuth());
- }
-
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
- "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
- "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
- "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
- "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
- "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
- "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
- "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
- "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
- "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
- "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
- "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
- "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
- "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
- "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
- "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
- "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
- "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
- "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
- "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
- "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
- "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
- "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
- "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
- "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
- "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
- "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
- "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
- "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
- "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
- "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
- "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
- "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
- "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
- "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
- "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
- "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
- "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
- "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
- "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
- "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
- "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- private String PASSWORD = "android";
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers() throws Exception {
- String keys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
- byte[] bytes = Base64.decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
-
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-
- private SSLServerSocket getSSLServerSocket() throws Exception {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(getKeyManagers(), null, null);
- SSLServerSocket sss = (SSLServerSocket) context.getServerSocketFactory()
- .createServerSocket();
- return sss;
- }
-
- public void test_creationStressTest() throws Exception {
- KeyManager[] keyManagers = getKeyManagers();
- // Test the default codepath, which uses /dev/urandom.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, null, null);
- for (int i = 0; i < 2048; ++i) {
- sslContext.getServerSocketFactory().createServerSocket().close();
- }
-
- // Test the other codepath, which copies a seed from a byte[].
- sslContext.init(keyManagers, null, new SecureRandom());
- for (int i = 0; i < 2048; ++i) {
- sslContext.getServerSocketFactory().createServerSocket().close();
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java
deleted file mode 100644
index dfccf68..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java
+++ /dev/null
@@ -1,236 +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 tests.api.javax.net.ssl;
-
-import java.security.Principal;
-import java.security.cert.Certificate;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.security.cert.X509Certificate;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>SSLSessionBindingEvent</code> class constructors and methods.
- *
- */
-public class SSLSessionBindingEventTest extends TestCase {
-
- public final void test_ConstructorLjavax_net_ssl_SSLSessionLjava_lang_String() {
- SSLSession ses = new MySSLSession();
-
- try {
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
- if (!"test".equals(event.getName())) {
- fail("incorrect name");
- }
- if (!event.getSession().equals(ses)) {
- fail("incorrect session");
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
-
- try {
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(null, "test");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, null);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException: " + e);
- }
- }
-
- /**
- * javax.net.ssl.SSLSessionBindingEvent#getName()
- */
- public void test_getName() {
- SSLSession ses = new MySSLSession();
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
- assertEquals("Incorrect session name", "test", event.getName());
- event = new SSLSessionBindingEvent(ses, null);
- assertEquals("Incorrect session name", null, event.getName());
- }
-
- /**
- * javax.net.ssl.SSLSessionBindingEvent#getSession()
- */
- public void test_getSession() {
- SSLSession ses = new MySSLSession();
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
- assertEquals("Incorrect session", ses, event.getSession());
- }
-}
-
-class MySSLSession implements SSLSession {
- /*
- * @see javax.net.ssl.SSLSession#getApplicationBufferSize()
- */
- public int getApplicationBufferSize() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getCipherSuite()
- */
- public String getCipherSuite() {
- return "MyTestCipherSuite";
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getCreationTime()
- */
- public long getCreationTime() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getId()
- */
- public byte[] getId() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getLastAccessedTime()
- */
- public long getLastAccessedTime() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getLocalCertificates()
- */
- public Certificate[] getLocalCertificates() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getLocalPrincipal()
- */
- public Principal getLocalPrincipal() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPacketBufferSize()
- */
- public int getPacketBufferSize() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerCertificateChain()
- */
- public X509Certificate[] getPeerCertificateChain()
- throws SSLPeerUnverifiedException {
- throw new SSLPeerUnverifiedException("test exception");
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerCertificates()
- */
- public Certificate[] getPeerCertificates()
- throws SSLPeerUnverifiedException {
- throw new SSLPeerUnverifiedException("test exception");
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerHost()
- */
- public String getPeerHost() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerPort()
- */
- public int getPeerPort() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerPrincipal()
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getProtocol()
- */
- public String getProtocol() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getSessionContext()
- */
- public SSLSessionContext getSessionContext() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getValue(java.lang.String)
- */
- public Object getValue(String name) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getValueNames()
- */
- public String[] getValueNames() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#invalidate()
- */
- public void invalidate() {
- }
-
- /*
- * @see javax.net.ssl.SSLSession#isValid()
- */
- public boolean isValid() {
- return false;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#putValue(java.lang.String,
- * java.lang.Object)
- */
- public void putValue(String name, Object value) {
- }
-
- /*
- * @see javax.net.ssl.SSLSession#removeValue(java.lang.String)
- */
- public void removeValue(String name) {
- }
-
-}
-
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java
deleted file mode 100644
index a006a83..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java
+++ /dev/null
@@ -1,85 +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 tests.api.javax.net.ssl;
-
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-
-import java.io.IOException;
-import java.net.UnknownHostException;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLSessionBindingListener class
- *
- */
-public class SSLSessionBindingListenerTest extends TestCase {
-
- public class mySSLSessionBindingListener implements SSLSessionBindingListener {
-
- public boolean boundDone = false;
- public boolean unboundDone = false;
-
- mySSLSessionBindingListener() {
- }
-
- public void valueBound(SSLSessionBindingEvent event) {
- if (event != null) boundDone = true;
- }
- public void valueUnbound(SSLSessionBindingEvent event) {
- if (event != null) unboundDone = true;
- }
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @throws InterruptedException
- * javax.net.ssl.SSLSessionBindingListener#valueBound(SSLSessionBindingEvent event)
- */
- public void test_valueBound() throws UnknownHostException, IOException,
- InterruptedException {
- SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault()
- .createSocket();
- SSLSession ss = sock.getSession();
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
- ss.putValue("test", sbl);
- assertTrue("valueBound was not called.", sbl.boundDone);
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * javax.net.ssl.SSLSessionBindingListener#valueUnbound(SSLSessionBindingEvent event)
- */
- public void test_valueUnbound() throws UnknownHostException, IOException {
- SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault()
- .createSocket();
- SSLSession ss = sock.getSession();
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
- ss.putValue("test", sbl);
- ss.removeValue("test");
- assertTrue("valueUnbound was not called.", sbl.unboundDone);
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java
deleted file mode 100644
index aa95eb8..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package tests.api.javax.net.ssl;
-
-import junit.framework.TestCase;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSessionContext;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Tests for <code>SSLSessionContext</code> class constructors and methods.
- */
-public class SSLSessionContextTest extends TestCase {
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * javax.net.ssl.SSLSessionContex#getSessionCacheSize()
- * javax.net.ssl.SSLSessionContex#setSessionCacheSize(int size)
- */
- public final void test_sessionCacheSize() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- sc.setSessionCacheSize(10);
- assertEquals("10 wasn't returned", 10, sc.getSessionCacheSize());
- sc.setSessionCacheSize(5);
- assertEquals("5 wasn't returned", 5, sc.getSessionCacheSize());
-
- try {
- sc.setSessionCacheSize(-1);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * javax.net.ssl.SSLSessionContex#getSessionTimeout()
- * javax.net.ssl.SSLSessionContex#setSessionTimeout(int seconds)
- */
- public final void test_sessionTimeout() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- sc.setSessionTimeout(100);
- assertEquals("100 wasn't returned", 100, sc.getSessionTimeout());
- sc.setSessionTimeout(5000);
- assertEquals("5000 wasn't returned", 5000, sc.getSessionTimeout());
-
- try {
- sc.setSessionTimeout(-1);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * javax.net.ssl.SSLSessionContex#getSession(byte[] sessionId)
- */
- public final void test_getSession() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- try {
- sc.getSession(null);
- } catch (NullPointerException e) {
- // expected
- }
- assertNull(sc.getSession(new byte[5]));
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * javax.net.ssl.SSLSessionContex#getIds()
- */
- public final void test_getIds() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- assertFalse(sc.getIds().hasMoreElements());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java
deleted file mode 100644
index 5084422..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java
+++ /dev/null
@@ -1,641 +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 tests.api.javax.net.ssl;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.security.KeyStore;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.TrustManager;
-import junit.framework.TestCase;
-import libcore.io.Base64;
-import tests.api.javax.net.ssl.HandshakeCompletedEventTest.MyHandshakeListener;
-import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
-
-public class SSLSessionTest extends TestCase {
-
- // set to true if on Android, false if on RI
- boolean useBKS = true;
-
- /**
- * javax.net.ssl.SSLSession#getPeerHost()
- * javax.net.ssl.SSLSession#getPeerPort()
- */
- public void test_getPeerHost() throws Exception {
- SSLSession s = clientSession;
- assertEquals(InetAddress.getLocalHost().getHostName(), s.getPeerHost());
- assertEquals(serverSocket.getLocalPort(), s.getPeerPort());
- }
-
- /**
- * javax.net.ssl.SSLSession#invalidate()
- * javax.net.ssl.SSLSession#isValid()
- */
- public void test_invalidate() {
- SSLSession s = clientSession;
- assertTrue(s.isValid());
- s.invalidate();
- assertFalse(s.isValid());
- }
-
- /**
- * javax.net.ssl.SSLSession#getPeerPrincipal()
- */
- public void test_getPeerPrincipal() throws Exception {
- Principal p1 = clientSession.getPeerPrincipal();
- KeyStore store = server.getStore();
- X509Certificate cert = (X509Certificate)store.getCertificate("mykey");
- Principal p2 = cert.getSubjectX500Principal();
- assertEquals(p1, p2);
- }
-
- /**
- * javax.net.ssl.SSLSession#getApplicationBufferSize()
- */
- public void test_getApplicationBufferSize() {
- assertTrue(clientSession.getApplicationBufferSize() > 0);
- }
-
- /**
- * javax.net.ssl.SSLSession#getCipherSuite()
- */
- public void test_getCipherSuite() {
- assertEquals(CIPHER_SUITE, clientSession.getCipherSuite());
- }
-
- /**
- * javax.net.ssl.SSLSession#getCreationTime()
- */
- public void test_getCreationTime() {
- // check if creation time was in the last 10 seconds
- long currentTime = System.currentTimeMillis();
- long sessionTime = clientSession.getCreationTime();
- long diff = currentTime - sessionTime;
- assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000",
- diff < 10000);
- }
-
- /**
- * javax.net.ssl.SSLSession#getId()
- */
- public void test_getId() {
- byte[] id = clientSession.getId();
- SSLSession sess = clientSslContext.getClientSessionContext().getSession(id);
- assertNotNull("Could not find session for id " + id, sess);
- assertEquals(clientSession, sess);
- }
-
- /**
- * javax.net.ssl.SSLSession#getLastAccessedTime()
- */
- public void test_getLastAccessedTime() {
- // check if last access time was in the last 10 seconds
- long currentTime = System.currentTimeMillis();
- long sessionTime = clientSession.getLastAccessedTime();
- long diff = currentTime - sessionTime;
- assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000",
- diff < 10000);
- assertTrue ("diff should be < 10000 but is " + diff, diff < 10000);
- }
-
- /**
- * javax.net.ssl.SSLSession#getLocalCertificates()
- */
- public void test_getLocalCertificates() throws Exception {
- KeyStore store = client.getStore();
- Certificate cert = store.getCertificate("mykey");
- Certificate[] certs = clientSession.getLocalCertificates();
- assertEquals(cert, certs[0]);
- }
-
- /**
- * javax.net.ssl.SSLSession#getLocalPrincipal()
- */
- public void test_getLocalPrincipal() throws Exception {
- Principal p1 = clientSession.getLocalPrincipal();
- KeyStore store = client.getStore();
- X509Certificate cert = (X509Certificate)store.getCertificate("mykey");
- Principal p2 = cert.getSubjectX500Principal();
- assertEquals(p1, p2);
- }
-
- /**
- * javax.net.ssl.SSLSession#getPacketBufferSize()
- */
- public void test_getPacketBufferSize() {
- assertTrue(clientSession.getPacketBufferSize() > 0);
- }
-
- /**
- * javax.net.ssl.SSLSession#getPeerCertificates()
- */
- public void test_getPeerCertificates() throws Exception {
- Certificate[] res = clientSession.getPeerCertificates();
- assertTrue(res.length > 0);
- }
-
- /**
- * javax.net.ssl.SSLSession#getPeerCertificateChain()
- */
- public void test_getPeerCertificateChain() throws Exception {
- javax.security.cert.X509Certificate[] res = clientSession.getPeerCertificateChain();
- assertTrue(res.length > 0);
- }
-
- /**
- * javax.net.ssl.SSLSession#getProtocol()
- */
- public void test_getProtocol() {
- assertEquals("TLSv1", clientSession.getProtocol());
- }
-
- /**
- * javax.net.ssl.SSLSession#getSessionContext()
- */
- public void test_getSessionContext() {
- assertEquals(clientSession.getSessionContext(),
- clientSslContext.getClientSessionContext());
- }
-
- /**
- * javax.net.ssl.SSLSession#putValue(String name, Object value)
- * javax.net.ssl.SSLSession#removeValue(String name)
- * javax.net.ssl.SSLSession#getValueNames()
- */
- public void test_putValue() {
- SSLSession s = clientSession;
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
- assertNotNull(s.getValueNames());
- assertEquals(0, s.getValueNames().length);
- s.putValue("Name_01", sbl);
- s.putValue("Name_02", sbl);
- s.putValue("Name_03", sbl);
- assertEquals(3, s.getValueNames().length);
- s.removeValue("Name_01");
- assertEquals(2, s.getValueNames().length);
-
- try {
- s.putValue(null, null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- // expected
- }
- try {
- s.putValue("ABC", null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- // expected
- }
- try {
- s.putValue(null, sbl);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- // expected
- }
-
- try {
- s.removeValue(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- // expected
- }
- }
-
- /**
- * javax.net.ssl.SSLSession#getValue(String name)
- */
- public void test_getValue() {
- SSLSession s = clientSession;
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
-
- try {
- s.getValue(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- // expected
- }
-
- s.putValue("Name", sbl);
- Object obj = s.getValue("Name");
- assertTrue(obj instanceof SSLSessionBindingListener);
- }
-
- Thread serverThread, clientThread;
- TestServer server;
- TestClient client;
-
- @Override
- protected void setUp() throws Exception {
- String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
- String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS);
- server = new TestServer(true, TestServer.CLIENT_AUTH_WANTED, serverKeys);
- client = new TestClient(true, clientKeys);
-
- serverThread = new Thread(server);
- clientThread = new Thread(client);
-
- serverThread.start();
- try {
- Thread.currentThread().sleep(1000);
- clientThread.start();
- } catch (InterruptedException e) {
- fail("Could not create server or cient " + e.getMessage());
- }
- while (clientSession == null
- && server.exception == null
- && client.exception == null) {
- try {
- Thread.currentThread().sleep(500);
- } catch (InterruptedException e) {
- fail("couldn't create session");
- }
- }
- if (server.exception != null) {
- server.exception.printStackTrace();
- }
- assertNull("server thread has a pending exception: " + server.exception,
- server.exception);
- if (client.exception != null) {
- client.exception.printStackTrace();
- }
- assertNull("client thread has a pending exception: " + client.exception,
- client.exception);
- assertNotNull("Could not initialize session", clientSession);
- }
-
- @Override
- protected void tearDown() {
- notFinished = false;
- try {
- serverThread.join();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- try {
- clientThread.join();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
- // The server must have completed without an exception.
- if (server.getException() != null) {
- throw new RuntimeException(server.getException());
- }
-
- // The client must have completed without an exception.
- if (client.getException() != null) {
- throw new RuntimeException(client.getException());
- }
- }
-
- public class mySSLSessionBindingListener implements
- SSLSessionBindingListener {
- mySSLSessionBindingListener() {
- }
- public void valueBound(SSLSessionBindingEvent event) {}
- public void valueUnbound(SSLSessionBindingEvent event) {}
- }
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
- + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
- + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
- + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
- + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
- + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
- + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
- + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
- + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
- + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
- + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
- + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
- + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
- + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
- + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
- + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
- + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
- + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
- + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
- + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
- + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
- + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
- + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
- + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the client, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_BKS =
- "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41"
- + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
- + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
- + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw"
- + "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
- + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu"
- + "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva"
- + "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD"
- + "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG"
- + "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F"
- + "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg"
- + "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx"
- + "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi"
- + "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD"
- + "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO"
- + "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz"
- + "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5"
- + "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8"
- + "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1"
- + "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9"
- + "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB"
- + "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9"
- + "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef"
- + "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";
-
- private static final String CIPHER_SUITE = "SSL_RSA_WITH_RC4_128_MD5";
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
- + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
- + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
- + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
- + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
- + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
- + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
- + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
- + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
- + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
- + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
- + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
- + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
- + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
- + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
- + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
- + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
- + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
- + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
- + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
- + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
- + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
- + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
- + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- /**
- * Defines the keystore contents for the client, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC"
- + "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5"
- + "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw"
- + "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY"
- + "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4"
- + "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit"
- + "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY"
- + "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O"
- + "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS"
- + "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4"
- + "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi"
- + "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL"
- + "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41"
- + "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV"
- + "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB"
- + "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5"
- + "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN"
- + "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w"
- + "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR"
- + "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5"
- + "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE"
- + "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng"
- + "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp"
- + "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
-
-
- SSLServerSocket serverSocket;
- MyHandshakeListener listener;
- String host = "localhost";
- boolean notFinished = true;
- SSLSession clientSession = null;
- SSLContext clientSslContext = null;
- String testData = "PING";
-
- private String PASSWORD = "android";
-
- /**
- * Implements a test SSL socket server. It waits for a connection on a given
- * port, requests client authentication (if specified), reads from the socket,
- * and writes to the socket.
- */
- class TestServer implements Runnable {
-
- public static final int CLIENT_AUTH_NONE = 0;
-
- public static final int CLIENT_AUTH_WANTED = 1;
-
- public static final int CLIENT_AUTH_NEEDED = 2;
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- String keys;
-
- private int clientAuth;
-
- private boolean provideKeys;
-
- private KeyStore store;
-
- public TestServer(boolean provideKeys, int clientAuth, String keys) throws Exception {
- this.keys = keys;
- this.clientAuth = clientAuth;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
-
- store = provideKeys ? getKeyStore(keys) : null;
- KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket();
-
- if (clientAuth == CLIENT_AUTH_WANTED) {
- serverSocket.setWantClientAuth(true);
- } else if (clientAuth == CLIENT_AUTH_NEEDED) {
- serverSocket.setNeedClientAuth(true);
- } else {
- serverSocket.setWantClientAuth(false);
- }
-
- serverSocket.bind(null);
- }
-
- public void run() {
- try {
- SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
-
- InputStream istream = clientSocket.getInputStream();
- byte[] buffer = new byte[1024];
- istream.read(buffer);
-
- OutputStream ostream = clientSocket.getOutputStream();
- ostream.write(testData.getBytes());
- ostream.flush();
-
- while (notFinished) {
- Thread.currentThread().sleep(500);
- }
-
- clientSocket.close();
- serverSocket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public javax.security.cert.X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- public KeyStore getStore() {
- return store;
- }
-
- }
-
- /**
- * Implements a test SSL socket client. It opens a connection to localhost on
- * a given port, writes to the socket, and reads from the socket.
- */
- class TestClient implements Runnable {
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- private String keys;
-
- private boolean provideKeys;
-
- private KeyStore store;
-
- public TestClient(boolean provideKeys, String keys) {
- this.keys = keys;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- store = provideKeys ? getKeyStore(keys) : null;
- KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- clientSslContext = SSLContext.getInstance("TLS");
- clientSslContext.init(keyManagers, trustManagers, null);
-
- SSLSocket socket = (SSLSocket)clientSslContext.getSocketFactory().createSocket();
-
- socket.connect(serverSocket.getLocalSocketAddress());
- OutputStream ostream = socket.getOutputStream();
- ostream.write(testData.getBytes());
- ostream.flush();
-
- InputStream istream = socket.getInputStream();
- byte[] buffer = new byte[1024];
- istream.read(buffer);
-
- clientSession = socket.getSession();
- while (notFinished) {
- Thread.currentThread().sleep(500);
- }
- socket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public javax.security.cert.X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- public KeyStore getStore() {
- return store;
- }
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyStore getKeyStore(String keys) throws Exception {
- byte[] bytes = Base64.decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
- return keyStore;
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java
deleted file mode 100644
index 0d91116..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-import javax.net.SocketFactory;
-import javax.net.ssl.SSLSocketFactory;
-
-import junit.framework.TestCase;
-
-public class SSLSocketFactoryTest extends TestCase {
-
- private ServerSocket ss;
-
- protected int startServer(String name) {
- try {
- ss = new ServerSocket(0);
- } catch (IOException e) {
- fail(name + ": " + e);
- }
- return ss.getLocalPort();
- }
-
- /**
- * javax.net.ssl.SSLSocketFactory#SSLSocketFactory()
- */
- public void test_Constructor() {
- try {
- SocketFactory sf = SSLSocketFactory.getDefault();
- assertTrue(sf instanceof SSLSocketFactory);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.net.ssl.SSLSocketFactory#getDefault()
- */
- public void test_getDefault() {
- assertNotNull("Incorrect default socket factory",
- SSLSocketFactory.getDefault());
- }
-
- /**
- * javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
- */
- public void test_createSocket() {
- SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault();
- int sport = startServer("test_createSocket()");
- int[] invalid = {
- Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE
- };
- try {
- Socket st = new Socket("localhost", sport);
- Socket s = sf.createSocket(st, "localhost", sport, false);
- assertFalse(s.isClosed());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- Socket st = new Socket("localhost", sport);
- Socket s = sf.createSocket(st, "localhost", sport, true);
- s.close();
- assertTrue(st.isClosed());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- sf.createSocket(null, "localhost", sport, true);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- // expected
- } catch (NullPointerException e) {
- // expected
- }
- for (int i = 0; i < invalid.length; i++) {
- try {
- Socket s = sf.createSocket(new Socket(), "localhost", 1080, false);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- // expected
- }
- }
-
- try {
- Socket st = new Socket("bla-bla", sport);
- Socket s = sf.createSocket(st, "bla-bla", sport, false);
- fail("UnknownHostException wasn't thrown: " + "bla-bla");
- } catch (UnknownHostException uhe) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnknownHostException");
- }
- }
-
- /**
- * javax.net.ssl.SSLSocketFactory#getDefaultCipherSuites()
- */
- public void test_getDefaultCipherSuites() {
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- assertTrue("no default cipher suites returned",
- sf.getDefaultCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.net.ssl.SSLSocketFactory#getSupportedCipherSuites()
- */
- public void test_getSupportedCipherSuites() {
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- assertTrue("no supported cipher suites returned",
- sf.getSupportedCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java
deleted file mode 100644
index b4cbde2..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java
+++ /dev/null
@@ -1,631 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import dalvik.annotation.AndroidOnly;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.util.Arrays;
-import javax.net.ssl.HandshakeCompletedEvent;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.security.cert.X509Certificate;
-import junit.framework.TestCase;
-import libcore.io.Base64;
-import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
-import libcore.java.security.StandardNames;
-
-public class SSLSocketTest extends TestCase {
-
- public class HandshakeCL implements HandshakeCompletedListener {
- public void handshakeCompleted(HandshakeCompletedEvent event) {
- }
- }
-
- /**
- * javax.net.ssl.SSLSocket#SSLSocket()
- */
- public void testConstructor() throws Exception {
- SSLSocket ssl = getSSLSocket();
- assertNotNull(ssl);
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port)
- */
- public void testConstructor_InetAddressI() throws Exception {
- int sport = startServer("Cons InetAddress,I");
- int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
-
- SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
- ssl.close();
-
- try {
- getSSLSocket(InetAddress.getLocalHost(), sport + 1);
- fail();
- } catch (IOException expected) {
- }
-
- for (int i = 0; i < invalidPort.length; i++) {
- try {
- getSSLSocket(InetAddress.getLocalHost(), invalidPort[i]);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
- }
-
- /**
- * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port,
- * InetAddress clientAddress, int clientPort)
- */
- public void testConstructor_InetAddressIInetAddressI() throws Exception {
- int sport = startServer("Cons InetAddress,I,InetAddress,I");
-
- SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), 0);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
- ssl.close();
-
- try {
- getSSLSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
- fail();
- } catch (IOException expected) {
- }
-
- try {
- getSSLSocket(InetAddress.getLocalHost(), -1, InetAddress.getLocalHost(), sport + 1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- try {
- getSSLSocket(InetAddress.getLocalHost(), sport, InetAddress.getLocalHost(), -1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- try {
- getSSLSocket(InetAddress.getLocalHost(), Integer.MIN_VALUE,
- InetAddress.getLocalHost(), sport + 1);
- fail();
- } catch (IOException expectedOnRI) {
- assertTrue(StandardNames.IS_RI);
- } catch (IllegalArgumentException expectedOnAndroid) {
- assertFalse(StandardNames.IS_RI);
- }
- try {
- getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), Integer.MAX_VALUE);
- fail();
- } catch (IllegalArgumentException expectedOnAndroid) {
- assertFalse(StandardNames.IS_RI);
- }
- }
-
- /**
- * javax.net.ssl.SSLSocket#SSLSocket(String host, int port)
- */
- public void testConstructor_StringI() throws Exception {
- int sport = startServer("Cons String,I");
- int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
-
- SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
- ssl.close();
-
- try {
- getSSLSocket("localhost", 8082);
- fail();
- } catch (IOException expected) {
- }
-
- for (int i = 0; i < invalidPort.length; i++) {
- try {
- getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i]);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- getSSLSocket("bla-bla", sport);
- fail();
- } catch (UnknownHostException expected) {
- }
- }
-
- /**
- * javax.net.ssl.SSLSocket#SSLSocket(String host, int port, InetAddress clientAddress,
- * int clientPort)
- */
- public void testConstructor_StringIInetAddressI() throws Exception {
- int sport = startServer("Cons String,I,InetAddress,I");
- int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
-
- SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), 0);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
-
- try {
- getSSLSocket(InetAddress.getLocalHost().getHostName(), 8081, InetAddress.getLocalHost(), 8082);
- fail();
- } catch (IOException expected) {
- }
-
- for (int i = 0; i < invalidPort.length; i++) {
- try {
- getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i],
- InetAddress.getLocalHost(), 0);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- try {
- getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), invalidPort[i]);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
-
- try {
- getSSLSocket("bla-bla", sport, InetAddress.getLocalHost(), 0);
- fail();
- } catch (UnknownHostException expected) {
- }
- }
-
- public void test_creationStressTest() throws Exception {
- // Test the default codepath, which uses /dev/urandom.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(null, null, null);
- for (int i = 0; i < 2048; ++i) {
- sslContext.getSocketFactory().createSocket().close();
- }
-
- // Test the other codepath, which copies a seed from a byte[].
- sslContext.init(null, null, new SecureRandom());
- for (int i = 0; i < 2048; ++i) {
- sslContext.getSocketFactory().createSocket().close();
- }
- }
-
- /**
- * javax.net.ssl.SSLSocket#addHandshakeCompletedListener(HandshakeCompletedListener listener)
- */
- @AndroidOnly("RI doesn't throw the specified IAE")
- public void test_addHandshakeCompletedListener() throws IOException {
- SSLSocket ssl = getSSLSocket();
- HandshakeCompletedListener ls = new HandshakeCL();
- try {
- ssl.addHandshakeCompletedListener(null);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- ssl.addHandshakeCompletedListener(ls);
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener)
- */
- public void test_removeHandshakeCompletedListener() throws IOException {
- SSLSocket ssl = getSSLSocket();
- HandshakeCompletedListener ls = new HandshakeCL();
- try {
- ssl.removeHandshakeCompletedListener(null);
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- try {
- ssl.removeHandshakeCompletedListener(ls);
- } catch (IllegalArgumentException expected) {
- }
-
- ssl.addHandshakeCompletedListener(ls);
- ssl.removeHandshakeCompletedListener(ls);
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#setEnableSessionCreation(boolean flag)
- * javax.net.ssl.SSLSocket#getEnableSessionCreation()
- */
- public void test_EnableSessionCreation() throws IOException {
- SSLSocket ssl = getSSLSocket();
- assertTrue(ssl.getEnableSessionCreation());
- ssl.setEnableSessionCreation(false);
- assertFalse(ssl.getEnableSessionCreation());
- ssl.setEnableSessionCreation(true);
- assertTrue(ssl.getEnableSessionCreation());
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#setNeedClientAuth(boolean need)
- * javax.net.ssl.SSLSocket#getNeedClientAuthCreation()
- */
- public void test_NeedClientAuth() throws UnknownHostException, IOException {
- SSLSocket ssl = getSSLSocket();
- ssl.setNeedClientAuth(true);
- assertTrue(ssl.getNeedClientAuth());
- ssl.setNeedClientAuth(false);
- assertFalse(ssl.getNeedClientAuth());
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#setWantClientAuth(boolean want)
- * javax.net.ssl.SSLSocket#getWantClientAuthCreation()
- */
- public void test_WantClientAuth() throws UnknownHostException, IOException {
- SSLSocket ssl = getSSLSocket();
- ssl.setWantClientAuth(true);
- assertTrue(ssl.getWantClientAuth());
- ssl.setWantClientAuth(false);
- assertFalse(ssl.getWantClientAuth());
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#getSupportedProtocols()
- */
- public void test_getSupportedProtocols() throws IOException {
- SSLSocket ssl = getSSLSocket();
- String[] res = ssl.getSupportedProtocols();
- assertTrue("No supported protocols found", res.length > 0);
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#getEnabledProtocols()
- * javax.net.ssl.SSLSocket#setEnabledProtocols(String[] protocols)
- */
- public void test_EnabledProtocols() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- ssl.setEnabledProtocols(null);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- ssl.setEnabledProtocols(new String[] {});
- try {
- ssl.setEnabledProtocols(new String[] {"blubb"});
- fail();
- } catch (IllegalArgumentException expected) {
- }
- ssl.setEnabledProtocols(ssl.getEnabledProtocols());
- String[] res = ssl.getEnabledProtocols();
- assertEquals("no enabled protocols set",
- ssl.getEnabledProtocols().length, res.length);
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#getSession()
- */
- public void test_getSession() throws IOException {
- SSLSocket ssl = getSSLSocket();
- assertNotNull(ssl.getSession());
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#getSupportedCipherSuites()
- */
- public void test_getSupportedCipherSuites() throws IOException {
- SSLSocket ssl = getSSLSocket();
- String[] res = ssl.getSupportedCipherSuites();
- assertTrue("no supported cipher suites", res.length > 0);
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#getEnabledCipherSuites()
- * javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[] suites)
- */
- public void test_EnabledCipherSuites() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- ssl.setEnabledCipherSuites(null);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- ssl.setEnabledCipherSuites(new String[] {});
- try {
- ssl.setEnabledCipherSuites(new String[] {"blubb"});
- fail();
- } catch (IllegalArgumentException expected) {
- }
- ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
- String[] res = ssl.getEnabledCipherSuites();
- assertNotNull("NULL result", res);
- assertEquals("not all supported cipher suites were enabled",
- Arrays.asList(ssl.getSupportedCipherSuites()),
- Arrays.asList(res));
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#getUseClientMode()
- * javax.net.ssl.SSLSocket#setUseClientMode(boolean mode)
- */
- public void test_UseClientMode() throws IOException {
- SSLSocket ssl = getSSLSocket();
- assertTrue(ssl.getUseClientMode());
- ssl.setUseClientMode(false);
- assertFalse(ssl.getUseClientMode());
- ssl.close();
-
- ssl = getSSLSocket("localhost", startServer("UseClientMode"));
- try {
- ssl.startHandshake();
- } catch (IOException ioe) {
- //fail(ioe + " was thrown for method startHandshake()");
- }
- try {
- ssl.setUseClientMode(false);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- ssl.close();
- }
-
- /**
- * javax.net.ssl.SSLSocket#startHandshake()
- */
- public void test_startHandshake() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- ssl.startHandshake();
- fail();
- } catch (IOException expected) {
- }
- ssl.close();
- }
-
- private boolean useBKS = !StandardNames.IS_RI;
-
- private String PASSWORD = "android";
-
- private boolean serverReady = false;
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS = ""
- + "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
- + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
- + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
- + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
- + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
- + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
- + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
- + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
- + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
- + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
- + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
- + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
- + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
- + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
- + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
- + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
- + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
- + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
- + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
- + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
- + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
- + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
- + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
- + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS = ""
- + "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
- + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
- + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
- + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
- + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
- + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
- + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
- + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
- + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
- + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
- + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
- + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
- + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
- + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
- + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
- + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
- + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
- + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
- + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
- + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
- + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
- + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
- + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
- + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- protected int startServer(String name) {
- String keys = useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS;
- TestServer server = new TestServer(true, keys);
- Thread serverThread = new Thread(server);
- serverThread.start();
- try {
- while (!serverReady) {
- Exception e = server.getException();
- if (e != null) {
- throw new AssertionError(e);
- }
- Thread.currentThread().sleep(50);
- }
- // give the server 100 millis to accept
- Thread.currentThread().sleep(100);
- } catch (InterruptedException ignore) {
- }
- return server.sport;
- }
-
- /**
- * Implements a test SSL socket server. It wait for a connection on a given
- * port, requests client authentication (if specified), and read 256 bytes
- * from the socket.
- */
- class TestServer implements Runnable {
-
- public static final int CLIENT_AUTH_NONE = 0;
-
- public static final int CLIENT_AUTH_WANTED = 1;
-
- public static final int CLIENT_AUTH_NEEDED = 2;
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- String keys;
-
- private boolean provideKeys;
-
- int sport;
-
- public TestServer(boolean provideKeys, String keys) {
- this.keys = keys;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- SSLServerSocket serverSocket = (SSLServerSocket)
- sslContext.getServerSocketFactory().createServerSocket();
- try {
- serverSocket.bind(new InetSocketAddress(0));
- sport = serverSocket.getLocalPort();
- serverReady = true;
-
- SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
-
- try {
- InputStream stream = clientSocket.getInputStream();
- try {
- for (int i = 0; i < 256; i++) {
- int j = stream.read();
- if (i != j) {
- throw new RuntimeException("Error reading socket, expected " + i
- + ", got " + j);
- }
- }
- } finally {
- stream.close();
- }
- } finally {
- clientSocket.close();
- }
- } finally {
- serverSocket.close();
- }
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers(String keys) throws Exception {
- byte[] bytes = Base64.decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
-
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-
- private SSLSocket getSSLSocket() throws IOException {
- return (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- }
-
- private SSLSocket getSSLSocket(InetAddress host, int port) throws IOException {
- return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
- }
-
- private SSLSocket getSSLSocket(String host, int port) throws UnknownHostException, IOException {
- return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
- }
-
- private SSLSocket getSSLSocket(InetAddress host, int port, InetAddress localHost, int localPort)
- throws IOException {
- return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,
- port,
- localHost,
- localPort);
- }
-
- private SSLSocket getSSLSocket(String host, int port, InetAddress localHost, int localPort)
- throws UnknownHostException, IOException {
- return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,
- port,
- localHost,
- localPort);
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java b/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java
deleted file mode 100644
index 23b24e4..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java
+++ /dev/null
@@ -1,519 +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 tests.api.javax.net.ssl;
-
-import dalvik.annotation.KnownFailure;
-import java.io.IOException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.PublicKey;
-import java.security.Security;
-import java.security.cert.CertificateException;
-import java.security.cert.PKIXBuilderParameters;
-import java.security.cert.TrustAnchor;
-import java.security.cert.X509CertSelector;
-import java.util.HashSet;
-import java.util.Set;
-import javax.net.ssl.CertPathTrustManagerParameters;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.TrustManagerFactorySpi;
-import junit.framework.TestCase;
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.security.tests.support.TestKeyPair;
-import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi;
-
-/**
- * Tests for <code>TrustManagerFactory</code> class constructors and methods.
- *
- */
-public class TrustManagerFactory1Test extends TestCase {
-
- private static final String srvTrustManagerFactory = "TrustManagerFactory";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static String DEFAULT_ALGORITHM;
- private static String DEFAULT_PROVIDER_NAME;
- private static Provider DEFAULT_PROVIDER;
- private static String[] VALID_VALUES;
-
- private static String getDefaultAlgorithm() {
- init();
- return DEFAULT_ALGORITHM;
- }
- private static String getDefaultProviderName() {
- init();
- return DEFAULT_PROVIDER_NAME;
- }
- private static Provider getDefaultProvider() {
- init();
- return DEFAULT_PROVIDER;
- }
- private static String[] getValidValues() {
- init();
- return VALID_VALUES;
- }
-
- private static synchronized void init() {
- if (DEFAULT_ALGORITHM != null) {
- return;
- }
- DEFAULT_ALGORITHM = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- assertNotNull(DEFAULT_ALGORITHM);
- DEFAULT_PROVIDER = SpiEngUtils.isSupport(DEFAULT_ALGORITHM, srvTrustManagerFactory);
- DEFAULT_PROVIDER_NAME = DEFAULT_PROVIDER.getName();
- VALID_VALUES = new String[] { DEFAULT_ALGORITHM,
- DEFAULT_ALGORITHM.toUpperCase(),
- DEFAULT_ALGORITHM.toLowerCase() };
- }
-
- private static TrustManagerFactory[] createTMFac() throws Exception {
- return new TrustManagerFactory[] {
- TrustManagerFactory.getInstance(getDefaultAlgorithm()),
- TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider()),
- TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProviderName())
- };
- }
-
- public void test_ConstructorLjavax_net_ssl_TrustManagerFactorySpiLjava_security_ProviderLjava_lang_String()
- throws NoSuchAlgorithmException {
- TrustManagerFactorySpi spi = new MyTrustManagerFactorySpi();
- TrustManagerFactory tmF = new myTrustManagerFactory(spi, getDefaultProvider(),
- getDefaultAlgorithm());
- assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmF.getAlgorithm(),
- getDefaultAlgorithm());
- assertEquals("Incorrect provider", tmF.getProvider(), getDefaultProvider());
- assertNull("Incorrect result", tmF.getTrustManagers());
-
- tmF = new myTrustManagerFactory(null, null, null);
- assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory);
- assertNull("Provider must be null", tmF.getProvider());
- assertNull("Algorithm must be null", tmF.getAlgorithm());
- try {
- tmF.getTrustManagers();
- fail("NullPointerException must be thrown");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * Test for <code>getAlgorithm()</code> method
- * Assertion: returns the algorithm name of this object
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- */
- public void test_getAlgorithm()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- assertEquals("Incorrect algorithm",
- getDefaultAlgorithm(),
- TrustManagerFactory
- .getInstance(getDefaultAlgorithm()).getAlgorithm());
- assertEquals("Incorrect algorithm",
- getDefaultAlgorithm(),
- TrustManagerFactory
- .getInstance(getDefaultAlgorithm(), getDefaultProviderName())
- .getAlgorithm());
- assertEquals("Incorrect algorithm",
- getDefaultAlgorithm(),
- TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider())
- .getAlgorithm());
- }
-
- /**
- * Test for <code>getDefaultAlgorithm()</code> method
- * Assertion: returns value which is specifoed in security property
- */
- public void test_getDefaultAlgorithm() {
- String def = TrustManagerFactory.getDefaultAlgorithm();
- if (getDefaultAlgorithm() == null) {
- assertNull("DefaultAlgorithm must be null", def);
- } else {
- assertEquals("Invalid default algorithm", def, getDefaultAlgorithm());
- }
- String defA = "Proba.trustmanagerfactory.defaul.type";
- Security.setProperty("ssl.TrustManagerFactory.algorithm", defA);
- assertEquals("Incorrect getDefaultAlgorithm()",
- TrustManagerFactory.getDefaultAlgorithm(), defA);
- if (def == null) {
- def = "";
- }
- Security.setProperty("ssl.TrustManagerFactory.algorithm", def);
- assertEquals("Incorrect getDefaultAlgorithm()",
- TrustManagerFactory.getDefaultAlgorithm(), def);
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions: returns security property "ssl.TrustManagerFactory.algorithm";
- * returns instance of TrustManagerFactory
- */
- public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
- for (String validValue : getValidValues()) {
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue);
- assertTrue("Not TrustManagerFactory object",
- trustMF instanceof TrustManagerFactory);
- assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- public void test_getInstanceLjava_lang_String02() {
- try {
- TrustManagerFactory.getInstance(null);
- fail();
- } catch (NoSuchAlgorithmException expected) {
- } catch (NullPointerException expected) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
- .concat(invalidValues[i]));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null
- * or empty
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws Exception {
- for (String validValue : getValidValues()) {
- try {
- TrustManagerFactory.getInstance(validValue, (String) null);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- try {
- TrustManagerFactory.getInstance(validValue, "");
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws Exception {
- try {
- TrustManagerFactory.getInstance(null, getDefaultProviderName());
- fail();
- } catch (NoSuchAlgorithmException expected) {
- } catch (NullPointerException expected) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i],
- getDefaultProviderName());
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws NoSuchProviderException when provider has
- * invalid value
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws Exception {
- for (String invalidValue : invalidValues) {
- for (String validValue : getValidValues()) {
- try {
- TrustManagerFactory.getInstance(validValue, invalidValue);
- fail("NoSuchProviderException must be thrown (algorithm: "
- .concat(validValue).concat(" provider: ")
- .concat(invalidValue).concat(")"));
- } catch (NoSuchProviderException expected) {
- assertFalse("".equals(invalidValue));
- } catch (IllegalArgumentException expected) {
- assertEquals("", invalidValue);
- }
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: returns instance of TrustManagerFactory
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws Exception {
- for (String validValue : getValidValues()) {
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue,
- getDefaultProviderName());
- assertTrue("Not TrustManagerFactory object",
- trustMF instanceof TrustManagerFactory);
- assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue);
- assertEquals("Invalid provider", trustMF.getProvider(), getDefaultProvider());
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws Exception {
- for (String validValue : getValidValues()) {
- try {
- TrustManagerFactory.getInstance(validValue, (Provider) null);
- } catch (IllegalArgumentException expected) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
- try {
- TrustManagerFactory.getInstance(null, getDefaultProvider());
- fail("");
- } catch (NoSuchAlgorithmException expected) {
- } catch (NullPointerException expected) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i],
- getDefaultProvider());
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: returns instance of TrustManagerFactory
- */
- public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws Exception {
- for (String validValue : getValidValues()) {
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(validValue,
- getDefaultProvider());
- assertTrue("Not TrustManagerFactory object",
- trustMF instanceof TrustManagerFactory);
- assertEquals("Invalid algorithm", trustMF.getAlgorithm(), validValue);
- assertEquals("Invalid provider", trustMF.getProvider(), getDefaultProvider());
- }
- }
-
- /**
- * Test for <code>getProvider()</code>
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- */
- public void test_getProvider()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- assertEquals("Incorrect provider",
- getDefaultProvider(),
- TrustManagerFactory
- .getInstance(getDefaultAlgorithm()).getProvider());
- assertEquals("Incorrect provider",
- getDefaultProvider(),
- TrustManagerFactory
- .getInstance(getDefaultAlgorithm(), getDefaultProviderName())
- .getProvider());
- assertEquals("Incorrect provider",
- getDefaultProvider(),
- TrustManagerFactory.getInstance(getDefaultAlgorithm(), getDefaultProvider())
- .getProvider());
- }
-
- /**
- * Test for <code>geTrustManagers()</code>
- * @throws KeyStoreException
- * @throws IOException
- * @throws CertificateException
- * @throws NoSuchAlgorithmException
- */
- public void test_getTrustManagers() {
- try {
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(getDefaultAlgorithm());
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- trustMF.init(ks);
- TrustManager[] tm = trustMF.getTrustManagers();
- assertNotNull("Result has not be null", tm);
- assertTrue("Length of result TrustManager array should not be 0",
- (tm.length > 0));
- } catch (Exception ex) {
- fail("Unexpected exception " + ex.toString());
- }
- }
-
- /**
- * Test for <code>init(KeyStore keyStore)</code>
- * Assertion: call method with null parameter
- */
- public void test_initLjava_security_KeyStore_01() throws Exception {
- KeyStore ksNull = null;
- TrustManagerFactory[] trustMF = createTMFac();
- assertNotNull("TrustManagerFactory objects were not created", trustMF);
- // null parameter
- try {
- trustMF[0].init(ksNull);
- } catch (Exception ex) {
- fail(ex + " unexpected exception was thrown for null parameter");
- }
- }
-
- /**
- * Test for <code>init(KeyStore keyStore)</code>
- * Assertion: call method with not null parameter
- */
- public void test_initLjava_security_KeyStore_02() throws Exception {
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- TrustManagerFactory[] trustMF = createTMFac();
- assertNotNull("TrustManagerFactory objects were not created", trustMF);
-
- // not null parameter
- trustMF[0].init(ks);
- }
-
- /**
- * Test for <code>init(ManagerFactoryParameters params)</code>
- * Assertion:
- * throws InvalidAlgorithmParameterException when params is null
- */
- @KnownFailure("ManagerFactoryParameters object is not supported "
- + "and InvalidAlgorithmParameterException was thrown.")
- public void test_initLjavax_net_ssl_ManagerFactoryParameters() throws Exception {
- ManagerFactoryParameters par = null;
- TrustManagerFactory[] trustMF = createTMFac();
- assertNotNull("TrustManagerFactory objects were not created", trustMF);
- for (int i = 0; i < trustMF.length; i++) {
- try {
- trustMF[i].init(par);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- }
-
- String keyAlg = "DSA";
- String validCaNameRfc2253 = ("CN=Test CA,"
- + "OU=Testing Division,"
- + "O=Test It All,"
- + "L=Test Town,"
- + "ST=Testifornia,"
- + "C=Testland");
-
- try {
- KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
- kStore.load(null, null);
- PublicKey pk = new TestKeyPair(keyAlg).getPublic();
- TrustAnchor ta = new TrustAnchor(validCaNameRfc2253, pk, getFullEncoding());
- Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
- trustAnchors.add(ta);
- X509CertSelector xcs = new X509CertSelector();
- PKIXBuilderParameters pkixBP = new PKIXBuilderParameters(trustAnchors, xcs);
- CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pkixBP);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(getDefaultAlgorithm());
- try {
- tmf.init(cptmp);
- } catch (Exception ex) {
- fail(ex + " was thrown for init(ManagerFactoryParameters spec)");
- }
- } catch (Exception e) {
- fail("Unexpected exception for configuration: " + e);
- }
-
- }
-
- private static final byte[] getFullEncoding() {
- // DO NOT MODIFY!
- return new byte[] {
- (byte)0x30,(byte)0x81,(byte)0x8c,(byte)0xa0,
- (byte)0x44,(byte)0x30,(byte)0x16,(byte)0x86,
- (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c,
- (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
- (byte)0x66,(byte)0x6f,(byte)0x6f,(byte)0x2e,
- (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80,
- (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
- (byte)0x01,(byte)0x30,(byte)0x16,(byte)0x86,
- (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c,
- (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
- (byte)0x62,(byte)0x61,(byte)0x72,(byte)0x2e,
- (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80,
- (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
- (byte)0x01,(byte)0x30,(byte)0x12,(byte)0x86,
- (byte)0x0a,(byte)0x66,(byte)0x69,(byte)0x6c,
- (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
- (byte)0x6d,(byte)0x75,(byte)0x75,(byte)0x80,
- (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
- (byte)0x01,(byte)0xa1,(byte)0x44,(byte)0x30,
- (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68,
- (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
- (byte)0x2f,(byte)0x2f,(byte)0x66,(byte)0x6f,
- (byte)0x6f,(byte)0x2e,(byte)0x63,(byte)0x6f,
- (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00,
- (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30,
- (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68,
- (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
- (byte)0x2f,(byte)0x2f,(byte)0x62,(byte)0x61,
- (byte)0x72,(byte)0x2e,(byte)0x63,(byte)0x6f,
- (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00,
- (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30,
- (byte)0x12,(byte)0x86,(byte)0x0a,(byte)0x68,
- (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
- (byte)0x2f,(byte)0x2f,(byte)0x6d,(byte)0x75,
- (byte)0x75,(byte)0x80,(byte)0x01,(byte)0x00,
- (byte)0x81,(byte)0x01,(byte)0x01
- };
- }
-}
-
-/**
- * Addifional class to verify TrustManagerFactory constructor
- */
-
-class myTrustManagerFactory extends TrustManagerFactory {
- public myTrustManagerFactory(TrustManagerFactorySpi spi, Provider prov,
- String alg) {
- super(spi, prov, alg);
- }
-}
-
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java b/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java
deleted file mode 100644
index 0c0760f..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java
+++ /dev/null
@@ -1,255 +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 tests.api.javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.Security;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi;
-import junit.framework.TestCase;
-
-/**
- * Tests for TrustManagerFactory class constructors and methods
- *
- */
-public class TrustManagerFactory2Test extends TestCase {
- private static final String srvTrustManagerFactory = "TrustManagerFactory";
- private static final String defaultAlg = "TMF";
- private static final String TrustManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static final String[] validValues;
-
- static {
- validValues = new String[4];
- validValues[0] = defaultAlg;
- validValues[1] = defaultAlg.toLowerCase();
- validValues[2] = "Tmf";
- validValues[3] = "tMF";
- }
-
- Provider mProv;
-
- protected void setUp() throws Exception {
- super.setUp();
- mProv = (new SpiEngUtils()).new MyProvider("MyTMFProvider",
- "Provider for testing", srvTrustManagerFactory.concat(".")
- .concat(defaultAlg), TrustManagerFactoryProviderClass);
- Security.insertProviderAt(mProv, 1);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- Security.removeProvider(mProv.getName());
- }
-
- private void checkResult(TrustManagerFactory tmf) throws Exception {
- KeyStore kStore = null;
- ManagerFactoryParameters mfp = null;
-
- try {
- tmf.init(kStore);
- fail("KeyStoreException must be thrown");
- } catch (KeyStoreException e) {
- }
- try {
- tmf.init(mfp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- assertNull("getTrustManagers() should return null object", tmf
- .getTrustManagers());
-
- try {
- kStore = KeyStore.getInstance(KeyStore.getDefaultType());
- kStore.load(null, null);
- } catch (KeyStoreException e) {
- fail("default keystore is not supported");
- return;
- }
- tmf.init(kStore);
- mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(null);
- try {
- tmf.init(mfp);
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertTrue("Incorrect exception", e.getCause() instanceof KeyStoreException);
- }
- mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(kStore);
- tmf.init(mfp);
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * returns TrustManagerFactory object
- */
- public void test_getInstanceLjava_lang_String() throws Exception {
- try {
- TrustManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- TrustManagerFactory tmf;
- for (int i = 0; i < validValues.length; i++) {
- tmf = TrustManagerFactory.getInstance(validValues[i]);
- assertTrue("Not instanceof TrustManagerFactory object",
- tmf instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", tmf.getProvider(), mProv);
- checkResult(tmf);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null or empty;
- * throws NoSuchProviderException when provider is available;
- * returns TrustManagerFactory object
- */
- public void test_getInstanceLjava_lang_StringLjava_lang_String() throws Exception {
- try {
- TrustManagerFactory.getInstance(null, mProv.getName());
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i], mProv
- .getName());
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- String prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- try {
- TrustManagerFactory.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- TrustManagerFactory.getInstance(validValues[i],
- invalidValues[j]);
- fail("NoSuchProviderException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(" provider: ")
- .concat(invalidValues[j]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- TrustManagerFactory tmf;
- for (int i = 0; i < validValues.length; i++) {
- tmf = TrustManagerFactory.getInstance(validValues[i], mProv
- .getName());
- assertTrue("Not instanceof TrustManagerFactory object",
- tmf instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", tmf.getProvider().getName(),
- mProv.getName());
- checkResult(tmf);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null;
- * returns TrustManagerFactory object
- */
- public void testLjava_lang_StringLjava_security_Provider() throws Exception {
- try {
- TrustManagerFactory.getInstance(null, mProv);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i], mProv);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- Provider prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- TrustManagerFactory tmf;
- for (int i = 0; i < validValues.length; i++) {
- tmf = TrustManagerFactory.getInstance(validValues[i], mProv);
- assertTrue("Not instanceof TrustManagerFactory object",
- tmf instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", tmf.getProvider(), mProv);
- checkResult(tmf);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java b/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java
deleted file mode 100644
index 7bdeb45..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Provider;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.TrustManagerFactorySpi;
-
-import junit.framework.TestCase;
-import org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl;
-import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi.Parameters;
-
-public class TrustManagerFactorySpiTest extends TestCase {
-
- private TrustManagerFactorySpiImpl factory = new TrustManagerFactorySpiImpl();
- /**
- * javax.net.ssl.TrustManagerFactorySpi#TrustManagerFactorySpi()
- */
- public void test_Constructor() {
- try {
- TrustManagerFactorySpiImpl tmf = new TrustManagerFactorySpiImpl();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
- */
- public void test_engineInit_01() throws NoSuchAlgorithmException,
- KeyStoreException {
- factory.reset();
- Provider provider = new MyProvider();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
- provider);
- KeyStore ks = null;
- try {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- tmf.init(ks);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- assertTrue(factory.isEngineInitCalled());
- assertEquals(ks, factory.getKs());
- factory.reset();
- tmf.init((KeyStore) null);
- assertTrue(factory.isEngineInitCalled());
- assertNull(factory.getKs());
- }
-
- /**
- * @throws InvalidAlgorithmParameterException
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.TrustManagerFactorySpi#engineInit(ManagerFactoryParameters spec)
- */
- public void test_engineInit_02() throws InvalidAlgorithmParameterException,
- NoSuchAlgorithmException {
- factory.reset();
- Provider provider = new MyProvider();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
- provider);
- Parameters pr = null;
- try {
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- pr = new Parameters(ks);
- tmf.init(pr);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- assertTrue(factory.isEngineInitCalled());
- assertEquals(pr, factory.getSpec());
- factory.reset();
- tmf.init((ManagerFactoryParameters) null);
- assertTrue(factory.isEngineInitCalled());
- assertNull(factory.getSpec());
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * javax.net.ssl.TrustManagerFactorySpi#engineGetTrustManagers()
- */
- public void test_engineGetTrustManagers() throws NoSuchAlgorithmException {
- factory.reset();
- Provider provider = new MyProvider();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
- provider);
- TrustManager[] tm = tmf.getTrustManagers();
- assertTrue(factory.isEngineGetTrustManagersCalled());
- factory.reset();
- try {
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- tmf.init(ks);
- tm = tmf.getTrustManagers();
- assertTrue(factory.isEngineGetTrustManagersCalled());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-}
-
-class MyProvider extends Provider {
-
- public MyProvider() {
- super("MyProvider", 1.0, "My Test Provider");
- AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
- public Void run() {
- put("TrustManagerFactory.MyTMF",
- "org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl");
- return null;
- }
- });
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java
deleted file mode 100644
index 514fed8..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java
+++ /dev/null
@@ -1,176 +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 tests.api.javax.net.ssl;
-
-import java.net.Socket;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.X509ExtendedKeyManager;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>X509ExtendedKeyManager</code> class constructors and methods.
- *
- */
-public class X509ExtendedKeyManagerTest extends TestCase {
-
- private class MockX509ExtendedKeyManager extends X509ExtendedKeyManager {
- public MockX509ExtendedKeyManager() {
- super();
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[], java.security.Principal[], java.net.Socket)
- */
- public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String, java.security.Principal[], java.net.Socket)
- */
- public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
- */
- public X509Certificate[] getCertificateChain(String arg0) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String, java.security.Principal[])
- */
- public String[] getClientAliases(String arg0, Principal[] arg1) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
- */
- public PrivateKey getPrivateKey(String arg0) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String, java.security.Principal[])
- */
- public String[] getServerAliases(String arg0, Principal[] arg1) {
- // it is a fake
- return null;
- }
- }
-
- /**
- * javax.net.ssl.X509ExtendedKeyManager#X509ExtendedKeyManager()
- */
- public final void test_Constructor() {
- try {
- new MockX509ExtendedKeyManager();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.net.ssl.X509ExtendedKeyManager
- * #chooseEngineClientAlias(java.lang.String[],
- * java.security.Principal[], javax.net.ssl.SSLEngine)
- */
- public final void test_chooseEngineClientAlias() {
- X509ExtendedKeyManager km = new MyX509ExtendedKeyManager();
- if (km.chooseEngineClientAlias(null, null, null) != null) {
- fail("non null result");
- }
- }
-
- /**
- * javax.net.ssl.X509ExtendedKeyManager
- * #chooseEngineServerAlias(java.lang.String,
- * java.security.Principal[], javax.net.ssl.SSLEngine)
- */
- public final void test_chooseEngineServerAlias() {
- X509ExtendedKeyManager km = new MyX509ExtendedKeyManager();
- if (km.chooseEngineServerAlias(null, null, null) != null) {
- fail("non null result");
- }
- }
-
-}
-
-class MyX509ExtendedKeyManager extends X509ExtendedKeyManager {
-
- /*
- * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[],
- * java.security.Principal[], java.net.Socket)
- */
- public String chooseClientAlias(String[] keyType, Principal[] issuers,
- Socket socket) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String,
- * java.security.Principal[], java.net.Socket)
- */
- public String chooseServerAlias(String keyType, Principal[] issuers,
- Socket socket) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
- */
- public X509Certificate[] getCertificateChain(String alias) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String,
- * java.security.Principal[])
- */
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String,
- * java.security.Principal[])
- */
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
- */
- public PrivateKey getPrivateKey(String alias) {
- return null;
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java
deleted file mode 100644
index 4dddbc6..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java
+++ /dev/null
@@ -1,753 +0,0 @@
-package tests.api.javax.net.ssl;
-
-import java.io.ByteArrayInputStream;
-import java.net.Socket;
-import java.security.KeyFactory;
-import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.security.spec.PKCS8EncodedKeySpec;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.X509KeyManager;
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>X509KeyManager</code> class constructors and methods.
- */
-public class X509KeyManagerTest extends TestCase {
-
- private X509KeyManager manager;
- private KeyManagerFactory factory;
-
- private static final String CLIENT = "CLIENT";
- private static final String SERVER = "SERVER";
- private static final String TYPE_RSA = "RSA";
- private static final char[] PASSWORD = "1234".toCharArray();
-
- private String keyType;
- private KeyStore keyTest;
- private X509Certificate[] cert;
- private PrivateKey[] keys;
-
-
- /*
- Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 0 (0x0)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Validity
- Not Before: Mar 20 17:00:06 2009 GMT
- Not After : Mar 19 17:00:06 2012 GMT
- Subject: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:aa:42:40:ed:92:21:17:99:5f:0e:e4:42:b8:cb:
- 66:3d:63:2a:16:34:3c:7b:d3:3e:1f:a8:3f:bd:9a:
- eb:b3:24:6b:8c:e4:da:2f:31:bc:61:07:27:2e:28:
- 71:77:58:ae:b4:89:7c:eb:b0:06:24:07:57:3c:54:
- 71:db:71:41:05:ab:3d:9f:05:d2:ca:cb:1c:bf:9d:
- 8a:21:96:8f:13:61:25:69:12:3b:77:bd:f7:34:b2:
- 09:a9:e0:52:94:44:31:ce:db:3d:eb:64:f1:d6:ca:
- c5:7d:2f:d6:6f:8d:e4:29:8b:06:98:8a:95:3d:7a:
- 97:41:9a:f1:66:c5:09:82:0d
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Subject Key Identifier:
- E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
- X509v3 Authority Key Identifier:
- keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
- DirName:/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android@android.com
- serial:00
-
- X509v3 Basic Constraints:
- CA:TRUE
- Signature Algorithm: sha1WithRSAEncryption
- 14:98:30:29:42:ef:ab:e6:b8:25:4b:55:85:04:a5:c4:dd:1d:
- 8b:6a:c1:6f:6c:1c:1d:c3:61:34:30:07:34:4d:6a:8b:55:6f:
- 75:55:6e:15:58:c5:f8:af:e0:be:73:ba:d9:a5:85:d7:b5:1a:
- 85:44:2b:88:fd:cc:cb:d1:ed:46:69:43:ff:59:ae:9b:5c:17:
- 26:da:ee:c8:bf:67:55:01:a0:0e:10:b9:85:49:54:d9:79:1e:
- 7b:2e:6f:65:4f:d9:10:2e:9d:b8:92:63:67:74:8b:22:0d:6d:
- d3:5d:9e:29:63:f9:36:93:1b:a7:80:e2:b1:f1:bf:29:19:81:
- 3d:07
- */
- String certificate = "-----BEGIN CERTIFICATE-----\n"
- + "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
- + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
- + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
- + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ\n"
- + "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw\n"
- + "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB\n"
- + "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n"
- + "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3\n"
- + "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU\n"
- + "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G\n"
- + "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q\n"
- + "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu\n"
- + "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV\n"
- + "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C\n"
- + "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF\n"
- + "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL\n"
- + "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T\n"
- + "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n"
- + "-----END CERTIFICATE-----";
-
- ByteArrayInputStream certArray = new ByteArrayInputStream(certificate
- .getBytes());
-
- /*
- * The key in DER format.
- * Below is the same key in PEM format as reference
- */
- byte[] keyBytes = new byte[] {
- (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x77, (byte)0x02, (byte)0x01, (byte)0x00,
- (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
- (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
- (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x61, (byte)0x30, (byte)0x82,
- (byte)0x02, (byte)0x5d, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
- (byte)0x81, (byte)0x00, (byte)0xaa, (byte)0x42, (byte)0x40, (byte)0xed, (byte)0x92,
- (byte)0x21, (byte)0x17, (byte)0x99, (byte)0x5f, (byte)0x0e, (byte)0xe4, (byte)0x42,
- (byte)0xb8, (byte)0xcb, (byte)0x66, (byte)0x3d, (byte)0x63, (byte)0x2a, (byte)0x16,
- (byte)0x34, (byte)0x3c, (byte)0x7b, (byte)0xd3, (byte)0x3e, (byte)0x1f, (byte)0xa8,
- (byte)0x3f, (byte)0xbd, (byte)0x9a, (byte)0xeb, (byte)0xb3, (byte)0x24, (byte)0x6b,
- (byte)0x8c, (byte)0xe4, (byte)0xda, (byte)0x2f, (byte)0x31, (byte)0xbc, (byte)0x61,
- (byte)0x07, (byte)0x27, (byte)0x2e, (byte)0x28, (byte)0x71, (byte)0x77, (byte)0x58,
- (byte)0xae, (byte)0xb4, (byte)0x89, (byte)0x7c, (byte)0xeb, (byte)0xb0, (byte)0x06,
- (byte)0x24, (byte)0x07, (byte)0x57, (byte)0x3c, (byte)0x54, (byte)0x71, (byte)0xdb,
- (byte)0x71, (byte)0x41, (byte)0x05, (byte)0xab, (byte)0x3d, (byte)0x9f, (byte)0x05,
- (byte)0xd2, (byte)0xca, (byte)0xcb, (byte)0x1c, (byte)0xbf, (byte)0x9d, (byte)0x8a,
- (byte)0x21, (byte)0x96, (byte)0x8f, (byte)0x13, (byte)0x61, (byte)0x25, (byte)0x69,
- (byte)0x12, (byte)0x3b, (byte)0x77, (byte)0xbd, (byte)0xf7, (byte)0x34, (byte)0xb2,
- (byte)0x09, (byte)0xa9, (byte)0xe0, (byte)0x52, (byte)0x94, (byte)0x44, (byte)0x31,
- (byte)0xce, (byte)0xdb, (byte)0x3d, (byte)0xeb, (byte)0x64, (byte)0xf1, (byte)0xd6,
- (byte)0xca, (byte)0xc5, (byte)0x7d, (byte)0x2f, (byte)0xd6, (byte)0x6f, (byte)0x8d,
- (byte)0xe4, (byte)0x29, (byte)0x8b, (byte)0x06, (byte)0x98, (byte)0x8a, (byte)0x95,
- (byte)0x3d, (byte)0x7a, (byte)0x97, (byte)0x41, (byte)0x9a, (byte)0xf1, (byte)0x66,
- (byte)0xc5, (byte)0x09, (byte)0x82, (byte)0x0d, (byte)0x02, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x34, (byte)0x91,
- (byte)0x8e, (byte)0x50, (byte)0x8b, (byte)0xfc, (byte)0xf1, (byte)0xb7, (byte)0x66,
- (byte)0x35, (byte)0x47, (byte)0xdf, (byte)0x1e, (byte)0x05, (byte)0x97, (byte)0x44,
- (byte)0xbe, (byte)0xf8, (byte)0x80, (byte)0xb0, (byte)0x92, (byte)0x38, (byte)0x3d,
- (byte)0x4a, (byte)0x02, (byte)0x26, (byte)0x45, (byte)0xbf, (byte)0xfa, (byte)0x34,
- (byte)0x6a, (byte)0x34, (byte)0x85, (byte)0x8c, (byte)0x94, (byte)0x20, (byte)0x95,
- (byte)0xcf, (byte)0xca, (byte)0x75, (byte)0x3e, (byte)0xeb, (byte)0x27, (byte)0x02,
- (byte)0x4f, (byte)0xbe, (byte)0x64, (byte)0xc0, (byte)0x54, (byte)0x77, (byte)0xda,
- (byte)0xfd, (byte)0x3e, (byte)0x75, (byte)0x36, (byte)0xec, (byte)0x99, (byte)0x4f,
- (byte)0xc4, (byte)0x56, (byte)0xff, (byte)0x45, (byte)0x61, (byte)0xa8, (byte)0xa8,
- (byte)0x41, (byte)0xe4, (byte)0x42, (byte)0x71, (byte)0x7a, (byte)0x8c, (byte)0x84,
- (byte)0xc2, (byte)0x02, (byte)0x40, (byte)0x0b, (byte)0x3d, (byte)0x42, (byte)0xe0,
- (byte)0x8b, (byte)0x22, (byte)0xf7, (byte)0x4c, (byte)0xa3, (byte)0xbb, (byte)0xd8,
- (byte)0x8f, (byte)0x45, (byte)0xa2, (byte)0x55, (byte)0xc7, (byte)0xd0, (byte)0x6a,
- (byte)0x25, (byte)0xbf, (byte)0xda, (byte)0x54, (byte)0x57, (byte)0x14, (byte)0x91,
- (byte)0x0c, (byte)0x09, (byte)0x0b, (byte)0x9a, (byte)0x50, (byte)0xca, (byte)0xe6,
- (byte)0x9e, (byte)0x28, (byte)0xc3, (byte)0x78, (byte)0x39, (byte)0x10, (byte)0x06,
- (byte)0x02, (byte)0x96, (byte)0x10, (byte)0x1a, (byte)0xd2, (byte)0x4b, (byte)0x7b,
- (byte)0x6c, (byte)0x72, (byte)0x9e, (byte)0x1e, (byte)0xac, (byte)0xd2, (byte)0xc1,
- (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xde, (byte)0x27, (byte)0xbd, (byte)0x43,
- (byte)0xa4, (byte)0xbd, (byte)0x95, (byte)0x14, (byte)0x2e, (byte)0x1c, (byte)0xa0,
- (byte)0x74, (byte)0xa5, (byte)0x3e, (byte)0xfa, (byte)0xf9, (byte)0x15, (byte)0xb2,
- (byte)0x29, (byte)0x6a, (byte)0x2a, (byte)0x42, (byte)0x94, (byte)0x5a, (byte)0xf2,
- (byte)0x81, (byte)0xf3, (byte)0xe1, (byte)0x76, (byte)0x49, (byte)0x11, (byte)0x9d,
- (byte)0x18, (byte)0xc5, (byte)0xeb, (byte)0xb6, (byte)0xbc, (byte)0x81, (byte)0x3a,
- (byte)0x14, (byte)0x9c, (byte)0x41, (byte)0x01, (byte)0x58, (byte)0x56, (byte)0xa9,
- (byte)0x9b, (byte)0x73, (byte)0x2f, (byte)0xd9, (byte)0xa8, (byte)0x8e, (byte)0xc4,
- (byte)0x48, (byte)0x69, (byte)0x35, (byte)0xe6, (byte)0xf4, (byte)0x73, (byte)0x2f,
- (byte)0xf9, (byte)0x12, (byte)0x12, (byte)0x71, (byte)0x02, (byte)0x41, (byte)0x00,
- (byte)0xc4, (byte)0x32, (byte)0x81, (byte)0x5d, (byte)0x19, (byte)0x54, (byte)0x2c,
- (byte)0x29, (byte)0x5a, (byte)0x9f, (byte)0x36, (byte)0x4c, (byte)0x6f, (byte)0x2d,
- (byte)0xfd, (byte)0x62, (byte)0x0e, (byte)0xe6, (byte)0x37, (byte)0xc2, (byte)0xf6,
- (byte)0x69, (byte)0x64, (byte)0xf9, (byte)0x3a, (byte)0xcc, (byte)0xb2, (byte)0x63,
- (byte)0x2f, (byte)0xa9, (byte)0xfe, (byte)0x7e, (byte)0x8b, (byte)0x2d, (byte)0x69,
- (byte)0x13, (byte)0xe5, (byte)0x61, (byte)0x58, (byte)0xb7, (byte)0xfa, (byte)0x55,
- (byte)0x74, (byte)0x2c, (byte)0xe8, (byte)0xa1, (byte)0xac, (byte)0xc3, (byte)0xdd,
- (byte)0x5b, (byte)0x62, (byte)0xae, (byte)0x0a, (byte)0x27, (byte)0xce, (byte)0xb0,
- (byte)0xf2, (byte)0x81, (byte)0x5f, (byte)0x9a, (byte)0x6f, (byte)0x5f, (byte)0x3f,
- (byte)0x5d, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0x92, (byte)0x42, (byte)0xff,
- (byte)0xac, (byte)0xe5, (byte)0x6d, (byte)0x9c, (byte)0x15, (byte)0x29, (byte)0x36,
- (byte)0xd7, (byte)0xbd, (byte)0x74, (byte)0x7e, (byte)0x3e, (byte)0xa6, (byte)0x77,
- (byte)0xce, (byte)0x50, (byte)0xce, (byte)0x00, (byte)0xfc, (byte)0xcc, (byte)0xc8,
- (byte)0x04, (byte)0x19, (byte)0xe3, (byte)0x03, (byte)0x71, (byte)0xe9, (byte)0x31,
- (byte)0x9b, (byte)0x88, (byte)0x8f, (byte)0xe6, (byte)0x5c, (byte)0xed, (byte)0x46,
- (byte)0xf7, (byte)0x82, (byte)0x52, (byte)0x4d, (byte)0xca, (byte)0x20, (byte)0xeb,
- (byte)0x0d, (byte)0xc7, (byte)0xb6, (byte)0xd2, (byte)0xae, (byte)0x2e, (byte)0xf7,
- (byte)0xaf, (byte)0xeb, (byte)0x2c, (byte)0xb9, (byte)0xbc, (byte)0x50, (byte)0xfc,
- (byte)0xf5, (byte)0x7c, (byte)0xba, (byte)0x95, (byte)0x41, (byte)0x02, (byte)0x40,
- (byte)0x54, (byte)0xf8, (byte)0x46, (byte)0x9c, (byte)0x6a, (byte)0x5e, (byte)0xd0,
- (byte)0xed, (byte)0x6c, (byte)0x08, (byte)0xed, (byte)0xfc, (byte)0x36, (byte)0x5e,
- (byte)0x65, (byte)0x91, (byte)0x75, (byte)0x40, (byte)0x71, (byte)0x3f, (byte)0xe7,
- (byte)0x76, (byte)0x07, (byte)0xbc, (byte)0x04, (byte)0xa2, (byte)0x28, (byte)0x53,
- (byte)0xda, (byte)0x8d, (byte)0xb5, (byte)0xe1, (byte)0x5a, (byte)0x27, (byte)0x65,
- (byte)0x8d, (byte)0xaf, (byte)0x56, (byte)0xf4, (byte)0x94, (byte)0x61, (byte)0x3f,
- (byte)0x67, (byte)0x1c, (byte)0x17, (byte)0xf8, (byte)0x05, (byte)0x19, (byte)0xa2,
- (byte)0xa1, (byte)0x74, (byte)0x60, (byte)0x49, (byte)0x97, (byte)0xa9, (byte)0xe5,
- (byte)0x6a, (byte)0x71, (byte)0x6b, (byte)0x55, (byte)0x38, (byte)0x0c, (byte)0xb9,
- (byte)0x25, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xae, (byte)0xf2, (byte)0xa8,
- (byte)0x6d, (byte)0x1d, (byte)0x35, (byte)0x38, (byte)0x73, (byte)0x98, (byte)0x15,
- (byte)0xc7, (byte)0x15, (byte)0x02, (byte)0x2f, (byte)0x29, (byte)0x5d, (byte)0x18,
- (byte)0x4b, (byte)0x7d, (byte)0xb2, (byte)0x59, (byte)0xbe, (byte)0x5a, (byte)0xc7,
- (byte)0x72, (byte)0xd0, (byte)0x80, (byte)0xd8, (byte)0x77, (byte)0xa1, (byte)0x7f,
- (byte)0xb2, (byte)0x35, (byte)0x0d, (byte)0x78, (byte)0x92, (byte)0x91, (byte)0x35,
- (byte)0x47, (byte)0xeb, (byte)0x4b, (byte)0x00, (byte)0x59, (byte)0xb4, (byte)0xc4,
- (byte)0x2c, (byte)0x29, (byte)0xe7, (byte)0x39, (byte)0x9d, (byte)0x48, (byte)0x8b,
- (byte)0x4f, (byte)0x46, (byte)0xe6, (byte)0xce, (byte)0xd3, (byte)0x6c, (byte)0x84,
- (byte)0x9b, (byte)0xd2, (byte)0x10, (byte)0xb0, (byte)0xe1
- };
-
- /*
- * The same key in PEM format.
- * The DER version of this key was created using
- *
- * openssl pkcs8 -topk8 -nocrypt -in key1.pem
- * -inform PEM -out key1.der -outform DER
- *
- * -----BEGIN RSA PRIVATE KEY-----
- * Proc-Type: 4,ENCRYPTED
- * DEK-Info: DES-EDE3-CBC,69E26FCC3A7F136E
- *
- * YKiLXOwf2teog4IoOvbbROy9vqp0EMt1KF9eNKeKFCWGCS4RFATaAGjKrdA26bOV
- * MBdyB4V7qaxLC8/UwLlzFLpprouIfGqrEoR/NT0eKQ+4Pl25GlMvlPaR0pATBLZ2
- * OEaB3zcNygOQ02Jdrmw2+CS9qVtGGXjn6Qp6TVFm6edNCoOVZODLP9kkzPLn8Mkm
- * /isgsprwMELuth8Y5BC0brI5XYdMqZFI5dLz4wzVH81wBYbRmJqR7yOE1pzAJS9I
- * gJ5YvcP7pSmoA2SHVN4v4qolM+GAM9YIp2bwEyWFRjbriNlF1yM+HflGMEZ1HNpZ
- * FSFFA3G8EIH9ogbZ3j+7EujrndJC7GIibwiu5rd3eIHtcwrWprp+wEoPc/vM8OpR
- * so9ms7iQYV6faYCWK4yeCfErYw7t+AhGqfLiqHO6bO2XAYJcD28RYV9gXmugZOhT
- * 9471MOw94HWF5tBVjgIkyNBcbRyMF9iyQKafbkHYpmxaB4s2EqQr1SNZl3SLEwhX
- * MEGy3/tyveuMLAvdTlSDZbt6memWoXXEX4Ep/q6r0ErCTY31awdP/XaJcJBGb9ni
- * Iai8DICaG1v4bUuBVgaiacZlgw1O4Hhj8D2DWfVZsgpx5y8tBRM2lGWvyzEi5n2F
- * PiR2UlT0DjCD1ObjCpWJ5insX/w8dXSHGZLLb9ccGRUrw/+5Bptn+AoEfdP+8S3j
- * UdMdxl6qt2gneCYu1Lr3cQ+qKPqikQty2UQ6Yp8dJkheLJ2Tr+rnaytOCp2dAT9K
- * KXTimIcXV+ftvUMbDPXYu4LJBldr2VokD+k3QbHDgFnfHIiNkwiPzA==
- * -----END RSA PRIVATE KEY-----
- */
-
- /*
- Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 1 (0x1)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Validity
- Not Before: Mar 20 17:00:40 2009 GMT
- Not After : Mar 20 17:00:40 2010 GMT
- Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:d0:44:5a:c4:76:ef:ae:ff:99:5b:c3:37:c1:09:
- 33:c1:97:e5:64:7a:a9:7e:98:4b:3a:a3:33:d0:5c:
- c7:56:ac:d8:42:e8:4a:ac:9c:d9:8f:89:84:c8:46:
- 95:ce:22:f7:6a:09:de:91:47:9c:38:23:a5:4a:fc:
- 08:af:5a:b4:6e:39:8e:e9:f5:0e:46:00:69:e1:e5:
- cc:4c:81:b6:82:7b:56:fb:f4:dc:04:ff:61:e2:7e:
- 5f:e2:f9:97:53:93:d4:69:9b:ba:79:20:cd:1e:3e:
- d5:9a:44:95:7c:cf:c1:51:f2:22:fc:ec:cc:66:18:
- 74:60:2a:a2:be:06:c2:9e:8d
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints:
- CA:FALSE
- Netscape Comment:
- OpenSSL Generated Certificate
- X509v3 Subject Key Identifier:
- 95:3E:C3:46:69:52:78:08:05:46:B9:00:69:E5:E7:A7:99:E3:C4:67
- X509v3 Authority Key Identifier:
- keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
-
- Signature Algorithm: sha1WithRSAEncryption
- a3:5b:30:f5:28:3f:87:f6:1b:36:6a:22:6d:66:48:fa:cb:ee:
- 4c:04:cf:11:14:e2:1f:b5:68:0c:e7:61:0e:bc:d3:69:19:02:
- 8b:d5:d3:05:4a:c8:29:e8:e3:d0:e9:32:ad:6c:7d:9c:c4:46:
- 6c:f9:66:e6:64:60:47:6b:ef:8e:c8:1c:67:5a:5a:cf:73:a3:
- 7e:9d:6e:89:0c:67:99:17:3d:b2:b8:8e:41:95:9c:84:95:bf:
- 57:95:24:22:8f:19:12:c1:fd:23:45:75:7f:4f:61:06:e3:9f:
- 05:dc:e7:29:9a:6b:17:e1:e1:37:d5:8b:ba:b4:d0:8a:3c:dd:
- 3f:6a
- */
- String certificate2 = "-----BEGIN CERTIFICATE-----\n"
- + "MIIC9jCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
- + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
- + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
- + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwNDBaFw0xMDAzMjAxNzAwNDBaMIGLMQsw\n"
- + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n"
- + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n"
- + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n"
- + "hkiG9w0BAQEFAAOBjQAwgYkCgYEA0ERaxHbvrv+ZW8M3wQkzwZflZHqpfphLOqMz\n"
- + "0FzHVqzYQuhKrJzZj4mEyEaVziL3agnekUecOCOlSvwIr1q0bjmO6fUORgBp4eXM\n"
- + "TIG2gntW+/TcBP9h4n5f4vmXU5PUaZu6eSDNHj7VmkSVfM/BUfIi/OzMZhh0YCqi\n"
- + "vgbCno0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n"
- + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFJU+w0ZpUngIBUa5AGnl\n"
- + "56eZ48RnMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n"
- + "DQEBBQUAA4GBAKNbMPUoP4f2GzZqIm1mSPrL7kwEzxEU4h+1aAznYQ6802kZAovV\n"
- + "0wVKyCno49DpMq1sfZzERmz5ZuZkYEdr747IHGdaWs9zo36dbokMZ5kXPbK4jkGV\n"
- + "nISVv1eVJCKPGRLB/SNFdX9PYQbjnwXc5ymaaxfh4TfVi7q00Io83T9q\n\n"
- + "-----END CERTIFICATE-----";
-
- ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2
- .getBytes());
-
- /*
- * The key in DER format.
- * Below is the same key in PEM format as reference
- */
- byte[] key2Bytes = new byte[] {
- (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x75, (byte)0x02, (byte)0x01, (byte)0x00,
- (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
- (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
- (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x5f, (byte)0x30, (byte)0x82,
- (byte)0x02, (byte)0x5b, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
- (byte)0x81, (byte)0x00, (byte)0xd0, (byte)0x44, (byte)0x5a, (byte)0xc4, (byte)0x76,
- (byte)0xef, (byte)0xae, (byte)0xff, (byte)0x99, (byte)0x5b, (byte)0xc3, (byte)0x37,
- (byte)0xc1, (byte)0x09, (byte)0x33, (byte)0xc1, (byte)0x97, (byte)0xe5, (byte)0x64,
- (byte)0x7a, (byte)0xa9, (byte)0x7e, (byte)0x98, (byte)0x4b, (byte)0x3a, (byte)0xa3,
- (byte)0x33, (byte)0xd0, (byte)0x5c, (byte)0xc7, (byte)0x56, (byte)0xac, (byte)0xd8,
- (byte)0x42, (byte)0xe8, (byte)0x4a, (byte)0xac, (byte)0x9c, (byte)0xd9, (byte)0x8f,
- (byte)0x89, (byte)0x84, (byte)0xc8, (byte)0x46, (byte)0x95, (byte)0xce, (byte)0x22,
- (byte)0xf7, (byte)0x6a, (byte)0x09, (byte)0xde, (byte)0x91, (byte)0x47, (byte)0x9c,
- (byte)0x38, (byte)0x23, (byte)0xa5, (byte)0x4a, (byte)0xfc, (byte)0x08, (byte)0xaf,
- (byte)0x5a, (byte)0xb4, (byte)0x6e, (byte)0x39, (byte)0x8e, (byte)0xe9, (byte)0xf5,
- (byte)0x0e, (byte)0x46, (byte)0x00, (byte)0x69, (byte)0xe1, (byte)0xe5, (byte)0xcc,
- (byte)0x4c, (byte)0x81, (byte)0xb6, (byte)0x82, (byte)0x7b, (byte)0x56, (byte)0xfb,
- (byte)0xf4, (byte)0xdc, (byte)0x04, (byte)0xff, (byte)0x61, (byte)0xe2, (byte)0x7e,
- (byte)0x5f, (byte)0xe2, (byte)0xf9, (byte)0x97, (byte)0x53, (byte)0x93, (byte)0xd4,
- (byte)0x69, (byte)0x9b, (byte)0xba, (byte)0x79, (byte)0x20, (byte)0xcd, (byte)0x1e,
- (byte)0x3e, (byte)0xd5, (byte)0x9a, (byte)0x44, (byte)0x95, (byte)0x7c, (byte)0xcf,
- (byte)0xc1, (byte)0x51, (byte)0xf2, (byte)0x22, (byte)0xfc, (byte)0xec, (byte)0xcc,
- (byte)0x66, (byte)0x18, (byte)0x74, (byte)0x60, (byte)0x2a, (byte)0xa2, (byte)0xbe,
- (byte)0x06, (byte)0xc2, (byte)0x9e, (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x06, (byte)0x41,
- (byte)0xd7, (byte)0x7c, (byte)0x49, (byte)0x9a, (byte)0x7f, (byte)0xe6, (byte)0x7c,
- (byte)0x04, (byte)0x0e, (byte)0xc4, (byte)0x71, (byte)0x0f, (byte)0x46, (byte)0xb7,
- (byte)0xcd, (byte)0x49, (byte)0x7e, (byte)0x10, (byte)0x55, (byte)0x61, (byte)0x51,
- (byte)0x50, (byte)0x09, (byte)0x4d, (byte)0xf7, (byte)0xf3, (byte)0x8d, (byte)0xa6,
- (byte)0x0b, (byte)0x8b, (byte)0x9b, (byte)0xdf, (byte)0xbe, (byte)0xbc, (byte)0xe7,
- (byte)0x9c, (byte)0xba, (byte)0xc8, (byte)0x9e, (byte)0x38, (byte)0x18, (byte)0x10,
- (byte)0x4e, (byte)0xd5, (byte)0xe7, (byte)0xa5, (byte)0x09, (byte)0x51, (byte)0x8c,
- (byte)0x97, (byte)0x4e, (byte)0xd0, (byte)0x79, (byte)0xbb, (byte)0x50, (byte)0x6f,
- (byte)0x05, (byte)0x4d, (byte)0x79, (byte)0x7f, (byte)0x3f, (byte)0x26, (byte)0x76,
- (byte)0xc1, (byte)0xcc, (byte)0x40, (byte)0x0f, (byte)0xde, (byte)0x42, (byte)0x5d,
- (byte)0xc1, (byte)0x5f, (byte)0x70, (byte)0x46, (byte)0x70, (byte)0x8d, (byte)0xff,
- (byte)0x26, (byte)0x35, (byte)0x75, (byte)0x9a, (byte)0x97, (byte)0xd2, (byte)0x74,
- (byte)0x53, (byte)0x11, (byte)0x2b, (byte)0xc1, (byte)0x76, (byte)0x9c, (byte)0x9f,
- (byte)0x93, (byte)0xaa, (byte)0xa8, (byte)0x41, (byte)0x23, (byte)0x9a, (byte)0x04,
- (byte)0x11, (byte)0x6e, (byte)0x56, (byte)0xea, (byte)0xf5, (byte)0xd6, (byte)0x1d,
- (byte)0x49, (byte)0x2a, (byte)0x83, (byte)0x49, (byte)0x7d, (byte)0xb7, (byte)0xd1,
- (byte)0xe6, (byte)0x8d, (byte)0x93, (byte)0x1a, (byte)0x81, (byte)0x8e, (byte)0xc2,
- (byte)0xb9, (byte)0xbf, (byte)0xfd, (byte)0x00, (byte)0xe2, (byte)0xb5, (byte)0x01,
- (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xea, (byte)0xce, (byte)0xc6, (byte)0x11,
- (byte)0x1e, (byte)0xf6, (byte)0xcf, (byte)0x3a, (byte)0x8c, (byte)0xe7, (byte)0x80,
- (byte)0x16, (byte)0x8f, (byte)0x1d, (byte)0xeb, (byte)0xa2, (byte)0xd2, (byte)0x23,
- (byte)0x9e, (byte)0xf9, (byte)0xf1, (byte)0x14, (byte)0x16, (byte)0xc8, (byte)0x87,
- (byte)0xf2, (byte)0x17, (byte)0xdf, (byte)0xc6, (byte)0xe4, (byte)0x1c, (byte)0x74,
- (byte)0x74, (byte)0xb0, (byte)0xbb, (byte)0x40, (byte)0xeb, (byte)0xa6, (byte)0xb2,
- (byte)0x5b, (byte)0x6d, (byte)0xf5, (byte)0x9a, (byte)0x85, (byte)0xf1, (byte)0x73,
- (byte)0x84, (byte)0xec, (byte)0xdb, (byte)0x9b, (byte)0xf9, (byte)0xf8, (byte)0x3d,
- (byte)0xba, (byte)0xeb, (byte)0xd7, (byte)0x6c, (byte)0x45, (byte)0x7b, (byte)0xca,
- (byte)0x12, (byte)0x67, (byte)0x5f, (byte)0xcd, (byte)0x02, (byte)0x41, (byte)0x00,
- (byte)0xe3, (byte)0x10, (byte)0x5b, (byte)0xd0, (byte)0xad, (byte)0x59, (byte)0x90,
- (byte)0x18, (byte)0x17, (byte)0xdc, (byte)0x68, (byte)0xd4, (byte)0x75, (byte)0x55,
- (byte)0xab, (byte)0x7d, (byte)0xd1, (byte)0xb5, (byte)0x5a, (byte)0xc4, (byte)0xb0,
- (byte)0x2d, (byte)0xa9, (byte)0xd1, (byte)0x6f, (byte)0xe9, (byte)0x21, (byte)0x4a,
- (byte)0x27, (byte)0xc4, (byte)0x98, (byte)0x89, (byte)0xfa, (byte)0x65, (byte)0xb6,
- (byte)0x10, (byte)0x5d, (byte)0x66, (byte)0xdd, (byte)0x17, (byte)0xb3, (byte)0xf3,
- (byte)0xd3, (byte)0xe3, (byte)0xa0, (byte)0x1a, (byte)0x93, (byte)0xe4, (byte)0xfb,
- (byte)0x88, (byte)0xa7, (byte)0x3b, (byte)0x97, (byte)0x1b, (byte)0xf1, (byte)0x08,
- (byte)0x0c, (byte)0x66, (byte)0xd0, (byte)0x86, (byte)0x5e, (byte)0x39, (byte)0xf9,
- (byte)0xc1, (byte)0x02, (byte)0x40, (byte)0x24, (byte)0x7c, (byte)0xcd, (byte)0x3a,
- (byte)0x8b, (byte)0xdd, (byte)0x3e, (byte)0x86, (byte)0x92, (byte)0xae, (byte)0xc6,
- (byte)0xb0, (byte)0xba, (byte)0xbc, (byte)0xa3, (byte)0x89, (byte)0x41, (byte)0xae,
- (byte)0x57, (byte)0x5d, (byte)0xef, (byte)0xa0, (byte)0x77, (byte)0x89, (byte)0xe1,
- (byte)0xd6, (byte)0x34, (byte)0xef, (byte)0x89, (byte)0x30, (byte)0x99, (byte)0x5b,
- (byte)0x5f, (byte)0x66, (byte)0xb7, (byte)0x32, (byte)0x77, (byte)0x6c, (byte)0x07,
- (byte)0xfb, (byte)0x3d, (byte)0x33, (byte)0x15, (byte)0x38, (byte)0x0b, (byte)0x35,
- (byte)0x30, (byte)0x4a, (byte)0xbe, (byte)0x35, (byte)0x96, (byte)0xba, (byte)0x84,
- (byte)0x9d, (byte)0x2f, (byte)0x58, (byte)0xe2, (byte)0x72, (byte)0x49, (byte)0xb2,
- (byte)0x34, (byte)0xf9, (byte)0xeb, (byte)0x61, (byte)0x02, (byte)0x40, (byte)0x2a,
- (byte)0xd4, (byte)0x89, (byte)0x1d, (byte)0x21, (byte)0xb5, (byte)0xc5, (byte)0x32,
- (byte)0x66, (byte)0x3d, (byte)0xd3, (byte)0x20, (byte)0x50, (byte)0x49, (byte)0xaa,
- (byte)0xa1, (byte)0x7f, (byte)0x0f, (byte)0x20, (byte)0x61, (byte)0xfd, (byte)0x81,
- (byte)0x7f, (byte)0x88, (byte)0xdb, (byte)0xfd, (byte)0x33, (byte)0xa4, (byte)0x53,
- (byte)0x40, (byte)0x08, (byte)0x2d, (byte)0xee, (byte)0xa7, (byte)0x84, (byte)0xe2,
- (byte)0x2d, (byte)0x5c, (byte)0x1b, (byte)0xd4, (byte)0x3e, (byte)0xc3, (byte)0x7d,
- (byte)0x72, (byte)0x70, (byte)0x5e, (byte)0xd3, (byte)0x0a, (byte)0xdc, (byte)0x4f,
- (byte)0x78, (byte)0x8c, (byte)0x0b, (byte)0x02, (byte)0xe0, (byte)0x42, (byte)0x4e,
- (byte)0x64, (byte)0x8e, (byte)0x6c, (byte)0xea, (byte)0x15, (byte)0x31, (byte)0x81,
- (byte)0x02, (byte)0x40, (byte)0x57, (byte)0x72, (byte)0xb9, (byte)0x78, (byte)0xc0,
- (byte)0x1f, (byte)0x5b, (byte)0x1d, (byte)0xb2, (byte)0xcf, (byte)0x94, (byte)0x42,
- (byte)0xed, (byte)0xbd, (byte)0xe7, (byte)0xaa, (byte)0x14, (byte)0x56, (byte)0xd0,
- (byte)0x94, (byte)0x25, (byte)0x30, (byte)0x87, (byte)0x35, (byte)0x82, (byte)0xa0,
- (byte)0x42, (byte)0xb5, (byte)0x7f, (byte)0x66, (byte)0x77, (byte)0xb0, (byte)0x13,
- (byte)0xbe, (byte)0x57, (byte)0x06, (byte)0x7e, (byte)0x50, (byte)0x67, (byte)0x13,
- (byte)0xa7, (byte)0x09, (byte)0xac, (byte)0xd6, (byte)0xbf, (byte)0x22, (byte)0x74,
- (byte)0x6b, (byte)0x37, (byte)0x92, (byte)0x2b, (byte)0x91, (byte)0xbd, (byte)0x0a,
- (byte)0xd8, (byte)0x0f, (byte)0x8d, (byte)0x86, (byte)0x4b, (byte)0x20, (byte)0x5e,
- (byte)0x50, (byte)0x60, (byte)0x80
- };
-
- /*
- * The same key in PEM format.
- * The DER version of this key was created using
- *
- * openssl pkcs8 -topk8 -nocrypt -in key1.pem
- * -inform PEM -out key1.der -outform DER
- *
- * -----BEGIN RSA PRIVATE KEY-----
- * Proc-Type: 4,ENCRYPTED
- * DEK-Info: DES-EDE3-CBC,370723FFDC1B1CFA
- *
- * KJ20ODBEQujoOpnzNfHNoo5DF/qENhw9IaApChGMj+WhqYuFfKfPQKuRli8sJSEk
- * uoPmEqjJndHz5M5bI7wVxiafv/Up4+SaNKhn/vu6xjx/senJMX8HMUchqfvn0eCd
- * 31NHQeNbQ67O73xGIdltLzwTRsavTu/hwhnnJxiXzXnYtI5HTZUaRbVJQNpdlkNW
- * H91u70lwlT8W2MATBhl3R3wIbRHQG1I0RQX12O04gMfK1PBl9d/tnFOi4ESfth1W
- * e06XV0U12g06V5/UUuicJANvgyf0Pix0xxPr2tqibWeGpFwCvJpNHl4L3tUocydF
- * HYoUKx/r3VSmesnZ1zUMsuO2zXOuLLcwCSFN+73GBLWocCxBvag6HFvCemy5Tuhs
- * 9MhfF+5lKER/9Ama/e7C61usaoUhR1OvpGWMfjewrFLCsyWlInscoZ1ad5YtcWGx
- * MM7+BsTnK00fcXZuPHTPsiwQ0fMVeNM2a/e65aIivfzzHmb6gqUigNpfNYcqQsJJ
- * Wwoc5hXVO92vugdHOHOiAUpfZZgNDZwgCTluMuI+KJ0QCb0dhF5w/TDA8z+vRwmW
- * sz5WrA4F+T3LfwwLQfxJyHTnbAu38VlMMZP98iIobOX3AAkBw4+kTOCEedvmKt0f
- * s7iSKrnnV6AyzRPEJUWknMF8xNFH7HDqkZf4Mv8cMM6e45K4kBGd17d3tcEFi2An
- * 5l6S9hHtoyMhHjnAcyuHJbD9rGRgyOlbhSYTcbX/gKiECZj0kf8xHi20qntO3c+p
- * jdpp97fIMnQTl5IDNxOy5h9MDLs/SYAR7iyF19RkIGc=
- * -----END RSA PRIVATE KEY-----
- */
-
- /*
- Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 2 (0x2)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Validity
- Not Before: Mar 20 17:02:32 2009 GMT
- Not After : Mar 20 17:02:32 2010 GMT
- Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:b4:c5:ed:df:30:42:6d:8b:af:4b:e4:9c:13:5e:
- 83:23:cd:2f:ce:34:e2:43:d7:6c:72:bb:03:b3:b9:
- 24:02:e0:cc:b5:8d:d6:92:41:04:2b:5c:94:b2:c3:
- 9c:9d:56:f0:99:bc:0f:81:af:eb:54:ed:80:a6:a0:
- c7:c2:43:05:04:7c:9c:7e:07:03:10:b9:bd:c5:16:
- cf:19:dd:e3:4f:73:83:72:c5:66:e4:5b:14:c4:96:
- d1:e3:24:0b:b6:d4:f7:84:2e:b1:e7:93:02:9d:f5:
- da:aa:c1:d9:cc:5e:36:e9:8f:bf:8b:da:a7:45:82:
- f2:b0:f5:a7:e4:e1:80:a3:17
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints:
- CA:FALSE
- Netscape Comment:
- OpenSSL Generated Certificate
- X509v3 Subject Key Identifier:
- 3B:5B:3D:DB:45:F5:8F:58:70:0B:FC:70:3E:31:2B:43:63:A9:FE:2B
- X509v3 Authority Key Identifier:
- keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
-
- Signature Algorithm: sha1WithRSAEncryption
- 1c:7f:93:1c:59:21:88:15:45:4b:e0:9c:78:3a:88:3e:55:19:
- 86:31:e8:53:3d:74:e2:4a:34:9f:92:17:4e:13:46:92:54:f8:
- 43:eb:5e:03:4f:14:51:61:d2:04:b8:04:5a:31:eb:14:6a:18:
- b0:20:03:92:0c:7f:07:c4:1b:f9:9e:7f:5f:ec:03:7a:c8:e3:
- df:d3:94:6e:68:8a:3a:3d:e4:61:f3:e0:87:5d:40:d8:cb:99:
- 4d:9a:7b:bc:95:7c:d2:9d:b7:04:9a:9a:63:89:cd:39:ec:32:
- 60:0a:97:da:e9:50:a5:73:4a:a2:aa:9c:9b:a8:7f:5a:20:d6:
- 48:bd
- */
- String certificate3 = "-----BEGIN CERTIFICATE-----\n"
- + "MIIC9jCCAl+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
- + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
- + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
- + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAyMzJaFw0xMDAzMjAxNzAyMzJaMIGLMQsw\n"
- + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n"
- + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n"
- + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n"
- + "hkiG9w0BAQEFAAOBjQAwgYkCgYEAtMXt3zBCbYuvS+ScE16DI80vzjTiQ9dscrsD\n"
- + "s7kkAuDMtY3WkkEEK1yUssOcnVbwmbwPga/rVO2ApqDHwkMFBHycfgcDELm9xRbP\n"
- + "Gd3jT3ODcsVm5FsUxJbR4yQLttT3hC6x55MCnfXaqsHZzF426Y+/i9qnRYLysPWn\n"
- + "5OGAoxcCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n"
- + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFDtbPdtF9Y9YcAv8cD4x\n"
- + "K0Njqf4rMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n"
- + "DQEBBQUAA4GBABx/kxxZIYgVRUvgnHg6iD5VGYYx6FM9dOJKNJ+SF04TRpJU+EPr\n"
- + "XgNPFFFh0gS4BFox6xRqGLAgA5IMfwfEG/mef1/sA3rI49/TlG5oijo95GHz4Idd\n"
- + "QNjLmU2ae7yVfNKdtwSammOJzTnsMmAKl9rpUKVzSqKqnJuof1og1ki9\n"
- + "-----END CERTIFICATE-----";
-
- ByteArrayInputStream certArray3 = new ByteArrayInputStream(certificate3
- .getBytes());
-
- /*
- * The key in DER format.
- * Below is the same key in PEM format as reference
- */
- byte[] key3Bytes = new byte[] {
- (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x76, (byte)0x02, (byte)0x01, (byte)0x00,
- (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
- (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
- (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x60, (byte)0x30, (byte)0x82,
- (byte)0x02, (byte)0x5c, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
- (byte)0x81, (byte)0x00, (byte)0xb4, (byte)0xc5, (byte)0xed, (byte)0xdf, (byte)0x30,
- (byte)0x42, (byte)0x6d, (byte)0x8b, (byte)0xaf, (byte)0x4b, (byte)0xe4, (byte)0x9c,
- (byte)0x13, (byte)0x5e, (byte)0x83, (byte)0x23, (byte)0xcd, (byte)0x2f, (byte)0xce,
- (byte)0x34, (byte)0xe2, (byte)0x43, (byte)0xd7, (byte)0x6c, (byte)0x72, (byte)0xbb,
- (byte)0x03, (byte)0xb3, (byte)0xb9, (byte)0x24, (byte)0x02, (byte)0xe0, (byte)0xcc,
- (byte)0xb5, (byte)0x8d, (byte)0xd6, (byte)0x92, (byte)0x41, (byte)0x04, (byte)0x2b,
- (byte)0x5c, (byte)0x94, (byte)0xb2, (byte)0xc3, (byte)0x9c, (byte)0x9d, (byte)0x56,
- (byte)0xf0, (byte)0x99, (byte)0xbc, (byte)0x0f, (byte)0x81, (byte)0xaf, (byte)0xeb,
- (byte)0x54, (byte)0xed, (byte)0x80, (byte)0xa6, (byte)0xa0, (byte)0xc7, (byte)0xc2,
- (byte)0x43, (byte)0x05, (byte)0x04, (byte)0x7c, (byte)0x9c, (byte)0x7e, (byte)0x07,
- (byte)0x03, (byte)0x10, (byte)0xb9, (byte)0xbd, (byte)0xc5, (byte)0x16, (byte)0xcf,
- (byte)0x19, (byte)0xdd, (byte)0xe3, (byte)0x4f, (byte)0x73, (byte)0x83, (byte)0x72,
- (byte)0xc5, (byte)0x66, (byte)0xe4, (byte)0x5b, (byte)0x14, (byte)0xc4, (byte)0x96,
- (byte)0xd1, (byte)0xe3, (byte)0x24, (byte)0x0b, (byte)0xb6, (byte)0xd4, (byte)0xf7,
- (byte)0x84, (byte)0x2e, (byte)0xb1, (byte)0xe7, (byte)0x93, (byte)0x02, (byte)0x9d,
- (byte)0xf5, (byte)0xda, (byte)0xaa, (byte)0xc1, (byte)0xd9, (byte)0xcc, (byte)0x5e,
- (byte)0x36, (byte)0xe9, (byte)0x8f, (byte)0xbf, (byte)0x8b, (byte)0xda, (byte)0xa7,
- (byte)0x45, (byte)0x82, (byte)0xf2, (byte)0xb0, (byte)0xf5, (byte)0xa7, (byte)0xe4,
- (byte)0xe1, (byte)0x80, (byte)0xa3, (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x53, (byte)0xbc,
- (byte)0x1f, (byte)0x1c, (byte)0x34, (byte)0x09, (byte)0x81, (byte)0x1e, (byte)0xa3,
- (byte)0xfb, (byte)0x5e, (byte)0x90, (byte)0xa1, (byte)0x34, (byte)0x35, (byte)0x40,
- (byte)0x9f, (byte)0x29, (byte)0xd6, (byte)0xb5, (byte)0x8e, (byte)0x5d, (byte)0x68,
- (byte)0x6a, (byte)0xf6, (byte)0x96, (byte)0x03, (byte)0xf7, (byte)0xfa, (byte)0xf9,
- (byte)0x60, (byte)0x4f, (byte)0xea, (byte)0xe2, (byte)0xea, (byte)0x29, (byte)0x8b,
- (byte)0x23, (byte)0x8c, (byte)0x9f, (byte)0xdd, (byte)0x49, (byte)0x8f, (byte)0xa8,
- (byte)0xa6, (byte)0x62, (byte)0x07, (byte)0x44, (byte)0x79, (byte)0xa1, (byte)0xaf,
- (byte)0xf9, (byte)0x1d, (byte)0x98, (byte)0xbf, (byte)0x85, (byte)0x28, (byte)0x03,
- (byte)0x87, (byte)0x14, (byte)0x20, (byte)0xba, (byte)0xd4, (byte)0x96, (byte)0x61,
- (byte)0x2a, (byte)0xd0, (byte)0xaa, (byte)0x30, (byte)0x19, (byte)0x4b, (byte)0x40,
- (byte)0x35, (byte)0xb0, (byte)0x79, (byte)0x0b, (byte)0x7f, (byte)0xd7, (byte)0xcd,
- (byte)0x64, (byte)0xd9, (byte)0x93, (byte)0x38, (byte)0xe2, (byte)0x59, (byte)0xe0,
- (byte)0x9e, (byte)0x3a, (byte)0x25, (byte)0x27, (byte)0xa2, (byte)0xd9, (byte)0x20,
- (byte)0xb0, (byte)0x45, (byte)0x5f, (byte)0x6c, (byte)0x15, (byte)0x6f, (byte)0x10,
- (byte)0x55, (byte)0xa7, (byte)0xf9, (byte)0x3d, (byte)0x92, (byte)0x3c, (byte)0x7c,
- (byte)0x23, (byte)0x1b, (byte)0xc0, (byte)0xb5, (byte)0x17, (byte)0x41, (byte)0x5e,
- (byte)0x8c, (byte)0xdc, (byte)0x25, (byte)0x1d, (byte)0x35, (byte)0x2b, (byte)0xd3,
- (byte)0x97, (byte)0x1a, (byte)0x6f, (byte)0xae, (byte)0xeb, (byte)0xf5, (byte)0xf9,
- (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd7, (byte)0x3e, (byte)0xed, (byte)0x70,
- (byte)0xfe, (byte)0xee, (byte)0x0e, (byte)0x30, (byte)0x29, (byte)0xfa, (byte)0xd7,
- (byte)0x38, (byte)0xcf, (byte)0x8e, (byte)0xc1, (byte)0x9c, (byte)0x78, (byte)0x06,
- (byte)0x2d, (byte)0xda, (byte)0x33, (byte)0x58, (byte)0xa1, (byte)0x7b, (byte)0xbf,
- (byte)0x00, (byte)0xb9, (byte)0xdf, (byte)0xea, (byte)0x65, (byte)0x86, (byte)0xbb,
- (byte)0xcc, (byte)0x83, (byte)0xce, (byte)0xde, (byte)0xc3, (byte)0xf8, (byte)0x89,
- (byte)0xf5, (byte)0x9f, (byte)0xa6, (byte)0x1d, (byte)0xc9, (byte)0xfb, (byte)0x98,
- (byte)0xa1, (byte)0x2e, (byte)0xe0, (byte)0x57, (byte)0x6e, (byte)0xbd, (byte)0x57,
- (byte)0x20, (byte)0xf9, (byte)0x6b, (byte)0x13, (byte)0x42, (byte)0x9d, (byte)0x8d,
- (byte)0x66, (byte)0x4d, (byte)0x7a, (byte)0x2d, (byte)0x02, (byte)0x41, (byte)0x00,
- (byte)0xd7, (byte)0x00, (byte)0x18, (byte)0x54, (byte)0xe8, (byte)0x37, (byte)0xdb,
- (byte)0xf8, (byte)0x98, (byte)0x7b, (byte)0x18, (byte)0x33, (byte)0xf6, (byte)0x28,
- (byte)0xa8, (byte)0x8c, (byte)0xd9, (byte)0xfd, (byte)0x4c, (byte)0x4e, (byte)0x41,
- (byte)0x73, (byte)0x2e, (byte)0x79, (byte)0x31, (byte)0xcc, (byte)0x7d, (byte)0x42,
- (byte)0xb7, (byte)0xa1, (byte)0xd2, (byte)0xbc, (byte)0x1f, (byte)0x62, (byte)0xcf,
- (byte)0x15, (byte)0x7c, (byte)0x62, (byte)0x97, (byte)0x70, (byte)0xf1, (byte)0x15,
- (byte)0xf1, (byte)0x33, (byte)0xa1, (byte)0x9d, (byte)0xbb, (byte)0x5f, (byte)0xd7,
- (byte)0x5a, (byte)0xf9, (byte)0x24, (byte)0x58, (byte)0xac, (byte)0x86, (byte)0x6a,
- (byte)0xed, (byte)0xd4, (byte)0x84, (byte)0xe4, (byte)0x3f, (byte)0xfe, (byte)0xb0,
- (byte)0xd3, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd4, (byte)0xb7, (byte)0x84,
- (byte)0xb2, (byte)0x39, (byte)0xce, (byte)0x0b, (byte)0x49, (byte)0x80, (byte)0x03,
- (byte)0x3c, (byte)0xb5, (byte)0x11, (byte)0x32, (byte)0x34, (byte)0x96, (byte)0xac,
- (byte)0x6a, (byte)0xf6, (byte)0xdf, (byte)0x80, (byte)0x04, (byte)0xe4, (byte)0x39,
- (byte)0xc6, (byte)0x0e, (byte)0x32, (byte)0xa3, (byte)0x5e, (byte)0x23, (byte)0x0d,
- (byte)0x9f, (byte)0x04, (byte)0xc3, (byte)0x72, (byte)0x2a, (byte)0xe6, (byte)0xa2,
- (byte)0xf5, (byte)0xbc, (byte)0x3f, (byte)0x15, (byte)0x4c, (byte)0xb5, (byte)0x33,
- (byte)0x26, (byte)0xa8, (byte)0x8c, (byte)0x09, (byte)0xfb, (byte)0x7e, (byte)0x1e,
- (byte)0x32, (byte)0x40, (byte)0x0d, (byte)0x1d, (byte)0xcb, (byte)0x7f, (byte)0xf6,
- (byte)0xf2, (byte)0x29, (byte)0x9b, (byte)0x01, (byte)0xd5, (byte)0x02, (byte)0x40,
- (byte)0x24, (byte)0x26, (byte)0x1c, (byte)0xf1, (byte)0x31, (byte)0xb6, (byte)0x2a,
- (byte)0xa3, (byte)0x0a, (byte)0xa8, (byte)0x2f, (byte)0xb2, (byte)0x94, (byte)0xe1,
- (byte)0xd3, (byte)0x2d, (byte)0x13, (byte)0x7d, (byte)0xd6, (byte)0x35, (byte)0x96,
- (byte)0x25, (byte)0x92, (byte)0x9b, (byte)0xc7, (byte)0xf6, (byte)0xb4, (byte)0xdc,
- (byte)0xe1, (byte)0xd9, (byte)0x30, (byte)0x80, (byte)0x76, (byte)0xda, (byte)0x7b,
- (byte)0x2d, (byte)0x06, (byte)0xa3, (byte)0xe1, (byte)0x08, (byte)0x99, (byte)0x50,
- (byte)0x72, (byte)0x24, (byte)0x97, (byte)0x38, (byte)0xd9, (byte)0x07, (byte)0x4d,
- (byte)0x43, (byte)0x3b, (byte)0x7e, (byte)0x93, (byte)0xf6, (byte)0x36, (byte)0x07,
- (byte)0x86, (byte)0x83, (byte)0x63, (byte)0xf0, (byte)0xa8, (byte)0x9d, (byte)0xdf,
- (byte)0x07, (byte)0x02, (byte)0x40, (byte)0x3e, (byte)0x58, (byte)0x03, (byte)0xbf,
- (byte)0xea, (byte)0x3e, (byte)0x34, (byte)0x2c, (byte)0xb7, (byte)0xc3, (byte)0x09,
- (byte)0xe9, (byte)0xf4, (byte)0x43, (byte)0x41, (byte)0xc4, (byte)0x7c, (byte)0x6e,
- (byte)0x75, (byte)0x72, (byte)0x5d, (byte)0xfc, (byte)0xa3, (byte)0x75, (byte)0x1d,
- (byte)0xa0, (byte)0xee, (byte)0xc2, (byte)0x1f, (byte)0x71, (byte)0xb0, (byte)0xf3,
- (byte)0x1d, (byte)0xec, (byte)0x81, (byte)0xdb, (byte)0x45, (byte)0xe5, (byte)0x6a,
- (byte)0xe8, (byte)0xe0, (byte)0x64, (byte)0x90, (byte)0xff, (byte)0xb9, (byte)0xf8,
- (byte)0x12, (byte)0xed, (byte)0x55, (byte)0x5c, (byte)0x9b, (byte)0x81, (byte)0xcd,
- (byte)0xbb, (byte)0x06, (byte)0x91, (byte)0xfe, (byte)0x27, (byte)0x2c, (byte)0x3a,
- (byte)0xed, (byte)0x96, (byte)0x3b, (byte)0xfe
- };
-
- /*
- * The same key in PEM format.
- * The DER version of this key was created using
- *
- * openssl pkcs8 -topk8 -nocrypt -in key1.pem
- * -inform PEM -out key1.der -outform DER
- *
- * -----BEGIN RSA PRIVATE KEY-----
- * Proc-Type: 4,ENCRYPTED
- * DEK-Info: DES-EDE3-CBC,0EE6B33EC2D92297
- *
- * r7lbWwtlmubgMG020XiOStqgrvPkP1hTrbOV7Gh2IVNTyXWyA8UriQlPyqBQNzy2
- * 5+Z+JUqzYoLCGY0fQ95ck+ya/wHJQX4OSKFOZwQKpU7pEY9wN1YPa7U9ZnyCPGtB
- * +ejvHuIMJhE5wq9Y1iEDIlON++onWTf4T36Sz3OQ8gEJbnx3x+UjcCINooj7kOeM
- * giCi5yJEOJaf4fkRioUh6S7cm/msTH3ID33rrvTjk7cD8mGzzTy4hWyKaK4K9GbC
- * dOvSORM9mVwTWMUdu1wJ5uyadwBhpSIhC/qpP8Je60nFy8YJlzB2FaMUpAuIOM7B
- * EVN2uAMDNOpGzcOJPbLig8smk2lA4+y1T3gFd9paskSjD9B8+/3KuagWEEQQL7T4
- * YK3xtjzXwEp6OdG2QjD4ZcK5D0MKuYPF3PszwzlCnBG/On6wIvIiTPWBn/G2u59D
- * gJPV7V3Jipn0iYYN+i7T5TNoT7Vko8s3BRpVSrlFUFFhtQPad6NcxGNNH5L1g3fF
- * +dp4TnG64PCQZtuu6I6gfuMXztOwQtEpxxHo9WktlCpwL0tT/tpx+zOVbLvgusjB
- * QKYCIplbSI7VtpOfcJ3kTTAWSOGZli4FayB/Dplf/FXN6ZwwASw09ioVQc/CFdLk
- * Xw05elxV8/AFvm+/VkUHK5JJSp32WMgAJA+XrUsOb5lw1Tl3Hlj9KHALp+Pt/i7N
- * +LPnxrpuTry31APt8aRup/pWOLa+f97Hz+arp4wJa5LK+GtTTtoI4+QZp5qzR/jy
- * oM+DoKtK+1WsCU7teJwEWXV/ayo1TEFEhcY0F7IAPCzDlG3XOFmulQ==
- * -----END RSA PRIVATE KEY-----
- */
-
- @Override
- protected void setUp() {
- String defAlg = KeyManagerFactory.getDefaultAlgorithm();
- try {
- factory = KeyManagerFactory.getInstance(defAlg);
- } catch (NoSuchAlgorithmException e) {
- fail("could not get default KeyManagerFactory");
- }
- }
-
- void init(String name) {
- keyType = name;
- try {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- KeyFactory kf = KeyFactory.getInstance("RSA");
- keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
- keyTest.load(null, "1234".toCharArray());
- if (keyType.equals(CLIENT)) {
- keys = new PrivateKey[3];
- keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
- keys[1] = kf.generatePrivate(new PKCS8EncodedKeySpec(key2Bytes));
- keys[2] = kf.generatePrivate(new PKCS8EncodedKeySpec(key3Bytes));
- cert = new X509Certificate[3];
- cert[0] = (X509Certificate) cf.generateCertificate(certArray);
- cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
- cert[2] = (X509Certificate) cf.generateCertificate(certArray3);
- keyTest.setKeyEntry("clientKey_01", keys[0], PASSWORD, new X509Certificate[] {cert[0]});
- keyTest.setKeyEntry("clientKey_02", keys[1], PASSWORD, new X509Certificate[] {cert[0], cert[1]});
- keyTest.setKeyEntry("clientKey_03", keys[2], PASSWORD, new X509Certificate[] {cert[0], cert[2]});
- keyTest.setCertificateEntry("clientAlias_01", cert[0]);
- keyTest.setCertificateEntry("clientAlias_02", cert[0]);
- keyTest.setCertificateEntry("clientAlias_03", cert[1]);
- } else if (keyType.equals(SERVER)) {
- keys = new PrivateKey[1];
- keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
- cert = new X509Certificate[1];
- cert[0] = (X509Certificate) cf.generateCertificate(certArray3);
- keyTest.setKeyEntry("serverKey_00", keys[0], PASSWORD, new X509Certificate[] {cert[0]});
- keyTest.setCertificateEntry("serverAlias_00", cert[0]);
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- throw new IllegalArgumentException(ex.getMessage());
- }
- try {
- factory.init(keyTest, "1234".toCharArray());
- } catch (Exception e) {
- fail("Could't init the KeyManagerFactory");
- }
- manager = (X509KeyManager) factory.getKeyManagers()[0];
- }
-
- /**
- * X509KeyManager#getClientAliases(String keyType, Principal[] issuers)
- */
- public void test_getClientAliases() {
- init(CLIENT);
- assertNull(manager.getClientAliases(null, null));
- assertNull(manager.getClientAliases("", null));
- String[] resArray = manager.getClientAliases(TYPE_RSA, null);
- assertNotNull(resArray);
- assertEquals(3, resArray.length);
- assertKnownAliases(resArray);
- }
-
- /**
- * X509KeyManager#chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
- */
- public void test_chooseClientAlias() {
- init(CLIENT);
- assertNull(manager.chooseClientAlias(null, null, new Socket()));
- assertNull(manager.chooseClientAlias(new String[0], null, new Socket()));
- assertNull(manager.chooseClientAlias(new String[]{"BOGUS"}, null, new Socket()));
- String res = manager.chooseClientAlias(new String[]{TYPE_RSA}, null, null);
- assertNotNull(res);
- assertKnownAlias(res);
- }
-
- /**
- * X509KeyManager#getServerAliases(String keyType, Principal[] issuers)
- */
- public void test_getServerAliases() {
- init(SERVER);
- assertNull(manager.getServerAliases(null, null));
- assertNull(manager.getServerAliases("", null));
- String[] resArray = manager.getServerAliases(TYPE_RSA, null);
- assertNotNull(resArray);
- assertEquals("Incorrect length", 1, resArray.length);
- assertEquals("Incorrect aliase", "serverkey_00", resArray[0].toLowerCase());
- }
-
- /**
- * X509KeyManager#chooseServerAlias(String keyType, Principal[] issuers, Socket socket)
- */
- public void test_chooseServerAlias() {
- init(SERVER);
- assertNull(manager.chooseServerAlias(null, null, new Socket()));
- assertNull(manager.chooseServerAlias("", null, new Socket()));
- String res = manager.chooseServerAlias(TYPE_RSA, null, null);
- assertNotNull(res);
- assertEquals("serverkey_00", res.toLowerCase());
- res = manager.chooseServerAlias(TYPE_RSA, null, new Socket());
- assertNotNull(res);
- assertEquals("serverkey_00", res.toLowerCase());
- }
-
- /**
- * X509KeyManager#getCertificateChain(String alias)
- */
- public void test_getCertificateChain() {
- init(SERVER);
- assertNull("Not NULL for NULL parameter", manager.getCertificateChain(null));
- assertNull("Not NULL for empty parameter",manager.getCertificateChain(""));
- assertNull("Not NULL for clientAlias_01 parameter", manager.getCertificateChain("clientAlias_01"));
- assertNull("Not NULL for serverAlias_00 parameter", manager.getCertificateChain("serverAlias_00"));
- }
-
- /**
- * X509KeyManager#getPrivateKey(String alias)
- */
- public void test_getPrivateKey() {
- init(CLIENT);
- assertNull("Not NULL for NULL parameter", manager.getPrivateKey(null));
- assertNull("Not NULL for serverAlias_00 parameter", manager.getPrivateKey("serverAlias_00"));
- assertNull("Not NULL for clientAlias_02 parameter", manager.getPrivateKey("clientAlias_02"));
- }
-
-
- private void assertKnownAliases(String[] aliases) {
- for (String alias : aliases) {
- assertKnownAlias(alias);
- }
- }
-
- private void assertKnownAlias(String alias) {
- String a = alias.toLowerCase();
- boolean okay = a.equals("clientkey_01") || a.equals("clientkey_02") || a.equals("clientkey_03");
- assertTrue("Expected one of clientkey_01, clientkey_02, clientkey_03. Received: " + alias, okay);
- }
-}
-
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java b/luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java
deleted file mode 100644
index ade0eca..0000000
--- a/luni/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package tests.api.javax.net.ssl;
-
-import java.io.ByteArrayInputStream;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.X509TrustManager;
-import junit.framework.TestCase;
-import org.apache.harmony.security.tests.support.cert.TestUtils;
-import org.apache.harmony.xnet.tests.support.X509TrustManagerImpl;
-
-public class X509TrustManagerTest extends TestCase {
-
- private X509Certificate[] setX509Certificate() throws Exception {
- CertificateFactory certFact = CertificateFactory.getInstance("X.509");
- X509Certificate pemCert = (X509Certificate) certFact.generateCertificate(
- new ByteArrayInputStream(TestUtils.getX509Certificate_v3()));
- X509Certificate[] xcert = { pemCert };
- return xcert;
- }
-
- private X509Certificate[] setInvalid() throws Exception {
- CertificateFactory certFact = CertificateFactory.getInstance("X.509");
- X509Certificate pemCert = (X509Certificate) certFact.generateCertificate(
- new ByteArrayInputStream(TestUtils.getX509Certificate_v1()));
- X509Certificate[] xcert = { pemCert };
- return xcert;
- }
-
- public void test_checkClientTrusted_01() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = null;
-
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- xcert = new X509Certificate[0];
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- xcert = setX509Certificate();
- try {
- xtm.checkClientTrusted(xcert, null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- try {
- xtm.checkClientTrusted(xcert, "");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- /**
- * javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
- */
- public void test_checkClientTrusted_02() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setInvalid();
-
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- fail("CertificateException wasn't thrown");
- } catch (CertificateException expected) {
- }
- }
-
- /**
- * javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
- */
- public void test_checkClientTrusted_03() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setX509Certificate();
- xtm.checkClientTrusted(xcert, "SSL");
- }
-
- /**
- * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
- */
- public void test_checkServerTrusted_01() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = null;
-
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- xcert = new X509Certificate[0];
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- xcert = setX509Certificate();
- try {
- xtm.checkServerTrusted(xcert, null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- try {
- xtm.checkServerTrusted(xcert, "");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- /**
- * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
- */
- public void test_checkServerTrusted_02() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setInvalid();
-
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- fail("CertificateException wasn't thrown");
- } catch (CertificateException expected) {
- }
- }
-
- /**
- * javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
- */
- public void test_checkServerTrusted_03() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setX509Certificate();
- xtm.checkServerTrusted(xcert, "SSL");
- }
-
- /**
- * javax.net.ssl.X509TrustManager#getAcceptedIssuers()
- */
- public void test_getAcceptedIssuers() throws Exception {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- assertNotNull(xtm.getAcceptedIssuers());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.java b/luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.java
deleted file mode 100644
index 76c860a..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/CallbackHandlerTest.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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-
-/**
- * Tests for <code>CallbackHandler</code> class constructors and methods.
- *
- */
-public class CallbackHandlerTest extends TestCase {
-
- /**
- * javax.security.auth.callback.CallbackHandler#handle(Callback[] callbacks)
- */
- public void test_CallbackHandler() {
- CallbackHandlerImpl ch = new CallbackHandlerImpl();
- assertFalse(ch.called);
- ch.handle(null);
- assertTrue(ch.called);
- }
-
- private class CallbackHandlerImpl implements CallbackHandler {
- boolean called = false;
- public void handle(Callback[] callbacks) {
- called = true;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.java b/luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.java
deleted file mode 100644
index 4472241..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/DestroyFailedExceptionTest.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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.DestroyFailedException;
-
-/**
- * Tests for <code>DestroyFailedException</code> class constructors and methods.
- *
- */
-public class DestroyFailedExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * javax.security.auth.DestroyFailedException#DestroyFailedException()
- * Assertion: constructs DestroyFailedException with no detail message
- */
- public void testDestroyFailedException01() {
- DestroyFailedException dfE = new DestroyFailedException();
- assertNull("getMessage() must return null.", dfE.getMessage());
- assertNull("getCause() must return null", dfE.getCause());
- }
-
- /**
- * javax.security.auth.DestroyFailedException#DestroyFailedException(String msg)
- * Assertion: constructs with not null parameter.
- */
- public void testDestroyFailedException02() {
- DestroyFailedException dfE;
- for (int i = 0; i < msgs.length; i++) {
- dfE = new DestroyFailedException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), dfE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", dfE.getCause());
- }
- }
-
- /**
- * javax.security.auth.DestroyFailedException#DestroyFailedException(String msg)
- * Assertion: constructs with null parameter.
- */
- public void testDestroyFailedException03() {
- String msg = null;
- DestroyFailedException dfE = new DestroyFailedException(msg);
- assertNull("getMessage() must return null.", dfE.getMessage());
- assertNull("getCause() must return null", dfE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java b/luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java
deleted file mode 100644
index 4ae47ce..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/DestroyableTest.java
+++ /dev/null
@@ -1,64 +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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.Destroyable;
-import javax.security.auth.DestroyFailedException;
-
-
-/**
- * Tests for <code>Destroyable</code> class constructors and methods.
- *
- */
-public class DestroyableTest extends TestCase {
-
- /**
- * javax.security.auth.Destroyable#destroy()
- * javax.security.auth.Destroyable#isDestroyed()
- */
- public void test_destroy() {
- myDestroyable md = new myDestroyable();
- try {
- assertFalse(md.isDestroyed());
- md.destroy();
- assertTrue(md.isDestroyed());
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- private class myDestroyable implements Destroyable {
-
- boolean destroyDone = false;
-
- myDestroyable() {
- }
-
- public void destroy() throws DestroyFailedException {
- destroyDone = true;
- }
-
- public boolean isDestroyed() {
- return destroyDone;
- }
- }
-}
-
-
diff --git a/luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.java b/luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.java
deleted file mode 100644
index 307d401..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/LoginExceptionTest.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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.login.LoginException;
-
-/**
- * Tests for <code>LoginException</code> class constructors and methods.
- *
- */
-public class LoginExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * javax.security.auth.login.LoginException#LoginException()
- * Assertion: constructs LoginException with no detail message
- */
- public void testLoginException01() {
- LoginException lE = new LoginException();
- assertNull("getMessage() must return null.", lE.getMessage());
- assertNull("getCause() must return null", lE.getCause());
- }
-
- /**
- * javax.security.auth.login.LoginException#LoginException(String msg)
- * Assertion: constructs with not null parameter.
- */
- public void testLoginException02() {
- LoginException lE;
- for (int i = 0; i < msgs.length; i++) {
- lE = new LoginException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), lE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", lE.getCause());
- }
- }
-
- /**
- * javax.security.auth.login.LoginException#LoginException(String msg)
- * Assertion: constructs with null parameter.
- */
- public void testLoginException03() {
- String msg = null;
- LoginException lE = new LoginException(msg);
- assertNull("getMessage() must return null.", lE.getMessage());
- assertNull("getCause() must return null", lE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java b/luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java
deleted file mode 100644
index cdd992b..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/PasswordCallbackTest.java
+++ /dev/null
@@ -1,107 +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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.callback.PasswordCallback;
-
-/**
- * Tests for <code>PasswordCallback</code> class constructors and methods.
- *
- */
-public class PasswordCallbackTest extends TestCase {
-
- /**
- * javax.security.auth.callback.PasswordCallback#PasswordCallback(String prompt, boolean echoOn)
- * javax.security.auth.callback.PasswordCallback#getPrompt()
- * javax.security.auth.callback.PasswordCallback#isEchoOn()
- */
- public void test_PasswordCallback() {
- String prompt = "promptTest";
-
- try {
- PasswordCallback pc = new PasswordCallback(prompt, true);
- assertNotNull("Null object returned", pc);
- assertEquals(prompt, pc.getPrompt());
- assertEquals(true, pc.isEchoOn());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- PasswordCallback pc = new PasswordCallback(prompt, false);
- assertNotNull("Null object returned", pc);
- assertEquals(prompt, pc.getPrompt());
- assertEquals(false, pc.isEchoOn());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- PasswordCallback pc = new PasswordCallback(null, true);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException npe) {
- }
-
- try {
- PasswordCallback pc = new PasswordCallback("", true);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException npe) {
- }
- }
-
- /**
- * javax.security.auth.callback.PasswordCallback#getPassword()
- * javax.security.auth.callback.PasswordCallback#setPassword(char[] password)
- * javax.security.auth.callback.PasswordCallback#clearPassword()
- */
- public void test_Password() {
- String prompt = "promptTest";
- char[] psw1 = "testPassword".toCharArray();
- char[] psw2 = "newPassword".toCharArray();
- PasswordCallback pc = new PasswordCallback(prompt, true);
-
- try {
- assertNull(pc.getPassword());
- pc.setPassword(psw1);
- assertEquals(psw1.length, pc.getPassword().length);
- pc.setPassword(null);
- assertNull(pc.getPassword());
- pc.setPassword(psw2);
- char[] res = pc.getPassword();
- assertEquals(psw2.length, res.length);
- for (int i = 0; i < res.length; i++) {
- assertEquals("Incorrect password was returned", psw2[i], res[i]);
- }
- pc.clearPassword();
- res = pc.getPassword();
- if (res.equals(psw2)) {
- fail("Incorrect password was returned after clear");
- }
- pc.setPassword(psw1);
- res = pc.getPassword();
- assertEquals(psw1.length, res.length);
- for (int i = 0; i < res.length; i++) {
- assertEquals("Incorrect result", psw1[i], res[i]);
- }
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java b/luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java
deleted file mode 100644
index 05741a9..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/SubjectTest.java
+++ /dev/null
@@ -1,250 +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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.AuthPermission;
-import javax.security.auth.PrivateCredentialPermission;
-import javax.security.auth.Subject;
-
-import java.util.Set;
-import java.util.HashSet;
-import java.security.Permission;
-import java.security.Principal;
-import java.security.PrivilegedAction;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.ProtectionDomain;
-
-/**
- * Tests for <code>Subject</code> class constructors and methods.
- *
- */
-public class SubjectTest extends TestCase {
-
- /**
- * javax.security.auth.Subject#Subject()
- */
- public void test_Constructor_01() {
- try {
- Subject s = new Subject();
- assertNotNull("Null object returned", s);
- assertTrue("Set of principal is not empty", s.getPrincipals().isEmpty());
- assertTrue("Set of private credentials is not empty", s.getPrivateCredentials().isEmpty());
- assertTrue("Set of public credentials is not empty", s.getPublicCredentials().isEmpty());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.security.auth.Subject#doAs(Subject subject, PrivilegedAction action)
- */
- public void test_doAs_01() {
- Subject subj = new Subject();
- PrivilegedAction<Object> pa = new myPrivilegedAction();
- PrivilegedAction<Object> paNull = null;
-
- try {
- Object obj = Subject.doAs(null, pa);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAs(subj, pa);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAs(subj, paNull);
- fail("NullPointerException wasn't thrown");
- } catch (NullPointerException npe) {
- }
- }
-
- /**
- * javax.security.auth.Subject#doAs(Subject subject, PrivilegedExceptionAction action)
- */
- public void test_doAs_02() {
- Subject subj = new Subject();
- PrivilegedExceptionAction<Object> pea = new myPrivilegedExceptionAction();
- PrivilegedExceptionAction<Object> peaNull = null;
-
- try {
- Object obj = Subject.doAs(null, pea);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAs(subj, pea);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAs(subj, peaNull);
- fail("NullPointerException wasn't thrown");
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of NullPointerException");
- }
-
- try {
- Subject.doAs(subj, new PrivilegedExceptionAction<Object>(){
- public Object run() throws PrivilegedActionException {
- throw new PrivilegedActionException(null);
- }
- });
- fail("PrivilegedActionException wasn't thrown");
- } catch (PrivilegedActionException e) {
- }
- }
-
- /**
- * javax.security.auth.Subject#doAsPrivileged(Subject subject,
- * PrivilegedAction action,
- * AccessControlContext acc)
- */
- public void test_doAsPrivileged_01() {
- Subject subj = new Subject();
- PrivilegedAction<Object> pa = new myPrivilegedAction();
- PrivilegedAction<Object> paNull = null;
- AccessControlContext acc = AccessController.getContext();
-
- try {
- Object obj = Subject.doAsPrivileged(null, pa, acc);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAsPrivileged(subj, pa, acc);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAsPrivileged(subj, paNull, acc);
- fail("NullPointerException wasn't thrown");
- } catch (NullPointerException npe) {
- }
- }
-
- /**
- * javax.security.auth.Subject#doAsPrivileged(Subject subject,
- * PrivilegedExceptionAction action,
- * AccessControlContext acc)
- */
- public void test_doAsPrivileged_02() {
- Subject subj = new Subject();
- PrivilegedExceptionAction<Object> pea = new myPrivilegedExceptionAction();
- PrivilegedExceptionAction<Object> peaNull = null;
- AccessControlContext acc = AccessController.getContext();
-
- try {
- Object obj = Subject.doAsPrivileged(null, pea, acc);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAsPrivileged(subj, pea, acc);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Object obj = Subject.doAsPrivileged(subj, peaNull, acc);
- fail("NullPointerException wasn't thrown");
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of NullPointerException");
- }
-
- try {
- Subject.doAsPrivileged(subj, new PrivilegedExceptionAction<Object>(){
- public Object run() throws PrivilegedActionException {
- throw new PrivilegedActionException(null);
- }
- }, acc);
- fail("PrivilegedActionException wasn't thrown");
- } catch (PrivilegedActionException e) {
- }
- }
-
- /**
- * javax.security.auth.Subject#getSubject(AccessControlContext acc)
- */
- public void test_getSubject() {
- Subject subj = new Subject();
- AccessControlContext acc = new AccessControlContext(new ProtectionDomain[0]);
-
- try {
- assertNull(Subject.getSubject(acc));
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * javax.security.auth.Subject#toString()
- */
- public void test_toString() {
- Subject subj = new Subject();
-
- try {
- assertNotNull("Null returned", subj.toString());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.security.auth.Subject#hashCode()
- */
- public void test_hashCode() {
- Subject subj = new Subject();
-
- try {
- assertNotNull("Null returned", subj.hashCode());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-}
-
-
-class myPrivilegedAction implements PrivilegedAction <Object> {
- myPrivilegedAction(){}
- public Object run() {
- return new Object();
- }
-}
-
-class myPrivilegedExceptionAction implements PrivilegedExceptionAction <Object> {
- myPrivilegedExceptionAction(){}
- public Object run() {
- return new Object();
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.java b/luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.java
deleted file mode 100644
index abef563..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/UnsupportedCallbackExceptionTest.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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.callback.Callback;
-
-/**
- * Tests for <code>UnsupportedCallbackException</code> class constructors and methods.
- *
- */
-public class UnsupportedCallbackExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback)
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#getCallback()
- * Assertion: constructs with null parameter.
- */
- public void testUnsupportedCallbackException01() {
- Callback c = null;
- UnsupportedCallbackException ucE = new UnsupportedCallbackException(c);
- assertNull("getMessage() must return null.", ucE.getMessage());
- assertNull("getCallback() must return null", ucE.getCallback());
- }
-
- /**
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback)
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#getCallback()
- * Assertion: constructs with not null parameter.
- */
- public void testUnsupportedCallbackException02() {
- myCallback c = new myCallback();
- assertNotNull("Callback object is null", c);
- UnsupportedCallbackException ucE = new UnsupportedCallbackException(c);
- assertNull("getMessage() must return null.", ucE.getMessage());
- assertEquals("Incorrect callback object was returned", c, ucE.getCallback());
- }
-
- /**
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
- * Assertion: constructs with null callback parameter and null message.
- */
- public void testUnsupportedCallbackException03() {
- UnsupportedCallbackException ucE = new UnsupportedCallbackException(null, null);
- assertNull("getMessage() must return null.", ucE.getMessage());
- assertNull("getCallback() must return null.", ucE.getCallback());
- }
-
- /**
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
- * Assertion: constructs with null callback parameter and not null message.
- */
- public void testUnsupportedCallbackException04() {
- UnsupportedCallbackException ucE;
- for (int i = 0; i < msgs.length; i++) {
- ucE = new UnsupportedCallbackException(null, msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), ucE.getMessage(), msgs[i]);
- assertNull("getCallback() must return null.", ucE.getCallback());
- }
- }
-
- /**
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
- * Assertion: constructs with not null callback parameter and null message.
- */
- public void testUnsupportedCallbackException05() {
- myCallback c = new myCallback();
- assertNotNull("Callback object is null", c);
- UnsupportedCallbackException ucE = new UnsupportedCallbackException(c, null);
- assertNull("getMessage() must return null.", ucE.getMessage());
- assertEquals("Incorrect callback object was returned", c, ucE.getCallback());
- }
-
- /**
- * javax.security.auth.callback.UnsupportedCallbackExceptionTest#UnsupportedCallbackException(Callback callback, String msg)
- * Assertion: constructs with not null parameters.
- */
- public void testUnsupportedCallbackException06() {
- myCallback c = new myCallback();
- assertNotNull("Callback object is null", c);
- UnsupportedCallbackException ucE;
- for (int i = 0; i < msgs.length; i++) {
- ucE = new UnsupportedCallbackException(c, msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), ucE.getMessage(), msgs[i]);
- assertEquals("Incorrect callback object was returned", c, ucE.getCallback());
- }
- }
-}
-
-class myCallback implements Callback {
- myCallback(){
- }
-}
-
diff --git a/luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java b/luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java
deleted file mode 100644
index 7cb81bb..0000000
--- a/luni/src/test/java/tests/api/javax/security/auth/X500PrincipalTest.java
+++ /dev/null
@@ -1,270 +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 tests.api.javax.security.auth;
-
-import junit.framework.TestCase;
-
-import javax.security.auth.x500.X500Principal;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import org.apache.harmony.security.tests.support.cert.TestUtils;
-
-/**
- * Tests for <code>X500Principal</code> class constructors and methods.
- *
- */
-public class X500PrincipalTest extends TestCase {
-
- /**
- * javax.security.auth.x500.X500Principal#X500Principal(String name)
- */
- public void test_X500Principal_01() {
- String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
-
- try {
- X500Principal xpr = new X500Principal(name);
- assertNotNull("Null object returned", xpr);
- String resName = xpr.getName();
- assertEquals(name, resName);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- X500Principal xpr = new X500Principal((String)null);
- fail("NullPointerException wasn't thrown");
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of NullPointerException");
- }
-
- try {
- X500Principal xpr = new X500Principal("X500PrincipalName");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#X500Principal(InputStream is)
- */
- public void test_X500Principal_02() {
- String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
- byte[] ba = getByteArray(TestUtils.getX509Certificate_v1());
- ByteArrayInputStream is = new ByteArrayInputStream(ba);
- InputStream isNull = null;
-
- try {
- X500Principal xpr = new X500Principal(is);
- assertNotNull("Null object returned", xpr);
- byte[] resArray = xpr.getEncoded();
- assertEquals(ba.length, resArray.length);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- X500Principal xpr = new X500Principal(isNull);
- fail("NullPointerException wasn't thrown");
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of NullPointerException");
- }
-
- is = new ByteArrayInputStream(name.getBytes());
- try {
- X500Principal xpr = new X500Principal(is);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#X500Principal(byte[] name)
- */
- public void test_X500Principal_03() {
- String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
- byte[] ba = getByteArray(TestUtils.getX509Certificate_v1());
- byte[] baNull = null;
-
- try {
- X500Principal xpr = new X500Principal(ba);
- assertNotNull("Null object returned", xpr);
- byte[] resArray = xpr.getEncoded();
- assertEquals(ba.length, resArray.length);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- X500Principal xpr = new X500Principal(baNull);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- ba = name.getBytes();
- try {
- X500Principal xpr = new X500Principal(ba);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#getName()
- */
- public void test_getName() {
- String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
- X500Principal xpr = new X500Principal(name);
- try {
- String resName = xpr.getName();
- assertEquals(name, resName);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#getName(String format)
- */
- public void test_getName_Format() {
- String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
- String expectedName = "cn=duke,ou=javasoft,o=sun microsystems,c=us";
- X500Principal xpr = new X500Principal(name);
- try {
- String resName = xpr.getName(X500Principal.CANONICAL);
- assertEquals(expectedName, resName);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- expectedName = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US";
- try {
- String resName = xpr.getName(X500Principal.RFC1779);
- assertEquals(expectedName, resName);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- String resName = xpr.getName(X500Principal.RFC2253);
- assertEquals(name, resName);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- String resName = xpr.getName(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- }
- try {
- String resName = xpr.getName("RFC2254");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#hashCode()
- */
- public void test_hashCode() {
- String name = "CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US";
- X500Principal xpr = new X500Principal(name);
- try {
- int res = xpr.hashCode();
- assertNotNull(res);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#toString()
- */
- public void test_toString() {
- String name = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US";
- X500Principal xpr = new X500Principal(name);
- try {
- String res = xpr.toString();
- assertNotNull(res);
- assertEquals(name, res);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#getEncoded()
- */
- public void test_getEncoded() {
- byte[] ba = getByteArray(TestUtils.getX509Certificate_v1());
- X500Principal xpr = new X500Principal(ba);
- try {
- byte[] res = xpr.getEncoded();
- assertNotNull(res);
- assertEquals(ba.length, res.length);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * javax.security.auth.x500.X500Principal#equals(Object o)
- */
- public void test_equals() {
- String name1 = "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US";
- String name2 = "cn=duke,ou=javasoft,o=sun microsystems,c=us";
- String name3 = "CN=Alex Astapchuk, OU=SSG, O=Intel ZAO, C=RU";
- X500Principal xpr1 = new X500Principal(name1);
- X500Principal xpr2 = new X500Principal(name2);
- X500Principal xpr3 = new X500Principal(name3);
- try {
- assertTrue("False returned", xpr1.equals(xpr2));
- assertFalse("True returned", xpr1.equals(xpr3));
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- private byte[] getByteArray(byte[] array) {
- byte[] x = null;
- try {
- ByteArrayInputStream is = new ByteArrayInputStream(array);
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- X509Certificate cert = (X509Certificate)cf.generateCertificate(is);
- X500Principal xx = cert.getIssuerX500Principal();
- x = xx.getEncoded();
- } catch (Exception e) {
- return null;
- }
- return x;
- }
-}
-
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.java
deleted file mode 100644
index 53fbd9f..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateEncodingExceptionTest.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.
- */
-
-/**
-* @author Vera Y. Petrashkova
-* @version $Revision$
-*/
-
-package tests.api.javax.security.cert;
-
-import junit.framework.TestCase;
-
-import javax.security.cert.CertificateEncodingException;
-
-/**
- * Tests for <code>DigestException</code> class constructors and methods.
- *
- */
-public class CertificateEncodingExceptionTest extends TestCase {
-
- static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>CertificateEncodingException()</code> constructor
- * Assertion: constructs CertificateEncodingException with no detail message
- */
- public void testCertificateEncodingException01() {
- CertificateEncodingException tE = new CertificateEncodingException();
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-
- /**
- * Test for <code>CertificateEncodingException(String)</code> constructor
- * Assertion: constructs CertificateEncodingException with detail message
- * msg. Parameter <code>msg</code> is not null.
- */
- public void testCertificateEncodingException02() {
- CertificateEncodingException tE;
- for (int i = 0; i < msgs.length; i++) {
- tE = new CertificateEncodingException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), tE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", tE.getCause());
- }
- }
-
- /**
- * Test for <code>CertificateEncodingException(String)</code> constructor
- * Assertion: constructs CertificateEncodingException when <code>msg</code>
- * is null
- */
- public void testCertificateEncodingException03() {
- String msg = null;
- CertificateEncodingException tE = new CertificateEncodingException(msg);
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java
deleted file mode 100644
index ccc3a2c..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateExceptionTest.java
+++ /dev/null
@@ -1,79 +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.
- */
-
-/**
-* @author Vera Y. Petrashkova
-* @version $Revision$
-*/
-
-package tests.api.javax.security.cert;
-
-import junit.framework.TestCase;
-
-import javax.security.cert.CertificateException;
-
-
-/**
- * Tests for <code>DigestException</code> class constructors and methods.
- *
- */
-public class CertificateExceptionTest extends TestCase {
-
- static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>CertificateException()</code> constructor Assertion:
- * constructs CertificateException with no detail message
- */
- public void testCertificateException01() {
- CertificateException tE = new CertificateException();
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-
- /**
- * Test for <code>CertificateException(String)</code> constructor
- * Assertion: constructs CertificateException with detail message msg.
- * Parameter <code>msg</code> is not null.
- */
- public void testCertificateException02() {
- CertificateException tE;
- for (int i = 0; i < msgs.length; i++) {
- tE = new CertificateException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), tE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", tE.getCause());
- }
- }
-
- /**
- * Test for <code>CertificateException(String)</code> constructor
- * Assertion: constructs CertificateException when <code>msg</code> is
- * null
- */
- public void testCertificateException03() {
- String msg = null;
- CertificateException tE = new CertificateException(msg);
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java
deleted file mode 100644
index d0e94e3..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateExpiredExceptionTest.java
+++ /dev/null
@@ -1,79 +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.
- */
-
-/**
-* @author Vera Y. Petrashkova
-* @version $Revision$
-*/
-
-package tests.api.javax.security.cert;
-
-import junit.framework.TestCase;
-
-import javax.security.cert.CertificateExpiredException;
-
-
-/**
- * Tests for <code>DigestException</code> class constructors and methods.
- *
- */
-public class CertificateExpiredExceptionTest extends TestCase {
-
- static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>CertificateExpiredException()</code> constructor
- * Assertion: constructs CertificateExpiredException with no detail message
- */
- public void testCertificateExpiredException01() {
- CertificateExpiredException tE = new CertificateExpiredException();
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-
- /**
- * Test for <code>CertificateExpiredException(String)</code> constructor
- * Assertion: constructs CertificateExpiredException with detail message
- * msg. Parameter <code>msg</code> is not null.
- */
- public void testCertificateExpiredException02() {
- CertificateExpiredException tE;
- for (int i = 0; i < msgs.length; i++) {
- tE = new CertificateExpiredException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), tE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", tE.getCause());
- }
- }
-
- /**
- * Test for <code>CertificateExpiredException(String)</code> constructor
- * Assertion: constructs CertificateExpiredException when <code>msg</code>
- * is null
- */
- public void testCertificateExpiredException03() {
- String msg = null;
- CertificateExpiredException tE = new CertificateExpiredException(msg);
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java
deleted file mode 100644
index c746648..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateNotYetValidExceptionTest.java
+++ /dev/null
@@ -1,81 +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.
- */
-
-/**
-* @author Vera Y. Petrashkova
-* @version $Revision$
-*/
-
-package tests.api.javax.security.cert;
-
-import junit.framework.TestCase;
-
-import javax.security.cert.CertificateNotYetValidException;
-
-
-/**
- * Tests for <code>DigestException</code> class constructors and methods.
- *
- */
-public class CertificateNotYetValidExceptionTest extends TestCase {
-
- static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>CertificateNotYetValidException()</code> constructor
- * Assertion: constructs CertificateNotYetValidException with no detail
- * message
- */
- public void testCertificateNotYetValidException01() {
- CertificateNotYetValidException tE = new CertificateNotYetValidException();
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-
- /**
- * Test for <code>CertificateNotYetValidException(String)</code>
- * constructor Assertion: constructs CertificateNotYetValidException with
- * detail message msg. Parameter <code>msg</code> is not null.
- */
- public void testCertificateNotYetValidException02() {
- CertificateNotYetValidException tE;
- for (int i = 0; i < msgs.length; i++) {
- tE = new CertificateNotYetValidException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), tE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", tE.getCause());
- }
- }
-
- /**
- * Test for <code>CertificateNotYetValidException(String)</code>
- * constructor Assertion: constructs CertificateNotYetValidException when
- * <code>msg</code> is null
- */
- public void testCertificateNotYetValidException03() {
- String msg = null;
- CertificateNotYetValidException tE = new CertificateNotYetValidException(
- msg);
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.java
deleted file mode 100644
index bc07ff6..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateParsingExceptionTest.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.
- */
-
-/**
-* @author Vera Y. Petrashkova
-* @version $Revision$
-*/
-
-package tests.api.javax.security.cert;
-
-import junit.framework.TestCase;
-
-import javax.security.cert.CertificateParsingException;
-
-
-/**
- * Tests for <code>DigestException</code> class constructors and methods.
- *
- */
-public class CertificateParsingExceptionTest extends TestCase {
-
-
- static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>CertificateParsingException()</code> constructor
- * Assertion: constructs CertificateParsingException with no detail message
- */
- public void testCertificateParsingException01() {
- CertificateParsingException tE = new CertificateParsingException();
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-
- /**
- * Test for <code>CertificateParsingException(String)</code> constructor
- * Assertion: constructs CertificateParsingException with detail message
- * msg. Parameter <code>msg</code> is not null.
- */
- public void testCertificateParsingException02() {
- CertificateParsingException tE;
- for (int i = 0; i < msgs.length; i++) {
- tE = new CertificateParsingException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), tE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", tE.getCause());
- }
- }
-
- /**
- * Test for <code>CertificateParsingException(String)</code> constructor
- * Assertion: constructs CertificateParsingException when <code>msg</code>
- * is null
- */
- public void testCertificateParsingException03() {
- String msg = null;
- CertificateParsingException tE = new CertificateParsingException(msg);
- assertNull("getMessage() must return null.", tE.getMessage());
- assertNull("getCause() must return null", tE.getCause());
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java
deleted file mode 100644
index da1c7a0..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java
+++ /dev/null
@@ -1,159 +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.
- */
-
-/**
- * @author Alexander Y. Kleymenov
- * @version $Revision$
- */
-
-package tests.api.javax.security.cert;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PublicKey;
-import java.security.SignatureException;
-
-import javax.security.cert.Certificate;
-import javax.security.cert.CertificateEncodingException;
-import javax.security.cert.CertificateException;
-
-public class CertificateTest extends TestCase {
-
- /**
- * The stub class used for testing of non abstract methods.
- */
- private class TBTCert extends Certificate {
- public byte[] getEncoded() throws CertificateEncodingException {
- return null;
- }
-
- public void verify(PublicKey key) throws CertificateException,
- NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
- }
-
- public void verify(PublicKey key, String sigProvider)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
- }
-
- public String toString() {
- return "TBTCert";
- }
-
- public PublicKey getPublicKey() {
- return null;
- }
- }
-
- /**
- * Test for <code>Certificate()</code> constructor<br>
- */
- public final void testCertificate() {
- TBTCert tbt_cert = new TBTCert();
-
- assertNull("Public key should be null", tbt_cert.getPublicKey());
- assertEquals("Wrong string representation for Certificate", "TBTCert", tbt_cert.toString());
- }
-
- /**
- * equals(Object obj) method testing. Tests the correctness of equal
- * operation: it should be reflexive, symmetric, transitive, consistent and
- * should be false on null object.
- */
- public void testEquals() {
- TBTCert tbt_cert = new TBTCert() {
- public byte[] getEncoded() {
- return new byte[] { 1, 2, 3 };
- }
- };
-
- TBTCert tbt_cert_1 = new TBTCert() {
- public byte[] getEncoded() {
- return new byte[] { 1, 2, 3 };
- }
- };
-
- TBTCert tbt_cert_2 = new TBTCert() {
- public byte[] getEncoded() {
- return new byte[] { 1, 2, 3 };
- }
- };
-
- TBTCert tbt_cert_3 = new TBTCert() {
- public byte[] getEncoded() {
- return new byte[] { 3, 2, 1 };
- }
- };
-
- // checking for reflexive law:
- assertTrue("The equivalence relation should be reflexive.", tbt_cert
- .equals(tbt_cert));
-
- assertEquals(
- "The Certificates with equal encoded form should be equal",
- tbt_cert, tbt_cert_1);
- // checking for symmetric law:
- assertTrue("The equivalence relation should be symmetric.", tbt_cert_1
- .equals(tbt_cert));
-
- assertEquals(
- "The Certificates with equal encoded form should be equal",
- tbt_cert_1, tbt_cert_2);
- // checking for transitive law:
- assertTrue("The equivalence relation should be transitive.", tbt_cert
- .equals(tbt_cert_2));
-
- assertFalse("Should not be equal to null object.", tbt_cert
- .equals(null));
-
- assertFalse("The Certificates with differing encoded form "
- + "should not be equal", tbt_cert.equals(tbt_cert_3));
- assertFalse("The Certificates should not be equals to the object "
- + "which is not an instance of Certificate", tbt_cert
- .equals(new Object()));
- }
-
- /**
- * hashCode() method testing.
- */
- public void testHashCode() {
- TBTCert tbt_cert = new TBTCert() {
- public byte[] getEncoded() {
- return new byte[] { 1, 2, 3 };
- }
- };
- TBTCert tbt_cert_1 = new TBTCert() {
- public byte[] getEncoded() {
- return new byte[] { 1, 2, 3 };
- }
- };
-
- assertTrue("Equal objects should have the same hash codes.", tbt_cert
- .hashCode() == tbt_cert_1.hashCode());
- }
-
- public static Test suite() {
- return new TestSuite(CertificateTest.class);
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java b/luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java
deleted file mode 100644
index e937db9..0000000
--- a/luni/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java
+++ /dev/null
@@ -1,788 +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.
- */
-
-/**
- * @author Alexander Y. Kleymenov
- * @version $Revision$
- */
-
-package tests.api.javax.security.cert;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.SideEffect;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-import tests.targets.security.cert.CertificateFactoryTestX509;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Principal;
-import java.security.Provider;
-import java.security.PublicKey;
-import java.security.Security;
-import java.security.SignatureException;
-import java.security.Provider.Service;
-import java.security.cert.CertificateFactory;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Set;
-import java.util.logging.Logger;
-
-import javax.security.cert.Certificate;
-import javax.security.cert.CertificateEncodingException;
-import javax.security.cert.CertificateException;
-import javax.security.cert.CertificateExpiredException;
-import javax.security.cert.CertificateNotYetValidException;
-import javax.security.cert.X509Certificate;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import tests.targets.security.cert.CertificateFactoryTestX509;
-
-/**
- */
-public class X509CertificateTest extends TestCase {
-
- // Testing data was generated by using of classes
- // from org.apache.harmony.security.asn1 package encoded
- // by org.apache.harmony.misc.Base64 class.
-
- private static String base64cert = "-----BEGIN CERTIFICATE-----\n"
- + "MIIC+jCCAragAwIBAgICAiswDAYHKoZIzjgEAwEBADAdMRswGQYDVQQKExJDZXJ0a"
- + "WZpY2F0ZSBJc3N1ZXIwIhgPMTk3MDAxMTIxMzQ2NDBaGA8xOTcwMDEyNDAzMzMyMF"
- + "owHzEdMBsGA1UEChMUU3ViamVjdCBPcmdhbml6YXRpb24wGTAMBgcqhkjOOAQDAQE"
- + "AAwkAAQIDBAUGBwiBAgCqggIAVaOCAhQwggIQMA8GA1UdDwEB/wQFAwMBqoAwEgYD"
- + "VR0TAQH/BAgwBgEB/wIBBTAUBgNVHSABAf8ECjAIMAYGBFUdIAAwZwYDVR0RAQH/B"
- + "F0wW4EMcmZjQDgyMi5OYW1lggdkTlNOYW1lpBcxFTATBgNVBAoTDE9yZ2FuaXphdG"
- + "lvboYaaHR0cDovL3VuaWZvcm0uUmVzb3VyY2UuSWSHBP///wCIByoDolyDsgMwDAY"
- + "DVR0eAQH/BAIwADAMBgNVHSQBAf8EAjAAMIGZBgNVHSUBAf8EgY4wgYsGBFUdJQAG"
- + "CCsGAQUFBwMBBggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDBggrBgEFBQcDB"
- + "AYIKwYBBQUHAwUGCCsGAQUFBwMGBggrBgEFBQcDBwYIKwYBBQUHAwgGCCsGAQUFBw"
- + "MJBggrBgEFBQgCAgYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GA1UdNgEB/wQDAgE"
- + "BMA4GBCpNhgkBAf8EAwEBATBkBgNVHRIEXTBbgQxyZmNAODIyLk5hbWWCB2ROU05h"
- + "bWWkFzEVMBMGA1UEChMMT3JnYW5pemF0aW9uhhpodHRwOi8vdW5pZm9ybS5SZXNvd"
- + "XJjZS5JZIcE////AIgHKgOiXIOyAzAJBgNVHR8EAjAAMAoGA1UdIwQDAQEBMAoGA1"
- + "UdDgQDAQEBMAoGA1UdIQQDAQEBMAwGByqGSM44BAMBAQADMAAwLQIUAL4QvoazNWP"
- + "7jrj84/GZlhm09DsCFQCBKGKCGbrP64VtUt4JPmLjW1VxQA==\n"
- + "-----END CERTIFICATE-----";
-
- /*
- * a self-signed certificate
- */
- private static final String selfSignedCert = "-----BEGIN CERTIFICATE-----\n" +
- "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ" +
- "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k" +
- "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh" +
- "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ" +
- "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw" +
- "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB" +
- "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB" +
- "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3" +
- "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU" +
- "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G" +
- "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q" +
- "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu" +
- "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV" +
- "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C" +
- "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF" +
- "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL" +
- "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T" +
- "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n" +
- "-----END CERTIFICATE-----";
-
- private java.security.cert.X509Certificate cert;
-
- private javax.security.cert.X509Certificate tbt_cert;
-
- private java.security.cert.X509Certificate javaCert;
-
- private Provider myProvider;
-
- private javax.security.cert.X509Certificate javaxCert;
-
- private java.security.cert.Certificate javaSSCert;
-
- private Provider mySSProvider;
-
- private Certificate javaxSSCert;
-
- @Override
- protected void setUp() throws Exception {
- try {
- ByteArrayInputStream bais = new ByteArrayInputStream(base64cert
- .getBytes());
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- this.cert = (java.security.cert.X509Certificate) cf
- .generateCertificate(bais);
- this.tbt_cert = X509Certificate.getInstance(cert.getEncoded());
-
- // non self signed cert
- this.javaCert = (java.security.cert.X509Certificate)cf
- .generateCertificate(new ByteArrayInputStream(selfSignedCert.getBytes()));
- this.javaxCert = X509Certificate.getInstance(javaCert.getEncoded());
- myProvider = cf.getProvider();
- Security.addProvider(myProvider);
-
- // self signed cert
- this.javaSSCert = cf.generateCertificate(new ByteArrayInputStream(
- selfSignedCert.getBytes()));
- this.javaxSSCert = X509Certificate.getInstance(javaCert
- .getEncoded());
- mySSProvider = cf.getProvider();
- Security.addProvider(mySSProvider);
-
- } catch (java.security.cert.CertificateException e) {
- // The requested certificate type is not available.
- // Test pass..
- this.cert = null;
- Logger.global.warning("Error in test setup: Certificate type not supported");
- } catch (javax.security.cert.CertificateException e) {
- // The requested certificate type is not available.
- // Test pass..
- this.cert = null;
- Logger.global.warning("Error in test setup: Certificate type not supported");
- }
- }
-
- /**
- * X509Certificate() constructor testing.
- * {@link X509Certificate#X509Certificate() }
- */
- public void testConstructor() {
- //Direct constructor, check if it throws an exception
- X509Certificate cert = new MyCertificate();
- }
-
- /**
- * getInstance(InputStream inStream) method testing.
- */
- public void testGetInstance1() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- try {
- ByteArrayInputStream bais = new ByteArrayInputStream(cert
- .getEncoded());
-
- X509Certificate.getInstance(bais);
- } catch (java.security.cert.CertificateEncodingException e) {
- fail("Unexpected CertificateEncodingException was thrown.");
- } catch (CertificateEncodingException e) {
- fail("Unexpected CertificateEncodingException was thrown.");
- } catch (CertificateException e) {
- // The requested certificate type is not available.
- // Test pass..
- }
-
- // Regression for HARMONY-756
- try {
- X509Certificate.getInstance((InputStream) null);
- fail("No expected CertificateException");
- } catch (CertificateException e) {
- // expected;
- }
- }
-
- /**
- * getInstance(byte[] certData) method testing.
- * @throws CertificateEncodingException
- * @throws java.security.cert.CertificateEncodingException
- */
- public void testGetInstance2() throws java.security.cert.CertificateEncodingException, CertificateEncodingException {
- boolean certificateException = false;
- X509Certificate c = null;
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- try {
- c = X509Certificate.getInstance(cert.getEncoded());
- } catch (java.security.cert.CertificateEncodingException e) {
- fail("Unexpected CertificateEncodingException was thrown.");
- } catch (CertificateException e) {
- // The requested certificate type is not available.
- // Test pass..
- certificateException = true;
-
- }
-
- if (! certificateException) {
- assertNotNull(c);
- assertTrue(Arrays.equals(c.getEncoded(),cert.getEncoded() ));
- }
-
- try {
- X509Certificate.getInstance(new byte[]{(byte) 1 });
- } catch (CertificateException e) {
- //ok
- }
-
- // Regression for HARMONY-756
- try {
- X509Certificate.getInstance((byte[]) null);
- fail("No expected CertificateException");
- } catch (CertificateException e) {
- // expected;
- }
-
- }
-
- /**
- * checkValidity() method testing.
- * @throws CertificateNotYetValidException
- * @throws CertificateExpiredException
- * @throws java.security.cert.CertificateExpiredException
- * @throws java.security.cert.CertificateNotYetValidException
- */
- public void testCheckValidity1() throws CertificateExpiredException, CertificateNotYetValidException, java.security.cert.CertificateExpiredException, java.security.cert.CertificateNotYetValidException {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- Date date = new Date();
- Date nb_date = tbt_cert.getNotBefore();
- Date na_date = tbt_cert.getNotAfter();
- try {
- tbt_cert.checkValidity();
- assertFalse("CertificateExpiredException expected", date
- .compareTo(na_date) > 0);
- assertFalse("CertificateNotYetValidException expected", date
- .compareTo(nb_date) < 0);
- } catch (CertificateExpiredException e) {
- assertTrue("Unexpected CertificateExpiredException was thrown",
- date.compareTo(na_date) > 0);
- } catch (CertificateNotYetValidException e) {
- assertTrue("Unexpected CertificateNotYetValidException was thrown",
- date.compareTo(nb_date) < 0);
- }
-
- try {
- tbt_cert.checkValidity();
- } catch (CertificateExpiredException e) {
- // ok
- }
-
- try {
- cert.checkValidity();
- } catch (java.security.cert.CertificateExpiredException e) {
- // ok
- }
-
- }
-
- /**
- * checkValidity(Date date) method testing.
- * @throws CertificateNotYetValidException
- * @throws CertificateExpiredException
- */
- public void testCheckValidity2() throws CertificateNotYetValidException, CertificateExpiredException {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- Date[] date = new Date[8];
- Calendar calendar = Calendar.getInstance();
- for (int i = 0; i < date.length; i++) {
- calendar.set(i * 500, Calendar.JANUARY, 1);
- date[i] = calendar.getTime();
- }
- Date nb_date = tbt_cert.getNotBefore();
- Date na_date = tbt_cert.getNotAfter();
- for (int i = 0; i < date.length; i++) {
- try {
- tbt_cert.checkValidity(date[i]);
- assertFalse("CertificateExpiredException expected", date[i]
- .compareTo(na_date) > 0);
- assertFalse("CertificateNotYetValidException expected", date[i]
- .compareTo(nb_date) < 0);
- } catch (CertificateExpiredException e) {
- assertTrue("Unexpected CertificateExpiredException was thrown",
- date[i].compareTo(na_date) > 0);
- } catch (CertificateNotYetValidException e) {
- assertTrue("Unexpected CertificateNotYetValidException "
- + "was thrown", date[i].compareTo(nb_date) < 0);
- }
- }
-
- Calendar calendarNow = Calendar.getInstance();
-
- try {
- tbt_cert.checkValidity(calendarNow.getTime());
- } catch (CertificateExpiredException e) {
- //ok
- }
-
- Calendar calendarPast = GregorianCalendar.getInstance();
- calendarPast.clear();
-
- try {
- tbt_cert.checkValidity(calendarPast.getTime());
- } catch (CertificateNotYetValidException e) {
- //ok
- }
-
- }
-
- /**
- * getVersion() method testing.
- */
- public void testGetVersion() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The version is not correct.", tbt_cert.getVersion(), 2);
- }
-
- /**
- * getSerialNumber() method testing.
- */
- public void testGetSerialNumber() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The serial number is not correct.", tbt_cert
- .getSerialNumber(), cert.getSerialNumber());
- }
-
- /**
- * getIssuerDN() method testing.
- */
- public void testGetIssuerDN() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- Logger.global.warning("testGetIssuerDN: error in test setup.");
- }
- assertEquals("The issuer DN is not correct.", tbt_cert.getIssuerDN(),
- cert.getIssuerDN());
- }
-
- /**
- * getSubjectDN() method testing.
- */
- public void testGetSubjectDN() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The subject DN is not correct.", tbt_cert.getSubjectDN(),
- cert.getSubjectDN());
- }
-
- /**
- * getNotBefore() method testing.
- */
- public void testGetNotBefore() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The NotBefore date is not correct.", tbt_cert
- .getNotBefore(), cert.getNotBefore());
- }
-
- /**
- * getNotAfter() method testing.
- */
- public void testGetNotAfter() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The NotAfter date is not correct.", tbt_cert
- .getNotAfter(), cert.getNotAfter());
- }
-
- /**
- * getSigAlgName() method testing.
- */
- public void testGetSigAlgName() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The name of signature algorithm is not correct.",
- tbt_cert.getSigAlgName(), cert.getSigAlgName());
- }
-
- /**
- * getSigAlgOID() method testing.
- */
- public void testGetSigAlgOID() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertEquals("The name of OID of signature algorithm is not correct.",
- tbt_cert.getSigAlgOID(), cert.getSigAlgOID());
- }
-
- /**
- * getSigAlgParams() method testing.
- */
- public void testGetSigAlgParams() {
- if (this.cert == null) {
- // The requested certificate type is not available.
- // Test can not be applied.
- return;
- }
- assertTrue("The byte array with encoded algorithm parameters "
- + "is not correct.", Arrays.equals(tbt_cert.getSigAlgParams(),
- cert.getSigAlgParams()));
- }
-
- /**
- * The stub class used for testing of non abstract methods.
- */
- private class MyCertificate extends X509Certificate {
-
- public MyCertificate() {
- super();
- }
-
- @Override
- public void checkValidity() throws CertificateExpiredException,
- CertificateNotYetValidException {
- }
-
- @Override
- public void checkValidity(Date arg0)
- throws CertificateExpiredException,
- CertificateNotYetValidException {
- }
-
- @Override
- public Principal getIssuerDN() {
- return null;
- }
-
- @Override
- public Date getNotAfter() {
- return null;
- }
-
- @Override
- public Date getNotBefore() {
- return null;
- }
-
- @Override
- public BigInteger getSerialNumber() {
- return null;
- }
-
- @Override
- public String getSigAlgName() {
- return null;
- }
-
- @Override
- public String getSigAlgOID() {
- return null;
- }
-
- @Override
- public byte[] getSigAlgParams() {
- return null;
- }
-
- @Override
- public Principal getSubjectDN() {
- return null;
- }
-
- @Override
- public int getVersion() {
- return 0;
- }
-
- @Override
- public byte[] getEncoded() throws CertificateEncodingException {
- return null;
- }
-
- @Override
- public PublicKey getPublicKey() {
- return null;
- }
-
- @Override
- public String toString() {
- return null;
- }
-
- @Override
- public void verify(PublicKey key) throws CertificateException,
- NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
- }
-
- @Override
- public void verify(PublicKey key, String sigProvider)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
- }
- }
-
- public class MyModifiablePublicKey implements PublicKey {
-
- private PublicKey key;
- private boolean modifiedAlgo;
- private String algo;
- private String format;
- private boolean modifiedFormat;
- private boolean modifiedEncoding;
- private byte[] encoding;
-
- public MyModifiablePublicKey(PublicKey k) {
- super();
- this.key = k;
- }
-
- public String getAlgorithm() {
- if (modifiedAlgo) {
- return algo;
- } else {
- return key.getAlgorithm();
- }
- }
-
- public String getFormat() {
- if (modifiedFormat) {
- return this.format;
- } else {
- return key.getFormat();
- }
-
- }
-
- public byte[] getEncoded() {
- if (modifiedEncoding) {
- return this.encoding;
- } else {
- return key.getEncoded();
- }
-
- }
-
- public long getSerVerUID() {
- return key.serialVersionUID;
- }
-
- public void setAlgorithm(String myAlgo) {
- modifiedAlgo = true;
- this.algo = myAlgo;
- }
-
- public void setFormat(String myFormat) {
- modifiedFormat = true;
- format = myFormat;
- }
-
- public void setEncoding(byte[] myEncoded) {
- modifiedEncoding = true;
- encoding = myEncoded;
- }
- }
-
- /**
- * @throws CertificateEncodingException
- * {@link Certificate#getEncoded()}
- */
- public void testGetEncoded()
- throws CertificateEncodingException, java.security.cert.CertificateException {
- // cert = DER encoding of the ASN1.0 structure
- assertTrue(Arrays.equals(cert.getEncoded(), tbt_cert.getEncoded()));
- assertFalse(Arrays.equals(javaxCert.getEncoded(), tbt_cert.getEncoded()));
- }
-
- /**
- * {@link Certificate#getPublicKey()}
- */
- public void testGetPublicKey() {
- PublicKey key = javaxCert.getPublicKey();
- assertNotNull(key);
- assertEquals(javaxCert.getPublicKey(), javaCert.getPublicKey());
- assertEquals(key.getAlgorithm(),"RSA");
-
- key = javaxSSCert.getPublicKey();
- assertNotNull(key);
- assertEquals(key.getAlgorithm(),"RSA");
-
- //assertTrue(mySSProvider.containsKey(key));
-
- }
-
- /**
- * @throws SignatureException
- * @throws NoSuchProviderException
- * @throws NoSuchAlgorithmException
- * @throws InvalidKeyException
- * @throws CertificateException
- * {@link Certificate#verify(PublicKey)}
- */
- @SideEffect("Destroys MD5 provider, hurts succeeding tests")
- public void testVerifyPublicKey() throws InvalidKeyException,
- NoSuchAlgorithmException, NoSuchProviderException,
- SignatureException, CertificateException {
-
- // Preconditions
- assertNotNull(javaxCert.getPublicKey());
- assertNotNull(javaxSSCert.getPublicKey());
- //precondition for self signed certificates
- /*assertEquals(((X509Certificate) javaxSSCert).getIssuerDN().getName(),
- ((X509Certificate) javaxSSCert).getSubjectDN());*/
-
- // must always evaluate true for self signed
- // here not self signed:
- try {
- javaxCert.verify(javaxCert.getPublicKey());
- } catch (SignatureException e) {
- // ok
- }
-
- PublicKey k = javaxCert.getPublicKey();
-
- MyModifiablePublicKey changedEncoding = new MyModifiablePublicKey(k);
- changedEncoding
- .setEncoding(new byte[javaxCert.getEncoded().length - 1]);
-
- try {
- javaxCert.verify(tbt_cert.getPublicKey());
- } catch (InvalidKeyException e) {
- // ok
- }
-
-
- try {
- javaxCert.verify(null);
- } catch (Exception e) {
- // ok
- }
-
- try {
- javaxCert.verify(changedEncoding);
- fail("Exception expected");
- } catch (Exception e) {
- // ok
- }
-
- // following test doesn't work because the algorithm is derived from
- // somewhere else.
-
- // MyModifiablePublicKey changedAlgo = new MyModifiablePublicKey(k);
- // changedAlgo.setAlgorithm("MD5withBla");
-
- // try {
- // javaxCert.verify(changedAlgo);
- // fail("Exception expected");
- // } catch (SignatureException e) {
- // // ok
- // }
-
- // Security.removeProvider(mySSProvider.getName());
-
- // try {
- // javaxSSCert.verify(javaxSSCert.getPublicKey());
- // } catch (NoSuchProviderException e) {
- // // ok
- // }
-
- // Security.addProvider(mySSProvider);
-
- // must always evaluate true for self signed
- // javaxSSCert.verify(javaxSSCert.getPublicKey());
- }
-
- /**
- * @throws SignatureException
- * @throws NoSuchProviderException
- * @throws NoSuchAlgorithmException
- * @throws java.security.cert.CertificateException
- * @throws InvalidKeyException
- * @throws IOException
- * @throws CertificateException
- * {@link Certificate#verify(PublicKey, String)}
- */
- @SideEffect("Destroys MD5 provider, hurts succeeding tests")
- public void testVerifyPublicKeyString() throws InvalidKeyException,
- java.security.cert.CertificateException, NoSuchAlgorithmException,
- NoSuchProviderException, SignatureException, IOException,
- CertificateException {
-
- try {
- javaxCert.verify(javaxCert.getPublicKey(), myProvider.getName());
- } catch (NoSuchAlgorithmException e) {
- // ok
- }
-
- // myProvider.getService(type, algorithm)
-
- Security.removeProvider(myProvider.getName());
- try {
- javaxCert.verify(javaxCert.getPublicKey(), myProvider.getName());
- } catch (NoSuchProviderException e) {
- // ok
- }
- Security.addProvider(myProvider);
-
- Provider[] providers = Security.getProviders("Signature.MD5withRSA");
- if (providers == null || providers.length == 0) {
- fail("no Provider for Signature.MD5withRSA");
- return;
- }
-
- // self signed cert: should verify with provider
- try {
- javaxSSCert.verify(javaxSSCert.getPublicKey(),
- providers[0].getName());
- } catch (SignatureException e) {
- fail("blu");
- }
-
- }
-
- public static Test suite() {
- return new TestSuite(X509CertificateTest.class);
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java
deleted file mode 100644
index 7d79560..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderFactoryTest.java
+++ /dev/null
@@ -1,975 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import junit.framework.TestCase;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-
-public class DocumentBuilderFactoryTest extends TestCase {
-
- DocumentBuilderFactory dbf;
-
- List<String> cdataElements;
-
- List<String> textElements;
-
- List<String> commentElements;
-
- protected void setUp() throws Exception {
- super.setUp();
- dbf = DocumentBuilderFactory.newInstance();
-
- cdataElements = new ArrayList<String>();
- textElements = new ArrayList<String>();
- commentElements = new ArrayList<String>();
- }
-
- protected void tearDown() throws Exception {
- dbf = null;
- cdataElements = null;
- textElements = null;
- commentElements = null;
- super.tearDown();
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#DocumentBuilderFactory().
- */
- public void test_Constructor() {
- try {
- new DocumentBuilderFactoryChild();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#getAttribute(String).
- */
-// public void test_getAttributeLjava_lang_String() {
-// String[] attributes = {
-// "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
-// "http://java.sun.com/xml/jaxp/properties/schemaSource" };
-// Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" };
-//
-// try {
-// for (int i = 0; i < attributes.length; i++) {
-// dbf.setAttribute(attributes[i], values[i]);
-// assertEquals(values[i], dbf.getAttribute(attributes[i]));
-// }
-// } catch (IllegalArgumentException e) {
-// fail("Unexpected IllegalArgumentException" + e.getMessage());
-// } catch (Exception e) {
-// fail("Unexpected exception" + e.getMessage());
-// }
-//
-// try {
-// for (int i = 0; i < attributes.length; i++) {
-// dbf.setAttribute(null, null);
-// fail("NullPointerException expected");
-// }
-// } catch (NullPointerException e) {
-// // expected
-// }
-//
-// String[] badAttributes = {"bad1", "bad2", ""};
-// try {
-// for (int i = 0; i < badAttributes.length; i++) {
-// dbf.getAttribute(badAttributes[i]);
-// fail("IllegalArgumentException expected");
-// }
-// } catch (IllegalArgumentException e) {
-// // expected
-// }
-// }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#getFeature(String).
- */
-// TODO Fails on JDK. Why?
-// public void test_getFeatureLjava_lang_String() {
-// String[] features = { "http://xml.org/sax/features/namespaces",
-// "http://xml.org/sax/features/validation",
-// "http://xml.org/sax/features/external-general-entities" };
-// try {
-// for (int i = 0; i < features.length; i++) {
-// dbf.setFeature(features[i], true);
-// assertTrue(dbf.getFeature(features[i]));
-// }
-// } catch (ParserConfigurationException e) {
-// fail("Unexpected ParserConfigurationException " + e.getMessage());
-// }
-//
-// try {
-// for (int i = 0; i < features.length; i++) {
-// dbf.setFeature(features[i], false);
-// assertFalse(dbf.getFeature(features[i]));
-// }
-// } catch (ParserConfigurationException e) {
-// fail("Unexpected ParserConfigurationException " + e.getMessage());
-// }
-//
-// try {
-// for (int i = 0; i < features.length; i++) {
-// dbf.setFeature(null, false);
-// fail("NullPointerException expected");
-// }
-// } catch (NullPointerException e) {
-// // expected
-// } catch (ParserConfigurationException e) {
-// fail("Unexpected ParserConfigurationException" + e.getMessage());
-// }
-//
-// String[] badFeatures = {"bad1", "bad2", ""};
-// try {
-// for (int i = 0; i < badFeatures.length; i++) {
-// dbf.getFeature(badFeatures[i]);
-// fail("ParserConfigurationException expected");
-// }
-// } catch (ParserConfigurationException e) {
-// // expected
-// }
-//
-// }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#getSchema().
- * TBD getSchemas() IS NOT SUPPORTED
- */
-/* public void test_getSchema() {
- assertNull(dbf.getSchema());
- SchemaFactory sf =
- SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- try {
- Schema schema = sf.newSchema();
- dbf.setSchema(schema);
- assertNotNull(dbf.getSchema());
- } catch (SAXException sax) {
- fail("Unexpected exception " + sax.toString());
- }
- }
- */
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#isCoalescing().
- */
- public void test_isCoalescing() {
- dbf.setCoalescing(true);
- assertTrue(dbf.isCoalescing());
-
- dbf.setCoalescing(false);
- assertFalse(dbf.isCoalescing());
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#isExpandEntityReferences().
- */
- public void test_isExpandEntityReferences() {
- dbf.setExpandEntityReferences(true);
- assertTrue(dbf.isExpandEntityReferences());
-
- dbf.setExpandEntityReferences(false);
- assertFalse(dbf.isExpandEntityReferences());
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#isIgnoringComments().
- */
- public void test_isIgnoringComments() {
- dbf.setIgnoringComments(true);
- assertTrue(dbf.isIgnoringComments());
-
- dbf.setIgnoringComments(false);
- assertFalse(dbf.isIgnoringComments());
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#isIgnoringElementContentWhitespace().
- */
- public void test_isIgnoringElementContentWhitespace() {
- dbf.setIgnoringElementContentWhitespace(true);
- assertTrue(dbf.isIgnoringElementContentWhitespace());
-
- dbf.setIgnoringElementContentWhitespace(false);
- assertFalse(dbf.isIgnoringElementContentWhitespace());
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#isNamespaceAware().
- */
- public void test_isNamespaceAware() {
- dbf.setNamespaceAware(true);
- assertTrue(dbf.isNamespaceAware());
-
- dbf.setNamespaceAware(false);
- assertFalse(dbf.isNamespaceAware());
- }
-
- public void test_setIsValidating() {
- dbf.setValidating(true);
- assertTrue(dbf.isValidating());
-
- dbf.setValidating(false);
- assertFalse(dbf.isValidating());
- }
-
- public void test_isSetXIncludeAware() {
- dbf.setXIncludeAware(true);
- assertTrue(dbf.isXIncludeAware());
-
- dbf.setXIncludeAware(false);
- assertFalse(dbf.isXIncludeAware());
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#newInstance().
- */
- public void test_newInstance() {
- String className = null;
- try {
- // case 1: Try to obtain a new instance of factory by default.
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- assertNotNull(dbf);
-
- // case 2: Try to create a new instance of factory using
- // property DATATYPEFACTORY_PROPERTY
- className = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
- System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
- "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl");
-
- dbf = DocumentBuilderFactory.newInstance();
- assertNotNull(dbf);
- assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl);
-
- // case 3: Try to create a new instance of factory using Property
- String keyValuePair = "javax.xml.parsers.DocumentBuilderFactory"
- + "=" + "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl";
- ByteArrayInputStream bis = new ByteArrayInputStream(keyValuePair
- .getBytes());
- Properties prop = System.getProperties();
- prop.load(bis);
- dbf = DocumentBuilderFactory.newInstance();
- assertNotNull(dbf);
- assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl);
-
- // case 4: Check FactoryConfiguration error
- System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "");
- try {
- DocumentBuilderFactory.newInstance();
- } catch (FactoryConfigurationError fce) {
- // expected
- }
-
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- } finally {
- // Set default value of Datatype factory,
- // because of this test modifies it.
- if (className == null) {
- System.clearProperty("javax.xml.parsers.DocumentBuilderFactory");
- } else {
- System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
- className);
- }
- }
- }
-
- public void test_newDocumentBuilder() {
- // Ordinary case
- try {
- DocumentBuilder db = dbf.newDocumentBuilder();
- assertTrue(db instanceof DocumentBuilder);
- db.parse(getClass().getResourceAsStream("/simple.xml"));
- } catch(Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // Exception case
- dbf.setValidating(true);
- try {
- DocumentBuilder db = dbf.newDocumentBuilder();
- } catch(ParserConfigurationException e) {
- // Expected, since Android doesn't have a validating parser.
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setAttribute(java.lang.String,
- * java.lang.Object).
- */
-// public void test_setAttributeLjava_lang_StringLjava_lang_Object() {
-// String[] attributes = {
-// "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
-// "http://java.sun.com/xml/jaxp/properties/schemaSource" };
-// Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" };
-//
-// try {
-// for (int i = 0; i < attributes.length; i++) {
-// dbf.setAttribute(attributes[i], values[i]);
-// assertEquals(values[i], dbf.getAttribute(attributes[i]));
-// }
-// } catch (IllegalArgumentException e) {
-// fail("Unexpected IllegalArgumentException" + e.getMessage());
-// } catch (Exception e) {
-// fail("Unexpected exception" + e.getMessage());
-// }
-//
-// String[] badAttributes = {"bad1", "bad2", ""};
-// try {
-// for (int i = 0; i < badAttributes.length; i++) {
-// dbf.setAttribute(badAttributes[i], "");
-// fail("IllegalArgumentException expected");
-// }
-// } catch (IllegalArgumentException iae) {
-// // expected
-// }
-//
-// try {
-// for (int i = 0; i < attributes.length; i++) {
-// dbf.setAttribute(null, null);
-// fail("NullPointerException expected");
-// }
-// } catch (NullPointerException e) {
-// // expected
-// }
-// }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setCoalescing(boolean).
- */
- public void test_setCoalescingZ() {
- dbf.setCoalescing(true);
- assertTrue(dbf.isCoalescing());
-
- textElements.clear();
- cdataElements.clear();
- Exception parseException = null;
- DocumentBuilder parser = null;
-
- try {
- parser = dbf.newDocumentBuilder();
- ValidationErrorHandler errorHandler = new ValidationErrorHandler();
- parser.setErrorHandler(errorHandler);
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- parseException = errorHandler.getFirstException();
-
- goThroughDocument((Node) document, "");
- assertTrue(textElements
- .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
- } catch (Exception ex) {
- parseException = ex;
- }
- parser.setErrorHandler(null);
-
- if (parseException != null) {
- fail("Unexpected exception " + parseException.getMessage());
- }
-
- dbf.setCoalescing(false);
- assertFalse(dbf.isCoalescing());
-
- textElements.clear();
- cdataElements.clear();
-
- try {
- parser = dbf.newDocumentBuilder();
- ValidationErrorHandler errorHandler = new ValidationErrorHandler();
- parser.setErrorHandler(errorHandler);
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- parseException = errorHandler.getFirstException();
-
- goThroughDocument((Node) document, "");
-
- assertFalse(textElements
- .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
-
- } catch (Exception ex) {
- parseException = ex;
- }
- parser.setErrorHandler(null);
-
- if (parseException != null) {
- fail("Unexpected exception " + parseException.getMessage());
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences(boolean).
- */
- public void test_setExpandEntityReferencesZ() {
- dbf.setExpandEntityReferences(true);
- assertTrue(dbf.isExpandEntityReferences());
-
- Exception parseException = null;
- DocumentBuilder parser = null;
-
- try {
- parser = dbf.newDocumentBuilder();
- ValidationErrorHandler errorHandler = new ValidationErrorHandler();
- parser.setErrorHandler(errorHandler);
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- parseException = errorHandler.getFirstException();
-
- assertNotNull(document);
-
- } catch (Exception ex) {
- parseException = ex;
- }
- parser.setErrorHandler(null);
-
- if (parseException != null) {
- fail("Unexpected exception " + parseException.getMessage());
- }
-
- dbf.setExpandEntityReferences(false);
- assertFalse(dbf.isExpandEntityReferences());
- try {
- parser = dbf.newDocumentBuilder();
- ValidationErrorHandler errorHandler = new ValidationErrorHandler();
- parser.setErrorHandler(errorHandler);
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- parseException = errorHandler.getFirstException();
-
- assertNotNull(document);
-
- } catch (Exception ex) {
- parseException = ex;
- }
- parser.setErrorHandler(null);
-
- if (parseException != null) {
- fail("Unexpected exception " + parseException.getMessage());
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setFeature(java.lang.String).
- */
- public void test_getSetFeatureLjava_lang_String() {
- String[] features = { "http://xml.org/sax/features/namespaces",
- "http://xml.org/sax/features/validation" };
- try {
- for (int i = 0; i < features.length; i++) {
- dbf.setFeature(features[i], true);
- assertTrue(dbf.getFeature(features[i]));
- }
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException" + e.getMessage());
- }
-
- try {
- for (int i = 0; i < features.length; i++) {
- dbf.setFeature(features[i], false);
- assertFalse(dbf.getFeature(features[i]));
- }
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException" + e.getMessage());
- }
-
- try {
- for (int i = 0; i < features.length; i++) {
- dbf.setFeature(null, false);
- fail("NullPointerException expected");
- }
- } catch (NullPointerException e) {
- // expected
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException" + e.getMessage());
- }
-
- String[] badFeatures = { "bad1", "bad2", "" };
- try {
- for (int i = 0; i < badFeatures.length; i++) {
- dbf.setFeature(badFeatures[i], false);
- fail("ParserConfigurationException expected");
- }
- } catch (ParserConfigurationException e) {
- // expected
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setIgnoringComments(boolean).
- */
- public void test_setIgnoringCommentsZ() {
- commentElements.clear();
-
- dbf.setIgnoringComments(true);
- assertTrue(dbf.isIgnoringComments());
-
- try {
- DocumentBuilder parser = dbf.newDocumentBuilder();
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- goThroughDocument((Node) document, "");
- assertFalse(commentElements.contains("comment1"));
- assertFalse(commentElements.contains("comment2"));
-
- } catch (IOException e) {
- fail("Unexpected IOException " + e.getMessage());
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException " + e.getMessage());
- } catch (SAXException e) {
- fail("Unexpected SAXException " + e.getMessage());
- }
-
- commentElements.clear();
-
- dbf.setIgnoringComments(false);
- assertFalse(dbf.isIgnoringComments());
-
- try {
- DocumentBuilder parser = dbf.newDocumentBuilder();
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- goThroughDocument((Node) document, "");
- assertTrue(commentElements.contains("comment1"));
- assertTrue(commentElements.contains("comment2"));
-
- } catch (IOException e) {
- fail("Unexpected IOException " + e.getMessage());
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException " + e.getMessage());
- } catch (SAXException e) {
- fail("Unexpected SAXException " + e.getMessage());
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setIgnoringElementContentWhitespace(boolean).
- */
- public void test_setIgnoringElementContentWhitespaceZ() {
- dbf.setIgnoringElementContentWhitespace(true);
- assertTrue(dbf.isIgnoringElementContentWhitespace());
-
- try {
- DocumentBuilder parser = dbf.newDocumentBuilder();
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- assertNotNull(document);
-
- } catch (IOException e) {
- fail("Unexpected IOException " + e.getMessage());
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException " + e.getMessage());
- } catch (SAXException e) {
- fail("Unexpected SAXException " + e.getMessage());
- }
-
- dbf.setIgnoringElementContentWhitespace(false);
- assertFalse(dbf.isIgnoringElementContentWhitespace());
-
- try {
- DocumentBuilder parser = dbf.newDocumentBuilder();
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- assertNotNull(document);
-
- } catch (IOException e) {
- fail("Unexpected IOException " + e.getMessage());
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException " + e.getMessage());
- } catch (SAXException e) {
- fail("Unexpected SAXException " + e.getMessage());
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware(boolean).
- */
- public void test_setNamespaceAwareZ() {
- dbf.setNamespaceAware(true);
- assertTrue(dbf.isNamespaceAware());
-
- try {
- DocumentBuilder parser = dbf.newDocumentBuilder();
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- assertNotNull(document);
-
- } catch (IOException e) {
- fail("Unexpected IOException " + e.getMessage());
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException " + e.getMessage());
- } catch (SAXException e) {
- fail("Unexpected SAXException " + e.getMessage());
- }
-
- dbf.setNamespaceAware(false);
- assertFalse(dbf.isNamespaceAware());
-
- try {
- DocumentBuilder parser = dbf.newDocumentBuilder();
-
- Document document = parser.parse(getClass().getResourceAsStream(
- "/recipt.xml"));
-
- assertNotNull(document);
-
- } catch (IOException e) {
- fail("Unexpected IOException " + e.getMessage());
- } catch (ParserConfigurationException e) {
- fail("Unexpected ParserConfigurationException " + e.getMessage());
- } catch (SAXException e) {
- fail("Unexpected SAXException " + e.getMessage());
- }
- }
-
- public void test_getSetAttribute() {
- // Android SAX implementation doesn't support attributes, so
- // we can only make sure the expected exception is thrown.
- try {
- dbf.setAttribute("foo", new Object());
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- try {
- dbf.getAttribute("foo");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setSchema(javax.xml.validation.Schema).
- */
- /* public void test_setSchemaLjavax_xml_validation_Schema() {
- SchemaFactory sf =
- SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- try {
- Schema schema = sf.newSchema();
- dbf.setSchema(schema);
- assertNotNull(dbf.getSchema());
- } catch (SAXException sax) {
- fail("Unexpected exception " + sax.toString());
- }
- }
-*/
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setValidating(boolean).
- */
-// public void test_setValidatingZ() {
-// Exception parseException = null;
-// DocumentBuilder parser = null;
-// Document document = null;
-//
-// ValidationErrorHandler errorHandler = new ValidationErrorHandler();
-//
-// dbf.setValidating(false);
-// assertFalse(dbf.isValidating());
-//
-// // case 1: Validation is not set. Correct xml-file
-// try {
-//
-// parser = dbf.newDocumentBuilder();
-// parser.setErrorHandler(errorHandler);
-//
-// document = parser.parse(getClass().getResourceAsStream(
-// "/recipt.xml"));
-//
-// parseException = errorHandler.getFirstException();
-//
-// assertNotNull(document);
-//
-// document = parser.parse(getClass().getResourceAsStream(
-// "/reciptWrong.xml"));
-//
-// parseException = errorHandler.getFirstException();
-//
-// assertNotNull(document);
-//
-// } catch (Exception ex) {
-// parseException = ex;
-// }
-// parser.setErrorHandler(null);
-//
-// if (parseException != null) {
-// fail("Unexpected exception " + parseException.getMessage());
-// }
-//
-// // case 2: Validation is not set. Wrong xml-file
-// try {
-//
-// parser = dbf.newDocumentBuilder();
-// parser.setErrorHandler(errorHandler);
-//
-// document = parser.parse(getClass().getResourceAsStream(
-// "/reciptWrong.xml"));
-// parseException = errorHandler.getFirstException();
-//
-// assertNotNull(document);
-//
-// } catch (Exception ex) {
-// parseException = ex;
-// }
-// parser.setErrorHandler(null);
-//
-// if (parseException != null) {
-// fail("Unexpected exception " + parseException.getMessage());
-// }
-//
-// // case 3: Validation is set. Correct xml-file
-// dbf.setValidating(true);
-// assertTrue(dbf.isValidating());
-//
-// try {
-//
-// parser = dbf.newDocumentBuilder();
-// parser.setErrorHandler(errorHandler);
-//
-// document = parser.parse(getClass().getResourceAsStream(
-// "/recipt.xml"));
-// parseException = errorHandler.getFirstException();
-//
-// assertNotNull(document);
-//
-// } catch (Exception ex) {
-// parseException = ex;
-// }
-// parser.setErrorHandler(null);
-//
-// if (parseException != null) {
-// fail("Unexpected exception " + parseException.getMessage());
-// }
-//
-// // case 4: Validation is set. Wrong xml-file
-// try {
-//
-// parser = dbf.newDocumentBuilder();
-// parser.setErrorHandler(errorHandler);
-//
-// document = parser.parse(getClass().getResourceAsStream(
-// "/reciptWrong.xml"));
-// parseException = errorHandler.getFirstException();
-//
-// assertNotNull(document);
-//
-// } catch (Exception ex) {
-// parseException = ex;
-// }
-// parser.setErrorHandler(null);
-//
-// if (parseException == null) {
-// fail("Unexpected exception " + parseException.getMessage());
-// } else {
-// assertTrue(parseException
-// .getMessage()
-// .contains(
-// "The content of element type \"collection\" must match \"(description,recipe+)\""));
-// }
-//
-// }
-
- /**
- * javax.xml.parsers.DocumentBuilderFactory#setXIncludeAware().
- */
-// public void test_setXIncludeAware() {
-// dbf.setXIncludeAware(true);
-// assertTrue(dbf.isXIncludeAware());
-//
-// try {
-// DocumentBuilder parser = dbf.newDocumentBuilder();
-//
-// Document document = parser.parse(getClass().getResourceAsStream(
-// "/recipt.xml"));
-//
-// assertNotNull(document);
-//
-// } catch (IOException e) {
-// fail("Unexpected IOException " + e.getMessage());
-// } catch (ParserConfigurationException e) {
-// fail("Unexpected ParserConfigurationException " + e.getMessage());
-// } catch (SAXException e) {
-// fail("Unexpected SAXException " + e.getMessage());
-// }
-//
-// dbf.setXIncludeAware(false);
-// assertFalse(dbf.isXIncludeAware());
-//
-// try {
-// DocumentBuilder parser = dbf.newDocumentBuilder();
-//
-// Document document = parser.parse(getClass().getResourceAsStream(
-// "/recipt.xml"));
-//
-// assertNotNull(document);
-//
-// } catch (IOException e) {
-// fail("Unexpected IOException " + e.getMessage());
-// } catch (ParserConfigurationException e) {
-// fail("Unexpected ParserConfigurationException " + e.getMessage());
-// } catch (SAXException e) {
-// fail("Unexpected SAXException " + e.getMessage());
-// }
-// }
-
- private void goThroughDocument(Node node, String indent) {
- String value = node.getNodeValue();
-
- if (value != null) {
- value = value.replaceAll(" ", "");
- value = value.replaceAll("\n", "");
- }
-
- switch (node.getNodeType()) {
- case Node.CDATA_SECTION_NODE:
- cdataElements.add(value);
- // System.out.println(indent + "CDATA_SECTION_NODE " + value);
- break;
- case Node.COMMENT_NODE:
- commentElements.add(value);
- // System.out.println(indent + "COMMENT_NODE " + value);
- break;
- case Node.DOCUMENT_FRAGMENT_NODE:
- // System.out.println(indent + "DOCUMENT_FRAGMENT_NODE " + value);
- break;
- case Node.DOCUMENT_NODE:
- // System.out.println(indent + "DOCUMENT_NODE " + value);
- break;
- case Node.DOCUMENT_TYPE_NODE:
- // System.out.println(indent + "DOCUMENT_TYPE_NODE " + value);
- break;
- case Node.ELEMENT_NODE:
- // System.out.println(indent + "ELEMENT_NODE " + value);
- break;
- case Node.ENTITY_NODE:
- // System.out.println(indent + "ENTITY_NODE " + value);
- break;
- case Node.ENTITY_REFERENCE_NODE:
- // System.out.println(indent + "ENTITY_REFERENCE_NODE " + value);
- break;
- case Node.NOTATION_NODE:
- // System.out.println(indent + "NOTATION_NODE " + value);
- break;
- case Node.PROCESSING_INSTRUCTION_NODE:
- // System.out.println(indent + "PROCESSING_INSTRUCTION_NODE " +
- // value);
- break;
- case Node.TEXT_NODE:
- textElements.add(value);
- // System.out.println(indent + "TEXT_NODE " + value);
- break;
- default:
- // System.out.println(indent + "Unknown node " + value);
- break;
- }
- NodeList list = node.getChildNodes();
- for (int i = 0; i < list.getLength(); i++)
- goThroughDocument(list.item(i), indent + " ");
- }
-
- private class ValidationErrorHandler implements ErrorHandler {
- private SAXException parseException;
-
- private int errorCount;
-
- private int warningCount;
-
- public ValidationErrorHandler() {
- parseException = null;
- errorCount = 0;
- warningCount = 0;
- }
-
- public void error(SAXParseException ex) {
- errorCount++;
- if (parseException == null) {
- parseException = ex;
- }
- }
-
- public void warning(SAXParseException ex) {
- warningCount++;
- }
-
- public void fatalError(SAXParseException ex) {
- if (parseException == null) {
- parseException = ex;
- }
- }
-
- public SAXException getFirstException() {
- return parseException;
- }
- }
-
- private class DocumentBuilderFactoryChild extends DocumentBuilderFactory {
- public DocumentBuilderFactoryChild() {
- super();
- }
-
- public Object getAttribute(String name) {
- return null;
- }
-
- public boolean getFeature(String name) {
- return false;
- }
-
- public DocumentBuilder newDocumentBuilder() {
- return null;
- }
-
- public void setAttribute(String name, Object value) {
- }
-
- public void setFeature(String name, boolean value) {
- }
-
- }
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java
deleted file mode 100644
index 66ce621..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/DocumentBuilderTest.java
+++ /dev/null
@@ -1,637 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import junit.framework.TestCase;
-import org.w3c.dom.DOMImplementation;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.EntityReference;
-import org.w3c.dom.Text;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import tests.api.org.xml.sax.support.MethodLogger;
-import tests.api.org.xml.sax.support.MockHandler;
-import tests.api.org.xml.sax.support.MockResolver;
-import tests.support.resource.Support_Resources;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-
-public class DocumentBuilderTest extends TestCase {
-
- private class MockDocumentBuilder extends DocumentBuilder {
-
- public MockDocumentBuilder() {
- super();
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#getDOMImplementation()
- */
- @Override
- public DOMImplementation getDOMImplementation() {
- // it is a fake
- return null;
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#isNamespaceAware()
- */
- @Override
- public boolean isNamespaceAware() {
- // it is a fake
- return false;
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#isValidating()
- */
- @Override
- public boolean isValidating() {
- // it is a fake
- return false;
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#newDocument()
- */
- @Override
- public Document newDocument() {
- // it is a fake
- return null;
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#parse(org.xml.sax.InputSource)
- */
- @Override
- public Document parse(InputSource is) throws SAXException, IOException {
- // it is a fake
- return null;
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#setEntityResolver(
- * org.xml.sax.EntityResolver)
- */
- @Override
- public void setEntityResolver(EntityResolver er) {
- // it is a fake
- }
-
- /*
- * @see javax.xml.parsers.DocumentBuilder#setErrorHandler(
- * org.xml.sax.ErrorHandler)
- */
- @Override
- public void setErrorHandler(ErrorHandler eh) {
- // it is a fake
- }
-
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
-
- DocumentBuilderFactory dbf;
-
- DocumentBuilder db;
-
- protected void setUp() throws Exception {
-
- dbf = DocumentBuilderFactory.newInstance();
-
- dbf.setIgnoringElementContentWhitespace(true);
-
- db = dbf.newDocumentBuilder();
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testDocumentBuilder() {
- try {
- new MockDocumentBuilder();
- } catch (Exception e) {
- fail("unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilder#getSchema()
- * TBD getSchema() is not supported
- */
- /* public void test_getSchema() {
- assertNull(db.getSchema());
- SchemaFactory sf =
- SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- try {
- Schema schema = sf.newSchema();
- dbf.setSchema(schema);
- assertNotNull(dbf.newDocumentBuilder().getSchema());
- } catch (ParserConfigurationException pce) {
- fail("Unexpected ParserConfigurationException " + pce.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
-*/
- public void testNewDocument() {
- Document d;
-
- try {
- d = dbf.newDocumentBuilder().newDocument();
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertNotNull(d);
- assertNull(d.getDoctype());
- assertNull(d.getDocumentElement());
- assertNull(d.getNamespaceURI());
- }
-
- public void testGetImplementation() {
- DOMImplementation d;
-
- try {
- d = dbf.newDocumentBuilder().getDOMImplementation();
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertNotNull(d);
- }
-
- public void testIsNamespaceAware() {
- try {
- dbf.setNamespaceAware(true);
- assertTrue(dbf.newDocumentBuilder().isNamespaceAware());
- dbf.setNamespaceAware(false);
- assertFalse(dbf.newDocumentBuilder().isNamespaceAware());
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testIsValidating() {
- try {
- dbf.setValidating(false);
- assertFalse(dbf.newDocumentBuilder().isValidating());
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testIsXIncludeAware() {
- try {
- dbf.setXIncludeAware(false);
- assertFalse(dbf.newDocumentBuilder().isXIncludeAware());
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- /**
- * Tests that the Base URI for the document is populated with the file URI.
- */
- public void testGetBaseURI() throws IOException, SAXException {
- File f = Support_Resources.resourceToTempFile("/simple.xml");
- Document d = db.parse(f);
- assertTrue(d.getDocumentElement().getBaseURI().startsWith("file://"));
- }
-
- /**
- * javax.xml.parsers.DocumentBuilder#parse(java.io.File)
- * Case 1: Try to parse correct xml document.
- * Case 2: Try to call parse() with null argument.
- * Case 3: Try to parse a non-existent file.
- * Case 4: Try to parse incorrect xml file.
- */
- public void test_parseLjava_io_File() throws IOException {
- File f = Support_Resources.resourceToTempFile("/simple.xml");
-
- // case 1: Trivial use.
- try {
- Document d = db.parse(f);
- assertNotNull(d);
- // TBD getXmlEncoding() IS NOT SUPPORTED
- // assertEquals("ISO-8859-1", d.getXmlEncoding());
- assertEquals(2, d.getChildNodes().getLength());
- assertEquals("#comment",
- d.getChildNodes().item(0).getNodeName());
- assertEquals("breakfast_menu",
- d.getChildNodes().item(1).getNodeName());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 2: Try to call parse with null argument
- try {
- db.parse((File)null);
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 3: Try to parse a non-existent file
- try {
- db.parse(new File("_"));
- fail("Expected IOException was not thrown");
- } catch (IOException ioe) {
- // expected
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 4: Try to parse incorrect xml file
- f = Support_Resources.resourceToTempFile("/wrong.xml");
- try {
- db.parse(f);
- fail("Expected SAXException was not thrown");
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- // expected
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream)
- * Case 1: Try to parse correct xml document.
- * Case 2: Try to call parse() with null argument.
- * Case 3: Try to parse a non-existent file.
- * Case 4: Try to parse incorrect xml file.
- */
- public void test_parseLjava_io_InputStream() {
- InputStream is = getClass().getResourceAsStream("/simple.xml");
- // case 1: Trivial use.
- try {
- Document d = db.parse(is);
- assertNotNull(d);
- // TBD getXmlEncoding() IS NOT SUPPORTED
- // assertEquals("ISO-8859-1", d.getXmlEncoding());
- assertEquals(2, d.getChildNodes().getLength());
- assertEquals("#comment",
- d.getChildNodes().item(0).getNodeName());
- assertEquals("breakfast_menu",
- d.getChildNodes().item(1).getNodeName());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 2: Try to call parse with null argument
- try {
- db.parse((InputStream)null);
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 3: Try to parse a non-existent file
- try {
- db.parse(new FileInputStream("_"));
- fail("Expected IOException was not thrown");
- } catch (IOException ioe) {
- // expected
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 4: Try to parse incorrect xml file
- try {
- is = getClass().getResourceAsStream("/wrong.xml");
- db.parse(is);
- fail("Expected SAXException was not thrown");
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- // expected
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream)
- * Case 1: Try to parse correct xml document.
- * Case 2: Try to call parse() with null argument.
- * Case 3: Try to parse a non-existent file.
- * Case 4: Try to parse incorrect xml file.
- */
- public void testParseInputSource() {
- InputStream stream = getClass().getResourceAsStream("/simple.xml");
- InputSource is = new InputSource(stream);
-
- // case 1: Trivial use.
- try {
- Document d = db.parse(is);
- assertNotNull(d);
- // TBD getXmlEncoding() IS NOT SUPPORTED
- // assertEquals("ISO-8859-1", d.getXmlEncoding());
- assertEquals(2, d.getChildNodes().getLength());
- assertEquals("#comment",
- d.getChildNodes().item(0).getNodeName());
- assertEquals("breakfast_menu",
- d.getChildNodes().item(1).getNodeName());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 2: Try to call parse with null argument
- try {
- db.parse((InputSource)null);
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 3: Try to parse a non-existent file
- try {
- db.parse(new InputSource(new FileInputStream("_")));
- fail("Expected IOException was not thrown");
- } catch (IOException ioe) {
- // expected
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 4: Try to parse incorrect xml file
- try {
- is = new InputSource(getClass().getResourceAsStream("/wrong.xml"));
- db.parse(is);
- fail("Expected SAXException was not thrown");
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- // expected
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilder#parse(java.io.InputStream,
- * java.lang.String)
- * Case 1: Try to parse correct xml document.
- * Case 2: Try to call parse() with null argument.
- * Case 3: Try to parse a non-existent file.
- * Case 4: Try to parse incorrect xml file.
- */
- public void test_parseLjava_io_InputStreamLjava_lang_String() {
- InputStream is = getClass().getResourceAsStream("/systemid.xml");
- // case 1: Trivial use.
- try {
- Document d = db.parse(is, SAXParserTestSupport.XML_SYSTEM_ID);
- assertNotNull(d);
-// TBD getXmlEncoding() is not supported
-// assertEquals("UTF-8", d.getXmlEncoding());
- assertEquals(4, d.getChildNodes().getLength());
- assertEquals("collection",
- d.getChildNodes().item(0).getNodeName());
- assertEquals("#comment",
- d.getChildNodes().item(1).getNodeName());
- assertEquals("collection",
- d.getChildNodes().item(2).getNodeName());
- assertEquals("#comment",
- d.getChildNodes().item(3).getNodeName());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 2: Try to call parse with null argument
- try {
- db.parse((InputStream)null, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- // case 3: Try to parse a non-existent file
-// Doesn't make sense this way...
-// try {
-// db.parse(is, "/");
-// fail("Expected IOException was not thrown");
-// } catch (IOException ioe) {
-// // expected
-// } catch (SAXException sax) {
-// fail("Unexpected SAXException " + sax.toString());
-// }
-
- // case 4: Try to parse incorrect xml file
- try {
- is = getClass().getResourceAsStream("/wrong.xml");
- db.parse(is, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("Expected SAXException was not thrown");
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- // expected
- }
- }
-
- /**
- * javax.xml.parsers.DocumentBuilder#parse(java.lang.String)
- * Case 1: Try to parse correct xml document.
- * Case 2: Try to call parse() with null argument.
- * Case 3: Try to parse a non-existent uri.
- * Case 4: Try to parse incorrect xml file.
- */
- public void test_parseLjava_lang_String() throws Exception {
- // case 1: Trivial use.
- URL resource = getClass().getResource("/simple.xml");
- Document d = db.parse(resource.toString());
- assertNotNull(d);
-// TBD getXmlEncoding() is not supported
-// assertEquals("ISO-8859-1", d.getXmlEncoding());
- assertEquals(2, d.getChildNodes().getLength());
- assertEquals("#comment",
- d.getChildNodes().item(0).getNodeName());
- assertEquals("breakfast_menu",
- d.getChildNodes().item(1).getNodeName());
-
- // case 2: Try to call parse with null argument
- try {
- db.parse((String)null);
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- }
-
- // case 3: Try to parse a non-existent uri
- try {
- db.parse("_");
- fail("Expected IOException was not thrown");
- } catch (IOException ioe) {
- // expected
- }
-
- // case 4: Try to parse incorrect xml file
- try {
- resource = getClass().getResource("/wrong.xml");
- db.parse(resource.toString());
- fail("Expected SAXException was not thrown");
- } catch (SAXException sax) {
- // expected
- }
- }
-
- public void testReset() {
- // Make sure EntityResolver gets reset
- InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes());
- InputStream entity = new ByteArrayInputStream("bar".getBytes());
-
- MockResolver resolver = new MockResolver();
- resolver.addEntity("foo", "foo", new InputSource(entity));
-
- Document d;
-
- try {
- db = dbf.newDocumentBuilder();
- db.setEntityResolver(resolver);
- db.reset();
- d = db.parse(source);
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- Element root = (Element)d.getElementsByTagName("a").item(0);
- assertEquals("foo", ((EntityReference)root.getFirstChild()).getNodeName());
-
- // Make sure ErrorHandler gets reset
- source = new ByteArrayInputStream("</a>".getBytes());
-
- MethodLogger logger = new MethodLogger();
- ErrorHandler handler = new MockHandler(logger);
-
- try {
- db = dbf.newDocumentBuilder();
- db.setErrorHandler(handler);
- db.reset();
- d = db.parse(source);
- } catch (SAXParseException e) {
- // Expected
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(0, logger.size());
- }
-
- public void testSetErrorHandler() {
- // Ordinary case
- InputStream source = new ByteArrayInputStream("</a>".getBytes());
-
- MethodLogger logger = new MethodLogger();
- ErrorHandler handler = new MockHandler(logger);
-
- try {
- db = dbf.newDocumentBuilder();
- db.setErrorHandler(handler);
- db.parse(source);
- } catch (SAXParseException e) {
- // Expected, ErrorHandler does not mask exception
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals("error", logger.getMethod());
- assertTrue(logger.getArgs()[0] instanceof SAXParseException);
-
- // null case
- source = new ByteArrayInputStream("</a>".getBytes());
-
- try {
- db = dbf.newDocumentBuilder();
- db.setErrorHandler(null);
- db.parse(source);
- } catch (SAXParseException e) {
- // Expected
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testSetEntityResolver() {
- // Ordinary case
- InputStream source = new ByteArrayInputStream("<a>&foo;</a>".getBytes());
- InputStream entity = new ByteArrayInputStream("bar".getBytes());
-
- MockResolver resolver = new MockResolver();
- resolver.addEntity("foo", "foo", new InputSource(entity));
-
- Document d;
-
- try {
- db = dbf.newDocumentBuilder();
- db.setEntityResolver(resolver);
- d = db.parse(source);
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- Element root = (Element)d.getElementsByTagName("a").item(0);
- assertEquals("bar", ((Text)root.getFirstChild()).getData());
-
- // null case
- source = new ByteArrayInputStream("<a>&foo;</a>".getBytes());
-
- try {
- db = dbf.newDocumentBuilder();
- db.setEntityResolver(null);
- d = db.parse(source);
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- root = (Element)d.getElementsByTagName("a").item(0);
- assertEquals("foo", ((EntityReference)root.getFirstChild()).getNodeName());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java
deleted file mode 100644
index cdef4e2..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/FactoryConfigurationErrorTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import javax.xml.parsers.FactoryConfigurationError;
-
-import junit.framework.TestCase;
-
-public class FactoryConfigurationErrorTest extends TestCase {
-
- public void test_Constructor() {
- FactoryConfigurationError fce = new FactoryConfigurationError();
- assertNull(fce.getMessage());
- assertNull(fce.getLocalizedMessage());
- assertNull(fce.getCause());
- }
-
- public void test_ConstructorLjava_lang_Exception() {
- Exception e = new Exception();
- // case 1: Try to create FactoryConfigurationError
- // which is based on Exception without parameters.
- FactoryConfigurationError fce = new FactoryConfigurationError(e);
- assertNotNull(fce.getMessage());
- assertNotNull(fce.getLocalizedMessage());
- assertEquals(e.getCause(), fce.getCause());
-
- // case 2: Try to create FactoryConfigurationError
- // which is based on Exception with String parameter.
- e = new Exception("test message");
- fce = new FactoryConfigurationError(e);
- assertEquals(e.toString(), fce.getMessage());
- assertEquals(e.toString(), fce.getLocalizedMessage());
- assertEquals(e.getCause(), fce.getCause());
- }
-
- public void test_ConstructorLjava_lang_ExceptionLjava_lang_String() {
- Exception e = new Exception();
- // case 1: Try to create FactoryConfigurationError
- // which is based on Exception without parameters.
- FactoryConfigurationError fce = new FactoryConfigurationError(e, "msg");
- assertNotNull(fce.getMessage());
- assertNotNull(fce.getLocalizedMessage());
- assertEquals(e.getCause(), fce.getCause());
-
- // case 2: Try to create FactoryConfigurationError
- // which is based on Exception with String parameter.
- e = new Exception("test message");
- fce = new FactoryConfigurationError(e, "msg");
- assertEquals("msg", fce.getMessage());
- assertEquals("msg", fce.getLocalizedMessage());
- assertEquals(e.getCause(), fce.getCause());
- }
-
- public void test_ConstructorLjava_lang_String() {
- FactoryConfigurationError fce = new FactoryConfigurationError("Oops!");
- assertEquals("Oops!", fce.getMessage());
- assertEquals("Oops!", fce.getLocalizedMessage());
- assertNull(fce.getCause());
- }
-
- public void test_getException() {
- FactoryConfigurationError fce = new FactoryConfigurationError();
- assertNull(fce.getException());
- fce = new FactoryConfigurationError("test");
- assertNull(fce.getException());
- Exception e = new Exception("msg");
- fce = new FactoryConfigurationError(e);
- assertEquals(e, fce.getException());
- NullPointerException npe = new NullPointerException();
- fce = new FactoryConfigurationError(npe);
- assertEquals(npe, fce.getException());
- }
-
- public void test_getMessage() {
- assertNull(new FactoryConfigurationError().getMessage());
- assertEquals("msg1",
- new FactoryConfigurationError("msg1").getMessage());
- assertEquals(new Exception("msg2").toString(),
- new FactoryConfigurationError(
- new Exception("msg2")).getMessage());
- assertEquals(new NullPointerException().toString(),
- new FactoryConfigurationError(
- new NullPointerException()).getMessage());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java
deleted file mode 100644
index d1feb9f..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/ParserConfigurationExceptionTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import javax.xml.parsers.ParserConfigurationException;
-
-import junit.framework.TestCase;
-
-public class ParserConfigurationExceptionTest extends TestCase{
-
- public void test_Constructor() {
- ParserConfigurationException pce = new ParserConfigurationException();
- assertNull(pce.getMessage());
- assertNull(pce.getLocalizedMessage());
- assertNull(pce.getCause());
- }
-
- public void test_ConstructorLjava_lang_String() {
- ParserConfigurationException pce =
- new ParserConfigurationException("Oops!");
- assertEquals("Oops!", pce.getMessage());
- assertEquals("Oops!", pce.getLocalizedMessage());
- assertNull(pce.getCause());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java
deleted file mode 100644
index 614b9d8..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserFactoryTest.java
+++ /dev/null
@@ -1,415 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Properties;
-import java.util.Vector;
-
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-
-public class SAXParserFactoryTest extends TestCase {
-
- SAXParserFactory spf;
-
- InputStream is1;
-
- static HashMap<String, String> ns;
-
- static Vector<String> el;
-
- static HashMap<String, String> attr;
-
- public void setUp() throws Exception {
- spf = SAXParserFactory.newInstance();
-
- is1 = getClass().getResourceAsStream("/simple.xml");
-
- ns = new HashMap<String, String>();
- attr = new HashMap<String, String>();
- el = new Vector<String>();
- }
-
- public void tearDown() throws Exception {
- is1.close();
- super.tearDown();
- }
-
- @AndroidOnly("Android SAX implementation is non-validating")
- public void test_Constructor() {
- MySAXParserFactory mpf = new MySAXParserFactory();
- assertTrue(mpf instanceof SAXParserFactory);
- assertFalse(mpf.isValidating());
- }
-
- /**
- * javax.xml.parsers.SAXParserFactory#getSchema().
- * TBD getSchema() IS NOT SUPPORTED
- */
- /* public void test_getSchema() {
- assertNull(spf.getSchema());
- SchemaFactory sf =
- SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- try {
- Schema schema = sf.newSchema();
- spf.setSchema(schema);
- assertNotNull(spf.getSchema());
- } catch (SAXException sax) {
- fail("Unexpected exception " + sax.toString());
- }
- }
- */
-
- public void test_setIsNamespaceAware() {
- spf.setNamespaceAware(true);
- assertTrue(spf.isNamespaceAware());
- spf.setNamespaceAware(false);
- assertFalse(spf.isNamespaceAware());
- spf.setNamespaceAware(true);
- assertTrue(spf.isNamespaceAware());
- }
-
- public void test_setIsValidating() {
- spf.setValidating(true);
- assertTrue(spf.isValidating());
- spf.setValidating(false);
- assertFalse(spf.isValidating());
- spf.setValidating(true);
- assertTrue(spf.isValidating());
- }
-
- public void test_setIsXIncludeAware() {
- spf.setXIncludeAware(true);
- assertTrue(spf.isXIncludeAware());
- spf.setXIncludeAware(false);
- assertFalse(spf.isXIncludeAware());
- }
-
- @KnownFailure("Dalvik doesn't honor system properties when choosing a SAX implementation")
- public void test_newInstance() {
- try {
- SAXParserFactory dtf = SAXParserFactory.newInstance();
- assertNotNull("New Instance of DatatypeFactory is null", dtf);
-
- System.setProperty("javax.xml.parsers.SAXParserFactory",
- "org.apache.harmony.xml.parsers.SAXParserFactoryImpl");
-
- SAXParserFactory spf1 = SAXParserFactory.newInstance();
- assertTrue(spf1 instanceof org.apache.harmony.xml.parsers.SAXParserFactoryImpl);
-
- String key = "javax.xml.parsers.SAXParserFactory = org.apache.harmony.xml.parsers.SAXParserFactoryImpl";
-
- ByteArrayInputStream bis = new ByteArrayInputStream(key.getBytes());
- Properties prop = System.getProperties();
- prop.load(bis);
- SAXParserFactory spf2 = SAXParserFactory.newInstance();
- assertTrue(spf2 instanceof org.apache.harmony.xml.parsers.SAXParserFactoryImpl);
-
- System.setProperty("javax.xml.parsers.SAXParserFactory", "");
- try {
- SAXParserFactory.newInstance();
- fail("Expected FactoryConfigurationError was not thrown");
- } catch (FactoryConfigurationError e) {
- // expected
- }
- } catch (IOException ioe) {
- fail("Unexpected exception " + ioe.toString());
- }
- }
-
- public void test_newSAXParser() {
- // Ordinary case
- try {
- SAXParser sp = spf.newSAXParser();
- assertTrue(sp instanceof SAXParser);
- sp.parse(is1, new MyHandler());
- } catch(Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // Exception case
- spf.setValidating(true);
- try {
- SAXParser sp = spf.newSAXParser();
- } catch(ParserConfigurationException e) {
- // Expected, since Android doesn't have a validating parser.
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void test_setFeatureLjava_lang_StringZ() {
- // We can't verify ParserConfigurationException and
- // SAXNotSupportedException since these are never
- // thrown by Android.
-
- String[] features = {
- "http://xml.org/sax/features/namespaces",
- "http://xml.org/sax/features/validation" };
- for (int i = 0; i < features.length; i++) {
- try {
- spf.setFeature(features[i], true);
- assertTrue(spf.getFeature(features[i]));
- spf.setFeature(features[i], false);
- assertFalse(spf.getFeature(features[i]));
- } catch (ParserConfigurationException pce) {
- fail("ParserConfigurationException is thrown");
- } catch (SAXNotRecognizedException snre) {
- fail("SAXNotRecognizedException is thrown");
- } catch (SAXNotSupportedException snse) {
- fail("SAXNotSupportedException is thrown");
- }
- }
-
- try {
- spf.setFeature("", true);
- fail("SAXNotRecognizedException is not thrown");
- } catch (ParserConfigurationException pce) {
- fail("ParserConfigurationException is thrown");
- } catch (SAXNotRecognizedException snre) {
- //expected
- } catch (SAXNotSupportedException snse) {
- fail("SAXNotSupportedException is thrown");
- } catch (NullPointerException npe) {
- fail("NullPointerException is thrown");
- }
-
- try {
- spf.setFeature("http://xml.org/sax/features/unknown-feature", true);
- } catch (ParserConfigurationException pce) {
- fail("ParserConfigurationException is thrown");
- } catch (SAXNotRecognizedException snre) {
- fail("SAXNotRecognizedException is thrown");
- } catch (SAXNotSupportedException snse) {
- // Acceptable, although this doesn't happen an Android.
- } catch (NullPointerException npe) {
- fail("NullPointerException is thrown");
- }
-
- try {
- spf.setFeature(null, true);
- fail("NullPointerException is not thrown");
- } catch (ParserConfigurationException pce) {
- fail("ParserConfigurationException is thrown");
- } catch (SAXNotRecognizedException snre) {
- fail("SAXNotRecognizedException is thrown");
- } catch (SAXNotSupportedException snse) {
- fail("SAXNotSupportedException is thrown");
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- public void test_setNamespaceAwareZ() throws Exception {
- MyHandler mh = new MyHandler();
-
- spf.setNamespaceAware(true);
- InputStream is = getClass().getResourceAsStream("/simple_ns.xml");
- spf.newSAXParser().parse(is, mh);
- is.close();
-
- spf.setNamespaceAware(false);
- is = getClass().getResourceAsStream("/simple_ns.xml");
- spf.newSAXParser().parse(is, mh);
- is.close();
- }
-
- /* public void test_setSchemaLjavax_xml_validation_Schema() {
- SchemaFactory sf =
- SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- try {
- Schema schema = sf.newSchema();
- spf.setSchema(schema);
- assertNotNull(spf.getSchema());
- } catch (SAXException sax) {
- fail("Unexpected exception " + sax.toString());
- }
- }
- */
-
-// public void test_setValidatingZ() {
-// MyHandler mh = new MyHandler();
-// InputStream is2 = getClass().getResourceAsStream("/recipe.xml");
-// try {
-// spf.setValidating(true);
-// assertTrue(spf.isValidating());
-// spf.newSAXParser().parse(is2, mh);
-// } catch (org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch (javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch (IOException ioe) {
-// fail("IOException was thrown during parsing");
-// } finally {
-// try {
-// is2.close();
-// } catch(Exception ioee) {}
-// }
-// InputStream is3 = getClass().getResourceAsStream("/recipe1.xml");
-// try {
-// assertTrue(spf.isValidating());
-// spf.newSAXParser().parse(is3, mh);
-// } catch (org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch (javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch (IOException ioe) {
-// fail("IOEXception was thrown during parsing: " + ioe.getMessage());
-// } finally {
-// try {
-// is3.close();
-// } catch(Exception ioee) {}
-// }
-// is2 = getClass().getResourceAsStream("/recipe.xml");
-// try {
-// spf.setValidating(false);
-// assertFalse(spf.isValidating());
-// spf.newSAXParser().parse(is2, mh);
-// } catch (org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch (javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch (IOException ioe) {
-// fail("IOException was thrown during parsing");
-// } finally {
-// try {
-// is2.close();
-// } catch(Exception ioee) {}
-// }
-// is3 = getClass().getResourceAsStream("/recipe1.xml");
-// try {
-// assertFalse(spf.isValidating());
-// spf.newSAXParser().parse(is3, mh);
-// } catch (org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch (javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch (IOException ioe) {
-// fail("IOEXception was thrown during parsing: " + ioe.getMessage());
-// } finally {
-// try {
-// is3.close();
-// } catch(Exception ioee) {}
-// }
-// }
-
-// public void test_setXIncludeAwareZ() {
-// spf.setXIncludeAware(true);
-// MyHandler mh = new MyHandler();
-// InputStream is = getClass().getResourceAsStream("/simple_ns.xml");
-// try {
-// spf.newSAXParser().parse(is, mh);
-// } catch(javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch(org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch(IOException ioe) {
-// fail("IOException was thrown during parsing");
-// } finally {
-// try {
-// is.close();
-// } catch(Exception ioee) {}
-// }
-// spf.setXIncludeAware(false);
-// is = getClass().getResourceAsStream("/simple_ns.xml");
-// try {
-// is = getClass().getResourceAsStream("/simple_ns.xml");
-// spf.newSAXParser().parse(is, mh);
-// } catch(javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch(org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch(IOException ioe) {
-// fail("IOException was thrown during parsing");
-// } finally {
-// try {
-// is.close();
-// } catch(Exception ioee) {}
-// }
-// is = getClass().getResourceAsStream("/simple_ns.xml");
-// try {
-// spf.setXIncludeAware(true);
-// spf.newSAXParser().parse(is, mh);
-// } catch(javax.xml.parsers.ParserConfigurationException pce) {
-// fail("ParserConfigurationException was thrown during parsing");
-// } catch(org.xml.sax.SAXException se) {
-// fail("SAXException was thrown during parsing");
-// } catch(IOException ioe) {
-// fail("IOException was thrown during parsing");
-// } finally {
-// try {
-// is.close();
-// } catch(Exception ioee) {}
-// }
-// }
-
- static class MyHandler extends DefaultHandler {
-
- public void startElement(String uri, String localName, String qName,
- Attributes atts) {
-
- el.add(qName);
- if (!uri.equals(""))
- ns.put(qName, uri);
- for (int i = 0; i < atts.getLength(); i++) {
- attr.put(atts.getQName(i), atts.getValue(i));
- }
-
- }
- }
-
- class MySAXParserFactory extends SAXParserFactory {
-
- public MySAXParserFactory() {
- super();
- }
-
- public SAXParser newSAXParser() {
- return null;
- }
-
- public void setFeature(String name, boolean value) throws
- ParserConfigurationException, SAXNotRecognizedException,
- SAXNotSupportedException {
-
- }
-
- public boolean getFeature(String name) throws
- ParserConfigurationException, SAXNotRecognizedException,
- SAXNotSupportedException {
- return true;
- }
-
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java b/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java
deleted file mode 100644
index 3586162..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTest.java
+++ /dev/null
@@ -1,922 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import dalvik.annotation.KnownFailure;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.HashMap;
-import java.util.Vector;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import junit.framework.TestCase;
-import org.xml.sax.HandlerBase;
-import org.xml.sax.InputSource;
-import org.xml.sax.Parser;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.ext.LexicalHandler;
-import org.xml.sax.helpers.DefaultHandler;
-import tests.api.javax.xml.parsers.SAXParserTestSupport.MyDefaultHandler;
-import tests.api.javax.xml.parsers.SAXParserTestSupport.MyHandler;
-import tests.api.org.xml.sax.support.BrokenInputStream;
-import tests.api.org.xml.sax.support.MethodLogger;
-import tests.api.org.xml.sax.support.MockHandler;
-import tests.support.resource.Support_Resources;
-
-@SuppressWarnings("deprecation")
-public class SAXParserTest extends TestCase {
-
- private class MockSAXParser extends SAXParser {
- public MockSAXParser() {
- super();
- }
-
- /*
- * @see javax.xml.parsers.SAXParser#getParser()
- */
- @Override
- public Parser getParser() throws SAXException {
- // it is a fake
- return null;
- }
-
- /*
- * @see javax.xml.parsers.SAXParser#getProperty(java.lang.String)
- */
- @Override
- public Object getProperty(String name) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- // it is a fake
- return null;
- }
-
- /*
- * @see javax.xml.parsers.SAXParser#getXMLReader()
- */
- @Override
- public XMLReader getXMLReader() throws SAXException {
- // it is a fake
- return null;
- }
-
- /*
- * @see javax.xml.parsers.SAXParser#isNamespaceAware()
- */
- @Override
- public boolean isNamespaceAware() {
- // it is a fake
- return false;
- }
-
- /*
- * @see javax.xml.parsers.SAXParser#isValidating()
- */
- @Override
- public boolean isValidating() {
- // it is a fake
- return false;
- }
-
- /*
- * @see javax.xml.parsers.SAXParser#setProperty(java.lang.String,
- * java.lang.Object)
- */
- @Override
- public void setProperty(String name, Object value) throws
- SAXNotRecognizedException, SAXNotSupportedException {
- // it is a fake
- }
- }
-
- private static final String LEXICAL_HANDLER_PROPERTY
- = "http://xml.org/sax/properties/lexical-handler";
-
- SAXParserFactory spf;
-
- SAXParser parser;
-
- static HashMap<String, String> ns;
-
- static Vector<String> el;
-
- static HashMap<String, String> attr;
-
- SAXParserTestSupport sp = new SAXParserTestSupport();
-
- File [] list_wf;
- File [] list_nwf;
- File [] list_out_dh;
- File [] list_out_hb;
-
- boolean validating = false;
-
- private InputStream getResource(String name) {
- return this.getClass().getResourceAsStream(name);
- }
-
- public void initFiles() throws Exception {
- // we differntiate between a validating and a non validating parser
- try {
- SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
- validating = parser.isValidating();
- } catch (Exception e) {
- fail("could not obtain a SAXParser");
- }
-
- String tmpPath = System.getProperty("java.io.tmpdir");
-
- // nwf = not well formed, wf = well formed
- list_wf = new File[] {new File(tmpPath + "/" +
- SAXParserTestSupport.XML_WF + "staff.xml")};
- list_nwf = new File[] {new File(tmpPath + "/" +
- SAXParserTestSupport.XML_NWF + "staff.xml")};
- list_out_dh = new File[] {new File(tmpPath + "/" +
- SAXParserTestSupport.XML_WF_OUT_DH + "staff.out")};
- list_out_hb = new File[] {new File(tmpPath + "/" +
- SAXParserTestSupport.XML_WF_OUT_HB + "staff.out")};
-
- list_wf[0].deleteOnExit();
- list_nwf[0].deleteOnExit();
- list_out_hb[0].deleteOnExit();
- list_out_dh[0].deleteOnExit();
-
-
- Support_Resources.copyLocalFileto(list_wf[0],
- getResource(SAXParserTestSupport.XML_WF + "staff.xml"));
- Support_Resources.copyLocalFileto(new File(
- tmpPath + "/" + SAXParserTestSupport.XML_WF + "staff.dtd"),
- getResource(SAXParserTestSupport.XML_WF + "staff.dtd"));
-
- Support_Resources.copyLocalFileto(list_nwf[0],
- getResource(SAXParserTestSupport.XML_NWF + "staff.xml"));
- Support_Resources.copyLocalFileto(new File(
- tmpPath + "/" + SAXParserTestSupport.XML_NWF + "staff.dtd"),
- getResource(SAXParserTestSupport.XML_NWF + "staff.dtd"));
-
- Support_Resources.copyLocalFileto(list_out_dh[0],
- getResource(SAXParserTestSupport.XML_WF_OUT_DH + "staff.out"));
- Support_Resources.copyLocalFileto(list_out_hb[0],
- getResource(SAXParserTestSupport.XML_WF_OUT_HB + "staff.out"));
- }
-
- @Override
- protected void setUp() throws Exception {
- spf = SAXParserFactory.newInstance();
- parser = spf.newSAXParser();
- assertNotNull(parser);
-
- ns = new HashMap<String, String>();
- attr = new HashMap<String, String>();
- el = new Vector<String>();
- initFiles();
- }
-
- @Override
- protected void tearDown() throws Exception {
- }
-
-// public static void main(String[] args) throws Exception {
-// SAXParserTest st = new SAXParserTest();
-// st.setUp();
-// st.generateDataFromReferenceImpl();
-//
-// }
-//
-// private void generateDataFromReferenceImpl() {
-// try {
-// for(int i = 0; i < list_wf.length; i++) {
-// MyDefaultHandler dh = new MyDefaultHandler();
-// InputStream is = new FileInputStream(list_wf[i]);
-// parser.parse(is, dh, ParsingSupport.XML_SYSTEM_ID);
-// HashMap refHm = dh.createData();
-//
-// StringBuilder sb = new StringBuilder();
-// for (int j = 0; j < ParsingSupport.KEYS.length; j++) {
-// String key = ParsingSupport.KEYS[j];
-// sb.append(refHm.get(key)).append(
-// ParsingSupport.SEPARATOR_DATA);
-// }
-// FileWriter fw = new FileWriter("/tmp/build_dh"+i+".out");
-// fw.append(sb.toString());
-// fw.close();
-// }
-//
-// for(int i = 0; i < list_nwf.length; i++) {
-// MyHandler hb = new MyHandler();
-// InputStream is = new FileInputStream(list_wf[i]);
-// parser.parse(is, hb, ParsingSupport.XML_SYSTEM_ID);
-// HashMap refHm = hb.createData();
-//
-// StringBuilder sb = new StringBuilder();
-// for (int j = 0; j < ParsingSupport.KEYS.length; j++) {
-// String key = ParsingSupport.KEYS[j];
-// sb.append(refHm.get(key)).append(
-// ParsingSupport.SEPARATOR_DATA);
-// }
-// FileWriter fw = new FileWriter("/tmp/build_hb"+i+".out");
-// fw.append(sb.toString());
-// fw.close();
-// }
-//
-//
-// } catch (Exception e) {
-// e.printStackTrace();
-// }
-// }
-
- public void testSAXParser() {
- try {
- new MockSAXParser();
- } catch (Exception e) {
- fail("unexpected exception " + e.toString());
- }
- }
-
- /**
- * javax.xml.parser.SAXParser#getSchema().
- * TODO getSchema() IS NOT SUPPORTED
- */
- /* public void test_getSchema() {
- assertNull(parser.getSchema());
- SchemaFactory sf =
- SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- try {
- Schema schema = sf.newSchema();
- spf.setSchema(schema);
- assertNotNull(spf.newSAXParser().getSchema());
- } catch (ParserConfigurationException pce) {
- fail("Unexpected ParserConfigurationException " + pce.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
- */
-
- public void testIsNamespaceAware() {
- try {
- spf.setNamespaceAware(true);
- assertTrue(spf.newSAXParser().isNamespaceAware());
- spf.setNamespaceAware(false);
- assertFalse(spf.newSAXParser().isNamespaceAware());
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testIsValidating() {
- try {
- spf.setValidating(false);
- assertFalse(spf.newSAXParser().isValidating());
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testIsXIncludeAware() {
- try {
- spf.setXIncludeAware(false);
- assertFalse(spf.newSAXParser().isXIncludeAware());
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- /**
- * @test javax.xml.parsers.SAXParser#parse(java.io.File,
- * org.xml.sax.helpers.DefaultHandler)
- */
- public void test_parseLjava_io_FileLorg_xml_sax_helpers_DefaultHandler()
- throws Exception {
-
- for(int i = 0; i < list_wf.length; i++) {
- HashMap<String, String> hm =
- new SAXParserTestSupport().readFile(list_out_dh[i].getPath());
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse(list_wf[i], dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for(int i = 0; i < list_nwf.length; i++) {
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse(list_nwf[i], dh);
- fail("SAXException is not thrown");
- } catch(org.xml.sax.SAXException se) {
- //expected
- }
- }
-
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse((File) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(java.lang.IllegalArgumentException iae) {
- //expected
- }
-
- try {
- parser.parse(list_wf[0], (DefaultHandler) null);
- } catch(java.lang.IllegalArgumentException iae) {
- fail("java.lang.IllegalArgumentException is thrown");
- }
- }
-
- public void testParseFileHandlerBase() {
- for(int i = 0; i < list_wf.length; i++) {
- try {
- HashMap<String, String> hm = sp.readFile(
- list_out_hb[i].getPath());
- MyHandler dh = new MyHandler();
- parser.parse(list_wf[i], dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm,
- dh.createData()));
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
-
- for(int i = 0; i < list_nwf.length; i++) {
- try {
- MyHandler dh = new MyHandler();
- parser.parse(list_nwf[i], dh);
- fail("SAXException is not thrown");
- } catch(org.xml.sax.SAXException se) {
- //expected
- } catch (FileNotFoundException fne) {
- fail("Unexpected FileNotFoundException " + fne.toString());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- }
- }
-
- try {
- MyHandler dh = new MyHandler();
- parser.parse((File) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(java.lang.IllegalArgumentException iae) {
- //expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch(SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- try {
- parser.parse(list_wf[0], (HandlerBase) null);
- } catch(java.lang.IllegalArgumentException iae) {
- fail("java.lang.IllegalArgumentException is thrown");
- } catch (FileNotFoundException fne) {
- fail("Unexpected FileNotFoundException " + fne.toString());
- } catch(IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch(SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
-
- /**
- * @test javax.xml.parsers.SAXParser#parse(org.xml.sax.InputSource,
- * org.xml.sax.helpers.DefaultHandler)
- */
- public void test_parseLorg_xml_sax_InputSourceLorg_xml_sax_helpers_DefaultHandler()
- throws Exception {
- for(int i = 0; i < list_wf.length; i++) {
- HashMap<String, String> hm = new SAXParserTestSupport().readFile(
- list_out_dh[i].getPath());
- MyDefaultHandler dh = new MyDefaultHandler();
- InputSource is = new InputSource(new FileInputStream(list_wf[i]));
- parser.parse(is, dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for (File file : list_nwf) {
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- InputSource is = new InputSource(new FileInputStream(file));
- parser.parse(is, dh);
- fail("SAXException is not thrown");
- } catch (SAXException expected) {
- }
- }
-
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse((InputSource) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- InputSource is = new InputSource(new FileInputStream(list_wf[0]));
- parser.parse(is, (DefaultHandler) null);
-
- InputStream in = null;
- try {
- in = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
- is = new InputSource(in);
- parser.parse(is, (DefaultHandler) null);
- fail("IOException expected");
- } catch(IOException expected) {
- } finally {
- in.close();
- }
- }
-
- public void testParseInputSourceHandlerBase() throws Exception {
- for(int i = 0; i < list_wf.length; i++) {
- HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath());
- MyHandler dh = new MyHandler();
- InputSource is = new InputSource(new FileInputStream(list_wf[i]));
- parser.parse(is, dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for (File file : list_nwf) {
- try {
- MyHandler dh = new MyHandler();
- InputSource is = new InputSource(new FileInputStream(file));
- parser.parse(is, dh);
- fail("SAXException is not thrown");
- } catch (SAXException expected) {
- }
- }
-
- try {
- MyHandler dh = new MyHandler();
- parser.parse((InputSource) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(IllegalArgumentException expected) {
- }
-
- InputSource is = new InputSource(new FileInputStream(list_wf[0]));
- parser.parse(is, (HandlerBase) null);
-
- // Reader case
- is = new InputSource(new InputStreamReader(new FileInputStream(list_wf[0])));
- parser.parse(is, (HandlerBase) null);
-
- // SystemID case
- is = new InputSource(list_wf[0].toURI().toString());
- parser.parse(is, (HandlerBase) null);
-
- // Inject IOException
- InputStream in = null;
- try {
- in = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
- parser.parse(in, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("IOException expected");
- } catch(IOException expected) {
- } finally {
- in.close();
- }
- }
-
- /**
- * @test javax.xml.parsers.SAXParser#parse(java.io.InputStream,
- * org.xml.sax.helpers.DefaultHandler)
- */
- public void test_parseLjava_io_InputStreamLorg_xml_sax_helpers_DefaultHandler()
- throws Exception {
-
- for(int i = 0; i < list_wf.length; i++) {
-
- HashMap<String, String> hm = new SAXParserTestSupport().readFile(
- list_out_dh[i].getPath());
- MyDefaultHandler dh = new MyDefaultHandler();
- InputStream is = new FileInputStream(list_wf[i]);
- parser.parse(is, dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for(int i = 0; i < list_nwf.length; i++) {
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- InputStream is = new FileInputStream(list_nwf[i]);
- parser.parse(is, dh);
- fail("SAXException is not thrown");
- } catch(org.xml.sax.SAXException se) {
- //expected
- }
- }
-
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse((InputStream) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(java.lang.IllegalArgumentException iae) {
- //expected
- }
-
- try {
- InputStream is = new FileInputStream(list_wf[0]);
- parser.parse(is, (DefaultHandler) null);
- } catch(java.lang.IllegalArgumentException iae) {
- fail("java.lang.IllegalArgumentException is thrown");
- }
- }
-
- /**
- * @test javax.xml.parsers.SAXParser#parse(java.io.InputStream,
- * org.xml.sax.helpers.DefaultHandler, java.lang.String)
- */
- @KnownFailure("We supply optional qnames, but this test doesn't expect them")
- public void test_parseLjava_io_InputStreamLorg_xml_sax_helpers_DefaultHandlerLjava_lang_String() {
- for(int i = 0; i < list_wf.length; i++) {
- try {
- HashMap<String, String> hm = sp.readFile(
- list_out_hb[i].getPath());
- MyDefaultHandler dh = new MyDefaultHandler();
- InputStream is = new FileInputStream(list_wf[i]);
- parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
- assertEquals(hm, dh.createData());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
-
- for(int i = 0; i < list_nwf.length; i++) {
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- InputStream is = new FileInputStream(list_nwf[i]);
- parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("SAXException is not thrown");
- } catch(org.xml.sax.SAXException se) {
- //expected
- } catch (FileNotFoundException fne) {
- fail("Unexpected FileNotFoundException " + fne.toString());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- }
- }
-
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse((InputStream) null, dh,
- SAXParserTestSupport.XML_SYSTEM_ID);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(java.lang.IllegalArgumentException iae) {
- //expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch(SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- try {
- InputStream is = new FileInputStream(list_wf[0]);
- parser.parse(is, (DefaultHandler) null,
- SAXParserTestSupport.XML_SYSTEM_ID);
- } catch(java.lang.IllegalArgumentException iae) {
- fail("java.lang.IllegalArgumentException is thrown");
- } catch (FileNotFoundException fne) {
- fail("Unexpected FileNotFoundException " + fne.toString());
- } catch(IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch(SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-//
-// for(int i = 0; i < list_wf.length; i++) {
-//
-// HashMap<String, String> hm = new SAXParserTestSupport().readFile(
-// list_out_dh[i].getPath());
-// MyDefaultHandler dh = new MyDefaultHandler();
-// InputStream is = new FileInputStream(list_wf[i]);
-// parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
-// assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
-// }
-//
-// for(int i = 0; i < list_nwf.length; i++) {
-// try {
-// MyDefaultHandler dh = new MyDefaultHandler();
-// InputStream is = new FileInputStream(list_nwf[i]);
-// parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
-// fail("SAXException is not thrown");
-// } catch(org.xml.sax.SAXException se) {
-// //expected
-// }
-// }
-//
-// try {
-// MyDefaultHandler dh = new MyDefaultHandler();
-// parser.parse((InputStream) null, dh,
-// SAXParserTestSupport.XML_SYSTEM_ID);
-// fail("java.lang.IllegalArgumentException is not thrown");
-// } catch(java.lang.IllegalArgumentException iae) {
-// //expected
-// }
-//
-// try {
-// InputStream is = new FileInputStream(list_wf[0]);
-// parser.parse(is, (DefaultHandler) null,
-// SAXParserTestSupport.XML_SYSTEM_ID);
-// } catch(java.lang.IllegalArgumentException iae) {
-// fail("java.lang.IllegalArgumentException is thrown");
-// }
-//
-// // TODO commented out since our parser is nonvalidating and thus never
-// // tries to load staff.dtd in "/" ... and therefore never can fail with
-// // an IOException
-// /*try {
-// MyDefaultHandler dh = new MyDefaultHandler();
-// InputStream is = new FileInputStream(list_wf[0]);
-// parser.parse(is, dh, "/");
-// fail("Expected IOException was not thrown");
-// } catch(IOException ioe) {
-// // expected
-// }*/
- }
-
- public void testParseInputStreamHandlerBase() throws Exception {
- for(int i = 0; i < list_wf.length; i++) {
- HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath());
- MyHandler dh = new MyHandler();
- InputStream is = new FileInputStream(list_wf[i]);
- parser.parse(is, dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for (File file : list_nwf) {
- try {
- MyHandler dh = new MyHandler();
- InputStream is = new FileInputStream(file);
- parser.parse(is, dh);
- fail("SAXException is not thrown");
- } catch (SAXException expected) {
- }
- }
-
- try {
- MyHandler dh = new MyHandler();
- parser.parse((InputStream) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch (IllegalArgumentException expected) {
- }
-
- InputStream is = new FileInputStream(list_wf[0]);
- parser.parse(is, (HandlerBase) null);
-
- // Inject IOException
- try {
- is = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
- parser.parse(is, (HandlerBase) null);
- fail("IOException expected");
- } catch(IOException e) {
- // Expected
- } finally {
- is.close();
- }
- }
-
- public void testParseInputStreamHandlerBaseString() throws Exception {
- for(int i = 0; i < list_wf.length; i++) {
- HashMap<String, String> hm = sp.readFile(list_out_hb[i].getPath());
- MyHandler dh = new MyHandler();
- InputStream is = new FileInputStream(list_wf[i]);
- parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for (File file : list_nwf) {
- try {
- MyHandler dh = new MyHandler();
- InputStream is = new FileInputStream(file);
- parser.parse(is, dh, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("SAXException is not thrown");
- } catch (SAXException expected) {
- }
- }
-
- try {
- MyHandler dh = new MyHandler();
- parser.parse(null, dh, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(IllegalArgumentException expected) {
- }
-
- InputStream is = new FileInputStream(list_wf[0]);
- parser.parse(is, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID);
-
- // Inject IOException
- try {
- is = new BrokenInputStream(new FileInputStream(list_wf[0]), 10);
- parser.parse(is, (HandlerBase) null, SAXParserTestSupport.XML_SYSTEM_ID);
- fail("IOException expected");
- } catch(IOException expected) {
- } finally {
- is.close();
- }
- }
-
- /**
- * @test javax.xml.parsers.SAXParser#parse(java.lang.String,
- * org.xml.sax.helpers.DefaultHandler)
- */
- public void test_parseLjava_lang_StringLorg_xml_sax_helpers_DefaultHandler()
- throws Exception {
-
- for(int i = 0; i < list_wf.length; i++) {
-
- HashMap<String, String> hm = new SAXParserTestSupport().readFile(
- list_out_dh[i].getPath());
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse(list_wf[i].toURI().toString(), dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm, dh.createData()));
- }
-
- for(int i = 0; i < list_nwf.length; i++) {
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse(list_nwf[i].toURI().toString(), dh);
- fail("SAXException is not thrown");
- } catch(org.xml.sax.SAXException se) {
- //expected
- }
- }
-
- try {
- MyDefaultHandler dh = new MyDefaultHandler();
- parser.parse((String) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(java.lang.IllegalArgumentException iae) {
- //expected
- }
-
- try {
- parser.parse(list_wf[0].toURI().toString(), (DefaultHandler) null);
- } catch(java.lang.IllegalArgumentException iae) {
- fail("java.lang.IllegalArgumentException is thrown");
- }
- }
-
- public void testParseStringHandlerBase() {
- for(int i = 0; i < list_wf.length; i++) {
- try {
- HashMap<String, String> hm = sp.readFile(
- list_out_hb[i].getPath());
- MyHandler dh = new MyHandler();
- parser.parse(list_wf[i].toURI().toString(), dh);
- assertTrue(SAXParserTestSupport.equalsMaps(hm,
- dh.createData()));
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch (SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
-
- for(int i = 0; i < list_nwf.length; i++) {
- try {
- MyHandler dh = new MyHandler();
- parser.parse(list_nwf[i].toURI().toString(), dh);
- fail("SAXException is not thrown");
- } catch(org.xml.sax.SAXException se) {
- //expected
- } catch (FileNotFoundException fne) {
- fail("Unexpected FileNotFoundException " + fne.toString());
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- }
- }
-
- try {
- MyHandler dh = new MyHandler();
- parser.parse((String) null, dh);
- fail("java.lang.IllegalArgumentException is not thrown");
- } catch(java.lang.IllegalArgumentException iae) {
- //expected
- } catch (IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch(SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
-
- try {
- parser.parse(list_wf[0].toURI().toString(), (HandlerBase) null);
- } catch(java.lang.IllegalArgumentException iae) {
- fail("java.lang.IllegalArgumentException is thrown");
- } catch (FileNotFoundException fne) {
- fail("Unexpected FileNotFoundException " + fne.toString());
- } catch(IOException ioe) {
- fail("Unexpected IOException " + ioe.toString());
- } catch(SAXException sax) {
- fail("Unexpected SAXException " + sax.toString());
- }
- }
-
- public void testReset() {
- try {
- spf = SAXParserFactory.newInstance();
- parser = spf.newSAXParser();
-
- parser.setProperty(LEXICAL_HANDLER_PROPERTY, new MockHandler(new MethodLogger()));
- parser.reset();
- assertEquals(null, parser.getProperty(LEXICAL_HANDLER_PROPERTY));
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetParser() {
- spf = SAXParserFactory.newInstance();
- try {
- Parser parser = spf.newSAXParser().getParser();
- assertNotNull(parser);
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetReader() {
- spf = SAXParserFactory.newInstance();
- try {
- XMLReader reader = spf.newSAXParser().getXMLReader();
- assertNotNull(reader);
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testSetGetProperty() {
- // Ordinary case
- String validName = "http://xml.org/sax/properties/lexical-handler";
- LexicalHandler validValue = new MockHandler(new MethodLogger());
-
- try {
- SAXParser parser = spf.newSAXParser();
- parser.setProperty(validName, validValue);
- assertEquals(validValue, parser.getProperty(validName));
-
- parser.setProperty(validName, null);
- assertEquals(null, parser.getProperty(validName));
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // Unsupported property
- try {
- SAXParser parser = spf.newSAXParser();
- parser.setProperty("foo", "bar");
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- try {
- SAXParser parser = spf.newSAXParser();
- parser.getProperty("foo");
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // No name case
- try {
- SAXParser parser = spf.newSAXParser();
- parser.setProperty(null, "bar");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- try {
- SAXParser parser = spf.newSAXParser();
- parser.getProperty(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- } catch (Exception e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java b/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java
deleted file mode 100644
index 2b7e1da..0000000
--- a/luni/src/test/java/tests/api/javax/xml/parsers/SAXParserTestSupport.java
+++ /dev/null
@@ -1,492 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.javax.xml.parsers;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.HandlerBase;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.DefaultHandler;
-
-/**
- * Support for SAXParserTest. Shares the element keys used in the golden files.
- * Compares the result of the parser with golden data.
- * Contains the handler classes used to track the output of the parser.
- */
-class SAXParserTestSupport {
-
- public static final char SEPARATOR_ELEMENT = '^';
- public static final char SEPARATOR_STRING = '$';
- public static final char SEPARATOR_DATA = '#';
-
- public static final String XML_WF = "/wf/";
- public static final String XML_NWF = "/nwf/";
-
- public static final String XML_WF_OUT_DH = "/out_dh/";
- public static final String XML_WF_OUT_HB = "/out_hb/";
-
- public static final String XML_SYSTEM_ID = "." + "/systemid/";
-
- public static final String KEY_IS_START_DOC = "isEndDocument";
- public static final String KEY_IS_END_DOC = "isStartDocument";
- public static final String KEY_TEXT = "text";
- public static final String KEY_ERROR = "error";
- public static final String KEY_FATAL_ERROR = "fatalError";
- public static final String KEY_WARNING = "warning";
- public static final String KEY_END_ELEMENT = "endElement";
- public static final String KEY_END_PREFIX_MAPPING = "endPrefixMapping";
- public static final String KEY_IGNORABLE_WHITE_SPACE =
- "ignorableWhitespace";
- public static final String KEY_NOTATION_DECL = "notationDecl";
- public static final String KEY_PROCESSING_INSTRUCTION =
- "processingInstruction";
- public static final String KEY_RESOLVE_ENTITY = "resolveEntity";
- public static final String KEY_DOCUMENT_LOCATORS = "documentLocators";
- public static final String KEY_SKIPPED_ENTITY = "skippedEntity";
- public static final String KEY_START_ELEMENT = "startElement";
- public static final String KEY_START_PREFIX_MAPPING = "startPrefixMapping";
- public static final String KEY_UNPARSED_ENTITY_DECL = "unparsedEntityDecl";
-
- static String [] KEYS = {KEY_IS_START_DOC, KEY_IS_END_DOC, KEY_TEXT,
- KEY_ERROR, KEY_FATAL_ERROR, KEY_WARNING, KEY_END_ELEMENT,
- KEY_END_PREFIX_MAPPING, KEY_PROCESSING_INSTRUCTION,
- KEY_SKIPPED_ENTITY, KEY_START_ELEMENT,
- KEY_START_PREFIX_MAPPING};
-
- static {
- String tmp = System.getProperty("java.io.tmpdir", ".");
-
- new File(tmp).mkdirs();
- new File(tmp, XML_WF).mkdirs();
- new File(tmp, XML_NWF).mkdirs();
- new File(tmp, XML_WF_OUT_DH).mkdirs();
- new File(tmp, XML_WF_OUT_HB).mkdirs();
- }
-
- /**
- * Initialize the SAXParserTest reference by filling in the data from the
- * file passed to the method. This will be the reference to compare
- * against with the output of the parser.
- */
- public HashMap<String, String> readFile(String fileName) {
- HashMap<String, String> storage = new HashMap<String, String>();
- try {
-
- InputStream is = new FileInputStream(fileName);
-
- int c = is.read();
-
- StringBuffer str = new StringBuffer();
- int i = 0;
- while(c != -1) {
- if((char)c == SEPARATOR_DATA) {
- // if(str.length() > 0) {
- if(i < KEYS.length) {
- storage.put(KEYS[i], str.toString());
- // System.out.println(str.toString());
- str.setLength(0);
- i++;
- }
- // }
- } else {
- str.append((char)c);
- }
- try {
- c = is.read();
- } catch (Exception e) {
- c = -1;
- }
- }
- try {
- is.close();
- } catch (IOException e) {
- }
-
- } catch(IOException ioe) {
- System.out.println("IOException during processing the file: "
- + fileName);
- }
- return storage;
- }
-
- /**
- * Compares the content of two HashMaps. One map should be the reference
- * containing the correct string for each xml document element and the other
- * should contain the elements filled with output from the parser.
- *
- * @param original the reference
- * @param result the result of the parser
- * @return true if they're equal.
- */
- public static boolean equalsMaps(HashMap<String, String> original,
- HashMap<String, String> result) {
-
- if(original == null && result == null) {
- return true;
- } else {
- if(original.size() != result.size()) return false;
-
- for(int i = 0; i < KEYS.length; i++) {
- if(!original.get(KEYS[i]).equals(result.get(KEYS[i]))) {
- System.out.println("for "+KEYS[i]+": original:" +
- original.get(KEYS[i]));
- System.out.println();
- System.out.println(" result:" + result.get(KEYS[i]));
- System.out.println();
- return false;
- }
- }
- return true;
- }
- }
-
- static class MyDefaultHandler extends DefaultHandler {
-
- public StringBuffer data_isEndDocument = new StringBuffer();
- public StringBuffer data_isStartDocument = new StringBuffer();
- public StringBuffer data_text = new StringBuffer();
- public StringBuffer data_error = new StringBuffer();
- public StringBuffer data_fatalError = new StringBuffer();
- public StringBuffer data_warning = new StringBuffer();
- public StringBuffer data_endElement = new StringBuffer();
- public StringBuffer data_endPrefixMapping = new StringBuffer();
- public StringBuffer data_processingInstruction = new StringBuffer();
- public StringBuffer data_skippedEntity = new StringBuffer();
- public StringBuffer data_startElement = new StringBuffer();
- public StringBuffer data_startPrefixMapping = new StringBuffer();
-
- public HashMap<String, String> createData() {
- HashMap<String, String> hm = new HashMap<String, String>();
- hm.put(KEY_IS_END_DOC, data_isEndDocument.toString());
- hm.put(KEY_IS_START_DOC, data_isStartDocument.toString());
- hm.put(KEY_TEXT, data_text.toString());
- hm.put(KEY_ERROR, data_error.toString());
- hm.put(KEY_FATAL_ERROR, data_fatalError.toString());
- hm.put(KEY_WARNING, data_warning.toString());
- hm.put(KEY_END_ELEMENT, data_endElement.toString());
- hm.put(KEY_END_PREFIX_MAPPING, data_endPrefixMapping.toString());
-
- hm.put(KEY_PROCESSING_INSTRUCTION,
- data_processingInstruction.toString());
- hm.put(KEY_SKIPPED_ENTITY, data_skippedEntity.toString());
- hm.put(KEY_START_ELEMENT, data_startElement.toString());
- hm.put(KEY_START_PREFIX_MAPPING,
- data_startPrefixMapping.toString());
- return hm;
- }
-
- public void printMap() {
- System.out.print(data_isStartDocument.toString() + SEPARATOR_DATA +
- data_isEndDocument.toString() + SEPARATOR_DATA +
- data_text.toString() + SEPARATOR_DATA +
- data_error.toString()+ SEPARATOR_DATA +
- data_fatalError.toString()+ SEPARATOR_DATA +
- data_warning.toString()+ SEPARATOR_DATA +
- data_endElement.toString() + SEPARATOR_DATA+
- data_endPrefixMapping.toString()+ SEPARATOR_DATA +
- data_processingInstruction.toString() + SEPARATOR_DATA +
- data_skippedEntity.toString() + SEPARATOR_DATA +
- data_startElement.toString() + SEPARATOR_DATA +
- data_startPrefixMapping.toString()+ SEPARATOR_DATA);
- }
-
- @Override
- public void characters(char[] ch, int start, int length) {
- String str = new String(ch, start, length);
- data_text.append(str);
- // different sax parsers are allowed to handle chunking differently,
- // therefore we cannot rely on identical chunks being delivered.
- //data_text.append(ParsingSupport.SEPARATOR_ELEMENT);
- }
-
- @Override
- public void endDocument() {
- data_isEndDocument.append(true);
- data_isEndDocument.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void endElement(String uri, String localName, String qName) {
- StringBuffer sb = new StringBuffer();
- sb.append(uri);
- sb.append(SEPARATOR_STRING);
- sb.append(localName);
- sb.append(SEPARATOR_STRING);
- sb.append(qName);
- data_endElement.append(sb);
- data_endElement.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void endPrefixMapping(String prefix) {
- data_endPrefixMapping.append(prefix);
- data_endPrefixMapping.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void error(SAXParseException e) {
- data_error.append(e);
- data_error.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void fatalError(SAXParseException e) {
- data_fatalError.append(e);
- data_fatalError.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void ignorableWhitespace(char[] ch, int start, int length) {
- /* String s = new String(ch, start, length);
- ignorableWhitespace.append(s);
- ignorableWhitespace.append(ParsingSupport.SEPARATOR_ELEMENT);*/
- }
-
- @Override
- public void notationDecl(String name, String publicId,
- String systemId) {
- /* data_notationDecl.append(name + ParsingSupport.SEPARATOR_STRING +
- publicId + ParsingSupport.SEPARATOR_STRING +
- systemId + ParsingSupport.SEPARATOR_STRING);
- data_notationDecl.append(ParsingSupport.SEPARATOR_ELEMENT);*/
- }
-
- @Override
- public void processingInstruction(String target, String data) {
- data_processingInstruction.append(target + SEPARATOR_STRING + data);
- data_processingInstruction.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public InputSource resolveEntity(String publicId, String systemId) {
- // data_resolveEntity.append(publicId +
- // ParsingSupport.SEPARATOR_STRING + systemId);
- // data_resolveEntity.append(ParsingSupport.SEPARATOR_ELEMENT);
- return null;
- }
-
- @Override
- public void setDocumentLocator(Locator locator) {
- // data_documentLocators.append(locator);
- // data_documentLocators.append(ParsingSupport.SEPARATOR_ELEMENT);
- }
-
- @Override
- public void skippedEntity(String name) {
- data_skippedEntity.append(name);
- data_skippedEntity.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void startDocument() {
- data_isStartDocument.append(true);
- data_isStartDocument.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) {
- data_startElement.append(uri);
- data_startElement.append(SEPARATOR_STRING);
- data_startElement.append(localName);
- data_startElement.append(SEPARATOR_STRING);
- data_startElement.append(qName);
-
- for(int i = 0; i < attributes.getLength(); i ++)
- data_startElement.append(
- SEPARATOR_STRING +attributes.getQName(i) +
- SEPARATOR_STRING + attributes.getValue(i));
-
- data_isStartDocument.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void startPrefixMapping(String prefix, String uri) {
- data_startPrefixMapping.append(prefix + SEPARATOR_STRING + uri);
- }
-
- @Override
- public void unparsedEntityDecl(String name, String publicId,
- String systemId, String notationName) {
- // data_unparsedEntityDecl.append(name
- // + ParsingSupport.SEPARATOR_STRING + publicId
- // + ParsingSupport.SEPARATOR_STRING
- // + systemId + ParsingSupport.SEPARATOR_STRING + notationName);
- }
-
- @Override
- public void warning(SAXParseException e) {
- data_warning.append(e);
- }
- }
-
- @SuppressWarnings("deprecation")
- static class MyHandler extends HandlerBase {
-
- public StringBuffer data_isEndDocument = new StringBuffer();
- public StringBuffer data_isStartDocument = new StringBuffer();
- public StringBuffer data_text = new StringBuffer();
- public StringBuffer data_error = new StringBuffer();
- public StringBuffer data_fatalError = new StringBuffer();
- public StringBuffer data_warning = new StringBuffer();
- public StringBuffer data_endElement = new StringBuffer();
- public StringBuffer data_endPrefixMapping = new StringBuffer();
- public StringBuffer data_processingInstruction = new StringBuffer();
- public StringBuffer data_skippedEntity = new StringBuffer();
- public StringBuffer data_startElement = new StringBuffer();
- public StringBuffer data_startPrefixMapping = new StringBuffer();
-
- public void printMap() {
- System.out.print(data_isStartDocument.toString() + SEPARATOR_DATA +
- data_isEndDocument.toString() + SEPARATOR_DATA +
- data_text.toString() + SEPARATOR_DATA +
- data_error.toString()+ SEPARATOR_DATA +
- data_fatalError.toString()+ SEPARATOR_DATA +
- data_warning.toString()+ SEPARATOR_DATA +
- data_endElement.toString() + SEPARATOR_DATA+
- data_endPrefixMapping.toString()+ SEPARATOR_DATA +
- data_processingInstruction.toString() + SEPARATOR_DATA +
- data_skippedEntity.toString() + SEPARATOR_DATA +
- data_startElement.toString() + SEPARATOR_DATA +
- data_startPrefixMapping.toString()+ SEPARATOR_DATA);
- }
-
- public HashMap<String, String> createData() {
- HashMap<String, String> hm = new HashMap<String, String>();
- hm.put(KEY_IS_END_DOC, data_isEndDocument.toString());
- hm.put(KEY_IS_START_DOC, data_isStartDocument.toString());
- hm.put(KEY_TEXT, data_text.toString());
- hm.put(KEY_ERROR, data_error.toString());
- hm.put(KEY_FATAL_ERROR, data_fatalError.toString());
- hm.put(KEY_WARNING, data_warning.toString());
- hm.put(KEY_END_ELEMENT, data_endElement.toString());
- hm.put(KEY_END_PREFIX_MAPPING, data_endPrefixMapping.toString());
- hm.put(KEY_PROCESSING_INSTRUCTION,
- data_processingInstruction.toString());
- hm.put(KEY_SKIPPED_ENTITY, data_skippedEntity.toString());
- hm.put(KEY_START_ELEMENT, data_startElement.toString());
- hm.put(KEY_START_PREFIX_MAPPING,
- data_startPrefixMapping.toString());
- return hm;
- }
-
- @Override
- public void characters(char[] ch, int start, int length) {
- String str = new String(ch, start, length);
- data_text.append(str);
- // different sax parsers are allowed to handle chunking differently,
- // therefore we cannot rely on identical chunks being delivered.
- //data_text.append(ParsingSupport.SEPARATOR_ELEMENT);
- }
-
- @Override
- public void endDocument() {
- data_isEndDocument.append(true);
- data_isEndDocument.append(SEPARATOR_ELEMENT);
- }
-
- public void endElement(String uri, String localName, String qName) {
- StringBuffer sb = new StringBuffer();
- sb.append(uri);
- sb.append(SEPARATOR_STRING);
- sb.append(localName);
- sb.append(SEPARATOR_STRING);
- sb.append(qName);
- data_endElement.append(sb);
- data_endElement.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void error(SAXParseException e) {
- data_error.append(e);
- data_error.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void fatalError(SAXParseException e) {
- data_fatalError.append(e);
- data_fatalError.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void ignorableWhitespace(char[] ch, int start, int length) {
-
- }
-
- @Override
- public void notationDecl(String name, String publicId,
- String systemId) {
-
- }
-
- @Override
- public void processingInstruction(String target, String data) {
- data_processingInstruction.append(target + SEPARATOR_STRING + data);
- data_processingInstruction.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public InputSource resolveEntity(String publicId, String systemId) {
- return null;
- }
-
- @Override
- public void setDocumentLocator(Locator locator) {
-
- }
-
- @Override
- public void startDocument() {
- data_isStartDocument.append(true);
- data_isStartDocument.append(SEPARATOR_ELEMENT);
- }
-
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) {
- data_startElement.append(uri);
- data_startElement.append(SEPARATOR_STRING);
- data_startElement.append(localName);
- data_startElement.append(SEPARATOR_STRING);
- data_startElement.append(qName);
-
- for(int i = 0; i < attributes.getLength(); i ++)
- data_startElement.append(SEPARATOR_STRING
- + attributes.getQName(i) +
- SEPARATOR_STRING + attributes.getValue(i));
-
- data_isStartDocument.append(SEPARATOR_ELEMENT);
- }
-
- @Override
- public void unparsedEntityDecl(String name, String publicId,
- String systemId, String notationName) {
-
- }
-
- @Override
- public void warning(SAXParseException e) {
- data_warning.append(e);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java b/luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java
deleted file mode 100644
index 19c6229..0000000
--- a/luni/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/ThreadsTest.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.apache.harmony.kernel.dalvik;
-
-import java.lang.reflect.Field;
-import java.util.concurrent.CyclicBarrier;
-import java.util.concurrent.TimeUnit;
-import junit.framework.Assert;
-import junit.framework.TestCase;
-import sun.misc.Unsafe;
-
-/**
- * Tests for the <code>park()</code> functionality of {@link Unsafe}.
- */
-public class ThreadsTest extends TestCase {
- private static Unsafe UNSAFE = null;
- static {
- /*
- * Set up {@link #UNSAFE}. This subverts the access check to
- * get the unique Unsafe instance. We can do this because
- * there's no security manager installed when running the
- * test.
- */
- try {
- Field field = Unsafe.class.getDeclaredField("THE_ONE");
- field.setAccessible(true);
-
- UNSAFE = (Unsafe) field.get(null);
- } catch (NoSuchFieldException ex) {
- throw new RuntimeException(ex);
- } catch (IllegalAccessException ex) {
- throw new RuntimeException(ex);
- }
- }
-
- /** Test the case where the park times out. */
- public void test_parkFor_1() throws Exception {
- CyclicBarrier barrier = new CyclicBarrier(2);
- Parker parker = new Parker(barrier, false, 500);
- Thread parkerThread = new Thread(parker);
- Thread waiterThread =
- new Thread(new WaitAndUnpark(barrier, 1000, parkerThread));
-
- parkerThread.start();
- waiterThread.start();
- parker.assertDurationIsInRange(500);
- waiterThread.join();
- parkerThread.join();
- }
-
- /** Test the case where the unpark happens before the timeout. */
- public void test_parkFor_2() throws Exception {
- CyclicBarrier barrier = new CyclicBarrier(2);
- Parker parker = new Parker(barrier, false, 1000);
- Thread parkerThread = new Thread(parker);
- Thread waiterThread =
- new Thread(new WaitAndUnpark(barrier, 300, parkerThread));
-
- parkerThread.start();
- waiterThread.start();
- parker.assertDurationIsInRange(300);
- waiterThread.join();
- parkerThread.join();
- }
-
- /** Test the case where the thread is preemptively unparked. */
- public void test_parkFor_3() throws Exception {
- CyclicBarrier barrier = new CyclicBarrier(1);
- Parker parker = new Parker(barrier, false, 1000);
- Thread parkerThread = new Thread(parker);
-
- UNSAFE.unpark(parkerThread);
- parkerThread.start();
- parker.assertDurationIsInRange(0);
- parkerThread.join();
- }
-
- /** Test the case where the park times out. */
- public void test_parkUntil_1() throws Exception {
- CyclicBarrier barrier = new CyclicBarrier(2);
- Parker parker = new Parker(barrier, true, 500);
- Thread parkerThread = new Thread(parker);
- Thread waiterThread =
- new Thread(new WaitAndUnpark(barrier, 1000, parkerThread));
-
- parkerThread.start();
- waiterThread.start();
- parker.assertDurationIsInRange(500);
- waiterThread.join();
- parkerThread.join();
- }
-
- /** Test the case where the unpark happens before the timeout. */
- public void test_parkUntil_2() throws Exception {
- CyclicBarrier barrier = new CyclicBarrier(2);
- Parker parker = new Parker(barrier, true, 1000);
- Thread parkerThread = new Thread(parker);
- Thread waiterThread =
- new Thread(new WaitAndUnpark(barrier, 300, parkerThread));
-
- parkerThread.start();
- waiterThread.start();
- parker.assertDurationIsInRange(300);
- waiterThread.join();
- parkerThread.join();
- }
-
- /** Test the case where the thread is preemptively unparked. */
- public void test_parkUntil_3() throws Exception {
- CyclicBarrier barrier = new CyclicBarrier(1);
- Parker parker = new Parker(barrier, true, 1000);
- Thread parkerThread = new Thread(parker);
-
- UNSAFE.unpark(parkerThread);
- parkerThread.start();
- parker.assertDurationIsInRange(0);
- parkerThread.join();
- }
-
- // TODO: Add more tests.
-
- /**
- * Helper <code>Runnable</code> for tests, which parks for or until
- * the indicated value, noting the duration of time actually parked.
- */
- private static class Parker implements Runnable {
-
- private final CyclicBarrier barrier;
-
- /** whether {@link #amount} is milliseconds to wait in an
- * absolute fashion (<code>true</code>) or nanoseconds to wait
- * in a relative fashion (<code>false</code>) */
- private final boolean absolute;
-
- /** amount to wait (see above) */
- private final long amount;
-
- /** whether the run has completed */
- private boolean completed;
-
- /** recorded start time */
- private long startMillis;
-
- /** recorded end time */
- private long endMillis;
-
- /**
- * Construct an instance.
- *
- * @param absolute whether to use an absolute time or not; in
- * either case, this constructor takes a duration to park for
- * @param parkMillis the number of milliseconds to be parked
- */
- public Parker(CyclicBarrier barrier, boolean absolute, long parkMillis) {
- this.barrier = barrier;
- this.absolute = absolute;
-
- // Multiply by 1000000 because parkFor() takes nanoseconds.
- this.amount = absolute ? parkMillis : parkMillis * 1000000;
- }
-
- public void run() {
- try {
- barrier.await(60, TimeUnit.SECONDS);
- } catch (Exception e) {
- throw new AssertionError(e);
- }
- boolean absolute = this.absolute;
- long amount = this.amount;
- long startNanos = System.nanoTime();
- long start = System.currentTimeMillis();
-
- if (absolute) {
- UNSAFE.park(true, start + amount);
- } else {
- UNSAFE.park(false, amount);
- }
-
- long endNanos = System.nanoTime();
-
- synchronized (this) {
- startMillis = startNanos / 1000000;
- endMillis = endNanos / 1000000;
- completed = true;
- notifyAll();
- }
- }
-
- /**
- * Wait for the test to complete and return the duration.
- *
- * @param maxWaitMillis the maximum amount of time to
- * wait for the test to complete
- * @return the duration in milliseconds
- */
- public long getDurationMillis(long maxWaitMillis) {
- synchronized (this) {
- if (! completed) {
- try {
- wait(maxWaitMillis);
- } catch (InterruptedException ignored) {
- }
- if (! completed) {
- Assert.fail("parker hung for more than " + maxWaitMillis + " ms");
- }
- }
-
- return endMillis - startMillis;
- }
- }
-
- /**
- * Asserts that the actual duration is within 10% of the
- * given expected time.
- *
- * @param expectedMillis the expected duration, in milliseconds
- */
- public void assertDurationIsInRange(long expectedMillis) {
- /*
- * Allow a bit more slop for the maximum on "expected
- * instantaneous" results.
- */
- long minimum = (long) ((double) expectedMillis * 0.90);
- long maximum =
- Math.max((long) ((double) expectedMillis * 1.10), 10);
- long waitMillis = Math.max(expectedMillis * 10, 10);
- long duration = getDurationMillis(waitMillis);
-
- if (duration < minimum) {
- Assert.fail("expected duration: " + expectedMillis +
- " minimum duration: " + minimum +
- " actual duration too short: " + duration);
- } else if (duration > maximum) {
- Assert.fail("expected duration: " + expectedMillis +
- " maximum duration: " + maximum +
- " actual duration too long: " + duration);
- }
- }
- }
-
- /**
- * Helper <code>Runnable</code> for tests, which waits for the
- * specified amount of time and then unparks an indicated thread.
- */
- private static class WaitAndUnpark implements Runnable {
- private final CyclicBarrier barrier;
- private final long waitMillis;
- private final Thread thread;
-
- public WaitAndUnpark(CyclicBarrier barrier, long waitMillis, Thread thread) {
- this.barrier = barrier;
- this.waitMillis = waitMillis;
- this.thread = thread;
- }
-
- public void run() {
- try {
- barrier.await(60, TimeUnit.SECONDS);
- } catch (Exception e) {
- throw new AssertionError(e);
- }
- try {
- Thread.sleep(waitMillis);
- } catch (InterruptedException ex) {
- throw new RuntimeException("shouldn't happen", ex);
- }
-
- UNSAFE.unpark(thread);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java b/luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java
deleted file mode 100644
index 8dfe38b..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/HandlerBaseTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.AttributeList;
-import org.xml.sax.HandlerBase;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.AttributeListImpl;
-import org.xml.sax.helpers.LocatorImpl;
-
-@SuppressWarnings("deprecation")
-public class HandlerBaseTest extends TestCase {
-
- /*
- * Note: most of the tests have to check for an empty implementation of the
- * respective methods and, as a result, are somewhat trivial.
- */
-
- private HandlerBase h = new HandlerBase();
-
- public void testResolveEntity() {
- try {
- h.resolveEntity("publicID", "systemID");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testNotationDecl() {
- h.notationDecl("name", "publicID", "systemID");
- }
-
- public void testUnparsedEntityDecl() {
- h.unparsedEntityDecl("name", "publicID", "systemID", "notationName");
- }
-
- public void testSetDocumentLocator() {
- h.setDocumentLocator(new LocatorImpl());
- }
-
- public void testStartDocument() {
- try {
- h.startDocument();
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testEndDocument() {
- try {
- h.endDocument();
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testStartElement() {
- try {
- h.startElement("name", new AttributeListImpl());
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testEndElement() {
- try {
- h.endElement("name");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testCharacters() {
- try {
- h.characters("The quick brown fox".toCharArray(), 4, 11);
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testIgnorableWhitespace() {
- try {
- h.ignorableWhitespace(" ".toCharArray(), 4, 11);
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testProcessingInstruction() {
- try {
- h.processingInstruction("target", "data");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testWarning() {
- try {
- h.warning(new SAXParseException("Foo", new LocatorImpl()));
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testError() {
- try {
- h.error(new SAXParseException("Foo", new LocatorImpl()));
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testFatalError() {
- // Ordinary case
- try {
- h.fatalError(new SAXParseException("Foo", new LocatorImpl()));
- fail("SAXException expected");
- } catch (SAXException e) {
- // Expected
- }
-
- // No exception
- try {
- h.fatalError(null);
- fail("NullPointerException expected");
- } catch (SAXException e) {
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
-
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java b/luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java
deleted file mode 100644
index f9040f0..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/InputSourceTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.InputSource;
-
-public class InputSourceTest extends TestCase {
-
- public void testInputSource() {
- InputSource i = new InputSource();
-
- assertNull(i.getByteStream());
- assertNull(i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
- }
-
- public void testInputSourceString() {
- InputSource i = new InputSource("Foo");
-
- assertNull(i.getByteStream());
- assertNull(i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertEquals("Foo", i.getSystemId());
- }
-
- public void testInputSourceInputStream() {
- ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
-
- // Ordinary case
- InputSource i = new InputSource(bais);
-
- assertEquals(bais, i.getByteStream());
- assertNull(i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
-
- // No input stream
- i = new InputSource((InputStream)null);
-
- assertNull(i.getByteStream());
- assertNull(i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
- }
-
- public void testInputSourceReader() {
- StringReader sr = new StringReader("Hello, world.");
-
- // Ordinary case
- InputSource i = new InputSource(sr);
-
- assertNull(i.getByteStream());
- assertEquals(sr, i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
-
- // No reader
- i = new InputSource((Reader)null);
-
- assertNull(i.getByteStream());
- assertNull(i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
- }
-
- public void testSetPublicIdGetPublicId() {
- InputSource i = new InputSource();
-
- i.setPublicId("Foo");
- assertEquals("Foo", i.getPublicId());
-
- i.setPublicId(null);
- assertNull(i.getPublicId());
- }
-
- public void testSetSystemIdGetSystemId() {
- InputSource i = new InputSource();
-
- i.setSystemId("Foo");
- assertEquals("Foo", i.getSystemId());
-
- i.setSystemId(null);
- assertNull(i.getSystemId());
- }
-
- public void testSetByteStreamGetByteStream() {
- ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
-
- InputSource i = new InputSource();
-
- // Ordinary case
- i.setByteStream(bais);
-
- assertEquals(bais, i.getByteStream());
-
- // No input stream
- i.setByteStream(null);
-
- assertNull(i.getByteStream());
- }
-
- public void testSetEncodingGetEncoding() {
- InputSource i = new InputSource();
-
- // Ordinary case
- i.setEncoding("Klingon");
-
- assertEquals("Klingon", i.getEncoding());
-
- // No encoding
- i.setEncoding(null);
-
- assertNull(i.getEncoding());
- }
-
- public void testSetCharacterStreamGetCharacterStream() {
- StringReader sr = new StringReader("Hello, world.");
-
- InputSource i = new InputSource();
-
- // Ordinary case
- i.setCharacterStream(sr);
-
- assertNull(i.getByteStream());
- assertEquals(sr, i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
-
- // No reader
- i.setCharacterStream(null);
-
- assertNull(i.getByteStream());
- assertNull(i.getCharacterStream());
- assertNull(i.getEncoding());
- assertNull(i.getPublicId());
- assertNull(i.getSystemId());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java
deleted file mode 100644
index 11d00e7..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/SAXExceptionTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-
-public class SAXExceptionTest extends TestCase {
-
- public static final String ERR = "Houston, we have a problem";
-
- public void testSAXParseException() {
- SAXException e = new SAXException();
-
- assertNull(e.getMessage());
- assertNull(e.getException());
- }
-
- public void testSAXException_String_Exception() {
- Exception c = new Exception();
-
- // Ordinary case
- SAXException e = new SAXException(ERR, c);
-
- assertEquals(ERR, e.getMessage());
- assertEquals(c, e.getException());
-
- // No message
- e = new SAXException(null, c);
-
- assertNull(e.getMessage());
- assertEquals(c, e.getException());
-
- // No cause
- e = new SAXParseException(ERR, null);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
- }
-
- public void testSAXException_String() {
- // Ordinary case
- SAXException e = new SAXException(ERR);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- // No message
- e = new SAXException((String)null);
-
- assertNull(e.getMessage());
- assertNull(e.getException());
- }
-
- public void testSAXException_Exception() {
- Exception c = new Exception();
-
- // Ordinary case
- SAXException e = new SAXException(c);
-
- assertNull(e.getMessage());
- assertEquals(c, e.getException());
-
- // No cause
- e = new SAXException((Exception)null);
-
- assertNull(e.getMessage());
- assertNull(e.getException());
- }
-
- public void testToString() {
- // Ordinary case
- SAXException e = new SAXException(ERR);
- String s = e.toString();
-
- assertTrue(s.contains(ERR));
-
- // No message
- e = new SAXException();
- s = e.toString();
-
- assertFalse(s.contains(ERR));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java
deleted file mode 100644
index 3c73b56..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/SAXNotRecognizedExceptionTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.SAXNotRecognizedException;
-
-public class SAXNotRecognizedExceptionTest extends TestCase {
-
- public static final String ERR = "Houston, we have a problem";
-
- public void testSAXNotRecognizedException() {
- SAXNotRecognizedException e = new SAXNotRecognizedException();
- assertNull(e.getMessage());
- }
-
- public void testSAXNotRecognizedException_String() {
- SAXNotRecognizedException e = new SAXNotRecognizedException(ERR);
- assertEquals(ERR, e.getMessage());
-
- e = new SAXNotRecognizedException(null);
- assertNull(e.getMessage());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java
deleted file mode 100644
index 71ea455..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/SAXNotSupportedExceptionTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.SAXNotSupportedException;
-
-public class SAXNotSupportedExceptionTest extends TestCase {
-
- public static final String ERR = "Houston, we have a problem";
-
- public void testSAXNotSupportedException() {
- SAXNotSupportedException e = new SAXNotSupportedException();
- assertNull(e.getMessage());
- }
-
- public void testSAXNotSupportedException_String() {
- SAXNotSupportedException e = new SAXNotSupportedException(ERR);
- assertEquals(ERR, e.getMessage());
-
- e = new SAXNotSupportedException(null);
- assertNull(e.getMessage());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java b/luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java
deleted file mode 100644
index bfc48d4..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/SAXParseExceptionTest.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Locator;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.LocatorImpl;
-
-public class SAXParseExceptionTest extends TestCase {
-
- public static final String ERR = "Houston, we have a problem";
-
- public static final String SYS = "mySystemID";
-
- public static final String PUB = "myPublicID";
-
- public static final int ROW = 1;
-
- public static final int COL = 2;
-
- public void testSAXParseException_String_Locator_Exception() {
- LocatorImpl l = new LocatorImpl();
- l.setPublicId(PUB);
- l.setSystemId(SYS);
- l.setLineNumber(ROW);
- l.setColumnNumber(COL);
-
- Exception c = new Exception();
-
- // Ordinary case
- SAXParseException e = new SAXParseException(ERR, l, c);
-
- assertEquals(ERR, e.getMessage());
- assertEquals(c, e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No message
- e = new SAXParseException(null, l, c);
-
- assertNull(e.getMessage());
- assertEquals(c, e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No locator
- e = new SAXParseException(ERR, null, c);
-
- assertEquals(ERR, e.getMessage());
- assertEquals(c, e.getException());
-
- assertNull(e.getPublicId());
- assertNull(e.getSystemId());
- assertEquals(-1, e.getLineNumber());
- assertEquals(-1, e.getColumnNumber());
-
- // No cause
- e = new SAXParseException(ERR, l, null);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
- }
-
- public void testSAXParseException_String_Locator() {
- LocatorImpl l = new LocatorImpl();
- l.setPublicId(PUB);
- l.setSystemId(SYS);
- l.setLineNumber(ROW);
- l.setColumnNumber(COL);
-
- // Ordinary case
- SAXParseException e = new SAXParseException(ERR, l);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No message
- e = new SAXParseException(null, l);
-
- assertNull(e.getMessage());
- assertNull(e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No locator
- e = new SAXParseException(ERR, null);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- assertNull(e.getPublicId());
- assertNull(e.getSystemId());
- assertEquals(-1, e.getLineNumber());
- assertEquals(-1, e.getColumnNumber());
-
- }
-
- public void testSAXParseException_String_String_String_int_int_Exception() {
- Exception c = new Exception();
-
- // Ordinary case
- SAXParseException e = new SAXParseException(ERR, PUB, SYS, ROW, COL, c);
-
- assertEquals(ERR, e.getMessage());
- assertEquals(c, e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No message
- e = new SAXParseException(null, PUB, SYS, ROW, COL, c);
-
- assertNull(e.getMessage());
- assertEquals(c, e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No locator
- e = new SAXParseException(ERR, null, null, -1, -1, c);
-
- assertEquals(ERR, e.getMessage());
- assertEquals(c, e.getException());
-
- assertNull(e.getPublicId());
- assertNull(e.getSystemId());
- assertEquals(-1, e.getLineNumber());
- assertEquals(-1, e.getColumnNumber());
-
- // No cause
- e = new SAXParseException(ERR, PUB, SYS, ROW, COL, null);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
- }
-
- public void testSAXParseException_String_String_String_int_int() {
- // Ordinary case
- SAXParseException e = new SAXParseException(ERR, PUB, SYS, ROW, COL);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No message
- e = new SAXParseException(null, PUB, SYS, ROW, COL);
-
- assertNull(e.getMessage());
- assertNull(e.getException());
-
- assertEquals(PUB, e.getPublicId());
- assertEquals(SYS, e.getSystemId());
- assertEquals(ROW, e.getLineNumber());
- assertEquals(COL, e.getColumnNumber());
-
- // No locator
- e = new SAXParseException(ERR, null, null, -1, -1);
-
- assertEquals(ERR, e.getMessage());
- assertNull(e.getException());
-
- assertNull(e.getPublicId());
- assertNull(e.getSystemId());
- assertEquals(-1, e.getLineNumber());
- assertEquals(-1, e.getColumnNumber());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java
deleted file mode 100644
index 348bef5..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/ext/Attributes2ImplTest.java
+++ /dev/null
@@ -1,392 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.ext;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.ext.Attributes2Impl;
-import org.xml.sax.helpers.AttributesImpl;
-
-public class Attributes2ImplTest extends TestCase {
-
- // Note: The original SAX2 implementation of Attributes2Impl is
- // severely broken. Thus all of these tests will probably fail
- // unless the Android implementation of the class gets fixed.
-
- private Attributes2Impl empty = new Attributes2Impl();
-
- private Attributes2Impl multi = new Attributes2Impl();
-
- private Attributes2Impl cdata = new Attributes2Impl();
-
- @Override
- public void setUp() {
- multi.addAttribute("http://some.uri", "foo", "ns1:foo",
- "string", "abc");
- multi.addAttribute("http://some.uri", "bar", "ns1:bar",
- "string", "xyz");
- multi.addAttribute("http://some.other.uri", "answer", "ns2:answer",
- "int", "42");
- multi.addAttribute("http://yet.another.uri", "gabba", "ns3:gabba",
- "string", "gabba");
-
- multi.setDeclared(0, false);
- multi.setSpecified(0, false);
-
- multi.setDeclared(1, true);
- multi.setSpecified(1, false);
-
- multi.setDeclared(2, false);
- multi.setSpecified(2, true);
-
- multi.setDeclared(3, true);
- multi.setSpecified(3, true);
-
- cdata.addAttribute("http://yet.another.uri", "hey", "ns3:hey",
- "CDATA", "hey");
- }
-
- public void testSetAttributes() {
- // Ordinary case with Attributes2Impl
- Attributes2Impl attrs = new Attributes2Impl();
- attrs.addAttribute("", "", "john", "string", "doe");
-
- attrs.setAttributes(empty);
- assertEquals(0, attrs.getLength());
-
- attrs.setAttributes(multi);
- for (int i = 0; i < multi.getLength(); i++) {
- assertEquals(multi.getURI(i), attrs.getURI(i));
- assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
- assertEquals(multi.getQName(i), attrs.getQName(i));
- assertEquals(multi.getType(i), attrs.getType(i));
- assertEquals(multi.getValue(i), attrs.getValue(i));
- assertEquals(multi.isDeclared(i), attrs.isDeclared(i));
- assertEquals(multi.isSpecified(i), attrs.isSpecified(i));
- }
-
- attrs.setAttributes(empty);
- assertEquals(0, attrs.getLength());
-
- // Ordinary case with AttributesImpl
- attrs.setAttributes(new AttributesImpl(multi));
- assertEquals(multi.getLength(), attrs.getLength());
-
- for (int i = 0; i < multi.getLength(); i++) {
- assertEquals(multi.getURI(i), attrs.getURI(i));
- assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
- assertEquals(multi.getQName(i), attrs.getQName(i));
- assertEquals(multi.getType(i), attrs.getType(i));
- assertEquals(multi.getValue(i), attrs.getValue(i));
- assertEquals(true, attrs.isDeclared(i));
- assertEquals(true, attrs.isSpecified(i));
- }
-
- // Special case with CDATA
- attrs.setAttributes(new AttributesImpl(cdata));
- assertEquals(1, attrs.getLength());
- assertEquals(false, attrs.isDeclared(0));
- assertEquals(true, attrs.isSpecified(0));
-
- // null case
- try {
- attrs.setAttributes(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testAddAttribute() {
- Attributes2Impl attrs = new Attributes2Impl();
-
- // Ordinary case
- attrs.addAttribute("http://yet.another.uri", "doe", "john:doe",
- "string", "abc");
-
- assertEquals(1, attrs.getLength());
-
- assertEquals("http://yet.another.uri", attrs.getURI(0));
- assertEquals("doe", attrs.getLocalName(0));
- assertEquals("john:doe", attrs.getQName(0));
- assertEquals("string", attrs.getType(0));
- assertEquals("abc", attrs.getValue(0));
-
- assertEquals(true, attrs.isDeclared(0));
- assertEquals(true, attrs.isSpecified(0));
-
- // CDATA case
- attrs.addAttribute("http://yet.another.uri", "doe", "jane:doe",
- "CDATA", "abc");
-
- assertEquals(2, attrs.getLength());
-
- assertEquals("http://yet.another.uri", attrs.getURI(1));
- assertEquals("doe", attrs.getLocalName(1));
- assertEquals("jane:doe", attrs.getQName(1));
- assertEquals("CDATA", attrs.getType(1));
- assertEquals("abc", attrs.getValue(1));
-
- assertEquals(false, attrs.isDeclared(1));
- assertEquals(true, attrs.isSpecified(1));
- }
-
- public void testRemoveAttribute() {
- Attributes2Impl attrs = new Attributes2Impl(multi);
-
- // Ordinary case
- attrs.removeAttribute(1);
-
- assertEquals(3, attrs.getLength());
-
- assertEquals(multi.getURI(0), attrs.getURI(0));
- assertEquals(multi.getLocalName(0), attrs.getLocalName(0));
- assertEquals(multi.getQName(0), attrs.getQName(0));
- assertEquals(multi.getType(0), attrs.getType(0));
- assertEquals(multi.getValue(0), attrs.getValue(0));
- assertEquals(multi.isDeclared(0), attrs.isDeclared(0));
- assertEquals(multi.isSpecified(0), attrs.isSpecified(0));
-
- assertEquals(multi.getURI(2), attrs.getURI(1));
- assertEquals(multi.getLocalName(2), attrs.getLocalName(1));
- assertEquals(multi.getQName(2), attrs.getQName(1));
- assertEquals(multi.getType(2), attrs.getType(1));
- assertEquals(multi.getValue(2), attrs.getValue(1));
- assertEquals(multi.isDeclared(2), attrs.isDeclared(1));
- assertEquals(multi.isSpecified(2), attrs.isSpecified(1));
-
- // Out of range
- try {
- attrs.removeAttribute(-1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- attrs.removeAttribute(3);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testAttributes2Impl() {
- assertEquals(0, empty.getLength());
- }
-
- public void testAttributes2ImplAttributes() {
- // Ordinary case with Attributes2Impl
- Attributes2Impl attrs = new Attributes2Impl(multi);
- assertEquals(multi.getLength(), attrs.getLength());
-
- for (int i = 0; i < multi.getLength(); i++) {
- assertEquals(multi.getURI(i), attrs.getURI(i));
- assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
- assertEquals(multi.getQName(i), attrs.getQName(i));
- assertEquals(multi.getType(i), attrs.getType(i));
- assertEquals(multi.getValue(i), attrs.getValue(i));
- assertEquals(multi.isDeclared(i), attrs.isDeclared(i));
- assertEquals(multi.isSpecified(i), attrs.isSpecified(i));
- }
-
- attrs = new Attributes2Impl(empty);
- assertEquals(0, attrs.getLength());
-
- // Ordinary case with AttributesImpl
- attrs = new Attributes2Impl(new AttributesImpl(multi));
- assertEquals(multi.getLength(), attrs.getLength());
-
- for (int i = 0; i < multi.getLength(); i++) {
- assertEquals(multi.getURI(i), attrs.getURI(i));
- assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
- assertEquals(multi.getQName(i), attrs.getQName(i));
- assertEquals(multi.getType(i), attrs.getType(i));
- assertEquals(multi.getValue(i), attrs.getValue(i));
- assertEquals(true, attrs.isDeclared(i));
- assertEquals(true, attrs.isSpecified(i));
- }
-
- // Special case with CDATA
- attrs = new Attributes2Impl(new AttributesImpl(cdata));
- assertEquals(1, attrs.getLength());
- assertEquals(false, attrs.isDeclared(0));
- assertEquals(true, attrs.isSpecified(0));
-
- // null case
- try {
- attrs = new Attributes2Impl(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testIsDeclaredInt() {
- // Ordinary cases
- assertEquals(false, multi.isDeclared(0));
- assertEquals(true, multi.isDeclared(1));
-
- // Out of range
- try {
- multi.isDeclared(-1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.isDeclared(4);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testIsDeclaredStringString() {
- // Ordinary cases
- assertEquals(false, multi.isDeclared("http://some.uri", "foo"));
- assertEquals(true, multi.isDeclared("http://some.uri", "bar"));
-
- // Not found
- try {
- assertFalse(multi.isDeclared("not", "found"));
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- public void testIsDeclaredString() {
- // Ordinary cases
- assertEquals(false, multi.isDeclared("ns1:foo"));
- assertEquals(true, multi.isDeclared("ns1:bar"));
-
- // Not found
- try {
- assertFalse(multi.isDeclared("notfound"));
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- public void testIsSpecifiedInt() {
- // Ordinary cases
- assertEquals(false, multi.isSpecified(1));
- assertEquals(true, multi.isSpecified(2));
-
- // Out of range
- try {
- multi.isSpecified(-1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.isSpecified(4);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testIsSpecifiedStringString() {
- // Ordinary cases
- assertEquals(false, multi.isSpecified("http://some.uri", "bar"));
- assertEquals(true, multi.isSpecified("http://some.other.uri", "answer"));
-
- // Not found
- try {
- assertFalse(multi.isSpecified("not", "found"));
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- public void testIsSpecifiedString() {
- // Ordinary cases
- assertEquals(false, multi.isSpecified("ns1:bar"));
- assertEquals(true, multi.isSpecified("ns2:answer"));
-
- // Not found
- try {
- assertFalse(multi.isSpecified("notfound"));
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- public void testSetDeclared() {
- // Ordinary cases
- multi.setSpecified(0, false);
- assertEquals(false, multi.isSpecified(0));
-
- multi.setSpecified(0, true);
- assertEquals(true, multi.isSpecified(0));
-
- multi.setSpecified(0, false);
- assertEquals(false, multi.isSpecified(0));
-
- // Out of range
- try {
- multi.setSpecified(-1, true);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setSpecified(5, true);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testSetSpecified() {
- // Ordinary cases
- multi.setSpecified(0, false);
- assertEquals(false, multi.isSpecified(0));
-
- multi.setSpecified(0, true);
- assertEquals(true, multi.isSpecified(0));
-
- multi.setSpecified(0, false);
- assertEquals(false, multi.isSpecified(0));
-
- // Out of range
- try {
- multi.setSpecified(-1, true);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setSpecified(5, true);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java b/luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java
deleted file mode 100644
index 0e6c245..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/ext/DefaultHandler2Test.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.ext;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.SAXException;
-import org.xml.sax.ext.DefaultHandler2;
-
-import java.io.IOException;
-
-public class DefaultHandler2Test extends TestCase {
-
- private DefaultHandler2 h = new DefaultHandler2();
-
- public void testDefaultHandler2() {
- new DefaultHandler2();
- }
-
- public void testStartCDATA() {
- try {
- h.startCDATA();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testEndCDATA() {
- try {
- h.endCDATA();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testStartDTD() {
- try {
- h.startDTD("name", "publicId", "systemId");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testEndDTD() {
- try {
- h.endDTD();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testStartEntity() {
- try {
- h.startEntity("name");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testEndEntity() {
- try {
- h.endEntity("name");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testComment() {
- try {
- h.comment("<!-- Comment -->".toCharArray(), 0, 15);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testAttributeDecl() {
- try {
- h.attributeDecl("eName", "aName", "type", "mode", "value");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testElementDecl() {
- try {
- h.elementDecl("name", "model");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testExternalEntityDecl() {
- try {
- h.externalEntityDecl("name", "publicId", "systemId");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testInternalEntityDecl() {
- try {
- h.internalEntityDecl("name", "value");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetExternalSubset() {
- try {
- assertNull(h.getExternalSubset("name", "http://some.uri"));
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testResolveEntityStringString() {
- try {
- assertNull(h.resolveEntity("publicId", "systemId"));
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testResolveEntityStringStringStringString() {
- try {
- assertNull(h.resolveEntity("name", "publicId", "http://some.uri",
- "systemId"));
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java
deleted file mode 100644
index dbed1de..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/ext/Locator2ImplTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.ext;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Locator;
-import org.xml.sax.ext.Locator2Impl;
-import org.xml.sax.helpers.LocatorImpl;
-
-public class Locator2ImplTest extends TestCase {
-
- public static final String SYS = "mySystemID";
-
- public static final String PUB = "myPublicID";
-
- public static final int ROW = 1;
-
- public static final int COL = 2;
-
- public static final String ENC = "Klingon";
-
- public static final String XML = "1.0";
-
- public void testLocatorImpl() {
- Locator2Impl l = new Locator2Impl();
-
- assertEquals(null, l.getPublicId());
- assertEquals(null, l.getSystemId());
- assertEquals(0, l.getLineNumber());
- assertEquals(0, l.getColumnNumber());
-
- assertEquals(null, l.getEncoding());
- assertEquals(null, l.getXMLVersion());
- }
-
- public void testLocatorImplLocator() {
- Locator2Impl inner = new Locator2Impl();
-
- inner.setPublicId(PUB);
- inner.setSystemId(SYS);
- inner.setLineNumber(ROW);
- inner.setColumnNumber(COL);
-
- inner.setEncoding(ENC);
- inner.setXMLVersion(XML);
-
- // Ordinary case
- Locator2Impl outer = new Locator2Impl(inner);
-
- assertEquals(PUB, outer.getPublicId());
- assertEquals(SYS, outer.getSystemId());
- assertEquals(ROW, outer.getLineNumber());
- assertEquals(COL, outer.getColumnNumber());
-
- assertEquals(ENC, outer.getEncoding());
- assertEquals(XML, outer.getXMLVersion());
-
- // Instance of old locator
- outer = new Locator2Impl(new LocatorImpl(inner));
-
- assertEquals(PUB, outer.getPublicId());
- assertEquals(SYS, outer.getSystemId());
- assertEquals(ROW, outer.getLineNumber());
- assertEquals(COL, outer.getColumnNumber());
-
- assertEquals(null, outer.getEncoding());
- assertEquals(null, outer.getXMLVersion());
-
- // No locator
- try {
- outer = new Locator2Impl(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testSetXMLVersionGetXMLVersion() {
- Locator2Impl l = new Locator2Impl();
-
- l.setXMLVersion(XML);
- assertEquals(XML, l.getXMLVersion());
-
- l.setXMLVersion(null);
- assertEquals(null, l.getXMLVersion());
- }
-
- public void testSetEncodingGetEncoding() {
- Locator2Impl l = new Locator2Impl();
-
- l.setEncoding(ENC);
- assertEquals(ENC, l.getEncoding());
-
- l.setEncoding(null);
- assertEquals(null, l.getEncoding());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java
deleted file mode 100644
index 27f36ae..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributeListImplTest.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.AttributeList;
-import org.xml.sax.helpers.AttributeListImpl;
-
-@SuppressWarnings("deprecation")
-public class AttributeListImplTest extends TestCase {
-
- private AttributeListImpl empty = new AttributeListImpl();
-
- private AttributeListImpl multi = new AttributeListImpl();
-
- @Override
- public void setUp() {
- multi.addAttribute("foo", "string", "abc");
- multi.addAttribute("bar", "string", "xyz");
- multi.addAttribute("answer", "int", "42");
- }
-
- public void testAttributeListImpl() {
- assertEquals(0, empty.getLength());
- assertEquals(3, multi.getLength());
- }
-
- public void testAttributeListImplAttributeList() {
- // Ordinary case
- AttributeListImpl ai = new AttributeListImpl(empty);
- assertEquals(0, ai.getLength());
-
- // Another ordinary case
- ai = new AttributeListImpl(multi);
- assertEquals(3, ai.getLength());
-
- // No Attributes
- try {
- ai = new AttributeListImpl(null);
- assertEquals(0, ai.getLength());
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testSetAttributeList() {
- // Ordinary cases
- AttributeListImpl attrs = new AttributeListImpl();
- attrs.addAttribute("doe", "boolean", "false");
-
- attrs.setAttributeList(empty);
- assertEquals(0, attrs.getLength());
-
- attrs.setAttributeList(multi);
- assertEquals(multi.getLength(), attrs.getLength());
-
- for (int i = 0; i < multi.getLength(); i++) {
- assertEquals(multi.getName(i), attrs.getName(i));
- assertEquals(multi.getType(i), attrs.getType(i));
- assertEquals(multi.getValue(i), attrs.getValue(i));
- }
-
- // null case
- try {
- attrs.setAttributeList(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected, must still have old elements
- assertEquals(3, attrs.getLength());
- }
- }
-
- public void testAddAttribute() {
- // Ordinary case
- multi.addAttribute("doe", "boolean", "false");
-
- assertEquals("doe", multi.getName(3));
- assertEquals("boolean", multi.getType(3));
- assertEquals("false", multi.getValue(3));
-
- // Duplicate case
- multi.addAttribute("doe", "boolean", "false");
-
- assertEquals("doe", multi.getName(4));
- assertEquals("boolean", multi.getType(4));
- assertEquals("false", multi.getValue(4));
-
- // null case
- multi.addAttribute(null, null, null);
- assertEquals(null, multi.getName(5));
- assertEquals(null, multi.getType(5));
- assertEquals(null, multi.getValue(5));
- }
-
- public void testRemoveAttribute() {
- // Ordinary case
- multi.removeAttribute("foo");
- assertEquals("bar", multi.getName(0));
- assertEquals("string", multi.getType(0));
- assertEquals("xyz", multi.getValue(0));
-
- // Unknown attribute
- multi.removeAttribute("john");
- assertEquals(2, multi.getLength());
-
- // null case
- multi.removeAttribute(null);
- assertEquals(2, multi.getLength());
- }
-
- public void testClear() {
- assertEquals(3, multi.getLength());
- multi.clear();
- assertEquals(0, multi.getLength());
- }
-
- public void testGetLength() {
- AttributeListImpl ai = new AttributeListImpl(empty);
- assertEquals(0, ai.getLength());
-
- ai = new AttributeListImpl(multi);
- assertEquals(3, ai.getLength());
-
- for (int i = 2; i >= 0; i--) {
- ai.removeAttribute(ai.getName(i));
- assertEquals(i, ai.getLength());
- }
- }
-
- public void testGetName() {
- // Ordinary cases
- assertEquals("foo", multi.getName(0));
- assertEquals("bar", multi.getName(1));
- assertEquals("answer", multi.getName(2));
-
- // Out of range
- assertEquals(null, multi.getName(-1));
- assertEquals(null, multi.getName(3));
- }
-
- public void testGetTypeInt() {
- // Ordinary cases
- assertEquals("string", multi.getType(0));
- assertEquals("string", multi.getType(1));
- assertEquals("int", multi.getType(2));
-
- // Out of range
- assertEquals(null, multi.getType(-1));
- assertEquals(null, multi.getType(3));
- }
-
- public void testGetValueInt() {
- // Ordinary cases
- assertEquals("abc", multi.getValue(0));
- assertEquals("xyz", multi.getValue(1));
- assertEquals("42", multi.getValue(2));
-
- // Out of range
- assertEquals(null, multi.getValue(-1));
- assertEquals(null, multi.getValue(5));
- }
-
- public void testGetTypeString() {
- // Ordinary cases
- assertEquals("string", multi.getType("foo"));
- assertEquals("string", multi.getType("bar"));
- assertEquals("int", multi.getType("answer"));
-
- // Not found
- assertEquals(null, multi.getType("john"));
-
- // null case
- assertEquals(null, multi.getType(null));
- }
-
- public void testGetValueString() {
- // Ordinary cases
- assertEquals("abc", multi.getValue("foo"));
- assertEquals("xyz", multi.getValue("bar"));
- assertEquals("42", multi.getValue("answer"));
-
- // Not found
- assertEquals(null, multi.getValue("john"));
-
- // null case
- assertEquals(null, multi.getValue(null));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java
deleted file mode 100644
index 1cc77ee..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/AttributesImplTest.java
+++ /dev/null
@@ -1,481 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.helpers.AttributesImpl;
-
-public class AttributesImplTest extends TestCase {
-
- private AttributesImpl empty = new AttributesImpl();
-
- private AttributesImpl multi = new AttributesImpl();
-
- @Override
- public void setUp() {
- multi.addAttribute("http://some.uri", "foo", "ns1:foo",
- "string", "abc");
- multi.addAttribute("http://some.uri", "bar", "ns1:bar",
- "string", "xyz");
- multi.addAttribute("http://some.other.uri", "answer", "ns2:answer",
- "int", "42");
-
- multi.addAttribute("", "gabbaHey", "", "string", "1-2-3-4");
- multi.addAttribute("", "", "gabba:hey", "string", "1-2-3-4");
- }
-
- public void testAttributesImpl() {
- assertEquals(0, empty.getLength());
- assertEquals(5, multi.getLength());
- }
-
- public void testAttributesImplAttributes() {
- // Ordinary case
- AttributesImpl ai = new AttributesImpl(empty);
- assertEquals(0, ai.getLength());
-
- // Another ordinary case
- ai = new AttributesImpl(multi);
- assertEquals(5, ai.getLength());
-
- // No Attributes
- try {
- ai = new AttributesImpl(null);
- assertEquals(0, ai.getLength());
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testGetLength() {
- AttributesImpl ai = new AttributesImpl(empty);
- assertEquals(0, ai.getLength());
-
- ai = new AttributesImpl(multi);
- assertEquals(5, ai.getLength());
-
- for (int i = 4; i >= 0; i--) {
- ai.removeAttribute(i);
- assertEquals(i, ai.getLength());
- }
- }
-
- public void testGetURI() {
- // Ordinary cases
- assertEquals("http://some.uri", multi.getURI(0));
- assertEquals("http://some.uri", multi.getURI(1));
- assertEquals("http://some.other.uri", multi.getURI(2));
- assertEquals("", multi.getURI(3));
- assertEquals("", multi.getURI(4));
-
- // Out of range
- assertEquals(null, multi.getURI(-1));
- assertEquals(null, multi.getURI(5));
- }
-
- public void testGetLocalName() {
- // Ordinary cases
- assertEquals("foo", multi.getLocalName(0));
- assertEquals("bar", multi.getLocalName(1));
- assertEquals("answer", multi.getLocalName(2));
- assertEquals("gabbaHey", multi.getLocalName(3));
- assertEquals("", multi.getLocalName(4));
-
- // Out of range
- assertEquals(null, multi.getLocalName(-1));
- assertEquals(null, multi.getLocalName(5));
- }
-
- public void testGetQName() {
- // Ordinary cases
- assertEquals("ns1:foo", multi.getQName(0));
- assertEquals("ns1:bar", multi.getQName(1));
- assertEquals("ns2:answer", multi.getQName(2));
- assertEquals("", multi.getQName(3));
- assertEquals("gabba:hey", multi.getQName(4));
-
- // Out of range
- assertEquals(null, multi.getQName(-1));
- assertEquals(null, multi.getQName(5));
- }
-
- public void testGetTypeInt() {
- // Ordinary cases
- assertEquals("string", multi.getType(0));
- assertEquals("string", multi.getType(1));
- assertEquals("int", multi.getType(2));
- assertEquals("string", multi.getType(3));
- assertEquals("string", multi.getType(4));
-
- // Out of range
- assertEquals(null, multi.getType(-1));
- assertEquals(null, multi.getType(5));
- }
-
- public void testGetValueInt() {
- // Ordinary cases
- assertEquals("abc", multi.getValue(0));
- assertEquals("xyz", multi.getValue(1));
- assertEquals("42", multi.getValue(2));
- assertEquals("1-2-3-4", multi.getValue(3));
- assertEquals("1-2-3-4", multi.getValue(4));
-
- // Out of range
- assertEquals(null, multi.getValue(-1));
- assertEquals(null, multi.getValue(5));
- }
-
- public void testGetIndexStringString() {
- // Ordinary cases
- assertEquals(0, multi.getIndex("http://some.uri", "foo"));
- assertEquals(1, multi.getIndex("http://some.uri", "bar"));
- assertEquals(2, multi.getIndex("http://some.other.uri", "answer"));
-
- // Not found
- assertEquals(-1, multi.getIndex("john", "doe"));
-
- // null cases
- assertEquals(-1, multi.getIndex("http://some.uri", null));
- assertEquals(-1, multi.getIndex(null, "foo"));
- }
-
- public void testGetIndexString() {
- // Ordinary cases
- assertEquals(0, multi.getIndex("ns1:foo"));
- assertEquals(1, multi.getIndex("ns1:bar"));
- assertEquals(2, multi.getIndex("ns2:answer"));
- assertEquals(4, multi.getIndex("gabba:hey"));
-
- // Not found
- assertEquals(-1, multi.getIndex("john:doe"));
-
- // null case
- assertEquals(-1, multi.getIndex(null));
- }
-
- public void testGetTypeStringString() {
- // Ordinary cases
- assertEquals("string", multi.getType("http://some.uri", "foo"));
- assertEquals("string", multi.getType("http://some.uri", "bar"));
- assertEquals("int", multi.getType("http://some.other.uri", "answer"));
-
- // Not found
- assertEquals(null, multi.getType("john", "doe"));
-
- // null cases
- assertEquals(null, multi.getType("http://some.uri", null));
- assertEquals(null, multi.getType(null, "foo"));
- }
-
- public void testGetTypeString() {
- // Ordinary cases
- assertEquals("string", multi.getType("ns1:foo"));
- assertEquals("string", multi.getType("ns1:bar"));
- assertEquals("int", multi.getType("ns2:answer"));
- assertEquals("string", multi.getType("gabba:hey"));
-
- // Not found
- assertEquals(null, multi.getType("john:doe"));
-
- // null case
- assertEquals(null, multi.getType(null));
- }
-
- public void testGetValueStringString() {
- // Ordinary cases
- assertEquals("abc", multi.getValue("http://some.uri", "foo"));
- assertEquals("xyz", multi.getValue("http://some.uri", "bar"));
- assertEquals("42", multi.getValue("http://some.other.uri", "answer"));
-
- // Not found
- assertEquals(null, multi.getValue("john", "doe"));
-
- // null cases
- assertEquals(null, multi.getValue("http://some.uri", null));
- assertEquals(null, multi.getValue(null, "foo"));
- }
-
- public void testGetValueString() {
- // Ordinary cases
- assertEquals("abc", multi.getValue("ns1:foo"));
- assertEquals("xyz", multi.getValue("ns1:bar"));
- assertEquals("42", multi.getValue("ns2:answer"));
- assertEquals("1-2-3-4", multi.getValue("gabba:hey"));
-
- // Not found
- assertEquals(null, multi.getValue("john:doe"));
-
- // null case
- assertEquals(null, multi.getValue(null));
- }
-
- public void testClear() {
- assertEquals(5, multi.getLength());
- multi.clear();
- assertEquals(0, multi.getLength());
- }
-
- public void testSetAttributes() {
- // Ordinary cases
- AttributesImpl attrs = new AttributesImpl();
- attrs.addAttribute("http://yet.another.uri", "doe", "john:doe",
- "boolean", "false");
-
- attrs.setAttributes(empty);
- assertEquals(0, attrs.getLength());
-
- attrs.setAttributes(multi);
- assertEquals(multi.getLength(), attrs.getLength());
-
- for (int i = 0; i < multi.getLength(); i++) {
- assertEquals(multi.getURI(i), attrs.getURI(i));
- assertEquals(multi.getLocalName(i), attrs.getLocalName(i));
- assertEquals(multi.getQName(i), attrs.getQName(i));
- assertEquals(multi.getType(i), attrs.getType(i));
- assertEquals(multi.getValue(i), attrs.getValue(i));
- }
-
- // null case
- try {
- attrs.setAttributes(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected, but must be empty now
- assertEquals(0, attrs.getLength());
- }
- }
-
- public void testAddAttribute() {
- // Ordinary case
- multi.addAttribute("http://yet.another.uri", "doe", "john:doe",
- "boolean", "false");
-
- assertEquals("http://yet.another.uri", multi.getURI(5));
- assertEquals("doe", multi.getLocalName(5));
- assertEquals("john:doe", multi.getQName(5));
- assertEquals("boolean", multi.getType(5));
- assertEquals("false", multi.getValue(5));
-
- // Duplicate case
- multi.addAttribute("http://yet.another.uri", "doe", "john:doe",
- "boolean", "false");
-
- assertEquals("http://yet.another.uri", multi.getURI(6));
- assertEquals("doe", multi.getLocalName(6));
- assertEquals("john:doe", multi.getQName(6));
- assertEquals("boolean", multi.getType(6));
- assertEquals("false", multi.getValue(6));
-
- // null case
- multi.addAttribute(null, null, null, null, null);
- assertEquals(null, multi.getURI(7));
- assertEquals(null, multi.getLocalName(7));
- assertEquals(null, multi.getQName(7));
- assertEquals(null, multi.getType(7));
- assertEquals(null, multi.getValue(7));
- }
-
- public void testSetAttribute() {
- // Ordinary case
- multi.setAttribute(0, "http://yet.another.uri", "doe", "john:doe",
- "boolean", "false");
- assertEquals("http://yet.another.uri", multi.getURI(0));
- assertEquals("doe", multi.getLocalName(0));
- assertEquals("john:doe", multi.getQName(0));
- assertEquals("boolean", multi.getType(0));
- assertEquals("false", multi.getValue(0));
-
- // null case
- multi.setAttribute(1, null, null, null, null, null);
- assertEquals(null, multi.getURI(1));
- assertEquals(null, multi.getLocalName(1));
- assertEquals(null, multi.getQName(1));
- assertEquals(null, multi.getType(1));
- assertEquals(null, multi.getValue(1));
-
- // Out of range
- try {
- multi.setAttribute(-1, "http://yet.another.uri", "doe", "john:doe",
- "boolean", "false");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setAttribute(5, "http://yet.another.uri", "doe", "john:doe",
- "boolean", "false");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testRemoveAttribute() {
- // Ordinary case
- multi.removeAttribute(0);
- assertEquals("http://some.uri", multi.getURI(0));
- assertEquals("bar", multi.getLocalName(0));
- assertEquals("ns1:bar", multi.getQName(0));
- assertEquals("string", multi.getType(0));
- assertEquals("xyz", multi.getValue(0));
-
- // Out of range
- try {
- multi.removeAttribute(-1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.removeAttribute(4);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testSetURI() {
- // Ordinary case
- multi.setURI(0, "http://yet.another.uri");
- assertEquals("http://yet.another.uri", multi.getURI(0));
-
- // null case
- multi.setURI(1, null);
- assertEquals(null, multi.getURI(1));
-
- // Out of range
- try {
- multi.setURI(-1, "http://yet.another.uri");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setURI(5, "http://yet.another.uri");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testSetLocalName() {
- // Ordinary case
- multi.setLocalName(0, "john");
- assertEquals("john", multi.getLocalName(0));
-
- // null case
- multi.setLocalName(1, null);
- assertEquals(null, multi.getLocalName(1));
-
- // Out of range
- try {
- multi.setLocalName(-1, "john");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setLocalName(5, "john");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testSetQName() {
- // Ordinary case
- multi.setQName(0, "john:doe");
- assertEquals("john:doe", multi.getQName(0));
-
- // null case
- multi.setQName(1, null);
- assertEquals(null, multi.getQName(1));
-
- // Out of range
- try {
- multi.setQName(-1, "john:doe");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setQName(5, "john:doe");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testSetType() {
- // Ordinary case
- multi.setType(0, "float");
- assertEquals("float", multi.getType(0));
-
- // null case
- multi.setType(1, null);
- assertEquals(null, multi.getType(1));
-
- // Out of range
- try {
- multi.setType(-1, "float");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setType(5, "float");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- public void testSetValue() {
- // Ordinary case
- multi.setValue(0, "too much");
- assertEquals("too much", multi.getValue(0));
-
- // null case
- multi.setValue(1, null);
- assertEquals(null, multi.getValue(1));
-
- // Out of range
- try {
- multi.setValue(-1, "too much");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- multi.setValue(5, "too much");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java
deleted file mode 100644
index a9530f2..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/DefaultHandlerTest.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.AttributesImpl;
-import org.xml.sax.helpers.DefaultHandler;
-import org.xml.sax.helpers.LocatorImpl;
-
-import java.io.IOException;
-
-public class DefaultHandlerTest extends TestCase {
-
- /*
- * Note: most of the tests have to check for an empty implementation of the
- * respective methods and, as a result, are somewhat trivial.
- */
-
- private DefaultHandler h = new DefaultHandler();
-
- public void testResolveEntity() {
- try {
- h.resolveEntity("publicID", "systemID");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testNotationDecl() {
- try {
- h.notationDecl("name", "publicID", "systemID");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testUnparsedEntityDecl() {
- try {
- h.unparsedEntityDecl("name", "publicID", "systemID",
- "notationName");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testSetDocumentLocator() {
- h.setDocumentLocator(new LocatorImpl());
- }
-
- public void testStartDocument() {
- try {
- h.startDocument();
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testEndDocument() {
- try {
- h.endDocument();
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testStartPrefixMapping() {
- try {
- h.startPrefixMapping("prefix", "uri");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testEndPrefixMapping() {
- try {
- h.endPrefixMapping("prefix");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testStartElement() {
- try {
- h.startElement("uri", "name", "qname", new AttributesImpl());
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testEndElement() {
- try {
- h.endElement("uri", "name", "qname");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testCharacters() {
- try {
- h.characters("The quick brown fox".toCharArray(), 4, 11);
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testIgnorableWhitespace() {
- try {
- h.ignorableWhitespace(" ".toCharArray(), 4, 11);
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testProcessingInstruction() {
- try {
- h.processingInstruction("target", "data");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testSkippedEntity() {
- try {
- h.skippedEntity("name");
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testWarning() {
- try {
- h.warning(new SAXParseException("Foo", new LocatorImpl()));
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testError() {
- try {
- h.error(new SAXParseException("Foo", new LocatorImpl()));
- } catch (SAXException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void testFatalError() {
- // Ordinary case
- try {
- h.fatalError(new SAXParseException("Foo", new LocatorImpl()));
- fail("SAXException expected");
- } catch (SAXException e) {
- // Expected
- }
-
- // No exception
- try {
- h.fatalError(null);
- fail("NullPointerException expected");
- } catch (SAXException e) {
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
-
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java
deleted file mode 100644
index 8aa9c11..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/LocatorImplTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Locator;
-import org.xml.sax.helpers.LocatorImpl;
-
-public class LocatorImplTest extends TestCase {
-
- public static final String SYS = "mySystemID";
-
- public static final String PUB = "myPublicID";
-
- public static final int ROW = 1;
-
- public static final int COL = 2;
-
- public void testLocatorImpl() {
- LocatorImpl l = new LocatorImpl();
-
- assertEquals(null, l.getPublicId());
- assertEquals(null, l.getSystemId());
- assertEquals(0, l.getLineNumber());
- assertEquals(0, l.getColumnNumber());
- }
-
- public void testLocatorImplLocator() {
- LocatorImpl inner = new LocatorImpl();
-
- inner.setPublicId(PUB);
- inner.setSystemId(SYS);
- inner.setLineNumber(ROW);
- inner.setColumnNumber(COL);
-
- // Ordinary case
- LocatorImpl outer = new LocatorImpl(inner);
-
- assertEquals(PUB, outer.getPublicId());
- assertEquals(SYS, outer.getSystemId());
- assertEquals(ROW, outer.getLineNumber());
- assertEquals(COL, outer.getColumnNumber());
-
- // No locator
- try {
- outer = new LocatorImpl(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testSetPublicIdGetPublicId() {
- LocatorImpl l = new LocatorImpl();
-
- l.setPublicId(PUB);
- assertEquals(PUB, l.getPublicId());
-
- l.setPublicId(null);
- assertEquals(null, l.getPublicId());
- }
-
- public void testSetSystemIdGetSystemId() {
- LocatorImpl l = new LocatorImpl();
-
- l.setSystemId(SYS);
- assertEquals(SYS, l.getSystemId());
-
- l.setSystemId(null);
- assertEquals(null, l.getSystemId());
- }
-
- public void testSetLineNumberGetLineNumber() {
- LocatorImpl l = new LocatorImpl();
-
- l.setLineNumber(ROW);
- assertEquals(ROW, l.getLineNumber());
-
- l.setLineNumber(0);
- assertEquals(0, l.getLineNumber());
- }
-
- public void testSetColumnNumberGetColumnNumber() {
- LocatorImpl l = new LocatorImpl();
-
- l.setColumnNumber(COL);
- assertEquals(COL, l.getColumnNumber());
-
- l.setColumnNumber(0);
- assertEquals(0, l.getColumnNumber());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java
deleted file mode 100644
index 2f1ff8d..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/NamespaceSupportTest.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EmptyStackException;
-import java.util.Enumeration;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.helpers.NamespaceSupport;
-
-public class NamespaceSupportTest extends TestCase {
-
- final static String defaultUri = "http://www.android.com";
- final static String marketUri = "http://www.android.com/market";
-
- NamespaceSupport ns;
- ArrayList<String> expected;
-
- @Override
- public void setUp() {
- expected = new ArrayList<String>();
- expected.add("ak");
- expected.add("bk");
-
- ns = new NamespaceSupport();
- ns.pushContext();
-
- ns.declarePrefix("ak", marketUri);
- ns.declarePrefix("bk", marketUri);
- ns.declarePrefix("", defaultUri);
- }
-
- @SuppressWarnings("unchecked")
- public void testConstructor() {
- String prefix;
- boolean xmlPrefixExists = false;
-
- ns = new NamespaceSupport();
- Enumeration<String> prefixes = ns.getDeclaredPrefixes();
-
- while (prefixes.hasMoreElements()) {
- prefix = prefixes.nextElement();
- if (prefix.equals("xml")) xmlPrefixExists = true;
- }
-
- assertTrue("Test 1: xml prefix does not exist.", xmlPrefixExists);
-
- // Check that only one context has been created by the constructor.
- try {
- ns.popContext();
- fail("Test 2: EmptyStackException expected.");
- } catch (EmptyStackException e) {
- // Expected.
- }
- }
-
- public void testPush_PopContext() {
- int count;
-
- ns = new NamespaceSupport();
- count = countPrefixes();
-
- ns.pushContext();
- ns.declarePrefix("dc", "http://www.purl.org/dc#");
- assertEquals("Test 1: Incorrect prefix count;",
- count + 1, countPrefixes());
-
- ns.popContext();
- assertEquals("Test 2: Incorrect prefix count;",
- count, countPrefixes());
-
- // Check that only one context has been created by pushContext().
- try {
- ns.popContext();
- fail("Test 3: EmptyStackException expected.");
- } catch (EmptyStackException e) {
- // Expected.
- }
- }
-
- public void testReset() {
- int count;
-
- ns = new NamespaceSupport();
- count = countPrefixes();
-
- ns.pushContext();
- ns.declarePrefix("dc", "http://www.purl.org/dc#");
-
- assertEquals("Test 1: Incorrect prefix count;",
- count + 1, countPrefixes());
-
- ns.reset();
- assertEquals("Test 2: Incorrect prefix count;",
- count, countPrefixes());
-
- // Check that only one context has been created by reset().
- try {
- ns.popContext();
- fail("Test 3: EmptyStackException expected.");
- } catch (EmptyStackException e) {
- // Expected.
- }
- }
-
- public void testDeclare_GetPrefix() {
- ns.pushContext();
-
- // Part 1: Check that xml and xmlns are not accepted as prefixes.
- assertFalse("Test 1: Invalid prefix accepted.",
- ns.declarePrefix("xml", marketUri));
-
- assertFalse("Test 2: Invalid prefix accepted.",
- ns.declarePrefix("xmlns", marketUri));
-
- // Part 2: Check that declarePrefix and getPrefix work for valid
- // prefixes.
- assertTrue("Test 3: Valid prefix not accepted.",
- ns.declarePrefix("ak", marketUri));
-
- assertTrue("Test 4: Incorrect prefix returned.",
- ns.getPrefix(marketUri).equals("ak"));
-
- assertTrue("Test 5: Valid prefix not accepted.",
- ns.declarePrefix("bk", marketUri));
-
- assertTrue("Test 6: Incorrect prefix returned.",
- expected.contains(ns.getPrefix(marketUri)));
-
- assertTrue("Test 7: Valid prefix not accepted.",
- ns.declarePrefix("", defaultUri));
-
- // Part 3: Negative Tests for getPrefix.
- assertNull("Test 8: Non-null value returned for the URI that is " +
- "assigned to the default namespace.",
- ns.getPrefix(defaultUri));
-
- assertNull("Test 9: Non-null value returned for an unassigned URI.",
- ns.getPrefix(defaultUri + "/42"));
- }
-
- @SuppressWarnings("unchecked")
- public void testGetPrefixesLjava_lang_String() {
- ArrayList<String> prefixes;
-
- prefixes = Collections.list(ns.getPrefixes(marketUri));
- assertTrue("Test 1: Incorrect set of prefixes returned.",
- expected.containsAll(prefixes) && prefixes.containsAll(expected));
-
- prefixes = Collections.list(ns.getPrefixes(defaultUri));
- assertTrue("Test 2: Default namespace prefix should not be returned.",
- prefixes.size() == 0);
-
- prefixes = Collections.list(ns.getPrefixes(NamespaceSupport.XMLNS));
- assertTrue("Test 3: xml prefix is missing.",
- prefixes.contains("xml") && prefixes.size() == 1);
-
- prefixes = Collections.list(ns.getPrefixes(defaultUri + "/42"));
- assertTrue("Test 4: Non-empty enumeration returned for an unassigned URI.",
- prefixes.size() == 0);
- }
-
- @SuppressWarnings("unchecked")
- public void testGetPrefixes() {
- ArrayList<String> prefixes;
-
- expected.add("xml");
-
- prefixes = Collections.list(ns.getPrefixes());
- assertTrue("Test 1: Incorrect set of prefixes returned.",
- expected.containsAll(prefixes) && prefixes.containsAll(expected));
- }
-
- @SuppressWarnings("unchecked")
- public void testGetDeclaredPrefixes() {
- ArrayList<String> prefixes;
-
- expected.add("");
-
- prefixes = Collections.list(ns.getDeclaredPrefixes());
- assertTrue("Test 1: Incorrect set of prefixes returned.",
- expected.containsAll(prefixes) && prefixes.containsAll(expected));
- }
-
- public void testGetUri() {
- assertEquals("Test 1: Incorrect URI returned;",
- marketUri, ns.getURI("bk"));
- assertEquals("Test 2: Incorrect URI returned;",
- defaultUri, ns.getURI(""));
- assertNull("Test 3: Null expected for not-existing prefix.",
- ns.getURI("ck"));
-
- ns.popContext();
- assertNull("Test 4: Null expected for not-existing prefix.",
- ns.getURI("bk"));
- assertEquals("Test 5: Incorrect URI returned;",
- NamespaceSupport.XMLNS, ns.getURI("xml"));
- }
-
- public void testNamespaceDeclUris() {
-
- assertFalse("Test 1: Incorrect default value returned by isNamespaceDeclUris().",
- ns.isNamespaceDeclUris());
-
- try {
- ns.setNamespaceDeclUris(true);
- fail("Test 2: IllegalStateException expected since a context has already been pushed in setUp().");
- } catch (IllegalStateException e) {
- // Expected.
- }
-
- ns = new NamespaceSupport();
- ns.setNamespaceDeclUris(true);
- assertTrue("Test 3: Incorrect value returned by isNamespaceDeclUris().",
- ns.isNamespaceDeclUris());
-
- ns.setNamespaceDeclUris(false);
- assertFalse("Test 4: Incorrect value returned by isNamespaceDeclUris().",
- ns.isNamespaceDeclUris());
- }
-
- public void testProcessName_Element() {
- String[] parts = new String[3];
-
- assertNotNull("Test 1: Non-null value expected.",
- ns.processName("ak:hello", parts, false));
- assertEquals("Test 2: Incorrect namespace URI;", marketUri, parts[0]);
- assertEquals("Test 3: Incorrect local name;", "hello", parts[1]);
- assertEquals("Test 4: Incorrect raw name;", "ak:hello", parts[2]);
-
- assertNotNull("Test 5: Non-null value expected.",
- ns.processName("bk:", parts, false));
- assertEquals("Test 6: Incorrect namespace URI;", marketUri, parts[0]);
- assertEquals("Test 7: Incorrect local name;", "", parts[1]);
- assertEquals("Test 8: Incorrect raw name;", "bk:", parts[2]);
-
- assertNotNull("Test 9: Non-null value expected.",
- ns.processName("world", parts, false));
- assertEquals("Test 10: Incorrect namespace URI;", defaultUri, parts[0]);
- assertEquals("Test 11: Incorrect local name;", "world", parts[1]);
- assertEquals("Test 12: Incorrect raw name;", "world", parts[2]);
-
- assertNull("Test 13: Null expected for undeclared prefix.",
- ns.processName("ck:lorem", parts, false));
-
- assertNull("Test 14: Null expected for xmlns prefix.",
- ns.processName("xmlns:ipsum", parts, false));
-
- ns = new NamespaceSupport();
- ns.pushContext();
- assertNotNull("Test 15: Non-null value expected.",
- ns.processName("world", parts, false));
- assertEquals("Test 16: Incorrect namespace URI;", "", parts[0]);
- assertEquals("Test 17: Incorrect local name;", "world", parts[1]);
- assertEquals("Test 18: Incorrect raw name;", "world", parts[2]);
- }
-
- public void testProcessName_Attribute() {
- String[] parts = new String[3];
-
- assertNotNull("Test 1: Non-null value expected.",
- ns.processName("ak:hello", parts, true));
- assertEquals("Test 2: Incorrect namespace URI;", marketUri, parts[0]);
- assertEquals("Test 3: Incorrect local name;", "hello", parts[1]);
- assertEquals("Test 4: Incorrect raw name;", "ak:hello", parts[2]);
-
- assertNotNull("Test 5: Non-null value expected.",
- ns.processName("bk:", parts, true));
- assertEquals("Test 6: Incorrect namespace URI;", marketUri, parts[0]);
- assertEquals("Test 7: Incorrect local name;", "", parts[1]);
- assertEquals("Test 8: Incorrect raw name;", "bk:", parts[2]);
-
- assertNotNull("Test 9: Non-null value expected.",
- ns.processName("world", parts, true));
- assertEquals("Test 10: Incorrect namespace URI;", "", parts[0]);
- assertEquals("Test 11: Incorrect local name;", "world", parts[1]);
- assertEquals("Test 12: Incorrect raw name;", "world", parts[2]);
-
- assertNull("Test 13: Null expected for undeclared prefix.",
- ns.processName("ck:lorem", parts, true));
-
- assertNull("Test 14: Null expected for xmlns prefix.",
- ns.processName("xmlns:ipsum", parts, true));
-
- ns = new NamespaceSupport();
- ns.setNamespaceDeclUris(true);
- ns.pushContext();
- assertNotNull("Test 15: Non-null value expected.",
- ns.processName("xmlns", parts, true));
- assertEquals("Test 16: Incorrect namespace URI;", NamespaceSupport.NSDECL, parts[0]);
- assertEquals("Test 17: Incorrect local name;", "xmlns", parts[1]);
- assertEquals("Test 18: Incorrect raw name;", "xmlns", parts[2]);
- }
-
- @SuppressWarnings("unchecked")
- private int countPrefixes()
- {
- ArrayList<String> prefixes = Collections.list(ns.getPrefixes());
- return prefixes.size();
- }
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java
deleted file mode 100644
index 2344736..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserAdapterTest.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.AttributeList;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.Parser;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.helpers.AttributeListImpl;
-import org.xml.sax.helpers.LocatorImpl;
-import org.xml.sax.helpers.ParserAdapter;
-
-import tests.api.org.xml.sax.support.MethodLogger;
-import tests.api.org.xml.sax.support.MockHandler;
-import tests.api.org.xml.sax.support.MockParser;
-import tests.api.org.xml.sax.support.MockResolver;
-
-@SuppressWarnings("deprecation")
-public class ParserAdapterTest extends TestCase {
-
- // Note: In many cases we can only test that delegation works
- // properly. The rest is outside the scope of the specification.
-
- private final static String FEATURES = "http://xml.org/sax/features/";
-
- private final static String NAMESPACES = FEATURES + "namespaces";
-
- private final static String NAMESPACE_PREFIXES = FEATURES
- + "namespace-prefixes";
-
- private final static String XMLNS_URIs = FEATURES + "xmlns-uris";
-
- private MethodLogger logger = new MethodLogger();
-
- private MockHandler handler = new MockHandler(logger);
-
- private Parser parser = new MockParser(logger);
-
- private ParserAdapter adapter = new ParserAdapter(parser);
-
- private void assertEquals(Object[] a, Object[] b) {
- assertEquals(a.length, b.length);
-
- for (int i = 0; i < a.length; i++) {
- assertEquals("Element #" + i + " must be equal", a[i], b[i]);
- }
- }
-
- @Override
- public void setUp() {
- adapter.setContentHandler(handler);
- adapter.setDTDHandler(handler);
- adapter.setErrorHandler(handler);
- }
-
- @Override protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testParserAdapter() {
- System.setProperty("org.xml.sax.parser",
- "tests.api.org.xml.sax.support.DoNothingParser");
-
- try {
- new ParserAdapter();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testParserAdapterParser() {
- // Ordinary case
- @SuppressWarnings("unused")
- ParserAdapter adapter = new ParserAdapter(parser);
-
- // Null case
- try {
- adapter = new ParserAdapter(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testGetSetFeature() {
- String[] features = new String[] { NAMESPACES, NAMESPACE_PREFIXES,
- XMLNS_URIs };
-
- for (String s: features) {
- try {
- adapter.setFeature(s, true);
- assertEquals(true, adapter.getFeature(s));
-
- adapter.setFeature(s, false);
- assertEquals(false, adapter.getFeature(s));
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- try {
- adapter.setFeature("http://argle.bargle", true);
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetSetProperty() {
- try {
- adapter.setProperty("http://argle.bargle", ":)");
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- try {
- adapter.getProperty("http://argle.bargle");
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetSetEntityResolver() {
- EntityResolver resolver = new MockResolver();
-
- adapter.setEntityResolver(resolver);
- assertEquals(resolver, adapter.getEntityResolver());
-
- adapter.setEntityResolver(null);
- assertEquals(null, adapter.getEntityResolver());
- }
-
- public void testGetSetDTDHandler() {
- adapter.setDTDHandler(null);
- assertEquals(null, adapter.getDTDHandler());
-
- adapter.setDTDHandler(handler);
- assertEquals(handler, adapter.getDTDHandler());
- }
-
- public void testGetSetContentHandler() {
- adapter.setContentHandler(null);
- assertEquals(null, adapter.getContentHandler());
-
- adapter.setContentHandler(handler);
- assertEquals(handler, adapter.getContentHandler());
- }
-
- public void testGetSetErrorHandler() {
- adapter.setErrorHandler(null);
- assertEquals(null, adapter.getErrorHandler());
-
- adapter.setErrorHandler(handler);
- assertEquals(handler, adapter.getErrorHandler());
- }
-
- public void testParseString() {
- try {
- adapter.parse("foo");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // The SAX RI creates an InputSource itself and then delegates to the
- // "other" parse method.
- assertEquals("parse", logger.getMethod());
- assertEquals(InputSource.class, logger.getArgs()[0].getClass());
- }
-
- public void testParseInputSource() {
- InputSource source = new InputSource("foo");
-
- try {
- adapter.parse(source);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals("parse", logger.getMethod());
- assertEquals(new Object[] { source }, logger.getArgs());
- }
-
- public void testSetDocumentLocator() {
- Locator l = new LocatorImpl();
-
- adapter.setDocumentLocator(l);
-
- assertEquals(logger.size(), 1);
- assertEquals("setDocumentLocator", logger.getMethod());
- assertEquals(new Object[] { l }, logger.getArgs());
-
- adapter.setDocumentLocator(null);
-
- assertEquals(logger.size(), 2);
- assertEquals("setDocumentLocator", logger.getMethod());
- assertEquals(new Object[] { null }, logger.getArgs());
- }
-
- public void testStartDocument() {
- try {
- adapter.startDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("startDocument", logger.getMethod());
- assertEquals(new Object[] {}, logger.getArgs());
- }
-
- public void testEndDocument() {
- try {
- adapter.endDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("endDocument", logger.getMethod());
- assertEquals(new Object[] {}, logger.getArgs());
- }
-
- public void testStartElement() {
- AttributeListImpl atts = new AttributeListImpl();
- atts.addAttribute("john:doe", "int", "42");
-
- try {
- adapter.startDocument();
- adapter.startElement("foo:bar", atts);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals("startElement", logger.getMethod());
- assertEquals("", logger.getArgs()[0]);
- assertEquals("", logger.getArgs()[1]);
- assertEquals("foo:bar", logger.getArgs()[2]);
- assertEquals("john:doe", ((Attributes)logger.getArgs()[3]).getQName(0));
- }
-
- public void testEndElement() {
- AttributeListImpl atts = new AttributeListImpl();
- atts.addAttribute("john:doe", "int", "42");
-
- try {
- adapter.startDocument();
- adapter.startElement("foo:bar", atts);
- adapter.endElement("foo:bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals("endElement", logger.getMethod());
- assertEquals(new String[] { "", "", "foo:bar" }, logger.getArgs());
- }
-
- public void testCharacters() {
- char[] ch = "Android".toCharArray();
-
- try {
- adapter.characters(ch, 2, 5);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("characters", logger.getMethod());
- assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs());
- }
-
- public void testIgnorableWhitespace() {
- char[] ch = " ".toCharArray();
-
- try {
- adapter.ignorableWhitespace(ch, 0, 5);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("ignorableWhitespace", logger.getMethod());
- assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs());
- }
-
- public void testProcessingInstruction() {
- try {
- adapter.processingInstruction("foo", "bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("processingInstruction", logger.getMethod());
- assertEquals(new Object[] { "foo" , "bar" }, logger.getArgs());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java
deleted file mode 100644
index b59ce50..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/ParserFactoryTest.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.helpers.ParserFactory;
-
-@SuppressWarnings("deprecation")
-public class ParserFactoryTest extends TestCase {
-
- @Override protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testMakeParser() throws ClassNotFoundException,
- IllegalAccessException, InstantiationException {
-
- System.clearProperty("org.xml.sax.parser");
-
- // Property not set at all
- try {
- ParserFactory.makeParser();
- fail("expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // Expected
- }
-
- // Unknown class
- System.setProperty("org.xml.sax.parser", "foo.bar.SAXParser");
-
- try {
- ParserFactory.makeParser();
- fail("expected ClassNotFoundException was not thrown");
- } catch (ClassNotFoundException e) {
- // Expected
- }
-
- // Non-accessible class
- System.setProperty("org.xml.sax.parser",
- "tests.api.org.xml.sax.support.NoAccessParser");
-
- try {
- ParserFactory.makeParser();
- fail("expected IllegalAccessException was not thrown");
- } catch (IllegalAccessException e) {
- // Expected
- }
-
- // Non-instantiable class
- System.setProperty("org.xml.sax.parser",
- "tests.api.org.xml.sax.support.NoInstanceParser");
-
- try {
- ParserFactory.makeParser();
- fail("expected InstantiationException was not thrown");
- } catch (InstantiationException e) {
- // Expected
- }
-
- // Non-Parser class
- System.setProperty("org.xml.sax.parser",
- "tests.api.org.xml.sax.support.NoSubclassParser");
-
- try {
- ParserFactory.makeParser();
- fail("expected ClassCastException was not thrown");
- } catch (ClassCastException e) {
- // Expected
- }
-
- // Good one, finally
- System.setProperty("org.xml.sax.parser",
- "tests.api.org.xml.sax.support.DoNothingParser");
-
- ParserFactory.makeParser();
-
- }
-
- public void testMakeParserString() throws ClassNotFoundException,
- IllegalAccessException, InstantiationException {
- // No class
- try {
- ParserFactory.makeParser(null);
- fail("expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // Expected
- }
-
- // Unknown class
- try {
- ParserFactory.makeParser("foo.bar.SAXParser");
- fail("expected ClassNotFoundException was not thrown");
- } catch (ClassNotFoundException e) {
- // Expected
- }
-
- // Non-accessible class
- try {
- ParserFactory.makeParser(
- "tests.api.org.xml.sax.support.NoAccessParser");
- fail("expected IllegalAccessException was not thrown");
- } catch (IllegalAccessException e) {
- // Expected
- }
-
- // Non-instantiable class
- try {
- ParserFactory.makeParser(
- "tests.api.org.xml.sax.support.NoInstanceParser");
- fail("expected InstantiationException was not thrown");
- } catch (InstantiationException e) {
- // Expected
- }
-
- // Non-Parser class
- try {
- ParserFactory.makeParser(
- "tests.api.org.xml.sax.support.NoSubclassParser");
- fail("expected ClassCastException was not thrown");
- } catch (ClassCastException e) {
- // Expected
- }
-
- // Good one, finally
- ParserFactory.makeParser(
- "tests.api.org.xml.sax.support.DoNothingParser");
-
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java
deleted file mode 100644
index d00879b..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLFilterImplTest.java
+++ /dev/null
@@ -1,484 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.AttributesImpl;
-import org.xml.sax.helpers.LocatorImpl;
-import org.xml.sax.helpers.XMLFilterImpl;
-
-import tests.api.org.xml.sax.support.MethodLogger;
-import tests.api.org.xml.sax.support.MockFilter;
-import tests.api.org.xml.sax.support.MockHandler;
-import tests.api.org.xml.sax.support.MockResolver;
-
-public class XMLFilterImplTest extends TestCase {
-
- // Note: In many cases we can only test that delegation works
- // properly. The rest is outside the scope of the specification.
-
- private MethodLogger logger = new MethodLogger();
-
- private MockHandler handler = new MockHandler(logger);
-
- private XMLFilterImpl parent = new MockFilter(logger);
-
- private XMLFilterImpl child = new XMLFilterImpl(parent);
-
- private XMLFilterImpl orphan = new XMLFilterImpl();
-
- private void assertEquals(Object[] a, Object[] b) {
- assertEquals(a.length, b.length);
-
- for (int i = 0; i < a.length; i++) {
- assertEquals("Element #" + i + " must be equal", a[i], b[i]);
- }
- }
-
- public void setUp() {
- parent.setContentHandler(handler);
- parent.setDTDHandler(handler);
- parent.setErrorHandler(handler);
-
- child.setContentHandler(handler);
- child.setDTDHandler(handler);
- child.setErrorHandler(handler);
- }
-
- public void testXMLFilterImpl() {
- assertEquals(null, parent.getParent());
- }
-
- public void testXMLFilterImplXMLReader() {
- // Ordinary case
- assertEquals(null, parent.getParent());
-
- // null case
- XMLFilterImpl filter = new XMLFilterImpl(null);
- assertEquals(null, filter.getParent());
- }
-
- public void testGetSetParent() {
- child.setParent(null);
- assertEquals(null, child.getParent());
-
- child.setParent(parent);
- assertEquals(parent, child.getParent());
- }
-
- public void testGetSetFeature() {
- // Ordinary case
- try {
- child.setFeature("foo", true);
- assertEquals(true, child.getFeature("foo"));
-
- child.setFeature("foo", false);
- assertEquals(false, child.getFeature("foo"));
- } catch (SAXNotRecognizedException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // No parent case
- try {
- orphan.setFeature("foo", false);
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetSetProperty() {
- // Ordinary case
- try {
- child.setProperty("foo", "bar");
- assertEquals("bar", child.getProperty("foo"));
-
- child.setProperty("foo", null);
- assertEquals(null, child.getProperty("foo"));
- } catch (SAXNotRecognizedException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // No parent case
- try {
- orphan.setProperty("foo", "bar");
- fail("SAXNotRecognizedException expected");
- } catch (SAXNotRecognizedException e) {
- // Expected
- } catch (SAXNotSupportedException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testGetSetEntityResolver() {
- EntityResolver resolver = new MockResolver();
-
- parent.setEntityResolver(resolver);
- assertEquals(resolver, parent.getEntityResolver());
-
- parent.setEntityResolver(null);
- assertEquals(null, parent.getEntityResolver());
- }
-
- public void testGetSetDTDHandler() {
- parent.setDTDHandler(null);
- assertEquals(null, parent.getDTDHandler());
-
- parent.setDTDHandler(handler);
- assertEquals(handler, parent.getDTDHandler());
- }
-
- public void testGetSetContentHandler() {
- parent.setContentHandler(null);
- assertEquals(null, parent.getContentHandler());
-
- parent.setContentHandler(handler);
- assertEquals(handler, parent.getContentHandler());
- }
-
- public void testGetSetErrorHandler() {
- parent.setErrorHandler(null);
- assertEquals(null, parent.getErrorHandler());
-
- parent.setErrorHandler(handler);
- assertEquals(handler, parent.getErrorHandler());
- }
-
- public void testParseInputSource() {
- InputSource is = new InputSource();
-
- // Ordinary case
- try {
- child.parse(is);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(1, logger.size());
- assertEquals("parse", logger.getMethod());
-
- // No parent case
- try {
- orphan.parse(is);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testParseString() {
- // Ordinary case
- try {
- child.parse("foo");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(1, logger.size());
- assertEquals("parse", logger.getMethod());
-
- // No parent case
- try {
- orphan.parse("foo");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testResolveEntity() {
- InputSource expected = new InputSource();
-
- MockResolver resolver = new MockResolver();
- resolver.addEntity("foo", "bar", expected);
-
- InputSource result = null;
-
- parent.setEntityResolver(resolver);
-
- // Ordinary case
- try {
- result = parent.resolveEntity("foo", "bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(expected, result);
-
- // No entity resolver case
- parent.setEntityResolver(null);
-
- try {
- result = parent.resolveEntity("foo", "bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(null, result);
- }
-
- public void testNotationDecl() {
- try {
- parent.notationDecl("foo", "bar", "foobar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("notationDecl", logger.getMethod());
- assertEquals(new Object[] { "foo", "bar", "foobar" },
- logger.getArgs());
- }
-
- public void testUnparsedEntityDecl() {
- try {
- parent.unparsedEntityDecl("foo", "bar", "gabba", "hey");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("unparsedEntityDecl", logger.getMethod());
- assertEquals(new Object[] { "foo", "bar", "gabba", "hey" },
- logger.getArgs());
- }
-
- public void testSetDocumentLocator() {
- Locator l = new LocatorImpl();
-
- child.setDocumentLocator(l);
-
- assertEquals(logger.size(), 1);
- assertEquals("setDocumentLocator", logger.getMethod());
- assertEquals(new Object[] { l }, logger.getArgs());
-
- child.setDocumentLocator(null);
-
- assertEquals(logger.size(), 2);
- assertEquals("setDocumentLocator", logger.getMethod());
- assertEquals(new Object[] { null }, logger.getArgs());
- }
-
- public void testStartDocument() {
- try {
- parent.startDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("startDocument", logger.getMethod());
- assertEquals(new Object[] {}, logger.getArgs());
- }
-
- public void testEndDocument() {
- try {
- parent.endDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("endDocument", logger.getMethod());
- assertEquals(new Object[] {}, logger.getArgs());
- }
-
- public void testStartPrefixMapping() {
- try {
- parent.startPrefixMapping("foo", "http://some.uri");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("startPrefixMapping", logger.getMethod());
- assertEquals(new Object[] { "foo", "http://some.uri" },
- logger.getArgs());
- }
-
- public void testEndPrefixMapping() {
- try {
- parent.endPrefixMapping("foo");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("endPrefixMapping", logger.getMethod());
- assertEquals(new Object[] { "foo" }, logger.getArgs());
- }
-
- public void testStartElement() {
- Attributes atts = new AttributesImpl();
-
- try {
- parent.startElement("http://some.uri", "bar", "foo:bar", atts);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("startElement", logger.getMethod());
- assertEquals(new Object[] { "http://some.uri", "bar", "foo:bar", atts },
- logger.getArgs());
- }
-
- public void testEndElement() {
- try {
- parent.endElement("http://some.uri", "bar", "foo:bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("endElement", logger.getMethod());
- assertEquals(new Object[] { "http://some.uri", "bar", "foo:bar" },
- logger.getArgs());
- }
-
- public void testCharacters() {
- char[] ch = "Android".toCharArray();
-
- try {
- parent.characters(ch, 2, 5);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("characters", logger.getMethod());
- assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs());
- }
-
- public void testIgnorableWhitespace() {
- char[] ch = " ".toCharArray();
-
- try {
- parent.ignorableWhitespace(ch, 0, 5);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("ignorableWhitespace", logger.getMethod());
- assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs());
- }
-
- public void testProcessingInstruction() {
- try {
- parent.processingInstruction("foo", "bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("processingInstruction", logger.getMethod());
- assertEquals(new Object[] { "foo", "bar" }, logger.getArgs());
- }
-
- public void testSkippedEntity() {
- try {
- parent.skippedEntity("foo");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("skippedEntity", logger.getMethod());
- assertEquals(new Object[] { "foo" }, logger.getArgs());
- }
-
- public void testWarning() {
- SAXParseException exception = new SAXParseException("Oops!", null);
-
- try {
- parent.warning(exception);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("warning", logger.getMethod());
- assertEquals(new Object[] { exception }, logger.getArgs());
- }
-
- public void testError() {
- SAXParseException exception = new SAXParseException("Oops!", null);
-
- try {
- parent.error(exception);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("error", logger.getMethod());
- assertEquals(new Object[] { exception }, logger.getArgs());
- }
-
- public void testFatalError() {
- SAXParseException exception = new SAXParseException("Oops!", null);
-
- try {
- parent.fatalError(exception);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("fatalError", logger.getMethod());
- assertEquals(new Object[] { exception }, logger.getArgs());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java
deleted file mode 100644
index 16104b3..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderAdapterTest.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import java.io.IOException;
-import java.util.Locale;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.AttributeList;
-import org.xml.sax.Attributes;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.AttributesImpl;
-import org.xml.sax.helpers.LocatorImpl;
-import org.xml.sax.helpers.XMLReaderAdapter;
-
-import tests.api.org.xml.sax.support.MethodLogger;
-import tests.api.org.xml.sax.support.MockHandler;
-import tests.api.org.xml.sax.support.MockReader;
-import tests.api.org.xml.sax.support.MockResolver;
-
-@SuppressWarnings("deprecation")
-public class XMLReaderAdapterTest extends TestCase {
-
- // Note: In many cases we can only test that delegation works
- // properly. The rest is outside the scope of the specification.
-
- private MethodLogger logger = new MethodLogger();
-
- private MockHandler handler = new MockHandler(logger);
-
- private XMLReader reader = new MockReader(logger);
-
- private XMLReaderAdapter adapter = new XMLReaderAdapter(reader);
-
- private void assertEquals(Object[] a, Object[] b) {
- assertEquals(a.length, b.length);
-
- for (int i = 0; i < a.length; i++) {
- assertEquals("Element #" + i + " must be equal", a[i], b[i]);
- }
- }
-
- @Override
- public void setUp() {
- adapter.setDocumentHandler(handler);
- adapter.setDTDHandler(handler);
- adapter.setErrorHandler(handler);
- }
-
- @Override protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testXMLReaderAdapter() {
- System.setProperty("org.xml.sax.driver",
- "tests.api.org.xml.sax.support.DoNothingXMLReader");
-
- try {
- new XMLReaderAdapter();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
- }
-
- public void testXMLReaderAdapterXMLReader() {
- // Ordinary case
- @SuppressWarnings("unused")
- XMLReaderAdapter adapter = new XMLReaderAdapter(reader);
-
- // Null case
- try {
- adapter = new XMLReaderAdapter(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- public void testSetLocale() {
- // SAX RI does not support this, hence always expect exception
- try {
- adapter.setLocale(Locale.getDefault());
- fail("SAXException expected");
- } catch (SAXException e) {
- // Expected
- }
- }
-
- public void testSetEntityResolver() {
- EntityResolver resolver = new MockResolver();
-
- // Ordinary case
- adapter.setEntityResolver(resolver);
- assertEquals(resolver, reader.getEntityResolver());
-
- // null case
- adapter.setEntityResolver(null);
- assertEquals(null, reader.getEntityResolver());
- }
-
- public void testSetDTDHandler() {
- // Ordinary case
- assertEquals(handler, reader.getDTDHandler());
-
- // null case
- adapter.setDTDHandler(null);
- assertEquals(null, reader.getDTDHandler());
- }
-
- public void testSetDocumentHandler() {
- // There is no getter for the DocumentHandler, so we can only test
- // indirectly whether is has been set correctly.
- try {
- adapter.startDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals("startDocument", logger.getMethod());
- assertEquals(new Object[] { }, logger.getArgs());
-
- // null case
- adapter.setDocumentHandler(null);
- }
-
- public void testSetErrorHandler() {
- // Ordinary case
- assertEquals(handler, reader.getErrorHandler());
-
- // null case
- adapter.setErrorHandler(null);
- assertEquals(null, reader.getErrorHandler());
- }
-
- public void testParseString() {
- try {
- adapter.parse("foo");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // The SAX RI creates an InputSource itself and then delegates to the
- // "other" parse method.
- assertEquals("parse", logger.getMethod(0));
- assertEquals(InputSource.class, logger.getArgs(0)[0].getClass());
- }
-
- public void testParseInputSource() {
- InputSource source = new InputSource("foo");
-
- try {
- adapter.parse(source);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- } catch (IOException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals("parse", logger.getMethod());
- assertEquals(new Object[] { source }, logger.getArgs());
- }
-
- public void testSetDocumentLocator() {
- // Ordinary case
- LocatorImpl locator = new LocatorImpl();
- adapter.setDocumentLocator(locator);
-
- assertEquals("setDocumentLocator", logger.getMethod());
- assertEquals(new Object[] { locator }, logger.getArgs());
-
- // null case (for the DocumentHandler itself!)
- adapter.setDocumentHandler(null);
- adapter.setDocumentLocator(locator);
- }
-
- public void testStartDocument() {
- try {
- adapter.startDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("startDocument", logger.getMethod());
- assertEquals(new Object[] {}, logger.getArgs());
- }
-
- public void testEndDocument() {
- try {
- adapter.endDocument();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("endDocument", logger.getMethod());
- assertEquals(new Object[] {}, logger.getArgs());
- }
-
- public void testStartPrefixMapping() {
- adapter.startPrefixMapping("foo", "http://some.uri");
- assertEquals(logger.size(), 0);
- }
-
- public void testEndPrefixMapping() {
- adapter.endPrefixMapping("foo");
- assertEquals(logger.size(), 0);
- }
-
- public void testStartElement() {
- AttributesImpl atts = new AttributesImpl();
- atts.addAttribute("http://some.other.uri", "gabba", "gabba:hey",
- "int", "42");
-
- try {
- adapter.startElement("http://some.uri", "bar", "foo:bar", atts);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("startElement", logger.getMethod());
- assertEquals("foo:bar", logger.getArgs()[0]);
- assertEquals("gabba:hey",
- ((AttributeList)logger.getArgs()[1]).getName(0));
- }
-
- public void testEndElement() {
- try {
- adapter.endElement("http://some.uri", "bar", "foo:bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("endElement", logger.getMethod());
- assertEquals(new Object[] { "foo:bar" }, logger.getArgs());
- }
-
- public void testCharacters() {
- char[] ch = "Android".toCharArray();
-
- try {
- adapter.characters(ch, 2, 5);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("characters", logger.getMethod());
- assertEquals(new Object[] { ch, 2, 5 }, logger.getArgs());
- }
-
- public void testIgnorableWhitespace() {
- char[] ch = " ".toCharArray();
-
- try {
- adapter.ignorableWhitespace(ch, 0, 5);
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("ignorableWhitespace", logger.getMethod());
- assertEquals(new Object[] { ch, 0, 5 }, logger.getArgs());
- }
-
- public void testProcessingInstruction() {
- try {
- adapter.processingInstruction("foo", "bar");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 1);
- assertEquals("processingInstruction", logger.getMethod());
- assertEquals(new Object[] { "foo" , "bar" }, logger.getArgs());
- }
-
- public void testSkippedEntity() {
- try {
- adapter.skippedEntity("foo");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- assertEquals(logger.size(), 0);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java b/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java
deleted file mode 100644
index 8205dfd..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/helpers/XMLReaderFactoryTest.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.helpers;
-
-import junit.framework.TestCase;
-
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.XMLReaderFactory;
-
-public class XMLReaderFactoryTest extends TestCase {
-
- @Override protected void setUp() throws Exception {
- super.setUp();
- }
-
- @Override protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testCreateXMLReader() {
- // Property not set at all
- try {
- XMLReaderFactory.createXMLReader();
- } catch (SAXException e) {
- // Expected
- }
-
- // Unknown class
- System.setProperty("org.xml.sax.driver", "foo.bar.XMLReader");
-
- try {
- XMLReaderFactory.createXMLReader();
- } catch (SAXException e) {
- // Expected
- }
-
- // Non-accessible class
- System.setProperty("org.xml.sax.driver",
- "tests.api.org.xml.sax.support.NoAccessXMLReader");
-
- try {
- XMLReaderFactory.createXMLReader();
- } catch (SAXException e) {
- // Expected
- }
-
- // Non-instantiable class
- System.setProperty("org.xml.sax.driver",
- "tests.api.org.xml.sax.support.NoInstanceXMLReader");
-
- try {
- XMLReaderFactory.createXMLReader();
- } catch (SAXException e) {
- // Expected
- }
-
- // Non-XMLReader class
- System.setProperty("org.xml.sax.driver",
- "tests.api.org.xml.sax.support.NoSubclassXMLReader");
-
- try {
- XMLReaderFactory.createXMLReader();
- } catch (ClassCastException e) {
- // Expected
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // Good one, finally
- System.setProperty("org.xml.sax.driver",
- "tests.api.org.xml.sax.support.DoNothingXMLReader");
-
- try {
- XMLReaderFactory.createXMLReader();
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- }
-
- public void testMakeParserString() {
- // No class
- try {
- XMLReaderFactory.createXMLReader(null);
- } catch (NullPointerException e) {
- // Expected
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- // Unknown class
- try {
- XMLReaderFactory.createXMLReader("foo.bar.XMLReader");
- } catch (SAXException e) {
- // Expected
- }
-
- // Non-accessible class
- try {
- XMLReaderFactory.createXMLReader(
- "tests.api.org.xml.sax.support.NoAccessXMLReader");
- } catch (SAXException e) {
- // Expected
- }
-
- // Non-instantiable class
- try {
- XMLReaderFactory.createXMLReader(
- "tests.api.org.xml.sax.support.NoInstanceXMLReader");
- } catch (SAXException e) {
- // Expected
- }
-
- // Non-Parser class
- try {
- XMLReaderFactory.createXMLReader(
- "tests.api.org.xml.sax.support.NoSubclassXMLReader");
- } catch (SAXException e) {
- // Expected
- }
-
- // Good one, finally
- try {
- XMLReaderFactory.createXMLReader(
- "tests.api.org.xml.sax.support.DoNothingXMLReader");
- } catch (SAXException e) {
- throw new RuntimeException("Unexpected exception", e);
- }
-
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java b/luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java
deleted file mode 100644
index 8136b86..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/BrokenInputStream.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Implements an InputStream what wraps another InputStream and throws an
- * IOException after having read a specified number of bytes. Used for
- * injecting IOExceptions on lower levels.
- */
-public class BrokenInputStream extends InputStream {
-
- private InputStream stream;
-
- private int offset;
-
- public BrokenInputStream(InputStream stream, int offset) {
- super();
-
- this.stream = stream;
- this.offset = offset;
- }
-
- @Override
- public int read() throws IOException {
- if (offset == 0) {
- throw new IOException("Injected exception");
- }
-
- offset--;
- return stream.read();
- }
-
- @Override
- public void close() throws IOException {
- stream.close();
- }
-} \ No newline at end of file
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java
deleted file mode 100644
index c18b6ee..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingParser.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Parser;
-
-import java.util.Locale;
-
-/**
- * A SAX Parser that does nothing, but can be instantiated properly.
- */
-@SuppressWarnings("deprecation")
-public class DoNothingParser implements Parser {
-
- public void parse(InputSource source) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setDocumentHandler(DocumentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setLocale(Locale locale) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java
deleted file mode 100644
index 8687bff..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/DoNothingXMLReader.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-
-/**
- * An XMLReader that does nothing, but can be instantiated properly.
- */
-public class DoNothingXMLReader implements XMLReader {
-
- public ContentHandler getContentHandler() {
- return null;
- }
-
- public DTDHandler getDTDHandler() {
- return null;
- }
-
- public EntityResolver getEntityResolver() {
- return null;
- }
-
- public ErrorHandler getErrorHandler() {
- return null;
- }
-
- public boolean getFeature(String name) {
- return false;
- }
-
- public Object getProperty(String name) {
- return null;
- }
-
- public void parse(InputSource input) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setContentHandler(ContentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setFeature(String name, boolean value) {
- }
-
- public void setProperty(String name, Object value) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java b/luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java
deleted file mode 100644
index ad8ef5f..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/MethodLogger.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A simple helper class that logs method calls by storing method names and
- * parameter lists. Used as a foundation for various simple SAX handlers.
- */
-public class MethodLogger {
-
- /**
- * The names of the invoked methods, in order.
- */
- private List<String> methods = new ArrayList<String>();
-
- /**
- * The parameter lists of the invoked methods, in order.
- */
- private List<Object[]> argLists = new ArrayList<Object[]>();
-
- /**
- * Adds a method call with a variable list of arguments.
- */
- public void add(String method, Object ... args) {
- Object[] argsCopy = new Object[args.length];
- System.arraycopy(args, 0, argsCopy, 0, args.length);
-
- methods.add(method);
- argLists.add(argsCopy);
- }
-
- /**
- * Returns the number of method invoked so far.
- */
- public int size() {
- return methods.size();
- }
-
- /**
- * Returns the method name stored at the given index.
- */
- public String getMethod(int index) {
- return methods.get(index);
- }
-
- /**
- * Returns the name of the last method that was invoked. Returns null if no
- * method calls have been logged so far.
- */
- public String getMethod() {
- return (size() == 0 ? null : getMethod(size() - 1));
- }
-
- /**
- * Returns the argument array stored at the given index. May be empty, but
- * not null.
- */
- public Object[] getArgs(int index) {
- return argLists.get(index);
- }
-
- /**
- * Returns the argument array of the last method that was invoked. Returns
- * null if no method has been invoked so far.
- */
- public Object[] getArgs() {
- return (size() == 0 ? null : getArgs(size() - 1));
- }
-
- /**
- * Clears the log.
- */
- public void clear() {
- methods.clear();
- argLists.clear();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java
deleted file mode 100644
index 1189ebd..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/MockFilter.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.helpers.XMLFilterImpl;
-
-/**
- * A helper class that extends XMLFilterImpl, provides dummy feature/property
- * management, and logs some method calls.
- */
-public class MockFilter extends XMLFilterImpl {
-
- private MethodLogger logger;
-
- private Set<String> features = new HashSet<String>();
-
- private Map<String, Object> properties = new HashMap<String, Object>();
-
- public MockFilter(MethodLogger logger) {
- super();
- this.logger = logger;
- }
-
- @Override
- public boolean getFeature(String name) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- return features.contains(name);
- }
-
- @Override
- public Object getProperty(String name) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- return properties.get(name);
- }
-
- @Override
- public void setFeature(String name, boolean value) {
- if (value) {
- features.add(name);
- } else {
- features.remove(name);
- }
- }
-
- @Override
- public void setProperty(String name, Object value) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- if (value == null) {
- properties.remove(name);
- } else {
- properties.put(name, value);
- }
- }
-
- @Override
- public void parse(InputSource input) throws SAXException, IOException {
- logger.add("parse", input);
- }
-
- @Override
- public void parse(String systemId) throws SAXException, IOException {
- logger.add("parse", systemId);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java
deleted file mode 100644
index 55757c9..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/MockHandler.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.AttributeList;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.ext.LexicalHandler;
-
-/**
- * A helper class that implements the various SAX callback interfaces and logs
- * method calls.
- */
-@SuppressWarnings("deprecation")
-public class MockHandler implements ContentHandler, DTDHandler, DocumentHandler,
- ErrorHandler, LexicalHandler {
-
- private MethodLogger logger;
-
- public MockHandler(MethodLogger logger) {
- super();
- this.logger = logger;
- }
-
- public void characters(char[] ch, int start, int length) throws SAXException {
- logger.add("characters", ch, start, length);
- }
-
- public void endDocument() throws SAXException {
- logger.add("endDocument");
- }
-
- public void endElement(String name) throws SAXException {
- logger.add("endElement", name);
- }
-
- public void endElement(String uri, String localName, String name) throws SAXException {
- logger.add("endElement", uri, localName, name);
- }
-
- public void endPrefixMapping(String prefix) throws SAXException {
- logger.add("endPrefixMapping", prefix);
- }
-
- public void error(SAXParseException exception) throws SAXException {
- logger.add("error", exception);
- }
-
- public void fatalError(SAXParseException exception) throws SAXException {
- logger.add("fatalError", exception);
- }
-
- public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
- logger.add("ignorableWhitespace", ch, start, length);
- }
-
- public void notationDecl(String name, String publicId, String systemId) throws SAXException {
- logger.add("notationDecl", name, publicId, systemId);
- }
-
- public void processingInstruction(String target, String data) throws SAXException {
- logger.add("processingInstruction", target, data);
- }
-
- public void setDocumentLocator(Locator locator) {
- logger.add("setDocumentLocator", locator);
- }
-
- public void skippedEntity(String name) throws SAXException {
- logger.add("skippedEntity", name);
- }
-
- public void startDocument() throws SAXException {
- logger.add("startDocument");
- }
-
- public void startElement(String name, AttributeList atts) throws SAXException {
- logger.add("startElement", name, atts);
- }
-
- public void startElement(String uri, String localName, String name, Attributes atts)
- throws SAXException {
- logger.add("startElement", uri, localName, name, atts);
- }
-
- public void startPrefixMapping(String prefix, String uri) throws SAXException {
- logger.add("startPrefixMapping", prefix, uri);
- }
-
- public void unparsedEntityDecl(String name, String publicId, String systemId,
- String notationName) throws SAXException {
- logger.add("unparsedEntityDecl", name, publicId, systemId, notationName);
- }
-
- public void warning(SAXParseException exception) throws SAXException {
- logger.add("warning", exception);
- }
-
- public void comment(char[] ch, int start, int length) throws SAXException {
- logger.add("comment", ch, start, length);
- }
-
- public void endCDATA() throws SAXException {
- logger.add("endCDATA");
- }
-
- public void endDTD() throws SAXException {
- logger.add("endDTD");
- }
-
- public void endEntity(String name) throws SAXException {
- logger.add("endEntity", name);
- }
-
- public void startCDATA() throws SAXException {
- logger.add("startCDATA");
- }
-
- public void startDTD(String name, String publicId, String systemId) throws SAXException {
- logger.add("startDTD", name, publicId, systemId);
- }
-
- public void startEntity(String name) throws SAXException {
- logger.add("startEntity", name);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java
deleted file mode 100644
index e19e14e..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/MockParser.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import java.io.IOException;
-import java.util.Locale;
-
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Parser;
-import org.xml.sax.SAXException;
-
-@SuppressWarnings("deprecation")
-public class MockParser implements Parser {
-
- private MethodLogger logger;
-
- public MockParser(MethodLogger logger) {
- super();
- this.logger = logger;
- }
-
- public void parse(InputSource source) throws SAXException, IOException {
- logger.add("parse", source);
- }
-
- public void parse(String systemId) throws SAXException, IOException {
- logger.add("parse", systemId);
- }
-
- public void setDTDHandler(DTDHandler handler) {
- logger.add("setDTDHandler", handler);
- }
-
- public void setDocumentHandler(DocumentHandler handler) {
- logger.add("setDocumentHandler", handler);
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- logger.add("setEntityResolver", resolver);
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- logger.add("setErrorHandler", handler);
- }
-
- public void setLocale(Locale locale) throws SAXException {
- logger.add("setLocale", locale);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java
deleted file mode 100644
index 2f0081c..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/MockReader.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.XMLReader;
-
-/**
- * A helper class that implements the SAX XMLReader interface and logs method
- * calls.
- */
-public class MockReader implements XMLReader {
-
- private MethodLogger logger;
-
- private ContentHandler contentHandler;
-
- private DTDHandler dtdHandler;
-
- private EntityResolver resolver;
-
- private ErrorHandler errorHandler;
-
- private Set<String> features = new HashSet<String>();
-
- private Map<String, Object> properties = new HashMap<String, Object>();
-
- public MockReader(MethodLogger logger) {
- super();
- this.logger = logger;
- }
-
-
- public ContentHandler getContentHandler() {
- return contentHandler;
- }
-
- public DTDHandler getDTDHandler() {
- return dtdHandler;
- }
-
- public EntityResolver getEntityResolver() {
- return resolver;
- }
-
- public ErrorHandler getErrorHandler() {
- return errorHandler;
- }
-
- public boolean getFeature(String name) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- return features.contains(name);
- }
-
- public Object getProperty(String name) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- return properties.get(name);
- }
-
- public void parse(InputSource input) throws IOException, SAXException {
- logger.add("parse", input);
- }
-
- public void parse(String systemId) throws IOException, SAXException {
- logger.add("parse", systemId);
- }
-
- public void setContentHandler(ContentHandler handler) {
- this.contentHandler = handler;
- }
-
- public void setDTDHandler(DTDHandler handler) {
- this.dtdHandler = handler;
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- this.resolver = resolver;
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- this.errorHandler = handler;
- }
-
- public void setFeature(String name, boolean value) {
- if (value) {
- features.add(name);
- } else {
- features.remove(name);
- }
- }
-
- public void setProperty(String name, Object value) throws SAXNotRecognizedException,
- SAXNotSupportedException {
- if (value == null) {
- properties.remove(name);
- } else {
- properties.put(name, value);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java b/luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java
deleted file mode 100644
index df4ddbf..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/MockResolver.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.xml.sax.EntityResolver;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * A helper class for resolving entities.
- */
-public class MockResolver implements EntityResolver {
-
- private Map<String, InputSource> entities = new HashMap<String, InputSource>();
-
- public void addEntity(String publicId, String systemId, InputSource source) {
- entities.put("[" + publicId + ":" + systemId + "]", source);
- }
-
- public void removeEntity(String publicId, String systemId) {
- entities.remove("[" + publicId + ":" + systemId + "]");
- }
-
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException, IOException {
- return entities.get("[" + publicId + ":" + systemId + "]");
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java
deleted file mode 100644
index 9fca514..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessParser.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Parser;
-
-import java.util.Locale;
-
-/**
- * A SAX Parser that can't be accessed.
- */
-@SuppressWarnings("deprecation")
-class NoAccessParser implements Parser {
-
- public void parse(InputSource source) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setDocumentHandler(DocumentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setLocale(Locale locale) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java
deleted file mode 100644
index b6a0a68..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/NoAccessXMLReader.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-
-/**
- * An XMLReader that is not accessible.
- */
-class NoAccessXMLReader implements XMLReader {
-
- public ContentHandler getContentHandler() {
- return null;
- }
-
- public DTDHandler getDTDHandler() {
- return null;
- }
-
- public EntityResolver getEntityResolver() {
- return null;
- }
-
- public ErrorHandler getErrorHandler() {
- return null;
- }
-
- public boolean getFeature(String name) {
- return false;
- }
-
- public Object getProperty(String name) {
- return null;
- }
-
- public void parse(InputSource input) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setContentHandler(ContentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setFeature(String name, boolean value) {
- }
-
- public void setProperty(String name, Object value) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java
deleted file mode 100644
index 48cfba7..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceParser.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Parser;
-
-import java.util.Locale;
-
-/**
- * A SAX Parser that can be accessed, but not instantiated.
- */
-@SuppressWarnings("deprecation")
-public class NoInstanceParser implements Parser {
-
- public NoInstanceParser(int i) {
- }
-
- public void parse(InputSource source) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setDocumentHandler(DocumentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setLocale(Locale locale) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java
deleted file mode 100644
index 7b386bc..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/NoInstanceXMLReader.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-
-/**
- * An XMLReader that is accessible, but can't be instantiated.
- */
-public class NoInstanceXMLReader implements XMLReader {
-
- public NoInstanceXMLReader(int i) {
- }
-
- public ContentHandler getContentHandler() {
- return null;
- }
-
- public DTDHandler getDTDHandler() {
- return null;
- }
-
- public EntityResolver getEntityResolver() {
- return null;
- }
-
- public ErrorHandler getErrorHandler() {
- return null;
- }
-
- public boolean getFeature(String name) {
- return false;
- }
-
- public Object getProperty(String name) {
- return null;
- }
-
- public void parse(InputSource input) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setContentHandler(ContentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setFeature(String name, boolean value) {
- }
-
- public void setProperty(String name, Object value) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java
deleted file mode 100644
index 8016c10..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassParser.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.DTDHandler;
-import org.xml.sax.DocumentHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-
-import java.util.Locale;
-
-/**
- * A SAX Parser that does not implement the Parser interface.
- */
-@SuppressWarnings("deprecation")
-public class NoSubclassParser {
-
- public void parse(InputSource source) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setDocumentHandler(DocumentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setLocale(Locale locale) {
- }
-
-}
diff --git a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java b/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java
deleted file mode 100644
index acdbd88..0000000
--- a/luni/src/test/java/tests/api/org/xml/sax/support/NoSubclassXMLReader.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2007 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 tests.api.org.xml.sax.support;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-
-/**
- * An XMLReader that does not implement the XMLReader interface.
- */
-public class NoSubclassXMLReader implements XMLReader {
-
- public ContentHandler getContentHandler() {
- return null;
- }
-
- public DTDHandler getDTDHandler() {
- return null;
- }
-
- public EntityResolver getEntityResolver() {
- return null;
- }
-
- public ErrorHandler getErrorHandler() {
- return null;
- }
-
- public boolean getFeature(String name) {
- return false;
- }
-
- public Object getProperty(String name) {
- return null;
- }
-
- public void parse(InputSource input) {
- }
-
- public void parse(String systemId) {
- }
-
- public void setContentHandler(ContentHandler handler) {
- }
-
- public void setDTDHandler(DTDHandler handler) {
- }
-
- public void setEntityResolver(EntityResolver resolver) {
- }
-
- public void setErrorHandler(ErrorHandler handler) {
- }
-
- public void setFeature(String name, boolean value) {
- }
-
- public void setProperty(String name, Object value) {
- }
-
-}
diff --git a/luni/src/test/java/tests/java/sql/SqlDateTest.java b/luni/src/test/java/tests/java/sql/SqlDateTest.java
new file mode 100644
index 0000000..fb226af
--- /dev/null
+++ b/luni/src/test/java/tests/java/sql/SqlDateTest.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2014 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.
+ */
+
+import java.sql.Date;
+
+import junit.framework.TestCase;
+
+public class SqlDateTest extends TestCase {
+
+ public void testValueOf() {
+ String[] dates = {
+ "2001-12-31", "2001-12-1", "2001-1-1", "1900-12-31"
+ };
+
+ for (String date : dates) {
+ Date.valueOf(date);
+ }
+ }
+
+ public void testValueOfInvalidDate() {
+ String[] invalidDates = {
+ "",
+ "+2001-12-31", "2001-+12-31", "2001-12-+31",
+ "-2001-12-31", "2001--12-31", "2001-12--31",
+ "2001--","2001--31","-12-31", "-12-", "--31",
+ "2000000001-12-31"
+ };
+
+ for (String date : invalidDates) {
+ try {
+ Date.valueOf(date);
+ fail();
+ } catch (IllegalArgumentException expected) { }
+ }
+ }
+
+}
diff --git a/luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java b/luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java
new file mode 100644
index 0000000..c3894f8
--- /dev/null
+++ b/luni/src/test/java/tests/security/cert/CertificateRevocationExceptionTest.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2014 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 tests.security.cert;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.security.cert.CRLReason;
+import java.security.cert.CertificateRevokedException;
+import java.security.cert.Extension;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import javax.security.auth.x500.X500Principal;
+
+import junit.framework.TestCase;
+
+/**
+ *
+ */
+public class CertificateRevocationExceptionTest extends TestCase implements SerializableAssert {
+ private CertificateRevokedException getTestException() {
+ HashMap<String, Extension> extensions = new HashMap<String, Extension>();
+ // REASON_CODE
+ extensions.put("2.5.29.21", getReasonExtension());
+ extensions.put("2.5.29.24", getInvalidityExtension());
+ return new CertificateRevokedException(
+ new Date(1199226851000L),
+ CRLReason.CESSATION_OF_OPERATION,
+ new X500Principal("CN=test1"),
+ extensions);
+ }
+
+ private Extension getReasonExtension() {
+ return new Extension() {
+ @Override
+ public String getId() {
+ return "2.5.29.21";
+ }
+
+ @Override
+ public boolean isCritical() {
+ return false;
+ }
+
+ @Override
+ public byte[] getValue() {
+ return new byte[] {4, 3, 10, 1, 5};
+ }
+
+ @Override
+ public void encode(OutputStream out) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ private Extension getInvalidityExtension() {
+ return new Extension() {
+ @Override
+ public String getId() {
+ return "2.5.29.24";
+ }
+
+ @Override
+ public boolean isCritical() {
+ return false;
+ }
+
+ @Override
+ public byte[] getValue() {
+ return new byte[] {
+ 0x18, 0x0F, 0x32, 0x30, 0x31, 0x34, 0x30, 0x31, 0x31, 0x37, 0x30, 0x38,
+ 0x33, 0x30, 0x30, 0x39, 0x5a
+ };
+ }
+
+ @Override
+ public void encode(OutputStream out) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+ public void testGetExtensions() throws Exception {
+ CertificateRevokedException original = getTestException();
+ Map<String, Extension> extensions = original.getExtensions();
+ assertNotSame(extensions, original.getExtensions());
+
+ try {
+ extensions.put("2.2.2.2", getReasonExtension());
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ }
+
+ public void testGetRevocationDate() throws Exception {
+ CertificateRevokedException exception = getTestException();
+
+ Date firstDate = exception.getRevocationDate();
+ assertNotSame(firstDate, exception.getRevocationDate());
+
+ firstDate.setYear(firstDate.getYear() + 1);
+ assertTrue(firstDate.compareTo(exception.getRevocationDate()) > 0);
+ }
+
+ public void testGetInvalidityDate() throws Exception {
+ CertificateRevokedException exception = getTestException();
+
+ Date firstDate = exception.getInvalidityDate();
+ assertNotSame(firstDate, exception.getInvalidityDate());
+
+ firstDate.setYear(firstDate.getYear() + 1);
+ assertTrue(firstDate.compareTo(exception.getInvalidityDate()) > 0);
+ }
+
+
+ /**
+ * serialization/deserialization compatibility.
+ */
+ public void testSerializationCertificateRevokedExceptionSelf() throws Exception {
+ SerializationTest.verifySelf(getTestException(), this);
+ }
+
+ /**
+ * serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCertificateRevokedExceptionCompatability() throws Exception {
+ // create test file (once)
+ // SerializationTest.createGoldenFile("/tmp", this, getTestException());
+ SerializationTest.verifyGolden(this, getTestException());
+ }
+
+ @Override
+ public void assertDeserialized(Serializable initial, Serializable deserialized) {
+ assertTrue(initial instanceof CertificateRevokedException);
+ assertTrue(deserialized instanceof CertificateRevokedException);
+
+ CertificateRevokedException expected = (CertificateRevokedException) initial;
+ CertificateRevokedException actual = (CertificateRevokedException) deserialized;
+
+ assertEquals(expected.getInvalidityDate(), actual.getInvalidityDate());
+ assertNotSame(expected.getInvalidityDate(), actual.getInvalidityDate());
+ assertEquals(expected.getRevocationDate(), actual.getRevocationDate());
+ assertNotSame(expected.getRevocationDate(), actual.getRevocationDate());
+ assertEquals(expected.getRevocationReason(), expected.getRevocationReason());
+
+ assertEquals(expected.getExtensions().size(), actual.getExtensions().size());
+ assertEquals(expected.getExtensions().keySet(), actual.getExtensions().keySet());
+ }
+}
diff --git a/luni/src/test/native/dalvik_system_JniTest.cpp b/luni/src/test/native/dalvik_system_JniTest.cpp
new file mode 100644
index 0000000..df48ca9
--- /dev/null
+++ b/luni/src/test/native/dalvik_system_JniTest.cpp
@@ -0,0 +1,274 @@
+/*
+ * 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.
+ */
+
+#include <jni.h>
+#include <stdlib.h> // for abort
+
+extern "C" jobject Java_dalvik_system_JniTest_returnThis(JNIEnv*, jobject obj) {
+ return obj;
+}
+
+extern "C" jclass Java_dalvik_system_JniTest_returnClass(JNIEnv*, jclass klass) {
+ return klass;
+}
+
+extern "C" jobject Java_dalvik_system_JniTest_returnObjectArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jobject o1, jobject o2, jobject o3, jobject o4, jobject o5,
+ jobject o6, jobject o7, jobject o8, jobject o9, jobject o10,
+ jobject o11, jobject o12, jobject o13, jobject o14, jobject o15,
+ jobject o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jboolean Java_dalvik_system_JniTest_returnBooleanArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jboolean o1, jboolean o2, jboolean o3, jboolean o4, jboolean o5,
+ jboolean o6, jboolean o7, jboolean o8, jboolean o9, jboolean o10,
+ jboolean o11, jboolean o12, jboolean o13, jboolean o14, jboolean o15,
+ jboolean o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jchar Java_dalvik_system_JniTest_returnCharArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jchar o1, jchar o2, jchar o3, jchar o4, jchar o5,
+ jchar o6, jchar o7, jchar o8, jchar o9, jchar o10,
+ jchar o11, jchar o12, jchar o13, jchar o14, jchar o15,
+ jchar o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jbyte Java_dalvik_system_JniTest_returnByteArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jbyte o1, jbyte o2, jbyte o3, jbyte o4, jbyte o5,
+ jbyte o6, jbyte o7, jbyte o8, jbyte o9, jbyte o10,
+ jbyte o11, jbyte o12, jbyte o13, jbyte o14, jbyte o15,
+ jbyte o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jshort Java_dalvik_system_JniTest_returnShortArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jshort o1, jshort o2, jshort o3, jshort o4, jshort o5,
+ jshort o6, jshort o7, jshort o8, jshort o9, jshort o10,
+ jshort o11, jshort o12, jshort o13, jshort o14, jshort o15,
+ jshort o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jint Java_dalvik_system_JniTest_returnIntArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jint o1, jint o2, jint o3, jint o4, jint o5,
+ jint o6, jint o7, jint o8, jint o9, jint o10,
+ jint o11, jint o12, jint o13, jint o14, jint o15,
+ jint o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jlong Java_dalvik_system_JniTest_returnLongArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jlong o1, jlong o2, jlong o3, jlong o4, jlong o5,
+ jlong o6, jlong o7, jlong o8, jlong o9, jlong o10,
+ jlong o11, jlong o12, jlong o13, jlong o14, jlong o15,
+ jlong o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jfloat Java_dalvik_system_JniTest_returnFloatArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jfloat o1, jfloat o2, jfloat o3, jfloat o4, jfloat o5,
+ jfloat o6, jfloat o7, jfloat o8, jfloat o9, jfloat o10,
+ jfloat o11, jfloat o12, jfloat o13, jfloat o14, jfloat o15,
+ jfloat o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jdouble Java_dalvik_system_JniTest_returnDoubleArgFrom16(
+ JNIEnv*, jobject, int arg_no,
+ jdouble o1, jdouble o2, jdouble o3, jdouble o4, jdouble o5,
+ jdouble o6, jdouble o7, jdouble o8, jdouble o9, jdouble o10,
+ jdouble o11, jdouble o12, jdouble o13, jdouble o14, jdouble o15,
+ jdouble o16) {
+ switch(arg_no){
+ case 0: return o1;
+ case 1: return o2;
+ case 2: return o3;
+ case 3: return o4;
+ case 4: return o5;
+ case 5: return o6;
+ case 6: return o7;
+ case 7: return o8;
+ case 8: return o9;
+ case 9: return o10;
+ case 10: return o11;
+ case 11: return o12;
+ case 12: return o13;
+ case 13: return o14;
+ case 14: return o15;
+ case 15: return o16;
+ default: abort();
+ }
+}
+
+extern "C" jclass Java_dalvik_system_JniTest_envGetSuperclass(
+ JNIEnv* env, jobject, jclass clazz) {
+ return env->GetSuperclass(clazz);
+}
diff --git a/luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider b/luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider
deleted file mode 100644
index d29245f..0000000
--- a/luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider
+++ /dev/null
@@ -1,2 +0,0 @@
-tests.api.java.nio.charset.CharsetTest$MockCharsetProvider
-tests.api.java.nio.charset.CharsetTest$MockCharsetProviderASCII
diff --git a/luni/src/test/resources/math_important_numbers.csv b/luni/src/test/resources/math_important_numbers.csv
new file mode 100644
index 0000000..3c71a4e
--- /dev/null
+++ b/luni/src/test/resources/math_important_numbers.csv
@@ -0,0 +1,738 @@
+#These numbers are automatically generated to test numbers such as pi, pi/2, 0, etc.
+abs,0x1.5bf0a8b145769p1,0x1.5bf0a8b145769p1,2.718281828459045
+abs,0x1.5bf0a8b145769p1,-0x1.5bf0a8b145769p1,-2.718281828459045
+abs,0x0.0p0,0x0.0p0,0.0
+abs,0x0.0p0,-0x0.0p0,-0.0
+abs,0x1.0p0,0x1.0p0,1.0
+abs,0x1.0p0,-0x1.0p0,-1.0
+abs,0x1.0p-1,-0x1.0p-1,-0.5
+abs,0x1.0p-1,0x1.0p-1,0.5
+abs,0x1.921fb54442d18p2,-0x1.921fb54442d18p2,-6.283185307179586
+abs,0x1.815e630c155e1p2,-0x1.815e630c155e1p2,-6.021385919380436
+abs,0x1.709d10d3e7eabp2,-0x1.709d10d3e7eabp2,-5.759586531581287
+abs,0x1.5fdbbe9bba775p2,-0x1.5fdbbe9bba775p2,-5.497787143782138
+abs,0x1.4f1a6c638d03fp2,-0x1.4f1a6c638d03fp2,-5.235987755982989
+abs,0x1.3e591a2b5f908p2,-0x1.3e591a2b5f908p2,-4.974188368183839
+abs,0x1.2d97c7f3321d2p2,-0x1.2d97c7f3321d2p2,-4.71238898038469
+abs,0x1.1cd675bb04a9cp2,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+abs,0x1.0c152382d7365p2,-0x1.0c152382d7365p2,-4.1887902047863905
+abs,0x1.f6a7a2955385dp1,-0x1.f6a7a2955385dp1,-3.926990816987241
+abs,0x1.d524fe24f89f1p1,-0x1.d524fe24f89f1p1,-3.665191429188092
+abs,0x1.b3a259b49db85p1,-0x1.b3a259b49db85p1,-3.4033920413889427
+abs,0x1.921fb54442d18p1,-0x1.921fb54442d18p1,-3.141592653589793
+abs,0x1.709d10d3e7eabp1,-0x1.709d10d3e7eabp1,-2.8797932657906435
+abs,0x1.4f1a6c638d03fp1,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+abs,0x1.2d97c7f3321d2p1,-0x1.2d97c7f3321d2p1,-2.356194490192345
+abs,0x1.0c152382d7365p1,-0x1.0c152382d7365p1,-2.0943951023931953
+abs,0x1.d524fe24f89f1p0,-0x1.d524fe24f89f1p0,-1.832595714594046
+abs,0x1.921fb54442d18p0,-0x1.921fb54442d18p0,-1.5707963267948966
+abs,0x1.4f1a6c638d03fp0,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+abs,0x1.0c152382d7365p0,-0x1.0c152382d7365p0,-1.0471975511965976
+abs,0x1.921fb54442d18p-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+abs,0x1.0c152382d7365p-1,-0x1.0c152382d7365p-1,-0.5235987755982988
+abs,0x1.0c152382d7365p-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+abs,0x0.0p0,0x0.0p0,0.0
+abs,0x1.0c152382d7365p-2,0x1.0c152382d7365p-2,0.2617993877991494
+abs,0x1.0c152382d7365p-1,0x1.0c152382d7365p-1,0.5235987755982988
+abs,0x1.921fb54442d18p-1,0x1.921fb54442d18p-1,0.7853981633974483
+abs,0x1.0c152382d7365p0,0x1.0c152382d7365p0,1.0471975511965976
+abs,0x1.4f1a6c638d03fp0,0x1.4f1a6c638d03fp0,1.3089969389957472
+abs,0x1.921fb54442d18p0,0x1.921fb54442d18p0,1.5707963267948966
+abs,0x1.d524fe24f89f1p0,0x1.d524fe24f89f1p0,1.832595714594046
+abs,0x1.0c152382d7365p1,0x1.0c152382d7365p1,2.0943951023931953
+abs,0x1.2d97c7f3321d2p1,0x1.2d97c7f3321d2p1,2.356194490192345
+abs,0x1.4f1a6c638d03fp1,0x1.4f1a6c638d03fp1,2.6179938779914944
+abs,0x1.709d10d3e7eabp1,0x1.709d10d3e7eabp1,2.8797932657906435
+abs,0x1.921fb54442d18p1,0x1.921fb54442d18p1,3.141592653589793
+abs,0x1.b3a259b49db85p1,0x1.b3a259b49db85p1,3.4033920413889427
+abs,0x1.d524fe24f89f1p1,0x1.d524fe24f89f1p1,3.665191429188092
+abs,0x1.f6a7a2955385dp1,0x1.f6a7a2955385dp1,3.926990816987241
+abs,0x1.0c152382d7365p2,0x1.0c152382d7365p2,4.1887902047863905
+abs,0x1.1cd675bb04a9cp2,0x1.1cd675bb04a9cp2,4.4505895925855405
+abs,0x1.2d97c7f3321d2p2,0x1.2d97c7f3321d2p2,4.71238898038469
+abs,0x1.3e591a2b5f908p2,0x1.3e591a2b5f908p2,4.974188368183839
+abs,0x1.4f1a6c638d03fp2,0x1.4f1a6c638d03fp2,5.235987755982989
+abs,0x1.5fdbbe9bba775p2,0x1.5fdbbe9bba775p2,5.497787143782138
+abs,0x1.709d10d3e7eabp2,0x1.709d10d3e7eabp2,5.759586531581287
+abs,0x1.815e630c155e1p2,0x1.815e630c155e1p2,6.021385919380436
+abs,0x1.921fb54442d18p2,0x1.921fb54442d18p2,6.283185307179586
+acos,0x1.921fb54442d18p0,0x0.0p0,0.0
+acos,0x1.921fb54442d18p0,-0x0.0p0,-0.0
+acos,0x0.0p0,0x1.0p0,1.0
+acos,0x1.921fb54442d18p1,-0x1.0p0,-1.0
+acos,0x1.0c152382d7366p1,-0x1.0p-1,-0.5
+acos,0x1.0c152382d7366p0,0x1.0p-1,0.5
+acos,0x1.3cb0785319b73p1,-0x1.921fb54442d18p-1,-0.7853981633974483
+acos,0x1.0f994d58bf2a8p1,-0x1.0c152382d7365p-1,-0.5235987755982988
+acos,0x1.d5ef495ee4bfcp0,-0x1.0c152382d7365p-2,-0.2617993877991494
+acos,0x1.921fb54442d18p0,0x0.0p0,0.0
+acos,0x1.4e502129a0e35p0,0x1.0c152382d7365p-2,0.2617993877991494
+acos,0x1.050ccfd7074dfp0,0x1.0c152382d7365p-1,0.5235987755982988
+acos,0x1.55bcf3c4a4694p-1,0x1.921fb54442d18p-1,0.7853981633974483
+asin,0x0.0p0,0x0.0p0,0.0
+asin,-0x0.0p0,-0x0.0p0,-0.0
+asin,0x1.921fb54442d18p0,0x1.0p0,1.0
+asin,-0x1.921fb54442d18p0,-0x1.0p0,-1.0
+asin,-0x1.0c152382d7366p-1,-0x1.0p-1,-0.5
+asin,0x1.0c152382d7366p-1,0x1.0p-1,0.5
+asin,-0x1.ce8276c3e139cp-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+asin,-0x1.1a25cada77072p-1,-0x1.0c152382d7365p-1,-0.5235987755982988
+asin,-0x1.0f3e506a87b8dp-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+asin,0x0.0p0,0x0.0p0,0.0
+asin,0x1.0f3e506a87b8dp-2,0x1.0c152382d7365p-2,0.2617993877991494
+asin,0x1.1a25cada77072p-1,0x1.0c152382d7365p-1,0.5235987755982988
+asin,0x1.ce8276c3e139cp-1,0x1.921fb54442d18p-1,0.7853981633974483
+atan,0x1.37e1637253389p0,0x1.5bf0a8b145769p1,2.718281828459045
+atan,-0x1.37e1637253389p0,-0x1.5bf0a8b145769p1,-2.718281828459045
+atan,0x0.0p0,0x0.0p0,0.0
+atan,-0x0.0p0,-0x0.0p0,-0.0
+atan,0x1.921fb54442d18p-1,0x1.0p0,1.0
+atan,-0x1.921fb54442d18p-1,-0x1.0p0,-1.0
+atan,-0x1.dac670561bb4fp-2,-0x1.0p-1,-0.5
+atan,0x1.dac670561bb4fp-2,0x1.0p-1,0.5
+atan,-0x1.69b8154baf42ep0,-0x1.921fb54442d18p2,-6.283185307179586
+atan,-0x1.67fe45e9cabc4p0,-0x1.815e630c155e1p2,-6.021385919380436
+atan,-0x1.661d6ceb7c4e6p0,-0x1.709d10d3e7eabp2,-5.759586531581287
+atan,-0x1.64102fc571c74p0,-0x1.5fdbbe9bba775p2,-5.497787143782138
+atan,-0x1.61d03090f6048p0,-0x1.4f1a6c638d03fp2,-5.235987755982989
+atan,-0x1.5f55ce92d0fd9p0,-0x1.3e591a2b5f908p2,-4.974188368183839
+atan,-0x1.5c97d37d98aa4p0,-0x1.2d97c7f3321d2p2,-4.71238898038469
+atan,-0x1.598b06657c521p0,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+atan,-0x1.56219a568d94cp0,-0x1.0c152382d7365p2,-4.1887902047863905
+atan,-0x1.524a69fcff2afp0,-0x1.f6a7a2955385dp1,-3.926990816987241
+atan,-0x1.4defeaff7c88p0,-0x1.d524fe24f89f1p1,-3.665191429188092
+atan,-0x1.48f6b941de94p0,-0x1.b3a259b49db85p1,-3.4033920413889427
+atan,-0x1.433b8a322ddd2p0,-0x1.921fb54442d18p1,-3.141592653589793
+atan,-0x1.3c903f4b32aaap0,-0x1.709d10d3e7eabp1,-2.8797932657906435
+atan,-0x1.34b7a85467ddcp0,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+atan,-0x1.2b5f4b53c7949p0,-0x1.2d97c7f3321d2p1,-2.356194490192345
+atan,-0x1.201634ac2828bp0,-0x1.0c152382d7365p1,-2.0943951023931953
+atan,-0x1.123f6ef47e0c2p0,-0x1.d524fe24f89f1p0,-1.832595714594046
+atan,-0x1.00fe987ed02ffp0,-0x1.921fb54442d18p0,-1.5707963267948966
+atan,-0x1.d63c8fb14e334p-1,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+atan,-0x1.9ded0009ac5adp-1,-0x1.0c152382d7365p0,-1.0471975511965976
+atan,-0x1.54e04c05d06ap-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+atan,-0x1.edec9c192bfaap-2,-0x1.0c152382d7365p-1,-0.5235987755982988
+atan,-0x1.0632b28478608p-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+atan,0x0.0p0,0x0.0p0,0.0
+atan,0x1.0632b28478608p-2,0x1.0c152382d7365p-2,0.2617993877991494
+atan,0x1.edec9c192bfaap-2,0x1.0c152382d7365p-1,0.5235987755982988
+atan,0x1.54e04c05d06ap-1,0x1.921fb54442d18p-1,0.7853981633974483
+atan,0x1.9ded0009ac5adp-1,0x1.0c152382d7365p0,1.0471975511965976
+atan,0x1.d63c8fb14e334p-1,0x1.4f1a6c638d03fp0,1.3089969389957472
+atan,0x1.00fe987ed02ffp0,0x1.921fb54442d18p0,1.5707963267948966
+atan,0x1.123f6ef47e0c2p0,0x1.d524fe24f89f1p0,1.832595714594046
+atan,0x1.201634ac2828bp0,0x1.0c152382d7365p1,2.0943951023931953
+atan,0x1.2b5f4b53c7949p0,0x1.2d97c7f3321d2p1,2.356194490192345
+atan,0x1.34b7a85467ddcp0,0x1.4f1a6c638d03fp1,2.6179938779914944
+atan,0x1.3c903f4b32aaap0,0x1.709d10d3e7eabp1,2.8797932657906435
+atan,0x1.433b8a322ddd2p0,0x1.921fb54442d18p1,3.141592653589793
+atan,0x1.48f6b941de94p0,0x1.b3a259b49db85p1,3.4033920413889427
+atan,0x1.4defeaff7c88p0,0x1.d524fe24f89f1p1,3.665191429188092
+atan,0x1.524a69fcff2afp0,0x1.f6a7a2955385dp1,3.926990816987241
+atan,0x1.56219a568d94cp0,0x1.0c152382d7365p2,4.1887902047863905
+atan,0x1.598b06657c521p0,0x1.1cd675bb04a9cp2,4.4505895925855405
+atan,0x1.5c97d37d98aa4p0,0x1.2d97c7f3321d2p2,4.71238898038469
+atan,0x1.5f55ce92d0fd9p0,0x1.3e591a2b5f908p2,4.974188368183839
+atan,0x1.61d03090f6048p0,0x1.4f1a6c638d03fp2,5.235987755982989
+atan,0x1.64102fc571c74p0,0x1.5fdbbe9bba775p2,5.497787143782138
+atan,0x1.661d6ceb7c4e6p0,0x1.709d10d3e7eabp2,5.759586531581287
+atan,0x1.67fe45e9cabc4p0,0x1.815e630c155e1p2,6.021385919380436
+atan,0x1.69b8154baf42ep0,0x1.921fb54442d18p2,6.283185307179586
+cos,-0x1.d2cec9a554007p-1,0x1.5bf0a8b145769p1,2.718281828459045
+cos,-0x1.d2cec9a554007p-1,-0x1.5bf0a8b145769p1,-2.718281828459045
+cos,0x1.0p0,0x0.0p0,0.0
+cos,0x1.0p0,-0x0.0p0,-0.0
+cos,0x1.14a280fb5068cp-1,0x1.0p0,1.0
+cos,0x1.14a280fb5068cp-1,-0x1.0p0,-1.0
+cos,0x1.c1528065b7d5p-1,-0x1.0p-1,-0.5
+cos,0x1.c1528065b7d5p-1,0x1.0p-1,0.5
+cos,0x1.0p0,-0x1.921fb54442d18p2,-6.283185307179586
+cos,0x1.ee8dd4748bf13p-1,-0x1.815e630c155e1p2,-6.021385919380436
+cos,0x1.bb67ae8584ca8p-1,-0x1.709d10d3e7eabp2,-5.759586531581287
+cos,0x1.6a09e667f3bcbp-1,-0x1.5fdbbe9bba775p2,-5.497787143782138
+cos,0x1.0000000000001p-1,-0x1.4f1a6c638d03fp2,-5.235987755982989
+cos,0x1.0907dc1930688p-2,-0x1.3e591a2b5f908p2,-4.974188368183839
+cos,-0x1.a79394c9e8a0ap-53,-0x1.2d97c7f3321d2p2,-4.71238898038469
+cos,-0x1.0907dc193068ep-2,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+cos,-0x1.0000000000004p-1,-0x1.0c152382d7365p2,-4.1887902047863905
+cos,-0x1.6a09e667f3bdp-1,-0x1.f6a7a2955385dp1,-3.926990816987241
+cos,-0x1.bb67ae8584cacp-1,-0x1.d524fe24f89f1p1,-3.665191429188092
+cos,-0x1.ee8dd4748bf15p-1,-0x1.b3a259b49db85p1,-3.4033920413889427
+cos,-0x1.0p0,-0x1.921fb54442d18p1,-3.141592653589793
+cos,-0x1.ee8dd4748bf14p-1,-0x1.709d10d3e7eabp1,-2.8797932657906435
+cos,-0x1.bb67ae8584cabp-1,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+cos,-0x1.6a09e667f3bccp-1,-0x1.2d97c7f3321d2p1,-2.356194490192345
+cos,-0x1.ffffffffffffcp-2,-0x1.0c152382d7365p1,-2.0943951023931953
+cos,-0x1.0907dc193068ep-2,-0x1.d524fe24f89f1p0,-1.832595714594046
+cos,0x1.1a62633145c07p-54,-0x1.921fb54442d18p0,-1.5707963267948966
+cos,0x1.0907dc193069p-2,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+cos,0x1.0000000000001p-1,-0x1.0c152382d7365p0,-1.0471975511965976
+cos,0x1.6a09e667f3bcdp-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+cos,0x1.bb67ae8584cabp-1,-0x1.0c152382d7365p-1,-0.5235987755982988
+cos,0x1.ee8dd4748bf15p-1,-0x1.0c152382d7365p-2,-0.2617993877991494
+cos,0x1.0p0,0x0.0p0,0.0
+cos,0x1.ee8dd4748bf15p-1,0x1.0c152382d7365p-2,0.2617993877991494
+cos,0x1.bb67ae8584cabp-1,0x1.0c152382d7365p-1,0.5235987755982988
+cos,0x1.6a09e667f3bcdp-1,0x1.921fb54442d18p-1,0.7853981633974483
+cos,0x1.0000000000001p-1,0x1.0c152382d7365p0,1.0471975511965976
+cos,0x1.0907dc193069p-2,0x1.4f1a6c638d03fp0,1.3089969389957472
+cos,0x1.1a62633145c07p-54,0x1.921fb54442d18p0,1.5707963267948966
+cos,-0x1.0907dc193068ep-2,0x1.d524fe24f89f1p0,1.832595714594046
+cos,-0x1.ffffffffffffcp-2,0x1.0c152382d7365p1,2.0943951023931953
+cos,-0x1.6a09e667f3bccp-1,0x1.2d97c7f3321d2p1,2.356194490192345
+cos,-0x1.bb67ae8584cabp-1,0x1.4f1a6c638d03fp1,2.6179938779914944
+cos,-0x1.ee8dd4748bf14p-1,0x1.709d10d3e7eabp1,2.8797932657906435
+cos,-0x1.0p0,0x1.921fb54442d18p1,3.141592653589793
+cos,-0x1.ee8dd4748bf15p-1,0x1.b3a259b49db85p1,3.4033920413889427
+cos,-0x1.bb67ae8584cacp-1,0x1.d524fe24f89f1p1,3.665191429188092
+cos,-0x1.6a09e667f3bdp-1,0x1.f6a7a2955385dp1,3.926990816987241
+cos,-0x1.0000000000004p-1,0x1.0c152382d7365p2,4.1887902047863905
+cos,-0x1.0907dc193068ep-2,0x1.1cd675bb04a9cp2,4.4505895925855405
+cos,-0x1.a79394c9e8a0ap-53,0x1.2d97c7f3321d2p2,4.71238898038469
+cos,0x1.0907dc1930688p-2,0x1.3e591a2b5f908p2,4.974188368183839
+cos,0x1.0000000000001p-1,0x1.4f1a6c638d03fp2,5.235987755982989
+cos,0x1.6a09e667f3bcbp-1,0x1.5fdbbe9bba775p2,5.497787143782138
+cos,0x1.bb67ae8584ca8p-1,0x1.709d10d3e7eabp2,5.759586531581287
+cos,0x1.ee8dd4748bf13p-1,0x1.815e630c155e1p2,6.021385919380436
+cos,0x1.0p0,0x1.921fb54442d18p2,6.283185307179586
+cosh,0x1.e70c4a4f41685p2,0x1.5bf0a8b145769p1,2.718281828459045
+cosh,0x1.e70c4a4f41685p2,-0x1.5bf0a8b145769p1,-2.718281828459045
+cosh,0x1.0p0,0x0.0p0,0.0
+cosh,0x1.0p0,-0x0.0p0,-0.0
+cosh,0x1.8b07551d9f551p0,0x1.0p0,1.0
+cosh,0x1.8b07551d9f551p0,-0x1.0p0,-1.0
+cosh,0x1.20ac1862ae8dp0,-0x1.0p-1,-0.5
+cosh,0x1.20ac1862ae8dp0,0x1.0p-1,0.5
+cosh,0x1.0bbf2bc2b69c6p8,-0x1.921fb54442d18p2,-6.283185307179586
+cosh,0x1.9c26de7a4c876p7,-0x1.815e630c155e1p2,-6.021385919380436
+cosh,0x1.3d38653fd9955p7,-0x1.709d10d3e7eabp2,-5.759586531581287
+cosh,0x1.e84f70f559672p6,-0x1.5fdbbe9bba775p2,-5.497787143782138
+cosh,0x1.77d703b1fef8ep6,-0x1.4f1a6c638d03fp2,-5.235987755982989
+cosh,0x1.2146cfce7a73dp6,-0x1.3e591a2b5f908p2,-4.974188368183839
+cosh,0x1.bd4e9aa3e9cdbp5,-0x1.2d97c7f3321d2p2,-4.71238898038469
+cosh,0x1.56c1a783ea3bcp5,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+cosh,0x1.07d51ffbc7ab2p5,-0x1.0c152382d7365p2,-4.1887902047863905
+cosh,0x1.9630955c947f2p4,-0x1.f6a7a2955385dp1,-3.926990816987241
+cosh,0x1.38b6b51cfc1f1p4,-0x1.d524fe24f89f1p1,-3.665191429188092
+cosh,0x1.e19635bf3b425p3,-0x1.b3a259b49db85p1,-3.4033920413889427
+cosh,0x1.72f147fee4p3,-0x1.921fb54442d18p1,-3.141592653589793
+cosh,0x1.1dde27bb3f2c8p3,-0x1.709d10d3e7eabp1,-2.8797932657906435
+cosh,0x1.b8ff233b92bd2p2,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+cosh,0x1.54a7f8a1b9b92p2,-0x1.2d97c7f3321d2p1,-2.356194490192345
+cosh,0x1.07cc2972b616ep2,-0x1.0c152382d7365p1,-2.0943951023931953
+cosh,0x1.9a3edca811aeep1,-0x1.d524fe24f89f1p0,-1.832595714594046
+cosh,0x1.412cc2a8d4e9ep1,-0x1.921fb54442d18p0,-1.5707963267948966
+cosh,0x1.fc7c7b72ba27ep0,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+cosh,0x1.99ac66460ce4p0,-0x1.0c152382d7365p0,-1.0471975511965976
+cosh,0x1.531994ce525b9p0,-0x1.921fb54442d18p-1,-0.7853981633974483
+cosh,0x1.23e6a89aab514p0,-0x1.0c152382d7365p-1,-0.5235987755982988
+cosh,0x1.08d2bd7d0bc1bp0,-0x1.0c152382d7365p-2,-0.2617993877991494
+cosh,0x1.0p0,0x0.0p0,0.0
+cosh,0x1.08d2bd7d0bc1bp0,0x1.0c152382d7365p-2,0.2617993877991494
+cosh,0x1.23e6a89aab514p0,0x1.0c152382d7365p-1,0.5235987755982988
+cosh,0x1.531994ce525b9p0,0x1.921fb54442d18p-1,0.7853981633974483
+cosh,0x1.99ac66460ce4p0,0x1.0c152382d7365p0,1.0471975511965976
+cosh,0x1.fc7c7b72ba27ep0,0x1.4f1a6c638d03fp0,1.3089969389957472
+cosh,0x1.412cc2a8d4e9ep1,0x1.921fb54442d18p0,1.5707963267948966
+cosh,0x1.9a3edca811aeep1,0x1.d524fe24f89f1p0,1.832595714594046
+cosh,0x1.07cc2972b616ep2,0x1.0c152382d7365p1,2.0943951023931953
+cosh,0x1.54a7f8a1b9b92p2,0x1.2d97c7f3321d2p1,2.356194490192345
+cosh,0x1.b8ff233b92bd2p2,0x1.4f1a6c638d03fp1,2.6179938779914944
+cosh,0x1.1dde27bb3f2c8p3,0x1.709d10d3e7eabp1,2.8797932657906435
+cosh,0x1.72f147fee4p3,0x1.921fb54442d18p1,3.141592653589793
+cosh,0x1.e19635bf3b425p3,0x1.b3a259b49db85p1,3.4033920413889427
+cosh,0x1.38b6b51cfc1f1p4,0x1.d524fe24f89f1p1,3.665191429188092
+cosh,0x1.9630955c947f2p4,0x1.f6a7a2955385dp1,3.926990816987241
+cosh,0x1.07d51ffbc7ab2p5,0x1.0c152382d7365p2,4.1887902047863905
+cosh,0x1.56c1a783ea3bcp5,0x1.1cd675bb04a9cp2,4.4505895925855405
+cosh,0x1.bd4e9aa3e9cdbp5,0x1.2d97c7f3321d2p2,4.71238898038469
+cosh,0x1.2146cfce7a73dp6,0x1.3e591a2b5f908p2,4.974188368183839
+cosh,0x1.77d703b1fef8ep6,0x1.4f1a6c638d03fp2,5.235987755982989
+cosh,0x1.e84f70f559672p6,0x1.5fdbbe9bba775p2,5.497787143782138
+cosh,0x1.3d38653fd9955p7,0x1.709d10d3e7eabp2,5.759586531581287
+cosh,0x1.9c26de7a4c876p7,0x1.815e630c155e1p2,6.021385919380436
+cosh,0x1.0bbf2bc2b69c6p8,0x1.921fb54442d18p2,6.283185307179586
+exp,0x1.e4efb75e4527ap3,0x1.5bf0a8b145769p1,2.718281828459045
+exp,0x1.0e49787e20548p-4,-0x1.5bf0a8b145769p1,-2.718281828459045
+exp,0x1.0p0,0x0.0p0,0.0
+exp,0x1.0p0,-0x0.0p0,-0.0
+exp,0x1.5bf0a8b14576ap1,0x1.0p0,1.0
+exp,0x1.78b56362cef38p-2,-0x1.0p0,-1.0
+exp,0x1.368b2fc6f960ap-1,-0x1.0p-1,-0.5
+exp,0x1.a61298e1e069cp0,0x1.0p-1,0.5
+exp,0x1.e989f5d6dff5ep-10,-0x1.921fb54442d18p2,-6.283185307179586
+exp,0x1.3e0545d310facp-9,-0x1.815e630c155e1p2,-6.021385919380436
+exp,0x1.9d317c88e8c75p-9,-0x1.709d10d3e7eabp2,-5.759586531581287
+exp,0x1.0c6c89f32cf3bp-8,-0x1.5fdbbe9bba775p2,-5.497787143782138
+exp,0x1.5cc10db1e9ap-8,-0x1.4f1a6c638d03fp2,-5.235987755982989
+exp,0x1.c51fd34fff925p-8,-0x1.3e591a2b5f908p2,-4.974188368183839
+exp,0x1.265d4e92b6b9cp-7,-0x1.2d97c7f3321d2p2,-4.71238898038469
+exp,0x1.7e752d40d9f68p-7,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+exp,0x1.f0ea0d2fef998p-7,-0x1.0c152382d7365p2,-4.1887902047863905
+exp,0x1.42cfd6c758445p-6,-0x1.f6a7a2955385dp1,-3.926990816987241
+exp,0x1.a36b1f41cd0d4p-6,-0x1.d524fe24f89f1p1,-3.665191429188092
+exp,0x1.1077d12ac7f27p-5,-0x1.b3a259b49db85p1,-3.4033920413889427
+exp,0x1.620227b598efap-5,-0x1.921fb54442d18p1,-3.141592653589793
+exp,0x1.cbf37855eeab7p-5,-0x1.709d10d3e7eabp1,-2.8797932657906435
+exp,0x1.2acca269f2ff5p-4,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+exp,0x1.843844e012c48p-4,-0x1.2d97c7f3321d2p1,-2.356194490192345
+exp,0x1.f86696ab8ba32p-4,-0x1.0c152382d7365p1,-2.0943951023931953
+exp,0x1.47ace27295d4bp-3,-0x1.d524fe24f89f1p0,-1.832595714594046
+exp,0x1.a9bcc46f767ep-3,-0x1.921fb54442d18p0,-1.5707963267948966
+exp,0x1.1492b1531c763p-2,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+exp,0x1.6757859d664c8p-2,-0x1.0c152382d7365p0,-1.0471975511965976
+exp,0x1.d2e171cf04879p-2,-0x1.921fb54442d18p-1,-0.7853981633974483
+exp,0x1.2f4d1112a3e2ap-1,-0x1.0c152382d7365p-1,-0.5235987755982988
+exp,0x1.8a1195bf0aa84p-1,-0x1.0c152382d7365p-2,-0.2617993877991494
+exp,0x1.0p0,0x0.0p0,0.0
+exp,0x1.4c9cb01a922f4p0,0x1.0c152382d7365p-2,0.2617993877991494
+exp,0x1.b026c8ac04b14p0,0x1.0c152382d7365p-1,0.5235987755982988
+exp,0x1.18bd669471caap1,0x1.921fb54442d18p-1,0.7853981633974483
+exp,0x1.6cc17592601a7p1,0x1.0c152382d7365p0,1.0471975511965976
+exp,0x1.d9ea254856992p1,0x1.4f1a6c638d03fp0,1.3089969389957472
+exp,0x1.33dedc855935fp2,0x1.921fb54442d18p0,1.5707963267948966
+exp,0x1.900175947d004p2,0x1.d524fe24f89f1p0,1.832595714594046
+exp,0x1.03db5c455effap3,0x1.0c152382d7365p1,2.0943951023931953
+exp,0x1.519f8817f9939p3,0x1.2d97c7f3321d2p1,2.356194490192345
+exp,0x1.b6a989f6bed72p3,0x1.4f1a6c638d03fp1,2.6179938779914944
+exp,0x1.1cf82dff14353p4,0x1.709d10d3e7eabp1,2.8797932657906435
+exp,0x1.724046eb09339p4,0x1.921fb54442d18p1,3.141592653589793
+exp,0x1.e10df9d6a5de5p4,0x1.b3a259b49db85p1,3.4033920413889427
+exp,0x1.388247b913e57p5,0x1.d524fe24f89f1p1,3.665191429188092
+exp,0x1.96083b61bb941p5,0x1.f6a7a2955385dp1,3.926990816987241
+exp,0x1.07c598ab5e2bap6,0x1.0c152382d7365p2,4.1887902047863905
+exp,0x1.56b5b3da8034fp6,0x1.1cd675bb04a9cp2,4.4505895925855405
+exp,0x1.bd4567b97538p6,0x1.2d97c7f3321d2p2,4.71238898038469
+exp,0x1.2143458ed3d3dp7,0x1.3e591a2b5f908p2,4.974188368183839
+exp,0x1.77d44a2fe3951p7,0x1.4f1a6c638d03fp2,5.235987755982989
+exp,0x1.e84d581c4580cp7,0x1.5fdbbe9bba775p2,5.497787143782138
+exp,0x1.3d3796a71b50ep8,0x1.709d10d3e7eabp2,5.759586531581287
+exp,0x1.9c263f77a99ddp8,0x1.815e630c155e1p2,6.021385919380436
+exp,0x1.0bbeee9177e18p9,0x1.921fb54442d18p2,6.283185307179586
+log,0x1.0p0,0x1.5bf0a8b145769p1,2.718281828459045
+log,0x0.0p0,0x1.0p0,1.0
+log,-0x1.62e42fefa39efp-1,0x1.0p-1,0.5
+log,-0x1.5715d30bf9b3dp0,0x1.0c152382d7365p-2,0.2617993877991494
+log,-0x1.4b4776284fc8bp-1,0x1.0c152382d7365p-1,0.5235987755982988
+log,-0x1.eeb95b094c193p-3,0x1.921fb54442d18p-1,0.7853981633974483
+log,0x1.79cb9c753d63fp-5,0x1.0c152382d7365p0,1.0471975511965976
+log,0x1.13b931cb7c7dbp-2,0x1.4f1a6c638d03fp0,1.3089969389957472
+log,0x1.ce6bb25aa1315p-2,0x1.921fb54442d18p0,1.5707963267948966
+log,0x1.3622afae57e34p-1,0x1.d524fe24f89f1p0,1.832595714594046
+log,0x1.7a80e9b6f7753p-1,0x1.0c152382d7365p1,2.0943951023931953
+log,0x1.b6cef8934d5bp-1,0x1.2d97c7f3321d2p1,2.356194490192345
+log,0x1.ecc0c8d561dddp-1,0x1.4f1a6c638d03fp1,2.6179938779914944
+log,0x1.0ec6a3e3ed35ap0,0x1.709d10d3e7eabp1,2.8797932657906435
+log,0x1.250d048e7a1bdp0,0x1.921fb54442d18p1,3.141592653589793
+log,0x1.398ab25a37d65p0,0x1.b3a259b49db85p1,3.4033920413889427
+log,0x1.4c836fcefdc12p0,0x1.d524fe24f89f1p1,3.665191429188092
+log,0x1.5e2cf41daf501p0,0x1.f6a7a2955385dp1,3.926990816987241
+log,0x1.6eb28cd34d8a1p0,0x1.0c152382d7365p2,4.1887902047863905
+log,0x1.7e37a533563b7p0,0x1.1cd675bb04a9cp2,4.4505895925855405
+log,0x1.8cd99441787dp0,0x1.2d97c7f3321d2p2,4.71238898038469
+log,0x1.9ab0edb49cb1cp0,0x1.3e591a2b5f908p2,4.974188368183839
+log,0x1.a7d27c6282be6p0,0x1.4f1a6c638d03fp2,5.235987755982989
+log,0x1.b44fff81fc225p0,0x1.5fdbbe9bba775p2,5.497787143782138
+log,0x1.c038bbdbbf052p0,0x1.709d10d3e7eabp2,5.759586531581287
+log,0x1.cb99ecae3cca3p0,0x1.815e630c155e1p2,6.021385919380436
+log,0x1.d67f1c864beb4p0,0x1.921fb54442d18p2,6.283185307179586
+log10,0x1.bcb7b1526e50ep-2,0x1.5bf0a8b145769p1,2.718281828459045
+log10,0x0.0p0,0x1.0p0,1.0
+log10,-0x1.34413509f79ffp-2,0x1.0p-1,0.5
+log10,-0x1.2a0004239932p-1,0x1.0c152382d7365p-2,0.2617993877991494
+log10,-0x1.1fbed33d3ac41p-2,0x1.0c152382d7365p-1,0.5235987755982988
+log10,-0x1.adb63b88d410dp-4,0x1.921fb54442d18p-1,0.7853981633974483
+log10,0x1.48261ccbcdbd2p-6,0x1.0c152382d7365p0,1.0471975511965976
+log10,0x1.defb0abb57f05p-4,0x1.4f1a6c638d03fp0,1.3089969389957472
+log10,0x1.91a74c4f85377p-3,0x1.921fb54442d18p0,1.5707963267948966
+log10,0x1.0d615927e723dp-2,0x1.d524fe24f89f1p0,1.832595714594046
+log10,0x1.48c396d6b47bcp-2,0x1.0c152382d7365p1,2.0943951023931953
+log10,0x1.7d24ea82c85bap-2,0x1.2d97c7f3321d2p1,2.356194490192345
+log10,0x1.abfff7b8cd9cp-2,0x1.4f1a6c638d03fp1,2.6179938779914944
+log10,0x1.d662cfccfef7ap-2,0x1.709d10d3e7eabp1,2.8797932657906435
+log10,0x1.fd14db31ba3bap-2,0x1.921fb54442d18p1,3.141592653589793
+log10,0x1.1056c453e917ep-1,0x1.b3a259b49db85p1,3.4033920413889427
+log10,0x1.20d14718ef61ep-1,0x1.d524fe24f89f1p1,3.665191429188092
+log10,0x1.30289e09e9adep-1,0x1.f6a7a2955385dp1,3.926990816987241
+log10,0x1.3e8265f0560dep-1,0x1.0c152382d7365p2,4.1887902047863905
+log10,0x1.4bfd6285d680ep-1,0x1.1cd675bb04a9cp2,4.4505895925855405
+log10,0x1.58b30fc65ffdcp-1,0x1.2d97c7f3321d2p2,4.71238898038469
+log10,0x1.64b8c69bdef01p-1,0x1.3e591a2b5f908p2,4.974188368183839
+log10,0x1.70209661629ep-1,0x1.4f1a6c638d03fp2,5.235987755982989
+log10,0x1.7af9e9467241ep-1,0x1.5fdbbe9bba775p2,5.497787143782138
+log10,0x1.8552026b7b4bcp-1,0x1.709d10d3e7eabp2,5.759586531581287
+log10,0x1.8f345fefe5fdep-1,0x1.815e630c155e1p2,6.021385919380436
+log10,0x1.98ab081dd8eddp-1,0x1.921fb54442d18p2,6.283185307179586
+sin,0x1.a4a3d9c2131dfp-2,0x1.5bf0a8b145769p1,2.718281828459045
+sin,-0x1.a4a3d9c2131dfp-2,-0x1.5bf0a8b145769p1,-2.718281828459045
+sin,0x0.0p0,0x0.0p0,0.0
+sin,-0x0.0p0,-0x0.0p0,-0.0
+sin,0x1.aed548f090ceep-1,0x1.0p0,1.0
+sin,-0x1.aed548f090ceep-1,-0x1.0p0,-1.0
+sin,-0x1.eaee8744b05fp-2,-0x1.0p-1,-0.5
+sin,0x1.eaee8744b05fp-2,0x1.0p-1,0.5
+sin,0x1.1a62633145c07p-52,-0x1.921fb54442d18p2,-6.283185307179586
+sin,0x1.0907dc193069fp-2,-0x1.815e630c155e1p2,-6.021385919380436
+sin,0x1.0000000000004p-1,-0x1.709d10d3e7eabp2,-5.759586531581287
+sin,0x1.6a09e667f3bcep-1,-0x1.5fdbbe9bba775p2,-5.497787143782138
+sin,0x1.bb67ae8584caap-1,-0x1.4f1a6c638d03fp2,-5.235987755982989
+sin,0x1.ee8dd4748bf16p-1,-0x1.3e591a2b5f908p2,-4.974188368183839
+sin,0x1.0p0,-0x1.2d97c7f3321d2p2,-4.71238898038469
+sin,0x1.ee8dd4748bf15p-1,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+sin,0x1.bb67ae8584ca9p-1,-0x1.0c152382d7365p2,-4.1887902047863905
+sin,0x1.6a09e667f3bc9p-1,-0x1.f6a7a2955385dp1,-3.926990816987241
+sin,0x1.ffffffffffffbp-2,-0x1.d524fe24f89f1p1,-3.665191429188092
+sin,0x1.0907dc1930691p-2,-0x1.b3a259b49db85p1,-3.4033920413889427
+sin,-0x1.1a62633145c07p-53,-0x1.921fb54442d18p1,-3.141592653589793
+sin,-0x1.0907dc1930695p-2,-0x1.709d10d3e7eabp1,-2.8797932657906435
+sin,-0x1.fffffffffffffp-2,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+sin,-0x1.6a09e667f3bcdp-1,-0x1.2d97c7f3321d2p1,-2.356194490192345
+sin,-0x1.bb67ae8584cabp-1,-0x1.0c152382d7365p1,-2.0943951023931953
+sin,-0x1.ee8dd4748bf15p-1,-0x1.d524fe24f89f1p0,-1.832595714594046
+sin,-0x1.0p0,-0x1.921fb54442d18p0,-1.5707963267948966
+sin,-0x1.ee8dd4748bf15p-1,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+sin,-0x1.bb67ae8584caap-1,-0x1.0c152382d7365p0,-1.0471975511965976
+sin,-0x1.6a09e667f3bccp-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+sin,-0x1.fffffffffffffp-2,-0x1.0c152382d7365p-1,-0.5235987755982988
+sin,-0x1.0907dc193069p-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+sin,0x0.0p0,0x0.0p0,0.0
+sin,0x1.0907dc193069p-2,0x1.0c152382d7365p-2,0.2617993877991494
+sin,0x1.fffffffffffffp-2,0x1.0c152382d7365p-1,0.5235987755982988
+sin,0x1.6a09e667f3bccp-1,0x1.921fb54442d18p-1,0.7853981633974483
+sin,0x1.bb67ae8584caap-1,0x1.0c152382d7365p0,1.0471975511965976
+sin,0x1.ee8dd4748bf15p-1,0x1.4f1a6c638d03fp0,1.3089969389957472
+sin,0x1.0p0,0x1.921fb54442d18p0,1.5707963267948966
+sin,0x1.ee8dd4748bf15p-1,0x1.d524fe24f89f1p0,1.832595714594046
+sin,0x1.bb67ae8584cabp-1,0x1.0c152382d7365p1,2.0943951023931953
+sin,0x1.6a09e667f3bcdp-1,0x1.2d97c7f3321d2p1,2.356194490192345
+sin,0x1.fffffffffffffp-2,0x1.4f1a6c638d03fp1,2.6179938779914944
+sin,0x1.0907dc1930695p-2,0x1.709d10d3e7eabp1,2.8797932657906435
+sin,0x1.1a62633145c07p-53,0x1.921fb54442d18p1,3.141592653589793
+sin,-0x1.0907dc1930691p-2,0x1.b3a259b49db85p1,3.4033920413889427
+sin,-0x1.ffffffffffffbp-2,0x1.d524fe24f89f1p1,3.665191429188092
+sin,-0x1.6a09e667f3bc9p-1,0x1.f6a7a2955385dp1,3.926990816987241
+sin,-0x1.bb67ae8584ca9p-1,0x1.0c152382d7365p2,4.1887902047863905
+sin,-0x1.ee8dd4748bf15p-1,0x1.1cd675bb04a9cp2,4.4505895925855405
+sin,-0x1.0p0,0x1.2d97c7f3321d2p2,4.71238898038469
+sin,-0x1.ee8dd4748bf16p-1,0x1.3e591a2b5f908p2,4.974188368183839
+sin,-0x1.bb67ae8584caap-1,0x1.4f1a6c638d03fp2,5.235987755982989
+sin,-0x1.6a09e667f3bcep-1,0x1.5fdbbe9bba775p2,5.497787143782138
+sin,-0x1.0000000000004p-1,0x1.709d10d3e7eabp2,5.759586531581287
+sin,-0x1.0907dc193069fp-2,0x1.815e630c155e1p2,6.021385919380436
+sin,-0x1.1a62633145c07p-52,0x1.921fb54442d18p2,6.283185307179586
+sinh,0x1.e2d3246d48e6fp2,0x1.5bf0a8b145769p1,2.718281828459045
+sinh,-0x1.e2d3246d48e6fp2,-0x1.5bf0a8b145769p1,-2.718281828459045
+sinh,0x0.0p0,0x0.0p0,0.0
+sinh,-0x0.0p0,-0x0.0p0,-0.0
+sinh,0x1.2cd9fc44eb982p0,0x1.0p0,1.0
+sinh,-0x1.2cd9fc44eb982p0,-0x1.0p0,-1.0
+sinh,-0x1.0acd00fe63b97p-1,-0x1.0p-1,-0.5
+sinh,0x1.0acd00fe63b97p-1,0x1.0p-1,0.5
+sinh,-0x1.0bbeb1603926ap8,-0x1.921fb54442d18p2,-6.283185307179586
+sinh,-0x1.9c25a07506b44p7,-0x1.815e630c155e1p2,-6.021385919380436
+sinh,-0x1.3d36c80e5d0c7p7,-0x1.709d10d3e7eabp2,-5.759586531581287
+sinh,-0x1.e84b3f43319a6p6,-0x1.5fdbbe9bba775p2,-5.497787143782138
+sinh,-0x1.77d190adc8314p6,-0x1.4f1a6c638d03fp2,-5.235987755982989
+sinh,-0x1.213fbb4f2d33dp6,-0x1.3e591a2b5f908p2,-4.974188368183839
+sinh,-0x1.bd3c34cf00a25p5,-0x1.2d97c7f3321d2p2,-4.71238898038469
+sinh,-0x1.56a9c031162e2p5,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+sinh,-0x1.07b6115af4ac2p5,-0x1.0c152382d7365p2,-4.1887902047863905
+sinh,-0x1.95dfe166e2a9p4,-0x1.f6a7a2955385dp1,-3.926990816987241
+sinh,-0x1.384dda552babdp4,-0x1.d524fe24f89f1p1,-3.665191429188092
+sinh,-0x1.e085bdee107a5p3,-0x1.b3a259b49db85p1,-3.4033920413889427
+sinh,-0x1.718f45d72e672p3,-0x1.921fb54442d18p1,-3.141592653589793
+sinh,-0x1.1c123442e93dep3,-0x1.709d10d3e7eabp1,-2.8797932657906435
+sinh,-0x1.b453f0b1eaf12p2,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+sinh,-0x1.4e97178e396ep2,-0x1.2d97c7f3321d2p1,-2.356194490192345
+sinh,-0x1.ffd51e300fd0ap1,-0x1.0c152382d7365p1,-2.0943951023931953
+sinh,-0x1.85c40e80e851ap1,-0x1.d524fe24f89f1p0,-1.832595714594046
+sinh,-0x1.2690f661dd82p1,-0x1.921fb54442d18p0,-1.5707963267948966
+sinh,-0x1.b757cf1df30a6p0,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+sinh,-0x1.3fd684deb350ep0,-0x1.0c152382d7365p0,-1.0471975511965976
+sinh,-0x1.bcc270b522736p-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+sinh,-0x1.18804022b2bffp-1,-0x1.0c152382d7365p-1,-0.5235987755982988
+sinh,-0x1.0f27ca7619b64p-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+sinh,0x0.0p0,0x0.0p0,0.0
+sinh,0x1.0f27ca7619b64p-2,0x1.0c152382d7365p-2,0.2617993877991494
+sinh,0x1.18804022b2bffp-1,0x1.0c152382d7365p-1,0.5235987755982988
+sinh,0x1.bcc270b522736p-1,0x1.921fb54442d18p-1,0.7853981633974483
+sinh,0x1.3fd684deb350ep0,0x1.0c152382d7365p0,1.0471975511965976
+sinh,0x1.b757cf1df30a6p0,0x1.4f1a6c638d03fp0,1.3089969389957472
+sinh,0x1.2690f661dd82p1,0x1.921fb54442d18p0,1.5707963267948966
+sinh,0x1.85c40e80e851ap1,0x1.d524fe24f89f1p0,1.832595714594046
+sinh,0x1.ffd51e300fd0ap1,0x1.0c152382d7365p1,2.0943951023931953
+sinh,0x1.4e97178e396ep2,0x1.2d97c7f3321d2p1,2.356194490192345
+sinh,0x1.b453f0b1eaf12p2,0x1.4f1a6c638d03fp1,2.6179938779914944
+sinh,0x1.1c123442e93dep3,0x1.709d10d3e7eabp1,2.8797932657906435
+sinh,0x1.718f45d72e672p3,0x1.921fb54442d18p1,3.141592653589793
+sinh,0x1.e085bdee107a5p3,0x1.b3a259b49db85p1,3.4033920413889427
+sinh,0x1.384dda552babdp4,0x1.d524fe24f89f1p1,3.665191429188092
+sinh,0x1.95dfe166e2a9p4,0x1.f6a7a2955385dp1,3.926990816987241
+sinh,0x1.07b6115af4ac2p5,0x1.0c152382d7365p2,4.1887902047863905
+sinh,0x1.56a9c031162e2p5,0x1.1cd675bb04a9cp2,4.4505895925855405
+sinh,0x1.bd3c34cf00a25p5,0x1.2d97c7f3321d2p2,4.71238898038469
+sinh,0x1.213fbb4f2d33dp6,0x1.3e591a2b5f908p2,4.974188368183839
+sinh,0x1.77d190adc8314p6,0x1.4f1a6c638d03fp2,5.235987755982989
+sinh,0x1.e84b3f43319a6p6,0x1.5fdbbe9bba775p2,5.497787143782138
+sinh,0x1.3d36c80e5d0c7p7,0x1.709d10d3e7eabp2,5.759586531581287
+sinh,0x1.9c25a07506b44p7,0x1.815e630c155e1p2,6.021385919380436
+sinh,0x1.0bbeb1603926ap8,0x1.921fb54442d18p2,6.283185307179586
+sqrt,0x1.a61298e1e069cp0,0x1.5bf0a8b145769p1,2.718281828459045
+sqrt,0x0.0p0,0x0.0p0,0.0
+sqrt,-0x0.0p0,-0x0.0p0,-0.0
+sqrt,0x1.0p0,0x1.0p0,1.0
+sqrt,0x1.6a09e667f3bcdp-1,0x1.0p-1,0.5
+sqrt,0x0.0p0,0x0.0p0,0.0
+sqrt,0x1.05f8bd37c0e62p-1,0x1.0c152382d7365p-2,0.2617993877991494
+sqrt,0x1.727bdd17583bbp-1,0x1.0c152382d7365p-1,0.5235987755982988
+sqrt,0x1.c5bf891b4ef6ap-1,0x1.921fb54442d18p-1,0.7853981633974483
+sqrt,0x1.05f8bd37c0e62p0,0x1.0c152382d7365p0,1.0471975511965976
+sqrt,0x1.24e4a86554ee4p0,0x1.4f1a6c638d03fp0,1.3089969389957472
+sqrt,0x1.40d931ff62705p0,0x1.921fb54442d18p0,1.5707963267948966
+sqrt,0x1.5a8e4f8ccf0dcp0,0x1.d524fe24f89f1p0,1.832595714594046
+sqrt,0x1.727bdd17583bbp0,0x1.0c152382d7365p1,2.0943951023931953
+sqrt,0x1.88f51bd3a1593p0,0x1.2d97c7f3321d2p1,2.356194490192345
+sqrt,0x1.9e36a9c593d0bp0,0x1.4f1a6c638d03fp1,2.6179938779914944
+sqrt,0x1.b26e49c64a5f3p0,0x1.709d10d3e7eabp1,2.8797932657906435
+sqrt,0x1.c5bf891b4ef6ap0,0x1.921fb54442d18p1,3.141592653589793
+sqrt,0x1.d846ad8819ddap0,0x1.b3a259b49db85p1,3.4033920413889427
+sqrt,0x1.ea1aa3667d6bep0,0x1.d524fe24f89f1p1,3.665191429188092
+sqrt,0x1.fb4e4f1347eb8p0,0x1.f6a7a2955385dp1,3.926990816987241
+sqrt,0x1.05f8bd37c0e62p1,0x1.0c152382d7365p2,4.1887902047863905
+sqrt,0x1.0e08c0345b894p1,0x1.1cd675bb04a9cp2,4.4505895925855405
+sqrt,0x1.15dce5d1822ccp1,0x1.2d97c7f3321d2p2,4.71238898038469
+sqrt,0x1.1d7a1aea4fad7p1,0x1.3e591a2b5f908p2,4.974188368183839
+sqrt,0x1.24e4a86554ee4p1,0x1.4f1a6c638d03fp2,5.235987755982989
+sqrt,0x1.2c204f9612dc7p1,0x1.5fdbbe9bba775p2,5.497787143782138
+sqrt,0x1.333060993db51p1,0x1.709d10d3e7eabp2,5.759586531581287
+sqrt,0x1.3a17cc297b8dcp1,0x1.815e630c155e1p2,6.021385919380436
+sqrt,0x1.40d931ff62705p1,0x1.921fb54442d18p2,6.283185307179586
+tan,-0x1.cd5cdb683b402p-2,0x1.5bf0a8b145769p1,2.718281828459045
+tan,0x1.cd5cdb683b402p-2,-0x1.5bf0a8b145769p1,-2.718281828459045
+tan,0x0.0p0,0x0.0p0,0.0
+tan,-0x0.0p0,-0x0.0p0,-0.0
+tan,0x1.8eb245cbee3a6p0,0x1.0p0,1.0
+tan,-0x1.8eb245cbee3a6p0,-0x1.0p0,-1.0
+tan,-0x1.17b4f5bf3474ap-1,-0x1.0p-1,-0.5
+tan,0x1.17b4f5bf3474ap-1,0x1.0p-1,0.5
+tan,0x1.1a62633145c07p-52,-0x1.921fb54442d18p2,-6.283185307179586
+tan,0x1.126145e9ecd66p-2,-0x1.815e630c155e1p2,-6.021385919380436
+tan,0x1.279a745903322p-1,-0x1.709d10d3e7eabp2,-5.759586531581287
+tan,0x1.0000000000002p0,-0x1.5fdbbe9bba775p2,-5.497787143782138
+tan,0x1.bb67ae8584ca9p0,-0x1.4f1a6c638d03fp2,-5.235987755982989
+tan,0x1.ddb3d742c2666p1,-0x1.3e591a2b5f908p2,-4.974188368183839
+tan,-0x1.3570efd768923p52,-0x1.2d97c7f3321d2p2,-4.71238898038469
+tan,-0x1.ddb3d742c2659p1,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+tan,-0x1.bb67ae8584ca2p0,-0x1.0c152382d7365p2,-4.1887902047863905
+tan,-0x1.ffffffffffff5p-1,-0x1.f6a7a2955385dp1,-3.926990816987241
+tan,-0x1.279a745903319p-1,-0x1.d524fe24f89f1p1,-3.665191429188092
+tan,-0x1.126145e9ecd56p-2,-0x1.b3a259b49db85p1,-3.4033920413889427
+tan,0x1.1a62633145c07p-53,-0x1.921fb54442d18p1,-3.141592653589793
+tan,0x1.126145e9ecd5bp-2,-0x1.709d10d3e7eabp1,-2.8797932657906435
+tan,0x1.279a74590331cp-1,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+tan,0x1.0000000000001p0,-0x1.2d97c7f3321d2p1,-2.356194490192345
+tan,0x1.bb67ae8584cafp0,-0x1.0c152382d7365p1,-2.0943951023931953
+tan,0x1.ddb3d742c265ap1,-0x1.d524fe24f89f1p0,-1.832595714594046
+tan,-0x1.d02967c31cdb5p53,-0x1.921fb54442d18p0,-1.5707963267948966
+tan,-0x1.ddb3d742c2656p1,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+tan,-0x1.bb67ae8584ca8p0,-0x1.0c152382d7365p0,-1.0471975511965976
+tan,-0x1.fffffffffffffp-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+tan,-0x1.279a74590331cp-1,-0x1.0c152382d7365p-1,-0.5235987755982988
+tan,-0x1.126145e9ecd56p-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+tan,0x0.0p0,0x0.0p0,0.0
+tan,0x1.126145e9ecd56p-2,0x1.0c152382d7365p-2,0.2617993877991494
+tan,0x1.279a74590331cp-1,0x1.0c152382d7365p-1,0.5235987755982988
+tan,0x1.fffffffffffffp-1,0x1.921fb54442d18p-1,0.7853981633974483
+tan,0x1.bb67ae8584ca8p0,0x1.0c152382d7365p0,1.0471975511965976
+tan,0x1.ddb3d742c2656p1,0x1.4f1a6c638d03fp0,1.3089969389957472
+tan,0x1.d02967c31cdb5p53,0x1.921fb54442d18p0,1.5707963267948966
+tan,-0x1.ddb3d742c265ap1,0x1.d524fe24f89f1p0,1.832595714594046
+tan,-0x1.bb67ae8584cafp0,0x1.0c152382d7365p1,2.0943951023931953
+tan,-0x1.0000000000001p0,0x1.2d97c7f3321d2p1,2.356194490192345
+tan,-0x1.279a74590331cp-1,0x1.4f1a6c638d03fp1,2.6179938779914944
+tan,-0x1.126145e9ecd5bp-2,0x1.709d10d3e7eabp1,2.8797932657906435
+tan,-0x1.1a62633145c07p-53,0x1.921fb54442d18p1,3.141592653589793
+tan,0x1.126145e9ecd56p-2,0x1.b3a259b49db85p1,3.4033920413889427
+tan,0x1.279a745903319p-1,0x1.d524fe24f89f1p1,3.665191429188092
+tan,0x1.ffffffffffff5p-1,0x1.f6a7a2955385dp1,3.926990816987241
+tan,0x1.bb67ae8584ca2p0,0x1.0c152382d7365p2,4.1887902047863905
+tan,0x1.ddb3d742c2659p1,0x1.1cd675bb04a9cp2,4.4505895925855405
+tan,0x1.3570efd768923p52,0x1.2d97c7f3321d2p2,4.71238898038469
+tan,-0x1.ddb3d742c2666p1,0x1.3e591a2b5f908p2,4.974188368183839
+tan,-0x1.bb67ae8584ca9p0,0x1.4f1a6c638d03fp2,5.235987755982989
+tan,-0x1.0000000000002p0,0x1.5fdbbe9bba775p2,5.497787143782138
+tan,-0x1.279a745903322p-1,0x1.709d10d3e7eabp2,5.759586531581287
+tan,-0x1.126145e9ecd66p-2,0x1.815e630c155e1p2,6.021385919380436
+tan,-0x1.1a62633145c07p-52,0x1.921fb54442d18p2,6.283185307179586
+tanh,0x1.fb8f76b1e2ab6p-1,0x1.5bf0a8b145769p1,2.718281828459045
+tanh,-0x1.fb8f76b1e2ab6p-1,-0x1.5bf0a8b145769p1,-2.718281828459045
+tanh,0x0.0p0,0x0.0p0,0.0
+tanh,-0x0.0p0,-0x0.0p0,-0.0
+tanh,0x1.85efab514f394p-1,0x1.0p0,1.0
+tanh,-0x1.85efab514f394p-1,-0x1.0p0,-1.0
+tanh,-0x1.d9353d7568af3p-2,-0x1.0p-1,-0.5
+tanh,0x1.d9353d7568af3p-2,0x1.0p-1,0.5
+tanh,-0x1.ffff15f81f9abp-1,-0x1.921fb54442d18p2,-6.283185307179586
+tanh,-0x1.fffe74ef7ed71p-1,-0x1.815e630c155e1p2,-6.021385919380436
+tanh,-0x1.fffd6518fcf42p-1,-0x1.709d10d3e7eabp2,-5.759586531581287
+tanh,-0x1.fffb9a371a4ddp-1,-0x1.5fdbbe9bba775p2,-5.497787143782138
+tanh,-0x1.fff893980bbap-1,-0x1.4f1a6c638d03fp2,-5.235987755982989
+tanh,-0x1.fff37800ab4eep-1,-0x1.3e591a2b5f908p2,-4.974188368183839
+tanh,-0x1.ffead8c8b7e1ep-1,-0x1.2d97c7f3321d2p2,-4.71238898038469
+tanh,-0x1.ffdc4b203d5d5p-1,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+tanh,-0x1.ffc3bacfc46c5p-1,-0x1.0c152382d7365p2,-4.1887902047863905
+tanh,-0x1.ff9a463bc561p-1,-0x1.f6a7a2955385dp1,-3.926990816987241
+tanh,-0x1.ff5452d7bd334p-1,-0x1.d524fe24f89f1p1,-3.665191429188092
+tanh,-0x1.fede53348bdfbp-1,-0x1.b3a259b49db85p1,-3.4033920413889427
+tanh,-0x1.fe175fa29281p-1,-0x1.921fb54442d18p1,-3.141592653589793
+tanh,-0x1.fcc835d71f5fdp-1,-0x1.709d10d3e7eabp1,-2.8797932657906435
+tanh,-0x1.fa945e2f9ed74p-1,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+tanh,-0x1.f6e20cfaf5241p-1,-0x1.2d97c7f3321d2p1,-2.356194490192345
+tanh,-0x1.f0b411c9f4d9fp-1,-0x1.0c152382d7365p1,-2.0943951023931953
+tanh,-0x1.e670ce4d24dc4p-1,-0x1.d524fe24f89f1p0,-1.832595714594046
+tanh,-0x1.d594fdae482bap-1,-0x1.921fb54442d18p0,-1.5707963267948966
+tanh,-0x1.ba6102fbc2ee2p-1,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+tanh,-0x1.8fb9cd6ec42dap-1,-0x1.0c152382d7365p0,-1.0471975511965976
+tanh,-0x1.4fc441fa6d6d6p-1,-0x1.921fb54442d18p-1,-0.7853981633974483
+tanh,-0x1.ec010e53336dap-2,-0x1.0c152382d7365p-1,-0.5235987755982988
+tanh,-0x1.061f0aa540191p-2,-0x1.0c152382d7365p-2,-0.2617993877991494
+tanh,0x0.0p0,0x0.0p0,0.0
+tanh,0x1.061f0aa540191p-2,0x1.0c152382d7365p-2,0.2617993877991494
+tanh,0x1.ec010e53336dap-2,0x1.0c152382d7365p-1,0.5235987755982988
+tanh,0x1.4fc441fa6d6d6p-1,0x1.921fb54442d18p-1,0.7853981633974483
+tanh,0x1.8fb9cd6ec42dap-1,0x1.0c152382d7365p0,1.0471975511965976
+tanh,0x1.ba6102fbc2ee2p-1,0x1.4f1a6c638d03fp0,1.3089969389957472
+tanh,0x1.d594fdae482bap-1,0x1.921fb54442d18p0,1.5707963267948966
+tanh,0x1.e670ce4d24dc4p-1,0x1.d524fe24f89f1p0,1.832595714594046
+tanh,0x1.f0b411c9f4d9fp-1,0x1.0c152382d7365p1,2.0943951023931953
+tanh,0x1.f6e20cfaf5241p-1,0x1.2d97c7f3321d2p1,2.356194490192345
+tanh,0x1.fa945e2f9ed74p-1,0x1.4f1a6c638d03fp1,2.6179938779914944
+tanh,0x1.fcc835d71f5fdp-1,0x1.709d10d3e7eabp1,2.8797932657906435
+tanh,0x1.fe175fa29281p-1,0x1.921fb54442d18p1,3.141592653589793
+tanh,0x1.fede53348bdfbp-1,0x1.b3a259b49db85p1,3.4033920413889427
+tanh,0x1.ff5452d7bd334p-1,0x1.d524fe24f89f1p1,3.665191429188092
+tanh,0x1.ff9a463bc561p-1,0x1.f6a7a2955385dp1,3.926990816987241
+tanh,0x1.ffc3bacfc46c5p-1,0x1.0c152382d7365p2,4.1887902047863905
+tanh,0x1.ffdc4b203d5d5p-1,0x1.1cd675bb04a9cp2,4.4505895925855405
+tanh,0x1.ffead8c8b7e1ep-1,0x1.2d97c7f3321d2p2,4.71238898038469
+tanh,0x1.fff37800ab4eep-1,0x1.3e591a2b5f908p2,4.974188368183839
+tanh,0x1.fff893980bbap-1,0x1.4f1a6c638d03fp2,5.235987755982989
+tanh,0x1.fffb9a371a4ddp-1,0x1.5fdbbe9bba775p2,5.497787143782138
+tanh,0x1.fffd6518fcf42p-1,0x1.709d10d3e7eabp2,5.759586531581287
+tanh,0x1.fffe74ef7ed71p-1,0x1.815e630c155e1p2,6.021385919380436
+tanh,0x1.ffff15f81f9abp-1,0x1.921fb54442d18p2,6.283185307179586
+ceil,0x1.8p1,0x1.5bf0a8b145769p1,2.718281828459045
+ceil,-0x1.0p1,-0x1.5bf0a8b145769p1,-2.718281828459045
+ceil,0x0.0p0,0x0.0p0,0.0
+ceil,-0x0.0p0,-0x0.0p0,-0.0
+ceil,0x1.0p0,0x1.0p0,1.0
+ceil,-0x1.0p0,-0x1.0p0,-1.0
+ceil,-0x0.0p0,-0x1.0p-1,-0.5
+ceil,0x1.0p0,0x1.0p-1,0.5
+ceil,-0x1.8p2,-0x1.921fb54442d18p2,-6.283185307179586
+ceil,-0x1.8p2,-0x1.815e630c155e1p2,-6.021385919380436
+ceil,-0x1.4p2,-0x1.709d10d3e7eabp2,-5.759586531581287
+ceil,-0x1.4p2,-0x1.5fdbbe9bba775p2,-5.497787143782138
+ceil,-0x1.4p2,-0x1.4f1a6c638d03fp2,-5.235987755982989
+ceil,-0x1.0p2,-0x1.3e591a2b5f908p2,-4.974188368183839
+ceil,-0x1.0p2,-0x1.2d97c7f3321d2p2,-4.71238898038469
+ceil,-0x1.0p2,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+ceil,-0x1.0p2,-0x1.0c152382d7365p2,-4.1887902047863905
+ceil,-0x1.8p1,-0x1.f6a7a2955385dp1,-3.926990816987241
+ceil,-0x1.8p1,-0x1.d524fe24f89f1p1,-3.665191429188092
+ceil,-0x1.8p1,-0x1.b3a259b49db85p1,-3.4033920413889427
+ceil,-0x1.8p1,-0x1.921fb54442d18p1,-3.141592653589793
+ceil,-0x1.0p1,-0x1.709d10d3e7eabp1,-2.8797932657906435
+ceil,-0x1.0p1,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+ceil,-0x1.0p1,-0x1.2d97c7f3321d2p1,-2.356194490192345
+ceil,-0x1.0p1,-0x1.0c152382d7365p1,-2.0943951023931953
+ceil,-0x1.0p0,-0x1.d524fe24f89f1p0,-1.832595714594046
+ceil,-0x1.0p0,-0x1.921fb54442d18p0,-1.5707963267948966
+ceil,-0x1.0p0,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+ceil,-0x1.0p0,-0x1.0c152382d7365p0,-1.0471975511965976
+ceil,-0x0.0p0,-0x1.921fb54442d18p-1,-0.7853981633974483
+ceil,-0x0.0p0,-0x1.0c152382d7365p-1,-0.5235987755982988
+ceil,-0x0.0p0,-0x1.0c152382d7365p-2,-0.2617993877991494
+ceil,0x0.0p0,0x0.0p0,0.0
+ceil,0x1.0p0,0x1.0c152382d7365p-2,0.2617993877991494
+ceil,0x1.0p0,0x1.0c152382d7365p-1,0.5235987755982988
+ceil,0x1.0p0,0x1.921fb54442d18p-1,0.7853981633974483
+ceil,0x1.0p1,0x1.0c152382d7365p0,1.0471975511965976
+ceil,0x1.0p1,0x1.4f1a6c638d03fp0,1.3089969389957472
+ceil,0x1.0p1,0x1.921fb54442d18p0,1.5707963267948966
+ceil,0x1.0p1,0x1.d524fe24f89f1p0,1.832595714594046
+ceil,0x1.8p1,0x1.0c152382d7365p1,2.0943951023931953
+ceil,0x1.8p1,0x1.2d97c7f3321d2p1,2.356194490192345
+ceil,0x1.8p1,0x1.4f1a6c638d03fp1,2.6179938779914944
+ceil,0x1.8p1,0x1.709d10d3e7eabp1,2.8797932657906435
+ceil,0x1.0p2,0x1.921fb54442d18p1,3.141592653589793
+ceil,0x1.0p2,0x1.b3a259b49db85p1,3.4033920413889427
+ceil,0x1.0p2,0x1.d524fe24f89f1p1,3.665191429188092
+ceil,0x1.0p2,0x1.f6a7a2955385dp1,3.926990816987241
+ceil,0x1.4p2,0x1.0c152382d7365p2,4.1887902047863905
+ceil,0x1.4p2,0x1.1cd675bb04a9cp2,4.4505895925855405
+ceil,0x1.4p2,0x1.2d97c7f3321d2p2,4.71238898038469
+ceil,0x1.4p2,0x1.3e591a2b5f908p2,4.974188368183839
+ceil,0x1.8p2,0x1.4f1a6c638d03fp2,5.235987755982989
+ceil,0x1.8p2,0x1.5fdbbe9bba775p2,5.497787143782138
+ceil,0x1.8p2,0x1.709d10d3e7eabp2,5.759586531581287
+ceil,0x1.cp2,0x1.815e630c155e1p2,6.021385919380436
+ceil,0x1.cp2,0x1.921fb54442d18p2,6.283185307179586
+floor,0x1.0p1,0x1.5bf0a8b145769p1,2.718281828459045
+floor,-0x1.8p1,-0x1.5bf0a8b145769p1,-2.718281828459045
+floor,0x0.0p0,0x0.0p0,0.0
+floor,-0x0.0p0,-0x0.0p0,-0.0
+floor,0x1.0p0,0x1.0p0,1.0
+floor,-0x1.0p0,-0x1.0p0,-1.0
+floor,-0x1.0p0,-0x1.0p-1,-0.5
+floor,0x0.0p0,0x1.0p-1,0.5
+floor,-0x1.cp2,-0x1.921fb54442d18p2,-6.283185307179586
+floor,-0x1.cp2,-0x1.815e630c155e1p2,-6.021385919380436
+floor,-0x1.8p2,-0x1.709d10d3e7eabp2,-5.759586531581287
+floor,-0x1.8p2,-0x1.5fdbbe9bba775p2,-5.497787143782138
+floor,-0x1.8p2,-0x1.4f1a6c638d03fp2,-5.235987755982989
+floor,-0x1.4p2,-0x1.3e591a2b5f908p2,-4.974188368183839
+floor,-0x1.4p2,-0x1.2d97c7f3321d2p2,-4.71238898038469
+floor,-0x1.4p2,-0x1.1cd675bb04a9cp2,-4.4505895925855405
+floor,-0x1.4p2,-0x1.0c152382d7365p2,-4.1887902047863905
+floor,-0x1.0p2,-0x1.f6a7a2955385dp1,-3.926990816987241
+floor,-0x1.0p2,-0x1.d524fe24f89f1p1,-3.665191429188092
+floor,-0x1.0p2,-0x1.b3a259b49db85p1,-3.4033920413889427
+floor,-0x1.0p2,-0x1.921fb54442d18p1,-3.141592653589793
+floor,-0x1.8p1,-0x1.709d10d3e7eabp1,-2.8797932657906435
+floor,-0x1.8p1,-0x1.4f1a6c638d03fp1,-2.6179938779914944
+floor,-0x1.8p1,-0x1.2d97c7f3321d2p1,-2.356194490192345
+floor,-0x1.8p1,-0x1.0c152382d7365p1,-2.0943951023931953
+floor,-0x1.0p1,-0x1.d524fe24f89f1p0,-1.832595714594046
+floor,-0x1.0p1,-0x1.921fb54442d18p0,-1.5707963267948966
+floor,-0x1.0p1,-0x1.4f1a6c638d03fp0,-1.3089969389957472
+floor,-0x1.0p1,-0x1.0c152382d7365p0,-1.0471975511965976
+floor,-0x1.0p0,-0x1.921fb54442d18p-1,-0.7853981633974483
+floor,-0x1.0p0,-0x1.0c152382d7365p-1,-0.5235987755982988
+floor,-0x1.0p0,-0x1.0c152382d7365p-2,-0.2617993877991494
+floor,0x0.0p0,0x0.0p0,0.0
+floor,0x0.0p0,0x1.0c152382d7365p-2,0.2617993877991494
+floor,0x0.0p0,0x1.0c152382d7365p-1,0.5235987755982988
+floor,0x0.0p0,0x1.921fb54442d18p-1,0.7853981633974483
+floor,0x1.0p0,0x1.0c152382d7365p0,1.0471975511965976
+floor,0x1.0p0,0x1.4f1a6c638d03fp0,1.3089969389957472
+floor,0x1.0p0,0x1.921fb54442d18p0,1.5707963267948966
+floor,0x1.0p0,0x1.d524fe24f89f1p0,1.832595714594046
+floor,0x1.0p1,0x1.0c152382d7365p1,2.0943951023931953
+floor,0x1.0p1,0x1.2d97c7f3321d2p1,2.356194490192345
+floor,0x1.0p1,0x1.4f1a6c638d03fp1,2.6179938779914944
+floor,0x1.0p1,0x1.709d10d3e7eabp1,2.8797932657906435
+floor,0x1.8p1,0x1.921fb54442d18p1,3.141592653589793
+floor,0x1.8p1,0x1.b3a259b49db85p1,3.4033920413889427
+floor,0x1.8p1,0x1.d524fe24f89f1p1,3.665191429188092
+floor,0x1.8p1,0x1.f6a7a2955385dp1,3.926990816987241
+floor,0x1.0p2,0x1.0c152382d7365p2,4.1887902047863905
+floor,0x1.0p2,0x1.1cd675bb04a9cp2,4.4505895925855405
+floor,0x1.0p2,0x1.2d97c7f3321d2p2,4.71238898038469
+floor,0x1.0p2,0x1.3e591a2b5f908p2,4.974188368183839
+floor,0x1.4p2,0x1.4f1a6c638d03fp2,5.235987755982989
+floor,0x1.4p2,0x1.5fdbbe9bba775p2,5.497787143782138
+floor,0x1.4p2,0x1.709d10d3e7eabp2,5.759586531581287
+floor,0x1.8p2,0x1.815e630c155e1p2,6.021385919380436
+floor,0x1.8p2,0x1.921fb54442d18p2,6.283185307179586
diff --git a/luni/src/test/resources/math_java_only.csv b/luni/src/test/resources/math_java_only.csv
new file mode 100644
index 0000000..7497244
--- /dev/null
+++ b/luni/src/test/resources/math_java_only.csv
@@ -0,0 +1,4132 @@
+#These tests are randomly generated.
+#Many of these test functions specific to java.
+cbrt,-0x1.28c16bdbe5b02p341,-0x1.8ec3beb2d4185p1023
+cbrt,-0x1.2e14b2c0fd516p341,-0x1.a49ea827e7d05p1023
+cbrt,-0x1.5e34a2f636f55p340,-0x1.47afe754a89fep1021
+cbrt,-0x1.f8a0db364f2c1p340,-0x1.ea33b08c7fbfbp1022
+cbrt,0x1.13fe315a92f2fp341,0x1.40c8f2c416881p1023
+cbrt,-0x1.f058cbbc49543p340,-0x1.d2762c5e7c22bp1022
+cbrt,0x1.4785ce183fe27p340,0x1.0c0c8b67b7daep1021
+cbrt,-0x1.250fa24b85fe4p341,-0x1.800e50b80ea85p1023
+cbrt,0x1.377220bf3a7dfp340,0x1.ccf6eeb86909cp1020
+cbrt,-0x1.c98f0eb5c5dcbp340,-0x1.6d6d5ccb7231fp1022
+cbrt,0x1.12ca9d6611445p341,0x1.3c9d1f4fb1b51p1023
+cbrt,-0x1.b8ce4aa4646f8p340,-0x1.46bd646b348a7p1022
+cbrt,0x1.39bb533ac53a5p341,0x1.d730774e9d4c9p1023
+cbrt,0x1.3ee216e720331p341,0x1.eec87765e84c1p1023
+cbrt,0x1.4490997193764p340,0x1.04da2953b2f46p1021
+cbrt,0x1.c37cdb4e17ca4p340,0x1.5f12c97e6cc4fp1022
+cbrt,-0x1.d903a0b4c6addp340,-0x1.93b8dc284f903p1022
+cbrt,-0x1.09f259fb99e2ep341,-0x1.1f03b54fdb6b3p1023
+cbrt,-0x1.1aee008eb2a55p341,-0x1.5995eb7752bb1p1023
+cbrt,-0x1.3734bc7ba5d4p340,-0x1.cbe68c7a0015cp1020
+cbrt,0x1.ed248b63d1995p340,0x1.c97c7a91bfb13p1022
+cbrt,-0x1.2fae8e1a994bdp341,-0x1.ab57cf7150fc7p1023
+cbrt,-0x1.e5dfd116468ddp340,-0x1.b58ddd93bfea3p1022
+cbrt,-0x1.3e1eb876a6e8ap341,-0x1.eb3d3b0b459ffp1023
+cbrt,-0x1.0ac38f307f1edp341,-0x1.21ab226ac9ce9p1023
+cbrt,-0x1.fb71e0cc80f22p340,-0x1.f274aa94c0813p1022
+cbrt,0x1.3bad1837822d4p341,0x1.e0012c863f62bp1023
+cbrt,0x1.fe974a28b759ep340,0x1.fbc8d827034c3p1022
+cbrt,0x1.07f5d2281bd68p341,0x1.18a1877e00a5fp1023
+cbrt,-0x1.b6ca6a7542dd8p340,-0x1.424779e743077p1022
+expm1,-0x1.0p0,-0x1.8ec3beb2d4185p1023
+expm1,-0x1.0p0,-0x1.a49ea827e7d05p1023
+expm1,-0x1.0p0,-0x1.47afe754a89fep1021
+expm1,-0x1.0p0,-0x1.ea33b08c7fbfbp1022
+expm1,Infinity,0x1.40c8f2c416881p1023
+expm1,-0x1.0p0,-0x1.d2762c5e7c22bp1022
+expm1,Infinity,0x1.0c0c8b67b7daep1021
+expm1,-0x1.0p0,-0x1.800e50b80ea85p1023
+expm1,Infinity,0x1.ccf6eeb86909cp1020
+expm1,-0x1.0p0,-0x1.6d6d5ccb7231fp1022
+expm1,Infinity,0x1.3c9d1f4fb1b51p1023
+expm1,-0x1.0p0,-0x1.46bd646b348a7p1022
+expm1,Infinity,0x1.d730774e9d4c9p1023
+expm1,Infinity,0x1.eec87765e84c1p1023
+expm1,Infinity,0x1.04da2953b2f46p1021
+expm1,Infinity,0x1.5f12c97e6cc4fp1022
+expm1,-0x1.0p0,-0x1.93b8dc284f903p1022
+expm1,-0x1.0p0,-0x1.1f03b54fdb6b3p1023
+expm1,-0x1.0p0,-0x1.5995eb7752bb1p1023
+expm1,-0x1.0p0,-0x1.cbe68c7a0015cp1020
+expm1,Infinity,0x1.c97c7a91bfb13p1022
+expm1,-0x1.0p0,-0x1.ab57cf7150fc7p1023
+expm1,-0x1.0p0,-0x1.b58ddd93bfea3p1022
+expm1,-0x1.0p0,-0x1.eb3d3b0b459ffp1023
+expm1,-0x1.0p0,-0x1.21ab226ac9ce9p1023
+expm1,-0x1.0p0,-0x1.f274aa94c0813p1022
+expm1,Infinity,0x1.e0012c863f62bp1023
+expm1,Infinity,0x1.fbc8d827034c3p1022
+expm1,Infinity,0x1.18a1877e00a5fp1023
+expm1,-0x1.0p0,-0x1.424779e743077p1022
+getExponent,0x1.ff8p9,-0x1.8ec3beb2d4185p1023
+getExponent,0x1.ff8p9,-0x1.a49ea827e7d05p1023
+getExponent,0x1.fe8p9,-0x1.47afe754a89fep1021
+getExponent,0x1.ffp9,-0x1.ea33b08c7fbfbp1022
+getExponent,0x1.ff8p9,0x1.40c8f2c416881p1023
+getExponent,0x1.ffp9,-0x1.d2762c5e7c22bp1022
+getExponent,0x1.fe8p9,0x1.0c0c8b67b7daep1021
+getExponent,0x1.ff8p9,-0x1.800e50b80ea85p1023
+getExponent,0x1.fep9,0x1.ccf6eeb86909cp1020
+getExponent,0x1.ffp9,-0x1.6d6d5ccb7231fp1022
+getExponent,0x1.ff8p9,0x1.3c9d1f4fb1b51p1023
+getExponent,0x1.ffp9,-0x1.46bd646b348a7p1022
+getExponent,0x1.ff8p9,0x1.d730774e9d4c9p1023
+getExponent,0x1.ff8p9,0x1.eec87765e84c1p1023
+getExponent,0x1.fe8p9,0x1.04da2953b2f46p1021
+getExponent,0x1.ffp9,0x1.5f12c97e6cc4fp1022
+getExponent,0x1.ffp9,-0x1.93b8dc284f903p1022
+getExponent,0x1.ff8p9,-0x1.1f03b54fdb6b3p1023
+getExponent,0x1.ff8p9,-0x1.5995eb7752bb1p1023
+getExponent,0x1.fep9,-0x1.cbe68c7a0015cp1020
+getExponent,0x1.ffp9,0x1.c97c7a91bfb13p1022
+getExponent,0x1.ff8p9,-0x1.ab57cf7150fc7p1023
+getExponent,0x1.ffp9,-0x1.b58ddd93bfea3p1022
+getExponent,0x1.ff8p9,-0x1.eb3d3b0b459ffp1023
+getExponent,0x1.ff8p9,-0x1.21ab226ac9ce9p1023
+getExponent,0x1.ffp9,-0x1.f274aa94c0813p1022
+getExponent,0x1.ff8p9,0x1.e0012c863f62bp1023
+getExponent,0x1.ffp9,0x1.fbc8d827034c3p1022
+getExponent,0x1.ff8p9,0x1.18a1877e00a5fp1023
+getExponent,0x1.ffp9,-0x1.424779e743077p1022
+log1p,NaN,-0x1.8ec3beb2d4185p1023
+log1p,NaN,-0x1.a49ea827e7d05p1023
+log1p,NaN,-0x1.47afe754a89fep1021
+log1p,NaN,-0x1.ea33b08c7fbfbp1022
+log1p,0x1.62a857235842dp9,0x1.40c8f2c416881p1023
+log1p,NaN,-0x1.d2762c5e7c22bp1022
+log1p,0x1.61dfe7df97bep9,0x1.0c0c8b67b7daep1021
+log1p,NaN,-0x1.800e50b80ea85p1023
+log1p,0x1.61cc940b2d36ap9,0x1.ccf6eeb86909cp1020
+log1p,NaN,-0x1.6d6d5ccb7231fp1022
+log1p,0x1.62a6aa4225779p9,0x1.3c9d1f4fb1b51p1023
+log1p,NaN,-0x1.46bd646b348a7p1022
+log1p,0x1.62d98e12c9f96p9,0x1.d730774e9d4c9p1023
+log1p,0x1.62dfcf19a6049p9,0x1.eec87765e84c1p1023
+log1p,0x1.61dc6c10526cfp9,0x1.04da2953b2f46p1021
+log1p,0x1.625b2a8fb49e6p9,0x1.5f12c97e6cc4fp1022
+log1p,NaN,-0x1.93b8dc284f903p1022
+log1p,NaN,-0x1.1f03b54fdb6b3p1023
+log1p,NaN,-0x1.5995eb7752bb1p1023
+log1p,NaN,-0x1.cbe68c7a0015cp1020
+log1p,0x1.627d0df092aa8p9,0x1.c97c7a91bfb13p1022
+log1p,NaN,-0x1.ab57cf7150fc7p1023
+log1p,NaN,-0x1.b58ddd93bfea3p1022
+log1p,NaN,-0x1.eb3d3b0b459ffp1023
+log1p,NaN,-0x1.21ab226ac9ce9p1023
+log1p,NaN,-0x1.f274aa94c0813p1022
+log1p,0x1.62dbed736c836p9,0x1.e0012c863f62bp1023
+log1p,0x1.628a67fbcd68fp9,0x1.fbc8d827034c3p1022
+log1p,0x1.6297390f32c3p9,0x1.18a1877e00a5fp1023
+log1p,NaN,-0x1.424779e743077p1022
+nextUp,-0x1.8ec3beb2d4184p1023,-0x1.8ec3beb2d4185p1023
+nextUp,-0x1.a49ea827e7d04p1023,-0x1.a49ea827e7d05p1023
+nextUp,-0x1.47afe754a89fdp1021,-0x1.47afe754a89fep1021
+nextUp,-0x1.ea33b08c7fbfap1022,-0x1.ea33b08c7fbfbp1022
+nextUp,0x1.40c8f2c416882p1023,0x1.40c8f2c416881p1023
+nextUp,-0x1.d2762c5e7c22ap1022,-0x1.d2762c5e7c22bp1022
+nextUp,0x1.0c0c8b67b7dafp1021,0x1.0c0c8b67b7daep1021
+nextUp,-0x1.800e50b80ea84p1023,-0x1.800e50b80ea85p1023
+nextUp,0x1.ccf6eeb86909dp1020,0x1.ccf6eeb86909cp1020
+nextUp,-0x1.6d6d5ccb7231ep1022,-0x1.6d6d5ccb7231fp1022
+nextUp,0x1.3c9d1f4fb1b52p1023,0x1.3c9d1f4fb1b51p1023
+nextUp,-0x1.46bd646b348a6p1022,-0x1.46bd646b348a7p1022
+nextUp,0x1.d730774e9d4cap1023,0x1.d730774e9d4c9p1023
+nextUp,0x1.eec87765e84c2p1023,0x1.eec87765e84c1p1023
+nextUp,0x1.04da2953b2f47p1021,0x1.04da2953b2f46p1021
+nextUp,0x1.5f12c97e6cc5p1022,0x1.5f12c97e6cc4fp1022
+nextUp,-0x1.93b8dc284f902p1022,-0x1.93b8dc284f903p1022
+nextUp,-0x1.1f03b54fdb6b2p1023,-0x1.1f03b54fdb6b3p1023
+nextUp,-0x1.5995eb7752bbp1023,-0x1.5995eb7752bb1p1023
+nextUp,-0x1.cbe68c7a0015bp1020,-0x1.cbe68c7a0015cp1020
+nextUp,0x1.c97c7a91bfb14p1022,0x1.c97c7a91bfb13p1022
+nextUp,-0x1.ab57cf7150fc6p1023,-0x1.ab57cf7150fc7p1023
+nextUp,-0x1.b58ddd93bfea2p1022,-0x1.b58ddd93bfea3p1022
+nextUp,-0x1.eb3d3b0b459fep1023,-0x1.eb3d3b0b459ffp1023
+nextUp,-0x1.21ab226ac9ce8p1023,-0x1.21ab226ac9ce9p1023
+nextUp,-0x1.f274aa94c0812p1022,-0x1.f274aa94c0813p1022
+nextUp,0x1.e0012c863f62cp1023,0x1.e0012c863f62bp1023
+nextUp,0x1.fbc8d827034c4p1022,0x1.fbc8d827034c3p1022
+nextUp,0x1.18a1877e00a6p1023,0x1.18a1877e00a5fp1023
+nextUp,-0x1.424779e743076p1022,-0x1.424779e743077p1022
+rint,-0x1.8ec3beb2d4185p1023,-0x1.8ec3beb2d4185p1023
+rint,-0x1.a49ea827e7d05p1023,-0x1.a49ea827e7d05p1023
+rint,-0x1.47afe754a89fep1021,-0x1.47afe754a89fep1021
+rint,-0x1.ea33b08c7fbfbp1022,-0x1.ea33b08c7fbfbp1022
+rint,0x1.40c8f2c416881p1023,0x1.40c8f2c416881p1023
+rint,-0x1.d2762c5e7c22bp1022,-0x1.d2762c5e7c22bp1022
+rint,0x1.0c0c8b67b7daep1021,0x1.0c0c8b67b7daep1021
+rint,-0x1.800e50b80ea85p1023,-0x1.800e50b80ea85p1023
+rint,0x1.ccf6eeb86909cp1020,0x1.ccf6eeb86909cp1020
+rint,-0x1.6d6d5ccb7231fp1022,-0x1.6d6d5ccb7231fp1022
+rint,0x1.3c9d1f4fb1b51p1023,0x1.3c9d1f4fb1b51p1023
+rint,-0x1.46bd646b348a7p1022,-0x1.46bd646b348a7p1022
+rint,0x1.d730774e9d4c9p1023,0x1.d730774e9d4c9p1023
+rint,0x1.eec87765e84c1p1023,0x1.eec87765e84c1p1023
+rint,0x1.04da2953b2f46p1021,0x1.04da2953b2f46p1021
+rint,0x1.5f12c97e6cc4fp1022,0x1.5f12c97e6cc4fp1022
+rint,-0x1.93b8dc284f903p1022,-0x1.93b8dc284f903p1022
+rint,-0x1.1f03b54fdb6b3p1023,-0x1.1f03b54fdb6b3p1023
+rint,-0x1.5995eb7752bb1p1023,-0x1.5995eb7752bb1p1023
+rint,-0x1.cbe68c7a0015cp1020,-0x1.cbe68c7a0015cp1020
+rint,0x1.c97c7a91bfb13p1022,0x1.c97c7a91bfb13p1022
+rint,-0x1.ab57cf7150fc7p1023,-0x1.ab57cf7150fc7p1023
+rint,-0x1.b58ddd93bfea3p1022,-0x1.b58ddd93bfea3p1022
+rint,-0x1.eb3d3b0b459ffp1023,-0x1.eb3d3b0b459ffp1023
+rint,-0x1.21ab226ac9ce9p1023,-0x1.21ab226ac9ce9p1023
+rint,-0x1.f274aa94c0813p1022,-0x1.f274aa94c0813p1022
+rint,0x1.e0012c863f62bp1023,0x1.e0012c863f62bp1023
+rint,0x1.fbc8d827034c3p1022,0x1.fbc8d827034c3p1022
+rint,0x1.18a1877e00a5fp1023,0x1.18a1877e00a5fp1023
+rint,-0x1.424779e743077p1022,-0x1.424779e743077p1022
+signum,-0x1.0p0,-0x1.8ec3beb2d4185p1023
+signum,-0x1.0p0,-0x1.a49ea827e7d05p1023
+signum,-0x1.0p0,-0x1.47afe754a89fep1021
+signum,-0x1.0p0,-0x1.ea33b08c7fbfbp1022
+signum,0x1.0p0,0x1.40c8f2c416881p1023
+signum,-0x1.0p0,-0x1.d2762c5e7c22bp1022
+signum,0x1.0p0,0x1.0c0c8b67b7daep1021
+signum,-0x1.0p0,-0x1.800e50b80ea85p1023
+signum,0x1.0p0,0x1.ccf6eeb86909cp1020
+signum,-0x1.0p0,-0x1.6d6d5ccb7231fp1022
+signum,0x1.0p0,0x1.3c9d1f4fb1b51p1023
+signum,-0x1.0p0,-0x1.46bd646b348a7p1022
+signum,0x1.0p0,0x1.d730774e9d4c9p1023
+signum,0x1.0p0,0x1.eec87765e84c1p1023
+signum,0x1.0p0,0x1.04da2953b2f46p1021
+signum,0x1.0p0,0x1.5f12c97e6cc4fp1022
+signum,-0x1.0p0,-0x1.93b8dc284f903p1022
+signum,-0x1.0p0,-0x1.1f03b54fdb6b3p1023
+signum,-0x1.0p0,-0x1.5995eb7752bb1p1023
+signum,-0x1.0p0,-0x1.cbe68c7a0015cp1020
+signum,0x1.0p0,0x1.c97c7a91bfb13p1022
+signum,-0x1.0p0,-0x1.ab57cf7150fc7p1023
+signum,-0x1.0p0,-0x1.b58ddd93bfea3p1022
+signum,-0x1.0p0,-0x1.eb3d3b0b459ffp1023
+signum,-0x1.0p0,-0x1.21ab226ac9ce9p1023
+signum,-0x1.0p0,-0x1.f274aa94c0813p1022
+signum,0x1.0p0,0x1.e0012c863f62bp1023
+signum,0x1.0p0,0x1.fbc8d827034c3p1022
+signum,0x1.0p0,0x1.18a1877e00a5fp1023
+signum,-0x1.0p0,-0x1.424779e743077p1022
+toDegrees,-Infinity,-0x1.8ec3beb2d4185p1023
+toDegrees,-Infinity,-0x1.a49ea827e7d05p1023
+toDegrees,-Infinity,-0x1.47afe754a89fep1021
+toDegrees,-Infinity,-0x1.ea33b08c7fbfbp1022
+toDegrees,Infinity,0x1.40c8f2c416881p1023
+toDegrees,-Infinity,-0x1.d2762c5e7c22bp1022
+toDegrees,Infinity,0x1.0c0c8b67b7daep1021
+toDegrees,-Infinity,-0x1.800e50b80ea85p1023
+toDegrees,Infinity,0x1.ccf6eeb86909cp1020
+toDegrees,-Infinity,-0x1.6d6d5ccb7231fp1022
+toDegrees,Infinity,0x1.3c9d1f4fb1b51p1023
+toDegrees,-Infinity,-0x1.46bd646b348a7p1022
+toDegrees,Infinity,0x1.d730774e9d4c9p1023
+toDegrees,Infinity,0x1.eec87765e84c1p1023
+toDegrees,Infinity,0x1.04da2953b2f46p1021
+toDegrees,Infinity,0x1.5f12c97e6cc4fp1022
+toDegrees,-Infinity,-0x1.93b8dc284f903p1022
+toDegrees,-Infinity,-0x1.1f03b54fdb6b3p1023
+toDegrees,-Infinity,-0x1.5995eb7752bb1p1023
+toDegrees,-Infinity,-0x1.cbe68c7a0015cp1020
+toDegrees,Infinity,0x1.c97c7a91bfb13p1022
+toDegrees,-Infinity,-0x1.ab57cf7150fc7p1023
+toDegrees,-Infinity,-0x1.b58ddd93bfea3p1022
+toDegrees,-Infinity,-0x1.eb3d3b0b459ffp1023
+toDegrees,-Infinity,-0x1.21ab226ac9ce9p1023
+toDegrees,-Infinity,-0x1.f274aa94c0813p1022
+toDegrees,Infinity,0x1.e0012c863f62bp1023
+toDegrees,Infinity,0x1.fbc8d827034c3p1022
+toDegrees,Infinity,0x1.18a1877e00a5fp1023
+toDegrees,-Infinity,-0x1.424779e743077p1022
+toRadians,-0x1.bd6ca335c8f8bp1017,-0x1.8ec3beb2d4185p1023
+toRadians,-0x1.d5d636d37463cp1017,-0x1.a49ea827e7d05p1023
+toRadians,-0x1.6e07b010242a3p1015,-0x1.47afe754a89fep1021
+toRadians,-0x1.11c7c808a0662p1017,-0x1.ea33b08c7fbfbp1022
+toRadians,0x1.6651facd75f48p1017,0x1.40c8f2c416881p1023
+toRadians,-0x1.048574b80ff57p1017,-0x1.d2762c5e7c22bp1022
+toRadians,0x1.2b69e24b71de8p1015,0x1.0c0c8b67b7daep1021
+toRadians,-0x1.acfe9cbf85fcep1017,-0x1.800e50b80ea85p1023
+toRadians,0x1.0173811fff46ap1015,0x1.ccf6eeb86909cp1020
+toRadians,-0x1.982fa40f44f9ap1016,-0x1.6d6d5ccb7231fp1022
+toRadians,0x1.61a934e496335p1017,0x1.3c9d1f4fb1b51p1023
+toRadians,-0x1.6cf8ccc8ea027p1016,-0x1.46bd646b348a7p1022
+toRadians,0x1.072969315a381p1018,0x1.d730774e9d4c9p1023
+toRadians,0x1.1456c8928aff4p1018,0x1.eec87765e84c1p1023
+toRadians,0x1.235fec19c543cp1015,0x1.04da2953b2f46p1021
+toRadians,0x1.882719ca8a188p1016,0x1.5f12c97e6cc4fp1022
+toRadians,-0x1.c2f640afddd61p1016,-0x1.93b8dc284f903p1022
+toRadians,-0x1.40992763eae48p1017,-0x1.1f03b54fdb6b3p1023
+toRadians,-0x1.8205d95283762p1017,-0x1.5995eb7752bb1p1023
+toRadians,-0x1.00db6068f8009p1015,-0x1.cbe68c7a0015cp1020
+toRadians,0x1.ff045cc909d01p1016,0x1.c97c7a91bfb13p1022
+toRadians,-0x1.dd58c2d344925p1017,-0x1.ab57cf7150fc7p1023
+toRadians,-0x1.e8c0b050f0382p1016,-0x1.b58ddd93bfea3p1022
+toRadians,-0x1.125c16633ee83p1018,-0x1.eb3d3b0b459ffp1023
+toRadians,-0x1.4390148899c34p1017,-0x1.21ab226ac9ce9p1023
+toRadians,-0x1.1663e3e36d831p1017,-0x1.f274aa94c0813p1022
+toRadians,0x1.0c15cb5b07c69p1018,0x1.e0012c863f62bp1023
+toRadians,0x1.1b99b34e2a2c9p1017,0x1.fbc8d827034c3p1022
+toRadians,0x1.3977c2280a1dep1017,0x1.18a1877e00a5fp1023
+toRadians,-0x1.67fd447707815p1016,-0x1.424779e743077p1022
+ulp,0x1.0p971,-0x1.8ec3beb2d4185p1023
+ulp,0x1.0p971,-0x1.a49ea827e7d05p1023
+ulp,0x1.0p969,-0x1.47afe754a89fep1021
+ulp,0x1.0p970,-0x1.ea33b08c7fbfbp1022
+ulp,0x1.0p971,0x1.40c8f2c416881p1023
+ulp,0x1.0p970,-0x1.d2762c5e7c22bp1022
+ulp,0x1.0p969,0x1.0c0c8b67b7daep1021
+ulp,0x1.0p971,-0x1.800e50b80ea85p1023
+ulp,0x1.0p968,0x1.ccf6eeb86909cp1020
+ulp,0x1.0p970,-0x1.6d6d5ccb7231fp1022
+ulp,0x1.0p971,0x1.3c9d1f4fb1b51p1023
+ulp,0x1.0p970,-0x1.46bd646b348a7p1022
+ulp,0x1.0p971,0x1.d730774e9d4c9p1023
+ulp,0x1.0p971,0x1.eec87765e84c1p1023
+ulp,0x1.0p969,0x1.04da2953b2f46p1021
+ulp,0x1.0p970,0x1.5f12c97e6cc4fp1022
+ulp,0x1.0p970,-0x1.93b8dc284f903p1022
+ulp,0x1.0p971,-0x1.1f03b54fdb6b3p1023
+ulp,0x1.0p971,-0x1.5995eb7752bb1p1023
+ulp,0x1.0p968,-0x1.cbe68c7a0015cp1020
+ulp,0x1.0p970,0x1.c97c7a91bfb13p1022
+ulp,0x1.0p971,-0x1.ab57cf7150fc7p1023
+ulp,0x1.0p970,-0x1.b58ddd93bfea3p1022
+ulp,0x1.0p971,-0x1.eb3d3b0b459ffp1023
+ulp,0x1.0p971,-0x1.21ab226ac9ce9p1023
+ulp,0x1.0p970,-0x1.f274aa94c0813p1022
+ulp,0x1.0p971,0x1.e0012c863f62bp1023
+ulp,0x1.0p970,0x1.fbc8d827034c3p1022
+ulp,0x1.0p971,0x1.18a1877e00a5fp1023
+ulp,0x1.0p970,-0x1.424779e743077p1022
+nextUp,-0x1.8ec3beb2d4184p1023,-0x1.8ec3beb2d4185p1023
+nextUp,-0x1.a49ea827e7d04p1023,-0x1.a49ea827e7d05p1023
+nextUp,-0x1.47afe754a89fdp1021,-0x1.47afe754a89fep1021
+nextUp,-0x1.ea33b08c7fbfap1022,-0x1.ea33b08c7fbfbp1022
+nextUp,0x1.40c8f2c416882p1023,0x1.40c8f2c416881p1023
+nextUp,-0x1.d2762c5e7c22ap1022,-0x1.d2762c5e7c22bp1022
+nextUp,0x1.0c0c8b67b7dafp1021,0x1.0c0c8b67b7daep1021
+nextUp,-0x1.800e50b80ea84p1023,-0x1.800e50b80ea85p1023
+nextUp,0x1.ccf6eeb86909dp1020,0x1.ccf6eeb86909cp1020
+nextUp,-0x1.6d6d5ccb7231ep1022,-0x1.6d6d5ccb7231fp1022
+nextUp,0x1.3c9d1f4fb1b52p1023,0x1.3c9d1f4fb1b51p1023
+nextUp,-0x1.46bd646b348a6p1022,-0x1.46bd646b348a7p1022
+nextUp,0x1.d730774e9d4cap1023,0x1.d730774e9d4c9p1023
+nextUp,0x1.eec87765e84c2p1023,0x1.eec87765e84c1p1023
+nextUp,0x1.04da2953b2f47p1021,0x1.04da2953b2f46p1021
+nextUp,0x1.5f12c97e6cc5p1022,0x1.5f12c97e6cc4fp1022
+nextUp,-0x1.93b8dc284f902p1022,-0x1.93b8dc284f903p1022
+nextUp,-0x1.1f03b54fdb6b2p1023,-0x1.1f03b54fdb6b3p1023
+nextUp,-0x1.5995eb7752bbp1023,-0x1.5995eb7752bb1p1023
+nextUp,-0x1.cbe68c7a0015bp1020,-0x1.cbe68c7a0015cp1020
+nextUp,0x1.c97c7a91bfb14p1022,0x1.c97c7a91bfb13p1022
+nextUp,-0x1.ab57cf7150fc6p1023,-0x1.ab57cf7150fc7p1023
+nextUp,-0x1.b58ddd93bfea2p1022,-0x1.b58ddd93bfea3p1022
+nextUp,-0x1.eb3d3b0b459fep1023,-0x1.eb3d3b0b459ffp1023
+nextUp,-0x1.21ab226ac9ce8p1023,-0x1.21ab226ac9ce9p1023
+nextUp,-0x1.f274aa94c0812p1022,-0x1.f274aa94c0813p1022
+nextUp,0x1.e0012c863f62cp1023,0x1.e0012c863f62bp1023
+nextUp,0x1.fbc8d827034c4p1022,0x1.fbc8d827034c3p1022
+nextUp,0x1.18a1877e00a6p1023,0x1.18a1877e00a5fp1023
+nextUp,-0x1.424779e743076p1022,-0x1.424779e743077p1022
+expm1,-0x1.9cce617760b86p-1,-0x1.a428e298f71edp0
+expm1,-0x1.c31b9fecb2667p-1,-0x1.108a530fc0d2p1
+expm1,0x1.d84cfb46444c3p1,0x1.8b9f5d1de5c3dp0
+expm1,-0x1.be3c4e9d3d4bp-1,-0x1.06affbb00d98fp1
+expm1,0x1.488d1a8fb117fp-1,0x1.fba17da5f8b4p-2
+expm1,0x1.4f362dab45f2cp-2,0x1.21fc1ec020265p-2
+expm1,-0x1.f6037ebeb4cc2p-1,-0x1.f7f314af56e93p1
+expm1,0x1.8c60ee23a58bdp0,0x1.def2ff6a5a047p-1
+expm1,0x1.2fb26016d86a5p-3,0x1.1b2f14c6ae1c5p-3
+expm1,0x1.17a5f93a6bfb8p0,0x1.7a0282d891ad3p-1
+expm1,0x1.113b136256129p-2,0x1.e4622024c81ebp-3
+expm1,0x1.7ff45eaad7988p24,0x1.10a770e97d9e7p4
+expm1,0x1.8a9d18e586db4p-2,0x1.4dc9651946b7ap-2
+expm1,0x1.3dc4de5d5ab42p-1,0x1.ee6915f64a79cp-2
+expm1,0x1.2a8d7c3f893fdp1,0x1.34260cf244cdp0
+expm1,0x1.6ab8fa5d2e61p1,0x1.5806777a3c3p0
+expm1,-0x1.79481038a9e3ep-5,-0x1.823ee1dc7fe48p-5
+expm1,0x1.555c872c09367p-3,0x1.3bb984b9c4954p-3
+expm1,0x1.0407e741c6d8ep-2,0x1.cf6feff705532p-3
+expm1,-0x1.08bae127926d4p-1,-0x1.74a7eff601cdcp-1
+expm1,0x1.50a2c9ded20fep23,0x1.0375984fb2281p4
+expm1,0x1.f6f4625d227dfp4,0x1.bd5755943de38p1
+expm1,0x1.d1d886cfed521p0,0x1.0960da57be582p0
+expm1,0x1.7fb6c0fe4b3f4p-3,0x1.5fb557ca64795p-3
+expm1,-0x1.e71cda74e9a52p-3,-0x1.1620bd9fc350fp-2
+expm1,-0x1.8e3322ce2ba4dp-1,-0x1.80fe46017449cp0
+expm1,-0x1.498d5bb3c3d3fp-1,-0x1.0828010a23fap0
+expm1,0x1.67234fceaea03p-1,0x1.101d9566db9cdp-1
+expm1,-0x1.db7e672db7ed9p-1,-0x1.520717e55c7cep1
+expm1,0x1.675c1aa18e11p3,0x1.407f835a98e74p1
+expm1,-0x1.6fb54f7ee5624p-2,-0x1.c78b0c72df77bp-2
+expm1,-0x1.ef6a015b45da5p-1,-0x1.b702b9b97b225p1
+expm1,0x1.fd8f7e7d22f9fp12,0x1.2033482ef147cp3
+expm1,0x1.347088405765ep-3,0x1.1f4f60b28d4b2p-3
+expm1,-0x1.91c228406494ep-1,-0x1.892064e9fbe38p0
+expm1,-0x1.c378b0f9be9ebp-1,-0x1.114e8b4e47b56p1
+expm1,0x1.0c37fefe1bd74p-1,0x1.af5c13c6cc9dp-2
+expm1,0x1.28663408d756bp-5,0x1.2329bed5f8384p-5
+expm1,0x1.89088de6f271ep-5,0x1.7fe5679450e6cp-5
+expm1,-0x1.6b946b2a63306p-1,-0x1.3cffb74d9883ap0
+expm1,0x1.65198db542bp3,0x1.3fc1bdbc5959bp1
+expm1,0x1.b4d62828103c6p0,0x1.fdc177ce6b2fp-1
+expm1,-0x1.a933d54962e62p-1,-0x1.c655c955055a4p0
+expm1,-0x1.4d9b515febaf6p-1,-0x1.0de8d59773e34p0
+expm1,0x1.1c1cfbfabe627p0,0x1.7e4287e158391p-1
+expm1,-0x1.783de8234820fp-1,-0x1.53d3b9e746ce5p0
+expm1,0x1.8782f9dfef649p25,0x1.1c0e68278cbe8p4
+expm1,-0x1.2c4d9740abd87p-1,-0x1.c42ebb78fbe73p-1
+expm1,0x1.45891e11d7d3ep0,0x1.a417e40cf4b43p-1
+expm1,0x1.50d809895a98ep24,0x1.0e8f417663934p4
+expm1,-0x1.ac7b2ffccc578p-4,-0x1.c496f63767e31p-4
+expm1,0x1.23f9698df255ep1,0x1.302b763fe6981p0
+expm1,-0x1.372fb3a1c8b16p-1,-0x1.df34782f9a1a5p-1
+expm1,0x1.31989d562b56ep3,0x1.2d95289794af2p1
+expm1,0x1.1a5b54e16683ap-1,0x1.c1bfc1f99f2e4p-2
+expm1,0x1.24deab3524f3bp0,0x1.867e7e0cc218ep-1
+expm1,0x1.4a933382051b6p0,0x1.a882d2b39ac55p-1
+expm1,-0x1.205716f69f914p-1,-0x1.a809a09f4f09bp-1
+expm1,0x1.59caf3c696abcp4,0x1.8f2a729c39e94p1
+expm1,0x1.e4d273a09d1f6p1,0x1.90e848d448a5cp0
+expm1,0x1.8e9c29fbb3306p-2,0x1.50aad6a5c5abp-2
+expm1,0x1.0ff80a690234ep-1,0x1.b4451257c6c54p-2
+expm1,0x1.0a404fd922ddp7,0x1.39858ee3507c2p2
+expm1,0x1.85a6937fa51d4p-6,0x1.8116e6578fb2dp-6
+expm1,-0x1.3afb4d3f1fe44p-1,-0x1.e8f9655fdf834p-1
+expm1,0x1.9e3df7b42b57bp4,0x1.a5585e10e1aa9p1
+expm1,-0x1.694462acf4144p-2,-0x1.bd8acde22cb7ap-2
+expm1,0x1.f89157586270bp0,0x1.16c158baaac49p0
+expm1,0x1.c988d67b49f5p-3,0x1.9cf4962ba6c93p-3
+expm1,0x1.6912956ef46f2p1,0x1.5729bdac949ffp0
+expm1,0x1.976bd3c015fd5p0,0x1.e78b094b3102ap-1
+expm1,0x1.8ff8984c9a5e9p3,0x1.4d22bdcf14f59p1
+expm1,0x1.20d1be1acf74ap0,0x1.82b3a24c13b11p-1
+expm1,-0x1.d693360e8c6aep-1,-0x1.41d934d83ecacp1
+expm1,0x1.ef46f146273dap0,0x1.139bdec0344acp0
+expm1,0x1.6f6a2734bc0cp-3,0x1.51ef54872e016p-3
+expm1,0x1.6d57ad055f3aap-4,0x1.5df51d8826a33p-4
+expm1,-0x1.21951d9534acfp-1,-0x1.aae3adbfd838dp-1
+expm1,0x1.24a9441e3b6b6p1,0x1.3096916641fcdp0
+expm1,-0x1.11ec382c1c485p-1,-0x1.880dad5ffc433p-1
+expm1,-0x1.2cf8056959716p-1,-0x1.c5cb938de2e43p-1
+expm1,0x1.e78acec13ab66p-3,0x1.b5567396909d5p-3
+expm1,0x1.0acdf96f8a344p1,0x1.20592c22f0e12p0
+expm1,0x1.0aae10d4f76f2p0,0x1.6d7620cd67311p-1
+expm1,-0x1.fff141245875cp-1,-0x1.22f64374a5fefp3
+expm1,-0x1.704270d7d5b56p-2,-0x1.c8675818dde29p-2
+expm1,0x1.0ea5330cfe07cp8,0x1.66b0150f95df3p2
+expm1,-0x1.110b939bd2f2cp-1,-0x1.862b74fd88896p-1
+expm1,-0x1.6d35632ffa269p-1,-0x1.3fd2e487b56e7p0
+expm1,-0x1.dfa7e2e9baa38p-2,-0x1.438717b32225cp-1
+expm1,0x1.70d19617dce74p-4,0x1.6125d50ed9678p-4
+expm1,-0x1.7580ffd64dce4p-1,-0x1.4eb72c14c261fp0
+expm1,0x1.24db28dd6a517p1,0x1.30b4eca7db93dp0
+expm1,-0x1.21e6aac0620bcp-2,-0x1.54d0dac99524ep-2
+expm1,-0x1.bfe1f0bc058ccp-1,-0x1.09ef1385af04ep1
+expm1,-0x1.fbfdbe07160d3p-1,-0x1.3663949103991p2
+expm1,0x1.b8c985fd94ab2p-4,0x1.a2a513214cf08p-4
+expm1,-0x1.d6bb18b6e1ceep-1,-0x1.4254ae7d34b85p1
+expm1,0x1.26e534694e3fap6,0x1.141548c4753dcp2
+expm1,-0x1.ffffffffec6fdp-1,-0x1.9720442923732p4
+expm1,-0x1.ff5ad1e90c8c8p-1,-0x1.ab4b38457d0ebp2
+expm1,-0x1.1854a1c9511f8p-3,-0x1.2d781c2629e67p-3
+expm1,0x1.49ae4bd04aec5p-2,0x1.1dcf3fe420e8cp-2
+expm1,0x1.64b8d50747509p1,0x1.54e02692fbe63p0
+expm1,-0x1.93a152134879dp-1,-0x1.8d82a61085183p0
+expm1,0x1.5eb4a9cb49518p-4,0x1.507f4aea5278ep-4
+expm1,-0x1.60ed8908acc26p-3,-0x1.835b0033fa82ap-3
+expm1,0x1.894401e1471aep5,0x1.f524b041d6afep1
+expm1,0x1.5e7713610bc9p4,0x1.90ceeb59d2e65p1
+expm1,0x1.1a9381803652ep18,0x1.9269de86ceb5bp3
+expm1,0x1.84df8f292531dp-1,0x1.214ceb7bf4fe3p-1
+expm1,0x1.af8deb21df20dp31,0x1.60280da9f724p4
+expm1,-0x1.f3c026d29d55ep-1,-0x1.ddcdee9ac0aedp1
+expm1,-0x1.8c475f33dd3cdp-1,-0x1.7cb5417d1500cp0
+expm1,0x1.eaf808c699c4p1,0x1.93765b7874f94p0
+expm1,-0x1.3f9c68880e8dp-2,-0x1.7f1ed1aa3dfbep-2
+expm1,0x1.028b61870c1ebp13,0x1.20ab69b28a6f2p3
+expm1,-0x1.e29e39ada503bp-1,-0x1.6dd121a3784ecp1
+expm1,0x1.d44a26593915ap-1,0x1.4c8e56d4b38f6p-1
+expm1,0x1.a12b346528777p-2,0x1.5df08a69ffa25p-2
+expm1,0x1.de99015a25355p0,0x1.0ddc7b316f55cp0
+expm1,-0x1.4751ce9f04508p-3,-0x1.64a58d2d3d862p-3
+expm1,0x1.c1f8914a16a78p0,0x1.03af8005e67f4p0
+expm1,0x1.1eac11460d1ddp0,0x1.80ae0cd2144f9p-1
+expm1,0x1.d5625b899ba64p0,0x1.0aa15159453cap0
+expm1,-0x1.b2d1ac357493fp-2,-0x1.1b0087f018c8ep-1
+expm1,0x1.519ad3e7f43aep0,0x1.ae9c503c2cb75p-1
+expm1,-0x1.fff8c6ad7f403p-1,-0x1.39cb9cb664d73p3
+expm1,0x1.051e09bc2e036p-1,0x1.a5ff2b458f59p-2
+expm1,0x1.9d35b26f2f0ecp-1,0x1.2ef2c216d36d7p-1
+expm1,0x1.6ddab7f791d8ep1,0x1.59a763b7ec024p0
+expm1,0x1.bdd26e12355b2p0,0x1.022d35d7df995p0
+expm1,-0x1.ed601aef58865p-1,-0x1.a82bf8e819c95p1
+expm1,-0x1.37184d31e17ecp-2,-0x1.72d082e93cd4dp-2
+expm1,0x1.daa52813f98e3p0,0x1.0c7ae8f0e2dadp0
+expm1,0x1.e17ce6f653039p1,0x1.8f82bfe855b11p0
+expm1,-0x1.acc878996cb32p-1,-0x1.d11ea87778deap0
+expm1,-0x1.7f2d6f558e874p-2,-0x1.dff7f18b3eb8dp-2
+expm1,0x1.019a0c524a6d4p4,0x1.6b6721fb77d64p1
+expm1,0x1.2eee056e6be7fp0,0x1.8fcb18f982104p-1
+expm1,-0x1.ee02c1c1f29a4p-1,-0x1.ac9d546d777f1p1
+expm1,0x1.e0f8520e3f74fp7,0x1.5f27da12948d5p2
+expm1,-0x1.fa51f9013364ep-1,-0x1.2017185e263aap2
+expm1,-0x1.fffff347e2e97p-1,-0x1.d9235e1b7a5a9p3
+expm1,-0x1.4fadeda3c8741p-1,-0x1.10e6bc2ddc52p0
+expm1,-0x1.8374a531bf374p-1,-0x1.69e5ccaf5364fp0
+expm1,-0x1.f243817ff9248p-1,-0x1.cf23dfadf368ep1
+expm1,0x1.87df0d951cb24p-2,0x1.4bce259942fcap-2
+expm1,-0x1.fd7cf4a0733a6p-1,-0x1.544e73656c7d8p2
+expm1,-0x1.fffffffdd8918p-1,-0x1.61b44adda7663p4
+expm1,0x1.3de6ebcb26012p-1,0x1.ee931b172020ap-2
+expm1,-0x1.ffffb1a5737ap-1,-0x1.9ef551cf59b37p3
+expm1,0x1.07d0e99a02bc2p-2,0x1.d57736189731ap-3
+expm1,0x1.a44f8299e564cp0,0x1.f1652af1430b5p-1
+expm1,0x1.bf47a56b4930ep0,0x1.02b5348d41e5bp0
+expm1,-0x1.9eb51a0d87adbp-1,-0x1.a91d363e50b44p0
+expm1,-0x1.77ca3c0fe0726p-1,-0x1.52f9f6f4c9acp0
+expm1,0x1.166de4ef3d416p1,0x1.27c6f62d2c468p0
+expm1,0x1.08f3ece97b06ap0,0x1.6bc44e11565c8p-1
+expm1,-0x1.23a705dc834e6p-2,-0x1.5743044c93751p-2
+expm1,0x1.b6edc05359a9bp-1,0x1.3cfc92a47c822p-1
+expm1,-0x1.3993741effd9bp-1,-0x1.e555903f9fc13p-1
+expm1,0x1.92613113c8a48p2,0x1.fc7228bab038bp0
+expm1,-0x1.7755e7311d1aep-1,-0x1.521fb0710abc3p0
+expm1,0x1.1a21c198f89bep1,0x1.2a194b3e5d53ep0
+expm1,-0x1.c9d0eaca3311bp-4,-0x1.e57bc924e2f2dp-4
+expm1,-0x1.febb541b2821dp-1,-0x1.800b46e48f2b6p2
+expm1,-0x1.ffc5b8ba75354p-1,-0x1.edf824a841cdbp2
+expm1,0x1.2cfdd76a7d35fp12,0x1.0f5b2a5d63f27p3
+expm1,-0x1.dcf1c5cf2184cp-2,-0x1.40fbd7c074ceap-1
+expm1,-0x1.f1ff96299ef96p-2,-0x1.5513e8d699d37p-1
+expm1,0x1.f428621e562fap1,0x1.973c1debbda23p0
+expm1,0x1.16ea64da4a6fp-1,0x1.bd4dae186e0dap-2
+expm1,-0x1.558389c108432p-1,-0x1.1983ffafcc07ap0
+expm1,0x1.235fb25f5a3cap0,0x1.8518c2271a4efp-1
+expm1,-0x1.73ac79e363b7bp-4,-0x1.85a1b57606f2dp-4
+expm1,-0x1.82d81ce50142ep-1,-0x1.68a4d5e78b7e3p0
+expm1,0x1.f581bb202cb26p-4,0x1.d919f2643fc6ep-4
+expm1,-0x1.6986e8c578466p-3,-0x1.8dc57cf5061e6p-3
+expm1,-0x1.352b3b5f86f8p-1,-0x1.da163c15bcbcbp-1
+expm1,-0x1.51f36d5848994p-1,-0x1.14387fc6f05bbp0
+expm1,-0x1.c08862cefbe94p-1,-0x1.0b3d0dd5bcb51p1
+expm1,-0x1.a6fdd18c77ce1p-1,-0x1.bfe54b897ab48p0
+expm1,-0x1.715d4d5a12f71p-1,-0x1.472d19c0097fp0
+expm1,0x1.25c83b0e671c1p0,0x1.87582f2251831p-1
+expm1,-0x1.0p0,-0x1.6d094519728eep5
+expm1,0x1.ac3d6de48d199p-3,0x1.84de863d16378p-3
+expm1,-0x1.0p0,-0x1.399ead5a292dcp6
+expm1,-0x1.2f6eb3e922f15p-1,-0x1.cbceb9f83bfb9p-1
+expm1,-0x1.2b7be3da57f59p-1,-0x1.c23489eca97bp-1
+expm1,0x1.8897fbecee0f6p8,0x1.7e6ba0eb82ac8p2
+expm1,0x1.af2c7f9a305b7p-8,0x1.adc2f9e2071fdp-8
+expm1,-0x1.bad097ccf9d39p-2,-0x1.21ff7db3be30ep-1
+expm1,0x1.76d7bf831b3ap13,0x1.2c8def13c5c46p3
+expm1,-0x1.e34e24d9fde43p-3,-0x1.13a212e510428p-2
+expm1,0x1.812e3302714c6p0,0x1.d615987472fadp-1
+expm1,-0x1.f327d02c5f307p-2,-0x1.56349189bf5c1p-1
+expm1,-0x1.8fc27592d306bp-4,-0x1.a4a3312901e9ep-4
+expm1,-0x1.060664c4e8ff6p-1,-0x1.6f15dac9569f1p-1
+expm1,0x1.1b42f11d89058p-2,0x1.f4288b79c0776p-3
+pow,NaN,-0x1.3543856880754p-1,0x1.35716fc87723bp0
+pow,0x1.1d4a986c89024p0,0x1.43ced9e886399p-3,-0x1.e126d87d20ed6p-5
+pow,0x1.522cbcdf959dep1,0x1.3c7d675466f15p-1,-0x1.0284cd3f0c777p1
+pow,0x1.b9bb1a3e302d4p4,0x1.5b6d1c408c6b9p-3,-0x1.decec1eac9a7cp0
+pow,0x1.73657e5443b04p15,0x1.b14dd1bdae0bp2,0x1.685fb1288c6ebp2
+pow,0x1.42aabebdcc329p-3,0x1.dbac3718db8c6p2,-0x1.d7b5616fb60a8p-1
+pow,NaN,-0x1.02396705ce823p1,-0x1.8534721a7fab8p-1
+pow,0x1.0d1bfde3040d9p0,0x1.0bcf497703256p0,0x1.1b7acc031c2b8p0
+pow,NaN,-0x1.673a84a184115p-1,0x1.da2090fb36b4ap0
+pow,NaN,-0x1.0acacaef8fc6ap0,-0x1.608b00fd22779p-1
+pow,NaN,-0x1.31a1f56d0d76cp0,-0x1.8ee0c2486c56cp-3
+pow,0x1.5833b6886737cp8,0x1.6cbf4ee77bc2bp8,0x1.faf7da80b95ap-1
+pow,0x1.8b0d0db11da52p-2,0x1.0c796357a15bap3,-0x1.ca895d25c2f87p-2
+pow,NaN,-0x1.9557e8d5ff0a4p3,0x1.53602f904ab43p-1
+pow,NaN,-0x1.e33ddb97a2aa5p-1,-0x1.de3bf71f3e726p-4
+pow,0x1.f9cdb40f437b6p1,0x1.023eb1fa2e356p-2,-0x1.feb82de9ff0a9p-1
+pow,NaN,-0x1.0d703b600d22ap-1,0x1.0f8b218cb4213p1
+pow,0x1.beac94ab9f868p-2,0x1.0e80760e867b5p1,-0x1.1bd8f6483defap0
+pow,NaN,-0x1.67450003d3a11p1,-0x1.2d82492ed37bap-4
+pow,0x1.206859cb610d6p0,0x1.230e63e0b0af4p1,0x1.292a06365effep-3
+pow,NaN,-0x1.e8c208b279e31p1,-0x1.db752e355f602p-1
+pow,NaN,-0x1.4129bf9beb84ep-1,-0x1.b18d8d5a363bap5
+pow,0x1.6ddd050ff85d3p0,0x1.9c311e9bc98dp-2,-0x1.91d2ce7ba1c81p-2
+pow,NaN,-0x1.6cdde918c6bb7p1,-0x1.13660ce5486d7p1
+pow,NaN,-0x1.d8a622fb32304p-1,-0x1.e3d8cb360b95cp0
+pow,NaN,-0x1.1f6deb57fbf3ep2,0x1.71a34e498178ep1
+pow,NaN,-0x1.aca945800269dp-1,0x1.246c80ddde002p5
+pow,0x1.f6fb38b81fe63p-1,0x1.f9269e1b13d24p-1,0x1.51d06818109ecp0
+pow,NaN,-0x1.70b5d7bc0df1ep2,0x1.1f8857556cb22p-1
+pow,0x1.be5f7398575d1p-1,0x1.89ddac959f5c5p0,-0x1.46063f0f1fd94p-2
+pow,NaN,-0x1.052522d976421p0,-0x1.576e0648a6313p-1
+pow,NaN,-0x1.c610ba3656ed4p-2,0x1.cc5ea57d50651p-2
+pow,NaN,-0x1.3b298780eaf4bp0,-0x1.9e4a93144fbf4p-2
+pow,0x1.3405a5acb927ep-1,0x1.31f27c400e9c7p0,-0x1.6cee77b97b391p1
+pow,NaN,-0x1.d4cc72dde98bdp0,-0x1.4c12bfe6381cbp-1
+pow,NaN,-0x1.a6654edf4e215p-1,-0x1.4cfa4851698bbp0
+pow,0x1.19cce90d83238p-146,0x1.5fd6a4426b0edp3,-0x1.515f384fdff55p5
+pow,NaN,-0x1.1b6e4a199b791p3,0x1.34e2a9b51e552p0
+pow,0x1.b1ab929e7ffdep-2,0x1.0231b33713194p1,-0x1.3976d1457c252p0
+pow,0x1.50d9f2fe33c7p-3,0x1.dde75639ea142p0,-0x1.721d427b01b2p1
+pow,0x1.0c7b1dd03f4b5p-4,0x1.7e424718ff1fdp-6,0x1.73435e4223861p-1
+pow,0x1.e130ed2ab279ap-3,0x1.674d21afc87dcp2,-0x1.add1aebe71ca4p-1
+pow,0x1.60dc514240fe2p0,0x1.ef54ddeb53ad2p-2,-0x1.c475f576d0f2dp-2
+pow,NaN,-0x1.012aeea2abd2ap0,0x1.2392fbe81d72cp-2
+pow,0x1.4f079d2764c28p7,0x1.6887b16643f58p-1,-0x1.d3364956d4d5cp3
+pow,0x1.9b8abb1d635b7p-2,0x1.cf76925768938p-6,0x1.05cf3eadaebdcp-2
+pow,NaN,-0x1.35634d0706b66p0,-0x1.22acb280acafdp0
+pow,0x1.f78cf9a9f2a4cp1,0x1.3e469a290341p1,0x1.80ef0426de88cp0
+pow,NaN,-0x1.9be8a4e6909dcp1,-0x1.901663cbb84fep-3
+pow,NaN,-0x1.1b2752600a802p-2,-0x1.da6c7a226c522p-1
+pow,NaN,-0x1.5fd774062642fp-2,0x1.886753a936a35p2
+pow,0x1.3edebd5811a14p-2,0x1.f20639aad80eap3,-0x1.b33cc11620f11p-2
+pow,0x1.fb715a6f77759p-1,0x1.ea47747e9fbf6p-1,0x1.a6639ae10617ep-3
+pow,0x1.17099bd97d53p-1,0x1.1138cc352d8dbp1,-0x1.99da752c2b32ap-1
+pow,NaN,-0x1.042cb9e40a3c3p1,-0x1.40cd562224abcp-1
+pow,NaN,-0x1.1c50c06fa3246p1,-0x1.31cef7cdd7413p0
+pow,0x1.ad60687187bfp0,0x1.3883a387b687cp-1,-0x1.0c2d4d6d96bb2p0
+pow,NaN,-0x1.a4f79c9fb339ep-4,0x1.59da8f5b4a73ep-2
+pow,NaN,-0x1.4c934c90f450ap0,0x1.5536d4aef0549p-2
+pow,NaN,-0x1.ad336d4adc286p-1,0x1.58ca22de47548p2
+pow,0x1.1c20079b73d21p0,0x1.840da607c2a5ap1,0x1.80f3df570f788p-4
+pow,0x1.7fb0f215b758ep0,0x1.b7b453bf4d92ap-4,-0x1.735b8374b0c87p-3
+pow,NaN,-0x1.fcab6aae1796fp-2,-0x1.780f83d5141cep-1
+pow,0x1.69c9ece38bf9cp3,0x1.3ae7171e64493p-3,-0x1.4b9afac6a55e4p0
+pow,0x1.0a21f58dbc366p-1,0x1.7a545c00cb271p0,-0x1.acdcac99c85abp0
+pow,NaN,-0x1.3e08913f9f21fp-3,0x1.81e633124343p-1
+pow,0x1.d2cb35b746486p-1,0x1.e695c53b4eeaep-6,0x1.aea9911568678p-6
+pow,0x1.0dbb3a7334225p0,0x1.6675cb29a0c1p0,0x1.3ddd7059c104cp-3
+pow,NaN,-0x1.070c2fa9e6802p1,0x1.9112142d4e9dcp-1
+pow,0x1.0a902bf5722d5p0,0x1.447dceaefa645p-1,-0x1.6b248caf29d8dp-4
+pow,0x1.1330f22590c4ap1,0x1.d72e780e0abfep-2,-0x1.f8e198dc7ba8ap-1
+pow,0x1.05b20b0a7d5c5p-3,0x1.a08b5114d4794p-3,0x1.4ab6ce7f2d8d9p0
+pow,NaN,-0x1.6cb5596f5bccap-1,-0x1.e026f2be2c735p-6
+pow,NaN,-0x1.bff74445e3f44p1,0x1.ff1d828a8f9fdp-2
+pow,0x1.bb29b1a0d9593p-1,0x1.19280f7df4f31p0,-0x1.8a574b3c6c21fp0
+pow,0x1.515d6f04001f2p0,0x1.8d40690d3afa9p1,0x1.f3137043bca52p-3
+pow,0x1.e69a356a6053p-1,0x1.e6272faa3e942p-1,0x1.f6de8fe572b0ep-1
+pow,0x1.de90ff863552cp-9,0x1.9d5d54f838bcp2,-0x1.811f7d5c9582p1
+pow,NaN,-0x1.023f6037d59cfp2,-0x1.4dfb18419fccp-2
+pow,NaN,-0x1.1cc20d156cb79p-1,0x1.459252a9af3d3p-2
+pow,0x1.d9135c8e48446p1,0x1.eb6de3ef8ffdfp-6,-0x1.7db8a8d7ce896p-2
+pow,0x1.0bfa0812358ap0,0x1.cb17ab770fd1ep-1,-0x1.ad40b171d56aep-2
+pow,NaN,-0x1.a8b99e1b72634p2,0x1.34643c33653d7p0
+pow,0x1.51a6995175d4ep-6,0x1.4708da39879c3p0,-0x1.fb4623599a3d8p3
+pow,0x1.0edaeef4b9561p0,0x1.0dbb2725712a2p0,0x1.1460b8658035p0
+pow,NaN,-0x1.045318f41eb9ap-1,-0x1.39c26e9f74658p-1
+pow,0x1.06c00c0bbad58p0,0x1.e5d8aef9c4c71p-1,-0x1.fc4b3bfffb0bcp-2
+pow,0x1.947f16f7e69b2p2,0x1.043dc775b7b51p3,0x1.c269498ff8d8ap-1
+pow,NaN,-0x1.5c12f7f31b4c3p-3,0x1.bfe15378a1e56p-3
+pow,NaN,-0x1.1f0cc14e65be8p0,-0x1.2f686c552f4bap-3
+pow,0x1.96a6a076abc92p1,0x1.fb9f996009b44p0,0x1.b04577c9d132dp0
+pow,NaN,-0x1.9033f9bf4d8bcp-1,0x1.71c885dc2d9aap-1
+pow,0x1.1b25976c149efp0,0x1.dbca857fcd851p-1,-0x1.5fc86ea34c098p0
+pow,0x1.0d9020d171475p-1,0x1.da9962780fcafp0,-0x1.0a0c5a536525ep0
+pow,NaN,-0x1.f0be3b0aed394p-3,0x1.6684a2e93eacfp-1
+pow,NaN,-0x1.13347d844b3ap2,0x1.52e80bda362f6p0
+pow,0x1.8ecabf0927c74p-1,0x1.08ef4600ac2a6p-1,0x1.8461b6ebd2638p-2
+pow,NaN,-0x1.545bab8fdb374p1,0x1.140b5443f6851p0
+pow,0x1.605e3b7e1a8a9p0,0x1.b694715b3bb5fp0,0x1.2fda4421ec27bp-1
+pow,0x1.19d126e964ecdp2,0x1.3886382511f91p2,0x1.de9b9c6ec17c8p-1
+pow,0x1.4b2a7193ded54p2,0x1.ffdaafc6d81ecp0,0x1.2faa4a532094dp1
+pow,0x1.07232bb72bf0ep182,0x1.e9c446b9f242cp-4,-0x1.db4ab29699bb1p5
+pow,NaN,-0x1.9e3204055de95p-1,0x1.0a5e93db70184p-1
+pow,0x1.1acd2b9124f7dp0,0x1.275823342912fp0,0x1.649532579916dp-1
+pow,0x1.0f47ca3682eccp0,0x1.485e42c4fd541p0,0x1.dcec8bd69c924p-3
+pow,NaN,-0x1.23bb2f8be2d74p0,-0x1.c9da27afeb55dp-2
+pow,NaN,-0x1.c587034a392cbp-2,-0x1.f25c5fb1a07bbp-1
+pow,0x1.05db5e5eda5c5p0,0x1.8db9e4a05f398p-1,-0x1.6edc4a7b93097p-4
+pow,NaN,-0x1.ab87fc0e311b7p1,-0x1.53034039016e2p1
+pow,NaN,-0x1.44bb4f7048ddfp-1,0x1.e6e647080ff5bp-2
+pow,NaN,-0x1.7817a6eb0dc76p-2,0x1.02e617c35511ap-2
+pow,NaN,-0x1.e01714a11dc2bp0,0x1.94ac311105b4ep-4
+pow,NaN,-0x1.48ad415149238p3,-0x1.7356089af8d59p-2
+pow,0x1.7aa3cf5e026e7p-2,0x1.06ed5362f04e2p-1,0x1.7e2962d832e75p0
+pow,0x1.5570ae9493bbfp0,0x1.e323a27f94fcbp-5,-0x1.a0bd6a6e9f10cp-4
+pow,0x1.152ee4ea3f7a5p1,0x1.b32a1da818d0dp1,0x1.4347b7ca029a7p-1
+pow,NaN,-0x1.03714e497f8fbp2,0x1.61ebbba8e8d3p0
+pow,NaN,-0x1.f94e76ca5ba42p-1,0x1.5fdaf42945025p0
+pow,0x1.188dcd71a310ap0,0x1.0f34cf5f7df65p0,0x1.965694c95ecc6p0
+pow,0x1.0b2cadb4cb147p0,0x1.0c40249de3f62p0,0x1.d3f98bdbca83dp-1
+pow,0x1.a5b803cf49fc6p-1,0x1.a5ea87cc7b8c2p0,-0x1.8d93f53a8c9abp-2
+pow,NaN,-0x1.045dd160caeb5p1,-0x1.562ce2be56b8ep0
+pow,0x1.84030e972f55cp1,0x1.009aa78e33834p2,0x1.98e4d1f15c54cp-1
+pow,NaN,-0x1.6e44edc8b9975p0,0x1.27b05fd665f56p-2
+pow,0x1.1d6e82b8c4526p-2,0x1.e25695af839a1p-2,0x1.b267e3187f557p0
+pow,0x1.67b1c3b809065p2,0x1.ad50aab97c6f6p-1,-0x1.39a5dd9c9ec23p3
+pow,NaN,-0x1.378b7a14b3123p-1,-0x1.d623cb500779bp-1
+pow,NaN,-0x1.b6b576540adb8p-4,-0x1.67f919b7388efp1
+pow,NaN,-0x1.a0e03f2c21b03p0,0x1.a0a6719a89da7p-4
+pow,NaN,-0x1.90f94b1510e6bp0,-0x1.2c5145f8c1ca6p-2
+pow,0x1.0820f220c6429p-3,0x1.c653e462f289fp2,-0x1.0b86c892c6d69p0
+pow,0x1.53298c15fd8dcp-3,0x1.d85a4c492edd1p0,-0x1.77beacc12e4cap1
+pow,0x1.e6872737c5bb5p-1,0x1.f99b40b5f414dp-2,0x1.282ec81705241p-4
+pow,0x1.05d050c7ea53bp0,0x1.16ce13c6d382cp0,0x1.0d76f4e269154p-2
+pow,0x1.3baf902827162p2,0x1.52d54e6210d31p-2,-0x1.7165fe6d96d64p0
+pow,0x1.8702acf8bd48ep2,0x1.83b27f2d7efbp-3,-0x1.165f690b351f5p0
+pow,NaN,-0x1.9785fb65297f6p2,-0x1.1b458cc769686p3
+pow,NaN,-0x1.09cb066385f12p0,0x1.f753576d60128p-6
+pow,0x1.e4b995c800645p-5,0x1.06d720a7e6f88p4,-0x1.02985a86e666ap0
+pow,NaN,-0x1.0939085a6f701p0,0x1.7ddd006196baap2
+pow,NaN,-0x1.d87072a74d8a6p6,0x1.790eaae918275p0
+pow,NaN,-0x1.fcc2b5194f768p-1,-0x1.c9d5f2a783883p-1
+pow,NaN,-0x1.6692393959fe5p-1,-0x1.3863994c1922cp1
+pow,NaN,-0x1.b0f50f7bf364cp-2,-0x1.14d074c377108p-5
+pow,NaN,-0x1.a20e8f0b2b858p-2,-0x1.2c0f54e075332p-2
+pow,NaN,-0x1.12d268bbaeea4p0,0x1.597d686214e67p0
+pow,0x1.b13cdddcc07c3p-2,0x1.46bbc31488813p3,-0x1.7b1c6344453f9p-2
+pow,NaN,-0x1.ff476e8f0a7e3p0,-0x1.62a04be50d505p0
+pow,NaN,-0x1.bf00588a896d3p-2,0x1.6c1c5d07803cap-1
+pow,0x1.e55b9058bb955p-7,0x1.1ec2d27a4235p1,-0x1.4e3872a7c948fp2
+pow,NaN,-0x1.b88b3d3bdf5d4p-2,-0x1.37bd82f1781b7p0
+pow,0x1.13812f08fe19dp0,0x1.d40211a90d254p-1,-0x1.a2775702dff48p-1
+pow,0x1.b3ada66ab5246p-1,0x1.869cdca43c5c8p-1,0x1.3169cc46548ep-1
+pow,NaN,-0x1.37849bc093986p0,-0x1.2aa7282eb9ebap-3
+pow,NaN,-0x1.a8944dda7586ep6,-0x1.2e47aadc1b58dp0
+pow,0x1.5aba3298bf201p-2,0x1.40a04ef8a623bp1,-0x1.2de9e2569d6d5p0
+pow,0x1.db384c61b4a74p-1,0x1.2914b4157ee24p0,-0x1.00758c0c2d72ep-1
+pow,0x1.03facf5415462p2,0x1.ada67df67a3b8p-2,-0x1.9d2c32cfcee69p0
+pow,NaN,-0x1.3088491768175p-1,0x1.bd3501f5958ap0
+pow,0x1.03796726a06a6p0,0x1.843fc5dd50c7ep-1,-0x1.8f1eee57736edp-5
+pow,NaN,-0x1.73a9bb89db993p-4,0x1.f9336be7fc6f5p0
+pow,0x1.3c59529730582p-1,0x1.931b3f08ef975p2,-0x1.0be83f40ce812p-2
+pow,NaN,-0x1.1c52401964251p0,-0x1.e209fab00f3cdp3
+pow,0x1.5870ce3110d05p-8,0x1.37a7a966690aap-5,0x1.9b0295360af3cp0
+pow,NaN,-0x1.97947ee95e148p2,0x1.fdf94a10f85d8p-2
+pow,NaN,-0x1.e3bd8870685d6p-1,0x1.0c9f51eb9fb1p-4
+pow,NaN,-0x1.06c9285154c11p-1,0x1.d21f5ac0f88dcp-4
+pow,NaN,-0x1.e851a51621887p-2,-0x1.495544552cfd7p-1
+pow,0x1.b15715904a6d4p-2,0x1.bccef58928994p-1,0x1.87377793afff2p2
+pow,0x1.3630070d85688p1,0x1.16030ade3d166p-1,-0x1.7311d0f1c9818p0
+pow,0x1.7b0bf1f3677efp0,0x1.5a0c8170f9574p0,0x1.4d5c01933c90ap0
+pow,0x1.4347bb7dbd2bap-5,0x1.00ab1db1da50fp-1,0x1.2b94fcad8bb28p2
+pow,0x1.e1d6f6b4ad3dcp0,0x1.1a71c356fda77p-1,-0x1.102d8be7b68b2p0
+pow,0x1.71ca2e9c802efp-1,0x1.93e69c1931aa2p0,-0x1.6d5b4b1eae5bap-1
+pow,0x1.60ee40140178cp-2,0x1.efd52cc8e9b32p-3,0x1.8082bff8e9734p-1
+pow,NaN,-0x1.3aa803d4e5afcp0,-0x1.853016b0f962ap0
+pow,0x1.1248c3ab2c50ap0,0x1.0a086b18b7be1p-1,-0x1.af9a7315362dcp-4
+pow,NaN,-0x1.1c65baf6ed71bp-1,-0x1.e4ce9408d718cp1
+pow,NaN,-0x1.129c9c18a45c9p0,0x1.dbd7977bbb3dbp1
+pow,NaN,-0x1.f8a2cbe4c9971p0,-0x1.6402723e29405p0
+pow,NaN,-0x1.090715aeef52ap-3,0x1.ff3c3f34c1216p0
+pow,0x1.633a5b7a503a6p6,0x1.48716eed60949p4,0x1.7c16158088824p0
+pow,NaN,-0x1.44930bdd5a09fp0,0x1.f17780da0c3bcp-4
+pow,0x1.3d8d6624ecbp-10,0x1.d6ec1a8e01545p-7,0x1.95411fce4c444p0
+pow,0x1.e5f2940ed1965p-1,0x1.1a84da1d7650cp1,-0x1.0e2f2b637c419p-4
+pow,0x1.5b1f6c1d4f497p-2,0x1.5e69e0f96815bp-2,0x1.0240a70912ecap0
+pow,0x1.7fd48e097e9a4p-4,0x1.23cefbdbeed36p3,-0x1.123500770a0b2p0
+pow,0x1.3c6a0ee0f14a2p-2,0x1.412b81765458dp-1,0x1.42579fdaa45edp1
+pow,0x1.1c477b9b71089p0,0x1.1d8bb34a7e43ap0,0x1.eb29bada420cfp-1
+pow,NaN,-0x1.7f6d0fa1fb44ep1,0x1.6b638367aa265p0
+pow,NaN,-0x1.42b4ebd31e0a3p3,-0x1.6d3fb072dd01dp1
+pow,0x1.52f4fb825bbf4p-1,0x1.7fc88d75156c4p-1,0x1.6e4f6fe5266fdp0
+pow,NaN,-0x1.2f63c263fcce9p-1,-0x1.fd3f99df0dd14p-1
+pow,0x1.aa8e9f53ca8adp1,0x1.eee1f221556d9p-4,-0x1.239c3f92a6941p-1
+pow,0x1.2fd9a918fec76p0,0x1.19574be3b830ap0,0x1.d0bf5745a62fbp0
+pow,0x1.e900a2abe38b7p-3,0x1.95f0e06b551e5p-7,0x1.4e01d522f7c2bp-2
+pow,NaN,-0x1.961230e761e2bp0,-0x1.a8d9a224ff5abp-2
+pow,NaN,-0x1.22a4b03c16fd4p-1,-0x1.bba2e8dcba702p-1
+pow,NaN,-0x1.9f94bd566490ap-1,-0x1.25051ed331b22p0
+pow,NaN,-0x1.0c252587ffbbep2,0x1.3df68e7581d3bp1
+nextUp,0x1.d3040e41e2ed6p-1,0x1.d3040e41e2ed5p-1
+nextUp,-0x1.53b76e8b2e194p0,-0x1.53b76e8b2e195p0
+nextUp,-0x1.2e7cc91f10c7fp3,-0x1.2e7cc91f10c8p3
+nextUp,0x1.115ecd0d3d8a9p-1,0x1.115ecd0d3d8a8p-1
+nextUp,-0x1.0a68bfff8d648p0,-0x1.0a68bfff8d649p0
+nextUp,-0x1.be4afc4ccae83p-1,-0x1.be4afc4ccae84p-1
+nextUp,-0x1.451ff3485acbbp-1,-0x1.451ff3485acbcp-1
+nextUp,0x1.14c999736e394p-1,0x1.14c999736e393p-1
+nextUp,-0x1.b01b9c1b9a649p3,-0x1.b01b9c1b9a64ap3
+nextUp,-0x1.665f667e2b3d1p0,-0x1.665f667e2b3d2p0
+nextUp,-0x1.1760f0ff2b4e3p0,-0x1.1760f0ff2b4e4p0
+nextUp,-0x1.910dc2365ef13p-1,-0x1.910dc2365ef14p-1
+nextUp,-0x1.16d967cb6fe61p1,-0x1.16d967cb6fe62p1
+nextUp,0x1.1f04263fb3e0fp0,0x1.1f04263fb3e0ep0
+nextUp,-0x1.69d304c513701p0,-0x1.69d304c513702p0
+nextUp,0x1.f529637ef54c6p-2,0x1.f529637ef54c5p-2
+nextUp,0x1.9acafec6b8ff6p-8,0x1.9acafec6b8ff5p-8
+nextUp,0x1.0375a2b72b97cp0,0x1.0375a2b72b97bp0
+nextUp,-0x1.9646c16b6fb92p-1,-0x1.9646c16b6fb93p-1
+nextUp,0x1.1e60599537373p0,0x1.1e60599537372p0
+nextUp,-0x1.8a8df712b9d86p-2,-0x1.8a8df712b9d87p-2
+nextUp,-0x1.a016f5f219b25p0,-0x1.a016f5f219b26p0
+nextUp,-0x1.e239718239c74p-1,-0x1.e239718239c75p-1
+nextUp,0x1.7c453055df8bbp-1,0x1.7c453055df8bap-1
+nextUp,0x1.72a89333661e3p-1,0x1.72a89333661e2p-1
+nextUp,-0x1.e638b805d1849p1,-0x1.e638b805d184ap1
+nextUp,0x1.88445788e7263p4,0x1.88445788e7262p4
+nextUp,-0x1.5bc1c772e6149p-1,-0x1.5bc1c772e614ap-1
+nextUp,-0x1.8d8971d94147fp-2,-0x1.8d8971d94148p-2
+nextUp,0x1.1216da190a47fp0,0x1.1216da190a47ep0
+nextUp,0x1.1f616373910f9p0,0x1.1f616373910f8p0
+nextUp,0x1.d7189f97e6d8ap-1,0x1.d7189f97e6d89p-1
+nextUp,-0x1.17b972d833cap0,-0x1.17b972d833ca1p0
+nextUp,-0x1.06b0482e9926ap0,-0x1.06b0482e9926bp0
+nextUp,-0x1.f0ad7aa11b04ep-3,-0x1.f0ad7aa11b04fp-3
+nextUp,-0x1.4744eeb81da2fp-9,-0x1.4744eeb81da3p-9
+nextUp,0x1.ff2a8df85b779p-1,0x1.ff2a8df85b778p-1
+nextUp,0x1.3130e66165a86p2,0x1.3130e66165a85p2
+nextUp,-0x1.3f67ba776c895p-2,-0x1.3f67ba776c896p-2
+nextUp,-0x1.dc657d757ae33p4,-0x1.dc657d757ae34p4
+nextUp,0x1.8e2bc626c19a4p-1,0x1.8e2bc626c19a3p-1
+nextUp,0x1.b80a35d69ebf3p-1,0x1.b80a35d69ebf2p-1
+nextUp,0x1.0c580407a5e36p-1,0x1.0c580407a5e35p-1
+nextUp,-0x1.e454f464be1ffp-5,-0x1.e454f464be2p-5
+nextUp,0x1.d02a4bdd0ebd8p-1,0x1.d02a4bdd0ebd7p-1
+nextUp,0x1.14cdd76d4b8dfp-9,0x1.14cdd76d4b8dep-9
+nextUp,0x1.e0a2080f509d3p4,0x1.e0a2080f509d2p4
+nextUp,0x1.381f37d3f5cd6p-1,0x1.381f37d3f5cd5p-1
+nextUp,0x1.158054cb50452p2,0x1.158054cb50451p2
+nextUp,0x1.5b2e36af1be1cp-4,0x1.5b2e36af1be1bp-4
+nextUp,-0x1.66961ded5be6ap-3,-0x1.66961ded5be6bp-3
+nextUp,-0x1.33a1f920451ffp0,-0x1.33a1f920452p0
+nextUp,0x1.511eabb05221dp-1,0x1.511eabb05221cp-1
+nextUp,-0x1.242fae41c6d6cp-1,-0x1.242fae41c6d6dp-1
+nextUp,-0x1.1774360b28c26p3,-0x1.1774360b28c27p3
+nextUp,0x1.d50670fb00411p2,0x1.d50670fb0041p2
+nextUp,-0x1.6f974900aa57fp-1,-0x1.6f974900aa58p-1
+nextUp,-0x1.15bdfc41db415p0,-0x1.15bdfc41db416p0
+nextUp,0x1.8016e77d9964fp-2,0x1.8016e77d9964ep-2
+nextUp,-0x1.3ab0226ac5151p-1,-0x1.3ab0226ac5152p-1
+nextUp,-0x1.27ef4b6c31cc5p2,-0x1.27ef4b6c31cc6p2
+nextUp,-0x1.604d629ffd6a8p-2,-0x1.604d629ffd6a9p-2
+nextUp,-0x1.a8e830ae29d51p-2,-0x1.a8e830ae29d52p-2
+nextUp,0x1.06c642cd93e74p-5,0x1.06c642cd93e73p-5
+nextUp,-0x1.6510315f22106p0,-0x1.6510315f22107p0
+nextUp,-0x1.59d954d49e322p2,-0x1.59d954d49e323p2
+nextUp,-0x1.a0d80268e728ep3,-0x1.a0d80268e728fp3
+nextUp,0x1.4750981c87bf6p-1,0x1.4750981c87bf5p-1
+nextUp,0x1.ca59601a4ecf2p1,0x1.ca59601a4ecf1p1
+nextUp,0x1.a4016ef4f07fep-1,0x1.a4016ef4f07fdp-1
+nextUp,0x1.5ae95775ad60fp-1,0x1.5ae95775ad60ep-1
+nextUp,0x1.7705ff641e54ep-1,0x1.7705ff641e54dp-1
+nextUp,-0x1.78f81f25c9ba3p-2,-0x1.78f81f25c9ba4p-2
+nextUp,0x1.2ae4ee50ec5adp-4,0x1.2ae4ee50ec5acp-4
+nextUp,-0x1.3cffd8537ef94p-3,-0x1.3cffd8537ef95p-3
+nextUp,-0x1.1dcaac99cc075p-1,-0x1.1dcaac99cc076p-1
+nextUp,0x1.6aa92508d4bd3p-1,0x1.6aa92508d4bd2p-1
+nextUp,-0x1.ee62b4748493bp-1,-0x1.ee62b4748493cp-1
+nextUp,-0x1.62b0a345a381dp0,-0x1.62b0a345a381ep0
+nextUp,-0x1.ca89336b0d6d7p0,-0x1.ca89336b0d6d8p0
+nextUp,0x1.5d52c172e660bp-1,0x1.5d52c172e660ap-1
+nextUp,-0x1.33b3a532f18efp-1,-0x1.33b3a532f18fp-1
+nextUp,0x1.5ee286d7628c6p0,0x1.5ee286d7628c5p0
+nextUp,-0x1.f54896afd80d9p1,-0x1.f54896afd80dap1
+nextUp,-0x1.7e0ed231e05fbp-1,-0x1.7e0ed231e05fcp-1
+nextUp,0x1.190d97337d16dp-2,0x1.190d97337d16cp-2
+nextUp,-0x1.47e39d27543e6p1,-0x1.47e39d27543e7p1
+nextUp,0x1.f710402c5a0b6p-1,0x1.f710402c5a0b5p-1
+nextUp,0x1.9eab86259cc5ep-1,0x1.9eab86259cc5dp-1
+nextUp,-0x1.e61993c4f1049p-3,-0x1.e61993c4f104ap-3
+nextUp,-0x1.a993a82593211p2,-0x1.a993a82593212p2
+nextUp,-0x1.dcd0767944698p-1,-0x1.dcd0767944699p-1
+nextUp,0x1.27ad12aa4aa63p-1,0x1.27ad12aa4aa62p-1
+nextUp,-0x1.0d8f21dcbd40fp0,-0x1.0d8f21dcbd41p0
+nextUp,-0x1.25ce2fc3e4012p0,-0x1.25ce2fc3e4013p0
+nextUp,-0x1.d32b06d8ec84fp0,-0x1.d32b06d8ec85p0
+nextUp,0x1.09d85d8919589p-6,0x1.09d85d8919588p-6
+nextUp,-0x1.560b1bfb41db6p0,-0x1.560b1bfb41db7p0
+nextUp,-0x1.2f96ae30cdd89p-1,-0x1.2f96ae30cdd8ap-1
+nextUp,-0x1.01755e3844e7dp-3,-0x1.01755e3844e7ep-3
+nextUp,-0x1.9f12b7eb60b02p1,-0x1.9f12b7eb60b03p1
+nextUp,0x1.460ef7006e16ap-1,0x1.460ef7006e169p-1
+nextUp,-0x1.6f2c9a0b25e78p-4,-0x1.6f2c9a0b25e79p-4
+nextUp,0x1.ccf1eb5e43126p-2,0x1.ccf1eb5e43125p-2
+nextUp,0x1.ee914a4e8319dp-1,0x1.ee914a4e8319cp-1
+nextUp,0x1.b9f2373904ccbp-1,0x1.b9f2373904ccap-1
+nextUp,-0x1.22698a06f367dp2,-0x1.22698a06f367ep2
+nextUp,0x1.bee5f900ae40ap-1,0x1.bee5f900ae409p-1
+nextUp,0x1.57c1d081e07e1p0,0x1.57c1d081e07ep0
+nextUp,0x1.32246ec86182cp2,0x1.32246ec86182bp2
+nextUp,-0x1.5ceea872790a6p1,-0x1.5ceea872790a7p1
+nextUp,0x1.db0b05d54a72fp-2,0x1.db0b05d54a72ep-2
+nextUp,0x1.afd3e9982737cp-1,0x1.afd3e9982737bp-1
+nextUp,-0x1.a646aa4a4d81fp-1,-0x1.a646aa4a4d82p-1
+nextUp,-0x1.65e897637b5f9p-3,-0x1.65e897637b5fap-3
+nextUp,-0x1.0f942a08ff30bp0,-0x1.0f942a08ff30cp0
+nextUp,0x1.dad26b69ba743p-1,0x1.dad26b69ba742p-1
+nextUp,-0x1.18c2ecb354efap0,-0x1.18c2ecb354efbp0
+nextUp,-0x1.8ec681589c041p-1,-0x1.8ec681589c042p-1
+nextUp,0x1.6c9430a270787p2,0x1.6c9430a270786p2
+nextUp,0x1.a85867e471f68p-1,0x1.a85867e471f67p-1
+nextUp,0x1.0843a878e12a1p0,0x1.0843a878e12ap0
+nextUp,0x1.6ccc6e57b1cd6p-1,0x1.6ccc6e57b1cd5p-1
+nextUp,0x1.b2aaeb34d39fbp3,0x1.b2aaeb34d39fap3
+nextUp,0x1.2abdb28b7c1e4p5,0x1.2abdb28b7c1e3p5
+nextUp,0x1.b313f8d493a33p-4,0x1.b313f8d493a32p-4
+nextUp,0x1.2be3833358578p-1,0x1.2be3833358577p-1
+nextUp,-0x1.71c37e4676141p4,-0x1.71c37e4676142p4
+nextUp,0x1.3e11db2e11d1cp-1,0x1.3e11db2e11d1bp-1
+nextUp,-0x1.0981ee2170da8p2,-0x1.0981ee2170da9p2
+nextUp,-0x1.5c8e75bf0af76p0,-0x1.5c8e75bf0af77p0
+nextUp,0x1.219e33d06f3d4p-2,0x1.219e33d06f3d3p-2
+nextUp,-0x1.573b7638ca558p-2,-0x1.573b7638ca559p-2
+nextUp,-0x1.dce03b67e91bp-1,-0x1.dce03b67e91b1p-1
+nextUp,0x1.d773763c9af9dp3,0x1.d773763c9af9cp3
+nextUp,-0x1.41215262e0d1p-1,-0x1.41215262e0d11p-1
+nextUp,0x1.24dffa399cd09p-1,0x1.24dffa399cd08p-1
+nextUp,0x1.6a2d79c75bd4p0,0x1.6a2d79c75bd3fp0
+nextUp,0x1.ccaeced5c93cbp1,0x1.ccaeced5c93cap1
+nextUp,-0x1.c2510db061757p-1,-0x1.c2510db061758p-1
+nextUp,-0x1.40258b211f9ecp-1,-0x1.40258b211f9edp-1
+nextUp,-0x1.41bb57a04554dp0,-0x1.41bb57a04554ep0
+nextUp,-0x1.582bf88c38d7p1,-0x1.582bf88c38d71p1
+nextUp,0x1.f59aec20bb862p-1,0x1.f59aec20bb861p-1
+nextUp,-0x1.15e39558d7f1p0,-0x1.15e39558d7f11p0
+nextUp,0x1.067c6d1b9c875p3,0x1.067c6d1b9c874p3
+nextUp,0x1.720a0ee1f2929p1,0x1.720a0ee1f2928p1
+nextUp,-0x1.aff57264e19dep-1,-0x1.aff57264e19dfp-1
+nextUp,0x1.045acc1c7c2efp-2,0x1.045acc1c7c2eep-2
+nextUp,-0x1.038f9095fbf4ep-3,-0x1.038f9095fbf4fp-3
+nextUp,-0x1.4a75d4c6d9f9p1,-0x1.4a75d4c6d9f91p1
+nextUp,0x1.299d935604783p-1,0x1.299d935604782p-1
+nextUp,0x1.27edf0b504754p1,0x1.27edf0b504753p1
+nextUp,-0x1.e4a6ca55e9e11p-3,-0x1.e4a6ca55e9e12p-3
+nextUp,-0x1.818f39f9060bep-1,-0x1.818f39f9060bfp-1
+nextUp,-0x1.36b15ae996101p-1,-0x1.36b15ae996102p-1
+nextUp,0x1.2dff034240e3bp2,0x1.2dff034240e3ap2
+nextUp,-0x1.c206b32a07242p1,-0x1.c206b32a07243p1
+nextUp,0x1.622128d7ead69p1,0x1.622128d7ead68p1
+nextUp,-0x1.e55d3fed82a0dp0,-0x1.e55d3fed82a0ep0
+nextUp,0x1.78c61780b267ep0,0x1.78c61780b267dp0
+nextUp,-0x1.a7cc575e5e61ap-1,-0x1.a7cc575e5e61bp-1
+nextUp,0x1.8c19aeb88f752p-2,0x1.8c19aeb88f751p-2
+nextUp,-0x1.def690507cf6bp-2,-0x1.def690507cf6cp-2
+nextUp,-0x1.17eb10ad97c13p-1,-0x1.17eb10ad97c14p-1
+nextUp,-0x1.1493191c91951p-1,-0x1.1493191c91952p-1
+nextUp,-0x1.4e5c6f56aa9adp-1,-0x1.4e5c6f56aa9aep-1
+nextUp,0x1.0f8f2deae231cp0,0x1.0f8f2deae231bp0
+nextUp,0x1.0bb8d0ee5a33dp-1,0x1.0bb8d0ee5a33cp-1
+nextUp,0x1.f453228e2a49bp2,0x1.f453228e2a49ap2
+nextUp,0x1.2bb00a8ecd186p-1,0x1.2bb00a8ecd185p-1
+nextUp,0x1.7abc047124f6ep-1,0x1.7abc047124f6dp-1
+nextUp,0x1.1b107be53002ep0,0x1.1b107be53002dp0
+nextUp,0x1.96bff92299892p1,0x1.96bff92299891p1
+nextUp,-0x1.fe95a2514fdb4p-1,-0x1.fe95a2514fdb5p-1
+nextUp,-0x1.3aab5df9db757p2,-0x1.3aab5df9db758p2
+nextUp,0x1.09114a178ef03p1,0x1.09114a178ef02p1
+nextUp,0x1.5a610cc38f488p1,0x1.5a610cc38f487p1
+nextUp,-0x1.6463a38870952p-3,-0x1.6463a38870953p-3
+nextUp,0x1.203de7acd52fdp0,0x1.203de7acd52fcp0
+nextUp,0x1.8bca2b5dddde1p-2,0x1.8bca2b5ddddep-2
+nextUp,0x1.2010056a0e9b7p-1,0x1.2010056a0e9b6p-1
+nextUp,-0x1.101cfc82211b4p-1,-0x1.101cfc82211b5p-1
+nextUp,0x1.be249fc8f9c52p-1,0x1.be249fc8f9c51p-1
+nextUp,0x1.783250d25c4fp-2,0x1.783250d25c4efp-2
+nextUp,0x1.71d19e2dc8f26p-2,0x1.71d19e2dc8f25p-2
+nextUp,0x1.0ab3f9ad495abp-1,0x1.0ab3f9ad495aap-1
+nextUp,-0x1.8e1f9722cb3eap-4,-0x1.8e1f9722cb3ebp-4
+nextUp,-0x1.f348e4e4a0a9fp-3,-0x1.f348e4e4a0aap-3
+nextUp,-0x1.4b1fa0a51eb9ap-3,-0x1.4b1fa0a51eb9bp-3
+nextUp,0x1.a428c1153bc54p2,0x1.a428c1153bc53p2
+nextUp,0x1.550447afd1e9cp-2,0x1.550447afd1e9bp-2
+nextUp,0x1.88f5e56cea93dp-1,0x1.88f5e56cea93cp-1
+nextUp,-0x1.49784bda32a1ep0,-0x1.49784bda32a1fp0
+nextUp,-0x1.ea3924a7ff3d9p1,-0x1.ea3924a7ff3dap1
+nextUp,-0x1.2fedfee49a714p-1,-0x1.2fedfee49a715p-1
+nextUp,0x1.592aad0aca4d9p0,0x1.592aad0aca4d8p0
+nextUp,-0x1.01545a95f248bp-2,-0x1.01545a95f248cp-2
+nextUp,0x1.764e065a3531fp-5,0x1.764e065a3531ep-5
+nextUp,0x1.7c608d2ea5e87p0,0x1.7c608d2ea5e86p0
+nextAfter,0x1.be08ed06ae399p-1,0x1.be08ed06ae39ap-1,-0x1.feeeaeefa83a6p0
+nextAfter,-0x1.1558e1e8299b7p0,-0x1.1558e1e8299b8p0,0x1.60d227f2f9e01p0
+nextAfter,0x1.912a35080f8b2p1,0x1.912a35080f8b3p1,-0x1.88072eb78a283p-2
+nextAfter,-0x1.e23dcc6153801p-1,-0x1.e23dcc6153802p-1,0x1.3bfd03c91e4ep8
+nextAfter,-0x1.122410b658edcp4,-0x1.122410b658eddp4,-0x1.35494eb6d5691p0
+nextAfter,-0x1.69355b8af8cd6p-1,-0x1.69355b8af8cd5p-1,-0x1.f0006d9d37145p-1
+nextAfter,-0x1.32a0dd3b6dd81p4,-0x1.32a0dd3b6dd82p4,-0x1.df3a32573fc8bp-2
+nextAfter,-0x1.6f6ec240848bfp-2,-0x1.6f6ec240848cp-2,-0x1.668e7e853506ep-2
+nextAfter,-0x1.81169faed0f51p-1,-0x1.81169faed0f52p-1,0x1.77d54e6483199p-1
+nextAfter,0x1.2d8f948b56dd7p4,0x1.2d8f948b56dd8p4,-0x1.d02d0fde59b9p1
+nextAfter,0x1.364bb6648481bp0,0x1.364bb6648481cp0,0x1.a679f94159201p-1
+nextAfter,-0x1.2ed1480b21aa2p-2,-0x1.2ed1480b21aa1p-2,-0x1.a995b18a896aep0
+nextAfter,0x1.b340ca4d97a4p-1,0x1.b340ca4d97a41p-1,-0x1.8ab2eb2634cf2p0
+nextAfter,0x1.eaa2ef7dbb9ep-1,0x1.eaa2ef7dbb9dfp-1,0x1.4dc94628ade56p0
+nextAfter,-0x1.09a5110d0e06dp0,-0x1.09a5110d0e06cp0,-0x1.2151d458f1cc9p0
+nextAfter,0x1.60da362a6212cp0,0x1.60da362a6212bp0,0x1.967dfbf52867bp0
+nextAfter,-0x1.c4e39b3bd6527p-1,-0x1.c4e39b3bd6528p-1,0x1.56333202bfbf1p-1
+nextAfter,0x1.d5a570731850ap4,0x1.d5a570731850bp4,-0x1.02688722f3b3fp0
+nextAfter,-0x1.97187568c9e9bp-1,-0x1.97187568c9e9ap-1,-0x1.81e2e09c8a0b1p2
+nextAfter,-0x1.7b2339123d502p-1,-0x1.7b2339123d503p-1,0x1.71b783b0efbfdp1
+nextAfter,0x1.7c4855534b564p1,0x1.7c4855534b565p1,-0x1.4e4cf60d4c8bfp0
+nextAfter,0x1.8bc32d4fd64f9p-1,0x1.8bc32d4fd64fap-1,-0x1.82480521fb705p0
+nextAfter,-0x1.2854a547967d3p3,-0x1.2854a547967d4p3,0x1.758478347d297p-3
+nextAfter,0x1.805683c6f76abp-1,0x1.805683c6f76aap-1,0x1.130156800e03p0
+nextAfter,-0x1.18ef725ab9968p-4,-0x1.18ef725ab9967p-4,-0x1.f146ef18a8022p-2
+nextAfter,-0x1.1f99b1d1c8feep-1,-0x1.1f99b1d1c8fefp-1,0x1.4ced4a2f389e2p-1
+nextAfter,-0x1.2611251b5806dp-2,-0x1.2611251b5806cp-2,-0x1.45f32769bed38p0
+nextAfter,-0x1.019e9cda4d56bp1,-0x1.019e9cda4d56cp1,-0x1.f103c160f70d1p-4
+nextAfter,-0x1.4bc4d28d6cdb6p2,-0x1.4bc4d28d6cdb7p2,0x1.61d7ef134d991p-1
+nextAfter,-0x1.67d2a760f5a3ap-6,-0x1.67d2a760f5a39p-6,-0x1.8c6752ff63432p-4
+nextAfter,-0x1.ab515f69190d8p2,-0x1.ab515f69190d9p2,-0x1.d72aae7ba1c68p-1
+nextAfter,-0x1.be2206d553e09p-2,-0x1.be2206d553e08p-2,-0x1.1060952b96b9ep-1
+nextAfter,0x1.cf365b29af936p-2,0x1.cf365b29af937p-2,-0x1.d288d17edddcp3
+nextAfter,-0x1.9a8387254ff5p1,-0x1.9a8387254ff51p1,0x1.d887ffbf1c225p0
+nextAfter,-0x1.d591a4ef45463p0,-0x1.d591a4ef45464p0,0x1.2248bba3318f3p0
+nextAfter,0x1.c5f0fdeba15bep-2,0x1.c5f0fdeba15bdp-2,0x1.2d4ae33b96f28p1
+nextAfter,0x1.12b003b9459cep-1,0x1.12b003b9459cfp-1,0x1.00ce7e72b7671p-1
+nextAfter,0x1.f5c5f4d5d62b7p-1,0x1.f5c5f4d5d62b8p-1,-0x1.00126d22c88dep-1
+nextAfter,0x1.10b04f432546cp0,0x1.10b04f432546dp0,-0x1.2cf01d09a9d1cp-1
+nextAfter,-0x1.98cdc00c06459p-1,-0x1.98cdc00c0645ap-1,0x1.b940443f519cdp0
+nextAfter,-0x1.bac06bffc30cdp1,-0x1.bac06bffc30cep1,-0x1.343aa5170ae4ep0
+nextAfter,0x1.150e265344e05p3,0x1.150e265344e06p3,-0x1.75b6356e210f8p-1
+nextAfter,0x1.d497e81b6cfa6p0,0x1.d497e81b6cfa7p0,0x1.9c6a2c4745f4ap-3
+nextAfter,0x1.5c7ac51d66174p-3,0x1.5c7ac51d66173p-3,0x1.cb7f5aec6eeb4p-2
+nextAfter,0x1.2ff8ab2a9ad62p0,0x1.2ff8ab2a9ad63p0,0x1.b1e04ed2de4e2p-1
+nextAfter,-0x1.04f992ba0eb58p0,-0x1.04f992ba0eb59p0,0x1.983e7b8bb7799p-1
+nextAfter,0x1.24a2da8478553p1,0x1.24a2da8478554p1,-0x1.243234bb62d2cp-2
+nextAfter,-0x1.85ee4008ad957p-2,-0x1.85ee4008ad958p-2,0x1.a5c5ca534bde7p0
+nextAfter,-0x1.997b182a9bb8p-3,-0x1.997b182a9bb7fp-3,-0x1.7889b32f872afp1
+nextAfter,0x1.efd864156ce0ep1,0x1.efd864156ce0fp1,-0x1.aa95787fc93edp1
+nextAfter,-0x1.9df023878d598p-1,-0x1.9df023878d599p-1,-0x1.2f73e50521bebp-2
+nextAfter,0x1.e72c1c9dcbedcp-3,0x1.e72c1c9dcbedbp-3,0x1.60971ac27b339p-2
+nextAfter,0x1.429a3e120ceaap0,0x1.429a3e120ceabp0,-0x1.0eb1e8536fe8bp0
+nextAfter,0x1.22e87863e519bp1,0x1.22e87863e519cp1,0x1.c6edc845c23d7p-1
+nextAfter,-0x1.b28da712af136p-1,-0x1.b28da712af137p-1,0x1.3e7c56007b11cp0
+nextAfter,0x1.34fa489be89c5p1,0x1.34fa489be89c6p1,-0x1.40a0c5e9d0fap-2
+nextAfter,0x1.19fcb20977287p3,0x1.19fcb20977288p3,-0x1.d943548d5f4b3p-5
+nextAfter,-0x1.817d9e10d3c75p1,-0x1.817d9e10d3c76p1,0x1.0d9e5aa41b3bdp2
+nextAfter,-0x1.24f917bbea9cp1,-0x1.24f917bbea9bfp1,-0x1.17908c48308f2p3
+nextAfter,-0x1.3285535c65036p0,-0x1.3285535c65035p0,-0x1.67bf9e6bd0e81p2
+nextAfter,-0x1.b83b7791e0baap0,-0x1.b83b7791e0babp0,-0x1.83b535ef83ff4p-1
+nextAfter,0x1.9125f81a5384cp-2,0x1.9125f81a5384bp-2,0x1.3b06893bb2556p0
+nextAfter,0x1.ad2b9aebd79bdp-1,0x1.ad2b9aebd79bep-1,-0x1.6300c36f4ea11p1
+nextAfter,0x1.2536e7ab2f17ep-2,0x1.2536e7ab2f17fp-2,0x1.625c3899e4f1dp-3
+nextAfter,-0x1.cb1c17d6292edp0,-0x1.cb1c17d6292eep0,0x1.402ddf503a101p0
+nextAfter,0x1.022c5ff67e8c5p0,0x1.022c5ff67e8c6p0,-0x1.ee13a25f9dcb4p3
+nextAfter,0x1.28eddab43c629p-2,0x1.28eddab43c628p-2,0x1.882dfc92fb49ap-1
+nextAfter,-0x1.01028dbd448d3p1,-0x1.01028dbd448d4p1,0x1.e9e56cfed0b34p0
+nextAfter,-0x1.5948348da9d86p-3,-0x1.5948348da9d87p-3,0x1.187bcbf7e8822p0
+nextAfter,0x1.6569c14304536p2,0x1.6569c14304537p2,-0x1.5054778b7a41fp-4
+nextAfter,-0x1.31541348909dfp2,-0x1.31541348909dep2,-0x1.846247c90221dp6
+nextAfter,-0x1.161c5cb703094p-3,-0x1.161c5cb703095p-3,0x1.f5541aff83618p1
+nextAfter,0x1.4beb4cad04695p0,0x1.4beb4cad04696p0,-0x1.91ac38ba89d5p0
+nextAfter,0x1.63c948150dd55p1,0x1.63c948150dd56p1,0x1.2dec1beb8af59p0
+nextAfter,0x1.98396629159cap-2,0x1.98396629159cbp-2,-0x1.9a25f676f5ffdp3
+nextAfter,0x1.a2e4939826476p2,0x1.a2e4939826477p2,0x1.3811e8ce43d01p0
+nextAfter,0x1.cf91f1698bbbap0,0x1.cf91f1698bbbbp0,-0x1.e036c0ca70cc9p-1
+nextAfter,0x1.0197750c62814p1,0x1.0197750c62815p1,0x1.8785e6aa38b3p-1
+nextAfter,0x1.2604374abf14ap0,0x1.2604374abf14bp0,-0x1.de65dc822a41ap-1
+nextAfter,0x1.4179ba5ebf2cp0,0x1.4179ba5ebf2c1p0,-0x1.9282734f2c477p5
+nextAfter,-0x1.9ad34119967d5p-1,-0x1.9ad34119967d6p-1,0x1.1587b953f681ep4
+nextAfter,0x1.9e6e7f25dc222p1,0x1.9e6e7f25dc223p1,-0x1.c2b2217411099p-1
+nextAfter,0x1.ae9e76e403cacp-1,0x1.ae9e76e403cadp-1,0x1.4c8dee18dd07p-7
+nextAfter,-0x1.11b2b9b348b5ep0,-0x1.11b2b9b348b5fp0,0x1.54d5f0bfc3e0fp0
+nextAfter,-0x1.1ba62c98dd46ap5,-0x1.1ba62c98dd46bp5,-0x1.e248655bfa8e2p-3
+nextAfter,0x1.053c6ed019c3fp0,0x1.053c6ed019c3ep0,0x1.741b833ba4264p0
+nextAfter,0x1.36c6119693a9fp0,0x1.36c6119693aap0,0x1.271cd019886ep0
+nextAfter,-0x1.14a41a276793ap-1,-0x1.14a41a276793bp-1,0x1.700723f91afc5p1
+nextAfter,0x1.0813380b99a9ap-1,0x1.0813380b99a9bp-1,-0x1.7c6622ee9a4fdp-1
+nextAfter,0x1.562bd1efcce1bp1,0x1.562bd1efcce1cp1,-0x1.0607dbc96d55ep3
+nextAfter,-0x1.90914d5da476ep0,-0x1.90914d5da476fp0,0x1.b5db24cebb4b2p-1
+nextAfter,-0x1.ab9eec55c7e3bp-1,-0x1.ab9eec55c7e3ap-1,-0x1.8cc010f6eb178p0
+nextAfter,0x1.2e679cc6e7224p0,0x1.2e679cc6e7225p0,0x1.30b5eb876dd6ep-1
+nextAfter,-0x1.112d5a8018aeap0,-0x1.112d5a8018aebp0,-0x1.d403dacfe3de2p-3
+nextAfter,-0x1.661c3fd6e470cp-4,-0x1.661c3fd6e470bp-4,-0x1.0b168f2c6b6ddp-2
+nextAfter,0x1.d209cbe3b1233p-1,0x1.d209cbe3b1232p-1,0x1.9fbf1b70821b9p1
+nextAfter,-0x1.14389111cc836p0,-0x1.14389111cc835p0,-0x1.2c67f46aa3c71p6
+nextAfter,0x1.393e6502546a6p1,0x1.393e6502546a7p1,-0x1.379ba570db078p0
+nextAfter,-0x1.ed6ce6384ef4ep2,-0x1.ed6ce6384ef4fp2,-0x1.37ac832cc3709p2
+nextAfter,0x1.73cbb8b795d61p4,0x1.73cbb8b795d62p4,0x1.8617316b1a779p-1
+nextAfter,0x1.3b2fa2e6c5bccp-1,0x1.3b2fa2e6c5bcdp-1,0x1.0c5acf0887cb2p-3
+nextAfter,-0x1.a81a4e1f5fd2dp1,-0x1.a81a4e1f5fd2ep1,0x1.72a39cece6988p-7
+nextAfter,-0x1.b47b120119042p-4,-0x1.b47b120119043p-4,0x1.0681dd0520a87p1
+nextAfter,0x1.c922bcbf67df4p-2,0x1.c922bcbf67df3p-2,0x1.1aac0d1be7f1p0
+nextAfter,0x1.119a9e8c2e15dp-1,0x1.119a9e8c2e15ep-1,-0x1.3e830aba61194p6
+nextAfter,-0x1.b5fde7070ac02p-5,-0x1.b5fde7070ac01p-5,-0x1.1451b0a839408p-1
+nextAfter,-0x1.411bb9b2b7d27p0,-0x1.411bb9b2b7d28p0,0x1.ed46666675a55p-1
+nextAfter,0x1.38ea05849874bp-1,0x1.38ea05849874cp-1,-0x1.fb18ec8f0c20cp-2
+nextAfter,-0x1.1534f39d7e135p-1,-0x1.1534f39d7e136p-1,0x1.78a4eedfaf3c4p0
+nextAfter,0x1.d8514ada63677p-1,0x1.d8514ada63676p-1,0x1.a4ba56fb5e95bp5
+nextAfter,-0x1.d2465e495e8f7p0,-0x1.d2465e495e8f8p0,0x1.2c92fdd2e8d32p0
+nextAfter,-0x1.86dc8707e63aap-1,-0x1.86dc8707e63abp-1,-0x1.2587435604f05p-2
+nextAfter,0x1.a723492cee1f4p0,0x1.a723492cee1f5p0,-0x1.47acb72c77762p-1
+nextAfter,0x1.8a4dc1e79fb62p-1,0x1.8a4dc1e79fb63p-1,0x1.1d2349af00cebp-1
+nextAfter,0x1.ad536251cf312p1,0x1.ad536251cf313p1,-0x1.4d0fff627210ep0
+nextAfter,-0x1.ef00c43645a3p-2,-0x1.ef00c43645a2fp-2,-0x1.5736c1d77de5bp2
+nextAfter,0x1.03558e0a72a2bp1,0x1.03558e0a72a2cp1,-0x1.8bb3ee5723bd9p0
+nextAfter,-0x1.059903c241cfbp0,-0x1.059903c241cfcp0,-0x1.959e8b56b89dbp-1
+nextAfter,-0x1.58ea3f0f2a56fp0,-0x1.58ea3f0f2a57p0,-0x1.50340dd6f0845p-3
+nextAfter,0x1.4882208f0cceep2,0x1.4882208f0ccefp2,-0x1.42e1e171eb0b6p2
+nextAfter,-0x1.3ba88c9df1697p-3,-0x1.3ba88c9df1696p-3,-0x1.8e04ae862d44ep2
+nextAfter,-0x1.dd5b75b8dc45dp1,-0x1.dd5b75b8dc45ep1,-0x1.648e1fc2e480bp-1
+nextAfter,-0x1.2aa6c715a1ad1p2,-0x1.2aa6c715a1ad2p2,-0x1.b30486358e2c5p1
+nextAfter,0x1.f02d719ee0e57p2,0x1.f02d719ee0e58p2,-0x1.3d4980849f152p-3
+nextAfter,-0x1.fcde0b5ea3b9fp-3,-0x1.fcde0b5ea3bap-3,-0x1.9351ec231b852p-3
+nextAfter,0x1.24eb83fa49e5cp-1,0x1.24eb83fa49e5bp-1,0x1.4a1a34417a1a2p1
+nextAfter,-0x1.036d6c4794c26p0,-0x1.036d6c4794c27p0,0x1.67aa7817a0d7p-2
+nextAfter,0x1.470a86b0f5795p1,0x1.470a86b0f5796p1,-0x1.0223f8be643e2p0
+nextAfter,-0x1.739de6b861d6p-1,-0x1.739de6b861d61p-1,0x1.81318046a727p-6
+nextAfter,-0x1.7cfdb659fff4p-1,-0x1.7cfdb659fff41p-1,0x1.f2d2d8bbddcb4p-1
+nextAfter,-0x1.862d750f0fc1fp0,-0x1.862d750f0fc2p0,-0x1.58cc5ef2f1669p-2
+nextAfter,-0x1.11344da901121p-1,-0x1.11344da90112p-1,-0x1.5a89a905652afp3
+nextAfter,0x1.5211661bc634bp-1,0x1.5211661bc634cp-1,-0x1.41aa7790f999ap1
+nextAfter,-0x1.3dd9e192b371bp1,-0x1.3dd9e192b371cp1,-0x1.0ee658dd025cp0
+nextAfter,0x1.8ccf3a1cb7e0ep-2,0x1.8ccf3a1cb7e0dp-2,0x1.190f4c5074b9fp0
+nextAfter,0x1.26aeb852f5c0fp0,0x1.26aeb852f5c1p0,-0x1.b5accc2fb8a9p-1
+nextAfter,0x1.3af5db50e71afp1,0x1.3af5db50e71bp1,0x1.b840b2022cc05p0
+nextAfter,0x1.04070e9aa96cep1,0x1.04070e9aa96cfp1,0x1.5cb117d184102p0
+nextAfter,0x1.7ee2cd94d2b95p0,0x1.7ee2cd94d2b96p0,-0x1.d681391227728p-1
+nextAfter,0x1.2486672587039p2,0x1.248667258703ap2,0x1.20e4c8a83353fp0
+nextAfter,0x1.10b25729ee664p-1,0x1.10b25729ee665p-1,-0x1.6cdfb8b3c1d2ep-3
+nextAfter,-0x1.05accfc2cd87ep-1,-0x1.05accfc2cd87fp-1,0x1.b76292642ac94p1
+nextAfter,0x1.1312882e464cdp1,0x1.1312882e464cep1,-0x1.f3b346a25174p-1
+nextAfter,-0x1.2e39389f91825p-7,-0x1.2e39389f91826p-7,0x1.31957b7ce603fp-2
+nextAfter,0x1.0404311fd38a1p0,0x1.0404311fd38ap0,0x1.db676eba6fed8p0
+nextAfter,-0x1.7744fb7dd7754p-1,-0x1.7744fb7dd7755p-1,0x1.075f2e9c47bf9p0
+nextAfter,0x1.bc1f6e00f5653p-3,0x1.bc1f6e00f5652p-3,0x1.3daa3d6afeb7cp2
+nextAfter,-0x1.c3fa1c5007a79p-2,-0x1.c3fa1c5007a78p-2,-0x1.78f60d3038c85p0
+nextAfter,0x1.8554149e7b9fap-4,0x1.8554149e7b9fbp-4,-0x1.102e3f3445a0fp-2
+nextAfter,-0x1.1c6206a0ed743p-1,-0x1.1c6206a0ed744p-1,-0x1.e74f2c15e4d54p-2
+nextAfter,-0x1.137691287d8b5p-2,-0x1.137691287d8b6p-2,0x1.06dee8d77e3d4p0
+nextAfter,0x1.5082525ceb9dp0,0x1.5082525ceb9d1p0,-0x1.27df8770d5364p0
+nextAfter,-0x1.16e8b2c8f8c5bp0,-0x1.16e8b2c8f8c5cp0,-0x1.a2ac01f652f22p-2
+nextAfter,-0x1.18c24796b1f6ep0,-0x1.18c24796b1f6fp0,0x1.090a349f4f2cp-3
+nextAfter,0x1.01faad9be063ap0,0x1.01faad9be063bp0,-0x1.701e1211a7b79p0
+nextAfter,0x1.99eb635ab89d1p-1,0x1.99eb635ab89d2p-1,-0x1.02f2bbb004abp1
+nextAfter,-0x1.c0b2ae0869a07p-4,-0x1.c0b2ae0869a08p-4,0x1.df7f53186a43ep0
+nextAfter,-0x1.b73d82e0c9a3dp0,-0x1.b73d82e0c9a3ep0,0x1.cc10ae0c5afe1p1
+nextAfter,0x1.129bd54ca61fp0,0x1.129bd54ca61f1p0,-0x1.db17ccd4a3f39p0
+nextAfter,0x1.a1146b7fbd789p-2,0x1.a1146b7fbd788p-2,0x1.996c59bfa19aap0
+nextAfter,-0x1.82335e167998fp4,-0x1.82335e167999p4,0x1.63f96ea33b812p-1
+nextAfter,0x1.27428424410acp0,0x1.27428424410abp0,0x1.7fa5a37c5990ap0
+nextAfter,-0x1.e222b0b6465ecp-2,-0x1.e222b0b6465edp-2,0x1.a0ef11dc9f2cep1
+nextAfter,-0x1.067fe1e10df97p1,-0x1.067fe1e10df98p1,0x1.4023b82c14d38p0
+nextAfter,0x1.418b7723e09edp0,0x1.418b7723e09eep0,-0x1.664ba9ba979ap-1
+nextAfter,-0x1.87080d5637d8cp-2,-0x1.87080d5637d8dp-2,0x1.4a6dd635b9104p-1
+nextAfter,-0x1.fc18e6d02940ap-1,-0x1.fc18e6d02940bp-1,-0x1.f19d7613c72abp-1
+nextAfter,0x1.d9d98db8c362dp1,0x1.d9d98db8c362ep1,-0x1.5d41c3f9a33dbp0
+nextAfter,-0x1.45b9cb3f31823p3,-0x1.45b9cb3f31824p3,0x1.603e322c512bap3
+nextAfter,-0x1.c71b747662ba7p-1,-0x1.c71b747662ba8p-1,-0x1.bab823fa2de24p-3
+nextAfter,0x1.1903f8b16baf3p-1,0x1.1903f8b16baf4p-1,-0x1.86c449048485p1
+nextAfter,0x1.2d7b9c45c61bbp1,0x1.2d7b9c45c61bcp1,0x1.754bcf7aa2cd2p-2
+nextAfter,-0x1.d121889bcf0edp-1,-0x1.d121889bcf0ecp-1,-0x1.d06b6c9d7c26ep3
+nextAfter,0x1.16cb05c6d4645p0,0x1.16cb05c6d4646p0,-0x1.e2d9919ca51f8p-1
+nextAfter,0x1.4bae2cc676e97p-2,0x1.4bae2cc676e96p-2,0x1.8212b8c75df29p-2
+nextAfter,0x1.ad92ab032b5b4p1,0x1.ad92ab032b5b5p1,-0x1.9ff12fc6dc92cp-3
+nextAfter,-0x1.f913004a6399dp1,-0x1.f913004a6399ep1,0x1.29b1616a10495p0
+nextAfter,0x1.f93514db1fcfp-5,0x1.f93514db1fcf1p-5,-0x1.5790d7e78012cp2
+nextAfter,-0x1.0a8f781a1d27ap-2,-0x1.0a8f781a1d27bp-2,0x1.1828e6ac11606p-2
+nextAfter,-0x1.f2b96848b118p0,-0x1.f2b96848b1181p0,-0x1.996c5e493b133p-3
+nextAfter,-0x1.6ae18cdc74a13p0,-0x1.6ae18cdc74a14p0,0x1.98a080c9ed305p3
+nextAfter,0x1.3d0661436de95p0,0x1.3d0661436de96p0,0x1.37e201923b73p-3
+nextAfter,0x1.f4d8d3f543b5p-3,0x1.f4d8d3f543b51p-3,-0x1.3f559c695c16fp-2
+nextAfter,-0x1.4da6088d207c9p2,-0x1.4da6088d207cap2,-0x1.2af134a1bc648p-2
+nextAfter,-0x1.3d16920744586p-2,-0x1.3d16920744587p-2,0x1.3696a5fd98068p-4
+nextAfter,0x1.c41e3a3208421p0,0x1.c41e3a3208422p0,0x1.766db3acfc398p-3
+nextAfter,0x1.861318513750bp-2,0x1.861318513750cp-2,0x1.10c6e3b329af8p-3
+nextAfter,0x1.090651142e1abp0,0x1.090651142e1acp0,-0x1.74cef95bb9b64p0
+nextAfter,0x1.a9afabf9d5443p5,0x1.a9afabf9d5444p5,0x1.d065e0ec9c193p-1
+nextAfter,-0x1.c134856a41724p-3,-0x1.c134856a41723p-3,-0x1.2452964c029f3p0
+nextAfter,-0x1.2f346c7a138c1p0,-0x1.2f346c7a138c2p0,0x1.e562ef5cbebe8p-1
+nextAfter,-0x1.52c791174a317p-2,-0x1.52c791174a318p-2,0x1.56a9ee5847c78p-2
+nextAfter,-0x1.e423e909074fap-1,-0x1.e423e909074fbp-1,-0x1.95c79cb8c6e94p-1
+nextAfter,0x1.7873f2f45fc5bp-2,0x1.7873f2f45fc5ap-2,0x1.500a588920313p1
+nextAfter,-0x1.79121493e8b55p-1,-0x1.79121493e8b56p-1,0x1.f252fbb8e02e9p0
+nextAfter,0x1.123d12f953371p-1,0x1.123d12f953372p-1,-0x1.006ee4c39945ep-1
+nextAfter,0x1.fc2f68afca109p0,0x1.fc2f68afca10ap0,0x1.ce207ceb1a883p0
+nextAfter,0x1.d430566acb85bp1,0x1.d430566acb85cp1,-0x1.71e632ff3e8c9p-2
+nextAfter,-0x1.4688d70c88797p-1,-0x1.4688d70c88798p-1,0x1.065d6da6343b4p0
+nextAfter,0x1.0f474783bacaap-1,0x1.0f474783bacabp-1,0x1.44bc0e877138dp-3
+abs,0x1.93d505df96a7bp1,-0x1.93d505df96a7bp1
+abs,0x1.772aabf17e9fap1,-0x1.772aabf17e9fap1
+abs,0x1.37482866cf6fbp0,0x1.37482866cf6fbp0
+abs,0x1.2f2d86b7d412bp0,-0x1.2f2d86b7d412bp0
+abs,0x1.1472bc84f162dp1,-0x1.1472bc84f162dp1
+abs,0x1.6f1aef4f2128fp-1,0x1.6f1aef4f2128fp-1
+abs,0x1.30f9423f14eeap0,-0x1.30f9423f14eeap0
+abs,0x1.a1c4694bb59efp-3,-0x1.a1c4694bb59efp-3
+abs,0x1.1103fecbf63fp0,-0x1.1103fecbf63fp0
+abs,0x1.2790898fcdf8ap1,-0x1.2790898fcdf8ap1
+abs,0x1.85960bf9370e4p2,-0x1.85960bf9370e4p2
+abs,0x1.f4e26ba23a8f5p-2,0x1.f4e26ba23a8f5p-2
+abs,0x1.10c18cfc2266p1,-0x1.10c18cfc2266p1
+abs,0x1.d7b107ca6e1afp3,-0x1.d7b107ca6e1afp3
+abs,0x1.ddee38e42203ep1,-0x1.ddee38e42203ep1
+abs,0x1.28da1d4f6bc26p2,-0x1.28da1d4f6bc26p2
+abs,0x1.3d5c63e8ecb65p-3,0x1.3d5c63e8ecb65p-3
+abs,0x1.3f055832d962dp2,0x1.3f055832d962dp2
+abs,0x1.1bece9ca0b776p5,-0x1.1bece9ca0b776p5
+abs,0x1.0bc00f4c3d999p-1,-0x1.0bc00f4c3d999p-1
+abs,0x1.68fd72aee66edp-2,-0x1.68fd72aee66edp-2
+abs,0x1.05123af8e5f4bp2,-0x1.05123af8e5f4bp2
+abs,0x1.ae1da006f080cp-6,0x1.ae1da006f080cp-6
+abs,0x1.90f8995fe2c91p-2,-0x1.90f8995fe2c91p-2
+abs,0x1.a87467f025ae1p-1,-0x1.a87467f025ae1p-1
+abs,0x1.e7fc319a4a286p-1,-0x1.e7fc319a4a286p-1
+abs,0x1.c93f851b2b5acp0,-0x1.c93f851b2b5acp0
+abs,0x1.103f892adf582p-1,0x1.103f892adf582p-1
+abs,0x1.6b0c4defd374p1,0x1.6b0c4defd374p1
+abs,0x1.07a14b2653758p0,0x1.07a14b2653758p0
+abs,0x1.8d534af6cd513p-2,-0x1.8d534af6cd513p-2
+abs,0x1.11d810c944e87p-4,-0x1.11d810c944e87p-4
+abs,0x1.b829be3ebdb13p-1,0x1.b829be3ebdb13p-1
+abs,0x1.fbeb13841fb27p-2,-0x1.fbeb13841fb27p-2
+abs,0x1.37d5860b925e1p-5,-0x1.37d5860b925e1p-5
+abs,0x1.3dd9a55c7b433p0,-0x1.3dd9a55c7b433p0
+abs,0x1.2bc0c7abed8a9p1,0x1.2bc0c7abed8a9p1
+abs,0x1.fd5a3d1160a29p2,0x1.fd5a3d1160a29p2
+abs,0x1.688a787f82432p-1,-0x1.688a787f82432p-1
+abs,0x1.951f0f59938e3p-3,0x1.951f0f59938e3p-3
+abs,0x1.a56f068d6f1c2p-2,-0x1.a56f068d6f1c2p-2
+abs,0x1.b734658226c62p1,0x1.b734658226c62p1
+abs,0x1.1edb19bf46cb3p-3,-0x1.1edb19bf46cb3p-3
+abs,0x1.e22fb685f7d56p-1,-0x1.e22fb685f7d56p-1
+abs,0x1.892b4e3724ad9p-1,0x1.892b4e3724ad9p-1
+abs,0x1.0ffcf5c95424cp0,-0x1.0ffcf5c95424cp0
+abs,0x1.6fd78d74ab1b4p-1,-0x1.6fd78d74ab1b4p-1
+abs,0x1.3ae03f54dd5efp5,0x1.3ae03f54dd5efp5
+abs,0x1.cc99e81a48a56p-3,0x1.cc99e81a48a56p-3
+abs,0x1.23749e32db3d7p0,0x1.23749e32db3d7p0
+abs,0x1.1a7f86b7edab4p1,-0x1.1a7f86b7edab4p1
+abs,0x1.023b9d65c66a8p0,-0x1.023b9d65c66a8p0
+abs,0x1.4a1fb6a7915fdp0,-0x1.4a1fb6a7915fdp0
+abs,0x1.af81ac251ece4p-3,-0x1.af81ac251ece4p-3
+abs,0x1.2923d510927d4p-1,-0x1.2923d510927d4p-1
+abs,0x1.4e77c7d585158p-2,0x1.4e77c7d585158p-2
+abs,0x1.f4b87199262b2p-2,0x1.f4b87199262b2p-2
+abs,0x1.18f7365dfc421p-1,-0x1.18f7365dfc421p-1
+abs,0x1.1924ecd75569p0,0x1.1924ecd75569p0
+abs,0x1.3f49e95c8e8cep0,-0x1.3f49e95c8e8cep0
+abs,0x1.2720bb83cb3a6p0,0x1.2720bb83cb3a6p0
+abs,0x1.1989d4d299b09p-2,0x1.1989d4d299b09p-2
+abs,0x1.40cce21585167p-2,0x1.40cce21585167p-2
+abs,0x1.6c17acb277c0fp-3,-0x1.6c17acb277c0fp-3
+abs,0x1.00f459acf7914p0,-0x1.00f459acf7914p0
+abs,0x1.438edcbe43ed7p-3,0x1.438edcbe43ed7p-3
+abs,0x1.bd85ef8c20593p-6,0x1.bd85ef8c20593p-6
+abs,0x1.df891eda559c8p-1,-0x1.df891eda559c8p-1
+abs,0x1.6e5b75d1137dp0,-0x1.6e5b75d1137dp0
+abs,0x1.02e678934f154p0,0x1.02e678934f154p0
+abs,0x1.d2d8c6b8d0cd8p-1,0x1.d2d8c6b8d0cd8p-1
+abs,0x1.4459aafa382f2p0,-0x1.4459aafa382f2p0
+abs,0x1.d1577c82fe71fp1,0x1.d1577c82fe71fp1
+abs,0x1.6a6fb3441e988p-1,-0x1.6a6fb3441e988p-1
+abs,0x1.3abccc514a8c2p1,0x1.3abccc514a8c2p1
+abs,0x1.55d0a948b9f51p0,-0x1.55d0a948b9f51p0
+abs,0x1.419af57d62a18p5,-0x1.419af57d62a18p5
+abs,0x1.d7374f447eb99p-1,0x1.d7374f447eb99p-1
+abs,0x1.1591ca359bf86p0,-0x1.1591ca359bf86p0
+abs,0x1.56227bd3b5c0ep0,0x1.56227bd3b5c0ep0
+abs,0x1.0d669e52d26eep0,0x1.0d669e52d26eep0
+abs,0x1.55967a2c5f14ep-1,0x1.55967a2c5f14ep-1
+abs,0x1.21c92c1da676ap-2,0x1.21c92c1da676ap-2
+abs,0x1.fa1f74f8ccfap-6,0x1.fa1f74f8ccfap-6
+abs,0x1.12f3cceec5f58p4,-0x1.12f3cceec5f58p4
+abs,0x1.f79f3804c644ep-2,0x1.f79f3804c644ep-2
+abs,0x1.077734a841ac4p0,0x1.077734a841ac4p0
+abs,0x1.6eb70a69e7edbp-7,-0x1.6eb70a69e7edbp-7
+abs,0x1.7b1acb6262a38p-5,0x1.7b1acb6262a38p-5
+abs,0x1.26bf90d99bad7p3,0x1.26bf90d99bad7p3
+abs,0x1.15e178c6e9cp-3,0x1.15e178c6e9cp-3
+abs,0x1.3db9d902c913dp-1,-0x1.3db9d902c913dp-1
+abs,0x1.5dc144017990dp2,0x1.5dc144017990dp2
+abs,0x1.57c20767d2d27p0,0x1.57c20767d2d27p0
+abs,0x1.51d561635d354p-1,-0x1.51d561635d354p-1
+abs,0x1.0767340df1842p-4,-0x1.0767340df1842p-4
+abs,0x1.6fe0b7cce7cacp-2,0x1.6fe0b7cce7cacp-2
+abs,0x1.b6cd599938293p1,0x1.b6cd599938293p1
+abs,0x1.6f4f9e1225456p0,0x1.6f4f9e1225456p0
+abs,0x1.e7fa55fb7eccep2,0x1.e7fa55fb7eccep2
+abs,0x1.e90530c032792p-1,-0x1.e90530c032792p-1
+abs,0x1.aede143746faap-2,0x1.aede143746faap-2
+abs,0x1.6969e23784517p-6,-0x1.6969e23784517p-6
+abs,0x1.28e79aec5c026p3,-0x1.28e79aec5c026p3
+abs,0x1.ce037c05e44c8p3,-0x1.ce037c05e44c8p3
+abs,0x1.9ceb675a53092p0,0x1.9ceb675a53092p0
+abs,0x1.e9100a74f2906p-3,-0x1.e9100a74f2906p-3
+abs,0x1.2e45cd1f857cbp0,0x1.2e45cd1f857cbp0
+abs,0x1.2fc7655c2a88cp0,-0x1.2fc7655c2a88cp0
+abs,0x1.f41aa97894034p-2,-0x1.f41aa97894034p-2
+abs,0x1.8f78641653a81p0,0x1.8f78641653a81p0
+abs,0x1.c891dfa01be47p-1,-0x1.c891dfa01be47p-1
+abs,0x1.14ada2fcadc78p0,-0x1.14ada2fcadc78p0
+abs,0x1.61ff113bad7cap-2,0x1.61ff113bad7cap-2
+abs,0x1.fe4f83a15e2bp0,0x1.fe4f83a15e2bp0
+abs,0x1.abf03b3e3555dp0,-0x1.abf03b3e3555dp0
+abs,0x1.36aeceb0a212fp2,0x1.36aeceb0a212fp2
+abs,0x1.4fd78714a7b1ap-1,0x1.4fd78714a7b1ap-1
+abs,0x1.b44cc28a57d79p-3,-0x1.b44cc28a57d79p-3
+abs,0x1.403f7b6e94691p-1,-0x1.403f7b6e94691p-1
+abs,0x1.1a3cf368dc818p-4,0x1.1a3cf368dc818p-4
+abs,0x1.e0927ac119806p-2,0x1.e0927ac119806p-2
+abs,0x1.19cdadc198e92p3,0x1.19cdadc198e92p3
+abs,0x1.e79c9a1248809p-1,-0x1.e79c9a1248809p-1
+abs,0x1.54e193436987ap-3,0x1.54e193436987ap-3
+abs,0x1.693883c2944e3p-1,0x1.693883c2944e3p-1
+abs,0x1.1610075970857p0,-0x1.1610075970857p0
+abs,0x1.ffd1d6b52e1f3p-1,-0x1.ffd1d6b52e1f3p-1
+abs,0x1.8e440475d4b95p0,-0x1.8e440475d4b95p0
+abs,0x1.3458e2df37c7ap3,0x1.3458e2df37c7ap3
+abs,0x1.5296b97c17ad7p-1,-0x1.5296b97c17ad7p-1
+abs,0x1.7bd42777c3a3cp0,-0x1.7bd42777c3a3cp0
+abs,0x1.f4011e1c00b13p-1,0x1.f4011e1c00b13p-1
+abs,0x1.effdb5c5f6168p1,0x1.effdb5c5f6168p1
+abs,0x1.106cfc6aa32dbp-1,-0x1.106cfc6aa32dbp-1
+abs,0x1.0891330243a0bp0,-0x1.0891330243a0bp0
+abs,0x1.2bb3ae2cd64ccp0,0x1.2bb3ae2cd64ccp0
+abs,0x1.be9ff1ff5cfbp-5,-0x1.be9ff1ff5cfbp-5
+abs,0x1.08f773894eb8bp1,-0x1.08f773894eb8bp1
+abs,0x1.c7b5126250ef1p0,0x1.c7b5126250ef1p0
+abs,0x1.5b72114574e27p-2,-0x1.5b72114574e27p-2
+abs,0x1.32da8c745294p1,0x1.32da8c745294p1
+abs,0x1.cba8780008dcbp-2,0x1.cba8780008dcbp-2
+abs,0x1.186280b392bep4,0x1.186280b392bep4
+abs,0x1.8b8c0931b034cp0,-0x1.8b8c0931b034cp0
+abs,0x1.5fa67dd961167p-1,-0x1.5fa67dd961167p-1
+abs,0x1.551e21d78f0d4p-1,0x1.551e21d78f0d4p-1
+abs,0x1.22b4cdfbcb362p2,0x1.22b4cdfbcb362p2
+abs,0x1.ca225fdeac97fp-4,0x1.ca225fdeac97fp-4
+abs,0x1.0b0315413a0adp-1,0x1.0b0315413a0adp-1
+abs,0x1.ab4f4dc47ce3dp-3,-0x1.ab4f4dc47ce3dp-3
+abs,0x1.459687e380122p-1,0x1.459687e380122p-1
+abs,0x1.2f865e72c5265p0,-0x1.2f865e72c5265p0
+abs,0x1.34f6f6cb1934ep0,0x1.34f6f6cb1934ep0
+abs,0x1.432e98ef925b8p0,-0x1.432e98ef925b8p0
+abs,0x1.030bc46593191p1,0x1.030bc46593191p1
+abs,0x1.b98a6750454a2p1,-0x1.b98a6750454a2p1
+abs,0x1.8c7a3a12eee03p-1,-0x1.8c7a3a12eee03p-1
+abs,0x1.fe3058a015c36p0,0x1.fe3058a015c36p0
+abs,0x1.4d5d66f59a092p2,-0x1.4d5d66f59a092p2
+abs,0x1.74fcf42a3e1e6p-2,-0x1.74fcf42a3e1e6p-2
+abs,0x1.65ed78fde4a9fp-1,0x1.65ed78fde4a9fp-1
+abs,0x1.d6ad78f43f9fp-2,-0x1.d6ad78f43f9fp-2
+abs,0x1.1bf0d35c15f61p0,-0x1.1bf0d35c15f61p0
+abs,0x1.c234de2271c65p-1,-0x1.c234de2271c65p-1
+abs,0x1.a7ad8ccd0f414p-1,-0x1.a7ad8ccd0f414p-1
+abs,0x1.b91cb0c0fa85ep-1,0x1.b91cb0c0fa85ep-1
+abs,0x1.121ac693ebb86p-3,0x1.121ac693ebb86p-3
+abs,0x1.774634c5bc94fp1,0x1.774634c5bc94fp1
+abs,0x1.23736fad28ac2p0,-0x1.23736fad28ac2p0
+abs,0x1.16dcf13a36185p0,-0x1.16dcf13a36185p0
+abs,0x1.82f85e5afa85ap-1,0x1.82f85e5afa85ap-1
+abs,0x1.895fc8b8eacc6p-1,0x1.895fc8b8eacc6p-1
+abs,0x1.2117248907393p-3,-0x1.2117248907393p-3
+abs,0x1.f1f1146df8bfep-1,-0x1.f1f1146df8bfep-1
+abs,0x1.4d08b68590db6p1,0x1.4d08b68590db6p1
+abs,0x1.0c2eedacd78ecp2,-0x1.0c2eedacd78ecp2
+abs,0x1.04ff93904e7a1p0,0x1.04ff93904e7a1p0
+abs,0x1.52aea1019dbc7p0,0x1.52aea1019dbc7p0
+abs,0x1.49086e1eb7f06p2,0x1.49086e1eb7f06p2
+abs,0x1.0b51b71c9c682p0,-0x1.0b51b71c9c682p0
+abs,0x1.3200aefc70fc2p-2,0x1.3200aefc70fc2p-2
+abs,0x1.e2e55f712f1adp-2,0x1.e2e55f712f1adp-2
+abs,0x1.5ea7722f6926cp-1,-0x1.5ea7722f6926cp-1
+abs,0x1.605dda7bbb498p-3,0x1.605dda7bbb498p-3
+abs,0x1.f5e9671f15694p-4,0x1.f5e9671f15694p-4
+abs,0x1.4f51d4031a0dp1,0x1.4f51d4031a0dp1
+abs,0x1.9f16ddc8cc68p-1,-0x1.9f16ddc8cc68p-1
+abs,0x1.da1e2e2f3ba9ap1,-0x1.da1e2e2f3ba9ap1
+abs,0x1.3e8a3a1ab480dp0,0x1.3e8a3a1ab480dp0
+abs,0x1.38e94bfc0c46ep1,0x1.38e94bfc0c46ep1
+abs,0x1.85788c2b568c8p0,0x1.85788c2b568c8p0
+abs,0x1.3f840392c269p0,-0x1.3f840392c269p0
+abs,0x1.cd26590ce463ap-7,-0x1.cd26590ce463ap-7
+abs,0x1.5e41a655a608ep-3,0x1.5e41a655a608ep-3
+abs,0x1.aa8028d9180efp0,-0x1.aa8028d9180efp0
+abs,0x1.11f51d15d857fp0,-0x1.11f51d15d857fp0
+abs,0x1.672f3ae9686cp0,-0x1.672f3ae9686cp0
+abs,0x1.89d73545edf5ap-2,0x1.89d73545edf5ap-2
+abs,0x1.152d198dcbd0ep2,0x1.152d198dcbd0ep2
+atan2,0x1.de03edb049d13p-1,0x1.8531a596c72ddp0,0x1.2010ab87fdf6dp0
+atan2,0x1.5e0006fe03d5ep0,0x1.c182771ea4203p0,0x1.733d7681a0201p-2
+atan2,0x1.b72d4f4b19fddp-4,0x1.301d6da490bbdp-2,0x1.612ec509c4202p1
+atan2,0x1.6f866e02214e2p1,0x1.2351cd82c823bp0,-0x1.06d812d67873ap2
+atan2,-0x1.0b52faa4294e2p1,-0x1.8e2cbf42c945fp-2,-0x1.c580a7fc9515bp-3
+atan2,0x1.cf2522c614544p-2,0x1.7d2347a2a0dd1p-1,0x1.883636d3453dap0
+atan2,0x1.890fffc7530aap-3,0x1.a4d671182277ep-1,0x1.0eb7570fae77p2
+atan2,0x1.a6f9610e27639p0,0x1.cefa08776cab6p-2,-0x1.2e54c0dcddf09p-5
+atan2,-0x1.5ea763bb781efp1,-0x1.fcf1dc252265dp0,-0x1.2b2e4e65498dcp2
+atan2,0x1.97705aba63a9cp0,0x1.d48096493194ap2,-0x1.374eb130f3a5p-3
+atan2,-0x1.37b0fe54312dap0,-0x1.4a82d8a0972abp0,0x1.e7762fe006ed3p-2
+atan2,0x1.55af893e47505p-2,0x1.c29ff37dccd13p-1,0x1.44feece352863p1
+atan2,0x1.e79c3c35f399bp0,0x1.752f79cfd059fp1,-0x1.02eefddee1837p0
+atan2,-0x1.985b3b66967cfp0,-0x1.02a40ab498803p8,-0x1.9313481211377p2
+atan2,0x1.ebc6d113c5787p0,0x1.47e0d187a983ep0,-0x1.df0bc161eaf0ep-2
+atan2,0x1.24643d4b7307bp0,0x1.c500dc3114dd9p0,0x1.9e0679427dbcbp-1
+atan2,0x1.8075840902432p-1,0x1.365917ef27714p0,0x1.4c8992bb60496p0
+atan2,0x1.4bca202ed05bdp1,0x1.772950cedf728p-1,-0x1.324df7fca4f85p0
+atan2,-0x1.8a7ecc4cdab06p1,-0x1.5b61bc78e19a7p-3,-0x1.6bdd688222debp1
+atan2,-0x1.7dfc6760ba829p0,-0x1.6468153072616p0,0x1.c181fa014bbffp-4
+atan2,0x1.067687fca9579p1,0x1.a106a730216ffp-2,-0x1.b1e4ecbdc6b6dp-3
+atan2,-0x1.aaf01c5d7b691p0,-0x1.9253b2abd0f6cp2,-0x1.38f60891bbacbp-1
+atan2,0x1.c60716ff8b4e5p0,0x1.ded02fca4aaccp1,-0x1.89b9e49345cbcp-1
+atan2,0x1.d589c41922022p0,0x1.0456351e08dfdp2,-0x1.18beb9570a313p0
+atan2,0x1.6dea06954837bp-2,0x1.849cec7964a43p-2,0x1.043565f785b81p0
+atan2,0x1.d1b8b75ca0805p0,0x1.bfa160b08cdf7p-1,-0x1.c632f73f14dfcp-3
+atan2,0x1.a498ca4fb0bc5p-2,0x1.010d5c02134edp0,0x1.271dbba8fa0abp1
+atan2,0x1.cba2802a80af5p-2,0x1.3feeced139a2dp-1,0x1.4c1ebc6c3c97p0
+atan2,-0x1.6bb2871a033dap1,-0x1.e2f34e0f5f988p-1,-0x1.8606a5e36c881p1
+atan2,0x1.1e2c1bae7d344p-2,0x1.1fca5abfa28d3p-3,0x1.f56b92435c166p-2
+atan2,-0x1.2d97b06159e9ap0,-0x1.95ad099b4ffbap-1,0x1.501303e00fa1dp-2
+atan2,0x1.709095033bc0ap1,0x1.8b8012a0223bap-2,-0x1.7071fcced3a65p0
+atan2,-0x1.0e6ae461133f2p1,-0x1.2b5cc52a3cf34p0,-0x1.6864a45b28908p-1
+atan2,-0x1.30b6cec1fc3f2p0,-0x1.acf7dd9105681p1,0x1.572cd3952f421p0
+atan2,0x1.370509592bb79p0,0x1.1777716e04b44p-1,0x1.9f833a4b4c096p-3
+atan2,0x1.7de31c93532acp1,0x1.5ff6c65ef376ap-2,-0x1.13f48c186e1c8p1
+atan2,0x1.ae9074154b5eap-3,0x1.3b0d32e25bbafp-1,0x1.711a84da4c808p1
+atan2,0x1.d665ce6a0df3cp-2,0x1.f00bdaf915ee6p-2,0x1.f564b5ae2ab47p-1
+atan2,-0x1.24546839d5b5fp1,-0x1.6bcd13101c4d2p-2,-0x1.3a9e6f6d70c5cp-2
+atan2,0x1.b0b4973d0e301p-3,0x1.89b90df4f741bp-2,0x1.caebbbdbb7369p0
+atan2,0x1.01f719228a78p1,0x1.ce7c2ec5315c8p-1,-0x1.b89e4d2564028p-2
+atan2,-0x1.789052f3b2dc7p0,-0x1.3a30f0aabfdebp1,0x1.f798c6ae52b61p-3
+atan2,-0x1.2d3cbab22d24p-2,-0x1.507136d9a808p0,0x1.159f593069f8dp2
+atan2,-0x1.a917d9f1c7243p0,-0x1.e5f48d5274b6cp-1,-0x1.5dc0db2921ab6p-4
+atan2,0x1.7fde965bf75f6p1,0x1.1879ea9a3f83ap-4,-0x1.e85693e92bd12p-2
+atan2,-0x1.37321703b449ep-1,-0x1.5678e01a6da7ap0,0x1.ec4d3620d0bdep0
+atan2,-0x1.48851ef932712p0,-0x1.8d2218d992ac1p-1,0x1.d5be246627fdp-3
+atan2,0x1.609789f81f64dp0,0x1.54a5a5ed0a069p3,0x1.0afa9ca5db82ap1
+atan2,0x1.821ae4a866496p1,0x1.79b65fcbdac1fp-1,-0x1.774c1b6003141p2
+atan2,0x1.14a8aa61cb474p-2,0x1.62d5ae5a96817p-1,0x1.404f660747c32p1
+atan2,0x1.72c718376a293p0,0x1.6e7770b244647p2,0x1.68c890c719b54p-1
+atan2,0x1.8f2e449945382p1,0x1.e442bbdf44b94p-2,-0x1.49056da0024d3p4
+atan2,0x1.40ff4e69cabaap0,0x1.b985a770343b2p0,0x1.2198e0b9d8d86p-1
+atan2,-0x1.e2b69f2c7b8a5p-13,-0x1.ee045e5e8d48bp-4,0x1.05fea7c172b9ap9
+atan2,-0x1.62313f6cb77bp0,-0x1.9873918570a35p0,0x1.3586d6eb4034p-2
+atan2,0x1.a210376fa870cp-1,0x1.958578988276p-1,0x1.7d06dbbc83cfcp-1
+atan2,0x1.8c129ae734679p0,0x1.9adca1b305d52p0,0x1.36d53bd11117cp-5
+atan2,-0x1.4196e5881496ap-1,-0x1.f977843e6d1d2p-1,0x1.5c03b1b1397e1p0
+atan2,0x1.c6e4a0a217f9bp-2,0x1.7a682e6a5d087p-3,0x1.8d84fdf370e1ep-2
+atan2,-0x1.17494c09f4f49p0,-0x1.a6724ea3a4c16p0,0x1.b7aeb0c75bfb7p-1
+atan2,-0x1.769ba827e371ep1,-0x1.114d061d2e95ep-2,-0x1.38edcb6d51326p0
+atan2,-0x1.888fe8d4addf5p1,-0x1.89e8bc6b0ef05p-1,-0x1.48f5709f268f7p3
+atan2,0x1.53d830906ecfp1,0x1.4c1cc00421dbap0,-0x1.39ebc36d9eb3fp1
+atan2,0x1.dff17c7821d6cp0,0x1.4ca941e6f8208p1,-0x1.a16e0565eb6b7p-1
+atan2,-0x1.5e0acc5f8fa83p-2,-0x1.01bd6aa09efd9p-1,0x1.6a30fb1f64f7dp0
+atan2,-0x1.6f33096e2714cp0,-0x1.a090328de346ap1,0x1.c9798e65adb9bp-2
+atan2,-0x1.a8eb5e1bb1255p0,-0x1.94664cc1227aep0,-0x1.20d79cf55f344p-3
+atan2,0x1.a3b503a18cc39p-1,0x1.9b54e5610ff14p-2,0x1.8001d5a6b8da1p-2
+atan2,-0x1.0fd6e19af269ep1,-0x1.6206ad4eae709p0,-0x1.b4fd0b775e25p-1
+atan2,0x1.fae70394d2c5p-4,0x1.5249bb08021cp-2,0x1.53f19d1ca151p1
+atan2,-0x1.29a0832eebf8dp0,-0x1.1c96da5e6fc3fp1,0x1.ec51a5852bfefp-1
+atan2,-0x1.7e6b861b81ef1p-1,-0x1.2a298c65321p-2,0x1.420ac5a0e085ep-2
+atan2,-0x1.742fea3c19d5bp1,-0x1.aa4dc36acc419p-1,-0x1.bf58b46f897f4p1
+atan2,0x1.078c9ce3d28bcp-1,0x1.1aab5553a169fp0,0x1.f3c3ce535d04bp0
+atan2,-0x1.4ea1d1782dbe1p-2,-0x1.1ac709ff8ecc6p0,0x1.a125f33f1e745p1
+atan2,0x1.18a1758a0aeacp-3,0x1.1b257d57e6401p-1,0x1.00ad22300d8c1p2
+atan2,-0x1.54f133eca1efep-5,-0x1.062c7be3ee3aap-2,0x1.897c055a404b6p2
+atan2,0x1.db66a72b7feb7p-1,0x1.0c2a245ff88d3p-2,0x1.9139391cabeb7p-3
+atan2,-0x1.36a51f11e0a19p1,-0x1.34d94e40c206cp0,-0x1.63f0e9f526d3dp0
+atan2,-0x1.56e0fce629779p-1,-0x1.bb76e79222ffep-2,0x1.180e60c28dd0dp-1
+atan2,0x1.1555fc07b00dp0,0x1.954dd20260f1bp0,0x1.adb8675b4478dp-1
+atan2,0x1.8242b6b8dc774p1,0x1.9a2f1c20f8cb6p-6,-0x1.9b997997aa3acp-3
+atan2,0x1.c9f77561fdda3p-1,0x1.04c5e032acc82p1,0x1.a2990c116f182p0
+atan2,0x1.06ae73edd64f8p1,0x1.afe9a377db5bbp-1,-0x1.c342047c5e69ep-2
+atan2,-0x1.0925a20bab4c3p1,-0x1.02e714ca716aap0,-0x1.1b534b24dc808p-1
+atan2,0x1.0318b83509e4ap0,0x1.53e60fb0dda16p0,0x1.a8f809c1ee6d2p-1
+atan2,-0x1.1c163bdeb02cp1,-0x1.8324618f989a3p0,-0x1.2578f25491111p0
+atan2,-0x1.509d46bb514dbp-3,-0x1.11db57a457979p-3,0x1.9cc945e5ab0e9p-1
+atan2,-0x1.273d736490657p-3,-0x1.e62a841d979dp-1,0x1.a2a03f25d4f12p2
+atan2,0x1.5d211bb9a4f16p-1,0x1.1979327f1dda2p-1,0x1.5aba887618f13p-1
+atan2,0x1.f99ef79bfe351p0,0x1.cabcf958e7b22p-1,-0x1.888bc54c3d127p-2
+atan2,-0x1.69d9687d7e301p1,-0x1.48c15fcf05e9fp-3,-0x1.f91123678c42dp-2
+atan2,-0x1.95683b903b191p0,-0x1.25b5c01517032p1,-0x1.e231fdffb84c1p-6
+atan2,-0x1.a3937ba3870a3p-1,-0x1.fdfa9b8718bbfp-2,0x1.dc587bb5598fbp-2
+atan2,0x1.d53cd872fe0b9p-4,0x1.e65900eeed15fp-4,0x1.082c408376464p0
+atan2,0x1.9b565b8da9814p0,0x1.fcff459d37763p-3,-0x1.253a8897ee4b5p-7
+atan2,0x1.4da18efc303a4p1,0x1.82ad70acbf6b7p0,-0x1.4626ca1c67ec6p1
+atan2,0x1.604db2b36a6e5p-2,0x1.ac15184e794f7p-4,0x1.2ab1717453984p-2
+atan2,0x1.2012611f36814p0,0x1.0e343be9dc285p1,0x1.02108970390f7p0
+atan2,0x1.b72104f7430a1p0,0x1.06f82022d9733p-1,-0x1.323c7773d129fp-4
+atan2,-0x1.d86db4c7e68fcp0,-0x1.15fff12ca5807p1,-0x1.394d52d5023d1p-1
+atan2,-0x1.bf6905834b3ebp0,-0x1.75abb1869d4bep2,-0x1.0b33cbeef85b1p0
+atan2,-0x1.19f27ea9add42p1,-0x1.adcf68cc0ca0bp0,-0x1.3aa4f4cda49a5p0
+atan2,0x1.1306a149435bp1,0x1.70eefafe5917p0,-0x1.e127fb7ac364dp-1
+atan2,0x1.065c279976392p-1,0x1.4d44ea2be9449p0,0x1.28378318fb1a8p1
+atan2,0x1.0b42d6b5b60d3p0,0x1.b82ba68eeaecap0,0x1.0004f4f2b9327p0
+atan2,-0x1.82e8284d431c9p1,-0x1.46ccb8a2d679ep-4,-0x1.55fec3def5839p-1
+atan2,0x1.f57bf8bd7c88dp-2,0x1.22bb569e3959ep-1,0x1.10b5b96e5ea49p0
+atan2,-0x1.63bf11e016f7dp-5,-0x1.efdc0bc4c9265p-4,0x1.649a61b038e17p1
+atan2,0x1.f108930cd5e6fp0,0x1.932ebb0529ffcp3,-0x1.39725a3cb358fp2
+atan2,0x1.81f09ceac7869p1,0x1.5fe4076ec4b1bp-2,-0x1.5a08f1681a41ap1
+atan2,-0x1.4b77647f83b03p0,-0x1.7fc8488ed5daap-3,0x1.b2cd533f2ac1ep-5
+atan2,0x1.101599c7ae0bep1,0x1.7979dcd1b104fp1,-0x1.d3ee7246ffaebp0
+atan2,-0x1.7b4853c777fbfp1,-0x1.596b976af1eb8p-1,-0x1.dec68c99aa45ap1
+atan2,-0x1.7453cfed8453fp1,-0x1.8ebf10238b687p-1,-0x1.a478b2a6f406dp1
+atan2,0x1.6142b2fc8b2c8p1,0x1.27e2fd81b5286p1,-0x1.7088c6d494f5dp2
+atan2,0x1.10cb9ed389c7ap1,0x1.b277dc0802e77p-1,-0x1.10a47abc4594bp-1
+atan2,-0x1.84f3f975b062p-1,-0x1.025d458a8188cp0,0x1.1002c8cd205d3p0
+atan2,-0x1.45988b51f4ab8p0,-0x1.e7f58fefb33f3p0,0x1.2cc049c474f57p-1
+atan2,-0x1.830ebac024c1fp1,-0x1.4045312f6bdbcp-3,-0x1.528bad6448038p0
+atan2,0x1.c8bb6ff9d42e3p0,0x1.f93e9e6e08b08p-1,-0x1.b5c332f661ca3p-3
+atan2,-0x1.465edfae23b18p1,-0x1.1f89c7d0ccc82p0,-0x1.abc2121cfab0ap0
+atan2,0x1.8565facce856ap0,0x1.d460bf318d18fp0,0x1.74d420fa2210dp-4
+atan2,0x1.0a0b88c880adap1,0x1.140ce10bdcd4cp1,-0x1.3324b090e8ee9p0
+atan2,0x1.5743b0ba8309cp-3,0x1.77d22d03e36c2p-2,0x1.15a687f77a71dp1
+atan2,-0x1.27ddefe6d9ffdp1,-0x1.149def9def705p-1,-0x1.f9d384ccbcc0bp-2
+atan2,0x1.404d2e333699ap1,0x1.989bc87d39ca8p-1,-0x1.12d6dc77dea54p0
+atan2,0x1.df721ca61dep-4,0x1.b2c02bf4a8d96p-1,0x1.ce25d8f777814p2
+atan2,-0x1.b3266f9c4939p0,-0x1.26854202382ebp2,-0x1.31a9f064ac1f9p-1
+atan2,0x1.8b84119b2494cp1,0x1.1688fb5dd5857p-4,-0x1.50e9627d3598dp0
+atan2,-0x1.f98f119fd229p0,-0x1.f3346f229d591p0,-0x1.aae318faf10a1p-1
+atan2,0x1.3983f65ece5e1p0,0x1.717c62e3fd8f4p2,0x1.0a81a9cf2bf7bp1
+atan2,-0x1.6932ebbc0a0fap0,-0x1.c92cf129a6261p1,0x1.26dbabb91199ap-1
+atan2,0x1.7a70a47a07ebep0,0x1.25cfb390c3934p1,0x1.b4281314ab214p-3
+atan2,0x1.c798a348bd1d6p0,0x1.e26ba3d7617afp0,-0x1.9907f947b4d63p-2
+atan2,-0x1.ec5187825e41bp0,-0x1.86ee51516a48ap1,-0x1.1f762d273aa95p0
+atan2,-0x1.73d313d8a95dep0,-0x1.7952cd69e1a04p-2,0x1.66f2af5e4527ap-5
+atan2,-0x1.7b64745f8ab0cp0,-0x1.5e15714a4c344p2,0x1.f2ae5421949dcp-2
+atan2,0x1.749f1ecb63879p-1,0x1.cfc73426ef23ep0,0x1.0447b54270e27p1
+atan2,-0x1.0aabe585fc8bap1,-0x1.7462ea39e2844p-1,-0x1.a31dbcb30d94bp-2
+atan2,-0x1.dd882de264022p0,-0x1.143c00f69d8fbp-1,-0x1.4f39c4340c992p-3
+atan2,-0x1.b50e6f8ffeedep0,-0x1.a8c4cc4862be3p-1,-0x1.d298460311b81p-4
+atan2,0x1.59f326f55e2p-1,0x1.c21458620b4b8p-3,0x1.18c1c5f7cbaf8p-2
+atan2,-0x1.e8638ced79c02p-1,-0x1.00a539603b877p2,0x1.6c0e1f5008171p1
+atan2,0x1.953f61e4f0744p0,0x1.0f8c3405d7a69p1,-0x1.a8243d0f95c4p-6
+atan2,-0x1.1a47bfebeeca8p1,-0x1.08ad8ea32e6d2p1,-0x1.85a2f8fd8f9afp0
+atan2,-0x1.660582e3c4a18p-2,-0x1.5d413746cc898p-2,0x1.def17c3f1dca3p-1
+atan2,-0x1.c5f468ac0cc53p0,-0x1.61793f458a773p1,-0x1.223d67c9babfap-1
+atan2,0x1.35e032a100decp1,0x1.b90c7fac94cd9p-1,-0x1.f62b796c51d15p-1
+atan2,-0x1.0d74faaea9b69p0,-0x1.126cdf0fefbdbp-1,0x1.38f65b42f19e1p-2
+atan2,-0x1.2d5bfee8358dp-4,-0x1.f21811e033cafp-4,0x1.a65bf6789b3adp0
+atan2,0x1.fead2bcbda9a7p-3,0x1.7f2398c779c02p-2,0x1.78232e66cfe1fp0
+atan2,-0x1.a8eff7b510feep0,-0x1.375321eeb9911p-3,-0x1.bd145be95394ep-7
+atan2,0x1.888bddd2168b6p1,0x1.3dd43a7b8369fp-3,-0x1.08fbe2f16fa6ep1
+atan2,0x1.89d07ec3a987dp1,0x1.4ae2b3dcfee33p-1,-0x1.3e1dcfa5a2338p3
+atan2,-0x1.04505b38996eep-2,-0x1.2da56f69e264dp0,0x1.223abfcf0e517p2
+atan2,0x1.8a68bdd90bdb3p1,0x1.ff097deb57743p-4,-0x1.08a5878452126p1
+atan2,0x1.1b492e98b09f4p1,0x1.98f1db91e4747p-2,-0x1.31fd43259db6ep-2
+atan2,-0x1.cdeca28129f61p0,-0x1.0ddb5ec777b1ep3,-0x1.00d69e4f78288p1
+atan2,-0x1.8a732af02607bp-2,-0x1.32d285280db1fp-1,0x1.7a5cd769730f5p0
+atan2,-0x1.d8e363a972f7bp-4,-0x1.53e99b8f23c3ep0,0x1.6e63b6d4cbd22p3
+atan2,0x1.50dac88f484bbp-4,0x1.74a21b041d867p-5,0x1.1a8d4f888e88bp-1
+atan2,-0x1.816dd590faa0dp-2,-0x1.9213b4b67e0f6p-2,0x1.fca66e9b5d54ap-1
+atan2,0x1.a9a5ee00ac2dap0,0x1.8bae1f4196731p2,-0x1.23b31b9f32697p-1
+atan2,-0x1.faf0ce42c982ep-3,-0x1.29eb4169cb92cp1,0x1.26b8c05863f5bp3
+atan2,-0x1.eaaa5f467858fp0,-0x1.285c4e6cdf603p4,-0x1.ab2cbbadc1ddcp2
+atan2,0x1.ff4616f547a1ep0,0x1.8f8a31e1ca847p-2,-0x1.6af7802be4411p-3
+atan2,0x1.cfc8e24b5ea9fp-3,0x1.87bfad3f0dbc1p-1,0x1.a90e8f3a59402p1
+atan2,-0x1.8c8e52931226p1,-0x1.1ccf95145909p-5,-0x1.98f596f1b4914p-1
+atan2,0x1.30b7fbf4dda28p1,0x1.e86261670c322p-3,-0x1.006b6e47fcd0bp-2
+atan2,-0x1.357969aa6c1fep-9,-0x1.73bb55f449d6ep-3,0x1.337fda2a0394cp6
+atan2,-0x1.3d8aabdd357b4p1,-0x1.a304e63201fa1p0,-0x1.0d8170f940b17p1
+atan2,0x1.53f514034b516p-1,0x1.5c7a0f825fe66p-1,0x1.bd565e2aecf06p-1
+atan2,-0x1.5537c9fb835f4p-1,-0x1.05594de0c6ab9p0,0x1.4c4d84ae99b4bp0
+atan2,0x1.91f6f316cdc95p0,0x1.0f89a40ddf756p5,0x1.59dbc42aaec81p-6
+atan2,0x1.2d38e3c622bdbp1,0x1.c1aed8b1f0143p-1,-0x1.bf160907fe663p-1
+atan2,0x1.3a0ab45adb6ecp1,0x1.dcdfaf809f942p-1,-0x1.21fe4001672c3p0
+atan2,0x1.482e04a12cf2cp1,0x1.96b5b564c76d5p-1,-0x1.37f4dc2a85229p0
+atan2,-0x1.81fa9ebfcb2afp0,-0x1.04d705862e8c4p1,0x1.078d1ec038372p-3
+atan2,-0x1.4760cd439a41p0,-0x1.88b2f42d8944ap2,0x1.d8208920c4bep0
+atan2,-0x1.8bf3a7e26c76ap1,-0x1.a5e48f83b1e79p-1,-0x1.113551b415d1ep4
+atan2,0x1.5ece1300019a2p-1,0x1.2d5d5f1151862p0,0x1.70c22c9b532dfp0
+atan2,0x1.75203047182d4p0,0x1.4d6f118d774ffp3,0x1.2f74303910affp0
+atan2,-0x1.1bbb29dcfb463p0,-0x1.0ea2cc1ee2516p-1,0x1.0dd73d3be7cb4p-2
+atan2,0x1.045677713c2f9p0,0x1.90363e597b217p0,0x1.eeff07e652f6cp-1
+atan2,0x1.59e138f72538fp0,0x1.57c714f819c95p2,0x1.3312c3f0441d2p0
+atan2,-0x1.4de5bb8a088p-1,-0x1.a9638aec111dap-3,0x1.168b6bc596bb7p-2
+atan2,-0x1.8300988d4fbbcp1,-0x1.8bdf43770c699p-5,-0x1.a0eb5ece9ec6p-2
+atan2,0x1.07ce9b0b696eap-1,0x1.080444b721de1p0,0x1.d23d1e62ebe9ap0
+atan2,0x1.8165148cf64ap1,0x1.8755b7b0e38d6p-1,-0x1.7425d5e8213fdp2
+atan2,-0x1.7dbffaedfd904p1,-0x1.656aad633ba21p-1,-0x1.164f9c7898dbfp2
+atan2,0x1.14e8210eff74p1,0x1.ebba1b0512f93p0,-0x1.4b0c862007029p0
+atan2,0x1.8586c56cb0933p1,0x1.2e545fdd7b153p2,-0x1.7ebfbbb4eba28p5
+atan2,-0x1.75153d5f09e71p1,-0x1.f184a4d2915ddp-2,-0x1.0d6304e29e117p1
+atan2,-0x1.bb77ae1fdab8dp0,-0x1.cb2a56fefe0d3p1,-0x1.2b39678ca203fp-1
+atan2,0x1.8e5a65499458cp1,0x1.2894a3902f614p-4,-0x1.3a8549dc9b0ccp1
+atan2,-0x1.b91719f497b41p-3,-0x1.df4d1dd714f07p-2,0x1.11dcbf1574eefp1
+atan2,0x1.305e7fb3b741p1,0x1.6b4faec249ebp-2,-0x1.7b6c5993b8edfp-2
+atan2,0x1.edd2c7199e7ddp0,0x1.54448cf99a1a1p1,-0x1.fd8485d86e3d1p-1
+atan2,-0x1.3401bfed63a95p0,-0x1.66e0a92ea0f2ep-2,0x1.147299409fd4cp-3
+atan,-0x1.33165704aa45cp0,-0x1.48ce7d70e6a0ap1
+atan,-0x1.de5952193ae66p-1,-0x1.5a57f5de17072p0
+atan,0x1.06f3498431431p-2,0x1.0ce2f7d413cdbp-2
+atan,0x1.09880a837be19p-1,0x1.243625fb54079p-1
+atan,0x1.2fe6d3eaa8704p-1,0x1.597506ebdf281p-1
+atan,-0x1.0fcd8b99dfc03p0,-0x1.caabf588a3cc5p0
+atan,-0x1.a49bc345118c4p-2,-0x1.bdf9ec63e50ffp-2
+atan,0x1.5ac7ec427eac8p-1,0x1.9bc23b48b72d8p-1
+atan,0x1.41945d04de0cp0,0x1.8951863009812p1
+atan,-0x1.6c74432d0e219p0,-0x1.afcb6cee7c77ap2
+atan,-0x1.41c41c994a946p-1,-0x1.741794913226p-1
+atan,-0x1.2443ef2c3806fp0,-0x1.17bc6ed44f9f3p1
+atan,0x1.1128bf0f3871cp-1,0x1.2e694c7b05c15p-1
+atan,0x1.d4698288791cap-1,0x1.4ca3b26d8d82ep0
+atan,0x1.afcc60f0bcb0ep-1,0x1.1f89a522d3316p0
+atan,0x1.6d125a9b7bb56p0,0x1.b7186b7ade84ep2
+atan,0x1.ea0dadeb6b082p-1,0x1.6b7073c21e62cp0
+atan,-0x1.78aba01034404p-3,-0x1.7cf9d37c81681p-3
+atan,-0x1.5c930372a9d6cp0,-0x1.2d7bde8a004bdp2
+atan,-0x1.6d98da8db709bp-1,-0x1.bbb3f45e04d65p-1
+atan,0x1.9829a4523d781p-1,0x1.061c755ae1857p0
+atan,-0x1.2c06abf12181cp0,-0x1.2fbf66a7eebc8p1
+atan,-0x1.34f2d200715c2p0,-0x1.50034d8a3d3b3p1
+atan,-0x1.c7fcc5d31d0a2p-2,-0x1.e8b9e81bde969p-2
+atan,-0x1.17da370518f56p0,-0x1.ee98d1470ab33p0
+atan,-0x1.4d3468cfee20ap0,-0x1.cfe9d17d70632p1
+atan,-0x1.b52fd5ded91dfp-1,-0x1.25b43aad343c1p0
+atan,-0x1.3521e834ac2acp0,-0x1.50bd7036a1a14p1
+atan,0x1.c383a281514a8p-2,0x1.e33ed607c28fep-2
+atan,0x1.0eb0e18395494p0,0x1.c606bace6103bp0
+atan,0x1.26feeb6ecedd6p-1,0x1.4ca55ad8d1706p-1
+atan,-0x1.fe2c5be73da28p-1,-0x1.8b95bd1c4cdefp0
+atan,0x1.0f98bcd9dd79dp-1,0x1.2c4eb5ee7b93fp-1
+atan,0x1.355f89cd233a4p0,0x1.51b222746e1dbp1
+atan,0x1.4abb434831bcep0,0x1.bf061660d03d2p1
+atan,0x1.353715d6ccacdp-1,0x1.613e9203ee421p-1
+atan,-0x1.eb96418ceb959p-1,-0x1.6dc2e3d405926p0
+atan,0x1.2fe249360fc78p-1,0x1.596e6aef899d8p-1
+atan,0x1.c881a53fe929bp-1,0x1.3d1a43a0ec22bp0
+atan,-0x1.926d325cac869p-1,-0x1.004d88d506e55p0
+atan,0x1.0f06eb6365d4ap-1,0x1.2b8adad3f7469p-1
+atan,-0x1.ef1f54763a778p-2,-0x1.0cd8a9c8498a9p-1
+atan,-0x1.3c8c4e149aad4p-2,-0x1.47083d40a57bep-2
+atan,-0x1.0c6e0ae142604p0,-0x1.bccc22763b743p0
+atan,-0x1.2809e19754ddcp0,-0x1.22ff391284474p1
+atan,-0x1.16c7aa436594p0,-0x1.e98fe178c5c6ep0
+atan,0x1.6aff81476fbb2p-4,0x1.6bf38e022962bp-4
+atan,0x1.4fdd199943858p0,0x1.e371388d4c39fp1
+atan,0x1.7a4bb67128b3p0,0x1.56cd60b54446ep3
+atan,-0x1.3059942eaa704p-2,-0x1.39a3e3bf39e3ep-2
+atan,-0x1.3afd7b1c0e3a4p-2,-0x1.4550f332fd795p-2
+atan,0x1.347d64811efa8p0,0x1.4e3626bfb4c66p1
+atan,-0x1.12a6812d28c97p-3,-0x1.144f0f9b4d222p-3
+atan,-0x1.bfc52ead8cf51p-1,-0x1.3242afc2d5d0bp0
+atan,-0x1.b943df8d2808dp-1,-0x1.2a78891234ae7p0
+atan,-0x1.d545f6a23e406p-1,-0x1.4dccad3454358p0
+atan,0x1.d3a6888178694p-1,0x1.4b9e1e2213afap0
+atan,-0x1.78855f59205fbp-1,-0x1.cf31b2af98fbfp-1
+atan,0x1.24fc92601a428p0,0x1.19d4fbe477393p1
+atan,0x1.36cb4173e1262p-1,0x1.639466b78c0f4p-1
+atan,-0x1.5429610212e13p0,-0x1.033c41b92f0c3p2
+atan,-0x1.6aa01d66ca951p0,-0x1.9b8135c13d607p2
+atan,0x1.7e9f911fb35b1p0,0x1.a34720e578bp3
+atan,-0x1.eb5861b0dc1aap-1,-0x1.6d64dcdac7ca9p0
+atan,0x1.3b6335e848a48p0,0x1.6b38851191959p1
+atan,0x1.9bc09f7f59a63p-1,0x1.09d075c2661e9p0
+atan,-0x1.5272e2663d8a2p-2,-0x1.5f561c854244bp-2
+atan,-0x1.5f4b029f05c7p-1,-0x1.a33e03ca2098bp-1
+atan,-0x1.65dccee7071ddp0,-0x1.6e7824e12489fp2
+atan,-0x1.4dc9067ff1774p0,-0x1.d40cebe43f5f1p1
+atan,0x1.efd23c5ce2b7p-2,0x1.0d4ad22f826e2p-1
+atan,0x1.c2ee2f5856f38p-1,0x1.362170d1b0351p0
+atan,-0x1.85dc612ef9b63p-2,-0x1.99dba0d07634p-2
+atan,0x1.ca97437ccf1e8p-4,0x1.cc8446c65c6c5p-4
+atan,0x1.1411864cf386ap-1,0x1.32594c18ceadep-1
+atan,0x1.7296c27cf33d3p0,0x1.0275bea97e23dp3
+atan,0x1.782a4d0bb9283p-4,0x1.7939f249ae61ep-4
+atan,0x1.1bb405cbc8839p0,0x1.00af2f404991cp1
+atan,-0x1.3b37b44c27275p-2,-0x1.45910de53f2b7p-2
+atan,-0x1.f18b875c89894p-1,-0x1.76f9a6aa08e08p0
+atan,-0x1.d915b11dc1407p-1,-0x1.52feed902fba7p0
+atan,0x1.a88f73a728872p-1,0x1.177b006d6a75dp0
+atan,-0x1.f3eaa84bd5d49p-3,-0x1.fe1698c27c477p-3
+atan,-0x1.0d78245ba4e99p-2,-0x1.13dde72124156p-2
+atan,0x1.54786c45385c6p-1,0x1.9177dd1ebae81p-1
+atan,-0x1.3fdfde6471406p0,-0x1.80983c9ee91edp1
+atan,-0x1.c24edb8cfd9e4p-1,-0x1.355d26b233bbp0
+atan,0x1.27e6a825ce0bep-1,0x1.4def4a28afc6cp-1
+atan,-0x1.671235f445918p-9,-0x1.671270d28f888p-9
+atan,-0x1.168af6cc8109ap-3,-0x1.1845eb7ce10dep-3
+atan,-0x1.0af38f85b3ffdp0,-0x1.b6ea28d59635fp0
+atan,-0x1.17cad0f7c3cd5p0,-0x1.ee4ff932ba75fp0
+atan,-0x1.dfa325de2bae3p-2,-0x1.030bcce52d3fp-1
+atan,0x1.9fb60472c6027p-1,0x1.0df5fe264e83ap0
+atan,0x1.4566ccb67f798p0,0x1.9e3c08443230cp1
+atan,-0x1.81c26948658ddp0,-0x1.f3ea63670b06p3
+atan,-0x1.64332a21e0951p-3,-0x1.67d5e748d5bdbp-3
+atan,-0x1.4748db7a8e569p-3,-0x1.4a1975881b88cp-3
+atan,0x1.669aeb9f7d992p0,0x1.74d92729a23bbp2
+atan,0x1.b6b04a9422536p-1,0x1.2772fb93942cfp0
+atan,-0x1.33816bb25942fp-1,-0x1.5eba0ed9aaae7p-1
+atan,0x1.4348ea6b35971p-4,0x1.43f5327378dcdp-4
+atan,-0x1.7e422af591522p0,-0x1.9b8c2286641ep3
+atan,0x1.5d78b6712df06p-1,0x1.a0355485836d6p-1
+atan,0x1.885669177868p-1,0x1.eccacb067b7adp-1
+atan,-0x1.12a0f62d61ab8p-2,-0x1.1968856cc5476p-2
+atan,-0x1.7fcd7f2f67864p0,-0x1.be5ec2f68c954p3
+atan,-0x1.849099f32d7a5p-1,-0x1.e593597e6fc7ap-1
+atan,-0x1.14a1e3eaf0c74p-1,-0x1.331d79f2731f6p-1
+atan,0x1.0584405998b0bp-1,0x1.1ee99f427692bp-1
+atan,0x1.4fa26243ec533p-5,0x1.4fd27e42fee18p-5
+atan,0x1.23f76c5b291dap0,0x1.16e006acb8705p1
+atan,0x1.6a2c00d87d8cbp0,0x1.96c1f56bb3ecp2
+atan,0x1.ce2ede3cfe213p-1,0x1.4465757dbedfbp0
+atan,-0x1.96de145a3522ap-3,-0x1.9c4e5eeeecbbep-3
+atan,0x1.fc986a4e02d85p-1,0x1.88ecbcd2d2faep0
+atan,-0x1.7d2bdd9dd963dp-1,-0x1.d7b88883d1ccp-1
+atan,-0x1.6ccc6912a2b52p-2,-0x1.7d0e90eb3979p-2
+atan,-0x1.7cce0b00139a5p-1,-0x1.d70b2efdbf7d6p-1
+atan,-0x1.c84f09989be7dp-1,-0x1.3cda2a813a76cp0
+atan,0x1.49997b5bd68fbp0,0x1.b7ab14bfee8e3p1
+atan,-0x1.8a17b210ea8f4p-2,-0x1.9ec69523e8b5dp-2
+atan,0x1.c2c2f910f5a49p-5,0x1.c337932bafc7fp-5
+atan,0x1.30b5e4abffe2bp-1,0x1.5aa2ae345e042p-1
+atan,-0x1.6f0d238644b13p0,-0x1.d038428eb72a2p2
+atan,0x1.eb0f0065197c4p-1,0x1.6cf583df7da58p0
+atan,-0x1.17f88069bcfb3p0,-0x1.ef28488b9b37ap0
+atan,0x1.9f15a9cdc1a55p-6,0x1.9f2c676017f62p-6
+atan,0x1.7a8eb9b9f6c8cp0,0x1.5aa1c940df06fp3
+atan,0x1.084798bf4f5bp-1,0x1.228deadc77f93p-1
+atan,-0x1.94d86a3730fcap-1,-0x1.02bc6fc2b9406p0
+atan,0x1.7f716012bca93p0,0x1.b5bdf80140d62p3
+atan,-0x1.0cd2bf725cd1fp0,-0x1.be61f0ae4b482p0
+atan,-0x1.81e572dd21298p-1,-0x1.e0881c5defdfbp-1
+atan,0x1.39aaae5bda58ep-6,0x1.39b47e2cbc2e1p-6
+atan,-0x1.48b9f68aa1f3ep0,-0x1.b225466841e6p1
+atan,0x1.5b28184ab3592p-1,0x1.9c60b29b278adp-1
+atan,0x1.0f7ef35db0cedp0,0x1.c961c61bb393cp0
+atan,0x1.0f0f5b6d2caa4p-1,0x1.2b962e4e16b09p-1
+atan,0x1.a5c56336af70cp-2,0x1.bf5c2d5f26beep-2
+atan,0x1.680ec9ce7c643p0,0x1.81f872a48680cp2
+atan,-0x1.48d23d579898ep0,-0x1.b2bd3e6325baep1
+atan,0x1.007eec1dce73dp-2,0x1.05ff912205895p-2
+atan,-0x1.a69fd5ea0e91p-5,-0x1.a6ffec34fdae1p-5
+atan,-0x1.f7938809d3e5dp-1,-0x1.80a0b8352e767p0
+atan,0x1.f515ff0fef504p-2,0x1.10a975f570853p-1
+atan,0x1.902e97ef8d67dp-1,0x1.fc2185cdb31a7p-1
+atan,0x1.6c5893306ecc8p-2,0x1.7c8ab62ecbab7p-2
+atan,0x1.b8c6aad242c76p-2,0x1.d62e14e11b1e7p-2
+atan,-0x1.1549e561cc3bfp-2,-0x1.1c4567ed7dd9bp-2
+atan,-0x1.0012912d25ea6p0,-0x1.8ef1e714578d8p0
+atan,-0x1.a2ec60e1153ccp-2,-0x1.bbf914ae73ba7p-2
+atan,0x1.55d9a44b6a28p0,0x1.0ac904e60e827p2
+atan,0x1.5e12c30d51e21p0,0x1.366bd74b5179dp2
+atan,0x1.7944f6639bf71p0,0x1.488ff56433813p3
+atan,0x1.9189a07a9863fp-1,0x1.fed42e46b2658p-1
+atan,0x1.4bc249840a266p0,0x1.c5e64aa13a641p1
+atan,-0x1.e0e2d63a8acaep-1,-0x1.5df559f13edbcp0
+atan,0x1.c358a9a45837p-3,0x1.cacc5dc9f46b9p-3
+atan,-0x1.a12e8b47bb59ap-1,-0x1.0f84d28c6afc3p0
+atan,0x1.beaa600735ac2p-1,0x1.30ebca35d471fp0
+atan,-0x1.3446c8ecbbfcfp-1,-0x1.5fdc5566d7c64p-1
+atan,0x1.42a6ca35be6dcp0,0x1.8efd0101ce554p1
+atan,-0x1.14b7ab3e48f35p-1,-0x1.333b180971a27p-1
+atan,-0x1.c192207f495cp-1,-0x1.347561bd4d841p0
+atan,0x1.dbe77966530f2p-1,0x1.56e7f4b249cd2p0
+atan,-0x1.1096376ddecc2p-2,-0x1.17369abf533b1p-2
+atan,0x1.83b362fd21348p-4,0x1.84dcdc2401be9p-4
+atan,0x1.834bdf0a516b8p-1,0x1.e32bfcdef37f3p-1
+atan,-0x1.8aae6465ee3d2p-1,-0x1.f153b4e67b34bp-1
+atan,-0x1.0cdd6ce8d2931p-1,-0x1.28a5bd4c72f68p-1
+atan,0x1.ab12e9bcfca44p-2,0x1.c5b07ae2644dep-2
+atan,-0x1.d8f3f0d9d900ep-1,-0x1.52d07a14b002ep0
+atan,0x1.55e73c1c43e7p0,0x1.0b07857cdb669p2
+atan,-0x1.993310a26c8c3p-1,-0x1.072cdbc0c3265p0
+atan,-0x1.1d9a4ed57ce1ap0,-0x1.058691ac7450ap1
+atan,-0x1.b4f4e4258ab19p-1,-0x1.256fffde053cdp0
+atan,0x1.78415f04d47b4p0,0x1.3b999693d4792p3
+atan,0x1.84665e9dbda69p0,0x1.2a2b7551ba18fp4
+atan,0x1.8ce99d073e7cap-1,0x1.f5ae9abbf5021p-1
+atan,0x1.aedf77914b5b2p-2,0x1.ca3dddb2e10edp-2
+atan,-0x1.4c5ad4fe03441p-1,-0x1.8485cc6541d79p-1
+atan,-0x1.68a1270c8a7ecp0,-0x1.87628ace570afp2
+atan,-0x1.26d36b5410e32p-1,-0x1.4c678181ece16p-1
+atan,0x1.090b91cfd10dep0,0x1.af7fe532b4115p0
+atan,0x1.6dc1a49fa96dap-2,0x1.7e25daf2404ebp-2
+atan,0x1.118cffbae8892p0,0x1.d21f2971059d7p0
+atan,0x1.4c8b94010a5f2p-1,0x1.84d2a2b940b3dp-1
+atan,0x1.f5ad4729db9adp-2,0x1.110a9555d7137p-1
+atan,0x1.7a8d8f3aa2a3ep-1,0x1.d2e70a2cd9268p-1
+atan,-0x1.bc217e08d139bp-3,-0x1.c33a03fbf97d3p-3
+atan,-0x1.297dd7227bb5ep-1,-0x1.5034dd186346cp-1
+atan,-0x1.ce6b7fbcba912p-1,-0x1.44b47fc0f18e4p0
+atan,0x1.93289102e9a14p-1,0x1.010965205f73fp0
+atan,-0x1.46d8b28b0f8f2p-1,-0x1.7be99431179dfp-1
+atan,-0x1.7e6490113792fp-1,-0x1.d9fbeffa46b75p-1
+atan,-0x1.8fe43874effc4p-8,-0x1.8fe57db7b553ep-8
+atan,-0x1.d37c2a2e19a16p-2,-0x1.f6eb6496635d2p-2
+atan,-0x1.9cb07072a00c7p-1,-0x1.0aca1ef2353e8p0
+atan,0x1.9c487bff5a805p-2,0x1.b41b45eb4edbp-2
+ceil,0x1.0p1,0x1.1529c4488417ep0
+ceil,0x1.0p1,0x1.8fa0a5e8cee32p0
+ceil,-0x0.0p0,-0x1.8819e79d62b8p-1
+ceil,-0x1.0p3,-0x1.1824560a8c094p3
+ceil,0x1.0p0,0x1.c7993d0a6bab1p-5
+ceil,0x1.0p0,0x1.d3f48401ae71dp-2
+ceil,-0x0.0p0,-0x1.fe333a8929a13p-4
+ceil,-0x1.0p0,-0x1.d3f9245636b8cp0
+ceil,-0x1.0p0,-0x1.38b161487c697p0
+ceil,-0x1.8p1,-0x1.c652252a89289p1
+ceil,0x1.0p0,0x1.8a14843eadfc1p-1
+ceil,-0x1.2p3,-0x1.2a33602af54ccp3
+ceil,-0x1.0p1,-0x1.3c7c5d5fb992ap1
+ceil,0x1.0p0,0x1.3268391790ec4p-1
+ceil,0x1.0p0,0x1.9094f869a3e47p-1
+ceil,0x1.0p0,0x1.8af45bc4cf8a4p-2
+ceil,0x1.0p2,0x1.d5c53dc486547p1
+ceil,-0x0.0p0,-0x1.275b5fb11c3a7p-1
+ceil,0x1.8p1,0x1.5bf1bc1ca6e71p1
+ceil,0x1.0p0,0x1.b20f092a375bep-2
+ceil,0x1.0p0,0x1.90e6fb00878ffp-4
+ceil,0x1.8p1,0x1.6645838752797p1
+ceil,-0x1.0p0,-0x1.090e646874031p0
+ceil,-0x0.0p0,-0x1.244624fd8840ep-1
+ceil,0x1.0p1,0x1.1dbcee46033afp0
+ceil,-0x0.0p0,-0x1.369578820b61fp-1
+ceil,0x1.0p0,0x1.dd12b37cb5c3dp-1
+ceil,-0x0.0p0,-0x1.aed83bf3664f7p-1
+ceil,0x1.0p0,0x1.79c6eb37d3bddp-2
+ceil,-0x0.0p0,-0x1.d3a80f7edc393p-9
+ceil,0x1.0p0,0x1.250e28aaafd2fp-1
+ceil,0x1.0p1,0x1.a130baee91cb9p0
+ceil,0x1.0p1,0x1.3b015aff7a8cap0
+ceil,-0x1.0p0,-0x1.27ed2173f606ap0
+ceil,0x1.8p1,0x1.2bc99fc2d28c7p1
+ceil,-0x0.0p0,-0x1.6407f78e81b44p-4
+ceil,-0x1.0p3,-0x1.0133e906d864ep3
+ceil,-0x1.0p1,-0x1.43744f4b6b838p1
+ceil,0x1.0p0,0x1.21f601ab8929bp-2
+ceil,-0x1.0p0,-0x1.0821a86abccecp0
+ceil,-0x0.0p0,-0x1.3e013d62a6722p-5
+ceil,0x1.0p1,0x1.ddeac791f09dep0
+ceil,0x1.0p0,0x1.577b2bc7f7031p-6
+ceil,0x1.8p1,0x1.03d2215d352dap1
+ceil,-0x0.0p0,-0x1.60e23c27385ap-1
+ceil,0x1.8p1,0x1.38514c0fe5f1dp1
+ceil,0x1.0p1,0x1.0b728ebae056bp0
+ceil,0x1.0p0,0x1.ebc2a1f6424cdp-1
+ceil,-0x0.0p0,-0x1.dee83d06f7f71p-1
+ceil,-0x0.0p0,-0x1.66edb73e176c4p-1
+ceil,0x1.0p0,0x1.fe84691bb10dap-2
+ceil,-0x1.0p1,-0x1.01915fd676f7ap1
+ceil,0x1.0p0,0x1.ff569cc31f4cdp-1
+ceil,-0x1.0p0,-0x1.b14772771033bp0
+ceil,0x1.0p0,0x1.27516fd308a65p-2
+ceil,0x1.0p0,0x1.e5837ca4f09d2p-1
+ceil,-0x1.0p0,-0x1.173346f7f2aa6p0
+ceil,0x1.0p1,0x1.7c11f2024962bp0
+ceil,-0x0.0p0,-0x1.a83c9b9ceca0ap-1
+ceil,-0x1.0p0,-0x1.422206d211aa1p0
+ceil,0x1.0p1,0x1.1ae5cbbea5764p0
+ceil,0x1.0p1,0x1.6eb6884552292p0
+ceil,0x1.f8p5,0x1.f0f5662565457p5
+ceil,-0x1.0p0,-0x1.4b85db6fcd1eep0
+ceil,-0x0.0p0,-0x1.dc8865f77e0c6p-1
+ceil,0x1.0p0,0x1.2ff388d1bfc0ap-1
+ceil,0x1.0p2,0x1.feb52d333684dp1
+ceil,-0x0.0p0,-0x1.8684a25997011p-1
+ceil,0x1.8p1,0x1.1065bca309eabp1
+ceil,-0x1.0p1,-0x1.2bad263cc2bbdp1
+ceil,0x1.0p3,0x1.c03e4c3d9a2fbp2
+ceil,-0x1.0p3,-0x1.0d3236eb056a6p3
+ceil,0x1.0p0,0x1.cedd70625e604p-1
+ceil,-0x1.0p3,-0x1.111661321bcfbp3
+ceil,0x1.0p0,0x1.fbe1cf7ae152bp-4
+ceil,-0x1.8p2,-0x1.b3d4537ae5063p2
+ceil,-0x1.bp4,-0x1.b7c60675c92b8p4
+ceil,0x1.0p1,0x1.346350e06b91cp0
+ceil,-0x0.0p0,-0x1.cdacbbaf88c8dp-1
+ceil,0x1.0p0,0x1.10c7104e9e63fp-1
+ceil,0x1.3p4,0x1.204422a4f53fep4
+ceil,-0x1.0p1,-0x1.0662f72abe8a6p1
+ceil,-0x1.0p0,-0x1.a3d7a01a3f3edp0
+ceil,-0x0.0p0,-0x1.87236c099c455p-1
+ceil,-0x1.0p1,-0x1.1d23595667d0ap1
+ceil,-0x1.0p1,-0x1.2fa6984e9bce5p1
+ceil,0x1.0p0,0x1.8653440b01b0cp-1
+ceil,0x1.0p1,0x1.110d9cff88cb3p0
+ceil,-0x0.0p0,-0x1.ce628c70988e6p-1
+ceil,-0x1.cp3,-0x1.dfb37608c0c64p3
+ceil,0x1.8p1,0x1.18034b67f0851p1
+ceil,0x1.ap3,0x1.92212ab8078d4p3
+ceil,-0x0.0p0,-0x1.16237c5f2fec2p-2
+ceil,-0x0.0p0,-0x1.3437619f7a954p-2
+ceil,0x1.0p1,0x1.65c8478a49299p0
+ceil,0x1.0p0,0x1.5c0bab7760c84p-2
+ceil,0x1.8p1,0x1.1f819dfae4afp1
+ceil,-0x1.0p0,-0x1.7cf71f30f00a1p0
+ceil,-0x1.4p3,-0x1.4343496871035p3
+ceil,0x1.8p2,0x1.7eed6e5ec8f76p2
+ceil,-0x0.0p0,-0x1.6250ab358d26ep-1
+ceil,-0x1.0p0,-0x1.061e9fa685ef2p0
+ceil,-0x1.0p0,-0x1.db3ce5988640bp0
+ceil,-0x0.0p0,-0x1.ccbb1731eab01p-3
+ceil,0x1.4p2,0x1.3d89f980914b3p2
+ceil,-0x0.0p0,-0x1.8561418dcb05fp-1
+ceil,-0x0.0p0,-0x1.7e6ae3e00fda7p-1
+ceil,-0x1.8p1,-0x1.b4d580276c008p1
+ceil,-0x0.0p0,-0x1.4481bfbcdeac8p-2
+ceil,-0x1.0p0,-0x1.f0bd42cf0da5p0
+ceil,0x1.0p0,0x1.6825db009c06fp-6
+ceil,-0x1.7cp6,-0x1.7e258696b572dp6
+ceil,-0x1.0p0,-0x1.08a7031acc1fbp0
+ceil,-0x1.0p0,-0x1.3bf4bdcfc2fcbp0
+ceil,-0x0.0p0,-0x1.af07481527887p-2
+ceil,-0x1.cp2,-0x1.c4323c29863c1p2
+ceil,0x1.0p0,0x1.e647720b87a44p-1
+ceil,-0x1.0p3,-0x1.1ce9f63825e86p3
+ceil,0x1.0p0,0x1.27092264d1649p-1
+ceil,0x1.0p2,0x1.ad5ee9acacce9p1
+ceil,-0x1.0p0,-0x1.563e9a4c62f6ep0
+ceil,0x1.0p0,0x1.c6a06bb05af8fp-1
+ceil,-0x0.0p0,-0x1.ba5fa6bbd75aap-1
+ceil,-0x1.0p1,-0x1.2a716a394422ep1
+ceil,-0x1.0p0,-0x1.5ce4388bb2741p0
+ceil,-0x1.8p1,-0x1.9647c24134d4fp1
+ceil,0x1.0p1,0x1.3c201ab593d83p0
+ceil,-0x1.8p1,-0x1.9fd79f468a524p1
+ceil,-0x1.0p0,-0x1.7f8801da75951p0
+ceil,-0x1.0p0,-0x1.c4b2c1f85d17ep0
+ceil,0x1.8p1,0x1.324fd4c7777afp1
+ceil,0x1.0p0,0x1.17dbcdbd1808dp-2
+ceil,-0x1.8p1,-0x1.91dd59b003aa4p1
+ceil,0x1.0p1,0x1.bb7f4cb0d714ep0
+ceil,-0x1.8p1,-0x1.ebb29f8a0960dp1
+ceil,-0x1.0p0,-0x1.7078ebcdda1c5p0
+ceil,0x1.4p2,0x1.18426a14825adp2
+ceil,0x1.8p1,0x1.1c4eed388ae27p1
+ceil,-0x1.0p0,-0x1.1a672e6f342cap0
+ceil,0x1.0p0,0x1.24df781832f6cp-2
+ceil,0x1.0p1,0x1.0a1f891d533b5p0
+ceil,-0x0.0p0,-0x1.ad75df6d0acc4p-5
+ceil,0x1.4p2,0x1.2278ad791ea05p2
+ceil,0x1.0p1,0x1.3453656d1d512p0
+ceil,0x1.8p1,0x1.777b9363eaa83p1
+ceil,0x1.0p0,0x1.298f39f5ec8cfp-1
+ceil,0x1.0p1,0x1.d874534d73fb8p0
+ceil,-0x1.0p1,-0x1.457fc8ce77418p1
+ceil,-0x1.4p3,-0x1.578f3415c0213p3
+ceil,0x1.0p0,0x1.19a28add78761p-2
+ceil,0x1.0p0,0x1.93ccc9c24d8bap-1
+ceil,-0x0.0p0,-0x1.ab3ce1ce572c5p-3
+ceil,-0x1.0p0,-0x1.02be59a5332b9p0
+ceil,0x1.0p0,0x1.e099afd9aa97dp-1
+ceil,0x1.8p1,0x1.27f2155750c05p1
+ceil,-0x0.0p0,-0x1.d355da98f638fp-4
+ceil,-0x1.0p0,-0x1.0041d23ea4d7bp0
+ceil,0x1.0p1,0x1.51145fc5e1f75p0
+ceil,-0x0.0p0,-0x1.6c1df0f11a2e7p-2
+ceil,-0x0.0p0,-0x1.21db253403df3p-1
+ceil,-0x1.0p0,-0x1.389765eb19788p0
+ceil,0x1.0p0,0x1.9394bba3f12b1p-1
+ceil,0x1.0p1,0x1.36f2b043cd3c6p0
+ceil,-0x1.0p1,-0x1.651fab3095a4p1
+ceil,-0x1.0p0,-0x1.19bc2e8032b5dp0
+ceil,0x1.0p0,0x1.52521ff2087fep-1
+ceil,0x1.0p0,0x1.d19920fd65aedp-1
+ceil,0x1.0p2,0x1.ca65379dbc236p1
+ceil,-0x0.0p0,-0x1.4182a228c01d8p-1
+ceil,-0x0.0p0,-0x1.31e846b97569ep-4
+ceil,-0x0.0p0,-0x1.7cf3e72de231dp-1
+ceil,-0x0.0p0,-0x1.73c457b5b6f22p-2
+ceil,-0x1.8p1,-0x1.9c10281fbe6a1p1
+ceil,0x1.0p0,0x1.d9d17cc9eb21bp-1
+ceil,-0x1.8p2,-0x1.a59ad9f77bc62p2
+ceil,0x1.0p0,0x1.0e8e995cbe5e5p-2
+ceil,0x1.0p1,0x1.a06747e83f024p0
+ceil,0x1.0p0,0x1.4f4bdabe2938p-1
+ceil,0x1.0p1,0x1.386e6fa60b62dp0
+ceil,0x1.0p0,0x1.72e70f3c3565cp-3
+ceil,-0x0.0p0,-0x1.57af1fd8538a3p-2
+ceil,0x1.0p0,0x1.113dddb6f917cp-2
+ceil,0x1.0p3,0x1.d2b6aec26de9fp2
+ceil,0x1.0p1,0x1.a74c3bfcfb9dbp0
+ceil,0x1.0p1,0x1.95f962791803p0
+ceil,-0x0.0p0,-0x1.340954bbf6f2fp-3
+ceil,-0x0.0p0,-0x1.9763472624c7ap-1
+ceil,-0x0.0p0,-0x1.4a8957e0afd17p-2
+ceil,-0x0.0p0,-0x1.f44af2012da19p-2
+ceil,0x1.0p1,0x1.c2a009304a9afp0
+ceil,-0x0.0p0,-0x1.2f91f183cfcafp-1
+ceil,0x1.0p0,0x1.a44995b6d17f8p-1
+ceil,-0x1.0p0,-0x1.3dcaa9d221b29p0
+ceil,-0x0.0p0,-0x1.4377f9d707078p-1
+ceil,-0x1.0p0,-0x1.ae0e18d669e6dp0
+ceil,0x1.0p2,0x1.ed421922674e3p1
+ceil,0x1.0p1,0x1.3048c00d10bf6p0
+ceil,0x1.0p0,0x1.96900a95da243p-2
+ceil,0x1.0p0,0x1.2d536970cab18p-2
+ceil,0x1.8p1,0x1.7274657cd9bf7p1
+floor,-0x1.0p0,-0x1.60ea637ea2799p-1
+floor,0x1.0p0,0x1.a0e6ad21f666dp0
+floor,-0x1.0p0,-0x1.8140ade02e521p-1
+floor,0x1.0p0,0x1.e8f78ef0d2ee3p0
+floor,0x0.0p0,0x1.4768d41c69116p-3
+floor,0x0.0p0,0x1.b135df74fb11ap-2
+floor,-0x1.0p1,-0x1.467b1c700773ap0
+floor,-0x1.8p1,-0x1.262bff2a64dfbp1
+floor,0x0.0p0,0x1.e0c30caa288c9p-5
+floor,0x0.0p0,0x1.c9114e290ccb5p-4
+floor,0x1.0p3,0x1.0a7b9c7291c7cp3
+floor,-0x1.8p1,-0x1.00a8853762f52p1
+floor,-0x1.0p1,-0x1.0dc1bfba6c846p0
+floor,0x1.0p0,0x1.1778a75927d75p0
+floor,0x1.0p0,0x1.519ca23faddbfp0
+floor,0x1.0p0,0x1.5e1c3249ec62dp0
+floor,-0x1.0p0,-0x1.3e3c0cdde87b8p-1
+floor,-0x1.0p0,-0x1.ca5fe8d10aa5cp-1
+floor,0x1.0p1,0x1.2aed263c57cacp1
+floor,-0x1.0p0,-0x1.4b67a366df0eep-1
+floor,-0x1.0p0,-0x1.ce05fad1edb67p-7
+floor,0x0.0p0,0x1.1bb55f4aa4993p-2
+floor,0x1.0p4,0x1.0a823844e502cp4
+floor,0x1.0p0,0x1.3a4cbb7c16ed9p0
+floor,-0x1.0p1,-0x1.b6d5224a0854cp0
+floor,0x0.0p0,0x1.167bad5a4ef99p-1
+floor,-0x1.0p0,-0x1.736d2d56b012ap-1
+floor,-0x1.0p1,-0x1.25a79ea67b0ddp0
+floor,0x1.0p0,0x1.704f495734a57p0
+floor,0x0.0p0,0x1.4c4b08060544dp-3
+floor,0x0.0p0,0x1.c40ab6550f5bap-4
+floor,0x1.0p1,0x1.2176c61aa4165p1
+floor,-0x1.0p0,-0x1.e8712f6aec8d6p-2
+floor,0x1.0p1,0x1.1a68bcf1c854ap1
+floor,-0x1.0p1,-0x1.65d0481233f84p0
+floor,0x0.0p0,0x1.73ed43d3e7f11p-1
+floor,0x0.0p0,0x1.dd7b26440e0fp-1
+floor,-0x1.8p1,-0x1.1c7a19a7c154ep1
+floor,0x0.0p0,0x1.d7e8971cb7371p-2
+floor,0x0.0p0,0x1.3dcd455837f28p-3
+floor,-0x1.0p0,-0x1.5b079da41f53fp-2
+floor,0x0.0p0,0x1.2a52ab19ae71bp-1
+floor,-0x1.cp2,-0x1.a483cfe4e5739p2
+floor,0x1.0p0,0x1.7a00e9fce97eep0
+floor,-0x1.0p0,-0x1.ed6655cca4ad1p-1
+floor,0x0.0p0,0x1.5555ca39f41dap-1
+floor,-0x1.8p1,-0x1.08b8f0227c007p1
+floor,0x1.0p0,0x1.7a7038a587767p0
+floor,0x1.3p4,0x1.32c7c23003bp4
+floor,0x1.cp2,0x1.dddf2d57aff3fp2
+floor,-0x1.0p0,-0x1.3d7423fd71bd3p-1
+floor,0x0.0p0,0x1.b792fa35f95c3p-1
+floor,-0x1.0p1,-0x1.3b6e1f376d271p0
+floor,-0x1.0p2,-0x1.daacf3a509866p1
+floor,-0x1.0p0,-0x1.bc1b98f41db09p-3
+floor,0x0.0p0,0x1.5b415fcfabca7p-1
+floor,0x1.bap7,0x1.baf7c0481a882p7
+floor,0x1.0p0,0x1.0cde4d5f908d1p0
+floor,0x1.5p4,0x1.52b25de23940ep4
+floor,-0x1.0p1,-0x1.32433c100d7c5p0
+floor,-0x1.0p1,-0x1.9590f9188898dp0
+floor,0x0.0p0,0x1.ae6a210494d6cp-1
+floor,-0x1.0p0,-0x1.57cde9e191efbp-3
+floor,0x1.0p1,0x1.3469d5db5ff16p1
+floor,-0x1.0p0,-0x1.3ed490470f44p-5
+floor,0x1.0p0,0x1.3a36b9f710262p0
+floor,0x0.0p0,0x1.12a59e5193b61p-2
+floor,0x0.0p0,0x1.4eb8dd0b28615p-1
+floor,0x1.0p1,0x1.66f0dc8b5c339p1
+floor,0x0.0p0,0x1.23a078e3b5e6p-2
+floor,0x0.0p0,0x1.da1a50e522d41p-3
+floor,-0x1.0p0,-0x1.d5912533e23bfp-1
+floor,-0x1.0p0,-0x1.d0aac7b5164a6p-3
+floor,0x1.0p0,0x1.153d729a3811ap0
+floor,-0x1.0p0,-0x1.35e3b75b5846ap-2
+floor,-0x1.0p1,-0x1.3357b71d4bd17p0
+floor,0x0.0p0,0x1.e96464db621dfp-2
+floor,0x1.0p0,0x1.40bd49dee854bp0
+floor,0x1.0p1,0x1.062e799f901dep1
+floor,-0x1.0p0,-0x1.04a4254ba4316p-2
+floor,0x0.0p0,0x1.2b58e8fb659abp-1
+floor,0x0.0p0,0x1.d59c6d5f0b9a5p-1
+floor,-0x1.0p1,-0x1.ce04754179edbp0
+floor,0x0.0p0,0x1.3d88c164be795p-1
+floor,0x0.0p0,0x1.9df30bf9eedfep-3
+floor,-0x1.0p0,-0x1.bd28c6cb9c04fp-1
+floor,0x1.0p0,0x1.5c84d6e9ecf5ep0
+floor,-0x1.0p0,-0x1.5ef4731d7afb8p-1
+floor,-0x1.0p1,-0x1.514f5822c3e18p0
+floor,0x1.0p1,0x1.1f445dca8719cp1
+floor,-0x1.0p1,-0x1.c32d845859f41p0
+floor,-0x1.0p0,-0x1.1499d5f055ed4p-2
+floor,0x0.0p0,0x1.f96e2e85d76ddp-1
+floor,0x1.2p4,0x1.2f54d9becdb9ap4
+floor,0x1.0p0,0x1.b4a70a664f94cp0
+floor,0x0.0p0,0x1.89925cf338b0ap-3
+floor,0x0.0p0,0x1.46bfd9a028234p-1
+floor,-0x1.4p2,-0x1.0cc01fd33b135p2
+floor,0x0.0p0,0x1.b2e629cd67709p-1
+floor,-0x1.0p1,-0x1.ae455bde069edp0
+floor,-0x1.0p0,-0x1.a7a453b404f81p-2
+floor,0x1.0p2,0x1.3c570740ad475p2
+floor,-0x1.0p0,-0x1.cf72c10746e05p-2
+floor,-0x1.8p1,-0x1.76f04aca37abap1
+floor,0x0.0p0,0x1.bec66b0a86f77p-1
+floor,0x1.0p4,0x1.0ba4c7ed4ce2ep4
+floor,0x1.0p1,0x1.0a46dbc6d5d34p1
+floor,-0x1.0p0,-0x1.00117e3bb17bp-2
+floor,-0x1.ep3,-0x1.dc28d1350a5ffp3
+floor,0x1.0p0,0x1.cd3d22916dea2p0
+floor,-0x1.0p0,-0x1.d535e729151f2p-2
+floor,-0x1.0p0,-0x1.87a04f8c3f0f3p-3
+floor,0x0.0p0,0x1.d5a27a7fa5ca6p-2
+floor,-0x1.0p0,-0x1.fe33a0c1cd67dp-1
+floor,-0x1.8p1,-0x1.1629a92d4c7e5p1
+floor,0x1.8p1,0x1.f01fb38ad0a02p1
+floor,-0x1.0p1,-0x1.1d61b49bf1823p0
+floor,-0x1.0p1,-0x1.dead34e8651f2p0
+floor,-0x1.2p3,-0x1.0813c277add17p3
+floor,0x1.0p0,0x1.4d2255b09c941p0
+floor,0x0.0p0,0x1.cf7ffb800697p-2
+floor,0x0.0p0,0x1.b11c2fbff3b72p-2
+floor,-0x1.0p0,-0x1.e94968648ecd3p-3
+floor,0x0.0p0,0x1.31b74583c0577p-1
+floor,0x0.0p0,0x1.be82361931e57p-3
+floor,0x1.8p1,0x1.dad0eb6f40657p1
+floor,-0x1.0p1,-0x1.5f1d91f872285p0
+floor,-0x1.8p2,-0x1.49a98786ea925p2
+floor,-0x1.8p1,-0x1.573ee5fbff85ep1
+floor,0x0.0p0,0x1.23d95b8567a42p-2
+floor,-0x1.0p2,-0x1.daa4ab42e2285p1
+floor,0x1.0p2,0x1.0ee22526606fep2
+floor,-0x1.0p0,-0x1.5a9ae8bc2ee6ap-2
+floor,-0x1.2cp6,-0x1.2a5ceb52951p6
+floor,-0x1.8p1,-0x1.6bc8f8b516b47p1
+floor,0x1.8p1,0x1.e9e0f48e16c06p1
+floor,0x0.0p0,0x1.d526a6e007cp-1
+floor,0x1.8p1,0x1.fbe84243ca9aep1
+floor,0x1.0p0,0x1.a5958e7ea9034p0
+floor,0x0.0p0,0x1.4cddd2d0f089p-2
+floor,0x1.0p0,0x1.22aee3a4b1f97p0
+floor,0x0.0p0,0x1.6be900fb60ba3p-2
+floor,0x1.0p1,0x1.7cd1b9585b0a6p1
+floor,-0x1.0p0,-0x1.2f87e8b9b32c5p-5
+floor,0x1.0p0,0x1.439b764651b23p0
+floor,-0x1.0p2,-0x1.8ec036fdd0566p1
+floor,0x1.0p2,0x1.02e194a0b1f1ep2
+floor,0x0.0p0,0x1.9b85107063739p-1
+floor,0x1.0p0,0x1.cf6177e36e21p0
+floor,-0x1.0p1,-0x1.7caa1215c337fp0
+floor,-0x1.0p1,-0x1.16416e7476fbfp0
+floor,0x0.0p0,0x1.c1b12bf16539ep-4
+floor,-0x1.cp2,-0x1.bc048d8aa90d4p2
+floor,-0x1.0p1,-0x1.23b3f2fd28dfp0
+floor,0x0.0p0,0x1.e4bae2b8297d9p-1
+floor,-0x1.4p2,-0x1.2b42ab1745eb3p2
+floor,-0x1.0p1,-0x1.07de022cfd745p0
+floor,0x0.0p0,0x1.323fcc0c22a1p-1
+floor,0x0.0p0,0x1.f5bce5b7c966cp-3
+floor,0x0.0p0,0x1.5993da56bb29cp-3
+floor,-0x1.4p2,-0x1.03a9d3b28df3fp2
+floor,-0x1.0p0,-0x1.59389b5a584a1p-2
+floor,0x0.0p0,0x1.c044a36dba2dep-6
+floor,-0x1.0p1,-0x1.6b4c7e12fa7bap0
+floor,0x0.0p0,0x1.8e7465c37d836p-2
+floor,0x0.0p0,0x1.4dc98a95e1b73p-2
+floor,0x0.0p0,0x1.441dde51458dbp-1
+floor,-0x1.0p0,-0x1.fdf675799bd3ap-1
+floor,-0x1.0p0,-0x1.1eb3acc2f5f8ep-1
+floor,-0x1.0p0,-0x1.5835ed6b38475p-2
+floor,0x1.8p2,0x1.99615c66977fbp2
+floor,-0x1.0p0,-0x1.5038df45d5039p-1
+floor,0x1.8p3,0x1.8a28ebd6820b9p3
+floor,0x1.8p1,0x1.8407d341a1b3ap1
+floor,-0x1.0p1,-0x1.e7c141af0dd15p0
+floor,-0x1.0p1,-0x1.9148faf3c8186p0
+floor,0x1.0p0,0x1.70792e2fc4575p0
+floor,0x1.2p5,0x1.27bdbf35f1357p5
+floor,0x0.0p0,0x1.ed53509ca5181p-1
+floor,-0x1.0p1,-0x1.16cea1321677cp0
+floor,0x1.0p0,0x1.35ec318d055dap0
+floor,-0x1.4p2,-0x1.1b3a65f84f0d3p2
+floor,0x1.0p0,0x1.da1158fdf2d88p0
+floor,-0x1.0p0,-0x1.2241894bf9a26p-1
+floor,-0x1.4p2,-0x1.26f9c915dfca7p2
+floor,-0x1.0p1,-0x1.37701c8fd1802p0
+floor,0x1.0p0,0x1.8359fb530facp0
+floor,-0x1.0p0,-0x1.9bc54c822ae78p-1
+floor,0x1.0p1,0x1.0edbd4f2daa43p1
+floor,0x1.2p4,0x1.2d57e9335a4a4p4
+floor,0x0.0p0,0x1.35eebd2e25a13p-4
+floor,-0x1.0p1,-0x1.4fc7efa4afbb4p0
+floor,0x0.0p0,0x1.89cfce5943f74p-1
+floor,-0x1.0p0,-0x1.f7b8793b8fb79p-2
+floor,0x1.4p3,0x1.51116bcb39f21p3
+floor,-0x1.0p1,-0x1.00861713523cap0
+floor,-0x1.0p1,-0x1.355af729b4d59p0
+floor,-0x1.0p0,-0x1.144405a9b9f7ap-2
+floor,0x1.0p0,0x1.58cd4d03e688p0
+floor,-0x1.0p0,-0x1.8a6380518a9eap-1
+copySign,-0x1.f0df8a466700bp1,-0x1.f0df8a466700bp1,-0x1.6e938e3732539p-1
+copySign,-0x1.58e4f34672f61p4,0x1.58e4f34672f61p4,-0x1.27d6a2e67009cp-1
+copySign,-0x1.f4b9bf237c55fp0,-0x1.f4b9bf237c55fp0,-0x1.37c0ebff02017p0
+copySign,-0x1.59f3d2a9fe64ap2,-0x1.59f3d2a9fe64ap2,-0x1.2669d7ca6a8d6p0
+copySign,-0x1.c46d4baa04314p-2,-0x1.c46d4baa04314p-2,-0x1.5d0597ad91f24p-2
+copySign,0x1.27953254ab2d4p0,-0x1.27953254ab2d4p0,0x1.cf0f007876816p-1
+copySign,-0x1.ee50997f5ec0cp-2,0x1.ee50997f5ec0cp-2,-0x1.1fe2c0d6e4b9bp-1
+copySign,0x1.3318225589ce5p1,0x1.3318225589ce5p1,0x1.8013386023341p1
+copySign,0x1.836934e49ccf1p-1,-0x1.836934e49ccf1p-1,0x1.23098c339673cp1
+copySign,-0x1.a76ccea1e588ap0,-0x1.a76ccea1e588ap0,-0x1.1bf459b597376p-1
+copySign,-0x1.0474aaa82fa0dp3,0x1.0474aaa82fa0dp3,-0x1.10aae9980d88ap-1
+copySign,0x1.3ad3f960b27ffp5,-0x1.3ad3f960b27ffp5,0x1.dbb76f5f93749p-1
+copySign,-0x1.759f798e531dbp-1,0x1.759f798e531dbp-1,-0x1.35757ea9c1ecep6
+copySign,0x1.07a6b63ed401cp2,0x1.07a6b63ed401cp2,0x1.5d12b41ddbb79p0
+copySign,0x1.1beba7d00213p-3,-0x1.1beba7d00213p-3,0x1.73b0d543f50eap1
+copySign,-0x1.ec2d7caf4bb15p-1,-0x1.ec2d7caf4bb15p-1,-0x1.35763cca9e848p-1
+copySign,-0x1.320be2d4133e4p1,0x1.320be2d4133e4p1,-0x1.f1aabc8d9cacdp-2
+copySign,-0x1.e81f03d1b1f11p-4,0x1.e81f03d1b1f11p-4,-0x1.c9787b7217e15p0
+copySign,-0x1.9e5de05c3a504p0,0x1.9e5de05c3a504p0,-0x1.9662999a6d0ecp0
+copySign,0x1.1ac5a7d39dd98p1,-0x1.1ac5a7d39dd98p1,0x1.f7df0731acbdfp-2
+copySign,0x1.81a4cc956f6d4p-1,0x1.81a4cc956f6d4p-1,0x1.1c8c997022c39p-1
+copySign,0x1.5a8a187b65edcp-2,0x1.5a8a187b65edcp-2,0x1.ed1693c7a34f7p-3
+copySign,-0x1.949965fc32defp-1,0x1.949965fc32defp-1,-0x1.20a1e248f5809p3
+copySign,0x1.0ad14bba1ef12p-2,0x1.0ad14bba1ef12p-2,0x1.4141fe80406c7p-5
+copySign,-0x1.0137cbd8c37ep4,0x1.0137cbd8c37ep4,-0x1.bbafad456d25ap-2
+copySign,-0x1.da814e501ccf5p-2,-0x1.da814e501ccf5p-2,-0x1.e7de8b3c8aa78p0
+copySign,-0x1.250e6e8bd43a9p3,-0x1.250e6e8bd43a9p3,-0x1.1c8849158f73bp-6
+copySign,0x1.9e75347b82bc2p2,-0x1.9e75347b82bc2p2,0x1.1cb9afbcdef47p4
+copySign,-0x1.e2f8822f31c16p-1,0x1.e2f8822f31c16p-1,-0x1.8ad3c5ca6b65dp-2
+copySign,0x1.b685eb38af916p0,0x1.b685eb38af916p0,0x1.6374ea7717b05p-6
+copySign,-0x1.979c64e9e1356p-1,-0x1.979c64e9e1356p-1,-0x1.d49e9503981dp0
+copySign,0x1.ab8e31884c0d5p1,0x1.ab8e31884c0d5p1,0x1.9c39fa86c97dp-2
+copySign,-0x1.1b35d4050d6eep3,0x1.1b35d4050d6eep3,-0x1.e52447d0af096p-1
+copySign,0x1.01ece3c27d9dcp-1,-0x1.01ece3c27d9dcp-1,0x1.145244847160cp6
+copySign,-0x1.b80c2678de384p-2,0x1.b80c2678de384p-2,-0x1.936c44fccd21fp-1
+copySign,-0x1.2052a36acdfedp3,-0x1.2052a36acdfedp3,-0x1.ba743cfd12628p0
+copySign,0x1.34e2b497e5db1p-1,0x1.34e2b497e5db1p-1,0x1.820c9bc86002cp1
+copySign,0x1.3b3c577d99964p-3,-0x1.3b3c577d99964p-3,0x1.049d22834db6cp0
+copySign,-0x1.85098ad6879f3p2,-0x1.85098ad6879f3p2,-0x1.2f3901f936a51p-2
+copySign,0x1.5ae7b6579504cp0,-0x1.5ae7b6579504cp0,0x1.784a5a5c4d26cp-1
+copySign,0x1.fafc40bb0a19cp-3,-0x1.fafc40bb0a19cp-3,0x1.69103cc689b08p3
+copySign,0x1.eabdbee4f9632p-3,-0x1.eabdbee4f9632p-3,0x1.d2afea24a5b42p-5
+copySign,-0x1.891004033ecd1p2,0x1.891004033ecd1p2,-0x1.3a11454e346a5p1
+copySign,-0x1.f01b6dc4ac0bbp1,-0x1.f01b6dc4ac0bbp1,-0x1.cfb6825579416p0
+copySign,0x1.f7c899d54f5c6p-1,-0x1.f7c899d54f5c6p-1,0x1.2d0fbe2b02166p-2
+copySign,0x1.7b38b91e000ccp-2,0x1.7b38b91e000ccp-2,0x1.ec7a13fe10c32p-2
+copySign,0x1.29200e4e691e8p0,-0x1.29200e4e691e8p0,0x1.22167b0a7138cp-1
+copySign,0x1.e1d6dede8d29bp-2,0x1.e1d6dede8d29bp-2,0x1.bb6f58f17f526p-5
+copySign,0x1.70b38d09c870dp0,-0x1.70b38d09c870dp0,0x1.5e3f8440b9a55p0
+copySign,-0x1.0d86ce4639fe5p-1,0x1.0d86ce4639fe5p-1,-0x1.a68483813b43cp-1
+copySign,0x1.704c56be88329p-1,-0x1.704c56be88329p-1,0x1.725af47086397p0
+copySign,-0x1.0d77a56187861p0,-0x1.0d77a56187861p0,-0x1.4e8f6c5c4da1fp-1
+copySign,0x1.616bc7a37d586p-4,0x1.616bc7a37d586p-4,0x1.dce538f8baef8p-1
+copySign,0x1.1984f7e58eb9fp-2,0x1.1984f7e58eb9fp-2,0x1.6bad4065ab9f9p-1
+copySign,-0x1.3bc46c7e3db39p0,-0x1.3bc46c7e3db39p0,-0x1.e3769055ffdd5p-1
+copySign,-0x1.890686c4cf1c2p1,-0x1.890686c4cf1c2p1,-0x1.c9f71a96f48b2p-2
+copySign,-0x1.60aaa4be5d131p1,0x1.60aaa4be5d131p1,-0x1.7cebdbee0a5fap0
+copySign,0x1.207e879e82852p1,0x1.207e879e82852p1,0x1.d738021c0a414p-1
+copySign,0x1.ca8842b5fa409p-1,0x1.ca8842b5fa409p-1,0x1.da66adef17274p0
+copySign,0x1.453da6fd920acp1,0x1.453da6fd920acp1,0x1.490346809f2c9p-1
+copySign,0x1.f40f26c3c0defp-1,0x1.f40f26c3c0defp-1,0x1.4bf3bcd970cfp-1
+copySign,-0x1.e17b7648f17b4p-3,0x1.e17b7648f17b4p-3,-0x1.ce8fac44b0264p-3
+copySign,0x1.c9e6c3dc73255p2,-0x1.c9e6c3dc73255p2,0x1.6e828ba149045p2
+copySign,0x1.d3e8a30c46d7p1,-0x1.d3e8a30c46d7p1,0x1.44afccd04b2c2p1
+copySign,0x1.1fe16aed90d5dp-1,-0x1.1fe16aed90d5dp-1,0x1.05f6ff020d2d3p1
+copySign,-0x1.0b67d7e1e5c5fp2,-0x1.0b67d7e1e5c5fp2,-0x1.7485440d87bedp-3
+copySign,0x1.6d14c2a1d5884p-2,0x1.6d14c2a1d5884p-2,0x1.0b603f6bc0c5cp1
+copySign,-0x1.200e9e5b458f1p1,-0x1.200e9e5b458f1p1,-0x1.1ddf63e8e2fdap5
+copySign,-0x1.191e5d337dd5p-2,0x1.191e5d337dd5p-2,-0x1.9159611a2cbe6p-2
+copySign,-0x1.5a4cdfcb8e387p0,0x1.5a4cdfcb8e387p0,-0x1.99b71920b3a42p-3
+copySign,-0x1.4edb118a322a9p1,-0x1.4edb118a322a9p1,-0x1.500dace8c8b9p0
+copySign,0x1.b8378828e00b7p0,0x1.b8378828e00b7p0,0x1.4a394aabf206ep-7
+copySign,0x1.ab4f73b6406b6p-3,-0x1.ab4f73b6406b6p-3,0x1.f9a4a4b155866p-1
+copySign,-0x1.7eacb4c59fb12p0,0x1.7eacb4c59fb12p0,-0x1.07fe825ae7a4fp-1
+copySign,0x1.15a0a17ecbc34p3,-0x1.15a0a17ecbc34p3,0x1.badefca8d13e1p3
+copySign,0x1.3ff41675d0a7ap-4,0x1.3ff41675d0a7ap-4,0x1.cb1c672a1658ep-1
+copySign,-0x1.b23ebb9174357p0,-0x1.b23ebb9174357p0,-0x1.dd12778fe5673p-1
+copySign,0x1.4bdada96f6dcap1,0x1.4bdada96f6dcap1,0x1.c26f18e638d3fp-1
+copySign,-0x1.bba29d24035efp-3,-0x1.bba29d24035efp-3,-0x1.3c380889a325cp-1
+copySign,0x1.02a89c0b5268cp0,-0x1.02a89c0b5268cp0,0x1.e300d4eec6a0ap-2
+copySign,0x1.55b2e0992047fp-2,0x1.55b2e0992047fp-2,0x1.1ac3b1feb5c5dp0
+copySign,-0x1.ce50f2788c33cp-1,0x1.ce50f2788c33cp-1,-0x1.b626ad516319ep-2
+copySign,-0x1.c2ca018fb926p-2,0x1.c2ca018fb926p-2,-0x1.9407139503761p-2
+copySign,-0x1.da74920d86b9ep2,-0x1.da74920d86b9ep2,-0x1.97c65cd575edcp-2
+copySign,0x1.bb518ae8cbeb5p-1,0x1.bb518ae8cbeb5p-1,0x1.538290c7db1f4p-2
+copySign,0x1.af5b250d0967ap-1,-0x1.af5b250d0967ap-1,0x1.f25525da93bfcp-1
+copySign,0x1.efcce730317acp0,0x1.efcce730317acp0,0x1.0e3cc24d1a6d3p0
+copySign,0x1.79e981a3dcf5fp-1,0x1.79e981a3dcf5fp-1,0x1.3718c1db7ea36p0
+copySign,-0x1.b3b07fab25362p-1,-0x1.b3b07fab25362p-1,-0x1.497027db2e31ap0
+copySign,0x1.a3f51d0063acfp0,-0x1.a3f51d0063acfp0,0x1.12bafba6131b7p1
+copySign,-0x1.6ae64480fad1p-1,0x1.6ae64480fad1p-1,-0x1.ae894d9208326p-3
+copySign,0x1.38ec72aab42efp-2,-0x1.38ec72aab42efp-2,0x1.37609b0c15295p7
+copySign,0x1.7261f9d8a06b6p-1,-0x1.7261f9d8a06b6p-1,0x1.5f7d4239730a7p3
+copySign,0x1.aa8341e431eeep-2,0x1.aa8341e431eeep-2,0x1.4965abdf5ea5ep2
+copySign,0x1.1876fd62a3b1bp0,-0x1.1876fd62a3b1bp0,0x1.d54386f9ede1p-2
+copySign,0x1.043f7753c91cp-1,-0x1.043f7753c91cp-1,0x1.a10b36b6b25b6p-1
+copySign,0x1.dc7a76693435dp-2,0x1.dc7a76693435dp-2,0x1.0d6f38f02ce74p-5
+copySign,-0x1.f5c235cf85acap-1,0x1.f5c235cf85acap-1,-0x1.9d1ba81be1b39p-2
+copySign,-0x1.8fd6c0e1894f8p-2,-0x1.8fd6c0e1894f8p-2,-0x1.9bb19e55de9b7p3
+copySign,-0x1.52b7a40bdb00bp-2,0x1.52b7a40bdb00bp-2,-0x1.b880297c99ddp-2
+copySign,-0x1.606226946e86ap-4,-0x1.606226946e86ap-4,-0x1.e3b5e858e235p-2
+copySign,0x1.be16c6dbe7e77p-1,0x1.be16c6dbe7e77p-1,0x1.18d16a97bf8e3p3
+copySign,0x1.93d6bff47ced7p-2,0x1.93d6bff47ced7p-2,0x1.bb654aa0e7343p-1
+copySign,0x1.c3ef005ead94dp-2,-0x1.c3ef005ead94dp-2,0x1.f96d72f57382fp-3
+copySign,-0x1.5d08152ecd007p-2,-0x1.5d08152ecd007p-2,-0x1.41e2bed9e0eb2p0
+copySign,0x1.0f0426ab5da2dp0,0x1.0f0426ab5da2dp0,0x1.180f1ed88e77bp-1
+copySign,-0x1.bf30ea42a1c62p6,0x1.bf30ea42a1c62p6,-0x1.79f4301027c34p0
+copySign,-0x1.4b2c95d80c1f8p-1,-0x1.4b2c95d80c1f8p-1,-0x1.bfdb14bead7b1p-2
+copySign,-0x1.fe8d41355fb51p-3,-0x1.fe8d41355fb51p-3,-0x1.106b10a1cf095p0
+copySign,-0x1.1e9ae4c0043cdp2,0x1.1e9ae4c0043cdp2,-0x1.b284b7bf2ed48p-1
+copySign,0x1.cf4752a33791ep2,-0x1.cf4752a33791ep2,0x1.d18edfd8af2d2p-2
+copySign,-0x1.34da3b809aa63p-3,-0x1.34da3b809aa63p-3,-0x1.5ed7996eb0cfep1
+copySign,-0x1.08462543a7f67p1,0x1.08462543a7f67p1,-0x1.622b88c45b6cp0
+copySign,0x1.ddb0f2a6118dp-4,-0x1.ddb0f2a6118dp-4,0x1.e2e91a136308ap-4
+copySign,0x1.0dc2c166f994fp0,-0x1.0dc2c166f994fp0,0x1.e2f251db9710dp2
+copySign,-0x1.7816949fdf252p-3,-0x1.7816949fdf252p-3,-0x1.25d0dfae54b6bp-2
+copySign,-0x1.6f32771c047f7p-2,0x1.6f32771c047f7p-2,-0x1.295d96f1a5e5bp-5
+copySign,0x1.023e90b9993efp0,-0x1.023e90b9993efp0,0x1.7c18d9c85dedcp-3
+copySign,0x1.84f071dee523ep-1,0x1.84f071dee523ep-1,0x1.d71ebec495bdcp3
+copySign,-0x1.0a7423ef61323p-1,0x1.0a7423ef61323p-1,-0x1.dd15fae5be205p-4
+copySign,-0x1.5f988007a55a1p-1,-0x1.5f988007a55a1p-1,-0x1.069d6b7740021p1
+copySign,-0x1.4cf28b55574adp0,-0x1.4cf28b55574adp0,-0x1.6778e69e6539ep0
+copySign,0x1.ebe7db995647dp-3,-0x1.ebe7db995647dp-3,0x1.81096c1fb11cep-2
+copySign,0x1.52e5afde5170dp-2,0x1.52e5afde5170dp-2,0x1.8a52b211e5e23p1
+copySign,-0x1.949c8dcc34bfep0,-0x1.949c8dcc34bfep0,-0x1.8f3553a64e9a3p4
+copySign,-0x1.3c33f5987f788p-4,0x1.3c33f5987f788p-4,-0x1.6e6b1f686a8f3p4
+copySign,-0x1.651f1423e68eap-1,-0x1.651f1423e68eap-1,-0x1.c526e77ba01eap1
+copySign,0x1.77e7bf9e99a76p-5,-0x1.77e7bf9e99a76p-5,0x1.e38cc78fad0c6p-1
+copySign,-0x1.1c181d4e01548p2,-0x1.1c181d4e01548p2,-0x1.7af633d5d0b38p-2
+copySign,-0x1.3001934e6ae0bp-2,-0x1.3001934e6ae0bp-2,-0x1.491f87b4ac373p1
+copySign,-0x1.af547dca7b826p-2,-0x1.af547dca7b826p-2,-0x1.4a4dd74c4d68p2
+copySign,0x1.78dba1b16b7dbp2,0x1.78dba1b16b7dbp2,0x1.6b74066c6b196p1
+copySign,-0x1.380961d62ec0dp-3,-0x1.380961d62ec0dp-3,-0x1.6e6aaee6298edp1
+copySign,-0x1.5cf87826e093ep-1,0x1.5cf87826e093ep-1,-0x1.ad5aa17eda056p-2
+copySign,-0x1.6fc1179d396p0,-0x1.6fc1179d396p0,-0x1.04302fee70a54p2
+copySign,-0x1.390659f7eb4cdp0,0x1.390659f7eb4cdp0,-0x1.8142f4ee52932p0
+copySign,-0x1.457189185be35p1,0x1.457189185be35p1,-0x1.a29b4fbc2cecep-1
+copySign,-0x1.2fdafd8daf546p1,0x1.2fdafd8daf546p1,-0x1.3352829eeb52ap1
+copySign,-0x1.3170c9d66604p-1,-0x1.3170c9d66604p-1,-0x1.153af45d94cb7p1
+copySign,0x1.722586c5396b4p-2,-0x1.722586c5396b4p-2,0x1.23fdf3add3787p-3
+copySign,0x1.d2b1ba3089506p-1,-0x1.d2b1ba3089506p-1,0x1.10002fbd075c2p0
+copySign,-0x1.48dbcf5c8188ep-1,0x1.48dbcf5c8188ep-1,-0x1.99be7ebce555bp-2
+copySign,-0x1.a9a87920c5ce4p3,-0x1.a9a87920c5ce4p3,-0x1.a05b68dd80554p-4
+copySign,0x1.1a9f934df77b5p-2,0x1.1a9f934df77b5p-2,0x1.b025bec52f56dp-3
+copySign,-0x1.a2adfb75ca99dp2,0x1.a2adfb75ca99dp2,-0x1.ba885fb9e404bp0
+copySign,-0x1.e09d728dc57ebp-1,0x1.e09d728dc57ebp-1,-0x1.75b95bff62f6cp-3
+copySign,0x1.c5593cba00eebp-5,0x1.c5593cba00eebp-5,0x1.7fb0e235bc2eep-3
+copySign,-0x1.3e89b0b0ab25fp0,-0x1.3e89b0b0ab25fp0,-0x1.8fa7c9a2f9bedp0
+copySign,-0x1.6faf937ce04c1p-1,-0x1.6faf937ce04c1p-1,-0x1.5feb7bf313fc1p-1
+copySign,0x1.bc23b8cbe4b6p-2,0x1.bc23b8cbe4b6p-2,0x1.19f1f78354f98p-1
+copySign,-0x1.c2119915765e5p-1,-0x1.c2119915765e5p-1,-0x1.876e1aa39077cp-10
+copySign,-0x1.01c346d4d878bp1,-0x1.01c346d4d878bp1,-0x1.d7c1227d6c119p1
+copySign,0x1.8ce2de24cf505p0,-0x1.8ce2de24cf505p0,0x1.198d30e9c11b4p2
+copySign,-0x1.288e3cab6a2e7p-1,0x1.288e3cab6a2e7p-1,-0x1.a89c4e9eb65cfp0
+copySign,0x1.b07ddc10ef97ap-1,-0x1.b07ddc10ef97ap-1,0x1.d789628d9a124p-4
+copySign,-0x1.dd2a148950301p-6,-0x1.dd2a148950301p-6,-0x1.2e6b8091614eap1
+copySign,-0x1.12f308ce41398p2,0x1.12f308ce41398p2,-0x1.bc8b51e9f443p6
+copySign,-0x1.4afaffad92481p-4,0x1.4afaffad92481p-4,-0x1.d89782a668c16p-1
+copySign,0x1.3ba2157bb5a21p-2,-0x1.3ba2157bb5a21p-2,0x1.d6c3f693229b1p1
+copySign,0x1.62c5c83d97087p2,0x1.62c5c83d97087p2,0x1.b1ec78bb1ee77p-2
+copySign,-0x1.1aa870ae181d3p5,-0x1.1aa870ae181d3p5,-0x1.a8c38c3d5764bp0
+copySign,-0x1.13237983c28bap-1,-0x1.13237983c28bap-1,-0x1.073560686b125p2
+copySign,0x1.440485a03c6bep-1,-0x1.440485a03c6bep-1,0x1.6c7ec47e69b2ep0
+copySign,-0x1.6b009e3e24ff3p1,-0x1.6b009e3e24ff3p1,-0x1.3bdf6b2ca1226p4
+copySign,0x1.86b6cc68a7493p4,-0x1.86b6cc68a7493p4,0x1.04b84cf137d19p-1
+copySign,0x1.239128f3f2cfcp-1,-0x1.239128f3f2cfcp-1,0x1.c2e45a93aa284p2
+copySign,0x1.b06c161e3d158p6,0x1.b06c161e3d158p6,0x1.418d5736566b4p1
+copySign,0x1.c4d364c8d6207p4,-0x1.c4d364c8d6207p4,0x1.ba81bd348bd68p-4
+copySign,0x1.e7b1ac8d6a23fp-1,0x1.e7b1ac8d6a23fp-1,0x1.bd3e6e94926ffp-3
+copySign,-0x1.84646cc829cfp-6,-0x1.84646cc829cfp-6,-0x1.067c187661027p0
+copySign,-0x1.1bfebdb2633a7p0,0x1.1bfebdb2633a7p0,-0x1.7a5e223dc1889p-2
+copySign,0x1.69bfe282b29a4p-2,0x1.69bfe282b29a4p-2,0x1.27729dac24612p0
+copySign,0x1.364c8afd2288ep1,-0x1.364c8afd2288ep1,0x1.4939bf2cc79bfp1
+copySign,0x1.1e104e615f229p2,0x1.1e104e615f229p2,0x1.5a0f78ff1b844p0
+copySign,0x1.080264d2974b4p0,0x1.080264d2974b4p0,0x1.48e2c5ad03dcep-2
+copySign,0x1.36ea7ecc7d913p-1,-0x1.36ea7ecc7d913p-1,0x1.5b8e5b16557d9p-3
+copySign,0x1.98ceb0be39d06p-1,0x1.98ceb0be39d06p-1,0x1.fd5fd1a41ade2p4
+copySign,0x1.461791ed70eedp0,-0x1.461791ed70eedp0,0x1.2098034e5257dp-2
+copySign,-0x1.0e863aa823658p-2,-0x1.0e863aa823658p-2,-0x1.6981ad1a51b86p5
+copySign,-0x1.cac1a69192654p-2,0x1.cac1a69192654p-2,-0x1.f55c98e03b68cp-6
+copySign,0x1.3309aa77b2c1ap-2,-0x1.3309aa77b2c1ap-2,0x1.f11564c63426ap-1
+copySign,0x1.edc084fb770ddp-5,0x1.edc084fb770ddp-5,0x1.2b912a59f3388p-1
+copySign,-0x1.b295af3affc24p-1,-0x1.b295af3affc24p-1,-0x1.c8ad5de54acecp1
+copySign,-0x1.43808dc4810f3p1,-0x1.43808dc4810f3p1,-0x1.8541214a13d1ap0
+copySign,-0x1.43990d0fc0ba3p4,0x1.43990d0fc0ba3p4,-0x1.165cc99ddcb41p1
+copySign,0x1.7af9a0494eb75p-2,0x1.7af9a0494eb75p-2,0x1.fca02fa705a9dp1
+copySign,0x1.2876d5adb29f5p-1,-0x1.2876d5adb29f5p-1,0x1.f8df58a3c29dbp-5
+copySign,-0x1.49f5e691137bdp0,0x1.49f5e691137bdp0,-0x1.455ada7c15032p-1
+copySign,-0x1.b5528b875cf65p1,-0x1.b5528b875cf65p1,-0x1.c5ea3878debd1p1
+copySign,-0x1.9ce99488b7ab4p3,0x1.9ce99488b7ab4p3,-0x1.8889d891b4a49p0
+copySign,0x1.b904b7fb7b589p-2,-0x1.b904b7fb7b589p-2,0x1.995da0765a726p-2
+copySign,0x1.9bdff08e77031p-2,0x1.9bdff08e77031p-2,0x1.8ec0666ac4f3fp-2
+copySign,-0x1.b8aee5bca4d84p-1,0x1.b8aee5bca4d84p-1,-0x1.9fdaa7abca4bcp0
+copySign,-0x1.f827acaf13633p4,0x1.f827acaf13633p4,-0x1.60d4ca7425722p-2
+copySign,0x1.1cc9b76dd0a65p0,0x1.1cc9b76dd0a65p0,0x1.1833bb6dccccdp-2
+copySign,-0x1.5748ad869338p4,0x1.5748ad869338p4,-0x1.d9c10e045123ap0
+copySign,-0x1.2743ef4061547p-1,-0x1.2743ef4061547p-1,-0x1.ac1f4d91209c3p-2
+copySign,0x1.bbb679a1647bbp-2,-0x1.bbb679a1647bbp-2,0x1.08b5bf8219ce6p0
+copySign,-0x1.069560250720cp0,0x1.069560250720cp0,-0x1.eba02acdec778p-1
+copySign,-0x1.365d3d73c52eep0,-0x1.365d3d73c52eep0,-0x1.818c200aa658ep-1
+hypot,0x1.8017a82d3363ep-3,0x1.035c9512d358dp-3,-0x1.1b4ca1504820ep-3
+hypot,0x1.bd197423d6635p0,-0x1.3179605bcd7dcp0,-0x1.43ba11665365cp0
+hypot,0x1.8aeac7c229b6p0,0x1.4fe074e3fd676p-1,-0x1.656e15ef969b7p0
+hypot,0x1.3580d43a93011p0,0x1.db8918b2fdcd8p-1,0x1.8c46c14d5afd9p-1
+hypot,0x1.373c78d07e52ep2,0x1.3641d487af99ap2,0x1.8aae0a08413d2p-2
+hypot,0x1.ad5fee98eb29bp-1,-0x1.accbc0217cb2p-1,0x1.649a1fcc0c4cbp-5
+hypot,0x1.7f5068cf4051bp1,-0x1.51fcf9b757d42p-3,-0x1.7ebb48fe34bf4p1
+hypot,0x1.58bc792d25202p2,-0x1.583c47afb2afep2,0x1.29307fc5a7ce2p-2
+hypot,0x1.53d3ad09df1fp1,0x1.073cf82be91edp1,-0x1.add3e494d4037p0
+hypot,0x1.016262e6307c2p1,0x1.28b80cd44885ep0,-0x1.a4a5da3ce316cp0
+hypot,0x1.0e4d8b6aa5e08p0,0x1.311064835aa81p-1,-0x1.be4ec7072592ep-1
+hypot,0x1.c11c1064ada32p4,0x1.a29a96a022628p-3,-0x1.c119040ae336dp4
+hypot,0x1.36c5961898dcfp2,0x1.34faef20b84efp1,-0x1.0da6c8cf17ee6p2
+hypot,0x1.4f3ff6aae5b99p0,0x1.040ee18ba0b07p-3,-0x1.4dab8c8f91fc1p0
+hypot,0x1.150ca9e71cd52p-1,-0x1.018ffca31383ap-1,0x1.984636905034cp-3
+hypot,0x1.bbb863c31d863p0,-0x1.bad342a98f7a6p0,-0x1.c2b4118dcde48p-4
+hypot,0x1.0c4a62f52adaap-1,0x1.0b1407c9dad71p-1,0x1.979f0307c39c2p-5
+hypot,0x1.57706318dcb2ap0,0x1.0f04ea72fde9p0,-0x1.a5e53d8a1dfdbp-1
+hypot,0x1.267541d554099p0,0x1.24faed88c1f27p0,0x1.d76dc40c15bf5p-4
+hypot,0x1.ec90fa1bf5a7fp-1,0x1.1eaa2c83eeeb3p-1,0x1.908e450f1847bp-1
+hypot,0x1.8c991ba802047p2,0x1.8651546f312e4p2,-0x1.19338343ba90cp0
+hypot,0x1.aad92cdc39b04p-2,0x1.152c91603038ap-2,-0x1.449d18ccb278cp-2
+hypot,0x1.21631ed90a577p1,0x1.a5bdc726dc45cp0,-0x1.8c604a66e05fap0
+hypot,0x1.1f21086b6526ap8,-0x1.c71e00f4249e2p-2,-0x1.1f20f1e04804fp8
+hypot,0x1.ab87a4b1099ap2,0x1.81a3fc7bb3c75p-1,-0x1.a8cdb4f1abeb8p2
+hypot,0x1.2281b0a4e7f7bp-2,-0x1.f81b8704b0955p-3,0x1.20e16841b160dp-3
+hypot,0x1.b65b179cf8c09p0,0x1.c06d19a70a803p-1,-0x1.78ace437034e7p0
+hypot,0x1.15dcce3c9decbp2,0x1.5bdf98fb6e2acp0,0x1.07e6d32abf5f7p2
+hypot,0x1.02bd3d2489d54p3,0x1.ea299155c629bp2,-0x1.4bcfd37dbd568p1
+hypot,0x1.186d9f5735b5fp-1,0x1.5c2c052c73881p-5,0x1.179527dc936bep-1
+hypot,0x1.43cee56f1a6dap1,0x1.2a16c30a612b2p1,-0x1.f9e19c365281ep-1
+hypot,0x1.20c79ed160387p2,0x1.1fee89d5737ecp2,0x1.61d3c2bd3d1efp-2
+hypot,0x1.9f2c1f990436cp-1,0x1.7564938f7927dp-3,-0x1.948abdc960078p-1
+hypot,0x1.93d9b49c8582fp-1,0x1.25d4214478fc7p-1,-0x1.150e45cd98ec1p-1
+hypot,0x1.268de963b13ccp-1,0x1.e19dc7b818391p-4,-0x1.20562925e0f3dp-1
+hypot,0x1.7bc04cf01f1dfp1,0x1.127b246843ab5p0,0x1.6215b0dc45a05p1
+hypot,0x1.493e2cba014fdp0,-0x1.98cea00a3d00cp-1,-0x1.021bcd4dfc3fep0
+hypot,0x1.074a8b6052eddp0,-0x1.0123efcaacc6bp0,-0x1.c49fdc1d31fc7p-3
+hypot,0x1.f87d0d411fb77p0,0x1.93dbe10d976c8p0,-0x1.2e55d460a68c1p0
+hypot,0x1.21b01adc7d5d4p1,0x1.09326ba7a131fp0,-0x1.018f261f8bb48p1
+hypot,0x1.a4091c6c7c7b5p1,-0x1.d698ccadef1ecp0,-0x1.5bf17c59a59fbp1
+hypot,0x1.a8da74b2de311p-1,0x1.d585820bc3e5cp-2,-0x1.6219f0919d956p-1
+hypot,0x1.e58e00daab4a8p-1,-0x1.8b7fff8553f0cp-1,0x1.19adda623b4e9p-1
+hypot,0x1.3c9125f484936p6,-0x1.3c90d882521c8p6,0x1.badef208bfb0fp-3
+hypot,0x1.ea3011c0f543bp-1,-0x1.bffa7db8de42cp-1,-0x1.8dfdda7c84022p-2
+hypot,0x1.c8417faa23771p0,-0x1.955d9ddff7839p0,0x1.a2cc6f7327644p-1
+hypot,0x1.5015828227fb4p0,0x1.0bc0514d1c9c5p-2,0x1.4959bf24e337fp0
+hypot,0x1.990caeba62831p-2,-0x1.71b0789a25c69p-2,0x1.5e267e0dfc068p-3
+hypot,0x1.7fdf153ba4ff5p2,-0x1.7e1ee76937d61p2,0x1.24f5b006b7dc6p-1
+hypot,0x1.18b4266b31b5p-1,-0x1.6ac13bedf55a7p-3,0x1.09a68045c0587p-1
+hypot,0x1.a535e62cc0e8dp3,0x1.0d68613d532b2p0,0x1.a3dcb7e793c5ap3
+hypot,0x1.51c58e272bebdp1,-0x1.493a047c97239p1,0x1.2dfb3b898aa8ep-1
+hypot,0x1.9fbba7b9f3223p0,-0x1.ab81047c0cb26p-2,0x1.91c2adf1cf61bp0
+hypot,0x1.c3cae8c055d28p-1,0x1.2b932f024eecap-1,0x1.52303de03e6cbp-1
+hypot,0x1.33cd3514c8c65p2,0x1.69ffa312bee3dp0,-0x1.263253bcf5adp2
+hypot,0x1.09dc1b47d4ff8p0,0x1.b30d7d6238dc5p-2,0x1.e53049c9b3acfp-1
+hypot,0x1.196d25030df8bp1,0x1.031723fc14628p1,0x1.b7820e016903bp-1
+hypot,0x1.9522414a32e74p0,-0x1.8572babad0f62p0,0x1.be8f8e453bc15p-2
+hypot,0x1.2f6cd48321bd7p1,-0x1.3cb3f1ad69bd3p-1,-0x1.24e9b837ea81ap1
+hypot,0x1.468c5be6ec2e4p1,-0x1.62dcd50a03becp-2,0x1.438580f9f8247p1
+hypot,0x1.9da77b392891fp-1,-0x1.6d574288b80f7p-1,0x1.83ffd55cb8a81p-2
+hypot,0x1.5176d43794d74p2,-0x1.5fac9f69cf192p-2,0x1.50bf648ff6d77p2
+hypot,0x1.70b66b40649d9p1,-0x1.6cb8e89367344p1,-0x1.b0c8f5127f707p-2
+hypot,0x1.234cbaed97268p1,-0x1.f7503d9f20336p0,0x1.256c922374787p0
+hypot,0x1.6d8784c3d84f3p1,0x1.5392d579bf882p1,0x1.0e90ef5859ae4p0
+hypot,0x1.e07408fa3aa64p-3,-0x1.a68e1b31b06b9p-4,-0x1.af8172d58ce1fp-3
+hypot,0x1.521dfd2317ef8p1,-0x1.432f3b3e0759dp1,-0x1.8d7de6d9c2bd8p-1
+hypot,0x1.6c63f48e45a31p-1,-0x1.6faf2282d0664p-2,0x1.3a9d661f261cap-1
+hypot,0x1.674bdc02e9a0bp1,0x1.674812a58db7ep1,-0x1.a14d5314f5264p-6
+hypot,0x1.f270ac8ef01b8p4,0x1.415b60ca7fcb2p-1,-0x1.f256c5e73cda2p4
+hypot,0x1.b7d8a2fbd6d1p2,-0x1.bffec7a06d6b7p-3,-0x1.b79f95d650223p2
+hypot,0x1.cd258330efbf7p0,0x1.44c8adf48bcecp0,0x1.475ee2b6c13c9p0
+hypot,0x1.a5506d089e931p0,-0x1.6df2b4cc974c5p-1,0x1.7b81fb6e663b1p0
+hypot,0x1.0014714db98e5p4,0x1.29f330b17d953p-1,-0x1.ffd230a5359bbp3
+hypot,0x1.acec442e7685cp7,-0x1.56f7de02b4136p-3,0x1.acec3b9c8dd78p7
+hypot,0x1.bd93ebfa0ed76p0,0x1.ad647304443a9p0,-0x1.dc035804e718ap-2
+hypot,0x1.8e03b5175cfb5p4,-0x1.b59106fcb173fp0,0x1.8d12e5f9f295ap4
+hypot,0x1.75941a32ed72ap0,0x1.880260c6fc7d8p-3,-0x1.7259d593af329p0
+hypot,0x1.a6bb3a0e03076p-1,0x1.8e6d7ada69108p-1,0x1.1a8a38056a267p-2
+hypot,0x1.aa5fffbbdfc31p-1,0x1.a45685abf4b7ap-1,-0x1.1dfb80efd3d33p-3
+hypot,0x1.b2d38ba4bfb8fp0,0x1.69617ec3eddc1p0,-0x1.e3a4d310e1969p-1
+hypot,0x1.a49fb548a8466p13,-0x1.6f75774d5f61ap-1,0x1.a49fb53ea02a6p13
+hypot,0x1.dd09a931578dp-1,-0x1.2082ff195f618p-1,-0x1.7be712002fbf2p-1
+hypot,0x1.401b22ceafd65p2,0x1.304116b6ca78bp2,-0x1.8df04eef5e3cep0
+hypot,0x1.39419858ee9dbp0,0x1.b05855f0ecfa8p-1,0x1.c56d30ad78eecp-1
+hypot,0x1.36ba750030663p2,-0x1.2eca04c9a45c9p2,-0x1.172a7006032acp0
+hypot,0x1.e4416f30acd7p0,-0x1.af16b5e1c9306p0,-0x1.b9351d8fcde7fp-1
+hypot,0x1.5f0dd88adfb2bp4,0x1.f9e4410be1debp-3,0x1.5f08267385e12p4
+hypot,0x1.7f6bd3646c94ap1,-0x1.abf9bcbba3bedp0,-0x1.3e270dc19ed1ap1
+hypot,0x1.1dc2e97a10a62p2,0x1.1a4350d7d067p2,-0x1.649f8a6ad3ab9p-1
+hypot,0x1.2d689682c167p2,0x1.2777997d3769p2,0x1.dc674976e59b6p-1
+hypot,0x1.3e109e9759f4cp-1,-0x1.dfc4c4f6c55d6p-4,0x1.385c2844181a3p-1
+hypot,0x1.f9056bb6ba48dp0,-0x1.b8f9d9f98d7p0,0x1.ec496ad9afd83p-1
+hypot,0x1.0b15ce9210793p3,-0x1.0aa38f9333759p3,0x1.edddac1222d8ap-2
+hypot,0x1.465d27068cb34p-1,0x1.033f2dfa7587ap-1,-0x1.8c81d44d2edd7p-2
+hypot,0x1.35f9b4f20ff7cp4,0x1.33aba6f1d125cp4,0x1.2dd8aa83efbeep1
+hypot,0x1.087346cd87a42p1,0x1.749d839bdf0bfp0,0x1.775bab304f38dp0
+hypot,0x1.a89eada56eed3p-2,0x1.9b91c9774806bp-2,0x1.a1da5c1595ca8p-4
+hypot,0x1.041e756d2a036p-4,-0x1.02b1e5879107ep-4,0x1.b2e6f33868b43p-8
+hypot,0x1.2415d267484d5p2,-0x1.1fc31fd3b33dfp0,-0x1.1b1650be2a772p2
+hypot,0x1.045e089a1ae7cp5,-0x1.044e7f6844b59p5,0x1.67c23d0c7967ep-1
+hypot,0x1.ee981daa3af01p-3,-0x1.da6609cbf5c63p-3,0x1.17c808e69464dp-4
+hypot,0x1.76c197cc053bcp2,-0x1.6b80ab7a7dcabp2,-0x1.6c98345550a4dp0
+hypot,0x1.26dd9f912c6d3p1,0x1.b4c2ecd022fc1p-6,0x1.26d891a499cddp1
+hypot,0x1.37e3348a3266dp-1,-0x1.156481f292284p-1,-0x1.1d259111e5715p-2
+hypot,0x1.3119960ee85dap1,0x1.b4a7a666a7cep-5,-0x1.31060df4f99edp1
+hypot,0x1.1519f4cf0ea02p1,0x1.05949b6f7ac3bp0,-0x1.e8960a19b528cp0
+hypot,0x1.fb63131444d72p-1,0x1.3ddacbc4d63e9p-3,0x1.f52036c5be9fcp-1
+hypot,0x1.8e62df654957cp1,0x1.546b78d0e40abp1,0x1.9de377eedc526p0
+hypot,0x1.168806ceaf54ap1,-0x1.c15b0d201cda2p0,-0x1.493d317cda155p0
+hypot,0x1.3225c5f998373p0,-0x1.2830126a5c178p0,-0x1.35d0e543809e4p-2
+hypot,0x1.ad83881035fa4p-1,-0x1.25c678eb6e408p-3,0x1.a7302276676d9p-1
+hypot,0x1.926e8d9f40793p-2,0x1.2f4c778b2da78p-4,-0x1.8b395829adc47p-2
+hypot,0x1.2d3e7ab1cf40dp1,0x1.e2a1b88474772p-2,-0x1.27242d9f3bd04p1
+hypot,0x1.38cae4e02bff1p4,-0x1.38411d9304aa3p4,-0x1.257570c64c2f3p0
+hypot,0x1.71ca45acb60e9p-3,0x1.0324663656b88p-5,-0x1.6c1221fc33928p-3
+hypot,0x1.01432baacbdc3p1,-0x1.50a65058c6723p0,-0x1.851ae4d375c3bp0
+hypot,0x1.13d28ce29c231p2,0x1.11265e394534ap1,0x1.df4587b32d3b1p1
+hypot,0x1.afc91f2dd16d6p0,0x1.a6fbb94c03904p0,0x1.5af68f6d9bbcp-2
+hypot,0x1.bff22080c3055p0,-0x1.38847b1044ce5p-5,-0x1.bfd6de9a148cp0
+hypot,0x1.c47f5855fa922p3,-0x1.507a0b8186773p-3,0x1.c47786a33add8p3
+hypot,0x1.66a689bcf92d7p-1,0x1.191b9b482a7fbp-1,-0x1.bd75b0d18cea2p-2
+hypot,0x1.02575fd2bf78ep4,0x1.817ccc59a8271p-3,0x1.0252e15d0388ep4
+hypot,0x1.d6ee5545f763ap0,-0x1.9bf454314d092p-2,-0x1.cb881aadaca7dp0
+hypot,0x1.81cf4cb57f074p1,-0x1.ee7fc6f4fff17p-1,0x1.6d7789a8f0cbfp1
+hypot,0x1.58a4d388253bfp1,0x1.d92b7f594eef9p0,-0x1.f539eceee06fap0
+hypot,0x1.aaf11e3d43fa6p4,0x1.aaf0b4237b71ep4,0x1.2cfe8369e23c4p-4
+hypot,0x1.43119ce321232p1,-0x1.36ad99667b8d3p1,0x1.627563d2d87cfp-1
+hypot,0x1.3a67807d50897p1,0x1.d94d0af047ce5p0,0x1.9dfd0e6432532p0
+hypot,0x1.c6c8ce885af15p0,-0x1.f6a2103fd574dp-1,-0x1.7b096810d00bfp0
+hypot,0x1.7eb6eb5b2d209p2,0x1.75fe4773e99p2,-0x1.44f29d9b38acap0
+hypot,0x1.1174ddb59c62bp1,0x1.3b812b948c3d1p0,0x1.bebbbec78a821p0
+hypot,0x1.8b090f8456993p0,-0x1.8422e7e1768dp-1,-0x1.58144753460ebp0
+hypot,0x1.b8e5e3a91d0dbp1,-0x1.d4a84fc843599p-1,-0x1.a90b9d04bd13ep1
+hypot,0x1.59a78eb87b229p0,-0x1.048bc8710db5cp-4,0x1.59454e6a140b1p0
+hypot,0x1.1fecf764af115p1,0x1.3c5c7003e5afep0,-0x1.e12a681e8034ep0
+hypot,0x1.7f118ef06aec5p0,0x1.86df8d0a2c418p-2,0x1.726532058c327p0
+hypot,0x1.f8f42b5158094p1,0x1.8209e521b3935p-2,0x1.f6a48f603e064p1
+hypot,0x1.32115d8e1bc4dp3,-0x1.f8d14cb4cb74ap0,0x1.2b7e06b2fbd07p3
+hypot,0x1.6b950430e37dbp0,-0x1.44a5a8119fdb4p0,0x1.47641324ef577p-1
+hypot,0x1.c1f2b2ff94756p2,-0x1.8886fc5e32efp2,-0x1.b7e3919de6f4ep1
+hypot,0x1.4acf61319f386p1,0x1.41fa14e8008aap1,0x1.2fbdea47bd94fp-1
+hypot,0x1.cc0c55809e1a6p0,0x1.81703e54c1c4p0,-0x1.f6521b1f1354dp-1
+hypot,0x1.99fdf6a85eef6p1,0x1.1e8543c9774b4p0,-0x1.8025fb6a780cep1
+hypot,0x1.8c40f4899458bp1,-0x1.f74893f7b1928p-1,0x1.77bf572b54b79p1
+hypot,0x1.f35832c710289p0,-0x1.28d787a926bcep-1,-0x1.dcc6e0481f2f1p0
+hypot,0x1.4648f024ad8dap0,-0x1.2683ffd9a9185p0,-0x1.18df74dfc99cbp-1
+hypot,0x1.63ef5de5b5ee8p1,-0x1.0db098198b967p1,-0x1.d092d38c00816p0
+hypot,0x1.104d8ab3eb11bp3,0x1.4a90dcca30dcep-1,-0x1.0f849acddd53ap3
+hypot,0x1.2907643018514p2,-0x1.25bdc94ce5d1cp2,-0x1.608f72e4bd0fap-1
+hypot,0x1.56a72ae4b9e94p0,0x1.c172c5b8dc582p-6,0x1.5694be2afe189p0
+hypot,0x1.7c913da22a1b4p0,0x1.6ceabebeb1aa6p0,-0x1.b00ebbe92fe9ep-2
+hypot,0x1.9b79e9c4011d4p0,0x1.424af6585a36ap0,-0x1.ff9ffbffd1331p-1
+hypot,0x1.b3821e3ebf1b5p0,-0x1.2687bc1b2e4cdp0,0x1.40cf80485c17bp0
+hypot,0x1.cde6ed75e0459p-1,-0x1.94fdeaec94d8cp-1,0x1.bc3ae9e16d5f8p-2
+hypot,0x1.62e1a9b5bd5b4p-1,0x1.14bc4656a0dddp-6,-0x1.62c6af2ad15d4p-1
+hypot,0x1.843071da576b2p0,0x1.517b32a05ad5fp-1,0x1.5d989f0bed307p0
+hypot,0x1.ea4dd008eaa16p1,0x1.e98659e3b8254p1,0x1.ba15766e322d9p-3
+hypot,0x1.eccb4068cf0d1p-1,-0x1.7feee220563bp-1,0x1.34ef8588ec801p-1
+hypot,0x1.13ac3ec05c11dp0,0x1.a8468d66bd8e7p-1,0x1.6018d1abe1a61p-1
+hypot,0x1.e602f9743bb51p0,0x1.3884aef9b9575p0,0x1.74358720cd00fp0
+hypot,0x1.919bb779dea3dp0,0x1.561919639cff9p0,0x1.a4c0985f4044p-1
+hypot,0x1.79fae38a64176p0,0x1.cc02224bb6489p-1,0x1.2bf1ea03166e8p0
+hypot,0x1.9e419a0dfc32p0,-0x1.2cc3028a36a64p-1,-0x1.81ff4870c85ccp0
+hypot,0x1.eef893d3dcbe6p2,-0x1.e6f1a4c783a04p0,-0x1.dfc46cc74dd64p2
+hypot,0x1.d2c1e613e4a55p-1,0x1.d158adbf0339cp-1,-0x1.22207fa622328p-4
+hypot,0x1.894e2337fc0d9p-1,-0x1.5b60941b5241p-1,-0x1.70e12d3fa5db9p-2
+hypot,0x1.5b1ab4e7fba04p-2,-0x1.4c42574154c9p-2,0x1.91b3aad06999bp-4
+hypot,0x1.c6037ec51f64cp1,0x1.b9275edc200e8p1,-0x1.ad2bc12e2599p-1
+hypot,0x1.af2b1a2685f99p0,-0x1.ab9b0e474d967p-3,0x1.abd7ac669b2d2p0
+hypot,0x1.48a9c2589c728p0,0x1.1dcef0625d0a2p-1,-0x1.27f825ee39e79p0
+hypot,0x1.3659f059cad77p-1,0x1.417f43db8ce85p-4,-0x1.33bd0960ab133p-1
+hypot,0x1.fe90bc6be9ef4p1,0x1.00e72de68d745p1,-0x1.b9391d6441499p1
+hypot,0x1.1568085ae001fp1,0x1.23cd4482baa0ep0,0x1.d7e0c765b481fp0
+hypot,0x1.a047c49b0bde1p-2,0x1.47511ca4d566ep-2,0x1.0133c8166661ap-2
+hypot,0x1.10cce99512b87p0,-0x1.107bb18770d41p0,0x1.a4e42adbe428dp-5
+hypot,0x1.457a166cb4078p3,-0x1.4579ff77f47a2p3,0x1.e8f8b25e670edp-7
+hypot,0x1.952b55bc85bd5p2,-0x1.951e3c55c86c3p2,0x1.9c1986dfb62bfp-4
+hypot,0x1.4ed6383e6299cp0,0x1.43d537aa1be88p0,0x1.548a19f98e3a8p-2
+hypot,0x1.000528b3f0ed7p1,-0x1.8a727b769138dp-3,-0x1.fda92ebdb0fd4p0
+hypot,0x1.978ed2893e4ecp-1,0x1.c0875a3cb510bp-2,0x1.544e9fab93924p-1
+hypot,0x1.2f1f72c453c24p2,0x1.e9d79a82803b3p0,-0x1.1548ea1f30464p2
+hypot,0x1.15518286d99e5p1,-0x1.0941e6e741adbp1,-0x1.439468d92ee49p-1
+hypot,0x1.50a58b6e00083p0,-0x1.8f9811df2239ap-2,-0x1.417b9ffd99018p0
+hypot,0x1.784f5a15004bbp2,-0x1.41da2a0bf3807p-1,0x1.76273812c2c52p2
+hypot,0x1.70af7ebdaf6ccp1,0x1.e5b3ebf06c063p0,0x1.156711d3ca2ccp1
+hypot,0x1.0d938539dbe96p0,-0x1.0eb2ac33bf57cp-2,-0x1.04f18a62ee1adp0
+hypot,0x1.f62262f339a7ep0,0x1.6100184e24683p-1,0x1.d61792743ce6dp0
+hypot,0x1.793302d58395fp2,-0x1.96bbe5f70caecp-3,-0x1.78fc2c3f53676p2
+hypot,0x1.2cc612f04cb84p1,0x1.161ad1d26afb7p1,-0x1.ca3719322ca2ep-1
+hypot,0x1.eb865a4473334p2,0x1.ea4e0f45d30bcp2,-0x1.14dd9faadeda6p-1
+hypot,0x1.374733be9f265p3,-0x1.36eb870cf1d02p3,-0x1.dda8f30fd43f9p-2
+hypot,0x1.00d5ba2f84b1dp5,-0x1.00d398c19548dp5,-0x1.08a750aec5e2cp-2
+hypot,0x1.30335553c8f9bp3,-0x1.efda9ea09b8d6p2,-0x1.6088dc8957025p2
+hypot,0x1.a0d8bd280e2c5p0,0x1.8f1ee95246894p0,0x1.e10fafc6cb42ap-2
+hypot,0x1.50eedd03ad891p0,-0x1.c0f1d9414c899p-1,0x1.f689a99fe4f7fp-1
+hypot,0x1.411383f09b35cp0,-0x1.244c4d4b2c51p-4,0x1.408e5b9ef6893p0
+hypot,0x1.937fffc74dd4fp1,-0x1.6658a91669e4cp1,0x1.72f2113c8c03dp0
+hypot,0x1.0dbe619dab1a1p2,-0x1.b3821369a8b0fp-1,0x1.08317c141257bp2
+hypot,0x1.ba6329899a6ep0,0x1.02970362943cep0,-0x1.66f09bd0d6d81p0
+IEEEremainder,0x1.92c6b518a96cp-4,-0x1.95cc024bc2e3dp2,-0x1.12ba136ac3b1p0
+IEEEremainder,-0x1.9a2601ee0b37cp-3,0x1.68e971ffed245p0,-0x1.12c976d3c9b23p-1
+IEEEremainder,-0x1.59e4503ff371p-3,-0x1.59e4503ff371p-3,-0x1.0c912a93f545ap-1
+IEEEremainder,-0x1.1741eb551c2a8p-3,-0x1.7b22c6245681cp0,-0x1.583a88b9b2fc7p0
+IEEEremainder,-0x1.d7104568a7836p-1,-0x1.d7104568a7836p-1,0x1.1165425b27d26p3
+IEEEremainder,-0x1.c961b96a089p-8,-0x1.3cc42fab56789p0,-0x1.3afacdf1ec7p-1
+IEEEremainder,0x1.67ad60a725d94p-3,-0x1.9e305f6421286p-1,-0x1.f81bb78dea9ebp-1
+IEEEremainder,0x1.98ebb4994eb7p-2,-0x1.16cff8747f0bep2,0x1.95d39a52c549cp0
+IEEEremainder,0x1.ae51d87c54eb6p-7,-0x1.e04eec4369cp-1,-0x1.d8460389127fbp-6
+IEEEremainder,0x1.530e632e0fdep-5,0x1.7a4ee15cae799p1,0x1.4b90952aa1facp-3
+IEEEremainder,-0x1.125599ee187fp-2,-0x1.5d9b3beed2a9fp0,0x1.1905d5734c8a3p0
+IEEEremainder,0x1.bf7034499694fp-6,0x1.bf7034499694fp-6,0x1.ebb4f6d58bb0bp0
+IEEEremainder,-0x1.a5151b60d8bbp-7,-0x1.4aeaf96c5ad82p0,0x1.766ea3aaf82c3p-3
+IEEEremainder,0x1.a1abeca2f5a04p-1,0x1.a1abeca2f5a04p-1,0x1.89d9fa4183389p7
+IEEEremainder,0x1.be4eb07f74d0bp-2,0x1.be4eb07f74d0bp-2,0x1.eaf676f43fb5ep-1
+IEEEremainder,0x1.3817ca0dd4788p-2,0x1.05a60fc50797fp2,-0x1.42db6edae315ep0
+IEEEremainder,0x1.5727f14b4a2d4p-2,-0x1.baa350a59c65ap0,0x1.6048ddfaf4a0ap-1
+IEEEremainder,-0x1.560ac9f65ba88p-2,0x1.f9013c566b5c8p0,0x1.2741f76a01235p0
+IEEEremainder,-0x1.c209a136b2107p-3,-0x1.c209a136b2107p-3,-0x1.bf8cef105da2bp-1
+IEEEremainder,-0x1.8a0951dd94f8p-4,-0x1.dbb3ba40684ccp1,-0x1.cf636fb17ba5p-1
+IEEEremainder,-0x1.1aa58e7a688dp-3,0x1.78312de742afcp-1,0x1.beda9185dcd3p-1
+IEEEremainder,-0x1.6766e2484b6e6p-2,-0x1.6766e2484b6e6p-2,0x1.577d4e4f0a8adp3
+IEEEremainder,-0x1.c53f47ce2dcep-4,0x1.511dfb3f748bp0,-0x1.6d71efbc5767ep-2
+IEEEremainder,0x1.9e954913c2dd4p0,0x1.9e954913c2dd4p0,0x1.53fb22fb97bp2
+IEEEremainder,-0x1.355a2d8403ea8p-3,-0x1.25c864b796e12p2,0x1.7ad219b9f3ad1p-1
+IEEEremainder,-0x1.34dbe8a6a7924p0,0x1.109179f49d05p1,-0x1.aaff6e47f0ce2p1
+IEEEremainder,0x1.ec34fbb4845b4p-3,-0x1.146ddb5d93238p-1,-0x1.8f7b1a4ab43a5p-1
+IEEEremainder,0x1.34d78f654359p-3,0x1.df2ba06f0eedp-1,0x1.91f5bc95be16cp-1
+IEEEremainder,0x1.4602d01729278p-1,-0x1.169c4aaf3aaa2p1,0x1.681cfeb504f4p0
+IEEEremainder,-0x1.3e96fbbad1928p-4,0x1.1936c90d6d1ccp1,-0x1.843a0139af8c7p-1
+IEEEremainder,0x1.e7de6e593b4c9p-1,0x1.e7de6e593b4c9p-1,-0x1.f4fed08490e1ap3
+IEEEremainder,0x1.3af0189c84d26p1,0x1.3af0189c84d26p1,0x1.7b6bd7a20d154p4
+IEEEremainder,0x1.7d2d2251f0754p-1,0x1.7d2d2251f0754p-1,-0x1.9c6393376bfd1p0
+IEEEremainder,0x1.a31c623321f7cp-1,-0x1.b9a70bc0f5db9p1,-0x1.11371226df2ccp2
+IEEEremainder,-0x1.0cd0bd0e6842p-10,0x1.a6e596084c617p-1,-0x1.d3395f56fb20ap-9
+IEEEremainder,-0x1.64ca49c110acp-16,0x1.07e061bfc14e8p-3,-0x1.d1f4946d915f6p-11
+IEEEremainder,-0x1.c4452529a9659p-2,0x1.f5555f0474e8bp-2,-0x1.dccd42170f272p-1
+IEEEremainder,-0x1.60cbc9caaa554p-7,0x1.bc5c37443371ap-3,-0x1.0a851da51131bp-5
+IEEEremainder,0x1.d171a1425a2a2p-4,0x1.d171a1425a2a2p-4,0x1.b32fd3630b0a2p-1
+IEEEremainder,-0x1.08655b374b8ccp-3,-0x1.1ec25309b279fp0,0x1.fb6b4f459210bp-1
+IEEEremainder,0x1.be5e794c843p-5,0x1.1b14147e07b68p8,0x1.0c594009b566cp0
+IEEEremainder,-0x1.633debecdeeep-4,-0x1.4775fe0141a8p0,-0x1.31421f4273b92p-2
+IEEEremainder,0x1.f6dba8e8a3c8bp2,0x1.f6dba8e8a3c8bp2,-0x1.016df1a64bdc5p5
+IEEEremainder,-0x1.221bc0b1a575p-1,-0x1.3304df061564ap3,-0x1.812ed94ea411cp0
+IEEEremainder,0x1.4249f849fd958p-5,0x1.f1e7f8eda3c1ap-2,0x1.c99eb9e4640efp-2
+IEEEremainder,-0x1.6ca2e52eb0cf8p-4,0x1.42e03452c82bep-1,0x1.707490f89e45dp-1
+IEEEremainder,-0x1.111fa3d8ce6bp-2,0x1.ad3896820fcb4p0,0x1.f1807f784366p0
+IEEEremainder,0x1.6aa7b57fa52c9p-6,0x1.6aa7b57fa52c9p-6,0x1.0a8a01b31c07ap-2
+IEEEremainder,0x1.d0e82b44db0d8p-3,0x1.01dd957f2f574p0,0x1.8f81202d27eb2p-1
+IEEEremainder,-0x1.eba043b61e22bp-2,-0x1.eba043b61e22bp-2,0x1.823946b1a8b2dp5
+IEEEremainder,0x1.8f3a751f5e40dp-1,0x1.8f3a751f5e40dp-1,-0x1.11254ed0e4508p1
+IEEEremainder,0x1.8f7337e12436p-2,0x1.5fbe1b7bb322fp1,0x1.2dcfb47f8e9c3p0
+IEEEremainder,0x1.801173086a19cp-2,-0x1.f28701e56f1acp-1,-0x1.5947ddb4d213dp0
+IEEEremainder,0x1.2d16336b4f27p-5,-0x1.2761251b0a27cp5,0x1.3636fe96f8a33p-2
+IEEEremainder,0x1.0e9be76ca753p-2,-0x1.2191cbc42d8bbp0,0x1.6538c59f57607p-1
+IEEEremainder,0x1.f06beaa1ecffp-4,0x1.2340bf87d2f7dp3,-0x1.486d9b1535d8fp-2
+IEEEremainder,-0x1.f2bfee626cf63p-1,-0x1.f2bfee626cf63p-1,-0x1.f81068e93d56ep5
+IEEEremainder,0x1.15cf59d769c4ep-3,0x1.15cf59d769c4ep-3,0x1.b1ca867b89e08p0
+IEEEremainder,-0x1.80addfdd0941p-4,-0x1.80addfdd0941p-4,-0x1.005e82dd26f59p1
+IEEEremainder,0x1.24aafaa91869fp0,0x1.24aafaa91869fp0,0x1.7dfab3cc95b52p2
+IEEEremainder,-0x1.f92f4d9bed0cp-3,-0x1.1bb7032f2fbc6p1,0x1.5030131c968f8p-1
+IEEEremainder,-0x1.b4c7cdb3ae61cp-2,-0x1.b4c7cdb3ae61cp-2,0x1.325583f80f736p0
+IEEEremainder,-0x1.b8c5db7d4a0ap-5,0x1.d7cf470433cd5p-1,0x1.4ce7c328059eap-3
+IEEEremainder,-0x1.4f82aca892d2p-5,0x1.2fe0b25c9b32p1,0x1.9c28fc1451fc6p-1
+IEEEremainder,-0x1.39acd6a8b27c5p-3,-0x1.39acd6a8b27c5p-3,-0x1.7af77e4a212e7p-1
+IEEEremainder,0x1.8c0696e5b34e9p-2,0x1.8c0696e5b34e9p-2,0x1.9b7f48ed07846p-1
+IEEEremainder,0x1.698974bdc50fp-9,-0x1.c0c8dfb7b7bb9p-1,-0x1.0ac88a2d4f1cdp-5
+IEEEremainder,0x1.9510bee0122a8p-3,-0x1.5ab25b780c4f5p0,0x1.8d5473540e94ap-1
+IEEEremainder,-0x1.9a93749e545a4p-1,-0x1.9a93749e545a4p-1,0x1.d2bfce6af6e8bp0
+IEEEremainder,-0x1.1c1b92874640bp-2,-0x1.1c1b92874640bp-2,0x1.7164c361b4fb2p-1
+IEEEremainder,0x1.9ab124bd90451p-2,-0x1.b7713f10f18cfp-2,0x1.a91131e740e9p-1
+IEEEremainder,-0x1.de23f63acdb76p-4,0x1.b80bd10967ca1p-3,0x1.538ee6136752ep-2
+IEEEremainder,0x1.2aaf4c0aa998p-6,0x1.44c087f959307p1,-0x1.426b296143dd4p0
+IEEEremainder,0x1.60a5b367a21p-1,0x1.26fa1c4ae3125p4,0x1.1bf4eeafa601dp1
+IEEEremainder,-0x1.923d2cfb69cf4p-1,-0x1.923d2cfb69cf4p-1,-0x1.9750d975a46c2p2
+IEEEremainder,-0x1.164f2c1d842fcp0,-0x1.164f2c1d842fcp0,0x1.16f9c68a74e4dp1
+IEEEremainder,0x1.68e94f7bcb251p-3,0x1.68e94f7bcb251p-3,0x1.0a8ede9c2f8ccp-1
+IEEEremainder,-0x1.18a29df42db78p-3,0x1.0e898090ee4a5p-1,-0x1.54b2280df9b83p-1
+IEEEremainder,0x1.6fa5356df394p-9,-0x1.d91bc89cac659p-2,-0x1.0ffd2f7204be2p-4
+IEEEremainder,0x1.22f5024349918p-6,0x1.4fad4097e876dp2,-0x1.5954f32f1e1e3p-4
+IEEEremainder,-0x1.4af7a4c3b892p-7,-0x1.256481e2329efp5,0x1.5a06de444e51ep-4
+IEEEremainder,0x1.4b39ddcc0e938p-5,0x1.49b4d70083a66p1,-0x1.72e47f785f56fp-2
+IEEEremainder,0x1.61bd946f1d0c8p-3,0x1.3aa06dbb9394dp1,-0x1.86061b462d056p-1
+IEEEremainder,-0x1.384e7178de044p-1,-0x1.ee295446e3e42p0,0x1.52021b8a74e2p0
+IEEEremainder,0x1.d5cc2f6198654p-6,-0x1.9b664b57eebf3p0,0x1.f048deea0613ep-5
+IEEEremainder,-0x1.08dadc47e3e4fp0,-0x1.08dadc47e3e4fp0,-0x1.354cbca212e52p1
+IEEEremainder,-0x1.916e3613b954p-3,-0x1.341bb9b9bf9ccp2,0x1.2790480921d22p0
+IEEEremainder,0x1.13770164501dp-3,-0x1.83d9670ce8401p1,0x1.440d78e8f1018p-1
+IEEEremainder,-0x1.7e1599abf88d2p-1,-0x1.4383fb2757057p1,0x1.c7fd2978b1c45p0
+IEEEremainder,-0x1.1b01d08de8179p-1,-0x1.1b01d08de8179p-1,-0x1.21d9a4a26db98p1
+IEEEremainder,-0x1.e41655279f92cp-1,0x1.688ea04e5c7acp0,0x1.2d4ce57116221p1
+IEEEremainder,-0x1.6ac9fddf4c2a6p-2,0x1.0c8e40f30dd9fp1,0x1.a28a00e949d45p-1
+IEEEremainder,-0x1.b215df61001dp-6,-0x1.d1baea2634851p-2,-0x1.5ee13cf35069p-4
+IEEEremainder,0x1.5ef9acbc8d206p-3,0x1.5ef9acbc8d206p-3,-0x1.f228f6f21ec12p-1
+IEEEremainder,0x1.1c31d39c6df9ap-3,0x1.1c31d39c6df9ap-3,0x1.c28d77df17f78p-1
+IEEEremainder,0x1.cd1c08e3be29p-4,-0x1.a3f47d0f2b0aap-2,0x1.0b9dbfa40d4a7p-2
+IEEEremainder,-0x1.0e60e475204p-10,0x1.850a519b5bad9p0,-0x1.854de9d478f5ap0
+IEEEremainder,-0x1.1b3d8cf21f434p-2,0x1.1459eb7cc6c09p-1,0x1.a1f8b1f5d6623p-1
+IEEEremainder,0x1.3c8e07e87cd3p-3,0x1.4a657594ff29dp-1,-0x1.f683e735bfea2p-2
+IEEEremainder,0x1.397b539fcea7p-3,0x1.28363fbac5405p0,-0x1.0106d546cb6b7p-1
+IEEEremainder,-0x1.1c55238bd3a5ep-2,0x1.2ff0484ad2a9p1,-0x1.c4a3e65066d25p-1
+IEEEremainder,0x1.703495b8c3537p-4,0x1.703495b8c3537p-4,-0x1.fa9864790c4c8p-3
+IEEEremainder,0x1.7155ccb6adb4p-6,0x1.546c341ff48f8p0,0x1.be33d13c22764p-3
+IEEEremainder,-0x1.c85aaf7aa4dbdp0,-0x1.c85aaf7aa4dbdp0,-0x1.a19a554f8fb0dp2
+IEEEremainder,0x1.59d7f420d6604p-2,-0x1.3c961c035d721p0,0x1.930c190b930a2p-1
+IEEEremainder,-0x1.7d37127616d11p-2,-0x1.7d37127616d11p-2,-0x1.9e0c653b825f5p0
+IEEEremainder,0x1.c105434e9e858p0,-0x1.00c6e4c4ab6a5p4,0x1.7bc9a14cc718ep2
+IEEEremainder,0x1.217e17fbaa198p0,0x1.217e17fbaa198p0,-0x1.c49ecbec7927dp4
+IEEEremainder,-0x1.138fc24a55672p-2,-0x1.05b84b6b50fc8p0,0x1.81a8b5b177457p-1
+IEEEremainder,0x1.9ed238fe1b80ap-6,0x1.9ed238fe1b80ap-6,-0x1.d4fe0e4e2c1ffp3
+IEEEremainder,0x1.4e164c6236a06p-1,-0x1.2a59f20997f46p0,-0x1.d165183ab3449p0
+IEEEremainder,0x1.d8e9b187f42ep-6,0x1.65593a63826f6p1,0x1.d789deab435ebp-4
+IEEEremainder,0x1.141578906beb3p-2,0x1.141578906beb3p-2,-0x1.0aae845ac8ed1p1
+IEEEremainder,0x1.db03194fa9092p-2,0x1.db03194fa9092p-2,0x1.b4ec10edb7605p2
+IEEEremainder,0x1.718f32fdb8cdcp-2,-0x1.56af54047de67p1,-0x1.0340d19823557p0
+IEEEremainder,-0x1.3df2956b19378p-5,0x1.21a18fc05f703p-3,0x1.711e351b25be1p-4
+IEEEremainder,0x1.915f9b24cf9ep-9,-0x1.39f19304c5942p1,0x1.92597e9e27667p-4
+IEEEremainder,-0x1.341222a731e64p-2,-0x1.03c739f1bda5p4,0x1.0ff656d467529p0
+IEEEremainder,0x1.2aa3c6cd7066fp-1,-0x1.d15153e9429f9p-1,0x1.7dfa8d5b59834p0
+IEEEremainder,0x1.9599ad0617bccp-2,-0x1.233788b724cd4p3,0x1.e63a236555ab7p0
+IEEEremainder,0x1.28357c323b3ep-2,-0x1.644e42bd4b7bap1,0x1.8954f24392e36p1
+IEEEremainder,-0x1.ab2ade18b8968p-4,0x1.f18fa04c46186p3,-0x1.c9f6d250e251ep-2
+IEEEremainder,-0x1.09e9c86d9134ap2,-0x1.09e9c86d9134ap2,0x1.6744144abe6p6
+IEEEremainder,-0x1.1da10fbf01c6fp-3,-0x1.1da10fbf01c6fp-3,0x1.13fbd42bacaccp0
+IEEEremainder,0x1.b703466af4f34p-3,-0x1.5ea8dd2e07097p-1,-0x1.cc69aec8c4464p-2
+IEEEremainder,0x1.aaf1453f17caap-2,-0x1.f02e901b9f26bp-1,-0x1.62d3995d9586p0
+IEEEremainder,-0x1.d2cbf13d5e3b4p-5,-0x1.d2cbf13d5e3b4p-5,0x1.70bb139c7f2ap4
+IEEEremainder,-0x1.bf89e288347p-7,-0x1.be1730e6eca82p1,0x1.bc57a7046473bp-2
+IEEEremainder,-0x1.0a6e862d907c4p0,-0x1.0a6e862d907c4p0,0x1.0c0fce2bc8d9ep1
+IEEEremainder,0x1.17f13c338e8f7p-2,0x1.17f13c338e8f7p-2,0x1.4cb7fd951aa3dp-1
+IEEEremainder,0x1.0143242f852b4p-4,0x1.645d7495bfbbdp-2,0x1.240cab89de71p-2
+IEEEremainder,0x1.1f47bbb3ba59p-3,-0x1.421ca57f8ccddp0,-0x1.66059cf60418fp-1
+IEEEremainder,0x1.76bb632d282c8p-2,0x1.dc64de3e6b886p1,-0x1.ad8d71d8c682dp1
+IEEEremainder,0x1.2647c10751ccp-6,-0x1.e3221751eabf1p0,0x1.e7bb365608064p-3
+IEEEremainder,-0x1.60376893d0838p-3,0x1.06eab1e883e1cp5,0x1.bd1fd9cbf203dp-2
+IEEEremainder,0x1.1a53f04d90e4cp-3,-0x1.2ddbaaae6a3fap-2,-0x1.bb05a2d532b2p-2
+IEEEremainder,0x1.548d3c188c51p-2,0x1.acbf9b5e7fe7ap0,0x1.579c4c585cd36p0
+IEEEremainder,-0x1.3839ceab3512p-4,0x1.a17de66dfd29bp1,-0x1.1cd5234239e18p-1
+IEEEremainder,0x1.dfb6af012bebep-1,0x1.dfb6af012bebep-1,0x1.23b777febfe1p3
+IEEEremainder,0x1.77027d1100f14p-1,-0x1.7fe4f5b4b64eep0,0x1.1db31a1e9b63cp1
+IEEEremainder,-0x1.ebb1ba9524da5p-4,-0x1.ebb1ba9524da5p-4,-0x1.8519f63a6904fp-1
+IEEEremainder,-0x1.708245d14a8b9p-1,-0x1.708245d14a8b9p-1,0x1.e8ec7cb7029b7p1
+IEEEremainder,-0x1.b532570494bdp-4,0x1.93d754a1d81d4p0,-0x1.af2a7a1221691p-2
+IEEEremainder,-0x1.270f63114a4e4p0,0x1.bc5a725b4cc0cp0,-0x1.71b4eab64b878p1
+IEEEremainder,-0x1.3813e4e6125c4p-2,-0x1.3813e4e6125c4p-2,0x1.6934bcf3ca13bp0
+IEEEremainder,0x1.3372b6c66f77ap-2,-0x1.bf1925b89cc6p0,-0x1.5d4e8cf17b17fp-1
+IEEEremainder,0x1.1414a3adb4c8p-1,0x1.1414a3adb4c8p-1,0x1.bcd487b099ff8p0
+IEEEremainder,-0x1.354e616b029b5p0,-0x1.354e616b029b5p0,0x1.2987b0d2c1c6ap4
+IEEEremainder,-0x1.07bd37471195dp-5,-0x1.07bd37471195dp-5,-0x1.3c87767dbe507p1
+IEEEremainder,-0x1.e3718da73d2cp-6,-0x1.9bf3f2267ec33p0,0x1.94662befe1ce8p-1
+IEEEremainder,0x1.4c2195d13e1ep-6,-0x1.44b69a320cb66p0,0x1.b7ded60c6ce92p-2
+IEEEremainder,0x1.038c62b1406b2p-6,-0x1.235df5ff05e7ap1,0x1.fb7e5ebb842a5p-5
+IEEEremainder,-0x1.939ff0dd73098p-2,0x1.6e869ba2dc439p2,0x1.bfb78c37a884cp-1
+IEEEremainder,-0x1.0186124b4bafp-2,0x1.fe393974641eep-2,0x1.7fdfa5dfd7e6fp-1
+IEEEremainder,0x1.1b9967dea8df8p-4,-0x1.82953f59dd2c5p-1,-0x1.a6086c55b2484p-1
+IEEEremainder,-0x1.3a3022dfc5a6ap0,-0x1.3a3022dfc5a6ap0,-0x1.67d0bdb25fc11p1
+IEEEremainder,0x1.131e46b7df6p-6,-0x1.9ba50827a27edp-1,0x1.a43dfa5d6179dp-2
+IEEEremainder,0x1.5e518f746e9ccp-2,0x1.85868ab677113p0,-0x1.2df226d95b6ap0
+IEEEremainder,-0x1.51e44e4fc4adep-2,-0x1.51e44e4fc4adep-2,0x1.8aa9327c3acacp-1
+IEEEremainder,0x1.822409e9132dp-3,-0x1.e4afee99b8ef4p-1,0x1.229c7889fedd4p0
+IEEEremainder,0x1.909d89e1f7307p-1,0x1.909d89e1f7307p-1,-0x1.75fc9f092b3a8p3
+IEEEremainder,0x1.44cda9dc59618p-1,0x1.44cda9dc59618p-1,0x1.2ba91f120e2dcp3
+IEEEremainder,0x1.1fc0ff61f7441p-1,-0x1.285e3caffdc53p-1,0x1.240f9e08fa84ap0
+IEEEremainder,-0x1.a1c7aba6daab9p-1,-0x1.a1c7aba6daab9p-1,-0x1.bc452fec006aep1
+IEEEremainder,-0x1.4035da047fb8p-4,-0x1.b4d8ac411492dp1,-0x1.aad6fd70f0951p-2
+IEEEremainder,0x1.b18fdae37de4p-8,0x1.8542f580f9183p-1,-0x1.762e62b585edp-6
+IEEEremainder,-0x1.1ed76b98f035cp-2,0x1.50a2ec449b72fp0,0x1.9858c72ad7806p-1
+IEEEremainder,0x1.27f544e1eb74dp1,-0x1.ae8037eb76c01p1,0x1.6b3abe66b11a7p2
+IEEEremainder,0x1.556c2751e3bfp-4,0x1.cfac7c5e66f14p0,0x1.ba55b9e948b55p-1
+IEEEremainder,0x1.939b8787f8a0cp-1,-0x1.a8442e2d22de2p-1,0x1.9defdada8dbf7p0
+IEEEremainder,0x1.2c877e8dcd8ep-4,-0x1.9bc975650ef5bp-1,-0x1.c15a6536c8a77p-2
+IEEEremainder,-0x1.2251737ff9d98p-3,-0x1.65b6be6482d5ep5,0x1.d1bca3305753ap-1
+IEEEremainder,0x1.ddb56687b4393p-5,0x1.ddb56687b4393p-5,0x1.72298db54d895p-3
+IEEEremainder,0x1.8ae6bfe8a9fdp-3,-0x1.417eacb67439ep0,-0x1.72db84b389798p-1
+IEEEremainder,0x1.e5e97b41c94bp-2,-0x1.8599a94908bd3p0,0x1.ff1408197b0ffp0
+IEEEremainder,0x1.bc8222d2d3c4p-5,0x1.6b90c5493d89cp0,0x1.5dacb432a6ebap0
+IEEEremainder,0x1.3cbcc2fea741p-4,-0x1.908c2172b4a34p-1,-0x1.b823b9d2898b6p-1
+IEEEremainder,0x1.069d3d55bdfa6p0,-0x1.a3b4f3d523d38p2,0x1.4392d771b78c1p1
+IEEEremainder,0x1.a717c4f38c853p-5,0x1.a717c4f38c853p-5,-0x1.a9c0eaf5d230ap0
+IEEEremainder,0x1.64d7ff718bba8p-1,0x1.64d7ff718bba8p-1,0x1.27a98dd41fd91p3
+IEEEremainder,-0x1.202706163244cp-1,-0x1.3d777b18721p5,-0x1.72ebb2f6a2b2ep0
+IEEEremainder,0x1.2967f1e7aeef8p-2,0x1.9af9a33b2fdccp0,0x1.509fa6c14420ep0
+IEEEremainder,-0x1.edef5630a84aep-1,-0x1.edef5630a84aep-1,0x1.2e01cbe060fbbp6
+IEEEremainder,-0x1.466c1a8b2e87p-5,0x1.38ce3ba3159f1p-1,0x1.4d34fd4bc8878p-2
+IEEEremainder,-0x1.1b5a021ae8447p-3,-0x1.1b5a021ae8447p-3,0x1.2deee2768e629p8
+IEEEremainder,-0x1.835165b6d5381p2,-0x1.835165b6d5381p2,0x1.72b2d8bc2092dp4
+IEEEremainder,0x1.8e6ba7288b34p-3,0x1.2661ac17c7835p1,0x1.0d7af1a53ed01p0
+IEEEremainder,-0x1.89f86f3ed2696p-1,0x1.3eade66d10b55p0,0x1.01d50f063cf5p1
+IEEEremainder,-0x1.13813e6f99302p-2,0x1.7e26c6bb96e0fp0,-0x1.2caf643a53735p-1
+IEEEremainder,-0x1.4e5482593a22p-1,0x1.0ecbcfc05249dp0,-0x1.b5f610ecef5adp0
+IEEEremainder,-0x1.8a4fb71feaebep-4,0x1.0b594e5f6c4dcp2,-0x1.a0c6ef9843023p-3
+IEEEremainder,-0x1.d39e274325d28p-2,0x1.47a1933a4a8a6p3,-0x1.c8535b45da4bfp0
+IEEEremainder,-0x1.83130de2f670ap-4,-0x1.83130de2f670ap-4,0x1.3c89aa3c489edp-2
+IEEEremainder,-0x1.c89c4903975d8p-3,0x1.a86a46eb2d8acp0,0x1.40fe8ab26af9ap-1
+IEEEremainder,0x1.4ac369a655b8ap-1,0x1.4ac369a655b8ap-1,-0x1.6d6526e38cecp0
+IEEEremainder,0x1.5227707fdb7ap-2,0x1.6a725355f68c1p2,0x1.554fdc4df8d47p-1
+IEEEremainder,0x1.3fd82958212dp-4,-0x1.541fb6d735eaep0,-0x1.681d396cb7fdbp-2
+IEEEremainder,-0x1.f4326fce678dfp-2,-0x1.f4326fce678dfp-2,-0x1.6f861c35a4158p0
+IEEEremainder,-0x1.89edf6bf8f46p-4,0x1.3f80a8f4e298dp5,-0x1.559f9988cf55dp-2
+IEEEremainder,-0x1.4800ae86e9d7dp0,-0x1.4800ae86e9d7dp0,0x1.ef985af4ec19dp2
+max,0x1.715eda6ab8562p2,-0x1.123d877d62ecbp2,0x1.715eda6ab8562p2
+max,0x1.6bf99eae2daf1p-1,0x1.04a084b48941ap-5,0x1.6bf99eae2daf1p-1
+max,0x1.71d3162e989e1p-2,-0x1.217c07c022339p1,0x1.71d3162e989e1p-2
+max,0x1.037880e10da75p0,0x1.5ca0113354b34p-2,0x1.037880e10da75p0
+max,-0x1.16982379a6ff7p-6,-0x1.4b06ec133eb96p-1,-0x1.16982379a6ff7p-6
+max,0x1.ec44f0f2f90acp-1,-0x1.34ea1e1f5a4e9p0,0x1.ec44f0f2f90acp-1
+max,0x1.9f4c3f68431f6p0,-0x1.01a6366c18264p1,0x1.9f4c3f68431f6p0
+max,0x1.30c55ff162bb6p4,0x1.30c55ff162bb6p4,0x1.3a5a028db64d5p2
+max,0x1.bf9b42ac4f87fp-1,-0x1.8a3e408bc21dbp1,0x1.bf9b42ac4f87fp-1
+max,0x1.f6c2140945b18p0,0x1.f6c2140945b18p0,0x1.bd6a19029eb1fp0
+max,0x1.361fe90d27d6cp0,-0x1.eb5bd9156282dp1,0x1.361fe90d27d6cp0
+max,-0x1.3a7b369b89b3fp-3,-0x1.c1423acc0c629p-3,-0x1.3a7b369b89b3fp-3
+max,0x1.d27991c908bf4p0,0x1.c36246cf7bc62p-2,0x1.d27991c908bf4p0
+max,-0x1.2fa756615e776p-1,-0x1.2ec76e5f00cb2p1,-0x1.2fa756615e776p-1
+max,-0x1.584cbd3d68345p-2,-0x1.584cbd3d68345p-2,-0x1.0da698ff2189fp0
+max,0x1.0c1cb0a904868p0,0x1.86872e85fffa9p-1,0x1.0c1cb0a904868p0
+max,0x1.0670c61480ba2p-1,-0x1.3bc0af2977443p-1,0x1.0670c61480ba2p-1
+max,0x1.2df485b8c1266p0,-0x1.a256078c47936p-1,0x1.2df485b8c1266p0
+max,-0x1.f38f820ff6615p-2,-0x1.01a1f7668b30ep1,-0x1.f38f820ff6615p-2
+max,-0x1.607caf8f08634p-3,-0x1.607caf8f08634p-3,-0x1.bd9ff189e6452p-1
+max,-0x1.b3584f460ebp-1,-0x1.d0e68946f28eep1,-0x1.b3584f460ebp-1
+max,-0x1.f97bf5141db1cp-3,-0x1.f97bf5141db1cp-3,-0x1.6db0a4b285f5cp3
+max,0x1.8ee8bddeb6d5ap-1,-0x1.93a1a1f3bd04ep0,0x1.8ee8bddeb6d5ap-1
+max,0x1.2728b6cd3c3d6p1,0x1.2728b6cd3c3d6p1,0x1.136773166616cp-2
+max,-0x1.eabb7b627b94p-3,-0x1.83bc983ee0ee9p-1,-0x1.eabb7b627b94p-3
+max,-0x1.38bea79bd28ffp-1,-0x1.38bea79bd28ffp-1,-0x1.0de83a1879db6p0
+max,-0x1.951d35a1da33dp-2,-0x1.951d35a1da33dp-2,-0x1.4abcb196e114ap-1
+max,0x1.0c6b8df400fe2p3,0x1.e47b3f44f389ap0,0x1.0c6b8df400fe2p3
+max,-0x1.83e508272f9c9p-1,-0x1.c1fa7b1d558a9p2,-0x1.83e508272f9c9p-1
+max,-0x1.b8135fe636e83p-1,-0x1.b8135fe636e83p-1,-0x1.0f39893694473p0
+max,0x1.24d75898c990bp-2,0x1.24d75898c990bp-2,-0x1.7004d30c2bf16p-1
+max,-0x1.ebbe591280802p0,-0x1.ebbe591280802p0,-0x1.8f7b657584d81p1
+max,-0x1.5e836be36ab5ap-3,-0x1.5e836be36ab5ap-3,-0x1.2e83e0ec4b20cp0
+max,0x1.84e6de8132685p-1,0x1.84e6de8132685p-1,-0x1.79f0d4fcacc49p-1
+max,0x1.818ace8d1e8adp0,0x1.c32c0459a4543p-1,0x1.818ace8d1e8adp0
+max,0x1.5ce7f477b5eebp-1,0x1.ec114bb26ae73p-2,0x1.5ce7f477b5eebp-1
+max,-0x1.069211abc123dp0,-0x1.9a15177bbfc47p0,-0x1.069211abc123dp0
+max,0x1.4ad52107f7727p-1,0x1.2bb4b116c81dep-1,0x1.4ad52107f7727p-1
+max,0x1.4cc769cfe9596p0,0x1.4cc769cfe9596p0,-0x1.169630d7de745p0
+max,0x1.7345b49b70be8p0,0x1.7345b49b70be8p0,0x1.0517fde42ca7dp0
+max,0x1.c4f4c38294774p0,0x1.4acb03f65488ap-5,0x1.c4f4c38294774p0
+max,0x1.4d16731fd3b9bp1,-0x1.e69f72e796907p-2,0x1.4d16731fd3b9bp1
+max,-0x1.454ece2014dc9p-1,-0x1.d552258c9a76ep-1,-0x1.454ece2014dc9p-1
+max,0x1.6fd73ebf324fp-2,-0x1.abb9930e9d057p-5,0x1.6fd73ebf324fp-2
+max,0x1.48a204ec37209p0,0x1.48a204ec37209p0,0x1.7d7fd6725396bp-1
+max,0x1.481e1a898f8d4p0,0x1.481e1a898f8d4p0,0x1.9cd901c3a1706p-1
+max,0x1.25cda40ee14ccp-3,-0x1.5c4cfc7b02eaep1,0x1.25cda40ee14ccp-3
+max,0x1.066d62f2bb4c1p0,0x1.066d62f2bb4c1p0,-0x1.a16b49a62fcfep-2
+max,0x1.301bff1794761p1,0x1.301bff1794761p1,-0x1.4815e57b7ec39p1
+max,-0x1.50844bd0c2fe1p0,-0x1.50844bd0c2fe1p0,-0x1.0f44240c9a3eap4
+max,0x1.f775724f9ed8dp0,0x1.f9f83c6009199p-3,0x1.f775724f9ed8dp0
+max,0x1.cfe7908fa475cp3,-0x1.4e5b60ae25edcp1,0x1.cfe7908fa475cp3
+max,0x1.2fbd00c704c43p-1,0x1.14b855d469e2bp-1,0x1.2fbd00c704c43p-1
+max,0x1.23466b685575bp2,0x1.a846a5c2b602cp-1,0x1.23466b685575bp2
+max,-0x1.0e0421fe943dbp1,-0x1.444d05ceb82d9p2,-0x1.0e0421fe943dbp1
+max,-0x1.d7bf6d0f640e6p-3,-0x1.d7bf6d0f640e6p-3,-0x1.93d6d88b65475p-2
+max,0x1.2c2a52842bcaep0,0x1.2c2a52842bcaep0,-0x1.3a47ff2c86de4p0
+max,0x1.937cf65a16ef7p4,0x1.a92448b787444p2,0x1.937cf65a16ef7p4
+max,0x1.708da1a5f1218p8,0x1.708da1a5f1218p8,0x1.34fafae05fb8ap-1
+max,0x1.a25f647876149p0,0x1.a25f647876149p0,0x1.6be965de57989p-4
+max,0x1.969fa2309498fp0,0x1.7b1f02d845448p-1,0x1.969fa2309498fp0
+max,0x1.4074059f5f18fp-3,0x1.4074059f5f18fp-3,-0x1.e3237282cb7ecp0
+max,0x1.9c01ebf07555fp1,0x1.fbd34ac0f39b7p-1,0x1.9c01ebf07555fp1
+max,0x1.90c7632923b73p-2,0x1.90c7632923b73p-2,-0x1.8152574bb0256p-1
+max,-0x1.841b121c3df5ap0,-0x1.841b121c3df5ap0,-0x1.5a0bc05bda8bp1
+max,-0x1.6cb075dcc54b8p-3,-0x1.a5dd9922cb9c1p0,-0x1.6cb075dcc54b8p-3
+max,0x1.a2494106a27f9p-1,0x1.a2494106a27f9p-1,-0x1.2b605d792e652p-1
+max,0x1.b13301e8f9cc5p1,0x1.b13301e8f9cc5p1,-0x1.3f3e72b6d33b4p0
+max,0x1.0bdc0c6797ebcp0,0x1.0bdc0c6797ebcp0,-0x1.08b82c1e635efp0
+max,0x1.245c222ba2cc1p0,0x1.644982935e712p-1,0x1.245c222ba2cc1p0
+max,0x1.52fb4ada5ee08p0,-0x1.05d3d956fa82ap4,0x1.52fb4ada5ee08p0
+max,-0x1.488ad710699ebp0,-0x1.488ad710699ebp0,-0x1.033b00e6a52e4p2
+max,0x1.e0d08b88b0fefp-1,0x1.e0d08b88b0fefp-1,-0x1.d324ede2c9a2dp-1
+max,0x1.c1f03b5c16e5fp-1,-0x1.02593399b1ba9p1,0x1.c1f03b5c16e5fp-1
+max,-0x1.b27fab5b5f889p-6,-0x1.b27fab5b5f889p-6,-0x1.4e834b39a50adp-2
+max,-0x1.22f533bcce775p-1,-0x1.22f533bcce775p-1,-0x1.6d68dc73dde4ap3
+max,0x1.da40eff1835b9p-3,0x1.da40eff1835b9p-3,-0x1.1eae7dfffe30bp2
+max,0x1.0e8be2988575dp-2,-0x1.59b27bbd180fap-2,0x1.0e8be2988575dp-2
+max,-0x1.0976afc0a9856p-3,-0x1.32a346caf9a8ep5,-0x1.0976afc0a9856p-3
+max,0x1.f24f3a1dca83p1,-0x1.1131e584a301ep-9,0x1.f24f3a1dca83p1
+max,0x1.9de4a5bce44bp-3,0x1.9de4a5bce44bp-3,-0x1.91cbaecf6868ep-2
+max,0x1.4c8c2b604cc7ap-1,0x1.4c8c2b604cc7ap-1,-0x1.25d9225df065bp-2
+max,0x1.f3993ce1d34d7p-4,-0x1.828ccd9d93983p2,0x1.f3993ce1d34d7p-4
+max,0x1.811a9846af52p-1,0x1.811a9846af52p-1,0x1.2a940e0025e4bp-3
+max,0x1.03276c4c1edf8p2,0x1.03276c4c1edf8p2,0x1.00fab79405848p-4
+max,-0x1.4223e3c3fcc54p-2,-0x1.4223e3c3fcc54p-2,-0x1.b34bd3516cf55p-2
+max,0x1.a7dc019ee8b93p-1,0x1.0c101e188a668p-3,0x1.a7dc019ee8b93p-1
+max,0x1.6b73c740b2a91p1,0x1.6b73c740b2a91p1,-0x1.5c10a67c1a282p-3
+max,-0x1.c0c1f9d834eeap-1,-0x1.c0c1f9d834eeap-1,-0x1.ec07432e06953p-1
+max,-0x1.eebed0cb2df88p-1,-0x1.eebed0cb2df88p-1,-0x1.1184b287779a4p0
+max,0x1.b7efe44adf4c4p0,-0x1.5a74dc1b5f887p0,0x1.b7efe44adf4c4p0
+max,0x1.323224efdc45ep-2,-0x1.8603e2a67a9ebp-2,0x1.323224efdc45ep-2
+max,0x1.49adbf589f7cdp-2,0x1.49adbf589f7cdp-2,-0x1.7e1ede8b0dcf1p0
+max,0x1.feadf76e213c5p-2,-0x1.38424eaa9f7d7p-1,0x1.feadf76e213c5p-2
+max,0x1.169084b55ce96p0,0x1.169084b55ce96p0,0x1.00dd40de863e5p0
+max,-0x1.3bd29ad82ab5fp-1,-0x1.ddb7032b6ec4ep3,-0x1.3bd29ad82ab5fp-1
+max,0x1.a4b7216b2e697p-1,0x1.0e69e57c45876p-1,0x1.a4b7216b2e697p-1
+max,0x1.42b704013ef84p0,-0x1.9871fcfe384eep-1,0x1.42b704013ef84p0
+max,0x1.375f4517cc0f8p-2,0x1.375f4517cc0f8p-2,-0x1.104d97045573fp0
+max,0x1.dcae4475307ccp-1,0x1.6d0a9164169e2p-3,0x1.dcae4475307ccp-1
+max,-0x1.f19b81b13d60fp-1,-0x1.f19b81b13d60fp-1,-0x1.12d9ae07eb3e6p0
+max,0x1.9b5c6c0054a45p0,-0x1.8b39de59fe01ap2,0x1.9b5c6c0054a45p0
+max,0x1.a14d6b9b7b3e6p-5,0x1.a14d6b9b7b3e6p-5,0x1.033cd886eed37p-5
+max,-0x1.c16334a678feap-1,-0x1.c16334a678feap-1,-0x1.21eb26cd790ddp0
+max,-0x1.77317877b98eap0,-0x1.1230ac4fdeaefp1,-0x1.77317877b98eap0
+max,0x1.53daa2336cc14p6,0x1.ae5c124ff767dp-1,0x1.53daa2336cc14p6
+max,0x1.508ec20cff9c8p3,0x1.508ec20cff9c8p3,-0x1.ca02307be68b8p1
+max,0x1.2f38cee16d234p1,-0x1.154fba07bd232p0,0x1.2f38cee16d234p1
+max,0x1.91d1d90fe15e1p0,-0x1.836bbbddcf13bp0,0x1.91d1d90fe15e1p0
+max,-0x1.fa036659caf6bp-1,-0x1.fa036659caf6bp-1,-0x1.9bc1460fe4d16p0
+max,0x1.3174b9a6a4a0cp0,0x1.3174b9a6a4a0cp0,-0x1.b5665b6332761p-1
+max,-0x1.11fa1ba53bea8p-4,-0x1.11fa1ba53bea8p-4,-0x1.b409525077441p-2
+max,0x1.36487ea0ca3f4p-1,-0x1.6d228f1905fap-1,0x1.36487ea0ca3f4p-1
+max,0x1.394210da3385ap1,0x1.6784e31973bbfp-1,0x1.394210da3385ap1
+max,0x1.d493b91366591p1,0x1.d493b91366591p1,0x1.1854337bb9aa5p-1
+max,0x1.a16d26d4804fep1,0x1.46098dafdf442p-4,0x1.a16d26d4804fep1
+max,0x1.ad5bebfca748fp2,-0x1.08911ef2e9a3dp0,0x1.ad5bebfca748fp2
+max,0x1.d937b7c5283edp-3,0x1.3ae867da6c443p-3,0x1.d937b7c5283edp-3
+max,0x1.3d711a6e2853fp0,0x1.3d711a6e2853fp0,-0x1.4e308f2d90dap-2
+max,0x1.35c41375b8715p1,0x1.02661c271b354p1,0x1.35c41375b8715p1
+max,-0x1.181f3885ccaabp-5,-0x1.847a53004ca9fp-1,-0x1.181f3885ccaabp-5
+max,0x1.bce610feea79cp3,0x1.b68d06485e079p0,0x1.bce610feea79cp3
+max,0x1.05a4b8c49b9c6p2,0x1.05a4b8c49b9c6p2,0x1.23e045b36cf71p-1
+max,0x1.23c70a9355ee2p6,-0x1.be2c987cc3f46p-2,0x1.23c70a9355ee2p6
+max,0x1.6aa2ccce0ee2p-1,0x1.1c6b6c3be7217p-1,0x1.6aa2ccce0ee2p-1
+max,0x1.47b5a27f88cd4p0,-0x1.ba7f7c40d48bap-1,0x1.47b5a27f88cd4p0
+max,0x1.1ffc51da30594p4,0x1.1ffc51da30594p4,-0x1.a99227ca9ec4dp-4
+max,0x1.f350685643306p4,0x1.f350685643306p4,-0x1.1ce3ee03d9515p2
+max,0x1.164ba7603719p-2,0x1.439bd3af0c60cp-5,0x1.164ba7603719p-2
+max,-0x1.0c5c4e2fa7943p-1,-0x1.0c5c4e2fa7943p-1,-0x1.685ba9ed1cd17p1
+max,-0x1.60bf854ce3c4dp-5,-0x1.2ef2aa9007428p0,-0x1.60bf854ce3c4dp-5
+max,0x1.cee376c29a96p-1,0x1.cee376c29a96p-1,-0x1.9654482c44979p-1
+max,-0x1.1caeeb891affdp1,-0x1.cb3ebdd8be3f5p1,-0x1.1caeeb891affdp1
+max,0x1.174344e5e0291p3,0x1.174344e5e0291p3,0x1.a6f7bfffd3397p-1
+max,-0x1.325ede26966aep-2,-0x1.9e6840eb53a02p0,-0x1.325ede26966aep-2
+max,0x1.e87e0753cc668p0,0x1.4dcd0a4107d63p-2,0x1.e87e0753cc668p0
+max,0x1.f450bb8dc737p-3,-0x1.884d05667a039p-2,0x1.f450bb8dc737p-3
+max,0x1.79db0a88a6178p-5,-0x1.b779584a48313p-2,0x1.79db0a88a6178p-5
+max,0x1.627d2bd7d0c3p-1,0x1.627d2bd7d0c3p-1,-0x1.5d3cc03d1c5dp-2
+max,-0x1.6e681a570701dp-1,-0x1.321834c90d23ep0,-0x1.6e681a570701dp-1
+max,-0x1.03f4bfa45cb81p1,-0x1.68648b4580fccp4,-0x1.03f4bfa45cb81p1
+max,-0x1.a5a2883f67b46p-4,-0x1.617687be3ec66p-2,-0x1.a5a2883f67b46p-4
+max,0x1.23efdf13fb84ap0,0x1.ab50f49f951aep-1,0x1.23efdf13fb84ap0
+max,0x1.b78f97655b26fp-1,0x1.b78f97655b26fp-1,0x1.1c7a04b4e9c28p-1
+max,0x1.4a3e497c49471p0,0x1.6548680dd16d5p-2,0x1.4a3e497c49471p0
+max,-0x1.dd070798cfdb3p0,-0x1.dd070798cfdb3p0,-0x1.03ee413663952p5
+max,0x1.300b8893f13f6p0,-0x1.0330898a2cc48p1,0x1.300b8893f13f6p0
+max,0x1.0ab1704aee3d6p0,0x1.b4bd912f7d76ep-5,0x1.0ab1704aee3d6p0
+max,-0x1.1b8dc0def141ap-1,-0x1.745059407937cp1,-0x1.1b8dc0def141ap-1
+max,0x1.87de0f34c2334p-2,0x1.87de0f34c2334p-2,-0x1.14bbf7bcc0a22p1
+max,0x1.5cfe604aa0362p-4,0x1.5cfe604aa0362p-4,-0x1.19824c8deb282p0
+max,0x1.817696d8ca183p-3,-0x1.3eb71189b4143p-1,0x1.817696d8ca183p-3
+max,0x1.66f42e69b47d7p-1,0x1.66f42e69b47d7p-1,-0x1.d449b1f44e633p0
+max,0x1.b92e7b3d72f42p1,0x1.0e56c2680ae1ap-2,0x1.b92e7b3d72f42p1
+max,0x1.7884f26864993p-1,-0x1.07ce3589c58f3p0,0x1.7884f26864993p-1
+max,-0x1.a8e4d58a575e4p-2,-0x1.a8e4d58a575e4p-2,-0x1.52b57140d661cp-1
+max,0x1.074337293b9dap1,0x1.074337293b9dap1,0x1.0d1f59d7b33d2p0
+max,0x1.b030a230348f5p-1,0x1.b030a230348f5p-1,-0x1.1ea0d9f821ddcp1
+max,-0x1.086488fa12f92p0,-0x1.b9fb23d610031p0,-0x1.086488fa12f92p0
+max,-0x1.5f4dd1578a099p-3,-0x1.5f4dd1578a099p-3,-0x1.a7081c64b4c25p-2
+max,-0x1.1fc6aa5158e82p-2,-0x1.1fc6aa5158e82p-2,-0x1.5392d0c9f5f0ep0
+max,0x1.44d25fe19310bp-1,0x1.44d25fe19310bp-1,0x1.6937b399c0539p-4
+max,0x1.417bad30a66f2p-1,-0x1.eb6772df6580ap0,0x1.417bad30a66f2p-1
+max,0x1.abb329087d29p-3,0x1.abb329087d29p-3,0x1.395b340a208b1p-3
+max,0x1.5374167cdb884p1,0x1.5374167cdb884p1,-0x1.b02196e1ff943p3
+max,0x1.56d6c27e9a1fp0,0x1.e505c8e2c4f68p-2,0x1.56d6c27e9a1fp0
+max,0x1.0c078dba2e9b6p4,0x1.0c078dba2e9b6p4,-0x1.6231dba32a3c8p-2
+max,-0x1.9b4d30df0f9e9p0,-0x1.34e1cb729841dp2,-0x1.9b4d30df0f9e9p0
+max,0x1.21ff139342d29p0,-0x1.56d9f8f4d560ep2,0x1.21ff139342d29p0
+max,-0x1.09729d33fdad6p0,-0x1.a1ac1648c825p1,-0x1.09729d33fdad6p0
+max,0x1.6e1aeba8be2e1p2,-0x1.07f074add9e8cp1,0x1.6e1aeba8be2e1p2
+max,0x1.a474ba1acb868p-1,0x1.a474ba1acb868p-1,-0x1.07813c5159cb8p0
+max,0x1.46456ec6f64b7p-4,0x1.46456ec6f64b7p-4,-0x1.f81c22ba6fd27p3
+max,-0x1.a90402ec8c761p-1,-0x1.a90402ec8c761p-1,-0x1.30989e3693c89p3
+max,0x1.19ebb41478199p0,0x1.19ebb41478199p0,0x1.168cc73044492p0
+max,0x1.f89e84c96dc67p0,0x1.f89e84c96dc67p0,0x1.1728a3644e497p-2
+max,0x1.cce3b436bec31p1,0x1.cce3b436bec31p1,-0x1.b6ea28bd83144p-1
+max,0x1.09c94ad4a514fp-1,0x1.09c94ad4a514fp-1,-0x1.b6a6a20dd7c58p-2
+max,0x1.04f2c8d7f6f81p-3,0x1.04f2c8d7f6f81p-3,-0x1.1dca4777e34edp0
+max,0x1.0e51e5bae1b4fp3,-0x1.eedd537f6ff89p-2,0x1.0e51e5bae1b4fp3
+max,-0x1.01be92a228736p0,-0x1.1b163fbe40b0ap0,-0x1.01be92a228736p0
+max,0x1.3209d6c43fef1p0,0x1.3209d6c43fef1p0,-0x1.3b26a1e0fb67dp0
+max,-0x1.ca4fd4ce38496p0,-0x1.82f541d1d82ap6,-0x1.ca4fd4ce38496p0
+max,0x1.21463a760ffe5p-2,-0x1.ea66ae1526363p-1,0x1.21463a760ffe5p-2
+max,0x1.5abae34817b0dp-1,0x1.5abae34817b0dp-1,0x1.ad6480acff31bp-4
+max,0x1.197568e5da05p0,0x1.6be9f832a5009p-1,0x1.197568e5da05p0
+max,-0x1.31cdc26bee4dap-2,-0x1.31cdc26bee4dap-2,-0x1.c97651d6a2bb1p-2
+max,0x1.de296ad50534fp-3,-0x1.d7d84b8df6dc8p2,0x1.de296ad50534fp-3
+max,0x1.a138e38ed9c27p-1,0x1.a138e38ed9c27p-1,-0x1.a461a761a5258p-5
+max,0x1.33fa6b58ddf8ep2,0x1.33fa6b58ddf8ep2,-0x1.4bd861119b025p0
+max,-0x1.0bcc00461b547p1,-0x1.50643ab09ebecp1,-0x1.0bcc00461b547p1
+max,0x1.a5405570b9037p1,-0x1.2c220c5318d9bp0,0x1.a5405570b9037p1
+max,0x1.0ab97b7b68f01p1,0x1.0ab97b7b68f01p1,-0x1.50348eb28878bp0
+max,0x1.eebcd506d7814p0,0x1.eebcd506d7814p0,-0x1.e3279f6a1fdc4p-2
+max,0x1.cbc718a2e8753p0,0x1.0b2651a6c4e51p0,0x1.cbc718a2e8753p0
+max,0x1.af34db6a803bp-2,0x1.af34db6a803bp-2,-0x1.364e5e5cce93p0
+max,0x1.d07715682f3e9p-2,0x1.be703a2ad1a97p-2,0x1.d07715682f3e9p-2
+max,-0x1.0f68a842c56edp4,-0x1.0f68a842c56edp4,-0x1.1f458b97e53d4p14
+max,-0x1.bb28456fa0b39p-1,-0x1.150b185442475p2,-0x1.bb28456fa0b39p-1
+max,0x1.ddb257fcd3ef2p-4,-0x1.e468c0dddb3a4p0,0x1.ddb257fcd3ef2p-4
+min,-0x1.13a94916c6632p1,0x1.ac23ebf48ab15p-1,-0x1.13a94916c6632p1
+min,0x1.2d7766f5c9b61p0,0x1.2d7766f5c9b61p0,0x1.59be058e00538p0
+min,0x1.fe34c9c10228dp-2,0x1.0c09f682d7678p3,0x1.fe34c9c10228dp-2
+min,-0x1.ce89c50cf4192p-1,0x1.3491274e10f1ep-1,-0x1.ce89c50cf4192p-1
+min,-0x1.4981407ee7abep3,-0x1.32fa1d18254cbp2,-0x1.4981407ee7abep3
+min,-0x1.3e13233971719p0,-0x1.3e13233971719p0,0x1.4239cce7fed1ap0
+min,-0x1.b93ae6945c66cp-2,-0x1.b93ae6945c66cp-2,0x1.4e41c5625209ap2
+min,-0x1.bae87769f9bc5p-4,0x1.1cfccaf510c3dp1,-0x1.bae87769f9bc5p-4
+min,-0x1.4513fe72d84fcp-1,-0x1.2204a6b91c706p-2,-0x1.4513fe72d84fcp-1
+min,-0x1.7d39541b56792p-1,-0x1.7d39541b56792p-1,0x1.9e00ae836a6d8p-4
+min,0x1.fcec31bd378f2p-4,0x1.cbcbe0818db38p-1,0x1.fcec31bd378f2p-4
+min,-0x1.074fee289c7a2p-1,-0x1.074fee289c7a2p-1,-0x1.3709c74314ba2p-2
+min,0x1.509aa2555639dp-2,0x1.7ac8e766b2394p-1,0x1.509aa2555639dp-2
+min,-0x1.b04a57efa1058p4,-0x1.b04a57efa1058p4,-0x1.8a85df2ddf534p-3
+min,-0x1.ca5a826213c65p0,-0x1.adfd7e008374ap0,-0x1.ca5a826213c65p0
+min,-0x1.3d06c467df783p0,0x1.b3362c98633e6p-3,-0x1.3d06c467df783p0
+min,-0x1.9cc47a7ba3095p-3,0x1.9d58995951072p2,-0x1.9cc47a7ba3095p-3
+min,0x1.86c86459dcf24p-1,0x1.86c86459dcf24p-1,0x1.b629984e3e5cep1
+min,0x1.61b79fa5440edp-1,0x1.f0b0816f2d328p1,0x1.61b79fa5440edp-1
+min,-0x1.de5e4512ed9afp-2,-0x1.de5e4512ed9afp-2,-0x1.594a6949300bfp-3
+min,-0x1.50b9c30194096p0,0x1.16d29d92eda58p1,-0x1.50b9c30194096p0
+min,0x1.dbdd3fd40e2c8p-1,0x1.dbdd3fd40e2c8p-1,0x1.03caf44b9ff2bp3
+min,0x1.6bfe7dedc912p2,0x1.6bfe7dedc912p2,0x1.c0c15315feae2p11
+min,-0x1.42f6f8eb41752p1,-0x1.82a5d68d432f7p-1,-0x1.42f6f8eb41752p1
+min,-0x1.3af239c2fc405p1,0x1.e184a195ab379p-2,-0x1.3af239c2fc405p1
+min,-0x1.26818ff4a5f7cp0,-0x1.095d94f089fcep0,-0x1.26818ff4a5f7cp0
+min,-0x1.bb0050d3325f6p-2,-0x1.521fc1c60961ep-3,-0x1.bb0050d3325f6p-2
+min,-0x1.2b9268bb58f28p-1,0x1.d90661b86086dp-3,-0x1.2b9268bb58f28p-1
+min,-0x1.24ee803b1efa2p1,0x1.71b5596e0ed89p-1,-0x1.24ee803b1efa2p1
+min,-0x1.b2249746077e9p-1,-0x1.b2249746077e9p-1,0x1.0946a46409006p-3
+min,0x1.0b91b04e6c8e2p0,0x1.0b91b04e6c8e2p0,0x1.27c18403a04f5p0
+min,0x1.27e9a5f752112p-2,0x1.52fc515f8014p-2,0x1.27e9a5f752112p-2
+min,0x1.d500a898f7f24p-1,0x1.d500a898f7f24p-1,0x1.4498cb7af2b64p2
+min,0x1.b8f586841bffcp0,0x1.61c0998390625p1,0x1.b8f586841bffcp0
+min,-0x1.443e68ba0322fp1,0x1.d7890d0ecaee8p3,-0x1.443e68ba0322fp1
+min,0x1.804ac6cecdb39p1,0x1.895ea7c1fcf4fp1,0x1.804ac6cecdb39p1
+min,-0x1.815862f8f6485p1,-0x1.815862f8f6485p1,-0x1.bfe7b047c0cd2p-1
+min,-0x1.19c230e5106cep-4,-0x1.19c230e5106cep-4,0x1.83646939220bap-3
+min,-0x1.33ed0b4cef53ep1,-0x1.bcbe25bbe45a3p-1,-0x1.33ed0b4cef53ep1
+min,-0x1.6edaedc73ac28p-1,-0x1.6edaedc73ac28p-1,0x1.f5ea59a73d2c8p-1
+min,-0x1.8a32540cff257p-1,0x1.d891764b4afc7p0,-0x1.8a32540cff257p-1
+min,0x1.fd551bb1c0d14p-3,0x1.a10e43e8080e7p-2,0x1.fd551bb1c0d14p-3
+min,-0x1.bd5990bc301d7p-5,-0x1.bd5990bc301d7p-5,-0x1.3ad52414fb659p-5
+min,0x1.cc95de78aef8dp-2,0x1.5cda5bd72af8fp0,0x1.cc95de78aef8dp-2
+min,-0x1.a7a2275c32905p-3,0x1.95476aa06da47p1,-0x1.a7a2275c32905p-3
+min,-0x1.4e336ed184b9p1,-0x1.0a824d5327642p0,-0x1.4e336ed184b9p1
+min,0x1.2696241411401p-4,0x1.2696241411401p-4,0x1.9c63dc87aaa93p-2
+min,-0x1.fd70ee2cf166dp1,-0x1.8b5e045b5fdbap-1,-0x1.fd70ee2cf166dp1
+min,0x1.f8c4c8fa2978ap-2,0x1.d9d4d4e4e68fap-1,0x1.f8c4c8fa2978ap-2
+min,-0x1.a0857e256e027p-3,0x1.4b4c644c8e532p4,-0x1.a0857e256e027p-3
+min,-0x1.bd89e6a9ea89p0,-0x1.bd89e6a9ea89p0,-0x1.9636ca86ebaadp-3
+min,-0x1.cffefe8a12e9ep0,0x1.3829a15c0609fp0,-0x1.cffefe8a12e9ep0
+min,-0x1.e80ec3fbd90a2p1,0x1.7a1ed46d8f78ep-2,-0x1.e80ec3fbd90a2p1
+min,0x1.d2c97c3e885aap-1,0x1.6bc43d43e903ep3,0x1.d2c97c3e885aap-1
+min,-0x1.bb71e7c6cab53p-7,-0x1.bb71e7c6cab53p-7,0x1.d8c3440fd7647p-1
+min,-0x1.67046d956ab12p1,-0x1.67046d956ab12p1,0x1.0ca6a127b808bp-3
+min,-0x1.07e98dc39755ep2,-0x1.752531e8e90d2p0,-0x1.07e98dc39755ep2
+min,-0x1.44a6e426d8222p2,0x1.e22481ebfe03bp5,-0x1.44a6e426d8222p2
+min,0x1.e41e3f941ff5ep-1,0x1.6d8025be2dbffp2,0x1.e41e3f941ff5ep-1
+min,-0x1.5446e930c75aap1,-0x1.49da496af8d41p1,-0x1.5446e930c75aap1
+min,0x1.5f38f4ec94713p-2,0x1.5f38f4ec94713p-2,0x1.7a01220226f5fp-2
+min,-0x1.9b4a035c03614p-1,-0x1.6a4d29ecc2fa7p-4,-0x1.9b4a035c03614p-1
+min,0x1.20b4c80b25be9p-1,0x1.dc7c67c9fd726p-1,0x1.20b4c80b25be9p-1
+min,0x1.f22075cdec45cp-5,0x1.7cbbc02f42fb1p-2,0x1.f22075cdec45cp-5
+min,-0x1.3dab3dd2da974p0,-0x1.3dab3dd2da974p0,-0x1.577dbfedb7979p-2
+min,-0x1.008180aa3ad24p1,-0x1.008180aa3ad24p1,-0x1.aa8ca022955dep-1
+min,-0x1.63f7ea987d0adp-4,-0x1.63f7ea987d0adp-4,0x1.d0e077799d2e8p1
+min,-0x1.dde07e80db509p-1,-0x1.dde07e80db509p-1,0x1.db20cf698cfe4p-1
+min,-0x1.ae1b9fe894e52p-2,0x1.6432af4638239p0,-0x1.ae1b9fe894e52p-2
+min,-0x1.9d83a101a86ccp0,-0x1.a653f08061f97p-4,-0x1.9d83a101a86ccp0
+min,0x1.99efea49f1495p-3,0x1.fad7dd51e4117p-1,0x1.99efea49f1495p-3
+min,-0x1.35497388bf3cbp2,-0x1.35497388bf3cbp2,0x1.2baeb4219b47ap-1
+min,0x1.0fadb0fb155c3p-1,0x1.0fadb0fb155c3p-1,0x1.8657d9977d917p0
+min,-0x1.46e4e9b96f9f7p1,-0x1.46e4e9b96f9f7p1,0x1.18aa8945c41ffp0
+min,-0x1.a0fd901352ccap0,-0x1.a0fd901352ccap0,0x1.88c5018a56f78p-5
+min,-0x1.674b8a2044c13p-1,-0x1.674b8a2044c13p-1,-0x1.0de4dda748eeep-1
+min,-0x1.a85f46badbc5cp0,-0x1.a85f46badbc5cp0,-0x1.7261fbfb3c976p-1
+min,-0x1.b9df217db7a2cp-2,0x1.0889c05cd2ecap-1,-0x1.b9df217db7a2cp-2
+min,-0x1.33221e13fc2dbp0,-0x1.6330d5283a276p-2,-0x1.33221e13fc2dbp0
+min,-0x1.88c13d0fb5a22p-2,-0x1.88c13d0fb5a22p-2,0x1.3986eb6becbbp-2
+min,-0x1.5d76c17f9c893p2,-0x1.7aa2aa56413p1,-0x1.5d76c17f9c893p2
+min,-0x1.360be8f735b0dp1,-0x1.b9df1f32ccee4p-3,-0x1.360be8f735b0dp1
+min,-0x1.3772007c0cb03p2,-0x1.3772007c0cb03p2,0x1.d1758810db26dp-4
+min,-0x1.4bd7e063b8ad8p2,-0x1.4bd7e063b8ad8p2,0x1.39a6d6f00bffdp0
+min,0x1.bd9ebd3b18aa4p-6,0x1.bd9ebd3b18aa4p-6,0x1.39d2605c7222ep0
+min,0x1.460bd0bfb9812p-2,0x1.cb61badc0d42ep-2,0x1.460bd0bfb9812p-2
+min,-0x1.1af162c525724p-2,-0x1.1af162c525724p-2,-0x1.09732a07365f2p-2
+min,-0x1.e358d4f069a66p2,-0x1.e358d4f069a66p2,0x1.ba64b7678c87dp4
+min,-0x1.cbf7833006116p0,-0x1.300a6e593b6cp-2,-0x1.cbf7833006116p0
+min,-0x1.20c3eb07baaeap-2,0x1.0a2dab0d9ca46p3,-0x1.20c3eb07baaeap-2
+min,0x1.8b2a647a609b7p-3,0x1.c8624c1a9621dp1,0x1.8b2a647a609b7p-3
+min,-0x1.3b0a1b6d077cdp4,-0x1.3b0a1b6d077cdp4,-0x1.067de6054e823p-1
+min,0x1.073456880db89p-1,0x1.073456880db89p-1,0x1.0f6614b3fe878p1
+min,-0x1.92a1feb2add1p-1,0x1.aa2e925776006p-2,-0x1.92a1feb2add1p-1
+min,-0x1.2d091736427b3p-1,-0x1.2d091736427b3p-1,-0x1.01434fc9abe1fp-1
+min,0x1.8c7b2d04ee95dp-4,0x1.8c7b2d04ee95dp-4,0x1.081d466e3ce4ap0
+min,-0x1.af8113522be2ep0,0x1.b3e4760fe707fp-2,-0x1.af8113522be2ep0
+min,-0x1.763300581d26dp-1,0x1.15a23a4a37ccfp0,-0x1.763300581d26dp-1
+min,-0x1.59565079e018cp-3,-0x1.59565079e018cp-3,0x1.b902426c23202p-3
+min,-0x1.2995e3abc47ddp-1,-0x1.2995e3abc47ddp-1,-0x1.089159215c8c7p-3
+min,0x1.b9ac949a714f4p-3,0x1.288efd4ea3781p1,0x1.b9ac949a714f4p-3
+min,-0x1.1b107e57195ecp0,-0x1.1b107e57195ecp0,0x1.dd5dfc47faebep3
+min,-0x1.891d8dc7f1cf5p0,-0x1.891d8dc7f1cf5p0,0x1.396c3e23a8d67p0
+min,-0x1.6e11956e6e222p2,-0x1.26aa706380677p0,-0x1.6e11956e6e222p2
+min,-0x1.31b28d71015dap-1,-0x1.31b28d71015dap-1,0x1.1fd5d137a4772p-2
+min,-0x1.7fac3d710e52ep0,0x1.893d0c6cfb41dp-1,-0x1.7fac3d710e52ep0
+min,-0x1.290ea7b4320f4p0,-0x1.290ea7b4320f4p0,-0x1.24d9a6462daf6p-3
+min,-0x1.0b73073da946p-1,-0x1.0b73073da946p-1,0x1.e39bf03d1f4afp-2
+min,0x1.7977ae89fa154p-1,0x1.7977ae89fa154p-1,0x1.ec60c74e164c8p-1
+min,0x1.d7aee0c6e6625p-3,0x1.bb8fc43d257d3p2,0x1.d7aee0c6e6625p-3
+min,-0x1.00ab753ab9c6ep0,-0x1.00ab753ab9c6ep0,0x1.fc49a71d17689p-2
+min,-0x1.482cfb8593e2p1,-0x1.482cfb8593e2p1,0x1.29df7c855981dp-2
+min,-0x1.b198b34422c07p-2,0x1.7f835f4bd8af2p-2,-0x1.b198b34422c07p-2
+min,0x1.a42c893fc161ap-1,0x1.a42c893fc161ap-1,0x1.c2173bc38cff3p1
+min,-0x1.f82ca9ee2de92p-2,0x1.02345d34264eap0,-0x1.f82ca9ee2de92p-2
+min,-0x1.2061d589bb4b6p2,-0x1.2061d589bb4b6p2,0x1.e2c0aacc85133p-1
+min,-0x1.2916403a07566p-1,-0x1.2916403a07566p-1,0x1.8470750c4fc3bp0
+min,0x1.e4ff5339ae12ap-1,0x1.1d98ea2485102p0,0x1.e4ff5339ae12ap-1
+min,0x1.dba31dc5ef2c4p-2,0x1.dba31dc5ef2c4p-2,0x1.92996be0e867bp-1
+min,0x1.979e52581bed3p-2,0x1.979e52581bed3p-2,0x1.56b76e856e6abp0
+min,-0x1.1be67a6ba09cdp2,-0x1.1be67a6ba09cdp2,0x1.9da5e6efa4367p-1
+min,-0x1.31cb8169ce6d1p0,-0x1.31cb8169ce6d1p0,0x1.fd8e186d36bfcp-3
+min,-0x1.634cf9402ddcep1,0x1.00473f38f91fap2,-0x1.634cf9402ddcep1
+min,-0x1.f0ae14204a759p2,-0x1.f0ae14204a759p2,0x1.45265bfbf6a3fp3
+min,0x1.8f09f028feaf6p-2,0x1.8f09f028feaf6p-2,0x1.9253fc0fb0c25p-1
+min,-0x1.3cd8d2ab263f1p-1,0x1.77becee8a3f81p0,-0x1.3cd8d2ab263f1p-1
+min,-0x1.3ce7a97163386p-1,-0x1.3ce7a97163386p-1,0x1.4aaadecc0b55p1
+min,-0x1.48e10ed6a0916p-2,-0x1.48e10ed6a0916p-2,0x1.84c5c9b63cd65p0
+min,0x1.2fdf5cb32b13bp-1,0x1.53b0c65709e7ep1,0x1.2fdf5cb32b13bp-1
+min,-0x1.5765b10b1fbc1p-1,0x1.1ade9d6dc4727p0,-0x1.5765b10b1fbc1p-1
+min,-0x1.10ae54518de82p0,-0x1.10ae54518de82p0,-0x1.19089b42bf9e3p-3
+min,0x1.eab67589caa88p-2,0x1.eab67589caa88p-2,0x1.bc68d01d7cbb4p1
+min,0x1.0781058915ba1p-1,0x1.0781058915ba1p-1,0x1.7b9108f9ad7p2
+min,-0x1.158873373f889p-1,0x1.7cd00b4b7869bp1,-0x1.158873373f889p-1
+min,0x1.7c365dec96c43p-2,0x1.7c365dec96c43p-2,0x1.86104c7100905p0
+min,-0x1.82fb00359be92p-2,0x1.b292515ab07a9p2,-0x1.82fb00359be92p-2
+min,-0x1.eaadde36a5e87p0,-0x1.16bce129cd9c8p-1,-0x1.eaadde36a5e87p0
+min,-0x1.008ae7b47fc2fp1,-0x1.c0555a351b89ap-2,-0x1.008ae7b47fc2fp1
+min,-0x1.9d065ed72be6dp1,0x1.1534ff6bbb57p-2,-0x1.9d065ed72be6dp1
+min,0x1.07938b9c6febep1,0x1.2252865eae102p1,0x1.07938b9c6febep1
+min,0x1.838467e24e11ep-3,0x1.838467e24e11ep-3,0x1.09a6301cf209ap0
+min,-0x1.75cd92b765f79p-3,0x1.fcbd7a7e6a031p1,-0x1.75cd92b765f79p-3
+min,-0x1.291c03cea77a4p1,0x1.383becfd3de9cp-2,-0x1.291c03cea77a4p1
+min,-0x1.dded413d25462p-1,-0x1.bc1a66ad220a2p-1,-0x1.dded413d25462p-1
+min,-0x1.c46c3d6f0a42fp-2,0x1.b5a7b9ec5f02fp-1,-0x1.c46c3d6f0a42fp-2
+min,-0x1.579a90bbd54d2p3,-0x1.23e73b0fa51fdp-1,-0x1.579a90bbd54d2p3
+min,-0x1.fff1fc8af0ea8p0,0x1.339b2190df843p0,-0x1.fff1fc8af0ea8p0
+min,-0x1.a15357ed77e9p-3,0x1.aca7e28d1eee6p-1,-0x1.a15357ed77e9p-3
+min,-0x1.86f0707a28e74p1,-0x1.5212591d1b84bp0,-0x1.86f0707a28e74p1
+min,0x1.b7f4f1cc7086dp-1,0x1.b7f4f1cc7086dp-1,0x1.23a5b48fcc793p0
+min,-0x1.4639a5f929423p-3,0x1.3d16734d170f6p0,-0x1.4639a5f929423p-3
+min,-0x1.11552179c7f92p-1,-0x1.11552179c7f92p-1,0x1.a1b4268ed58fbp0
+min,-0x1.42ce24a8a256fp0,-0x1.42ce24a8a256fp0,-0x1.205189643d941p-1
+min,-0x1.e24d0eef7619p1,0x1.fdbb6fec69597p-2,-0x1.e24d0eef7619p1
+min,-0x1.148aead0c530bp5,-0x1.148aead0c530bp5,-0x1.3571cb1c20489p0
+min,-0x1.1efd819f91dbfp-2,-0x1.6cf5c6cd76b48p-3,-0x1.1efd819f91dbfp-2
+min,0x1.4c2aab84a2edbp-1,0x1.3cc62c5b5d4acp1,0x1.4c2aab84a2edbp-1
+min,-0x1.c4bec7964c1dp1,-0x1.c4bec7964c1dp1,-0x1.16585f3a378bcp1
+min,-0x1.e50e295fe6847p-1,-0x1.e50e295fe6847p-1,0x1.16226dfd2aabp0
+min,-0x1.a29e12c602ea1p-6,-0x1.a29e12c602ea1p-6,0x1.0f621347a3362p-5
+min,-0x1.185b0afb229dcp-2,-0x1.185b0afb229dcp-2,0x1.7b94a5681c7c7p-1
+min,-0x1.efd68d4fc0d47p0,-0x1.efd68d4fc0d47p0,-0x1.f7908abf9d8cdp-1
+min,-0x1.3a0267472a46cp2,0x1.2fd06ba2f553p-1,-0x1.3a0267472a46cp2
+min,-0x1.5df3ef4ea824dp-3,-0x1.5df3ef4ea824dp-3,0x1.5a16dd49f65fap0
+min,-0x1.39730602fe424p2,-0x1.56da97ba0787dp-3,-0x1.39730602fe424p2
+min,-0x1.af04c0e061947p0,0x1.e80882cd87a91p-2,-0x1.af04c0e061947p0
+min,-0x1.35cb5a414d308p2,-0x1.cb532bb97b52dp0,-0x1.35cb5a414d308p2
+min,0x1.b5f60b456b70dp-2,0x1.b5f60b456b70dp-2,0x1.82fffd7d5415dp0
+min,0x1.5c8a81e9f07e7p0,0x1.2e731b3b69a8cp1,0x1.5c8a81e9f07e7p0
+min,-0x1.7b0832976dff7p0,-0x1.7b0832976dff7p0,0x1.e364f679bf66bp-4
+min,-0x1.29e86809f4d32p2,0x1.e901e1b270bcfp-1,-0x1.29e86809f4d32p2
+min,-0x1.9c34005f9660dp-2,-0x1.9c34005f9660dp-2,0x1.5f03fa3b42fe1p-2
+min,-0x1.a046e65b3c456p-1,-0x1.a046e65b3c456p-1,0x1.f03620aa8ec09p-2
+min,-0x1.f581433baebbfp-8,-0x1.f581433baebbfp-8,0x1.b3456be2b36f8p-2
+min,-0x1.19389067a4bd5p-1,0x1.c5f73e666db0cp-2,-0x1.19389067a4bd5p-1
+min,-0x1.05f048693203fp1,-0x1.f5cacbe6855c4p-3,-0x1.05f048693203fp1
+min,-0x1.5ab3f8d498c8bp0,0x1.7c28d87baaecdp-1,-0x1.5ab3f8d498c8bp0
+min,-0x1.980a2fbf39e6bp-1,0x1.3b230bd4ceb4ap2,-0x1.980a2fbf39e6bp-1
+min,-0x1.07f038d7ae4bp0,-0x1.6cceed5d8afe1p-2,-0x1.07f038d7ae4bp0
+min,-0x1.1028a1ea4819ep0,0x1.246cb2321c69ep3,-0x1.1028a1ea4819ep0
+min,-0x1.3915753b2f211p0,0x1.b6ff957de56cp-8,-0x1.3915753b2f211p0
+min,-0x1.fc7df66f806f8p-1,0x1.764610e115881p-1,-0x1.fc7df66f806f8p-1
+min,-0x1.23c638306f8e8p-7,0x1.e5e780c1ed765p-1,-0x1.23c638306f8e8p-7
+min,0x1.86e6ffdca85bcp-1,0x1.1610ff1ddd62ep0,0x1.86e6ffdca85bcp-1
+min,0x1.3369be7382cb8p-1,0x1.aa86c4209f5eap-1,0x1.3369be7382cb8p-1
+min,-0x1.655e6a5389e78p1,-0x1.655e6a5389e78p1,0x1.c857034185afdp-1
+min,-0x1.9a3df57c6e1e4p-5,0x1.5003df95d3ec1p0,-0x1.9a3df57c6e1e4p-5
+min,-0x1.b0c7bfebfb80fp4,-0x1.b0c7bfebfb80fp4,0x1.bacb853d5d68cp3
+min,0x1.6e77565bcbec2p-1,0x1.5f57d8bdecf2fp1,0x1.6e77565bcbec2p-1
+min,-0x1.7a344909b4508p-7,0x1.658a46fe9a9fbp1,-0x1.7a344909b4508p-7
+min,-0x1.b9d0826f5f698p-5,0x1.5bded8ac0971cp-1,-0x1.b9d0826f5f698p-5
+min,-0x1.97e6fe051caf9p-1,-0x1.97e6fe051caf9p-1,-0x1.1cd6541c7dc28p-1
+min,-0x1.e826faa85a8cap0,0x1.1ee6597d17c77p0,-0x1.e826faa85a8cap0
+min,0x1.c081562b3d5f9p-5,0x1.9973cd63cbc18p-1,0x1.c081562b3d5f9p-5
+min,-0x1.4ce116f80496ep-4,0x1.1a22bb6efef72p-6,-0x1.4ce116f80496ep-4
+min,-0x1.0f004c5397ce5p0,-0x1.e03a80bc462b9p-2,-0x1.0f004c5397ce5p0
+min,-0x1.e54e81b91b3a6p0,-0x1.090169b160b8ap0,-0x1.e54e81b91b3a6p0
+min,-0x1.8a92051939d93p-2,-0x1.8a92051939d93p-2,-0x1.7d9eb3345b248p-2
+min,-0x1.f78dd1ca43a2dp-2,0x1.2665f9efc27dfp-1,-0x1.f78dd1ca43a2dp-2
+min,-0x1.1f4f31c42bfebp0,-0x1.1f4f31c42bfebp0,0x1.1c156fc7f2067p-1
+rint,-0x0.0p0,-0x1.268abd7b97d4dp-4
+rint,-0x0.0p0,-0x1.ce90039b60aebp-4
+rint,0x1.0p0,0x1.e4ecfa4f952e7p-1
+rint,-0x1.8p1,-0x1.afd4d19b7f8dap1
+rint,0x1.0p2,0x1.da3bd68bd4ddp1
+rint,-0x1.0p0,-0x1.0c3beddeb78a4p-1
+rint,0x1.0p0,0x1.75ef526669baap-1
+rint,0x1.0p0,0x1.74c104b92d4f9p0
+rint,-0x1.0p0,-0x1.3ed05cc70184fp0
+rint,-0x1.0p0,-0x1.e1a608b27df63p-1
+rint,-0x0.0p0,-0x1.af55e5fdbcc39p-3
+rint,0x1.0p0,0x1.ad5f44a429e87p-1
+rint,0x0.0p0,0x1.27cb5aab0dc54p-2
+rint,0x0.0p0,0x1.6699d74d1ce71p-2
+rint,0x0.0p0,0x1.ea333793843b6p-2
+rint,-0x1.0p0,-0x1.1bd32dc0009bfp-1
+rint,-0x1.8p1,-0x1.6ee93cb207aefp1
+rint,-0x1.0p0,-0x1.0de525de65447p-1
+rint,0x1.0p0,0x1.0148b70820c4dp-1
+rint,-0x0.0p0,-0x1.10805217b21aap-2
+rint,0x0.0p0,0x1.3d5c1de583edbp-3
+rint,0x1.0p0,0x1.a03b3152d028dp-1
+rint,-0x1.0p0,-0x1.5f041c44e90d1p-1
+rint,0x1.0p0,0x1.49439046777f9p0
+rint,-0x1.0p1,-0x1.28d5436eb7d2cp1
+rint,0x1.8p2,0x1.8b46c1838b98ap2
+rint,-0x0.0p0,-0x1.0471304f5a054p-5
+rint,0x0.0p0,0x1.9e8b18c8ebb83p-3
+rint,-0x1.0p1,-0x1.0a1df02bedaefp1
+rint,-0x0.0p0,-0x1.9a5d030e54e1cp-3
+rint,-0x1.8p1,-0x1.52f62b561d26ap1
+rint,0x0.0p0,0x1.be298f5967fd8p-6
+rint,-0x0.0p0,-0x1.f3f7d52af06dp-3
+rint,0x0.0p0,0x1.1f1297cdaad7fp-4
+rint,0x1.cp3,0x1.c5acc7f21f38dp3
+rint,-0x0.0p0,-0x1.c007c15df048ep-2
+rint,0x1.0p0,0x1.ddb83a6a98236p-1
+rint,-0x1.0p0,-0x1.10a321d00f1ebp-1
+rint,-0x1.8p1,-0x1.74981d40f271ep1
+rint,-0x1.0p0,-0x1.1fb6fbae1d141p-1
+rint,-0x0.0p0,-0x1.415207ed705b6p-2
+rint,0x0.0p0,0x1.721d06298d307p-3
+rint,0x0.0p0,0x1.f48709c1582f3p-4
+rint,0x1.0p1,0x1.f2cc062d0b567p0
+rint,0x1.0p1,0x1.ceac8b442b1b2p0
+rint,-0x1.0p0,-0x1.3522e3b9f349ap-1
+rint,-0x1.0p1,-0x1.35afc5d834dfap1
+rint,0x1.8p1,0x1.7e7edf2fdff71p1
+rint,-0x1.0p2,-0x1.10fc2ad87812cp2
+rint,-0x0.0p0,-0x1.8e02dcac1f3e3p-4
+rint,0x0.0p0,0x1.9c3a20144eb05p-7
+rint,-0x1.0p1,-0x1.3d52736f68b18p1
+rint,-0x1.cp2,-0x1.acb397da75f33p2
+rint,0x0.0p0,0x1.2b2b450cc38c6p-2
+rint,0x1.0p0,0x1.0a831b90c4eeep-1
+rint,-0x1.0p0,-0x1.12eedbd5f386fp0
+rint,0x1.0p0,0x1.34a220f0a02e2p0
+rint,0x1.0p1,0x1.04a277452476ep1
+rint,0x1.0p0,0x1.74e575fa823c4p-1
+rint,-0x1.8p2,-0x1.78205b0f35ab5p2
+rint,-0x1.0p0,-0x1.24a7e6a756508p0
+rint,-0x0.0p0,-0x1.6974bb79f8e3bp-2
+rint,-0x1.2p3,-0x1.15a591f8587fep3
+rint,-0x1.8p1,-0x1.be9c1872a9ae6p1
+rint,-0x1.8p2,-0x1.6b63b4774299ap2
+rint,-0x1.0p0,-0x1.01adda08540dp0
+rint,-0x1.0p0,-0x1.340ebda39a1d7p0
+rint,-0x1.0p0,-0x1.0b2ef4d4a5c38p0
+rint,0x0.0p0,0x1.02a715d4ded6dp-4
+rint,0x1.8p1,0x1.8970f490209afp1
+rint,-0x0.0p0,-0x1.e2a29b50fab79p-5
+rint,0x1.0p1,0x1.bd3180ca69342p0
+rint,-0x1.8p1,-0x1.6a707eb8365a4p1
+rint,-0x0.0p0,-0x1.0822c287571bbp-2
+rint,-0x0.0p0,-0x1.0774d818c096bp-2
+rint,-0x0.0p0,-0x1.cb57cd88b6814p-2
+rint,-0x1.6cp6,-0x1.6b3ee9a81134ep6
+rint,0x1.0p1,0x1.a4a0c509da1adp0
+rint,0x1.4p2,0x1.51c88432f3971p2
+rint,-0x1.0p0,-0x1.486abf9b592f6p-1
+rint,0x1.0p0,0x1.d80857586bc6fp-1
+rint,0x0.0p0,0x1.578876d5d5b3p-4
+rint,0x0.0p0,0x1.5b4c6a063ecddp-2
+rint,-0x1.8p3,-0x1.8109174b6f54fp3
+rint,0x1.3b4p10,0x1.3b4fc176c52cbp10
+rint,0x1.0p0,0x1.88530af7996bfp-1
+rint,0x0.0p0,0x1.c6ef91def2719p-7
+rint,-0x1.0p0,-0x1.003eb6cf0dc56p0
+rint,-0x0.0p0,-0x1.a80b404026eb5p-2
+rint,0x1.0p0,0x1.298d6a47d157ap0
+rint,-0x0.0p0,-0x1.933e7d46c7f34p-2
+rint,-0x1.0p1,-0x1.3c9574c6d096ap1
+rint,-0x0.0p0,-0x1.61caab39e144ep-2
+rint,-0x1.0p1,-0x1.042a8d6059565p1
+rint,-0x0.0p0,-0x1.0af3cdc9934e8p-5
+rint,-0x1.0p0,-0x1.3484927522febp0
+rint,0x0.0p0,0x1.734e12503c09bp-2
+rint,-0x1.0p3,-0x1.0e6cc242db1fdp3
+rint,-0x1.8p1,-0x1.4def7e9d6dfb9p1
+rint,0x1.0p1,0x1.867db25aa4c32p0
+rint,0x1.8p2,0x1.81caf889ccfb8p2
+rint,0x0.0p0,0x1.3251cfb971c4p-3
+rint,-0x1.0p0,-0x1.3cdad02b0127ep-1
+rint,-0x1.0p0,-0x1.072c2cf906319p0
+rint,-0x1.0p4,-0x1.045edd6c4c77cp4
+rint,-0x1.4p2,-0x1.2683e3e45b08cp2
+rint,-0x1.0p0,-0x1.356de8ee4699bp-1
+rint,0x1.0p2,0x1.c608611d27d43p1
+rint,0x0.0p0,0x1.72093650a52e4p-5
+rint,-0x1.0p0,-0x1.af9180dd287afp-1
+rint,-0x0.0p0,-0x1.6d67d3b3f0b87p-2
+rint,0x0.0p0,0x1.b8160d95ed57fp-2
+rint,0x1.4p2,0x1.55631268345bp2
+rint,0x1.0p0,0x1.2d1e3d29b568ap-1
+rint,-0x0.0p0,-0x1.53cf3c25e9902p-2
+rint,0x0.0p0,0x1.810155815f88p-2
+rint,0x1.0p1,0x1.e27bb3c0d372ap0
+rint,0x1.0p0,0x1.f93f6636ecd53p-1
+rint,0x1.8p1,0x1.a15121e27b58fp1
+rint,-0x1.0p0,-0x1.c79b4a9a78428p-1
+rint,-0x1.8p1,-0x1.54539c2aee079p1
+rint,0x1.0p1,0x1.a621d064219ecp0
+rint,0x1.0p0,0x1.4b2e7fd5a37c8p-1
+rint,-0x1.8p1,-0x1.589f47d9d3c4cp1
+rint,0x1.4p3,0x1.3818b56b20c08p3
+rint,-0x1.0p2,-0x1.f347d0a2f131fp1
+rint,-0x1.1p5,-0x1.0c44185d3cadfp5
+rint,-0x1.8p1,-0x1.4fe27fb2b0c53p1
+rint,0x1.0p0,0x1.5a582cbefb753p0
+rint,-0x1.0p2,-0x1.f092a0e332f9cp1
+rint,-0x1.0p0,-0x1.129eb68b04642p-1
+rint,0x1.0p2,0x1.c69b739b282fap1
+rint,0x0.0p0,0x1.604287f5a9429p-3
+rint,0x1.8p1,0x1.aa964836cb159p1
+rint,-0x1.0p1,-0x1.2fa3611ab6901p1
+rint,-0x1.6p3,-0x1.608a85772ead9p3
+rint,0x1.0p0,0x1.34f6be354890ap0
+rint,0x0.0p0,0x1.b2383068a5d09p-3
+rint,-0x1.0p0,-0x1.39707c4318253p0
+rint,-0x1.0p1,-0x1.199a1176dbd0ap1
+rint,-0x1.0p1,-0x1.a3f67dd020e44p0
+rint,-0x1.0p0,-0x1.8e05241eda779p-1
+rint,0x1.8p1,0x1.5d3a575dd10d8p1
+rint,-0x1.0p0,-0x1.14c85ca3d3d11p0
+rint,-0x1.0p0,-0x1.9e8c010f8ac2fp-1
+rint,-0x0.0p0,-0x1.c638361514109p-3
+rint,0x1.0p0,0x1.975be2d983681p-1
+rint,-0x1.1p5,-0x1.0f5471d8cd949p5
+rint,-0x1.0p1,-0x1.2173e0a3d232fp1
+rint,-0x0.0p0,-0x1.85e89615d5d38p-7
+rint,0x1.0p0,0x1.d74d2a411a4bbp-1
+rint,0x1.0p0,0x1.b64cf0264b1cp-1
+rint,0x0.0p0,0x1.6b739bd0f2b3p-2
+rint,0x0.0p0,0x1.d36b272bef8a3p-3
+rint,-0x1.0p0,-0x1.4fcbac94f975bp0
+rint,-0x1.0p0,-0x1.0c75ec256951ep0
+rint,0x0.0p0,0x1.d04737a528f0bp-2
+rint,-0x1.0p0,-0x1.3b8eb84ec9779p0
+rint,-0x1.0p0,-0x1.f6761584c5abbp-1
+rint,0x0.0p0,0x1.c2e85bc939218p-2
+rint,-0x1.0p1,-0x1.ca9e6a69f834ep0
+rint,-0x1.0p0,-0x1.916e37ff31e97p-1
+rint,0x1.0p1,0x1.3c871f6a61f44p1
+rint,0x1.4p2,0x1.295c95d904121p2
+rint,0x0.0p0,0x1.7645fac957147p-2
+rint,-0x1.8p1,-0x1.411df06a5babp1
+rint,-0x1.0p0,-0x1.21c5d31f6d27dp0
+rint,0x0.0p0,0x1.6fcc22eb7ce3ep-3
+rint,-0x0.0p0,-0x1.f98ce2709e33cp-2
+rint,0x1.0p1,0x1.28a6a7522f16ap1
+rint,-0x1.0p0,-0x1.3a507d95ce782p-1
+rint,-0x1.0p0,-0x1.420022071b16fp-1
+rint,-0x1.0p0,-0x1.1f391e0a98888p-1
+rint,0x1.0p1,0x1.bed218a13531ap0
+rint,0x1.0p2,0x1.db4357d53c349p1
+rint,-0x1.0p3,-0x1.f0827e913504dp2
+rint,0x0.0p0,0x1.31c6aa34c1195p-4
+rint,-0x1.0p0,-0x1.985452fd721c5p-1
+rint,-0x0.0p0,-0x1.4ad70030a2d28p-3
+rint,-0x1.1p4,-0x1.17d28e9b110d3p4
+rint,0x1.0p0,0x1.595b1ca5e2a74p0
+rint,-0x1.0p0,-0x1.04e0cd5ad5047p0
+rint,0x0.0p0,0x1.66693ef0a6de5p-2
+rint,-0x0.0p0,-0x1.23dc08e8cd76dp-9
+rint,0x0.0p0,0x1.438d036dcda45p-4
+rint,0x1.0p0,0x1.def796f294cbp-1
+rint,-0x0.0p0,-0x1.bf0fb62b5523fp-2
+rint,0x1.0p1,0x1.b39853ef0793bp0
+rint,0x1.0p4,0x1.f436c1fd8da07p3
+rint,-0x1.0p0,-0x1.a8160b5980e3ep-1
+rint,0x1.9p4,0x1.8833cb03caaa3p4
+rint,-0x0.0p0,-0x1.22fc97f963e56p-2
+rint,-0x1.0p0,-0x1.1bccce0791131p0
+rint,-0x1.cp2,-0x1.caa0e2178cd8ep2
+rint,0x1.bp5,0x1.b264348bcc276p5
+rint,0x0.0p0,0x1.8c6767b398dcep-2
+rint,-0x1.0p0,-0x1.7dccb23a33987p0
+rint,-0x1.0p0,-0x1.f26cf24d7d559p-1
+rint,-0x1.0p1,-0x1.eaaffa465b2a9p0
+rint,0x1.0p0,0x1.6c6dc2105be73p0
+signum,0x1.0p0,0x1.1a3d4fc7a8b02p-2
+signum,-0x1.0p0,-0x1.fe228b95ba25p-1
+signum,-0x1.0p0,-0x1.21fb1cbc2abdap0
+signum,-0x1.0p0,-0x1.3868b16944313p0
+signum,0x1.0p0,0x1.c66f8e4997682p-1
+signum,-0x1.0p0,-0x1.b0044eb46302p0
+signum,-0x1.0p0,-0x1.0131e3e8d92bdp-2
+signum,0x1.0p0,0x1.cac5840d66fe4p-3
+signum,0x1.0p0,0x1.572daf6ef2c5ap0
+signum,0x1.0p0,0x1.2e0c4ad74ec76p3
+signum,0x1.0p0,0x1.2710c81ed7afdp-2
+signum,-0x1.0p0,-0x1.e0e0fd00294d8p1
+signum,0x1.0p0,0x1.291f5a63a7303p3
+signum,0x1.0p0,0x1.b57ee4f88101bp0
+signum,-0x1.0p0,-0x1.3d767f97d77a5p0
+signum,-0x1.0p0,-0x1.84de638b42e32p0
+signum,-0x1.0p0,-0x1.0325a07f68cc8p1
+signum,0x1.0p0,0x1.4fe6826cce163p0
+signum,0x1.0p0,0x1.5fef43261ddabp1
+signum,-0x1.0p0,-0x1.bb43de2566d35p-3
+signum,-0x1.0p0,-0x1.fb641d350b093p0
+signum,0x1.0p0,0x1.887f25688ea32p-2
+signum,-0x1.0p0,-0x1.8f20d2d9d6ee5p-1
+signum,-0x1.0p0,-0x1.a19d0ac67fbb6p0
+signum,-0x1.0p0,-0x1.2bf0b23fc1b4ep1
+signum,0x1.0p0,0x1.650cec3003075p-1
+signum,-0x1.0p0,-0x1.ea4e336101c8p1
+signum,0x1.0p0,0x1.675f330659971p0
+signum,0x1.0p0,0x1.73fffcb287664p0
+signum,0x1.0p0,0x1.365746730f361p0
+signum,0x1.0p0,0x1.5f4d80f30fe66p-2
+signum,0x1.0p0,0x1.9a043c1b669p-6
+signum,0x1.0p0,0x1.763b03359f34ep-3
+signum,-0x1.0p0,-0x1.2245446decb07p0
+signum,-0x1.0p0,-0x1.ca16429735d7fp-2
+signum,-0x1.0p0,-0x1.430f48f2008d1p-2
+signum,-0x1.0p0,-0x1.28d356e3ae333p-1
+signum,0x1.0p0,0x1.b2fb022a4b2edp-5
+signum,-0x1.0p0,-0x1.0f49c17309a43p-4
+signum,-0x1.0p0,-0x1.4de1cb5097a3ep-2
+signum,0x1.0p0,0x1.4b43fccb09cb6p-1
+signum,0x1.0p0,0x1.b518077afad3dp-1
+signum,0x1.0p0,0x1.a071852a00314p0
+signum,-0x1.0p0,-0x1.dd00ccaa516c9p-1
+signum,-0x1.0p0,-0x1.68a31396f668ep0
+signum,-0x1.0p0,-0x1.22c69d1964442p0
+signum,0x1.0p0,0x1.57c6f812fee5fp-2
+signum,0x1.0p0,0x1.9a39f3f040c8ap6
+signum,-0x1.0p0,-0x1.1b0911ab7ac1dp-2
+signum,0x1.0p0,0x1.31801f7d375a2p-1
+signum,-0x1.0p0,-0x1.f3f8fcc027d4cp-2
+signum,-0x1.0p0,-0x1.71cc9ad409ea3p1
+signum,-0x1.0p0,-0x1.e2fed0da81e26p-3
+signum,0x1.0p0,0x1.7370cd960d4bp-2
+signum,0x1.0p0,0x1.fe003e889800cp0
+signum,0x1.0p0,0x1.1a5aefcdaa3ecp1
+signum,-0x1.0p0,-0x1.3a970a5def0b2p1
+signum,-0x1.0p0,-0x1.28aaff34f1f45p7
+signum,0x1.0p0,0x1.1c0a51cf8cdd6p2
+signum,0x1.0p0,0x1.4438e1b39db8ep-2
+signum,0x1.0p0,0x1.cd7c85cfe2a64p0
+signum,-0x1.0p0,-0x1.af0deb5d481a6p-4
+signum,-0x1.0p0,-0x1.ca053b9bfce0dp-2
+signum,-0x1.0p0,-0x1.2895c9f97406fp2
+signum,-0x1.0p0,-0x1.f22fca52bf512p5
+signum,0x1.0p0,0x1.41482e8745338p0
+signum,-0x1.0p0,-0x1.25f7f46a2f42bp1
+signum,0x1.0p0,0x1.567ad05164c56p-3
+signum,-0x1.0p0,-0x1.8055a246a94fap1
+signum,0x1.0p0,0x1.9a42bc3a82794p0
+signum,-0x1.0p0,-0x1.3bb3ad9a7630dp1
+signum,-0x1.0p0,-0x1.246146574c798p-1
+signum,0x1.0p0,0x1.4f78727ba4c6ap-3
+signum,0x1.0p0,0x1.1b98c2b509583p1
+signum,-0x1.0p0,-0x1.3dac8b72f4cfp1
+signum,0x1.0p0,0x1.6f46aff1cfca7p4
+signum,0x1.0p0,0x1.4515b3ad37985p1
+signum,-0x1.0p0,-0x1.21571f9f3d1aap-2
+signum,0x1.0p0,0x1.7a60191e80647p-1
+signum,-0x1.0p0,-0x1.e53fc2572804ep0
+signum,0x1.0p0,0x1.0f1a092b52ab7p1
+signum,0x1.0p0,0x1.f6d2a77acdf0bp1
+signum,0x1.0p0,0x1.1b946f3faf8c1p0
+signum,-0x1.0p0,-0x1.aeeaa2713927cp-1
+signum,-0x1.0p0,-0x1.f0c59b6da2eedp-6
+signum,-0x1.0p0,-0x1.908bd8875fb43p-1
+signum,-0x1.0p0,-0x1.8e5f9318ff445p0
+signum,-0x1.0p0,-0x1.58ad85cb73478p-3
+signum,-0x1.0p0,-0x1.27491677b5921p4
+signum,0x1.0p0,0x1.1a49b147641bdp1
+signum,-0x1.0p0,-0x1.29fe7b26dabdp-2
+signum,0x1.0p0,0x1.525fe0c81e43cp0
+signum,-0x1.0p0,-0x1.5d8e7da56990ap2
+signum,-0x1.0p0,-0x1.798a32640bacbp-1
+signum,0x1.0p0,0x1.942046d0d9f15p0
+signum,-0x1.0p0,-0x1.8383fe82a12c8p-1
+signum,0x1.0p0,0x1.5898f1786262ap-1
+signum,-0x1.0p0,-0x1.021b830a8beb8p0
+signum,-0x1.0p0,-0x1.b1230ebba73fbp-2
+signum,0x1.0p0,0x1.a3e32096e6635p0
+signum,0x1.0p0,0x1.dad58f3211322p-3
+signum,-0x1.0p0,-0x1.3c3b078d86766p-3
+signum,0x1.0p0,0x1.ccc09ab1c1addp0
+signum,-0x1.0p0,-0x1.58d9b6a6d1431p0
+signum,0x1.0p0,0x1.e34a9c872b574p6
+signum,0x1.0p0,0x1.7482aceab150ep0
+signum,-0x1.0p0,-0x1.486a2958dd734p1
+signum,-0x1.0p0,-0x1.0b9f0216571b4p-1
+signum,-0x1.0p0,-0x1.35777db826f93p-6
+signum,0x1.0p0,0x1.0d42beac642dp1
+signum,0x1.0p0,0x1.a87e45f5905ep-2
+signum,-0x1.0p0,-0x1.f9722a203855ep3
+signum,0x1.0p0,0x1.d584c8358f506p-2
+signum,-0x1.0p0,-0x1.e1320ee76d769p1
+signum,-0x1.0p0,-0x1.88334cc2177cbp-1
+signum,0x1.0p0,0x1.e908ff7ee1169p-1
+signum,0x1.0p0,0x1.55ef3fc6f89b2p-2
+signum,-0x1.0p0,-0x1.9ac2c7f86c6cdp-2
+signum,0x1.0p0,0x1.83f8e75e71eb2p-1
+signum,0x1.0p0,0x1.c9b44dfc4af65p1
+signum,0x1.0p0,0x1.9355350574ca9p2
+signum,0x1.0p0,0x1.585b4f630c574p1
+signum,0x1.0p0,0x1.1c96d0c66af4dp0
+signum,-0x1.0p0,-0x1.ab681f99c5d86p-3
+signum,0x1.0p0,0x1.9482749d0aa73p2
+signum,0x1.0p0,0x1.67cc7b0b4c26cp0
+signum,-0x1.0p0,-0x1.085f59e533c7ep-1
+signum,-0x1.0p0,-0x1.afefdc4c46c3ap0
+signum,0x1.0p0,0x1.6bb5e4a51967cp3
+signum,0x1.0p0,0x1.bfd9ab5f4332bp-1
+signum,-0x1.0p0,-0x1.1767d42fb2752p-3
+signum,0x1.0p0,0x1.95aaf6213e9c6p2
+signum,0x1.0p0,0x1.8825bf4dfdabfp0
+signum,-0x1.0p0,-0x1.1135f535c69dep-4
+signum,0x1.0p0,0x1.1f9e7b6d921b4p-2
+signum,0x1.0p0,0x1.4a9c752e94911p0
+signum,-0x1.0p0,-0x1.27f4c44a73fe6p-1
+signum,-0x1.0p0,-0x1.11f97648b9f8ap3
+signum,0x1.0p0,0x1.c77d53a50b053p0
+signum,-0x1.0p0,-0x1.d8113d6e9f8bcp-3
+signum,-0x1.0p0,-0x1.1d72c07d87e62p-2
+signum,-0x1.0p0,-0x1.358fe8d5cc199p0
+signum,-0x1.0p0,-0x1.aeead14f758b7p0
+signum,-0x1.0p0,-0x1.2a7e904ae4a44p1
+signum,-0x1.0p0,-0x1.e6b3bf0d17edbp-2
+signum,-0x1.0p0,-0x1.f4605a9efd9f1p0
+signum,-0x1.0p0,-0x1.d42845ce529bfp-3
+signum,-0x1.0p0,-0x1.64682ee910c7dp-8
+signum,0x1.0p0,0x1.8d935ae25468bp0
+signum,0x1.0p0,0x1.9de083cf13d31p0
+signum,0x1.0p0,0x1.33c2a52e9e197p-3
+signum,-0x1.0p0,-0x1.fdfbf0f5f8398p-4
+signum,-0x1.0p0,-0x1.c72c98ed1485dp0
+signum,-0x1.0p0,-0x1.bb8932b45fb62p-1
+signum,0x1.0p0,0x1.6e160c56703eap-1
+signum,-0x1.0p0,-0x1.fa25a6ee41b41p-1
+signum,-0x1.0p0,-0x1.272ac69f3cf22p0
+signum,-0x1.0p0,-0x1.71454149572f4p0
+signum,0x1.0p0,0x1.05c13c3872b5ap0
+signum,-0x1.0p0,-0x1.dc99d4ea8c043p-2
+signum,-0x1.0p0,-0x1.28eb471a3a91p-2
+signum,0x1.0p0,0x1.f40a33e7d49fbp-1
+signum,-0x1.0p0,-0x1.fda94be1a7904p-3
+signum,0x1.0p0,0x1.27074a195fb51p2
+signum,0x1.0p0,0x1.87b04e5581039p-3
+signum,0x1.0p0,0x1.9a188523a000cp2
+signum,-0x1.0p0,-0x1.e2a7f0d1cfdb8p-1
+signum,-0x1.0p0,-0x1.819901f0b0904p-3
+signum,0x1.0p0,0x1.2bb070c99fb6cp0
+signum,0x1.0p0,0x1.bb7402e945b7fp-4
+signum,-0x1.0p0,-0x1.7bf8d55eaefbdp1
+signum,-0x1.0p0,-0x1.199a2ffa37bf6p1
+signum,-0x1.0p0,-0x1.899df2cc40a33p-1
+signum,0x1.0p0,0x1.d8b19d1bed5eap-1
+signum,0x1.0p0,0x1.41ef45e1d237cp-1
+signum,0x1.0p0,0x1.fd50fff158b77p3
+signum,-0x1.0p0,-0x1.61db1558b5de3p5
+signum,0x1.0p0,0x1.082ef19a40405p1
+signum,0x1.0p0,0x1.48158d2f038eep-1
+signum,-0x1.0p0,-0x1.b9651dbebc609p2
+signum,0x1.0p0,0x1.c8f519f2f3045p-2
+signum,0x1.0p0,0x1.72a1e287cbf08p0
+signum,0x1.0p0,0x1.f09e7d5cd1a2ep-3
+signum,-0x1.0p0,-0x1.755699aee4ad9p-3
+signum,0x1.0p0,0x1.33c7b83b94af2p2
+signum,-0x1.0p0,-0x1.6c7c38f40084p1
+signum,-0x1.0p0,-0x1.e8073e9378aa3p-4
+signum,-0x1.0p0,-0x1.0d9e13d7f9284p0
+signum,-0x1.0p0,-0x1.14e0bcfb1aa8bp0
+signum,0x1.0p0,0x1.f2f0b1c247f41p-2
+signum,0x1.0p0,0x1.93c091038736cp2
+signum,0x1.0p0,0x1.5e0f2e629f9bep1
+signum,0x1.0p0,0x1.b5720829fea68p5
+signum,0x1.0p0,0x1.c056f6d23d03cp-1
+signum,-0x1.0p0,-0x1.2f7d64e8f0761p0
+signum,-0x1.0p0,-0x1.553f5170e1d75p-3
+signum,0x1.0p0,0x1.d8b9fda94abd4p-1
+signum,0x1.0p0,0x1.c31faf27fa01ep3
+signum,-0x1.0p0,-0x1.06058171a93d9p0
+signum,-0x1.0p0,-0x1.852592119514fp0
+toDegrees,0x1.9cc4da55f56cbp4,0x1.cd113dd73a73cp-2
+toDegrees,-0x1.94c416d548e15p2,-0x1.c420c0252959cp-4
+toDegrees,-0x1.7b02a36e7559fp5,-0x1.a75bcb9bdae6fp-1
+toDegrees,0x1.0f6e61abce825p7,0x1.2f31087c78663p1
+toDegrees,-0x1.be896265c1388p6,-0x1.f2c946a2c6a66p0
+toDegrees,-0x1.560657ad9eebdp4,-0x1.7e0b9b7822823p-2
+toDegrees,0x1.c97fc36ec2798p0,0x1.ff080809e5354p-6
+toDegrees,-0x1.231218346bfap6,-0x1.45210ae12d5dep0
+toDegrees,0x1.acd981a0f8f16p5,0x1.df07967013bfbp-1
+toDegrees,0x1.ffc04d8008847p5,0x1.1dd0d6e0a9014p0
+toDegrees,-0x1.22b4bf371bcefp6,-0x1.44b8c5afa5478p0
+toDegrees,-0x1.38f0f9d667f87p6,-0x1.5d8f0d930782dp0
+toDegrees,-0x1.516ecfff380abp7,-0x1.78ea87163eeabp1
+toDegrees,-0x1.2ae526db45ae4p7,-0x1.4dde7a996b9c8p1
+toDegrees,-0x1.a6b4650d4c965p5,-0x1.d82a67b42deaap-1
+toDegrees,0x1.7773b321056e7p6,0x1.a362445ee7c18p0
+toDegrees,-0x1.190c89382e7e9p4,-0x1.39ef493e52db9p-2
+toDegrees,0x1.42d69a1fb31b4p6,0x1.689d23fbea30ap0
+toDegrees,0x1.c8f48084d3c8fp6,0x1.fe6c7995f196fp0
+toDegrees,0x1.c5c438960265fp6,0x1.fadcae2a0e937p0
+toDegrees,-0x1.a296ca69d0b03p4,-0x1.d391849fee2e3p-2
+toDegrees,-0x1.90854d79fef1ep-1,-0x1.bf62cc5fffe35p-7
+toDegrees,-0x1.8e1570b872b7ap9,-0x1.bca9effb7253dp3
+toDegrees,0x1.0a21d4a34b9a3p3,0x1.2945c0511b397p-3
+toDegrees,-0x1.960053e8339dbp3,-0x1.c581fe108de79p-3
+toDegrees,0x1.880aeb1504fb8p4,0x1.b5ea74abe58d2p-2
+toDegrees,-0x1.74d2108f3c1aap3,-0x1.a071cf3c58906p-3
+toDegrees,0x1.c4324f9a9f8bdp5,0x1.f91bbe117d1cp-1
+toDegrees,0x1.18467de646d62p7,0x1.3912118f3c746p1
+toDegrees,0x1.0eed528a37375p9,0x1.2ea0df6c23f34p3
+toDegrees,-0x1.450d273c40222p6,-0x1.6b15fbfe1b148p0
+toDegrees,0x1.dd9b163174e74p3,0x1.0abed2c6e1761p-2
+toDegrees,0x1.60880fe3738a2p3,0x1.89c80d8ae0428p-3
+toDegrees,0x1.12bfe174fb77ap2,0x1.32e5eecd756dbp-4
+toDegrees,0x1.90c57dddec21ap1,0x1.bfaa7f87fb8a7p-5
+toDegrees,-0x1.3a350b8cda184p6,-0x1.5ef90ab264d6p0
+toDegrees,0x1.75031f7ed32cdp6,0x1.a0a89bb3a76ap0
+toDegrees,0x1.fcb5dee07145fp4,0x1.1c1e14b2b9db4p-1
+toDegrees,0x1.69114d2c22ba8p4,0x1.9350fd1d452d5p-2
+toDegrees,-0x1.526b1f129d2c1p5,-0x1.7a045c02d25bfp-1
+toDegrees,0x1.e2dfecd8124b2p3,0x1.0db028288dd15p-2
+toDegrees,-0x1.0dd14c6709a48p7,-0x1.2d639d6b5ce98p1
+toDegrees,0x1.2a01518efb356p6,0x1.4cdffc9db8986p0
+toDegrees,-0x1.9bc784f0c6b48p5,-0x1.cbf643e726dd8p-1
+toDegrees,-0x1.4f0025a5e36cep6,-0x1.763300f441a5p0
+toDegrees,0x1.689f3d35e9e25p3,0x1.92d19471a60b9p-3
+toDegrees,0x1.071bc5fd59a7fp4,0x1.25e51efb7444dp-2
+toDegrees,0x1.3d28cd1ab705cp6,0x1.62453abb2adc3p0
+toDegrees,-0x1.713bef68c5494p3,-0x1.9c703fc03e9d5p-3
+toDegrees,0x1.6618e48537401p3,0x1.8fff9a9c68351p-3
+toDegrees,-0x1.358164697bc5cp4,-0x1.59b88c71a52ddp-2
+toDegrees,0x1.7717dd5882015p6,0x1.a2fbafb0d679cp0
+toDegrees,-0x1.1b5f7b4512444p5,-0x1.3c87d8bc0f4f4p-1
+toDegrees,0x1.044ba83c26953p6,0x1.22c0be546d685p0
+toDegrees,-0x1.6d40cb9cad76ep9,-0x1.97fddbe158cc3p3
+toDegrees,0x1.3708b29f0dc25p5,0x1.5b6da41c12f38p-1
+toDegrees,-0x1.975ed02c432d9p6,-0x1.c7097d08166fp0
+toDegrees,0x1.4c557ad19a278p6,0x1.733875000be6cp0
+toDegrees,0x1.4734be48e506dp5,0x1.6d7e1dc7db526p-1
+toDegrees,0x1.485976815821dp6,0x1.6ec51657a80b1p0
+toDegrees,0x1.f2596d0c82a2fp5,0x1.1654ad221e6ep0
+toDegrees,0x1.8eff75442afa9p5,0x1.bdaf56785b7cbp-1
+toDegrees,0x1.e8e4b12a2aba2p8,0x1.110caef53c05dp3
+toDegrees,-0x1.c4fa982ea8112p6,-0x1.f9fb761682d11p0
+toDegrees,0x1.1a5f7514640c3p5,0x1.3b69dd67cf39fp-1
+toDegrees,-0x1.794600ac5da92p7,-0x1.a56b21e64998p1
+toDegrees,0x1.e35d13fe74edfp5,0x1.0df60e3206348p0
+toDegrees,-0x1.c4e1b476eda0ep4,-0x1.f9dfa8cf9b3d5p-2
+toDegrees,0x1.69682c8023cc2p5,0x1.93b206aeab843p-1
+toDegrees,-0x1.6b3653d3330f4p4,-0x1.95b641b33e0c1p-2
+toDegrees,0x1.b4a966dff8b42p5,0x1.e7c17e0aedc62p-1
+toDegrees,0x1.90ec5ba49fbb5p4,0x1.bfd5e989b0585p-2
+toDegrees,-0x1.e889680f077cap5,-0x1.10d9b32fdd367p0
+toDegrees,-0x1.3730338445bfcp7,-0x1.5b99c4527ddd1p1
+toDegrees,-0x1.022c00433be75p5,-0x1.20617946cc6bep-1
+toDegrees,0x1.12162302b21bp7,0x1.322853b853541p1
+toDegrees,0x1.b9be356b5ae5p6,0x1.ed6e81ec514c4p0
+toDegrees,0x1.9e768d7447387p3,0x1.cef5b0528789cp-3
+toDegrees,0x1.2adffc78f9eb4p6,0x1.4dd8b57b73478p0
+toDegrees,-0x1.3f4e073a6bbd3p7,-0x1.64aab8cf9710fp1
+toDegrees,0x1.c0aa08f3f6bbap4,0x1.f529a80fabcc6p-2
+toDegrees,-0x1.e192542d3cd5ap2,-0x1.0cf5d76d8bc39p-3
+toDegrees,0x1.04ab229374e59p6,0x1.232b64afd152ep0
+toDegrees,-0x1.f9e0a77142ffdp-1,-0x1.1a890b24927f6p-6
+toDegrees,0x1.e97f3f3966932p5,0x1.116300d074b9bp0
+toDegrees,-0x1.1cec99f1b0757p6,-0x1.3e436f08204c9p0
+toDegrees,-0x1.7d252f6ad8e33p6,-0x1.a9be4b43df93ap0
+toDegrees,-0x1.8a42007322f05p3,-0x1.b863e4e12bc6fp-3
+toDegrees,-0x1.278d84dfc3f4cp4,-0x1.4a22ba5b4331p-2
+toDegrees,-0x1.ed3a5058db8abp3,-0x1.137869c4a0318p-2
+toDegrees,-0x1.b5b4e4413337ep7,-0x1.e8ec48029555bp1
+toDegrees,0x1.5684eea8fbe01p3,0x1.7e99026a5d775p-3
+toDegrees,-0x1.4b23ed2f49fp5,-0x1.71e32698a8e3fp-1
+toDegrees,-0x1.df05855cfd054p8,-0x1.0b893eacbacc4p3
+toDegrees,-0x1.40573e27c281fp6,-0x1.65d2f82c221f3p0
+toDegrees,-0x1.68c5edf3d9b3ep5,-0x1.92fccc2599ddp-1
+toDegrees,0x1.16f591c9d9791p7,0x1.3799b906d8ee9p1
+toDegrees,0x1.2c9a73b1f03b8p3,0x1.4fc6f2a6f562cp-3
+toDegrees,-0x1.98e03048c019dp4,-0x1.c8b7f4f73266cp-2
+toDegrees,-0x1.be6f129011c73p6,-0x1.f2abe2a2e1c9dp0
+toDegrees,0x1.e5d4c67fad724p8,0x1.0f56dc9cfb8ddp3
+toDegrees,0x1.e8a586d34db52p7,0x1.10e967bc9c3f8p2
+toDegrees,0x1.0acde77827a8ep7,0x1.2a05f5915fde8p1
+toDegrees,-0x1.66c7f595b3323p4,-0x1.90c327c09c62ap-2
+toDegrees,0x1.8dd01c0733ae9p4,0x1.bc5c7e80a714cp-2
+toDegrees,0x1.1b088597a996dp6,0x1.3c26b633ca24fp0
+toDegrees,-0x1.cddf63ec90861p3,-0x1.01f55555933f7p-2
+toDegrees,-0x1.02b7b8b3d1fe1p6,-0x1.20fd8b01dd796p0
+toDegrees,-0x1.559d98a788a77p7,-0x1.7d969accdb9d9p1
+toDegrees,-0x1.3f5f0d0bfb216p6,-0x1.64bdbc8a7e518p0
+toDegrees,0x1.16226547ded9dp4,0x1.36add6dc29f2ap-2
+toDegrees,0x1.d4d4543876317p3,0x1.05d7ff438dc75p-2
+toDegrees,0x1.1d28bbaefee9dp5,0x1.3e869a00f7c61p-1
+toDegrees,-0x1.86579970698fap5,-0x1.b404332954a1ep-1
+toDegrees,0x1.2ef51ad45c23bp9,0x1.52681e197503fp3
+toDegrees,-0x1.3cf9701fe3407p6,-0x1.621052ffaaa7ap0
+toDegrees,0x1.e7244245038d5p3,0x1.10123b28dd00ap-2
+toDegrees,0x1.a5a03aa78362p5,0x1.d6f5ecd5f2423p-1
+toDegrees,0x1.e8f39b8a61b6ap3,0x1.1115038a9416bp-2
+toDegrees,0x1.3bf51b0182135p5,0x1.60ed87afc67a6p-1
+toDegrees,0x1.5b13311fb6c09p7,0x1.83afbbe37580cp1
+toDegrees,0x1.395e71b8dc57ap9,0x1.5e09548dca6fap3
+toDegrees,0x1.b5fd9e97cb653p7,0x1.e93d84e4beffdp1
+toDegrees,0x1.0b5531c717ccdp10,0x1.2a9d14762cdbep4
+toDegrees,-0x1.0f7be127bd95dp6,-0x1.2f401c4c8c6dap0
+toDegrees,-0x1.f8a402b4d979cp5,-0x1.19d832498ae13p0
+toDegrees,-0x1.8d2c07dfa6e11p5,-0x1.bba537696177bp-1
+toDegrees,-0x1.c154bc5577641p5,-0x1.f5e854bcf804bp-1
+toDegrees,-0x1.39d507bcace13p3,-0x1.5e8dcac830903p-3
+toDegrees,0x1.11e06dc88ae51p4,0x1.31ec55af95699p-2
+toDegrees,0x1.1ebf16f38b1d9p7,0x1.404c8193c1f93p1
+toDegrees,-0x1.708e7799a7b4ep4,-0x1.9bae7bc08c7c8p-2
+toDegrees,-0x1.5c8a2d06523abp9,-0x1.85529856c320fp3
+toDegrees,-0x1.5e2b963a36dp7,-0x1.8724d8fae038fp1
+toDegrees,0x1.3e13287c19be7p7,0x1.634b0236da71bp1
+toDegrees,0x1.a3ff712c87297p6,0x1.d5245e9b2e50cp0
+toDegrees,0x1.80d8a3f61cf0dp5,0x1.ade09c96d6ep-1
+toDegrees,0x1.cbaa19fa7d4edp5,0x1.00b99dd1e4d8ep0
+toDegrees,0x1.dc522f7f9e4e9p4,0x1.0a07215ac31f7p-1
+toDegrees,-0x1.2c3cf84f90a7ep3,-0x1.4f5e870a148f8p-3
+toDegrees,-0x1.1dc120f5ca3afp7,-0x1.3f30d4407fa7fp1
+toDegrees,0x1.6e2c3ba13a4d3p5,0x1.9904d85ecc7c9p-1
+toDegrees,-0x1.ea38a3aa95e47p7,-0x1.11ca8bb9c2c15p2
+toDegrees,-0x1.322c04414ec4cp8,-0x1.55ff51a36f15dp2
+toDegrees,-0x1.4fe90d155a88dp6,-0x1.773728f881204p0
+toDegrees,0x1.ff58a2d82d4b1p8,0x1.1d96f0e567a04p3
+toDegrees,-0x1.a25d798c48c75p5,-0x1.d3517ee076ecap-1
+toDegrees,0x1.6c39408ca491fp4,0x1.96d77a72adc61p-2
+toDegrees,0x1.58be156cc8725p7,0x1.8114c1f74781cp1
+toDegrees,-0x1.45cb34c0c3921p3,-0x1.6bea467e50e53p-3
+toDegrees,0x1.cf7a84939fa02p6,0x1.02daf3455c5ebp1
+toDegrees,0x1.c8d9ec779379ap5,0x1.fe4ec9630f342p-1
+toDegrees,0x1.40f290dd23f99p5,0x1.6680778b4b4dbp-1
+toDegrees,-0x1.d007e807137ccp5,-0x1.0329ea9fd53c5p0
+toDegrees,-0x1.0b45c757e1c32p5,-0x1.2a8bdc408764ap-1
+toDegrees,-0x1.260688556fd89p3,-0x1.486dfdea7261dp-3
+toDegrees,-0x1.e5e3535741671p8,-0x1.0f5efcf51e5d2p3
+toDegrees,-0x1.0086c685a5706p6,-0x1.1e8af5d50c276p0
+toDegrees,0x1.57a34296c3044p7,0x1.7fd8d738cb1ddp1
+toDegrees,0x1.2a33a57def28bp7,0x1.4d18341b9bfep1
+toDegrees,0x1.a7c08f4d64de1p6,0x1.d955f2c4fe762p0
+toDegrees,0x1.7128c6132b42ap3,0x1.9c5ad8709aa79p-3
+toDegrees,-0x1.688e096df3805p7,-0x1.92be5d5f8c398p1
+toDegrees,0x1.000dfdac23b5cp3,0x1.1e040ae962b82p-3
+toDegrees,-0x1.1af109f43a815p5,-0x1.3c0c7b234319cp-1
+toDegrees,0x1.fc9f8ecba486dp6,0x1.1c119e785bc66p1
+toDegrees,-0x1.aab953e1cd1d7p5,-0x1.dca7bbf503ce4p-1
+toDegrees,-0x1.5e8928b59890ep7,-0x1.878d5e64a5e27p1
+toDegrees,0x1.836a93ac41202p3,0x1.b0bf889de387cp-3
+toDegrees,0x1.3b7cdcc880872p6,0x1.6067379d26339p0
+toDegrees,0x1.c8056c371e64dp5,0x1.fd616bb8f3785p-1
+toDegrees,-0x1.ec401ac74c4bcp4,-0x1.12ecab81b3564p-1
+toDegrees,-0x1.ca28aa208a7a4p5,-0x1.ffc4b21fba5b4p-1
+toDegrees,-0x1.1a006a6cef937p6,-0x1.3affb3cdd2bf1p0
+toDegrees,0x1.563d185336d2bp9,0x1.7e48c436ce2a6p3
+toDegrees,-0x1.4ca0d7ea15c7fp8,-0x1.738ca398485b2p2
+toDegrees,0x1.009f3a101b96dp4,0x1.1ea645ce750cdp-2
+toDegrees,-0x1.2beb979f7ba94p5,-0x1.4f03a0b42782dp-1
+toDegrees,-0x1.0c9a2275da42ap6,-0x1.2c080aa4dcbeap0
+toDegrees,-0x1.6162e5122ed34p4,-0x1.8abc7dcdd3575p-2
+toDegrees,-0x1.41e855cd03379p6,-0x1.6792fe6ff2af7p0
+toDegrees,0x1.2db550afa1b3ap7,0x1.5102e8bd4e53ep1
+toDegrees,-0x1.f55dbe6f2720ep6,-0x1.1804051e6ce8ep1
+toDegrees,-0x1.2eb22726e4acdp3,-0x1.521d54e55310dp-3
+toDegrees,-0x1.3ef9ae1414208p7,-0x1.644c8107f5d37p1
+toDegrees,-0x1.2a6babb40908dp8,-0x1.4d56c882fd11ap2
+toDegrees,-0x1.6eb2ba40302ebp4,-0x1.999b13be37afp-2
+toDegrees,-0x1.1f825cdc83933p8,-0x1.4126a0d7b7ec8p2
+toDegrees,0x1.196d47a93599dp6,0x1.3a5b599fc865dp0
+toDegrees,-0x1.152cb9e9e5ap2,-0x1.359b6c87594cep-4
+toDegrees,0x1.e8033ad066cefp5,0x1.108ec2f31fd2p0
+toDegrees,-0x1.380d292404d8ap1,-0x1.5c9094bb0fa5ap-5
+toDegrees,-0x1.e3b0170b51c6cp8,-0x1.0e246b0558ec9p3
+toDegrees,0x1.5292d8b4c17e7p7,0x1.7a30bb99bbf7ap1
+toDegrees,0x1.a643cd81be412p8,0x1.d7aca37eb05a1p2
+toDegrees,-0x1.6202c5199be34p2,-0x1.8b6f12d9e8ceap-4
+toDegrees,-0x1.5c58d80880982p5,-0x1.851b7d9eba78dp-1
+toDegrees,-0x1.43b8e1a23e479p7,-0x1.6999e5a23a02fp1
+toDegrees,-0x1.8815f8f42cea6p5,-0x1.b5f6cdab230d6p-1
+toDegrees,-0x1.4bf63f89b2173p7,-0x1.72ce151501a48p1
+toRadians,0x1.343b2ed481bd1p-6,0x1.13f162387c30ep0
+toRadians,0x1.62b1bc6a273c9p-7,0x1.3d89f0fad72e1p-1
+toRadians,-0x1.269dd1f61b4dfp-6,-0x1.07c11fe9ef09ap0
+toRadians,0x1.8f9413ec4afd4p-5,0x1.65b8a1590af12p1
+toRadians,-0x1.d5e34359a07fep-6,-0x1.a4aa56bfa319bp0
+toRadians,0x1.dccef5cda0302p-8,0x1.aadc71cf68e4p-2
+toRadians,-0x1.756bb6c6074bp-6,-0x1.4e4dbbcc2fa9fp0
+toRadians,0x1.bd04cff56f47ep-7,0x1.8e66cbb71fd56p-1
+toRadians,0x1.78fefa23b96fap-6,0x1.51811ea8e898bp0
+toRadians,0x1.0d4d232276716p-6,0x1.e22ea197722cep-1
+toRadians,-0x1.33d9fd2988496p-4,-0x1.139a5efe42b6ap2
+toRadians,-0x1.229982e2b8d7cp-5,-0x1.042888e04d436p1
+toRadians,-0x1.29c7dd4973314p-6,-0x1.0a965060eb912p0
+toRadians,0x1.20d720e76b068p-5,0x1.029554c15c57ap1
+toRadians,0x1.7f5bf73fdde9cp-7,0x1.5733775f2d25p-1
+toRadians,0x1.42170369d60b3p-4,0x1.2059910e0b436p2
+toRadians,0x1.a8b0ae7ecdabdp-3,0x1.7c33d0cf9cf15p3
+toRadians,0x1.630ea69bd5949p-5,0x1.3ddd1f7cf69b8p1
+toRadians,0x1.7f69b05ec6601p-3,0x1.573fc07b23f0dp3
+toRadians,0x1.af6c649a981abp-5,0x1.823af65afedeap1
+toRadians,-0x1.4a937400ee9d5p-5,-0x1.27f26f955178ap1
+toRadians,-0x1.b809620a4ff24p-4,-0x1.89f0f8d5f08f1p2
+toRadians,0x1.5fc99f56b4abap-7,0x1.3aefc6b5b91b7p-1
+toRadians,-0x1.517b699ec7bep-4,-0x1.2e21320a4ff91p2
+toRadians,-0x1.0bb8960d4d455p-7,-0x1.df5a490650c4ap-2
+toRadians,-0x1.ec1e137eb7753p-7,-0x1.b891050802839p-1
+toRadians,0x1.29829f741d254p-6,0x1.0a5853632a0e3p0
+toRadians,-0x1.4f91fde8cb341p-6,-0x1.2c6b0b115881dp0
+toRadians,0x1.33d962b6df19p-6,0x1.1399d4b969204p0
+toRadians,-0x1.c22d9a20d8453p-3,-0x1.93053a6c3aac9p3
+toRadians,0x1.8a562054567fdp-5,0x1.610740b5d01cbp1
+toRadians,-0x1.f38e2489f0cc6p-9,-0x1.bf39a0f24dfa5p-3
+toRadians,0x1.d8241c6f90ae7p-6,0x1.a6aec291de8e6p0
+toRadians,0x1.ea933e48ad7p-7,0x1.b72f8c019babcp-1
+toRadians,0x1.3a4dc8294ed8p-7,0x1.1961220e2d1bfp-1
+toRadians,-0x1.19ba22c2bb686p-7,-0x1.f86e2feb49188p-2
+toRadians,-0x1.85b38b279cecbp-9,-0x1.5ce0f7fbeaff5p-3
+toRadians,-0x1.eb71d9b818fd5p-7,-0x1.b7f6d5cfb47c3p-1
+toRadians,0x1.6ac5dcc337895p-3,0x1.44c56ca0989b1p3
+toRadians,-0x1.8d19564a6d62bp-5,-0x1.6380617bbb3d9p1
+toRadians,-0x1.241f2b58bedb9p-3,-0x1.05855fec5a98bp3
+toRadians,-0x1.6366121646645p-8,-0x1.3e2b62a393a8ap-2
+toRadians,0x1.6ecc94720253cp-6,0x1.48602bae2826p0
+toRadians,0x1.71d14914d9a1p-7,0x1.4b13eec2e34aep-1
+toRadians,-0x1.5a9a542f7ce34p-6,-0x1.364b856e7ad01p0
+toRadians,-0x1.0a0bba58bd01dp-7,-0x1.dc5a6ae50df52p-2
+toRadians,-0x1.8c8b2bf16c84ap-2,-0x1.63011b91a72d5p4
+toRadians,-0x1.d56110f9c4a6ap-7,-0x1.a435c7d87ec43p-1
+toRadians,0x1.96182610fd5dp-10,0x1.6b8df7081097cp-4
+toRadians,0x1.3d395c885fe78p-6,0x1.1bfe66ac6aca2p0
+toRadians,0x1.fa9331390851p-7,0x1.c5826e5d6a8fdp-1
+toRadians,-0x1.3a41e6900b66ep-7,-0x1.19567f131b0b3p-1
+toRadians,0x1.ef7b1d4585839p-6,0x1.bb93dc72c9319p0
+toRadians,0x1.62d84b7aedaa3p-5,0x1.3dac76046aacep1
+toRadians,-0x1.0f20042155341p-6,-0x1.e572931c5417bp-1
+toRadians,-0x1.690ea94f0a1b8p-6,-0x1.433c3b2cb5df1p0
+toRadians,-0x1.94c307b06c295p-8,-0x1.6a5c9464a575dp-2
+toRadians,-0x1.c7c50a49a546cp-9,-0x1.9806b7e00001p-3
+toRadians,0x1.73099f305d1fep-4,0x1.4c2b8cfb45c8bp2
+toRadians,-0x1.389be50a6fd97p-8,-0x1.17dcb26fb38ap-2
+toRadians,0x1.5fbc85728b899p-8,0x1.3ae40c2677db1p-2
+toRadians,0x1.ef94c7f3a2ecfp-6,0x1.bbaad6d3bf4d2p0
+toRadians,-0x1.8f2d697a05737p-9,-0x1.655cb8140865dp-3
+toRadians,0x1.b20508bdffb78p-5,0x1.848dfae3dca6ep1
+toRadians,-0x1.bdb35ca54ab81p-7,-0x1.8f030f8701c68p-1
+toRadians,0x1.0861b9ad91254p-5,0x1.d95fa9ae542c1p0
+toRadians,0x1.a76bd0ab65c66p-7,0x1.7b10fae457027p-1
+toRadians,0x1.54c5e8e9a7843p-7,0x1.3113702f0fc4fp-1
+toRadians,-0x1.13d8a20895e4fp0,-0x1.ede6983faab45p5
+toRadians,-0x1.cebc35c4a890bp-8,-0x1.9e43184cdea2ap-2
+toRadians,0x1.3d3e1280d3313p-4,0x1.1c029e507fabcp2
+toRadians,-0x1.5f6a1f54ab2a4p-7,-0x1.3a9a47b707798p-1
+toRadians,-0x1.3c0058e027e76p-6,-0x1.1ae62d156322p0
+toRadians,0x1.91a20082f74adp-3,0x1.678f764a36e11p3
+toRadians,0x1.5a7a88c4fde6ep-8,0x1.362f0ea5bddffp-2
+toRadians,-0x1.dd2d62c4677b5p-7,-0x1.ab30fa92aab8ep-1
+toRadians,0x1.c090beda0a1ebp-4,0x1.91939eabe933ep2
+toRadians,-0x1.fa64fbfece91ep-8,-0x1.c559104a2fc35p-2
+toRadians,0x1.03e06cf40987fp-6,0x1.d14eb0092067dp-1
+toRadians,-0x1.9e2d350067dbbp-8,-0x1.72ca4846014p-2
+toRadians,0x1.2b149a9831e4ep-2,0x1.0bc032a6985a2p4
+toRadians,-0x1.eb36b025b1424p-7,-0x1.b7c1deca5038ep-1
+toRadians,-0x1.581a480c8d362p-4,-0x1.340e855ef1af6p2
+toRadians,-0x1.0c3f652158269p-7,-0x1.e04ba8df602b9p-2
+toRadians,-0x1.309379cfc0976p-11,-0x1.10abb1f2f2834p-5
+toRadians,0x1.3f6a7aa234715p-7,0x1.1df4bd59b7a1fp-1
+toRadians,-0x1.65dd0dca04ae2p-7,-0x1.40604556bbc5ap-1
+toRadians,-0x1.69934495b8f4ap-6,-0x1.43b2f25b4c342p0
+toRadians,-0x1.f6766633423b6p-7,-0x1.c1d3ebf82f78ep-1
+toRadians,0x1.4c96adb0ee339p-6,0x1.29bfb0889a191p0
+toRadians,0x1.51c4cc005ef3ep-7,0x1.2e62e47bbc5f8p-1
+toRadians,-0x1.37fcc828121c6p-8,-0x1.174e407648858p-2
+toRadians,0x1.3c85a053a8dbfp-6,0x1.1b5d7e6798ac9p0
+toRadians,0x1.2fa1707ca7533p-6,0x1.0fd303496037ep0
+toRadians,-0x1.fd30ff4ab5bb4p-8,-0x1.c7da125a7e8cp-2
+toRadians,-0x1.07053d4647f61p-3,-0x1.d6efb37cbda3cp2
+toRadians,0x1.2e6539dacf422p-6,0x1.0eb7ec831448p0
+toRadians,0x1.90768a6c41a28p-6,0x1.66835ed1b0038p0
+toRadians,-0x1.3b5f769af4c14p-9,-0x1.1a5625378947dp-3
+toRadians,0x1.5e2305a747b1bp-7,0x1.397571d90c1e8p-1
+toRadians,-0x1.9684bb151928dp-6,-0x1.6bef2c36e0214p0
+toRadians,0x1.80aab10e1f8a3p-10,0x1.585f20e007884p-4
+toRadians,-0x1.73454254905c1p-9,-0x1.4c60f0d6580cep-3
+toRadians,-0x1.64e173018ac6bp-6,-0x1.3f7f05ce9fc63p0
+toRadians,0x1.6c33df8f50558p-9,0x1.460d18271bc01p-3
+toRadians,-0x1.a66398e8cab57p-11,-0x1.7a2470a132a52p-5
+toRadians,-0x1.4044a3024d4c3p-6,-0x1.1eb80b6a865f3p0
+toRadians,0x1.a5edecbd257d2p-7,0x1.79bb1811e0512p-1
+toRadians,0x1.2f63061aafa03p-9,0x1.0f9b22b1cf7b8p-3
+toRadians,0x1.57a84a0a48335p-6,0x1.33a878472947cp0
+toRadians,-0x1.1fbadf0bde297p-5,-0x1.0196d9ca7dd6dp1
+toRadians,0x1.0579eb2f75c14p-5,0x1.d42be1d80dafap0
+toRadians,0x1.4bb08a6dddaffp-10,0x1.28f1a8d929a18p-4
+toRadians,-0x1.785e5c8f3248bp-6,-0x1.50f15449acabep0
+toRadians,0x1.7c2e98ed7c20ap-6,0x1.545b4d0e37923p0
+toRadians,0x1.8afa8d5f6beb4p-7,0x1.619a745cb9468p-1
+toRadians,0x1.9ab81ca6e2142p-7,0x1.6fb1e76a3d452p-1
+toRadians,0x1.5abbd97d5f2dfp-8,0x1.366987d08a848p-2
+toRadians,0x1.10b1ed52fa65ap-5,0x1.e8423180e2757p0
+toRadians,0x1.1977488637e48p-7,0x1.f7f67cff2be2p-2
+toRadians,-0x1.ea464cd97d49ep-5,-0x1.b6eaa9f230e9ap1
+toRadians,0x1.b91c40b587a6dp-4,0x1.8ae70c5a81ab4p2
+toRadians,0x1.4437a94ee4aa7p-5,0x1.2241293012d19p1
+toRadians,0x1.f5efccce5b07bp-6,0x1.c15b6c1b274d9p0
+toRadians,-0x1.9f99237013c3ep-9,-0x1.741017345ad98p-3
+toRadians,-0x1.0973876df224ap-6,-0x1.db49e80f5e81ep-1
+toRadians,0x1.6fa164f8ba5d2p-6,0x1.491eb12f08f23p0
+toRadians,0x1.6c2759fa3c865p-9,0x1.4601e25dc1082p-3
+toRadians,-0x1.9e741ead7ac95p-9,-0x1.7309c44a173a5p-3
+toRadians,0x1.9030fa34f406dp-6,0x1.664518133618ep0
+toRadians,-0x1.efe26ef81c43dp-4,-0x1.bbf05b72f4d36p2
+toRadians,-0x1.f34430fc0f19fp-7,-0x1.bef76c89ad7e8p-1
+toRadians,-0x1.2cbb12850bd1p-6,-0x1.0d3a694a092f3p0
+toRadians,-0x1.6ca79b649b4dap-6,-0x1.4674b45e4bef9p0
+toRadians,-0x1.5ed33ec70db7ap-6,-0x1.3a1335377f47p0
+toRadians,0x1.4bb2ac4bfd435p0,0x1.28f39188d12e9p6
+toRadians,-0x1.1e73f51abbca9p-5,-0x1.00722ea8a6779p1
+toRadians,0x1.50359082fe9fap-6,0x1.2cfd7b2947624p0
+toRadians,-0x1.6890f9618d29ep-7,-0x1.42cbb5c946d7ep-1
+toRadians,-0x1.b7177f3ea7634p-7,-0x1.89186caa94425p-1
+toRadians,0x1.14ded07f7b65p-6,0x1.efbc076595c42p-1
+toRadians,0x1.94c88977ca0cap-6,0x1.6a61827e245e2p0
+toRadians,-0x1.f25873e1c75c3p-8,-0x1.be24613628b96p-2
+toRadians,-0x1.caa05a18ca625p-6,-0x1.9a956c2ee4594p0
+toRadians,-0x1.6674a31e63532p-7,-0x1.40e7f9ad2943fp-1
+toRadians,0x1.5ebd1a81b95b7p-6,0x1.39ff62b7845c3p0
+toRadians,0x1.7770bfa4cac45p-8,0x1.501c9b691eb28p-2
+toRadians,0x1.52c145c51ab79p0,0x1.2f44eba454717p6
+toRadians,-0x1.5082c8921deefp-5,-0x1.2d429c72b1d75p1
+toRadians,0x1.288a3adfc8e7ap-5,0x1.0979f3ee43321p1
+toRadians,-0x1.ef75b508090c5p-8,-0x1.bb8f05364e233p-2
+toRadians,0x1.365709f9e92dbp-5,0x1.15d4b01c6f66fp1
+toRadians,0x1.bd29cf8766e9fp-8,0x1.8e87eb1b1cb6ap-2
+toRadians,0x1.5705e9472736dp-10,0x1.331719fc9f227p-4
+toRadians,-0x1.c0f0760371a15p-5,-0x1.91e94f0aeb6fdp1
+toRadians,0x1.aa4b9d7189cd6p-11,0x1.7da3b3ce92d0bp-5
+toRadians,-0x1.e36f3239795c7p-7,-0x1.b0cafe786941p-1
+toRadians,-0x1.5d453f9711567p-6,-0x1.38aee7103062ap0
+toRadians,0x1.4f5935250958dp-9,0x1.2c3835144a6c6p-3
+toRadians,-0x1.fc315cc3236d5p-5,-0x1.c6f5372783487p1
+toRadians,-0x1.5f6f0db8815dcp-11,-0x1.3a9eb1dd80ae8p-5
+toRadians,0x1.044ced10f50cep-6,0x1.d210f4f97b4fap-1
+toRadians,-0x1.0820c249570a6p-12,-0x1.d8eb574a001cap-7
+toRadians,0x1.c0dce341827e4p-7,0x1.91d7c92de11e9p-1
+toRadians,-0x1.54c0758b47cf8p-5,-0x1.310e8efc1fc1dp1
+toRadians,-0x1.0c22f069d37e6p-6,-0x1.e018b5a31fb2cp-1
+toRadians,-0x1.0d44d90e1098cp-6,-0x1.e21fca05c552fp-1
+toRadians,0x1.aa370725bfc19p-6,0x1.7d914597b0f93p0
+toRadians,0x1.5dae1ab6a26cap-8,0x1.390cc646e30c2p-2
+toRadians,-0x1.93d8aca9afc4cp-6,-0x1.698ac60d72cfap0
+toRadians,0x1.dde50e06e847bp-8,0x1.abd568673b34cp-2
+toRadians,0x1.85367605681f8p-8,0x1.5c70fd2cabf94p-2
+toRadians,0x1.0f398ad1f05d4p-6,0x1.e5a0476d86f65p-1
+toRadians,-0x1.d61f59195aa6cp-7,-0x1.a4e02134d1a6bp-1
+toRadians,-0x1.2ea0ffdaa0e6p-6,-0x1.0eed6f92fd525p0
+toRadians,-0x1.ed05911e835b4p-7,-0x1.b96042cbd3729p-1
+toRadians,0x1.2cd0b41a46717p-3,0x1.0d4dc6ca8eaa8p3
+toRadians,0x1.381d20fe74a4p-6,0x1.176b35da6d972p0
+toRadians,-0x1.135812197a196p-5,-0x1.ed0067a8591e4p0
+toRadians,0x1.9487e02c71b95p-4,0x1.6a279f36895cap2
+toRadians,0x1.2f1b98fbb5e38p-7,0x1.0f5b3100c4226p-1
+toRadians,-0x1.df126097b8ce9p-10,-0x1.ace32a703c8p-4
+toRadians,0x1.27602746d31p-5,0x1.086f19d122d5p1
+toRadians,-0x1.6f00c2e92cd4ep-7,-0x1.488ee2ccee45dp-1
+toRadians,-0x1.6d6cad1da49f1p-8,-0x1.4725214f128bcp-2
+toRadians,0x1.53853b6e52504p-6,0x1.2ff45a46f0239p0
+toRadians,-0x1.35bedb84f10a2p-6,-0x1.154c72afce441p0
+toRadians,0x1.e5b425177b774p-8,0x1.b2d3161ad8a1fp-2
+toRadians,-0x1.0bfd2695d0ed9p-8,-0x1.dfd50cb6eb642p-3
+toRadians,0x1.9e42202419179p-7,0x1.72dd02718e33ep-1
+toRadians,0x1.91ed5a574b502p-7,0x1.67d2eb7176ee9p-1
+toRadians,0x1.88624a4753cb9p-5,0x1.5f47c6b4bedb7p1
+toRadians,-0x1.88c9a0d956ca6p-10,-0x1.5fa44a11aabe3p-4
+toRadians,-0x1.a5a8e50293634p-8,-0x1.797d4b83f869p-2
+toRadians,-0x1.aee96588d5d7ap-6,-0x1.81c5b0333bb09p0
+toRadians,-0x1.a0bb132c02b9p-7,-0x1.7513a7bf2c3eep-1
+toRadians,-0x1.159284ff767c1p-2,-0x1.f0fdca230f3f5p3
+toRadians,0x1.6ec5baab9dfccp-7,0x1.485a099e8a8a4p-1
+toRadians,-0x1.479fe44ef6b39p-4,-0x1.254e05afbfe62p2
+toRadians,0x1.0ce113f6e801dp-4,0x1.e16d26e044eb6p1
+ulp,0x1.0p-52,-0x1.9369810dd84a3p0
+ulp,0x1.0p-54,-0x1.9f2928d31e01cp-2
+ulp,0x1.0p-51,-0x1.73ea1caeccadfp1
+ulp,0x1.0p-56,-0x1.b86c6f1a71af3p-4
+ulp,0x1.0p-52,-0x1.a6ef99791510fp0
+ulp,0x1.0p-52,-0x1.5d387a9331d4bp0
+ulp,0x1.0p-51,-0x1.1e9fa73b0f17ep1
+ulp,0x1.0p-53,0x1.5ae973c9b8796p-1
+ulp,0x1.0p-52,-0x1.0442e3e3b3b79p0
+ulp,0x1.0p-53,0x1.54c946e25ac81p-1
+ulp,0x1.0p-50,-0x1.823ca7a97f04fp2
+ulp,0x1.0p-52,-0x1.2224e7e88298ep0
+ulp,0x1.0p-54,-0x1.fea5f17ff5016p-2
+ulp,0x1.0p-54,-0x1.871996754d049p-2
+ulp,0x1.0p-52,-0x1.907690c67abfbp0
+ulp,0x1.0p-53,0x1.b27d04e53486bp-1
+ulp,0x1.0p-50,-0x1.9f83f235455adp2
+ulp,0x1.0p-55,-0x1.27db0f3453088p-3
+ulp,0x1.0p-53,0x1.dcb0659fc998p-1
+ulp,0x1.0p-55,0x1.fb07cf43a2d89p-3
+ulp,0x1.0p-54,-0x1.9edeb774425ebp-2
+ulp,0x1.0p-52,0x1.1555de3dd020dp0
+ulp,0x1.0p-55,0x1.88207d030a31ep-3
+ulp,0x1.0p-55,0x1.a43d08b26be4ap-3
+ulp,0x1.0p-52,-0x1.15f5854c2bcd5p0
+ulp,0x1.0p-51,0x1.1a7ea8c3d6b39p1
+ulp,0x1.0p-51,-0x1.6f1f146ede7c2p1
+ulp,0x1.0p-51,0x1.feb1e4c4d0e41p1
+ulp,0x1.0p-53,-0x1.acf03f6287edfp-1
+ulp,0x1.0p-52,0x1.4fe731c91c69cp0
+ulp,0x1.0p-50,-0x1.e07be31b55062p2
+ulp,0x1.0p-55,0x1.dc1cf3e87e286p-3
+ulp,0x1.0p-53,-0x1.aaceaee575b18p-1
+ulp,0x1.0p-52,0x1.05f4ba3309817p0
+ulp,0x1.0p-55,-0x1.8865f997482aep-3
+ulp,0x1.0p-51,-0x1.3fefc64092de6p1
+ulp,0x1.0p-51,0x1.2719b1d2899ap1
+ulp,0x1.0p-50,-0x1.08cecb8ac651fp2
+ulp,0x1.0p-50,-0x1.2685e7840932dp2
+ulp,0x1.0p-52,-0x1.d0bd1fa84868ep0
+ulp,0x1.0p-50,0x1.bb4733e2cd111p2
+ulp,0x1.0p-53,0x1.ad427a13426a2p-1
+ulp,0x1.0p-54,0x1.5f1c41010e9dep-2
+ulp,0x1.0p-55,-0x1.2fc9edef312b5p-3
+ulp,0x1.0p-51,0x1.11242db5bd479p1
+ulp,0x1.0p-50,0x1.024f116156aeap2
+ulp,0x1.0p-52,-0x1.2f61c2afb9797p0
+ulp,0x1.0p-52,0x1.074aab47fa7bap0
+ulp,0x1.0p-52,-0x1.1e23ee7e724fp0
+ulp,0x1.0p-53,-0x1.10d1095c94562p-1
+ulp,0x1.0p-53,0x1.f797fb150a518p-1
+ulp,0x1.0p-52,-0x1.6ba40f9142b55p0
+ulp,0x1.0p-57,0x1.f6be0e1131cd9p-5
+ulp,0x1.0p-51,0x1.60936f7891dcbp1
+ulp,0x1.0p-52,0x1.76daad2da2fe2p0
+ulp,0x1.0p-52,0x1.3176325cb1721p0
+ulp,0x1.0p-55,0x1.35bfdee8919fdp-3
+ulp,0x1.0p-53,-0x1.271b0dd5cae1ap-1
+ulp,0x1.0p-56,0x1.eeb504b6dfd4ap-4
+ulp,0x1.0p-54,-0x1.62f2ea303123cp-2
+ulp,0x1.0p-53,-0x1.0b9b74d01a53p-1
+ulp,0x1.0p-54,-0x1.a25637868c8afp-2
+ulp,0x1.0p-51,0x1.4937474239c4cp1
+ulp,0x1.0p-53,-0x1.24e1d894ebd5bp-1
+ulp,0x1.0p-55,-0x1.aa1959b2ee2e7p-3
+ulp,0x1.0p-53,-0x1.519d5013ccc5ap-1
+ulp,0x1.0p-56,0x1.31cd2f93f176bp-4
+ulp,0x1.0p-53,0x1.a774c37c3fe41p-1
+ulp,0x1.0p-52,-0x1.8fd2aa3d25cf2p0
+ulp,0x1.0p-52,-0x1.0dd5221361bbfp0
+ulp,0x1.0p-54,-0x1.8e228ae1ed28ap-2
+ulp,0x1.0p-54,0x1.31010af798345p-2
+ulp,0x1.0p-55,0x1.fc20dfe30e64dp-3
+ulp,0x1.0p-49,-0x1.c2cbf5304bf0fp3
+ulp,0x1.0p-53,-0x1.599ea9e345bc3p-1
+ulp,0x1.0p-50,-0x1.5de71437e6098p2
+ulp,0x1.0p-51,-0x1.e0b06deed431ep1
+ulp,0x1.0p-53,0x1.a1c4c4cfd06e5p-1
+ulp,0x1.0p-52,0x1.af15d99cd9357p0
+ulp,0x1.0p-49,-0x1.c07b831808071p3
+ulp,0x1.0p-53,-0x1.24e1dfa1b04e1p-1
+ulp,0x1.0p-52,-0x1.0523d74000559p0
+ulp,0x1.0p-53,0x1.98227ece1cdebp-1
+ulp,0x1.0p-52,0x1.031b64f8b50bp0
+ulp,0x1.0p-50,-0x1.13e9f65198dc9p2
+ulp,0x1.0p-51,0x1.8101df83d5ff7p1
+ulp,0x1.0p-51,-0x1.5a449b9d853fbp1
+ulp,0x1.0p-52,-0x1.63b66f63b7592p0
+ulp,0x1.0p-50,-0x1.75d152f3855e4p2
+ulp,0x1.0p-52,-0x1.60b419eb80a92p0
+ulp,0x1.0p-54,0x1.0ab24d9767072p-2
+ulp,0x1.0p-56,-0x1.677f82863e19bp-4
+ulp,0x1.0p-53,-0x1.c1d83c1e436a5p-1
+ulp,0x1.0p-53,-0x1.8a192f285be71p-1
+ulp,0x1.0p-52,-0x1.52c3011b6fe09p0
+ulp,0x1.0p-49,-0x1.3076869da11dbp3
+ulp,0x1.0p-47,-0x1.62753b9029688p5
+ulp,0x1.0p-50,0x1.6d859d4adc109p2
+ulp,0x1.0p-53,0x1.e2598b488484p-1
+ulp,0x1.0p-56,-0x1.b89a9bb75880dp-4
+ulp,0x1.0p-57,-0x1.344e647fb82dbp-5
+ulp,0x1.0p-53,-0x1.3d3c417ea51c6p-1
+ulp,0x1.0p-54,0x1.f0b8097570173p-2
+ulp,0x1.0p-52,0x1.4e14e33ecdf99p0
+ulp,0x1.0p-51,0x1.1391e3bde920bp1
+ulp,0x1.0p-54,0x1.24809ab102362p-2
+ulp,0x1.0p-53,0x1.4bc9511d85d9cp-1
+ulp,0x1.0p-52,-0x1.09a22fbedba27p0
+ulp,0x1.0p-50,-0x1.a4d703650a565p2
+ulp,0x1.0p-51,-0x1.feb1e72fa3007p1
+ulp,0x1.0p-51,0x1.b01b70b420dc8p1
+ulp,0x1.0p-54,0x1.2773164ad9322p-2
+ulp,0x1.0p-52,-0x1.7502d121daceap0
+ulp,0x1.0p-53,-0x1.eae29ee9c5ef1p-1
+ulp,0x1.0p-50,-0x1.483240344459bp2
+ulp,0x1.0p-55,0x1.c0103c2efe682p-3
+ulp,0x1.0p-54,0x1.b37df0c13405p-2
+ulp,0x1.0p-53,0x1.1e5fccb8bb648p-1
+ulp,0x1.0p-52,-0x1.d6fce3c72d00dp0
+ulp,0x1.0p-52,0x1.bbbdbba0acfe1p0
+ulp,0x1.0p-50,0x1.4879b63b323bap2
+ulp,0x1.0p-51,0x1.2c7eb76edde01p1
+ulp,0x1.0p-53,-0x1.7cb31a5805664p-1
+ulp,0x1.0p-54,0x1.dff05a29b1a26p-2
+ulp,0x1.0p-51,-0x1.51dbe032b9c06p1
+ulp,0x1.0p-53,0x1.534efa559f66fp-1
+ulp,0x1.0p-53,0x1.2a916c337b64ap-1
+ulp,0x1.0p-52,-0x1.1adcf04b3064bp0
+ulp,0x1.0p-53,-0x1.568dee10a8ad9p-1
+ulp,0x1.0p-53,0x1.5442044e7c1c7p-1
+ulp,0x1.0p-46,-0x1.31ab0c728438fp6
+ulp,0x1.0p-51,-0x1.7259325752162p1
+ulp,0x1.0p-57,-0x1.1a30486920f7bp-5
+ulp,0x1.0p-51,-0x1.b16030f80babp1
+ulp,0x1.0p-54,0x1.2614558cba404p-2
+ulp,0x1.0p-51,-0x1.7d5d8217e0831p1
+ulp,0x1.0p-53,-0x1.a0f4358bb963p-1
+ulp,0x1.0p-51,-0x1.a088924c7d188p1
+ulp,0x1.0p-55,-0x1.e7f3eef54f87ap-3
+ulp,0x1.0p-50,-0x1.fe3cd0e46db73p2
+ulp,0x1.0p-54,-0x1.39983772d5ab8p-2
+ulp,0x1.0p-57,0x1.dd29df7b3f96ap-5
+ulp,0x1.0p-52,0x1.3dffeec0811f1p0
+ulp,0x1.0p-52,-0x1.d2bad5256de4p0
+ulp,0x1.0p-48,0x1.5fb78d86618a6p4
+ulp,0x1.0p-49,-0x1.5ae03318632e8p3
+ulp,0x1.0p-56,-0x1.bde7eaeb40779p-4
+ulp,0x1.0p-52,0x1.f1974828ea84p0
+ulp,0x1.0p-53,0x1.80b6f42d2bdefp-1
+ulp,0x1.0p-55,0x1.b63403d4a8bd4p-3
+ulp,0x1.0p-53,0x1.601d62621a398p-1
+ulp,0x1.0p-56,-0x1.8da30ebf2699ep-4
+ulp,0x1.0p-53,0x1.52e994b0bf5fap-1
+ulp,0x1.0p-44,0x1.68b8d3d4caec1p8
+ulp,0x1.0p-52,0x1.290206f80c1bbp0
+ulp,0x1.0p-47,-0x1.31f2eb6da1f32p5
+ulp,0x1.0p-48,0x1.2eb942192a685p4
+ulp,0x1.0p-51,0x1.4985c432f4e67p1
+ulp,0x1.0p-57,-0x1.c41bd03336427p-5
+ulp,0x1.0p-56,0x1.e05e5b77d153cp-4
+ulp,0x1.0p-50,0x1.e8e2441e1dd1bp2
+ulp,0x1.0p-51,-0x1.1d17c19fb812bp1
+ulp,0x1.0p-51,0x1.bd7d2fbe8ab71p1
+ulp,0x1.0p-53,0x1.67be4b958620dp-1
+ulp,0x1.0p-52,-0x1.3f3300c19df5bp0
+ulp,0x1.0p-52,-0x1.d474a6d231974p0
+ulp,0x1.0p-51,-0x1.b2ffcba471472p1
+ulp,0x1.0p-51,0x1.a50dfd97235aep1
+ulp,0x1.0p-52,-0x1.565eeb5a460aap0
+ulp,0x1.0p-47,0x1.ce6d570b266b2p5
+ulp,0x1.0p-52,0x1.8d85cece5190cp0
+ulp,0x1.0p-46,-0x1.1b29a95d8973p6
+ulp,0x1.0p-52,0x1.44e58ae4e0f71p0
+ulp,0x1.0p-55,-0x1.09d04981b12a3p-3
+ulp,0x1.0p-52,0x1.e135d7eb33b54p0
+ulp,0x1.0p-54,-0x1.24f0a8aa287bep-2
+ulp,0x1.0p-52,-0x1.0cca58d230b3cp0
+ulp,0x1.0p-52,-0x1.0bbdc09c44261p0
+ulp,0x1.0p-53,0x1.cc27aac8ccd2bp-1
+ulp,0x1.0p-55,0x1.849ac758f5bbap-3
+ulp,0x1.0p-52,-0x1.716751ce9b3p0
+ulp,0x1.0p-52,0x1.06d1aadc5d03fp0
+ulp,0x1.0p-51,-0x1.37c7c20ede5dp1
+ulp,0x1.0p-52,0x1.af0bc6aa67949p0
+ulp,0x1.0p-52,0x1.13e3c05223dd8p0
+ulp,0x1.0p-53,-0x1.fcfccf983f742p-1
+ulp,0x1.0p-52,0x1.2109216556897p0
+ulp,0x1.0p-58,-0x1.cf9910c8f7fb7p-6
+ulp,0x1.0p-54,-0x1.710efab54e94bp-2
+ulp,0x1.0p-52,0x1.1b38ea6942004p0
+ulp,0x1.0p-52,0x1.ed158cf170328p0
+ulp,0x1.0p-51,0x1.b52c5e8111303p1
+ulp,0x1.0p-49,-0x1.2e7f6bbcee20ep3
+ulp,0x1.0p-54,0x1.8a5fd3b9ca19ap-2
+ulp,0x1.0p-52,0x1.a6c899c30c922p0
+ulp,0x1.0p-53,0x1.afeba7ea55248p-1
+ulp,0x1.0p-53,-0x1.8ea9b89dffed6p-1
+ulp,0x1.0p-54,-0x1.efd893fe08d6fp-2
+ulp,0x1.0p-58,0x1.4b9af1ea9f96fp-6
+ulp,0x1.0p-46,0x1.1a46e5c8b221p6
diff --git a/luni/src/test/resources/math_tests.csv b/luni/src/test/resources/math_tests.csv
new file mode 100644
index 0000000..3393400
--- /dev/null
+++ b/luni/src/test/resources/math_tests.csv
@@ -0,0 +1,5199 @@
+#These tests come from the intel tests in bionic
+tan,0x1.5078cebff9c73p-5,0x1.50486b2f87014p-5
+tan,-0x1.5078cebff9c73p-5,-0x1.50486b2f87014p-5
+tan,0x1.5389e6df41979p-4,0x1.52c39ef070cadp-4
+tan,-0x1.5389e6df41979p-4,-0x1.52c39ef070cadp-4
+tan,0x1.a933fe176b375p-3,0x1.a33f32ac5ceb5p-3
+tan,-0x1.a933fe176b375p-3,-0x1.a33f32ac5ceb5p-3
+tan,0x1.fac71cd34eea7p-2,0x1.d696bfa988db9p-2
+tan,-0x1.fac71cd34eea7p-2,-0x1.d696bfa988db9p-2
+tan,0x1.7ba49f739829fp-1,0x1.46ac372243536p-1
+tan,-0x1.7ba49f739829fp-1,-0x1.46ac372243536p-1
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x1.8f048832144b7p0,-0x1.0018p0
+tan,0x1.8f048832144b7p0,0x1.0018p0
+tan,-0x1.8e884b24313afp0,-0x1.090cca18a5565p2
+tan,0x1.8e884b24313afp0,0x1.090cca18a5565p2
+tan,-0x1.ca18654b35697p0,-0x1.0faa7650df144p0
+tan,0x1.ca18654b35697p0,0x1.0faa7650df144p0
+tan,-0x1.e52fafa22ef14p-2,-0x1.180000000004p5
+tan,0x1.e52fafa22ef14p-2,0x1.180000000004p5
+tan,-0x1.a3ca421dc30f2p-3,-0x1.4000527aca388p99
+tan,0x1.a3ca421dc30f2p-3,0x1.4000527aca388p99
+tan,0x1.1f3b7d1978609p1,-0x1.486c3634751ecp2
+tan,-0x1.1f3b7d1978609p1,0x1.486c3634751ecp2
+tan,-0x1.7eb873343fa7ap-1,-0x1.48a71800b5713p-1
+tan,0x1.7eb873343fa7ap-1,0x1.48a71800b5713p-1
+tan,0x1.be071572f64e8p-1,-0x1.49af0314eea3cp299
+tan,-0x1.be071572f64e8p-1,0x1.49af0314eea3cp299
+tan,0x1.ffbb2647f57a2p-1,-0x1.5fe00c814ffd6p2
+tan,-0x1.ffbb2647f57a2p-1,0x1.5fe00c814ffd6p2
+tan,-0x1.a8eb142b2f428p-1,-0x1.62ac241f79439p-1
+tan,0x1.a8eb142b2f428p-1,0x1.62ac241f79439p-1
+tan,-0x1.7d1d3559ddac9p-4,-0x1.7c051b476ca8dp-4
+tan,0x1.7d1d3559ddac9p-4,0x1.7c051b476ca8dp-4
+tan,-0x1.0e1d0305b7b72p2,-0x1.7e43c880074c6p996
+tan,0x1.0e1d0305b7b72p2,0x1.7e43c880074c6p996
+tan,-0x1.812bdfe0246bcp-4,-0x1.800ac363398c4p-4
+tan,0x1.812bdfe0246bcp-4,0x1.800ac363398c4p-4
+tan,-0x1.850e5544b0c79p-4,-0x1.83e46aedbff36p-4
+tan,0x1.850e5544b0c79p-4,0x1.83e46aedbff36p-4
+tan,0x1.e6b5d91bba934p-2,-0x1.83ecf42e9265ap3
+tan,-0x1.e6b5d91bba934p-2,0x1.83ecf42e9265ap3
+tan,-0x1.f3688bc2594e2p-1,-0x1.8bcp-1
+tan,0x1.f3688bc2594e2p-1,0x1.8bcp-1
+tan,0x1.ec0d0facdd08bp-2,-0x1.8d2ffffffffd1p9
+tan,-0x1.ec0d0facdd08bp-2,0x1.8d2ffffffffd1p9
+tan,0x1.ec0336d539259p-2,-0x1.8d3000fffffd1p9
+tan,-0x1.ec0336d539259p-2,0x1.8d3000fffffd1p9
+tan,-0x1.f8093a017021fp-1,-0x1.baeee6f6fa538p6
+tan,0x1.f8093a017021fp-1,0x1.baeee6f6fa538p6
+tan,0x1.deaf34994b7e7p3,-0x1.c6867e07455eap3
+tan,-0x1.deaf34994b7e7p3,0x1.c6867e07455eap3
+tan,-0x1.f29aa87d4e1dep-1,-0x1.d27ffffffep7
+tan,0x1.f29aa87d4e1dep-1,0x1.d27ffffffep7
+tan,0x1.762fb47a1925ap-3,-0x1.f0df38029c9efp3
+tan,-0x1.762fb47a1925ap-3,0x1.f0df38029c9efp3
+tan,-0x1.8eb23ef2126bcp0,-0x1.fffffc0000fffp-1
+tan,0x1.8eb23ef2126bcp0,0x1.fffffc0000fffp-1
+tan,-0x1.d299d285bf018p-2,-0x1.ffffffffffffcp1023
+tan,0x1.d299d285bf018p-2,0x1.ffffffffffffcp1023
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,-0x1.82bee572e2ac9p-6,0x1.0p64
+tan,0x1.82bee572e2ac9p-6,-0x1.0p64
+tan,0x1.f53a8d05afcf7p4,0x1.0000000000001p51
+tan,-0x1.f53a8d05afcf7p4,-0x1.0000000000001p51
+tan,-0x1.6b371df5980cep-1,0x1.0000000000001p1017
+tan,0x1.6b371df5980cep-1,-0x1.0000000000001p1017
+tan,-0x1.b32e78f49a0c8p2,0x1.0000000000003p3
+tan,0x1.b32e78f49a0c8p2,-0x1.0000000000003p3
+tan,0x1.98afbd24264bcp-1,0x1.0000000000003p21
+tan,-0x1.98afbd24264bcp-1,-0x1.0000000000003p21
+tan,0x1.b667a2abe36c3p0,0x1.0000000000003p511
+tan,-0x1.b667a2abe36c3p0,-0x1.0000000000003p511
+tan,0x1.204c26a427862p-2,0x1.0000000000003p716
+tan,-0x1.204c26a427862p-2,-0x1.0000000000003p716
+tan,0x1.91c8f2938262dp4,0x1.0000000000007p8
+tan,-0x1.91c8f2938262dp4,-0x1.0000000000007p8
+tan,-0x1.27f7f0880032p-2,0x1.0000000000038p380
+tan,0x1.27f7f0880032p-2,-0x1.0000000000038p380
+tan,-0x1.d6890cc32711dp-3,0x1.0000000000118p380
+tan,0x1.d6890cc32711dp-3,-0x1.0000000000118p380
+tan,0x1.9af0e6f72f912p-3,0x1.0000000000908p500
+tan,-0x1.9af0e6f72f912p-3,-0x1.0000000000908p500
+tan,0x1.17b4f5bf44098p-1,0x1.000000000cp-1
+tan,-0x1.17b4f5bf44098p-1,-0x1.000000000cp-1
+tan,-0x1.17eb22e4dba73p0,0x1.00000001cp40
+tan,0x1.17eb22e4dba73p0,-0x1.00000001cp40
+tan,0x1.f6f03ce5690a7p-1,0x1.0000001p250
+tan,-0x1.f6f03ce5690a7p-1,-0x1.0000001p250
+tan,0x1.e23b78282a75dp-1,0x1.000000988p27
+tan,-0x1.e23b78282a75dp-1,-0x1.000000988p27
+tan,-0x1.981b657e1ca27p-3,0x1.00000cp429
+tan,0x1.981b657e1ca27p-3,-0x1.00000cp429
+tan,-0x1.455a2184f4c3ep-1,0x1.00000fcp1000
+tan,0x1.455a2184f4c3ep-1,-0x1.00000fcp1000
+tan,0x1.8ee66962f210cp0,0x1.000f371b7a006p0
+tan,-0x1.8ee66962f210cp0,-0x1.000f371b7a006p0
+tan,-0x1.ecd75cf6d4664p-3,0x1.001p15
+tan,0x1.ecd75cf6d4664p-3,-0x1.001p15
+tan,0x1.17d42033277ccp-1,0x1.0017ffffffffdp-1
+tan,-0x1.17d42033277ccp-1,-0x1.0017ffffffffdp-1
+tan,0x1.8f048832144b7p0,0x1.0018p0
+tan,-0x1.8f048832144b7p0,-0x1.0018p0
+tan,-0x1.18273cc3e7639p-2,0x1.001fffep500
+tan,0x1.18273cc3e7639p-2,-0x1.001fffep500
+tan,-0x1.d8f90cad30547p-2,0x1.018p40
+tan,0x1.d8f90cad30547p-2,-0x1.018p40
+tan,0x1.b079ea0d14a4ap-2,0x1.01b8a484ac0b6p4
+tan,-0x1.b079ea0d14a4ap-2,-0x1.01b8a484ac0b6p4
+tan,-0x1.a40c262f6ab9ap-1,0x1.026ac0ef32d4p28
+tan,0x1.a40c262f6ab9ap-1,-0x1.026ac0ef32d4p28
+tan,0x1.03b8c1f329665p-4,0x1.035fdcd08a596p-4
+tan,-0x1.03b8c1f329665p-4,-0x1.035fdcd08a596p-4
+tan,0x1.044979d134ed9p-4,0x1.03fp-4
+tan,-0x1.044979d134ed9p-4,-0x1.03fp-4
+tan,-0x1.e717de7da2ce8p0,0x1.07p1
+tan,0x1.e717de7da2ce8p0,-0x1.07p1
+tan,-0x1.8c896f607ff52p-1,0x1.07p30
+tan,0x1.8c896f607ff52p-1,-0x1.07p30
+tan,0x1.fffffffff5d84p-1,0x1.07e4cef4cbb0ep4
+tan,-0x1.fffffffff5d84p-1,-0x1.07e4cef4cbb0ep4
+tan,0x1.b476d32c1b745p0,0x1.0a53a78b13ab2p0
+tan,-0x1.b476d32c1b745p0,-0x1.0a53a78b13ab2p0
+tan,0x1.f2df7c02d20cep-1,0x1.0afbc268b9848p6
+tan,-0x1.f2df7c02d20cep-1,-0x1.0afbc268b9848p6
+tan,-0x1.b571af562f08ap0,0x1.0cd5d435bea6dp1
+tan,0x1.b571af562f08ap0,-0x1.0cd5d435bea6dp1
+tan,-0x1.ac73d2920a795p0,0x1.0ep1
+tan,0x1.ac73d2920a795p0,-0x1.0ep1
+tan,-0x1.126dce8ac7c81p-1,0x1.1086210842108p5
+tan,0x1.126dce8ac7c81p-1,-0x1.1086210842108p5
+tan,-0x1.9680c02601047p0,0x1.11p1
+tan,0x1.9680c02601047p0,-0x1.11p1
+tan,0x1.d1e716934469bp0,0x1.118p0
+tan,-0x1.d1e716934469bp0,-0x1.118p0
+tan,-0x1.6aa7310143084p-1,0x1.19df389f39e0ap3
+tan,0x1.6aa7310143084p-1,-0x1.19df389f39e0ap3
+tan,0x1.cb9a99227bdc9p1,0x1.1c3598211013ap2
+tan,-0x1.cb9a99227bdc9p1,-0x1.1c3598211013ap2
+tan,-0x1.bc109c3e61724p7,0x1.1d65aa4224c3p118
+tan,0x1.bc109c3e61724p7,-0x1.1d65aa4224c3p118
+tan,-0x1.09b393f48b2c6p-1,0x1.1e4658272dc6fp3
+tan,0x1.09b393f48b2c6p-1,-0x1.1e4658272dc6fp3
+tan,0x1.200000000007ap-22,0x1.2p-22
+tan,-0x1.200000000007ap-22,-0x1.2p-22
+tan,-0x1.02a335b00707ap0,0x1.2127409620cacp95
+tan,0x1.02a335b00707ap0,-0x1.2127409620cacp95
+tan,0x1.2508b9c1273acp-4,0x1.2489224892248p-4
+tan,-0x1.2508b9c1273acp-4,-0x1.2489224892248p-4
+tan,0x1.fded5f53d132dp2,0x1.2a52d119da061p237
+tan,-0x1.fded5f53d132dp2,-0x1.2a52d119da061p237
+tan,0x1.2de56a6ef9c5ep-4,0x1.2d59ebab8dae4p-4
+tan,-0x1.2de56a6ef9c5ep-4,-0x1.2d59ebab8dae4p-4
+tan,0x1.31665eb191fbbp-4,0x1.30d5f8e54b6d8p-4
+tan,-0x1.31665eb191fbbp-4,-0x1.30d5f8e54b6d8p-4
+tan,0x1.3cc1d4d28bfd2p-2,0x1.333275d63ec5p-2
+tan,-0x1.3cc1d4d28bfd2p-2,-0x1.333275d63ec5p-2
+tan,0x1.3cc237c0c7dccp-2,0x1.3332d020b6da9p-2
+tan,-0x1.3cc237c0c7dccp-2,-0x1.3332d020b6da9p-2
+tan,0x1.5e472e16999dfp-1,0x1.333333401e66bp-1
+tan,-0x1.5e472e16999dfp-1,-0x1.333333401e66bp-1
+tan,0x1.b5ed1c2080a98p-1,0x1.38f137cb9dbfcp9
+tan,-0x1.b5ed1c2080a98p-1,-0x1.38f137cb9dbfcp9
+tan,0x1.01aa22e2133d4p1,0x1.39a383f3fa003p85
+tan,-0x1.01aa22e2133d4p1,-0x1.39a383f3fa003p85
+tan,0x1.ffffffffff582p-1,0x1.3a28c59d54311p4
+tan,-0x1.ffffffffff582p-1,-0x1.3a28c59d54311p4
+tan,0x1.7166689d4803fp-1,0x1.4000000003fffp-1
+tan,-0x1.7166689d4803fp-1,-0x1.4000000003fffp-1
+tan,-0x1.ff7d27b37eba1p-1,0x1.40724a44714cfp5
+tan,0x1.ff7d27b37eba1p-1,-0x1.40724a44714cfp5
+tan,0x1.453a7d29dadadp-4,0x1.448c2d6e1e1afp-4
+tan,-0x1.453a7d29dadadp-4,-0x1.448c2d6e1e1afp-4
+tan,-0x1.a50f7601413e5p0,0x1.478fc08p43
+tan,0x1.a50f7601413e5p0,-0x1.478fc08p43
+tan,-0x1.a9991acb7636cp-4,0x1.4e93bee72b565p62
+tan,0x1.a9991acb7636cp-4,-0x1.4e93bee72b565p62
+tan,0x1.2952396945948p1,0x1.4f0f308p488
+tan,-0x1.2952396945948p1,-0x1.4f0f308p488
+tan,0x1.5078cebff9c73p-5,0x1.50486b2f87014p-5
+tan,-0x1.5078cebff9c73p-5,-0x1.50486b2f87014p-5
+tan,-0x1.1c929b6ede9eep-1,0x1.5130d552f1036p1
+tan,0x1.1c929b6ede9eep-1,-0x1.5130d552f1036p1
+tan,0x1.2ab3189e2d4aep1,0x1.52f00ep793
+tan,-0x1.2ab3189e2d4aep1,-0x1.52f00ep793
+tan,-0x1.7d2e63fb98891p0,0x1.5371684e5fb34p2
+tan,0x1.7d2e63fb98891p0,-0x1.5371684e5fb34p2
+tan,-0x1.f9f4f0da4de54p-1,0x1.54ef2208956p239
+tan,0x1.f9f4f0da4de54p-1,-0x1.54ef2208956p239
+tan,0x1.1483073142e6p2,0x1.57e590af09014p0
+tan,-0x1.1483073142e6p2,-0x1.57e590af09014p0
+tan,0x1.9972d4021c972p-1,0x1.596p-1
+tan,-0x1.9972d4021c972p-1,-0x1.596p-1
+tan,-0x1.e501ffd3a68c4p-2,0x1.5981293783e1fp1
+tan,0x1.e501ffd3a68c4p-2,-0x1.5981293783e1fp1
+tan,0x1.1604cc3dfc418p-1,0x1.5bea01p468
+tan,-0x1.1604cc3dfc418p-1,-0x1.5bea01p468
+tan,-0x1.f76ca50bbbaebp-1,0x1.60661c1969666p2
+tan,0x1.f76ca50bbbaebp-1,-0x1.60661c1969666p2
+tan,0x1.cd8b73c9430ffp0,0x1.62c5a850a142ap59
+tan,-0x1.cd8b73c9430ffp0,-0x1.62c5a850a142ap59
+tan,0x1.3accfd453ee67p0,0x1.64ef438p142
+tan,-0x1.3accfd453ee67p0,-0x1.64ef438p142
+tan,-0x1.acd9302d72de4p-1,0x1.658p2
+tan,0x1.acd9302d72de4p-1,-0x1.658p2
+tan,0x1.f004f875c2e74p-1,0x1.6603c65d348d2p5
+tan,-0x1.f004f875c2e74p-1,-0x1.6603c65d348d2p5
+tan,0x1.f53496e6d7f72p-1,0x1.660e6bf2e092ap5
+tan,-0x1.f53496e6d7f72p-1,-0x1.660e6bf2e092ap5
+tan,0x1.b64ee24f0119cp-1,0x1.6a8p-1
+tan,-0x1.b64ee24f0119cp-1,-0x1.6a8p-1
+tan,-0x1.d9ba9a7975636p60,0x1.6ac5b262ca1ffp849
+tan,0x1.d9ba9a7975636p60,-0x1.6ac5b262ca1ffp849
+tan,0x1.b6f557b999e23p-1,0x1.6aep-1
+tan,-0x1.b6f557b999e23p-1,-0x1.6aep-1
+tan,0x1.c1e1d5c4c0f08p-1,0x1.6cdb36cdb36c9p239
+tan,-0x1.c1e1d5c4c0f08p-1,-0x1.6cdb36cdb36c9p239
+tan,0x1.95bce4f578698p-1,0x1.6f1af1612270ap6
+tan,-0x1.95bce4f578698p-1,-0x1.6f1af1612270ap6
+tan,0x1.711e8f5fffba2p-4,0x1.702p-4
+tan,-0x1.711e8f5fffba2p-4,-0x1.702p-4
+tan,0x1.fb5898f29bb26p2,0x1.72p0
+tan,-0x1.fb5898f29bb26p2,-0x1.72p0
+tan,-0x1.ff9b771284d23p1,0x1.7348c347ddc2p239
+tan,0x1.ff9b771284d23p1,-0x1.7348c347ddc2p239
+tan,0x1.f72d47a0080e3p-2,0x1.739ce739ce738p100
+tan,-0x1.f72d47a0080e3p-2,-0x1.739ce739ce738p100
+tan,0x1.76441e7f8ea6p-4,0x1.753acc3d3ff35p-4
+tan,-0x1.76441e7f8ea6p-4,-0x1.753acc3d3ff35p-4
+tan,0x1.ce3f642e15af4p-1,0x1.77fffffffffffp-1
+tan,-0x1.ce3f642e15af4p-1,-0x1.77fffffffffffp-1
+tan,0x1.f425002a548ebp42,0x1.78fdb9effea26p4
+tan,-0x1.f425002a548ebp42,-0x1.78fdb9effea26p4
+tan,-0x1.dbc80de7dd043p-1,0x1.7a5f74607e851p19
+tan,0x1.dbc80de7dd043p-1,-0x1.7a5f74607e851p19
+tan,0x1.7b3bb3d0b3ca4p42,0x1.7f7ef77e83f1ap19
+tan,-0x1.7b3bb3d0b3ca4p42,-0x1.7f7ef77e83f1ap19
+tan,0x1.e7f05b71cd2d1p33,0x1.7f7f10a07f45ep20
+tan,-0x1.e7f05b71cd2d1p33,-0x1.7f7f10a07f45ep20
+tan,0x1.8000000000004p-25,0x1.7ffffffffffffp-25
+tan,-0x1.8000000000004p-25,-0x1.7ffffffffffffp-25
+tan,0x1.8000000000007p-25,0x1.8000000000002p-25
+tan,-0x1.8000000000007p-25,-0x1.8000000000002p-25
+tan,0x1.24245af4cd995p-52,0x1.81ae0dffa3b33p959
+tan,-0x1.24245af4cd995p-52,-0x1.81ae0dffa3b33p959
+tan,0x1.d72261d98e26cp-1,0x1.846bd7a4dce55p698
+tan,-0x1.d72261d98e26cp-1,-0x1.846bd7a4dce55p698
+tan,0x1.42d8a1ba441adp1,0x1.8720588p392
+tan,-0x1.42d8a1ba441adp1,-0x1.8720588p392
+tan,0x1.ea7b444cd798ep-1,0x1.8722a67ea14acp-1
+tan,-0x1.ea7b444cd798ep-1,-0x1.8722a67ea14acp-1
+tan,-0x1.c7dc7f08dbbap-1,0x1.89936c8828d38p299
+tan,0x1.c7dc7f08dbbap-1,-0x1.89936c8828d38p299
+tan,0x1.569653e319bbap1,0x1.8a69106fb9798p6
+tan,-0x1.569653e319bbap1,-0x1.8a69106fb9798p6
+tan,0x1.f2db21469f3d6p-1,0x1.8b777e1d2308cp-1
+tan,-0x1.f2db21469f3d6p-1,-0x1.8b777e1d2308cp-1
+tan,0x1.f3688bc2594e2p-1,0x1.8bcp-1
+tan,-0x1.f3688bc2594e2p-1,-0x1.8bcp-1
+tan,0x1.8d3a2544566dfp-4,0x1.8bfd2274d851ap-4
+tan,-0x1.8d3a2544566dfp-4,-0x1.8bfd2274d851ap-4
+tan,0x1.f4575cc4e477fp-1,0x1.8c3a450071dd9p-1
+tan,-0x1.f4575cc4e477fp-1,-0x1.8c3a450071dd9p-1
+tan,-0x1.1e09f66c4250cp11,0x1.8cc0dd2b0f4b8p200
+tan,0x1.1e09f66c4250cp11,-0x1.8cc0dd2b0f4b8p200
+tan,0x1.f71496cb921e6p-1,0x1.8dap-1
+tan,-0x1.f71496cb921e6p-1,-0x1.8dap-1
+tan,0x1.f71b4a659116ap-1,0x1.8da368da368d8p-1
+tan,-0x1.f71b4a659116ap-1,-0x1.8da368da368d8p-1
+tan,0x1.ff9b68ccadb3p-1,0x1.91ed64b977a9ap-1
+tan,-0x1.ff9b68ccadb3p-1,-0x1.91ed64b977a9ap-1
+tan,0x1.0000000029048p18,0x1.921f754442d19p0
+tan,-0x1.0000000029048p18,-0x1.921f754442d19p0
+tan,0x1.eef067afd328fp48,0x1.921fb54442d1p0
+tan,-0x1.eef067afd328fp48,-0x1.921fb54442d1p0
+tan,0x1.0000000003af3p-17,0x1.921ff54442d18p1
+tan,-0x1.0000000003af3p-17,-0x1.921ff54442d18p1
+tan,-0x1.b6772cb667dc2p17,0x1.922p0
+tan,0x1.b6772cb667dc2p17,-0x1.922p0
+tan,-0x1.fffffffceeefep-1,0x1.922071c31fc99p20
+tan,0x1.fffffffceeefep-1,-0x1.922071c31fc99p20
+tan,0x1.9d7c1354ba6f8p-3,0x1.97fffffffffffp-3
+tan,-0x1.9d7c1354ba6f8p-3,-0x1.97fffffffffffp-3
+tan,0x1.9af8877bb45e4p-4,0x1.999999a10a13cp-4
+tan,-0x1.9af8877bb45e4p-4,-0x1.999999a10a13cp-4
+tan,-0x1.b6ce128587cdp4,0x1.9b74446ed05dcp0
+tan,0x1.b6ce128587cdp4,-0x1.9b74446ed05dcp0
+tan,0x1.ff65aef54c8fcp-1,0x1.9eae494d2b275p4
+tan,-0x1.ff65aef54c8fcp-1,-0x1.9eae494d2b275p4
+tan,0x1.61776aa407a44p-3,0x1.a8p1
+tan,-0x1.61776aa407a44p-3,-0x1.a8p1
+tan,0x1.b6001de13ad96p-3,0x1.af8p-3
+tan,-0x1.b6001de13ad96p-3,-0x1.af8p-3
+tan,0x1.b5a0503ae354bp-4,0x1.b3f8ea7b1f91bp-4
+tan,-0x1.b5a0503ae354bp-4,-0x1.b3f8ea7b1f91bp-4
+tan,0x1.b5a0503ae4c7bp-4,0x1.b3f8ea7b21008p-4
+tan,-0x1.b5a0503ae4c7bp-4,-0x1.b3f8ea7b21008p-4
+tan,0x1.057584c429b3ap59,0x1.b951f1572eba5p23
+tan,-0x1.057584c429b3ap59,-0x1.b951f1572eba5p23
+tan,-0x1.9a282fa1ff7dap2,0x1.b9cp0
+tan,0x1.9a282fa1ff7dap2,-0x1.b9cp0
+tan,-0x1.027d184afb198p-52,0x1.bab62ed655019p970
+tan,0x1.027d184afb198p-52,-0x1.bab62ed655019p970
+tan,0x1.ca6efdf845d6dp2,0x1.bea1b35f3cb6dp84
+tan,-0x1.ca6efdf845d6dp2,-0x1.bea1b35f3cb6dp84
+tan,0x1.fd87b34747b74p42,0x1.c463abeccb27bp3
+tan,-0x1.fd87b34747b74p42,-0x1.c463abeccb27bp3
+tan,0x1.ffffffffffffbp-1,0x1.c463abeccb2bbp2
+tan,-0x1.ffffffffffffbp-1,-0x1.c463abeccb2bbp2
+tan,0x1.fb057029acfd2p-1,0x1.c6cbe26b7b45fp86
+tan,-0x1.fb057029acfd2p-1,-0x1.c6cbe26b7b45fp86
+tan,0x1.c8d5a08be40c2p-117,0x1.c8d5a08be40c2p-117
+tan,-0x1.c8d5a08be40c2p-117,-0x1.c8d5a08be40c2p-117
+tan,0x1.e5dffd7f06cb3p-2,0x1.cad4e9827a2bep1
+tan,-0x1.e5dffd7f06cb3p-2,-0x1.cad4e9827a2bep1
+tan,0x1.e6be378b1b4ecp-2,0x1.caeb940e4b997p1
+tan,-0x1.e6be378b1b4ecp-2,-0x1.caeb940e4b997p1
+tan,0x1.e72bd025a1fd6p-2,0x1.caf6c04ecd034p1
+tan,-0x1.e72bd025a1fd6p-2,-0x1.caf6c04ecd034p1
+tan,0x1.e844b3d7cbe44p-2,0x1.cb135ec1c956ep1
+tan,-0x1.e844b3d7cbe44p-2,-0x1.cb135ec1c956ep1
+tan,0x1.dd38a1f1d289bp-54,0x1.cb44e86bc192bp648
+tan,-0x1.dd38a1f1d289bp-54,-0x1.cb44e86bc192bp648
+tan,0x1.dd38a1f1d289bp-53,0x1.cb44e86bc192bp649
+tan,-0x1.dd38a1f1d289bp-53,-0x1.cb44e86bc192bp649
+tan,-0x1.fff6e755320edp1,0x1.cb61afedb2b3cp119
+tan,0x1.fff6e755320edp1,-0x1.cb61afedb2b3cp119
+tan,0x1.ccdf4aa6c229p-7,0x1.ccd7834ba3804p-7
+tan,-0x1.ccdf4aa6c229p-7,-0x1.ccd7834ba3804p-7
+tan,0x1.cee50016fc2d9p-4,0x1.ccf0599da478ep-4
+tan,-0x1.cee50016fc2d9p-4,-0x1.ccf0599da478ep-4
+tan,0x1.44cf3ee8a75a8p0,0x1.ce8p-1
+tan,-0x1.44cf3ee8a75a8p0,-0x1.ce8p-1
+tan,0x1.45aa12ff98152p0,0x1.cf276c9cb9afp-1
+tan,-0x1.45aa12ff98152p0,-0x1.cf276c9cb9afp-1
+tan,0x1.f9bc744f61e0fp-4,0x1.d2e979148a458p61
+tan,-0x1.f9bc744f61e0fp-4,-0x1.d2e979148a458p61
+tan,0x1.6e70f9edbd1ap-2,0x1.d6b5ad6b5ab68p100
+tan,-0x1.6e70f9edbd1ap-2,-0x1.d6b5ad6b5ab68p100
+tan,0x1.13e9c6a348e4ap2,0x1.d96e058p488
+tan,-0x1.13e9c6a348e4ap2,-0x1.d96e058p488
+tan,-0x1.d355463c23036p-5,0x1.dd10f25171bc9p5
+tan,0x1.d355463c23036p-5,-0x1.dd10f25171bc9p5
+tan,0x1.ddf21ebf6fc93p-6,0x1.ddcf6e56696a4p-6
+tan,-0x1.ddf21ebf6fc93p-6,-0x1.ddcf6e56696a4p-6
+tan,0x1.5cb0bfc1558p0,0x1.ep-1
+tan,-0x1.5cb0bfc1558p0,-0x1.ep-1
+tan,-0x1.97b5e8ae9a21dp1,0x1.ep0
+tan,0x1.97b5e8ae9a21dp1,-0x1.ep0
+tan,-0x1.f8bf68d0c23f3p0,0x1.e779de779de71p118
+tan,0x1.f8bf68d0c23f3p0,-0x1.e779de779de71p118
+tan,-0x1.fffffffffd71dp-1,0x1.eb0567bed1f71p12
+tan,0x1.fffffffffd71dp-1,-0x1.eb0567bed1f71p12
+tan,0x1.ee788d1cc7955p-4,0x1.ec16f30a34fbcp-4
+tan,-0x1.ee788d1cc7955p-4,-0x1.ec16f30a34fbcp-4
+tan,0x1.efdad938b4b0fp-4,0x1.ed7424ba2aa4ep-4
+tan,-0x1.efdad938b4b0fp-4,-0x1.ed7424ba2aa4ep-4
+tan,0x1.da347607948f4p-1,0x1.ee9eda589039p499
+tan,-0x1.da347607948f4p-1,-0x1.ee9eda589039p499
+tan,0x1.f682d27a8be88p0,0x1.f4ff0d7b3ac1p100
+tan,-0x1.f682d27a8be88p0,-0x1.f4ff0d7b3ac1p100
+tan,-0x1.ffd36a753ced9p-1,0x1.f5a814afd69f5p119
+tan,0x1.ffd36a753ced9p-1,-0x1.f5a814afd69f5p119
+tan,-0x1.0fa7701d059b5p-9,0x1.f8fc824d2693bp61
+tan,0x1.0fa7701d059b5p-9,-0x1.f8fc824d2693bp61
+tan,-0x1.afe3875bd3afep-4,0x1.f9be6f9be6f98p9
+tan,0x1.afe3875bd3afep-4,-0x1.f9be6f9be6f98p9
+tan,0x1.fd1032e82deabp-4,0x1.fa775cd264f43p-4
+tan,-0x1.fd1032e82deabp-4,-0x1.fa775cd264f43p-4
+tan,0x1.fea8c67dd46cbp-4,0x1.fc09b47402d82p-4
+tan,-0x1.fea8c67dd46cbp-4,-0x1.fc09b47402d82p-4
+tan,-0x1.9020caf18a874p-1,0x1.feeffffffffc6p995
+tan,0x1.9020caf18a874p-1,-0x1.feeffffffffc6p995
+tan,0x1.af135beb0f281p0,0x1.ff01fffffffffp7
+tan,-0x1.af135beb0f281p0,-0x1.ff01fffffffffp7
+tan,-0x1.fd97532efd89bp3,0x1.ff8ffffffffffp540
+tan,0x1.fd97532efd89bp3,-0x1.ff8ffffffffffp540
+tan,-0x1.cc32cb9338181p-1,0x1.ff8ffffffffffp870
+tan,0x1.cc32cb9338181p-1,-0x1.ff8ffffffffffp870
+tan,-0x1.8659d3e2b52b8p-1,0x1.ffc1p9
+tan,0x1.8659d3e2b52b8p-1,-0x1.ffc1p9
+tan,-0x1.b66066fb812eep-2,0x1.ffcfff8p19
+tan,0x1.b66066fb812eep-2,-0x1.ffcfff8p19
+tan,-0x1.520ebd32e1d8fp1,0x1.ffcfff8p365
+tan,0x1.520ebd32e1d8fp1,-0x1.ffcfff8p365
+tan,0x1.489813c24d13bp0,0x1.ffcffffffff6cp720
+tan,-0x1.489813c24d13bp0,-0x1.ffcffffffff6cp720
+tan,0x1.413e63f7dd608p0,0x1.ffcfffffffff9p320
+tan,-0x1.413e63f7dd608p0,-0x1.ffcfffffffff9p320
+tan,-0x1.fc3928a39b652p-2,0x1.ffcffffffffffp990
+tan,0x1.fc3928a39b652p-2,-0x1.ffcffffffffffp990
+tan,-0x1.9ad70d284f16ep-1,0x1.ffeffffffffccp995
+tan,0x1.9ad70d284f16ep-1,-0x1.ffeffffffffccp995
+tan,0x1.aad6effcb6784p-3,0x1.ffefffffffffdp366
+tan,-0x1.aad6effcb6784p-3,-0x1.ffefffffffffdp366
+tan,0x1.c88645f9d119fp2,0x1.ffeffffffffffp180
+tan,-0x1.c88645f9d119fp2,-0x1.ffeffffffffffp180
+tan,0x1.131aa7b9d4aap2,0x1.ffeffffffffffp231
+tan,-0x1.131aa7b9d4aap2,-0x1.ffeffffffffffp231
+tan,0x1.f671719be50d2p-3,0x1.ffeffffffffffp1019
+tan,-0x1.f671719be50d2p-3,-0x1.ffeffffffffffp1019
+tan,0x1.ff078a2d2d872p-1,0x1.fff1fffffffffp40
+tan,-0x1.ff078a2d2d872p-1,-0x1.fff1fffffffffp40
+tan,0x1.0784b04fc42a6p9,0x1.fff1fffffffffp41
+tan,-0x1.0784b04fc42a6p9,-0x1.fff1fffffffffp41
+tan,0x1.8eb22dd167a37p0,0x1.fffff1fffffffp-1
+tan,-0x1.8eb22dd167a37p0,-0x1.fffff1fffffffp-1
+tan,-0x1.22e7346fd3ddap1,0x1.ffffff8p119
+tan,0x1.22e7346fd3ddap1,-0x1.ffffff8p119
+tan,-0x1.db0b3b019f176p-3,0x1.ffffff8p192
+tan,0x1.db0b3b019f176p-3,-0x1.ffffff8p192
+tan,0x1.06b6bede91026p-1,0x1.ffffff8p543
+tan,-0x1.06b6bede91026p-1,-0x1.ffffff8p543
+tan,-0x1.40f02a15dfa3dp1,0x1.ffffffffbbfffp40
+tan,0x1.40f02a15dfa3dp1,-0x1.ffffffffbbfffp40
+tan,0x1.ab60112ef4fdep-2,0x1.fffffffff7fffp231
+tan,-0x1.ab60112ef4fdep-2,-0x1.fffffffff7fffp231
+tan,0x1.35a9929eeafd7p0,0x1.fffffffffff78p920
+tan,-0x1.35a9929eeafd7p0,-0x1.fffffffffff78p920
+tan,0x1.4630298f3b993p0,0x1.fffffffffffd5p995
+tan,-0x1.4630298f3b993p0,-0x1.fffffffffffd5p995
+tan,-0x1.9472e045129fep-1,0x1.fffffffffffe8p720
+tan,0x1.9472e045129fep-1,-0x1.fffffffffffe8p720
+tan,0x1.42e586daa1b42p0,0x1.fffffffffffebp920
+tan,-0x1.42e586daa1b42p0,-0x1.fffffffffffebp920
+tan,-0x1.bfc436b94374cp-1,0x1.ffffffffffff1p245
+tan,0x1.bfc436b94374cp-1,-0x1.ffffffffffff1p245
+tan,0x1.35117d4a4f1e5p0,0x1.ffffffffffff4p845
+tan,-0x1.35117d4a4f1e5p0,-0x1.ffffffffffff4p845
+tan,-0x1.bfdd9292798aap-1,0x1.ffffffffffff4p1020
+tan,0x1.bfdd9292798aap-1,-0x1.ffffffffffff4p1020
+tan,-0x1.9b768ccdae6ecp9,0x1.ffffffffffffcp45
+tan,0x1.9b768ccdae6ecp9,-0x1.ffffffffffffcp45
+tan,0x1.feca047f2730fp-1,0x1.ffffffffffffcp474
+tan,-0x1.feca047f2730fp-1,-0x1.ffffffffffffcp474
+tan,-0x1.449f15cc94559p-2,0x1.ffffffffffffcp976
+tan,0x1.449f15cc94559p-2,-0x1.ffffffffffffcp976
+tan,0x1.fffc58da07952p-2,0x1.ffffffffffffep881
+tan,-0x1.fffc58da07952p-2,-0x1.ffffffffffffep881
+tan,-0x1.c1c9195ec23aap-1,0x1.ffffffffffffep970
+tan,0x1.c1c9195ec23aap-1,-0x1.ffffffffffffep970
+tan,0x1.3cc1ed3906d2fp-2,0x1.33328c1b37321p-2
+tan,-0x1.3cc1ed3906d2fp-2,-0x1.33328c1b37321p-2
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0p0,-0x0.0p0
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,-0x1.0000000000001p-1022,-0x1.0000000000001p-1022
+tan,0x1.0000000000001p-1022,0x1.0000000000001p-1022
+tan,-0x1.0p-1022,-0x1.0p-1022
+tan,0x1.0p-1022,0x1.0p-1022
+tan,-0x0.fffffffffffffp-1022,-0x0.fffffffffffffp-1022
+tan,0x0.fffffffffffffp-1022,0x0.fffffffffffffp-1022
+tan,0x0.fffffffffffffp-1022,0x0.fffffffffffffp-1022
+tan,-0x0.fffffffffffffp-1022,-0x0.fffffffffffffp-1022
+tan,0x1.0p-1022,0x1.0p-1022
+tan,-0x1.0p-1022,-0x1.0p-1022
+tan,0x1.0000000000001p-1022,0x1.0000000000001p-1022
+tan,-0x1.0000000000001p-1022,-0x1.0000000000001p-1022
+tan,0x1.999999f0fb38cp-13,0x1.999999999999ap-13
+tan,-0x1.999999f0fb38cp-13,-0x1.999999999999ap-13
+tan,0x1.99999af720174p-12,0x1.999999999999ap-12
+tan,-0x1.99999af720174p-12,-0x1.999999999999ap-12
+tan,0x1.33333581062a4p-11,0x1.3333333333334p-11
+tan,-0x1.33333581062a4p-11,-0x1.3333333333334p-11
+tan,0x1.99999f0fb3a1p-11,0x1.999999999999ap-11
+tan,-0x1.99999f0fb3a1p-11,-0x1.999999999999ap-11
+tan,0x1.0000055555777p-10,0x1.0p-10
+tan,-0x1.0000055555777p-10,-0x1.0p-10
+tan,0x1.33333c6a7f4ecp-10,0x1.3333333333333p-10
+tan,-0x1.33333c6a7f4ecp-10,-0x1.3333333333333p-10
+tan,0x1.66667508e0a1bp-10,0x1.6666666666666p-10
+tan,-0x1.66667508e0a1bp-10,-0x1.6666666666666p-10
+tan,0x1.9999af7202c36p-10,0x1.9999999999999p-10
+tan,-0x1.9999af7202c36p-10,-0x1.9999999999999p-10
+tan,0x1.ccccebe76f103p-10,0x1.cccccccccccccp-10
+tan,-0x1.ccccebe76f103p-10,-0x1.cccccccccccccp-10
+tan,0x1.0667d5fcf3d08p-7,0x1.0666666666666p-7
+tan,-0x1.0667d5fcf3d08p-7,-0x1.0666666666666p-7
+tan,0x1.ccd4939d0ccd7p-7,0x1.cccccccccccccp-7
+tan,-0x1.ccd4939d0ccd7p-7,-0x1.cccccccccccccp-7
+tan,0x1.49a4fc02ad194p-6,0x1.4999999999999p-6
+tan,-0x1.49a4fc02ad194p-6,-0x1.4999999999999p-6
+tan,0x1.ace5ded5f6be7p-6,0x1.accccccccccccp-6
+tan,-0x1.ace5ded5f6be7p-6,-0x1.accccccccccccp-6
+tan,0x1.081767fd3cb68p-5,0x1.08p-5
+tan,-0x1.081767fd3cb68p-5,-0x1.08p-5
+tan,0x1.39c0d6dea66fbp-5,0x1.399999999999ap-5
+tan,-0x1.39c0d6dea66fbp-5,-0x1.399999999999ap-5
+tan,0x1.6b702b954bc1dp-5,0x1.6b33333333334p-5
+tan,-0x1.6b702b954bc1dp-5,-0x1.6b33333333334p-5
+tan,0x1.9d265618dd0c7p-5,0x1.9cccccccccccep-5
+tan,-0x1.9d265618dd0c7p-5,-0x1.9cccccccccccep-5
+tan,0x1.cee446e4cfd4cp-5,0x1.ce66666666666p-5
+tan,-0x1.cee446e4cfd4cp-5,-0x1.ce66666666666p-5
+tan,0x1.a1eaedd5a4314p-1,0x1.5e7fc4369bdadp-1
+tan,-0x1.a1eaedd5a4314p-1,-0x1.5e7fc4369bdadp-1
+tan,0x1.d93b8aad424dep1,0x1.4e7fc4369bdadp0
+tan,-0x1.d93b8aad424dep1,-0x1.4e7fc4369bdadp0
+tan,-0x1.563acf158c2ebp1,0x1.edbfa651e9c84p0
+tan,0x1.563acf158c2ebp1,-0x1.edbfa651e9c84p0
+tan,-0x1.576b77609f089p-1,0x1.467fc4369bdadp1
+tan,0x1.576b77609f089p-1,-0x1.467fc4369bdadp1
+tan,0x1.00155777aebf7p-5,0x1.961fb54442d18p1
+tan,-0x1.00155777aebf7p-5,-0x1.961fb54442d18p1
+tan,0x1.87e9966e7d22dp-1,0x1.e5bfa651e9c83p1
+tan,-0x1.87e9966e7d22dp-1,-0x1.e5bfa651e9c83p1
+tan,0x1.a49e7d8987851p1,0x1.1aafcbafc85f7p2
+tan,-0x1.a49e7d8987851p1,-0x1.1aafcbafc85f7p2
+tan,-0x1.79ced8156d041p1,0x1.427fc4369bdadp2
+tan,0x1.79ced8156d041p1,-0x1.427fc4369bdadp2
+tan,-0x1.6f1f65cd1e91bp-1,0x1.6a4fbcbd6f562p2
+tan,0x1.6f1f65cd1e91bp-1,-0x1.6a4fbcbd6f562p2
+tan,-0x1.67747d5f844e2p-1,0x1.6af2eff0a2896p2
+tan,0x1.67747d5f844e2p-1,-0x1.6af2eff0a2896p2
+tan,-0x1.626a258815d18p1,0x1.43c62a9d02414p2
+tan,0x1.626a258815d18p1,-0x1.43c62a9d02414p2
+tan,0x1.d6adaf80f8b05p1,0x1.1c99654961f92p2
+tan,-0x1.d6adaf80f8b05p1,-0x1.1c99654961f92p2
+tan,0x1.a94d1b21370d5p-1,0x1.ead93feb8361fp1
+tan,-0x1.a94d1b21370d5p-1,-0x1.ead93feb8361fp1
+tan,0x1.4cba9e7822234p-4,0x1.9c7fb54442d1ap1
+tan,-0x1.4cba9e7822234p-4,-0x1.9c7fb54442d1ap1
+tan,-0x1.2cb6d02634532p-1,0x1.4e262a9d02415p1
+tan,0x1.2cb6d02634532p-1,-0x1.4e262a9d02415p1
+tan,-0x1.18d9112308d5bp1,0x1.ff993feb8362p0
+tan,0x1.18d9112308d5bp1,-0x1.ff993feb8362p0
+tan,0x1.56fe0145cf29p2,0x1.62e62a9d02416p0
+tan,-0x1.56fe0145cf29p2,-0x1.62e62a9d02416p0
+tan,0x1.f4ad353aca454p-1,0x1.8c662a9d02419p-1
+tan,-0x1.f4ad353aca454p-1,-0x1.8c662a9d02419p-1
+tan,0x1.6a7e1f6407ee6p3,-0x1.a8aa1d11c44ffp0
+tan,-0x1.6a7e1f6407ee6p3,0x1.a8aa1d11c44ffp0
+tan,0x1.0d718cfc82464p6,-0x1.95ec8b9e03d54p0
+tan,-0x1.0d718cfc82464p6,0x1.95ec8b9e03d54p0
+tan,-0x1.11d87146c2d5ap4,-0x1.832efa2a435a9p0
+tan,0x1.11d87146c2d5ap4,0x1.832efa2a435a9p0
+tan,-0x1.e3a3729b3e86ep2,-0x1.707168b682dfep0
+tan,0x1.e3a3729b3e86ep2,0x1.707168b682dfep0
+tan,-0x1.3429e61a5d1f3p2,-0x1.5db3d742c2653p0
+tan,0x1.3429e61a5d1f3p2,0x1.5db3d742c2653p0
+tan,-0x1.c08caec5cf997p1,-0x1.4af645cf01ea8p0
+tan,0x1.c08caec5cf997p1,0x1.4af645cf01ea8p0
+tan,-0x1.5d603d751767fp1,-0x1.3838b45b416fdp0
+tan,0x1.5d603d751767fp1,0x1.3838b45b416fdp0
+tan,-0x1.1b48a35b1b278p1,-0x1.257b22e780f52p0
+tan,0x1.1b48a35b1b278p1,0x1.257b22e780f52p0
+tan,-0x1.d74caf9912dc8p0,-0x1.12bd9173c07abp0
+tan,0x1.d74caf9912dc8p0,0x1.12bd9173c07abp0
+tan,-0x1.6be702e1f6cd6p0,-0x1.ea5c3ed5b385p-1
+tan,0x1.6be702e1f6cd6p0,0x1.ea5c3ed5b385p-1
+tan,-0x1.4d0df1fc1d348p0,-0x1.d4b87dab670ap-1
+tan,0x1.4d0df1fc1d348p0,0x1.d4b87dab670ap-1
+tan,-0x1.316c8b068a7afp0,-0x1.bf14bc811a8fp-1
+tan,0x1.316c8b068a7afp0,0x1.bf14bc811a8fp-1
+tan,-0x1.1872a1aaa7e27p0,-0x1.a970fb56ce14p-1
+tan,0x1.1872a1aaa7e27p0,0x1.a970fb56ce14p-1
+tan,-0x1.01aeeed04cbb1p0,-0x1.93cd3a2c8199p-1
+tan,0x1.01aeeed04cbb1p0,0x1.93cd3a2c8199p-1
+tan,-0x1.d98e408ac2086p-1,-0x1.7e297902351ep-1
+tan,0x1.d98e408ac2086p-1,0x1.7e297902351ep-1
+tan,-0x1.b2e4750631c54p-1,-0x1.6885b7d7e8a3p-1
+tan,0x1.b2e4750631c54p-1,0x1.6885b7d7e8a3p-1
+tan,-0x1.8ee916392e046p-1,-0x1.52e1f6ad9c28p-1
+tan,0x1.8ee916392e046p-1,0x1.52e1f6ad9c28p-1
+tan,-0x1.6d395e495f77ep-1,-0x1.3d3e35834fadp-1
+tan,0x1.6d395e495f77ep-1,0x1.3d3e35834fadp-1
+tan,-0x1.24e3e017a098fp-1,-0x1.0a0b02501c799p-1
+tan,0x1.24e3e017a098fp-1,0x1.0a0b02501c799p-1
+tan,-0x1.fdbd5f0596bdcp-2,-0x1.d8f7208e6b82cp-2
+tan,0x1.fdbd5f0596bdcp-2,0x1.d8f7208e6b82cp-2
+tan,-0x1.b5f3d6afbe6f2p-2,-0x1.9dd83c7c9e126p-2
+tan,0x1.b5f3d6afbe6f2p-2,0x1.9dd83c7c9e126p-2
+tan,-0x1.71a0f98081eaap-2,-0x1.62b9586ad0a2p-2
+tan,0x1.71a0f98081eaap-2,0x1.62b9586ad0a2p-2
+tan,-0x1.301909a2c36e9p-2,-0x1.279a74590331ap-2
+tan,0x1.301909a2c36e9p-2,0x1.279a74590331ap-2
+tan,-0x1.e18e941cc7fd5p-3,-0x1.d8f7208e6b829p-3
+tan,0x1.e18e941cc7fd5p-3,0x1.d8f7208e6b829p-3
+tan,-0x1.6650784bbdccp-3,-0x1.62b9586ad0a1ep-3
+tan,0x1.6650784bbdccp-3,0x1.62b9586ad0a1ep-3
+tan,-0x1.db142468cdafcp-4,-0x1.d8f7208e6b826p-4
+tan,0x1.db142468cdafcp-4,0x1.d8f7208e6b826p-4
+tan,-0x1.d97dd6d2e53f3p-5,-0x1.d8f7208e6b82dp-5
+tan,0x1.d97dd6d2e53f3p-5,0x1.d8f7208e6b82dp-5
+tan,0x1.d97dd6d2e53f3p-5,0x1.d8f7208e6b82dp-5
+tan,-0x1.d97dd6d2e53f3p-5,-0x1.d8f7208e6b82dp-5
+tan,0x1.db142468cdb03p-4,0x1.d8f7208e6b82dp-4
+tan,-0x1.db142468cdb03p-4,-0x1.d8f7208e6b82dp-4
+tan,0x1.6650784bbdcc4p-3,0x1.62b9586ad0a22p-3
+tan,-0x1.6650784bbdcc4p-3,-0x1.62b9586ad0a22p-3
+tan,0x1.e18e941cc7fd9p-3,0x1.d8f7208e6b82dp-3
+tan,-0x1.e18e941cc7fd9p-3,-0x1.d8f7208e6b82dp-3
+tan,0x1.301909a2c36ebp-2,0x1.279a74590331cp-2
+tan,-0x1.301909a2c36ebp-2,-0x1.279a74590331cp-2
+tan,0x1.71a0f98081eacp-2,0x1.62b9586ad0a22p-2
+tan,-0x1.71a0f98081eacp-2,-0x1.62b9586ad0a22p-2
+tan,0x1.b5f3d6afbe6f5p-2,0x1.9dd83c7c9e128p-2
+tan,-0x1.b5f3d6afbe6f5p-2,-0x1.9dd83c7c9e128p-2
+tan,0x1.fdbd5f0596bdfp-2,0x1.d8f7208e6b82ep-2
+tan,-0x1.fdbd5f0596bdfp-2,-0x1.d8f7208e6b82ep-2
+tan,0x1.24e3e017a098fp-1,0x1.0a0b02501c799p-1
+tan,-0x1.24e3e017a098fp-1,-0x1.0a0b02501c799p-1
+tan,0x1.6d395e495f778p-1,0x1.3d3e35834faccp-1
+tan,-0x1.6d395e495f778p-1,-0x1.3d3e35834faccp-1
+tan,0x1.8ee916392e03fp-1,0x1.52e1f6ad9c27cp-1
+tan,-0x1.8ee916392e03fp-1,-0x1.52e1f6ad9c27cp-1
+tan,0x1.b2e4750631c4dp-1,0x1.6885b7d7e8a2cp-1
+tan,-0x1.b2e4750631c4dp-1,-0x1.6885b7d7e8a2cp-1
+tan,0x1.d98e408ac207ep-1,0x1.7e297902351dcp-1
+tan,-0x1.d98e408ac207ep-1,-0x1.7e297902351dcp-1
+tan,0x1.01aeeed04cbadp0,0x1.93cd3a2c8198cp-1
+tan,-0x1.01aeeed04cbadp0,-0x1.93cd3a2c8198cp-1
+tan,0x1.1872a1aaa7e22p0,0x1.a970fb56ce13cp-1
+tan,-0x1.1872a1aaa7e22p0,-0x1.a970fb56ce13cp-1
+tan,0x1.316c8b068a7aap0,0x1.bf14bc811a8ecp-1
+tan,-0x1.316c8b068a7aap0,-0x1.bf14bc811a8ecp-1
+tan,0x1.4d0df1fc1d343p0,0x1.d4b87dab6709cp-1
+tan,-0x1.4d0df1fc1d343p0,-0x1.d4b87dab6709cp-1
+tan,0x1.6be702e1f6cdp0,0x1.ea5c3ed5b384cp-1
+tan,-0x1.6be702e1f6cdp0,-0x1.ea5c3ed5b384cp-1
+tan,0x1.d74caf9912dc8p0,0x1.12bd9173c07abp0
+tan,-0x1.d74caf9912dc8p0,-0x1.12bd9173c07abp0
+tan,0x1.1b48a35b1b284p1,0x1.257b22e780f56p0
+tan,-0x1.1b48a35b1b284p1,-0x1.257b22e780f56p0
+tan,0x1.5d603d751769p1,0x1.3838b45b41701p0
+tan,-0x1.5d603d751769p1,-0x1.3838b45b41701p0
+tan,0x1.c08caec5cf9b2p1,0x1.4af645cf01eacp0
+tan,-0x1.c08caec5cf9b2p1,-0x1.4af645cf01eacp0
+tan,0x1.3429e61a5d20bp2,0x1.5db3d742c2657p0
+tan,-0x1.3429e61a5d20bp2,-0x1.5db3d742c2657p0
+tan,0x1.e3a3729b3e8a8p2,0x1.707168b682e02p0
+tan,-0x1.e3a3729b3e8a8p2,-0x1.707168b682e02p0
+tan,0x1.11d87146c2da4p4,0x1.832efa2a435adp0
+tan,-0x1.11d87146c2da4p4,-0x1.832efa2a435adp0
+tan,-0x1.0d718cfc82349p6,0x1.95ec8b9e03d58p0
+tan,0x1.0d718cfc82349p6,-0x1.95ec8b9e03d58p0
+tan,-0x1.6a7e1f6407ee6p3,0x1.a8aa1d11c44ffp0
+tan,0x1.6a7e1f6407ee6p3,-0x1.a8aa1d11c44ffp0
+tan,0x1.9f39ea5bbe475p0,0x1.04aff6d330942p0
+tan,-0x1.9f39ea5bbe475p0,-0x1.04aff6d330942p0
+tan,0x1.9f3c4b8469f85p0,0x1.04b09e98dcdb4p0
+tan,-0x1.9f3c4b8469f85p0,-0x1.04b09e98dcdb4p0
+tan,0x1.9f3eacb224c21p0,0x1.04b1465e89226p0
+tan,-0x1.9f3eacb224c21p0,-0x1.04b1465e89226p0
+tan,0x1.9f410de4eeb69p0,0x1.04b1ee2435698p0
+tan,-0x1.9f410de4eeb69p0,-0x1.04b1ee2435698p0
+tan,0x1.9f436f1cc7e82p0,0x1.04b295e9e1b0ap0
+tan,-0x1.9f436f1cc7e82p0,-0x1.04b295e9e1b0ap0
+tan,0x1.9f45d059b068fp0,0x1.04b33daf8df7cp0
+tan,-0x1.9f45d059b068fp0,-0x1.04b33daf8df7cp0
+tan,0x1.9f48319ba84b2p0,0x1.04b3e5753a3eep0
+tan,-0x1.9f48319ba84b2p0,-0x1.04b3e5753a3eep0
+tan,0x1.9f4a92e2afa0dp0,0x1.04b48d3ae686p0
+tan,-0x1.9f4a92e2afa0dp0,-0x1.04b48d3ae686p0
+tan,0x1.9f4cf42ec67bbp0,0x1.04b5350092ccfp0
+tan,-0x1.9f4cf42ec67bbp0,-0x1.04b5350092ccfp0
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0p0,-0x0.0p0
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x1.4d82b68cac19ep-1,0x1.279a74590331bp-1
+tan,-0x1.4d82b68cac19ep-1,-0x1.279a74590331bp-1
+tan,0x1.4d82b68cac1ap-1,0x1.279a74590331cp-1
+tan,-0x1.4d82b68cac1ap-1,-0x1.279a74590331cp-1
+tan,0x1.4d82b68cac1a1p-1,0x1.279a74590331dp-1
+tan,-0x1.4d82b68cac1a1p-1,-0x1.279a74590331dp-1
+tan,-0x1.89712eeca32bfp2,0x1.bb67ae8584ca9p0
+tan,0x1.89712eeca32bfp2,-0x1.bb67ae8584ca9p0
+tan,-0x1.89712eeca32b5p2,0x1.bb67ae8584caap0
+tan,0x1.89712eeca32b5p2,-0x1.bb67ae8584caap0
+tan,-0x1.89712eeca32abp2,0x1.bb67ae8584cabp0
+tan,0x1.89712eeca32abp2,-0x1.bb67ae8584cabp0
+tan,0x1.def49eaab37ap-2,0x1.bffffffffffffp-2
+tan,-0x1.def49eaab37ap-2,-0x1.bffffffffffffp-2
+tan,0x1.def49eaab37a1p-2,0x1.cp-2
+tan,-0x1.def49eaab37a1p-2,-0x1.cp-2
+tan,0x1.def49eaab37a3p-2,0x1.c000000000001p-2
+tan,-0x1.def49eaab37a3p-2,-0x1.c000000000001p-2
+tan,0x1.a46cb2be6a0bp-1,0x1.5ffffffffffffp-1
+tan,-0x1.a46cb2be6a0bp-1,-0x1.5ffffffffffffp-1
+tan,0x1.a46cb2be6a0b2p-1,0x1.6p-1
+tan,-0x1.a46cb2be6a0b2p-1,-0x1.6p-1
+tan,0x1.a46cb2be6a0b4p-1,0x1.6000000000001p-1
+tan,-0x1.a46cb2be6a0b4p-1,-0x1.6000000000001p-1
+tan,0x1.3d6dc956eac7ap1,0x1.2ffffffffffffp0
+tan,-0x1.3d6dc956eac7ap1,-0x1.2ffffffffffffp0
+tan,0x1.3d6dc956eac7dp1,0x1.3p0
+tan,-0x1.3d6dc956eac7dp1,-0x1.3p0
+tan,0x1.3d6dc956eac81p1,0x1.3000000000001p0
+tan,-0x1.3d6dc956eac81p1,-0x1.3000000000001p0
+tan,-0x1.b2d89a9382954p-1,0x1.37fffffffffffp1
+tan,0x1.b2d89a9382954p-1,-0x1.37fffffffffffp1
+tan,-0x1.b2d89a938294cp-1,0x1.38p1
+tan,0x1.b2d89a938294cp-1,-0x1.38p1
+tan,-0x1.b2d89a9382946p-1,0x1.3800000000001p1
+tan,0x1.b2d89a9382946p-1,-0x1.3800000000001p1
+tan,0x1.06f8d014bf084p-4,0x1.069c8b46b3792p-4
+tan,-0x1.06f8d014bf084p-4,-0x1.069c8b46b3792p-4
+tan,0x1.080f73b07051ep-3,0x1.069c8b46b3792p-3
+tan,-0x1.080f73b07051ep-3,-0x1.069c8b46b3792p-3
+tan,0x1.8ed9142fc9189p-3,0x1.89ead0ea0d35bp-3
+tan,-0x1.8ed9142fc9189p-3,-0x1.89ead0ea0d35bp-3
+tan,0x1.0c864083d1e7dp-2,0x1.069c8b46b3792p-2
+tan,-0x1.0c864083d1e7dp-2,-0x1.069c8b46b3792p-2
+tan,0x1.53fdcdfd37f04p-2,0x1.4843ae1860576p-2
+tan,-0x1.53fdcdfd37f04p-2,-0x1.4843ae1860576p-2
+tan,0x1.9e9257e6b62a1p-2,0x1.89ead0ea0d35ap-2
+tan,-0x1.9e9257e6b62a1p-2,-0x1.89ead0ea0d35ap-2
+tan,0x1.ed21e59972b08p-2,0x1.cb91f3bbba13ep-2
+tan,-0x1.ed21e59972b08p-2,-0x1.cb91f3bbba13ep-2
+tan,0x1.205a6009d5e3ep-1,0x1.069c8b46b3791p-1
+tan,-0x1.205a6009d5e3ep-1,-0x1.069c8b46b3791p-1
+tan,0x1.4d466accad48ep-1,0x1.27701caf89e83p-1
+tan,-0x1.4d466accad48ep-1,-0x1.27701caf89e83p-1
+tan,0x1.7e1d936f4d615p-1,0x1.4843ae1860575p-1
+tan,-0x1.7e1d936f4d615p-1,-0x1.4843ae1860575p-1
+tan,0x1.b3df386f18228p-1,0x1.69173f8136c67p-1
+tan,-0x1.b3df386f18228p-1,-0x1.69173f8136c67p-1
+tan,0x1.efd82742d778cp-1,0x1.89ead0ea0d359p-1
+tan,-0x1.efd82742d778cp-1,-0x1.89ead0ea0d359p-1
+tan,0x1.19e26b5ecd5cp0,0x1.aabe6252e3a4bp-1
+tan,-0x1.19e26b5ecd5cp0,-0x1.aabe6252e3a4bp-1
+tan,0x1.41038b70be0fap0,0x1.cb91f3bbba13dp-1
+tan,-0x1.41038b70be0fap0,-0x1.cb91f3bbba13dp-1
+tan,0x1.6efec8c1e493bp0,0x1.ec6585249082fp-1
+tan,-0x1.6efec8c1e493bp0,-0x1.ec6585249082fp-1
+tan,0x1.a64c7c9d65346p0,0x1.069c8b46b3791p0
+tan,-0x1.a64c7c9d65346p0,-0x1.069c8b46b3791p0
+tan,0x1.eab43e0e5e87cp0,0x1.170653fb1eb0ap0
+tan,-0x1.eab43e0e5e87cp0,-0x1.170653fb1eb0ap0
+tan,0x1.21277b97c0137p1,0x1.27701caf89e83p0
+tan,-0x1.21277b97c0137p1,-0x1.27701caf89e83p0
+tan,0x1.5bd13dda077cdp1,0x1.37d9e563f51fcp0
+tan,-0x1.5bd13dda077cdp1,-0x1.37d9e563f51fcp0
+tan,0x1.af4643e9371f9p1,0x1.4843ae1860575p0
+tan,-0x1.af4643e9371f9p1,-0x1.4843ae1860575p0
+tan,0x1.1866fe845e75ap2,0x1.58ad76cccb8eep0
+tan,-0x1.1866fe845e75ap2,-0x1.58ad76cccb8eep0
+tan,0x1.8bdcd54bd5981p2,0x1.69173f8136c67p0
+tan,-0x1.8bdcd54bd5981p2,-0x1.69173f8136c67p0
+tan,0x1.4bb6a64e0625cp3,0x1.79810835a1fep0
+tan,-0x1.4bb6a64e0625cp3,-0x1.79810835a1fep0
+tan,0x1.f2f05cfb656a4p4,0x1.89ead0ea0d359p0
+tan,-0x1.f2f05cfb656a4p4,-0x1.89ead0ea0d359p0
+tan,-0x1.f2f05cfb657f5p4,0x1.9a54999e786d2p0
+tan,0x1.f2f05cfb657f5p4,-0x1.9a54999e786d2p0
+tan,-0x1.4bb6a64e062a7p3,0x1.aabe6252e3a4bp0
+tan,0x1.4bb6a64e062a7p3,-0x1.aabe6252e3a4bp0
+tan,-0x1.8bdcd54bd59b7p2,0x1.bb282b074edc4p0
+tan,0x1.8bdcd54bd59b7p2,-0x1.bb282b074edc4p0
+tan,-0x1.1866fe845e776p2,0x1.cb91f3bbba13dp0
+tan,0x1.1866fe845e776p2,-0x1.cb91f3bbba13dp0
+tan,-0x1.af4643e93721bp1,0x1.dbfbbc70254b6p0
+tan,0x1.af4643e93721bp1,-0x1.dbfbbc70254b6p0
+tan,-0x1.5bd13dda077e4p1,0x1.ec6585249082fp0
+tan,0x1.5bd13dda077e4p1,-0x1.ec6585249082fp0
+tan,-0x1.21277b97c0148p1,0x1.fccf4dd8fbba8p0
+tan,0x1.21277b97c0148p1,-0x1.fccf4dd8fbba8p0
+tan,-0x1.eab43e0e5e891p0,0x1.069c8b46b3791p1
+tan,0x1.eab43e0e5e891p0,-0x1.069c8b46b3791p1
+tan,-0x1.a64c7c9d65353p0,0x1.0ed16fa0e914ep1
+tan,0x1.a64c7c9d65353p0,-0x1.0ed16fa0e914ep1
+tan,-0x1.6efec8c1e4945p0,0x1.170653fb1eb0bp1
+tan,0x1.6efec8c1e4945p0,-0x1.170653fb1eb0bp1
+tan,-0x1.41038b70be1p0,0x1.1f3b3855544c8p1
+tan,0x1.41038b70be1p0,-0x1.1f3b3855544c8p1
+tan,-0x1.19e26b5ecd5c3p0,0x1.27701caf89e85p1
+tan,0x1.19e26b5ecd5c3p0,-0x1.27701caf89e85p1
+tan,-0x1.efd82742d778cp-1,0x1.2fa50109bf842p1
+tan,0x1.efd82742d778cp-1,-0x1.2fa50109bf842p1
+tan,-0x1.b3df386f18225p-1,0x1.37d9e563f51ffp1
+tan,0x1.b3df386f18225p-1,-0x1.37d9e563f51ffp1
+tan,-0x1.7e1d936f4d60fp-1,0x1.400ec9be2abbcp1
+tan,0x1.7e1d936f4d60fp-1,-0x1.400ec9be2abbcp1
+tan,-0x1.4d466accad486p-1,0x1.4843ae1860579p1
+tan,0x1.4d466accad486p-1,-0x1.4843ae1860579p1
+tan,-0x1.205a6009d5e34p-1,0x1.5078927295f36p1
+tan,0x1.205a6009d5e34p-1,-0x1.5078927295f36p1
+tan,-0x1.ed21e59972aefp-2,0x1.58ad76cccb8f3p1
+tan,0x1.ed21e59972aefp-2,-0x1.58ad76cccb8f3p1
+tan,-0x1.9e9257e6b6285p-2,0x1.60e25b27012bp1
+tan,0x1.9e9257e6b6285p-2,-0x1.60e25b27012bp1
+tan,-0x1.53fdcdfd37ee5p-2,0x1.69173f8136c6dp1
+tan,0x1.53fdcdfd37ee5p-2,-0x1.69173f8136c6dp1
+tan,-0x1.0c864083d1e5bp-2,0x1.714c23db6c62ap1
+tan,0x1.0c864083d1e5bp-2,-0x1.714c23db6c62ap1
+tan,-0x1.8ed9142fc913fp-3,0x1.79810835a1fe7p1
+tan,0x1.8ed9142fc913fp-3,-0x1.79810835a1fe7p1
+tan,-0x1.080f73b0704cfp-3,0x1.81b5ec8fd79a4p1
+tan,0x1.080f73b0704cfp-3,-0x1.81b5ec8fd79a4p1
+tan,-0x1.06f8d014bf09bp-4,0x1.89ead0ea0d35bp1
+tan,0x1.06f8d014bf09bp-4,-0x1.89ead0ea0d35bp1
+tan,0x1.0c864083d1e7fp-2,-0x1.81b5ec8fd799fp2
+tan,-0x1.0c864083d1e7fp-2,0x1.81b5ec8fd799fp2
+tan,0x1.205a6009d5e3fp-1,-0x1.714c23db6c626p2
+tan,-0x1.205a6009d5e3fp-1,0x1.714c23db6c626p2
+tan,0x1.efd82742d778ep-1,-0x1.60e25b27012adp2
+tan,-0x1.efd82742d778ep-1,0x1.60e25b27012adp2
+tan,0x1.a64c7c9d65347p0,-0x1.5078927295f34p2
+tan,-0x1.a64c7c9d65347p0,0x1.5078927295f34p2
+tan,0x1.af4643e9371f9p1,-0x1.400ec9be2abbbp2
+tan,-0x1.af4643e9371f9p1,0x1.400ec9be2abbbp2
+tan,0x1.f2f05cfb656aap4,-0x1.2fa50109bf842p2
+tan,-0x1.f2f05cfb656aap4,0x1.2fa50109bf842p2
+tan,-0x1.1866fe845e775p2,-0x1.1f3b3855544c9p2
+tan,0x1.1866fe845e775p2,0x1.1f3b3855544c9p2
+tan,-0x1.eab43e0e5e896p0,-0x1.0ed16fa0e915p2
+tan,0x1.eab43e0e5e896p0,0x1.0ed16fa0e915p2
+tan,-0x1.19e26b5ecd5cdp0,-0x1.fccf4dd8fbbaep1
+tan,0x1.19e26b5ecd5cdp0,0x1.fccf4dd8fbbaep1
+tan,-0x1.4d466accad49fp-1,-0x1.dbfbbc70254bcp1
+tan,0x1.4d466accad49fp-1,0x1.dbfbbc70254bcp1
+tan,-0x1.53fdcdfd37f1fp-2,-0x1.bb282b074edcap1
+tan,0x1.53fdcdfd37f1fp-2,0x1.bb282b074edcap1
+tan,-0x1.06f8d014bf0e9p-4,-0x1.9a54999e786d8p1
+tan,0x1.06f8d014bf0e9p-4,0x1.9a54999e786d8p1
+tan,0x1.8ed9142fc915p-3,-0x1.79810835a1fe6p1
+tan,-0x1.8ed9142fc915p-3,0x1.79810835a1fe6p1
+tan,0x1.ed21e59972ae6p-2,-0x1.58ad76cccb8f4p1
+tan,-0x1.ed21e59972ae6p-2,0x1.58ad76cccb8f4p1
+tan,0x1.b3df386f1821p-1,-0x1.37d9e563f5202p1
+tan,-0x1.b3df386f1821p-1,0x1.37d9e563f5202p1
+tan,0x1.6efec8c1e4926p0,-0x1.170653fb1eb1p1
+tan,-0x1.6efec8c1e4926p0,0x1.170653fb1eb1p1
+tan,0x1.5bd13dda077aep1,-0x1.ec6585249083cp0
+tan,-0x1.5bd13dda077aep1,0x1.ec6585249083cp0
+tan,0x1.4bb6a64e061f7p3,-0x1.aabe6252e3a58p0
+tan,-0x1.4bb6a64e061f7p3,0x1.aabe6252e3a58p0
+tan,-0x1.8bdcd54bd5ap2,-0x1.69173f8136c74p0
+tan,0x1.8bdcd54bd5ap2,0x1.69173f8136c74p0
+tan,-0x1.21277b97c015fp1,-0x1.27701caf89e9p0
+tan,0x1.21277b97c015fp1,0x1.27701caf89e9p0
+tan,-0x1.41038b70be11bp0,-0x1.cb91f3bbba157p-1
+tan,0x1.41038b70be11bp0,0x1.cb91f3bbba157p-1
+tan,-0x1.7e1d936f4d63cp-1,-0x1.4843ae186058ep-1
+tan,0x1.7e1d936f4d63cp-1,0x1.4843ae186058ep-1
+tan,-0x1.9e9257e6b62d9p-2,-0x1.89ead0ea0d38ap-2
+tan,0x1.9e9257e6b62d9p-2,0x1.89ead0ea0d38ap-2
+tan,-0x1.080f73b07057ep-3,-0x1.069c8b46b37fp-3
+tan,0x1.080f73b07057ep-3,0x1.069c8b46b37fp-3
+tan,0x1.080f73b0704bfp-3,0x1.069c8b46b3734p-3
+tan,-0x1.080f73b0704bfp-3,-0x1.069c8b46b3734p-3
+tan,0x1.9e9257e6b626bp-2,0x1.89ead0ea0d32cp-2
+tan,-0x1.9e9257e6b626bp-2,-0x1.89ead0ea0d32cp-2
+tan,0x1.7e1d936f4d5f3p-1,0x1.4843ae186055fp-1
+tan,-0x1.7e1d936f4d5f3p-1,-0x1.4843ae186055fp-1
+tan,0x1.41038b70be0dfp0,0x1.cb91f3bbba128p-1
+tan,-0x1.41038b70be0dfp0,-0x1.cb91f3bbba128p-1
+tan,0x1.21277b97c0116p1,0x1.27701caf89e78p0
+tan,-0x1.21277b97c0116p1,-0x1.27701caf89e78p0
+tan,0x1.8bdcd54bd5915p2,0x1.69173f8136c5cp0
+tan,-0x1.8bdcd54bd5915p2,-0x1.69173f8136c5cp0
+tan,-0x1.4bb6a64e0633cp3,0x1.aabe6252e3a4p0
+tan,0x1.4bb6a64e0633cp3,-0x1.aabe6252e3a4p0
+tan,-0x1.5bd13dda07812p1,0x1.ec65852490824p0
+tan,0x1.5bd13dda07812p1,-0x1.ec65852490824p0
+tan,-0x1.6efec8c1e497p0,0x1.170653fb1eb04p1
+tan,0x1.6efec8c1e497p0,-0x1.170653fb1eb04p1
+tan,-0x1.b3df386f18263p-1,0x1.37d9e563f51f6p1
+tan,0x1.b3df386f18263p-1,-0x1.37d9e563f51f6p1
+tan,-0x1.ed21e59972b5cp-2,0x1.58ad76cccb8e8p1
+tan,0x1.ed21e59972b5cp-2,-0x1.58ad76cccb8e8p1
+tan,-0x1.8ed9142fc9217p-3,0x1.79810835a1fdap1
+tan,0x1.8ed9142fc9217p-3,-0x1.79810835a1fdap1
+tan,0x1.06f8d014bef68p-4,0x1.9a54999e786ccp1
+tan,-0x1.06f8d014bef68p-4,-0x1.9a54999e786ccp1
+tan,0x1.53fdcdfd37eb4p-2,0x1.bb282b074edbep1
+tan,-0x1.53fdcdfd37eb4p-2,-0x1.bb282b074edbep1
+tan,0x1.4d466accad45ap-1,0x1.dbfbbc70254bp1
+tan,-0x1.4d466accad45ap-1,-0x1.dbfbbc70254bp1
+tan,0x1.19e26b5ecd598p0,0x1.fccf4dd8fbba2p1
+tan,-0x1.19e26b5ecd598p0,-0x1.fccf4dd8fbba2p1
+tan,0x1.eab43e0e5e825p0,0x1.0ed16fa0e914ap2
+tan,-0x1.eab43e0e5e825p0,-0x1.0ed16fa0e914ap2
+tan,0x1.1866fe845e6fcp2,0x1.1f3b3855544c3p2
+tan,-0x1.1866fe845e6fcp2,-0x1.1f3b3855544c3p2
+tan,-0x1.f2f05cfb65c5ep4,0x1.2fa50109bf83cp2
+tan,0x1.f2f05cfb65c5ep4,-0x1.2fa50109bf83cp2
+tan,-0x1.af4643e93728dp1,0x1.400ec9be2abb5p2
+tan,0x1.af4643e93728dp1,-0x1.400ec9be2abb5p2
+tan,-0x1.a64c7c9d653ap0,0x1.5078927295f2ep2
+tan,0x1.a64c7c9d653ap0,-0x1.5078927295f2ep2
+tan,-0x1.efd82742d77ebp-1,0x1.60e25b27012a7p2
+tan,0x1.efd82742d77ebp-1,-0x1.60e25b27012a7p2
+tan,-0x1.205a6009d5e7fp-1,0x1.714c23db6c62p2
+tan,0x1.205a6009d5e7fp-1,-0x1.714c23db6c62p2
+tan,-0x1.0c864083d1ee6p-2,0x1.81b5ec8fd7999p2
+tan,0x1.0c864083d1ee6p-2,-0x1.81b5ec8fd7999p2
+tan,0x1.f09b63aa81fc3p-5,0x1.effffffffffffp-5
+tan,-0x1.f09b63aa81fc3p-5,-0x1.effffffffffffp-5
+tan,0x1.f09b63aa81fc4p-5,0x1.fp-5
+tan,-0x1.f09b63aa81fc4p-5,-0x1.fp-5
+tan,0x1.f09b63aa81fc5p-5,0x1.f000000000001p-5
+tan,-0x1.f09b63aa81fc5p-5,-0x1.f000000000001p-5
+tan,0x1.fa8f21c8a33afp-4,0x1.f7fffffffffffp-4
+tan,-0x1.fa8f21c8a33afp-4,-0x1.f7fffffffffffp-4
+tan,0x1.fa8f21c8a33bp-4,0x1.f8p-4
+tan,-0x1.fa8f21c8a33bp-4,-0x1.f8p-4
+tan,0x1.fa8f21c8a33b1p-4,0x1.f800000000001p-4
+tan,-0x1.fa8f21c8a33b1p-4,-0x1.f800000000001p-4
+tan,0x1.4ef06cb4f0a87p-3,0x1.4bfffffffffffp-3
+tan,-0x1.4ef06cb4f0a87p-3,-0x1.4bfffffffffffp-3
+tan,0x1.4ef06cb4f0a88p-3,0x1.4cp-3
+tan,-0x1.4ef06cb4f0a88p-3,-0x1.4cp-3
+tan,0x1.4ef06cb4f0a89p-3,0x1.4c00000000001p-3
+tan,-0x1.4ef06cb4f0a89p-3,-0x1.4c00000000001p-3
+tan,0x1.3cc2a44e29996p-2,0x1.3333333333332p-2
+tan,-0x1.3cc2a44e29996p-2,-0x1.3333333333332p-2
+tan,0x1.3cc2a44e29998p-2,0x1.3333333333333p-2
+tan,-0x1.3cc2a44e29998p-2,-0x1.3333333333333p-2
+tan,0x1.3cc2a44e29999p-2,0x1.3333333333334p-2
+tan,-0x1.3cc2a44e29999p-2,-0x1.3333333333334p-2
+tan,0x1.9943711dc2ce8p-1,0x1.594317acc4ef8p-1
+tan,-0x1.9943711dc2ce8p-1,-0x1.594317acc4ef8p-1
+tan,0x1.9943711dc2ceap-1,0x1.594317acc4ef9p-1
+tan,-0x1.9943711dc2ceap-1,-0x1.594317acc4ef9p-1
+tan,0x1.9943711dc2cecp-1,0x1.594317acc4efap-1
+tan,-0x1.9943711dc2cecp-1,-0x1.594317acc4efap-1
+tan,0x1.fbc511df5917dp-1,0x1.8ffffffffffffp-1
+tan,-0x1.fbc511df5917dp-1,-0x1.8ffffffffffffp-1
+tan,0x1.fbc511df5917fp-1,0x1.9p-1
+tan,-0x1.fbc511df5917fp-1,-0x1.9p-1
+tan,0x1.fbc511df59181p-1,0x1.9000000000001p-1
+tan,-0x1.fbc511df59181p-1,-0x1.9000000000001p-1
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0p0,-0x0.0p0
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x1.927278a3b1161p-5,0x1.921fb54442d17p-5
+tan,-0x1.927278a3b1161p-5,-0x1.921fb54442d17p-5
+tan,0x1.927278a3b1162p-5,0x1.921fb54442d18p-5
+tan,-0x1.927278a3b1162p-5,-0x1.921fb54442d18p-5
+tan,0x1.927278a3b1163p-5,0x1.921fb54442d19p-5
+tan,-0x1.927278a3b1163p-5,-0x1.921fb54442d19p-5
+tan,0x1.936bb8c5b2da1p-4,0x1.921fb54442d17p-4
+tan,-0x1.936bb8c5b2da1p-4,-0x1.921fb54442d17p-4
+tan,0x1.936bb8c5b2da2p-4,0x1.921fb54442d18p-4
+tan,-0x1.936bb8c5b2da2p-4,-0x1.921fb54442d18p-4
+tan,0x1.936bb8c5b2da3p-4,0x1.921fb54442d19p-4
+tan,-0x1.936bb8c5b2da3p-4,-0x1.921fb54442d19p-4
+tan,0x1.975f5e0553157p-3,0x1.921fb54442d17p-3
+tan,-0x1.975f5e0553157p-3,-0x1.921fb54442d17p-3
+tan,0x1.975f5e0553158p-3,0x1.921fb54442d18p-3
+tan,-0x1.975f5e0553158p-3,-0x1.921fb54442d18p-3
+tan,0x1.975f5e0553159p-3,0x1.921fb54442d19p-3
+tan,-0x1.975f5e0553159p-3,-0x1.921fb54442d19p-3
+tan,0x1.a827999fcef31p-2,0x1.921fb54442d17p-2
+tan,-0x1.a827999fcef31p-2,-0x1.921fb54442d17p-2
+tan,0x1.a827999fcef32p-2,0x1.921fb54442d18p-2
+tan,-0x1.a827999fcef32p-2,-0x1.921fb54442d18p-2
+tan,0x1.a827999fcef33p-2,0x1.921fb54442d19p-2
+tan,-0x1.a827999fcef33p-2,-0x1.921fb54442d19p-2
+tan,0x1.ffffffffffffdp-1,0x1.921fb54442d17p-1
+tan,-0x1.ffffffffffffdp-1,-0x1.921fb54442d17p-1
+tan,0x1.fffffffffffffp-1,0x1.921fb54442d18p-1
+tan,-0x1.fffffffffffffp-1,-0x1.921fb54442d18p-1
+tan,0x1.0000000000001p0,0x1.921fb54442d19p-1
+tan,-0x1.0000000000001p0,-0x1.921fb54442d19p-1
+tan,0x1.9153d9443ed0bp51,0x1.921fb54442d17p0
+tan,-0x1.9153d9443ed0bp51,-0x1.921fb54442d17p0
+tan,0x1.d02967c31cdb5p53,0x1.921fb54442d18p0
+tan,-0x1.d02967c31cdb5p53,-0x1.921fb54442d18p0
+tan,-0x1.617a15494767ap52,0x1.921fb54442d19p0
+tan,0x1.617a15494767ap52,-0x1.921fb54442d19p0
+tan,-0x1.469898cc51702p-51,0x1.921fb54442d17p1
+tan,0x1.469898cc51702p-51,-0x1.921fb54442d17p1
+tan,-0x1.1a62633145c07p-53,0x1.921fb54442d18p1
+tan,0x1.1a62633145c07p-53,-0x1.921fb54442d18p1
+tan,0x1.72cece675d1fdp-52,0x1.921fb54442d19p1
+tan,-0x1.72cece675d1fdp-52,-0x1.921fb54442d19p1
+tan,-0x1.469898cc51702p-50,0x1.921fb54442d17p2
+tan,0x1.469898cc51702p-50,-0x1.921fb54442d17p2
+tan,-0x1.1a62633145c07p-52,0x1.921fb54442d18p2
+tan,0x1.1a62633145c07p-52,-0x1.921fb54442d18p2
+tan,0x1.72cece675d1fdp-51,0x1.921fb54442d19p2
+tan,-0x1.72cece675d1fdp-51,-0x1.921fb54442d19p2
+tan,-0x1.469898cc51702p-49,0x1.921fb54442d17p3
+tan,0x1.469898cc51702p-49,-0x1.921fb54442d17p3
+tan,-0x1.1a62633145c07p-51,0x1.921fb54442d18p3
+tan,0x1.1a62633145c07p-51,-0x1.921fb54442d18p3
+tan,0x1.72cece675d1fdp-50,0x1.921fb54442d19p3
+tan,-0x1.72cece675d1fdp-50,-0x1.921fb54442d19p3
+tan,-0x1.469898cc51702p-48,0x1.921fb54442d17p4
+tan,0x1.469898cc51702p-48,-0x1.921fb54442d17p4
+tan,-0x1.1a62633145c07p-50,0x1.921fb54442d18p4
+tan,0x1.1a62633145c07p-50,-0x1.921fb54442d18p4
+tan,0x1.72cece675d1fdp-49,0x1.921fb54442d19p4
+tan,-0x1.72cece675d1fdp-49,-0x1.921fb54442d19p4
+tan,-0x1.469898cc51702p-47,0x1.921fb54442d17p5
+tan,0x1.469898cc51702p-47,-0x1.921fb54442d17p5
+tan,-0x1.1a62633145c07p-49,0x1.921fb54442d18p5
+tan,0x1.1a62633145c07p-49,-0x1.921fb54442d18p5
+tan,0x1.72cece675d1fdp-48,0x1.921fb54442d19p5
+tan,-0x1.72cece675d1fdp-48,-0x1.921fb54442d19p5
+tan,-0x1.469898cc51702p-46,0x1.921fb54442d17p6
+tan,0x1.469898cc51702p-46,-0x1.921fb54442d17p6
+tan,-0x1.1a62633145c07p-48,0x1.921fb54442d18p6
+tan,0x1.1a62633145c07p-48,-0x1.921fb54442d18p6
+tan,0x1.72cece675d1fdp-47,0x1.921fb54442d19p6
+tan,-0x1.72cece675d1fdp-47,-0x1.921fb54442d19p6
+tan,-0x1.469898cc51702p-45,0x1.921fb54442d17p7
+tan,0x1.469898cc51702p-45,-0x1.921fb54442d17p7
+tan,-0x1.1a62633145c07p-47,0x1.921fb54442d18p7
+tan,0x1.1a62633145c07p-47,-0x1.921fb54442d18p7
+tan,0x1.72cece675d1fdp-46,0x1.921fb54442d19p7
+tan,-0x1.72cece675d1fdp-46,-0x1.921fb54442d19p7
+tan,-0x1.0000000000005p0,0x1.2d97c7f3321d1p1
+tan,0x1.0000000000005p0,-0x1.2d97c7f3321d1p1
+tan,-0x1.0000000000001p0,0x1.2d97c7f3321d2p1
+tan,0x1.0000000000001p0,-0x1.2d97c7f3321d2p1
+tan,-0x1.ffffffffffffap-1,0x1.2d97c7f3321d3p1
+tan,0x1.ffffffffffffap-1,-0x1.2d97c7f3321d3p1
+tan,0x1.ffffffffffff5p-1,0x1.f6a7a2955385dp1
+tan,-0x1.ffffffffffff5p-1,-0x1.f6a7a2955385dp1
+tan,0x1.ffffffffffffdp-1,0x1.f6a7a2955385ep1
+tan,-0x1.ffffffffffffdp-1,-0x1.f6a7a2955385ep1
+tan,0x1.0000000000003p0,0x1.f6a7a2955385fp1
+tan,-0x1.0000000000003p0,-0x1.f6a7a2955385fp1
+tan,0x1.a8410087262e4p49,0x1.2d97c7f3321d1p2
+tan,-0x1.a8410087262e4p49,-0x1.2d97c7f3321d1p2
+tan,0x1.3570efd768923p52,0x1.2d97c7f3321d2p2
+tan,-0x1.3570efd768923p52,-0x1.2d97c7f3321d2p2
+tan,-0x1.42c0d64d5de51p50,0x1.2d97c7f3321d3p2
+tan,0x1.42c0d64d5de51p50,-0x1.2d97c7f3321d3p2
+tan,-0x1.000000000000ap0,0x1.5fdbbe9bba774p2
+tan,0x1.000000000000ap0,-0x1.5fdbbe9bba774p2
+tan,-0x1.0000000000002p0,0x1.5fdbbe9bba775p2
+tan,0x1.0000000000002p0,-0x1.5fdbbe9bba775p2
+tan,-0x1.ffffffffffff4p-1,0x1.5fdbbe9bba776p2
+tan,0x1.ffffffffffff4p-1,-0x1.5fdbbe9bba776p2
+tan,0x1.fffffffffffebp-1,0x1.c463abeccb2bap2
+tan,-0x1.fffffffffffebp-1,-0x1.c463abeccb2bap2
+tan,0x1.ffffffffffffbp-1,0x1.c463abeccb2bbp2
+tan,-0x1.ffffffffffffbp-1,-0x1.c463abeccb2bbp2
+tan,0x1.0000000000006p0,0x1.c463abeccb2bcp2
+tan,-0x1.0000000000006p0,-0x1.c463abeccb2bcp2
+tan,0x1.7cc080f895856p49,0x1.f6a7a2955385dp2
+tan,-0x1.7cc080f895856p49,-0x1.f6a7a2955385dp2
+tan,0x1.735453027d7c4p51,0x1.f6a7a2955385ep2
+tan,-0x1.735453027d7c4p51,-0x1.f6a7a2955385ep2
+tan,-0x1.86aa4a3a127a4p50,0x1.f6a7a2955385fp2
+tan,0x1.86aa4a3a127a4p50,-0x1.f6a7a2955385fp2
+tan,-0x1.000000000001bp0,0x1.1475cc9eedeffp3
+tan,0x1.000000000001bp0,-0x1.1475cc9eedeffp3
+tan,-0x1.000000000000bp0,0x1.1475cc9eedfp3
+tan,0x1.000000000000bp0,-0x1.1475cc9eedfp3
+tan,-0x1.ffffffffffff6p-1,0x1.1475cc9eedf01p3
+tan,0x1.ffffffffffff6p-1,-0x1.1475cc9eedf01p3
+tan,-0x1.34f272993d141p-49,0x1.2d97c7f3321d1p3
+tan,0x1.34f272993d141p-49,-0x1.2d97c7f3321d1p3
+tan,-0x1.a79394c9e8a0ap-52,0x1.2d97c7f3321d2p3
+tan,0x1.a79394c9e8a0ap-52,-0x1.2d97c7f3321d2p3
+tan,0x1.961b1acd85d7dp-50,0x1.2d97c7f3321d3p3
+tan,-0x1.961b1acd85d7dp-50,-0x1.2d97c7f3321d3p3
+tan,0x1.fffffffffffc9p-1,0x1.46b9c347764a2p3
+tan,-0x1.fffffffffffc9p-1,-0x1.46b9c347764a2p3
+tan,0x1.fffffffffffe9p-1,0x1.46b9c347764a3p3
+tan,-0x1.fffffffffffe9p-1,-0x1.46b9c347764a3p3
+tan,0x1.0000000000004p0,0x1.46b9c347764a4p3
+tan,-0x1.0000000000004p0,-0x1.46b9c347764a4p3
+tan,0x1.9c78eea78baa7p48,0x1.5fdbbe9bba774p3
+tan,-0x1.9c78eea78baa7p48,-0x1.5fdbbe9bba774p3
+tan,0x1.093c3b4aebeb1p51,0x1.5fdbbe9bba775p3
+tan,-0x1.093c3b4aebeb1p51,-0x1.5fdbbe9bba775p3
+tan,-0x1.516ac96142185p49,0x1.5fdbbe9bba776p3
+tan,0x1.516ac96142185p49,-0x1.5fdbbe9bba776p3
+tan,-0x1.000000000001cp0,0x1.78fdb9effea45p3
+tan,0x1.000000000001cp0,-0x1.78fdb9effea45p3
+tan,-0x1.000000000000cp0,0x1.78fdb9effea46p3
+tan,0x1.000000000000cp0,-0x1.78fdb9effea46p3
+tan,-0x1.ffffffffffff8p-1,0x1.78fdb9effea47p3
+tan,0x1.ffffffffffff8p-1,-0x1.78fdb9effea47p3
+tan,0x1.fffffffffffc7p-1,0x1.ab41b09886fe8p3
+tan,-0x1.fffffffffffc7p-1,-0x1.ab41b09886fe8p3
+tan,0x1.fffffffffffe7p-1,0x1.ab41b09886fe9p3
+tan,-0x1.fffffffffffe7p-1,-0x1.ab41b09886fe9p3
+tan,0x1.0000000000003p0,0x1.ab41b09886feap3
+tan,-0x1.0000000000003p0,-0x1.ab41b09886feap3
+tan,0x1.86c4e333b3c9fp48,0x1.c463abeccb2bap3
+tan,-0x1.86c4e333b3c9fp48,-0x1.c463abeccb2bap3
+tan,0x1.9c96951f36184p50,0x1.c463abeccb2bbp3
+tan,-0x1.9c96951f36184p50,-0x1.c463abeccb2bbp3
+tan,-0x1.73244d369e0b7p49,0x1.c463abeccb2bcp3
+tan,0x1.73244d369e0b7p49,-0x1.c463abeccb2bcp3
+tan,-0x1.000000000001dp0,0x1.dd85a7410f58bp3
+tan,0x1.000000000001dp0,-0x1.dd85a7410f58bp3
+tan,-0x1.000000000000dp0,0x1.dd85a7410f58cp3
+tan,0x1.000000000000dp0,-0x1.dd85a7410f58cp3
+tan,-0x1.ffffffffffffap-1,0x1.dd85a7410f58dp3
+tan,0x1.ffffffffffffap-1,-0x1.dd85a7410f58dp3
+tan,-0x1.583ebeff65cc2p-49,0x1.f6a7a2955385dp3
+tan,0x1.583ebeff65cc2p-49,-0x1.f6a7a2955385dp3
+tan,-0x1.60fafbfd97309p-51,0x1.f6a7a2955385ep3
+tan,0x1.60fafbfd97309p-51,-0x1.f6a7a2955385ep3
+tan,0x1.4f8282013467cp-50,0x1.f6a7a2955385fp3
+tan,-0x1.4f8282013467cp-50,-0x1.f6a7a2955385fp3
+tan,0x1.fffffffffff84p-1,0x1.07e4cef4cbd96p4
+tan,-0x1.fffffffffff84p-1,-0x1.07e4cef4cbd96p4
+tan,0x1.fffffffffffc4p-1,0x1.07e4cef4cbd97p4
+tan,-0x1.fffffffffffc4p-1,-0x1.07e4cef4cbd97p4
+tan,0x1.0000000000002p0,0x1.07e4cef4cbd98p4
+tan,-0x1.0000000000002p0,-0x1.07e4cef4cbd98p4
+tan,0x1.2f0842389e5bcp47,0x1.1475cc9eedeffp4
+tan,-0x1.2f0842389e5bcp47,-0x1.1475cc9eedeffp4
+tan,0x1.733c4e8ef9c51p48,0x1.1475cc9eedfp4
+tan,-0x1.733c4e8ef9c51p48,-0x1.1475cc9eedfp4
+tan,-0x1.9c5b4c7289899p49,0x1.1475cc9eedf01p4
+tan,0x1.9c5b4c7289899p49,-0x1.1475cc9eedf01p4
+tan,-0x1.000000000002ep0,0x1.2106ca4910068p4
+tan,0x1.000000000002ep0,-0x1.2106ca4910068p4
+tan,-0x1.000000000000ep0,0x1.2106ca4910069p4
+tan,0x1.000000000000ep0,-0x1.2106ca4910069p4
+tan,-0x1.fffffffffffddp-1,0x1.2106ca491006ap4
+tan,0x1.fffffffffffddp-1,-0x1.2106ca491006ap4
+tan,-0x1.34f272993d141p-48,0x1.2d97c7f3321d1p4
+tan,0x1.34f272993d141p-48,-0x1.2d97c7f3321d1p4
+tan,-0x1.a79394c9e8a0ap-51,0x1.2d97c7f3321d2p4
+tan,0x1.a79394c9e8a0ap-51,-0x1.2d97c7f3321d2p4
+tan,0x1.961b1acd85d7dp-49,0x1.2d97c7f3321d3p4
+tan,-0x1.961b1acd85d7dp-49,-0x1.2d97c7f3321d3p4
+tan,0x1.fffffffffff82p-1,0x1.3a28c59d54339p4
+tan,-0x1.fffffffffff82p-1,-0x1.3a28c59d54339p4
+tan,0x1.fffffffffffc2p-1,0x1.3a28c59d5433ap4
+tan,-0x1.fffffffffffc2p-1,-0x1.3a28c59d5433ap4
+tan,0x1.0000000000001p0,0x1.3a28c59d5433bp4
+tan,-0x1.0000000000001p0,-0x1.3a28c59d5433bp4
+tan,0x1.28f934315e5ecp47,0x1.46b9c347764a2p4
+tan,-0x1.28f934315e5ecp47,-0x1.46b9c347764a2p4
+tan,0x1.618fdb7f21c14p48,0x1.46b9c347764a3p4
+tan,-0x1.618fdb7f21c14p48,-0x1.46b9c347764a3p4
+tan,-0x1.cfde61218ab9ep49,0x1.46b9c347764a4p4
+tan,0x1.cfde61218ab9ep49,-0x1.46b9c347764a4p4
+tan,-0x1.000000000002fp0,0x1.534ac0f19860bp4
+tan,0x1.000000000002fp0,-0x1.534ac0f19860bp4
+tan,-0x1.000000000000fp0,0x1.534ac0f19860cp4
+tan,0x1.000000000000fp0,-0x1.534ac0f19860cp4
+tan,-0x1.fffffffffffdfp-1,0x1.534ac0f19860dp4
+tan,0x1.fffffffffffdfp-1,-0x1.534ac0f19860dp4
+tan,-0x1.3dc585b2c7422p-48,0x1.5fdbbe9bba774p4
+tan,0x1.3dc585b2c7422p-48,-0x1.5fdbbe9bba774p4
+tan,-0x1.ee2c2d963a10cp-51,0x1.5fdbbe9bba775p4
+tan,0x1.ee2c2d963a10cp-51,-0x1.5fdbbe9bba775p4
+tan,0x1.8474f49a717bdp-49,0x1.5fdbbe9bba776p4
+tan,-0x1.8474f49a717bdp-49,-0x1.5fdbbe9bba776p4
+tan,0x1.fffffffffff8p-1,0x1.6c6cbc45dc8dcp4
+tan,-0x1.fffffffffff8p-1,-0x1.6c6cbc45dc8dcp4
+tan,0x1.fffffffffffcp-1,0x1.6c6cbc45dc8ddp4
+tan,-0x1.fffffffffffcp-1,-0x1.6c6cbc45dc8ddp4
+tan,0x1.0p0,0x1.6c6cbc45dc8dep4
+tan,-0x1.0p0,-0x1.6c6cbc45dc8dep4
+tan,0x1.2326f4e8f2bb2p47,0x1.78fdb9effea45p4
+tan,-0x1.2326f4e8f2bb2p47,-0x1.78fdb9effea45p4
+tan,0x1.517ea08708ba7p48,0x1.78fdb9effea46p4
+tan,-0x1.517ea08708ba7p48,-0x1.78fdb9effea46p4
+tan,-0x1.090b3d5161786p50,0x1.78fdb9effea47p4
+tan,0x1.090b3d5161786p50,-0x1.78fdb9effea47p4
+tan,-0x1.0000000000031p0,0x1.858eb79a20baep4
+tan,0x1.0000000000031p0,-0x1.858eb79a20baep4
+tan,-0x1.0000000000011p0,0x1.858eb79a20bafp4
+tan,0x1.0000000000011p0,-0x1.858eb79a20bafp4
+tan,-0x1.fffffffffffe1p-1,0x1.858eb79a20bbp4
+tan,0x1.fffffffffffe1p-1,-0x1.858eb79a20bbp4
+tan,-0x1.af0792001f856p2,0x1.fffffffffffffp62
+tan,0x1.af0792001f856p2,-0x1.fffffffffffffp62
+tan,0x1.52f50e757941dp6,0x1.0p63
+tan,-0x1.52f50e757941dp6,-0x1.0p63
+tan,0x1.7570667d032edp1,0x1.0000000000001p63
+tan,-0x1.7570667d032edp1,-0x1.0000000000001p63
+tan,-0x1.2e8fc248e7b85p0,0x1.fffffffffffffp26
+tan,0x1.2e8fc248e7b85p0,-0x1.fffffffffffffp26
+tan,-0x1.2e8fc1af81d8cp0,0x1.0p27
+tan,0x1.2e8fc1af81d8cp0,-0x1.0p27
+tan,-0x1.2e8fc07cb61a9p0,0x1.0000000000001p27
+tan,0x1.2e8fc07cb61a9p0,-0x1.0000000000001p27
+tan,-0x1.3ea282860e7fcp0,0x1.fffffffffffffp23
+tan,0x1.3ea282860e7fcp0,-0x1.fffffffffffffp23
+tan,-0x1.3ea28271a9beap0,0x1.0p24
+tan,0x1.3ea28271a9beap0,-0x1.0p24
+tan,-0x1.3ea28248e03c7p0,0x1.0000000000001p24
+tan,0x1.3ea28248e03c7p0,-0x1.0000000000001p24
+tan,0x1.2866f9be4de0fp0,0x1.fffffffffffffp1
+tan,-0x1.2866f9be4de0fp0,-0x1.fffffffffffffp1
+tan,0x1.2866f9be4de14p0,0x1.0p2
+tan,-0x1.2866f9be4de14p0,-0x1.0p2
+tan,0x1.2866f9be4de1dp0,0x1.0000000000001p2
+tan,-0x1.2866f9be4de1dp0,-0x1.0000000000001p2
+tan,-0x1.17af62e0950fbp1,0x1.fffffffffffffp0
+tan,0x1.17af62e0950fbp1,-0x1.fffffffffffffp0
+tan,-0x1.17af62e0950f8p1,0x1.0p1
+tan,0x1.17af62e0950f8p1,-0x1.0p1
+tan,-0x1.17af62e0950f2p1,0x1.0000000000001p1
+tan,0x1.17af62e0950f2p1,-0x1.0000000000001p1
+tan,0x1.8eb245cbee3a4p0,0x1.fffffffffffffp-1
+tan,-0x1.8eb245cbee3a4p0,-0x1.fffffffffffffp-1
+tan,0x1.8eb245cbee3a6p0,0x1.0p0
+tan,-0x1.8eb245cbee3a6p0,-0x1.0p0
+tan,0x1.8eb245cbee3a9p0,0x1.0000000000001p0
+tan,-0x1.8eb245cbee3a9p0,-0x1.0000000000001p0
+tan,0x1.17b4f5bf3474ap-1,0x1.fffffffffffffp-2
+tan,-0x1.17b4f5bf3474ap-1,-0x1.fffffffffffffp-2
+tan,0x1.17b4f5bf3474ap-1,0x1.0p-1
+tan,-0x1.17b4f5bf3474ap-1,-0x1.0p-1
+tan,0x1.17b4f5bf3474cp-1,0x1.0000000000001p-1
+tan,-0x1.17b4f5bf3474cp-1,-0x1.0000000000001p-1
+tan,0x1.05785a43c4c55p-2,0x1.fffffffffffffp-3
+tan,-0x1.05785a43c4c55p-2,-0x1.fffffffffffffp-3
+tan,0x1.05785a43c4c56p-2,0x1.0p-2
+tan,-0x1.05785a43c4c56p-2,-0x1.0p-2
+tan,0x1.05785a43c4c57p-2,0x1.0000000000001p-2
+tan,-0x1.05785a43c4c57p-2,-0x1.0000000000001p-2
+tan,0x1.01577af1511a4p-3,0x1.fffffffffffffp-4
+tan,-0x1.01577af1511a4p-3,-0x1.fffffffffffffp-4
+tan,0x1.01577af1511a5p-3,0x1.0p-3
+tan,-0x1.01577af1511a5p-3,-0x1.0p-3
+tan,0x1.01577af1511a6p-3,0x1.0000000000001p-3
+tan,-0x1.01577af1511a6p-3,-0x1.0000000000001p-3
+tan,0x1.005577854dfp-4,0x1.fffffffffffffp-5
+tan,-0x1.005577854dfp-4,-0x1.fffffffffffffp-5
+tan,0x1.005577854df01p-4,0x1.0p-4
+tan,-0x1.005577854df01p-4,-0x1.0p-4
+tan,0x1.005577854df02p-4,0x1.0000000000001p-4
+tan,-0x1.005577854df02p-4,-0x1.0000000000001p-4
+tan,0x1.00155777aec08p-5,0x1.fffffffffffffp-6
+tan,-0x1.00155777aec08p-5,-0x1.fffffffffffffp-6
+tan,0x1.00155777aec08p-5,0x1.0p-5
+tan,-0x1.00155777aec08p-5,-0x1.0p-5
+tan,0x1.00155777aec09p-5,0x1.0000000000001p-5
+tan,-0x1.00155777aec09p-5,-0x1.0000000000001p-5
+tan,0x1.0005557778548p-6,0x1.fffffffffffffp-7
+tan,-0x1.0005557778548p-6,-0x1.fffffffffffffp-7
+tan,0x1.0005557778549p-6,0x1.0p-6
+tan,-0x1.0005557778549p-6,-0x1.0p-6
+tan,0x1.000555777854ap-6,0x1.0000000000001p-6
+tan,-0x1.000555777854ap-6,-0x1.0000000000001p-6
+tan,0x1.0000000555555p-14,0x1.fffffffffffffp-15
+tan,-0x1.0000000555555p-14,-0x1.fffffffffffffp-15
+tan,0x1.0000000555555p-14,0x1.0p-14
+tan,-0x1.0000000555555p-14,-0x1.0p-14
+tan,0x1.0000000555556p-14,0x1.0000000000001p-14
+tan,-0x1.0000000555556p-14,-0x1.0000000000001p-14
+tan,0x1.fffffffffffffp-28,0x1.fffffffffffffp-28
+tan,-0x1.fffffffffffffp-28,-0x1.fffffffffffffp-28
+tan,0x1.0p-27,0x1.0p-27
+tan,-0x1.0p-27,-0x1.0p-27
+tan,0x1.0000000000001p-27,0x1.0000000000001p-27
+tan,-0x1.0000000000001p-27,-0x1.0000000000001p-27
+tan,0x1.fffffffffffffp-31,0x1.fffffffffffffp-31
+tan,-0x1.fffffffffffffp-31,-0x1.fffffffffffffp-31
+tan,0x1.0p-30,0x1.0p-30
+tan,-0x1.0p-30,-0x1.0p-30
+tan,0x1.0000000000001p-30,0x1.0000000000001p-30
+tan,-0x1.0000000000001p-30,-0x1.0000000000001p-30
+tan,0x1.4530cfe729484p-8,-0x1.fffffffffffffp1023
+tan,-0x1.4530cfe729484p-8,0x1.fffffffffffffp1023
+tan,-0x1.4530cfe729484p-8,0x1.fffffffffffffp1023
+tan,0x1.4530cfe729484p-8,-0x1.fffffffffffffp1023
+tan,-0x1.4530cfe729484p-8,0x1.fffffffffffffp1023
+tan,0x1.4530cfe729484p-8,-0x1.fffffffffffffp1023
+tan,0x1.3c6e9970f78b8p1,0x1.ffffffffffffep1023
+tan,-0x1.3c6e9970f78b8p1,-0x1.ffffffffffffep1023
+tan,-0x1.1a62633145c07p-53,0x1.921fb54442d18p1
+tan,0x1.1a62633145c07p-53,-0x1.921fb54442d18p1
+tan,0x1.d02967c31cdb5p53,0x1.921fb54442d18p0
+tan,-0x1.d02967c31cdb5p53,-0x1.921fb54442d18p0
+tan,0x1.8eb245cbee3a9p0,0x1.0000000000001p0
+tan,-0x1.8eb245cbee3a9p0,-0x1.0000000000001p0
+tan,0x1.8eb245cbee3a6p0,0x1.0p0
+tan,-0x1.8eb245cbee3a6p0,-0x1.0p0
+tan,0x1.8eb245cbee3a4p0,0x1.fffffffffffffp-1
+tan,-0x1.8eb245cbee3a4p0,-0x1.fffffffffffffp-1
+tan,0x1.fffffffffffffp-1,0x1.921fb54442d18p-1
+tan,-0x1.fffffffffffffp-1,-0x1.921fb54442d18p-1
+tan,0x1.0000000000001p-1022,0x1.0000000000001p-1022
+tan,-0x1.0000000000001p-1022,-0x1.0000000000001p-1022
+tan,0x1.0p-1022,0x1.0p-1022
+tan,-0x1.0p-1022,-0x1.0p-1022
+tan,0x0.fffffffffffffp-1022,0x0.fffffffffffffp-1022
+tan,-0x0.fffffffffffffp-1022,-0x0.fffffffffffffp-1022
+tan,0x0.ffffffffffffep-1022,0x0.ffffffffffffep-1022
+tan,-0x0.ffffffffffffep-1022,-0x0.ffffffffffffep-1022
+tan,0x0.0000000000002p-1022,0x0.0000000000002p-1022
+tan,-0x0.0000000000002p-1022,-0x0.0000000000002p-1022
+tan,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+tan,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+tan,0x0.0p0,0x0.0p0
+tan,-0x0.0p0,-0x0.0p0
+log,0x1.d77fd13d27fffp-11,0x1.003af6c37c1d3p0
+log,0x1.411efd297c781p-6,0x1.05112792934b3p0
+log,0x1.d4840664446fcp-6,0x1.076d1d8c75ea6p0
+log,0x1.f6e4c3ced7c72p-3,0x1.47408cb9583cep0
+log,0x1.1a0408712e00ap-2,0x1.512b3126454f3p0
+log,0x1.8b52c15ea9c24p-2,0x1.789e95b11578cp0
+log,0x1.d707029bb59d9p-2,0x1.958497f7b353fp0
+log,0x1.0727af5fee8f6p-1,0x1.ac032a8d2ec23p0
+log,0x1.12fcce02efb32p-1,0x1.b604e1942098dp0
+log,0x1.178e6d3ecaceap-1,0x1.b9f1fa4587967p0
+log,0x1.62f71c4656b61p-1,0x1.000976581ce4ep1
+log,0x1.d6336a88077aap0,0x1.91a8dff540ff7p2
+log,0x1.016e82ceda359p1,0x1.de37fb31fd5fcp2
+log,0x1.1e126f5d95f38p1,0x1.2b1199e497739p3
+log,0x1.2f3832cad3d5fp1,0x1.55f0eaa1b2fc8p3
+log,0x1.42ee3c7dc4946p1,0x1.8ede492d96072p3
+log,0x1.6b5df7e3cd422p1,0x1.11867637cbd03p4
+log,0x1.7e7f095703eeep1,0x1.3d9d7d597a9ddp4
+log,0x1.9687c83faf006p1,0x1.7f3825778aaafp4
+log,0x1.83d4bcdebb3f4p2,0x1.ac50b409c8aeep8
+log,0x1.fffffffffffffp-53,0x1.0000000000001p0
+log,0x1.76e7e5d7b6eacp3,0x1.de7cd6751029ap16
+log,0x1.fffffffffffffp-53,0x1.0000000000001p0
+log,-0x1.91550c357f884p8,0x1.0000000000003p-579
+log,0x1.7fffffffffffcp-50,0x1.0000000000006p0
+log,0x1.bffffffffffe8p-48,0x1.000000000001cp0
+log,0x1.7fdfffffff701p-41,0x1.0000000000bffp0
+log,0x1.0fffffffedfp-35,0x1.0000000022p0
+log,0x1.ffffffffp-33,0x1.00000001p0
+log,0x1.7fffff7000004p-25,0x1.000000cp0
+log,0x1.0a2ea3e77af06p1,0x1.0007p3
+log,0x1.90412094d368p-13,0x1.000c82573f5f9p0
+log,0x1.ffe002aa6ab11p-12,0x1.002p0
+log,0x1.bfcf07242969dp-11,0x1.0038p0
+log,0x1.d77fd13d27fffp-11,0x1.003af6c37c1d3p0
+log,0x1.ea054ce8508e5p-10,0x1.007a9ea7a9e8p0
+log,0x1.ff004a7ab9084p-10,0x1.007fdff7fdfep0
+log,0x1.ffda65d44dccdp-10,0x1.0080169a16cd5p0
+log,0x1.b956989d2589dp-9,0x1.00dd0a8317176p0
+log,0x1.fd0816d97152cp-9,0x1.00ff02ba8a543p0
+log,-0x1.37915555785bp9,0x1.00fffffffffffp-899
+log,0x1.64a2a9b6a4058p0,0x1.01c00000000dcp2
+log,0x1.d465957106bd3p-8,0x1.01d6131d09dc5p0
+log,0x1.fdf639bea5ad3p-8,0x1.01fff37a34084p0
+log,0x1.fdf6e4fcf4569p-8,0x1.01fff426c8cb6p0
+log,0x1.fdf6e4fd0426fp-8,0x1.01fff426c8db5p0
+log,0x1.fdfe9c57debe1p-8,0x1.01fffbed922e3p0
+log,-0x1.d17be245122ap3,0x1.028p-21
+log,0x1.6dcb2fed7f25dp-7,0x1.02dfafa07df6dp0
+log,0x1.ff092a85ee03p-7,0x1.040615461f6cap0
+log,0x1.0aa53cea3f1acp-6,0x1.04334eec5a65dp0
+log,0x1.6ea07021c1335p-6,0x1.05cb09bb9fed7p0
+log,0x1.7199f984f5608p-6,0x1.05d735184261cp0
+log,0x1.7788bc9c08318p-6,0x1.05ef7bdee7bep0
+log,0x1.c2688e952a724p-6,0x1.0722a05711778p0
+log,0x1.e02151352512fp-6,0x1.079cf00fe24f9p0
+log,-0x1.3e1fee699c6bcp8,0x1.07cp-459
+log,0x1.f31b56b8b6f1ap-6,0x1.07eb259ee01b5p0
+log,-0x1.d0819095fcd6cp3,0x1.0a8551f8fc7f8p-21
+log,-0x1.0268d40000c72p1,0x1.0fff8p-3
+log,0x1.6b5df7e3cd422p1,0x1.11867637cbd03p4
+log,0x1.6b96cb66f55c2p1,0x1.11ffffffffff8p4
+log,-0x1.f7a213a7cd381p0,0x1.1e6p-3
+log,-0x1.a0765853dec07p8,0x1.206658d9b0f05p-601
+log,0x1.0d7b6ff6e3a24p6,0x1.2514738e6dcadp97
+log,0x1.1ee3899f6818ep1,0x1.2cfbb9e4a1599p3
+log,-0x1.331533367928ap6,0x1.2f0617037e59p-111
+log,-0x1.04c1e6cec9638p3,0x1.2f29fd4b42515p-12
+log,-0x1.0578bc4a143d6p-1,0x1.333e1f03af55ep-1
+log,-0x1.fd2a1d4dcf23ep-2,0x1.3767a0aaf1452p-1
+log,-0x1.fb0ce0ec79bcap-2,0x1.380c640e6246cp-1
+log,-0x1.ee693caa501aap-2,0x1.3bec837d601c1p-1
+log,-0x1.ed67b9b0f2f8ep-2,0x1.3c3cp-1
+log,0x1.25397dc9f85bep1,0x1.3c419b9db662ap3
+log,0x1.9c041f7ed8d33p0,0x1.3ffffffffffffp2
+log,0x1.c8ff7c79a9a22p-3,0x1.4p0
+log,0x1.d42adfec35d14p-3,0x1.41cp0
+log,0x1.d7577477b9eaep-3,0x1.423fc24d04fc6p0
+log,-0x1.d360e90c3850cp-2,0x1.446p-1
+log,-0x1.cdeabe01a86b2p-2,0x1.461c159a76d4bp-1
+log,0x1.fb9186d5e3e24p-3,0x1.47fffffffffffp0
+log,0x1.fb9186d5e3e2ap-3,0x1.48p0
+log,0x1.fb920464f5fc8p-3,0x1.4800141bea83fp0
+log,0x1.fb9c2792045eap-3,0x1.4801b3bf42a4ap0
+log,0x1.fc46718a2dc22p-3,0x1.481cfade8a64dp0
+log,0x1.ff9bd7855aaebp-3,0x1.48a5d0c7ac5b5p0
+log,0x1.ffd65f29bfd4ep-3,0x1.48af356081ca1p0
+log,0x1.e737cb23865c6p-1,0x1.4b8p1
+log,0x1.90ed52d1a23c5p8,0x1.556ee611fa309p578
+log,-0x1.b25b8d863b3b4p3,0x1.55ep-20
+log,0x1.16758a93d29bp6,0x1.5996659966598p100
+log,-0x1.7e3a93bf3540dp-2,0x1.608054de74582p-1
+log,0x1.583a417be2216p-2,0x1.6649bb515354fp0
+log,-0x1.4f7dac3f1d7f4p5,0x1.69b109377f7p-61
+log,0x1.62e42fefa3837p-2,0x1.6a09e667f3b31p0
+log,-0x1.e7a2dd016daa8p1,0x1.6bp-6
+log,0x1.739d7f6bbd006p-2,0x1.7p0
+log,-0x1.4c3af47972063p-2,0x1.7223cef78e25dp-1
+log,-0x1.48e65fe2c2305p-2,0x1.73587ce75368p-1
+log,-0x1.4057b02bfdd0ap-2,0x1.76764087395fcp-1
+log,0x1.4a5f12ed407a4p8,0x1.8ad934b838bdap476
+log,-0x1.83d0f90690d1p1,0x1.8bep-5
+log,-0x1.e387545735931p-1,0x1.8e4p-2
+log,-0x1.fcc59e0136976p-3,0x1.8f6p-1
+log,-0x1.edd6149b33156p-3,0x1.924c57d629082p-1
+log,0x1.cfbe6164a73f2p-2,0x1.92a4cb798664bp0
+log,-0x1.b428216a5c158p4,0x1.98p-40
+log,-0x1.d081f0f25d664p-3,0x1.9819d0255be6p-1
+log,-0x1.cc0d6a92b7916p-1,0x1.a0ef883be2177p-2
+log,-0x1.8f62e2cb65864p-3,0x1.a549336310e6fp-1
+log,-0x1.3651d0de2368ep-3,0x1.b80300c030118p-1
+log,0x1.20f25e686e7fap-1,0x1.c22024dc8289cp0
+log,-0x1.9e327eb6ac2c4p-1,0x1.c8p-2
+log,-0x1.b76f3d0aaf0cap-4,0x1.cbea22c8a9a16p-1
+log,-0x1.9335e5d594992p-4,0x1.cffffffffffffp-1
+log,0x1.b6cc2b05c90a8p2,0x1.dae1894a2dbedp9
+log,-0x1.fc702b8d96d0ep-5,0x1.e1304c1304c13p-1
+log,-0x1.f6c7f7d0b0356p-5,0x1.e185646bc7856p-1
+log,-0x1.eb8dcb764e07ep-5,0x1.e22e7349f6e97p-1
+log,-0x1.d94a9c323e77cp-5,0x1.e341f0592c2abp-1
+log,-0x1.ccb106085394fp-5,0x1.e4005dfd66c32p-1
+log,-0x1.a9bd8afc6d84cp-5,0x1.e61222241ca7fp-1
+log,-0x1.787392a45888ep-5,0x1.e901133e161e4p-1
+log,-0x1.79a634cdfb256p4,0x1.eddc0821c76c1p-35
+log,0x1.5172153d5fe9cp-1,0x1.eed9208a6a349p0
+log,-0x1.12b227244ff98p-5,0x1.ef1dbcea195cdp-1
+log,-0x1.f8a34d2505f81p-6,0x1.f0786fa48bd9cp-1
+log,0x1.06885d03c19c4p1,0x1.f1a945a457d96p2
+log,0x1.a28cccb9c6f0dp6,0x1.f1fffffffffffp150
+log,-0x1.b032da095671ep-6,0x1.f2ab9dee841b5p-1
+log,-0x1.9d66ada690565p-6,0x1.f33e2a944ac96p-1
+log,-0x1.88e7a6bf1b5bap-6,0x1.f3de268394e8dp-1
+log,-0x1.84e362ad21702p-6,0x1.f3fd86b392884p-1
+log,-0x1.744eff6d77ddep-6,0x1.f47f1e1f53f24p-1
+log,-0x1.68b4f86497a0ap0,0x1.f48p-3
+log,-0x1.6f51e68fcd7cep-6,0x1.f4a622df760c9p-1
+log,-0x1.6bab4f93a372p-6,0x1.f4c2b2a5a5c1dp-1
+log,-0x1.65ae4deeda7b8p-6,0x1.f4f18fab5c3b8p-1
+log,-0x1.4c2a64cb22442p-6,0x1.f5b96e5b96eb7p-1
+log,-0x1.43ae6c44b9f76p-6,0x1.f5fbf5cedc48p-1
+log,-0x1.41f7812310c9bp-6,0x1.f60968a5952d9p-1
+log,-0x1.3b0cb0b1469dcp-6,0x1.f63fae6bae321p-1
+log,-0x1.311e67575b4f5p-6,0x1.f68da368da368p-1
+log,-0x1.020da703f2f9dp-6,0x1.f7ffbefc5d9d8p-1
+log,-0x1.0205658935b94p-6,0x1.f7fffffffffe6p-1
+log,-0x1.ae825fe2eb67p-7,0x1.f95139c561139p-1
+log,-0x1.23851c80dddf2p-7,0x1.fb77177fb5d35p-1
+log,-0x1.7c498eb87ed68p-8,0x1.fd09a0b5b17fp-1
+log,-0x1.50dd41aeb4865p-8,0x1.fd6p-1
+log,-0x1.08b8bba5db3a8p-8,0x1.fdef9fe7f9fe3p-1
+log,-0x1.07c989add9f58p-8,0x1.fdf17c5f17cp-1
+log,-0x1.008055958e10bp-8,0x1.fdfffffffff55p-1
+log,-0x1.1f3e47178f97cp-9,0x1.fee1123d05c1bp-1
+log,-0x1.ff7faa9ab1367p-10,0x1.ff007ffffffffp-1
+log,-0x1.ff39ecbe26759p-10,0x1.ff00a2cd88b55p-1
+log,-0x1.6363477698d25p0,0x1.ff020ffffffffp-3
+log,-0x1.f7a248bf22faap-10,0x1.ff046cbe6cbddp-1
+log,-0x1.dae60fee9fa9fp-10,0x1.ff12c3ff12c3p-1
+log,-0x1.d208bc8587776p-10,0x1.ff17309fefcd2p-1
+log,-0x1.babff263eabf8p-12,0x1.ffc8aaff534d4p-1
+log,-0x1.c00c40725b061p-13,0x1.ffe3fffffffffp-1
+log,-0x1.78bfa50041531p-13,0x1.ffe874904abdp-1
+log,-0x1.1148dff957e7cp-13,0x1.ffeeebbaeebb8p-1
+log,-0x1.4aa196aae1ef9p8,0x1.fffffbbffffffp-478
+log,0x1.8e8f43d38041p8,0x1.fffffbbffffffp574
+log,-0x1.0000040100001p-31,0x1.fffffffbfffffp-1
+log,-0x1.ff8040007fc02p-34,0x1.ffffffff003fep-1
+log,0x1.86ef5ccdfa1b1p7,0x1.ffffffffddfffp281
+log,-0x1.0008000000801p-40,0x1.fffffffffdfffp-1
+log,-0x1.0020000000201p-42,0x1.ffffffffff7ffp-1
+log,-0x1.0040000000101p-43,0x1.ffffffffffbffp-1
+log,0x1.30fc1931f09c9p7,0x1.fffffffffffeep219
+log,-0x1.0000000000001p-51,0x1.ffffffffffffcp-1
+log,-0x1.0000000000001p-52,0x1.ffffffffffffep-1
+log,-0x1.03fe55a061c76p-1,0x1.342185798f6d6p-1
+log,-0x1.62e42fefa39f1p-2,0x1.6a09e667f3bccp-1
+log,-0x1.da391c9043a0fp-3,0x1.962b5f9438d25p-1
+log,-0x1.06fbec52082bdp-3,0x1.c24cd8c07de7ep-1
+log,-0x1.1e0a8f670c50bp-5,0x1.ee6e51ecc2fd7p-1
+log,0x1.9e548e7e3dde8p-5,0x1.0d47e58c84098p0
+log,0x1.08e0bae73ac24p-3,0x1.2358a222a6944p0
+log,0x1.9e6462187c36bp-3,0x1.39695eb8c91fp0
+log,0x1.14dd6b0af939bp-2,0x1.4f7a1b4eeba9cp0
+log,0x1.56181f19d7198p-2,0x1.658ad7e50e348p0
+log,0x1.936a82fadcd86p-2,0x1.7b9b947b30bf4p0
+log,0x1.cd45b0a9f2502p-2,0x1.91ac5111534ap0
+log,0x1.02044c9b70627p-1,0x1.a7bd0da775d4cp0
+log,0x1.1c01dad59e73p-1,0x1.bdcdca3d985f8p0
+log,0x1.34bde9b821fe3p-1,0x1.d3de86d3baea4p0
+log,0x1.4c561dbbb21dap-1,0x1.e9ef4369dd75p0
+log,0x1.62e42fefa39ebp-1,0x1.ffffffffffffcp0
+log,-0x1.62e42fefa39f1p-2,0x1.6a09e667f3bccp-1
+log,-0x1.24cfce6f80d9bp-2,0x1.80aa84ce72f89p-1
+log,-0x1.d490246defa6cp-3,0x1.974b2334f2346p-1
+log,-0x1.65d558d4ce00ap-3,0x1.adebc19b71703p-1
+log,-0x1.f991c6cb3b377p-4,0x1.c48c6001f0acp-1
+log,-0x1.31b994d3a4f8p-4,0x1.db2cfe686fe7dp-1
+log,-0x1.ccb73cdddb2b4p-6,0x1.f1cd9cceef23ap-1
+log,0x1.0b94f7c196175p-6,0x1.04371d9ab72fbp0
+log,0x1.e27076e2af2d9p-5,0x1.0f876ccdf6cd9p0
+log,0x1.986d3228180bep-4,0x1.1ad7bc01366b7p0
+log,0x1.1c898c16999f3p-3,0x1.26280b3476095p0
+log,0x1.69d4592a03622p-3,0x1.31785a67b5a73p0
+log,0x1.b44f77bcc8f56p-3,0x1.3cc8a99af5451p0
+log,0x1.fc2d6cf47cf0cp-3,0x1.4818f8ce34e2fp0
+log,0x1.20cdcd192ab65p-2,0x1.536948017480dp0
+log,0x1.426174dbd515ep-2,0x1.5eb99734b41ebp0
+log,0x1.62e42fefa39e5p-2,0x1.6a09e667f3bc9p0
+log,-0x1.269621134db92p-2,0x1.8p-1
+log,-0x1.89fa465cb93c4p-3,0x1.a666666666666p-1
+log,-0x1.af8e8210a4165p-4,0x1.cccccccccccccp-1
+log,-0x1.9ece955321b91p-6,0x1.f333333333332p-1
+log,0x1.8fb063ef2c7d1p-5,0x1.0ccccccccccccp0
+log,0x1.e27076e2af2d8p-4,0x1.1ffffffffffffp0
+log,0x1.7565011e4966ep-3,0x1.3333333333332p0
+log,0x1.f18dc41e8ef17p-3,0x1.4666666666665p0
+log,0x1.334e9e47d07fp-2,0x1.5999999999998p0
+log,0x1.6aac04146152p-2,0x1.6cccccccccccbp0
+log,0x1.9f323ecbf9846p-2,0x1.7fffffffffffep0
+log,0x0.0p0,0x1.0p0
+log,0x1.8663f793c46ccp-4,0x1.199999999999ap0
+log,0x1.7565011e4967cp-3,0x1.3333333333334p0
+log,0x1.0ca937be1b9ep-2,0x1.4cccccccccccep0
+log,0x1.588c2d9133494p-2,0x1.6666666666668p0
+log,0x1.9f323ecbf9851p-2,0x1.8000000000002p0
+log,0x1.e148a1a2726d4p-2,0x1.999999999999cp0
+log,0x1.0fae81914a994p-1,0x1.b333333333336p0
+log,0x1.2cf25fad8f1c7p-1,0x1.cccccccccccdp0
+log,0x1.48a11293d786p-1,0x1.e66666666666ap0
+log,0x1.62e42fefa39efp-1,0x1.0p1
+log,0x1.1542457337d43p6,0x1.0p100
+log,0x1.15a3de711cc55p6,0x1.199999999999ap100
+log,0x1.15fcf7f3c6f8ep6,0x1.3333333333334p100
+log,0x1.164eeeaaf5efdp6,0x1.4cccccccccccep100
+log,0x1.169ad1a0c9077p6,0x1.6666666666668p100
+log,0x1.16e177b203cdbp6,0x1.8000000000002p100
+log,0x1.17238e14da46ap6,0x1.999999999999cp100
+log,0x1.1761a2765a696p6,0x1.b333333333336p100
+log,0x1.179c2a3292f26p6,0x1.cccccccccccdp100
+log,0x1.17d387985f834p6,0x1.e66666666666ap100
+log,0x1.18080dd3171b7p6,0x1.0p101
+log,0x1.1542457337d43p7,0x1.0p200
+log,0x1.157311f22a4ccp7,0x1.199999999999ap200
+log,0x1.159f9eb37f669p7,0x1.3333333333334p200
+log,0x1.15c89a0f16e2p7,0x1.4cccccccccccep200
+log,0x1.15ee8b8a006ddp7,0x1.6666666666668p200
+log,0x1.1611de929dd0fp7,0x1.8000000000002p200
+log,0x1.1632e9c4090d6p7,0x1.999999999999cp200
+log,0x1.1651f3f4c91ecp7,0x1.b333333333336p200
+log,0x1.166f37d2e5635p7,0x1.cccccccccccdp200
+log,0x1.168ae685cbabbp7,0x1.e66666666666ap200
+log,0x1.16a529a32777dp7,0x1.0p201
+log,0x1.5a92d6d005c94p9,0x1.0p1000
+log,-0x1.0000080000555p-20,0x1.ffffep-1
+log,-0x1.0000040000155p-21,0x1.fffffp-1
+log,0x0.0p0,0x1.0p0
+log,0x1.fffff800002abp-22,0x1.000008p0
+log,0x1.fffff00000aabp-21,0x1.00001p0
+log,-0x1.00000002p-30,0x1.fffffff8p-1
+log,-0x1.00000001p-31,0x1.fffffffcp-1
+log,0x0.0p0,0x1.0p0
+log,0x1.fffffffep-32,0x1.00000002p0
+log,0x1.fffffffcp-31,0x1.00000004p0
+log,-0x1.00000000008p-40,0x1.fffffffffep-1
+log,-0x1.00000000004p-41,0x1.ffffffffffp-1
+log,0x0.0p0,0x1.0p0
+log,0x1.ffffffffff8p-42,0x1.00000000008p0
+log,0x1.ffffffffffp-41,0x1.0000000001p0
+log,-0x1.0000000000002p-50,0x1.ffffffffffff8p-1
+log,-0x1.0000000000001p-51,0x1.ffffffffffffcp-1
+log,0x0.0p0,0x1.0p0
+log,0x1.ffffffffffffep-52,0x1.0000000000002p0
+log,0x1.ffffffffffffcp-51,0x1.0000000000004p0
+log,0x1.62e42fefa39efp9,0x1.fffffffffffffp1023
+log,-0x1.74385446d71c3p9,0x0.0000000000001p-1022
+log,-0x1.62e42fefa39f4p-2,0x1.6a09e667f3bcbp-1
+log,-0x1.62e42fefa39f1p-2,0x1.6a09e667f3bccp-1
+log,-0x1.62e42fefa39eep-2,0x1.6a09e667f3bcdp-1
+log,0x1.62e42fefa39ebp-2,0x1.6a09e667f3bcbp0
+log,0x1.62e42fefa39eep-2,0x1.6a09e667f3bccp0
+log,0x1.62e42fefa39fp-2,0x1.6a09e667f3bcdp0
+log,-0x1.62e42fefa39fp-1,0x1.fffffffffffffp-2
+log,-0x1.62e42fefa39efp-1,0x1.0p-1
+log,-0x1.62e42fefa39edp-1,0x1.0000000000001p-1
+log,-0x1.269621134db95p-2,0x1.7ffffffffffffp-1
+log,-0x1.269621134db92p-2,0x1.8p-1
+log,-0x1.269621134db9p-2,0x1.8000000000001p-1
+log,0x1.9f323ecbf9849p-2,0x1.7ffffffffffffp0
+log,0x1.9f323ecbf984cp-2,0x1.8p0
+log,0x1.9f323ecbf984ep-2,0x1.8000000000001p0
+log,0x1.54e3c0b10a364p-9,0x1.00aaaaaaaaaaap0
+log,0x1.54e3c0b10a563p-9,0x1.00aaaaaaaaaabp0
+log,0x1.54e3c0b10a762p-9,0x1.00aaaaaaaaaacp0
+log,0x1.62e42fefa39efp0,0x1.fffffffffffffp1
+log,0x1.62e42fefa39efp0,0x1.0p2
+log,0x1.62e42fefa39fp0,0x1.0000000000001p2
+log,0x1.62e42fefa39eep-1,0x1.fffffffffffffp0
+log,0x1.62e42fefa39efp-1,0x1.0p1
+log,0x1.62e42fefa39f1p-1,0x1.0000000000001p1
+log,-0x1.0p-53,0x1.fffffffffffffp-1
+log,0x0.0p0,0x1.0p0
+log,0x1.fffffffffffffp-53,0x1.0000000000001p0
+log,-0x1.62e42fefa39fp-1,0x1.fffffffffffffp-2
+log,-0x1.62e42fefa39efp-1,0x1.0p-1
+log,-0x1.62e42fefa39edp-1,0x1.0000000000001p-1
+log,-0x1.62e42fefa39fp0,0x1.fffffffffffffp-3
+log,-0x1.62e42fefa39efp0,0x1.0p-2
+log,-0x1.62e42fefa39eep0,0x1.0000000000001p-2
+log,-0x1.0a2b23f3bab74p1,0x1.fffffffffffffp-4
+log,-0x1.0a2b23f3bab73p1,0x1.0p-3
+log,-0x1.0a2b23f3bab73p1,0x1.0000000000001p-3
+log,-0x1.62e42fefa39efp1,0x1.fffffffffffffp-5
+log,-0x1.62e42fefa39efp1,0x1.0p-4
+log,-0x1.62e42fefa39efp1,0x1.0000000000001p-4
+log,-0x1.bb9d3beb8c86bp1,0x1.fffffffffffffp-6
+log,-0x1.bb9d3beb8c86bp1,0x1.0p-5
+log,-0x1.bb9d3beb8c86bp1,0x1.0000000000001p-5
+log,-0x1.0a2b23f3bab74p2,0x1.fffffffffffffp-7
+log,-0x1.0a2b23f3bab73p2,0x1.0p-6
+log,-0x1.0a2b23f3bab73p2,0x1.0000000000001p-6
+log,-0x1.3687a9f1af2b1p2,0x1.fffffffffffffp-8
+log,-0x1.3687a9f1af2b1p2,0x1.0p-7
+log,-0x1.3687a9f1af2b1p2,0x1.0000000000001p-7
+log,-0x1.62e42fefa39efp2,0x1.fffffffffffffp-9
+log,-0x1.62e42fefa39efp2,0x1.0p-8
+log,-0x1.62e42fefa39efp2,0x1.0000000000001p-8
+log,-0x1.8f40b5ed9812dp2,0x1.fffffffffffffp-10
+log,-0x1.8f40b5ed9812dp2,0x1.0p-9
+log,-0x1.8f40b5ed9812dp2,0x1.0000000000001p-9
+log,-0x1.bb9d3beb8c86bp2,0x1.fffffffffffffp-11
+log,-0x1.bb9d3beb8c86bp2,0x1.0p-10
+log,-0x1.bb9d3beb8c86bp2,0x1.0000000000001p-10
+log,-0x1.205966f2b4f12p3,0x1.fffffffffffffp-14
+log,-0x1.205966f2b4f12p3,0x1.0p-13
+log,-0x1.205966f2b4f12p3,0x1.0000000000001p-13
+log,-0x1.205966f2b4f12p3,0x1.fffffffffffffp-14
+log,-0x1.205966f2b4f12p3,0x1.0p-13
+log,-0x1.205966f2b4f12p3,0x1.0000000000001p-13
+log,-0x1.0a2b23f3bab74p1,0x1.fffffffffffffp-4
+log,-0x1.0a2b23f3bab73p1,0x1.0p-3
+log,-0x1.0a2b23f3bab73p1,0x1.0000000000001p-3
+log,-0x1.1178e8227e48p-3,0x1.bffffffffffffp-1
+log,-0x1.1178e8227e47cp-3,0x1.cp-1
+log,-0x1.1178e8227e477p-3,0x1.c000000000001p-1
+log,-0x1.62e42fefa39efp1,0x1.fffffffffffffp-5
+log,-0x1.62e42fefa39efp1,0x1.0p-4
+log,-0x1.62e42fefa39efp1,0x1.0000000000001p-4
+log,-0x1.08598b59e3a0fp-4,0x1.dffffffffffffp-1
+log,-0x1.08598b59e3a07p-4,0x1.ep-1
+log,-0x1.08598b59e39fep-4,0x1.e000000000001p-1
+log,-0x1.bb9d3beb8c86bp1,0x1.fffffffffffffp-6
+log,-0x1.bb9d3beb8c86bp1,0x1.0p-5
+log,-0x1.bb9d3beb8c86bp1,0x1.0000000000001p-5
+log,-0x1.0415d89e74455p-5,0x1.effffffffffffp-1
+log,-0x1.0415d89e74444p-5,0x1.fp-1
+log,-0x1.0415d89e74434p-5,0x1.f000000000001p-1
+log,-0x1.0a2b23f3bab74p2,0x1.fffffffffffffp-7
+log,-0x1.0a2b23f3bab73p2,0x1.0p-6
+log,-0x1.0a2b23f3bab73p2,0x1.0000000000001p-6
+log,-0x1.0205658935868p-6,0x1.f7fffffffffffp-1
+log,-0x1.0205658935847p-6,0x1.f8p-1
+log,-0x1.0205658935827p-6,0x1.f800000000001p-1
+log,-0x1.3687a9f1af2b1p2,0x1.fffffffffffffp-8
+log,-0x1.3687a9f1af2b1p2,0x1.0p-7
+log,-0x1.3687a9f1af2b1p2,0x1.0000000000001p-7
+log,-0x1.010157588deb2p-7,0x1.fbfffffffffffp-1
+log,-0x1.010157588de71p-7,0x1.fcp-1
+log,-0x1.010157588de31p-7,0x1.fc00000000001p-1
+log,-0x1.62e42fefa39efp2,0x1.fffffffffffffp-9
+log,-0x1.62e42fefa39efp2,0x1.0p-8
+log,-0x1.62e42fefa39efp2,0x1.0000000000001p-8
+log,-0x1.0080559588bb6p-8,0x1.fdfffffffffffp-1
+log,-0x1.0080559588b35p-8,0x1.fep-1
+log,-0x1.0080559588ab5p-8,0x1.fe00000000001p-1
+log,-0x1.8f40b5ed9812dp2,0x1.fffffffffffffp-10
+log,-0x1.8f40b5ed9812dp2,0x1.0p-9
+log,-0x1.8f40b5ed9812dp2,0x1.0000000000001p-9
+log,-0x1.0040155d5899ep-9,0x1.fefffffffffffp-1
+log,-0x1.0040155d5889ep-9,0x1.ffp-1
+log,-0x1.0040155d5879dp-9,0x1.ff00000000001p-1
+log,-0x1.bb9d3beb8c86bp2,0x1.fffffffffffffp-11
+log,-0x1.bb9d3beb8c86bp2,0x1.0p-10
+log,-0x1.bb9d3beb8c86bp2,0x1.0000000000001p-10
+log,-0x1.0020055655a8ap-10,0x1.ff7ffffffffffp-1
+log,-0x1.0020055655889p-10,0x1.ff8p-1
+log,-0x1.0020055655689p-10,0x1.ff80000000001p-1
+log,-0x1.205966f2b4f12p3,0x1.fffffffffffffp-14
+log,-0x1.205966f2b4f12p3,0x1.0p-13
+log,-0x1.205966f2b4f12p3,0x1.0000000000001p-13
+log,-0x1.0004001556d56p-13,0x1.ffeffffffffffp-1
+log,-0x1.0004001555d56p-13,0x1.fffp-1
+log,-0x1.0004001554d55p-13,0x1.fff0000000001p-1
+log,0x1.62e42fefa39efp9,0x1.fffffffffffffp1023
+log,0x1.62e42fefa39efp9,0x1.ffffffffffffep1023
+log,0x1.250d048e7a1bdp0,0x1.921fb54442d18p1
+log,0x1.ce6bb25aa1315p-2,0x1.921fb54442d18p0
+log,0x1.fffffffffffffp-53,0x1.0000000000001p0
+log,0x0.0p0,0x1.0p0
+log,-0x1.0p-53,0x1.fffffffffffffp-1
+log,-0x1.eeb95b094c193p-3,0x1.921fb54442d18p-1
+log,-0x1.6232bdd7abcd2p9,0x1.0000000000001p-1022
+log,-0x1.6232bdd7abcd2p9,0x1.0p-1022
+log,-0x1.6232bdd7abcd2p9,0x0.fffffffffffffp-1022
+log,-0x1.6232bdd7abcd2p9,0x0.ffffffffffffep-1022
+log,-0x1.73df9b3adb335p9,0x0.0000000000002p-1022
+log,-0x1.74385446d71c3p9,0x0.0000000000001p-1022
+sin,0x1.9259e3708bd3ap-5,0x1.9283586503fep-5
+sin,-0x1.9259e3708bd3ap-5,-0x1.9283586503fep-5
+sin,0x1.d77b117f230d6p-5,0x1.d7bdcd778049fp-5
+sin,-0x1.d77b117f230d6p-5,-0x1.d7bdcd778049fp-5
+sin,0x1.a1490c8c06ba7p-4,0x1.a202b3fb84788p-4
+sin,-0x1.a1490c8c06ba7p-4,-0x1.a202b3fb84788p-4
+sin,0x1.cc40c3805229ap-3,0x1.d037cb27ee6dfp-3
+sin,-0x1.cc40c3805229ap-3,-0x1.d037cb27ee6dfp-3
+sin,0x1.d0ef799001ba9p-3,0x1.d5064e6fe82c5p-3
+sin,-0x1.d0ef799001ba9p-3,-0x1.d5064e6fe82c5p-3
+sin,0x1.e9950730c4696p-2,0x1.fe767739d0f6dp-2
+sin,-0x1.e9950730c4696p-2,-0x1.fe767739d0f6dp-2
+sin,0x1.98dcd09337793p-1,0x1.d98c4c612718dp-1
+sin,-0x1.98dcd09337793p-1,-0x1.d98c4c612718dp-1
+sin,0x1.0p0,0x1.921fb54442d18p0
+sin,-0x1.0p0,-0x1.921fb54442d18p0
+sin,0x1.70a9d825b5064p-1,-0x1.0000001f8p500
+sin,-0x1.70a9d825b5064p-1,0x1.0000001f8p500
+sin,0x1.bf3980c6c1e9fp-1,-0x1.00c0bf8p700
+sin,-0x1.bf3980c6c1e9fp-1,0x1.00c0bf8p700
+sin,0x1.d62899d48b43ap-4,-0x1.13fffffffff8p6
+sin,-0x1.d62899d48b43ap-4,0x1.13fffffffff8p6
+sin,-0x1.17b7a60ce1f15p-5,-0x1.17c5920767dfcp-5
+sin,0x1.17b7a60ce1f15p-5,0x1.17c5920767dfcp-5
+sin,0x1.f0192b794fbbep-1,-0x1.1d99be08713ccp2
+sin,-0x1.f0192b794fbbep-1,0x1.1d99be08713ccp2
+sin,-0x1.5e61328c0034fp-3,-0x1.1ddbfd64fc0d3p81
+sin,0x1.5e61328c0034fp-3,0x1.1ddbfd64fc0d3p81
+sin,0x1.fb028c5df1db4p-1,-0x1.1e2a1563e068ep7
+sin,-0x1.fb028c5df1db4p-1,0x1.1e2a1563e068ep7
+sin,-0x1.2cefb196ba208p-3,-0x1.2e07a91314dp-3
+sin,0x1.2cefb196ba208p-3,0x1.2e07a91314dp-3
+sin,0x1.b80f489d3edf5p-2,-0x1.3bcec270444e2p3
+sin,-0x1.b80f489d3edf5p-2,0x1.3bcec270444e2p3
+sin,-0x1.4fffffffffa39p-20,-0x1.500000000004p-20
+sin,0x1.4fffffffffa39p-20,0x1.500000000004p-20
+sin,-0x1.d29da5b44f51cp-2,-0x1.559001a42d90cp1
+sin,0x1.d29da5b44f51cp-2,0x1.559001a42d90cp1
+sin,-0x1.f85f526147f78p-1,-0x1.597bf3e9776b7p99
+sin,0x1.f85f526147f78p-1,0x1.597bf3e9776b7p99
+sin,-0x1.6d61b58c99c43p-59,-0x1.6c6cbc45dc8dep7
+sin,0x1.6d61b58c99c43p-59,0x1.6c6cbc45dc8dep7
+sin,0x1.e5c3c08a258a8p-1,-0x1.73d8d173f90dp4
+sin,-0x1.e5c3c08a258a8p-1,0x1.73d8d173f90dp4
+sin,0x1.feb36806ca5fbp-1,-0x1.8c202d3a31802p6
+sin,-0x1.feb36806ca5fbp-1,0x1.8c202d3a31802p6
+sin,-0x1.7c6c7b01b98dap-1,-0x1.acd538b1a6d5dp-1
+sin,0x1.7c6c7b01b98dap-1,0x1.acd538b1a6d5dp-1
+sin,-0x1.191be2059dcb6p-1,-0x1.b7525ac97e0d2p2
+sin,0x1.191be2059dcb6p-1,0x1.b7525ac97e0d2p2
+sin,-0x1.f8305993a212cp-1,-0x1.bee5fa8a84b02p0
+sin,0x1.f8305993a212cp-1,0x1.bee5fa8a84b02p0
+sin,0x1.ff3b13530fd71p-1,-0x1.c393979fe5921p9
+sin,-0x1.ff3b13530fd71p-1,0x1.c393979fe5921p9
+sin,-0x1.f119da81a4da6p-1,-0x1.c48ffc72563c8p18
+sin,0x1.f119da81a4da6p-1,0x1.c48ffc72563c8p18
+sin,-0x1.fd73b81e04cccp-1,-0x1.c79548bc31856p3
+sin,0x1.fd73b81e04cccp-1,0x1.c79548bc31856p3
+sin,-0x1.c7885aef33a95p-3,-0x1.cb6p-3
+sin,0x1.c7885aef33a95p-3,0x1.cb6p-3
+sin,-0x1.e6494911eedd1p-7,-0x1.e64ddaf7bd72fp-7
+sin,0x1.e6494911eedd1p-7,0x1.e64ddaf7bd72fp-7
+sin,0x1.e180eef5b1c88p-1,-0x1.ecdd0fbf07942p5
+sin,-0x1.e180eef5b1c88p-1,0x1.ecdd0fbf07942p5
+sin,-0x1.fd98d20c1be44p-1,-0x1.f073a23292337p2
+sin,0x1.fd98d20c1be44p-1,0x1.f073a23292337p2
+sin,-0x1.7268c112297c8p-5,-0x1.f5e4c410f4ef8p15
+sin,0x1.7268c112297c8p-5,0x1.f5e4c410f4ef8p15
+sin,0x1.420796146070ep-18,-0x1.f8000000002p95
+sin,-0x1.420796146070ep-18,0x1.f8000000002p95
+sin,-0x1.e4f6dc499d9ccp-2,-0x1.f9365d79546e1p-2
+sin,0x1.e4f6dc499d9ccp-2,0x1.f9365d79546e1p-2
+sin,0x1.b2ef99b140d65p-14,-0x1.ffffffffffe7ep1023
+sin,-0x1.b2ef99b140d65p-14,0x1.ffffffffffe7ep1023
+sin,0x1.db0ffc3ecc6e4p-1,0x1.0p15
+sin,-0x1.db0ffc3ecc6e4p-1,-0x1.0p15
+sin,-0x1.e98f87098b627p-1,0x1.0000000000001p13
+sin,0x1.e98f87098b627p-1,-0x1.0000000000001p13
+sin,0x1.053c35068e10dp-4,0x1.0000000000001p52
+sin,-0x1.053c35068e10dp-4,-0x1.0000000000001p52
+sin,0x1.72d421b6884e5p-1,0x1.0000000000001p228
+sin,-0x1.72d421b6884e5p-1,-0x1.0000000000001p228
+sin,0x1.77fba987c5654p-1,0x1.0000000000001p491
+sin,-0x1.77fba987c5654p-1,-0x1.0000000000001p491
+sin,-0x1.723b2625331afp-1,0x1.0000000000003p215
+sin,0x1.723b2625331afp-1,-0x1.0000000000003p215
+sin,0x1.aed548f090cf5p-1,0x1.0000000000006p0
+sin,-0x1.aed548f090cf5p-1,-0x1.0000000000006p0
+sin,-0x1.ff983208c7dc9p-1,0x1.0000000000007p8
+sin,0x1.ff983208c7dc9p-1,-0x1.0000000000007p8
+sin,0x1.ffef29dc38453p-1,0x1.0000000000007p275
+sin,-0x1.ffef29dc38453p-1,-0x1.0000000000007p275
+sin,-0x1.fa88c375723c1p-8,0x1.0000000000007p449
+sin,0x1.fa88c375723c1p-8,-0x1.0000000000007p449
+sin,0x1.fff5322c94eaep-1,0x1.0000000000011p644
+sin,-0x1.fff5322c94eaep-1,-0x1.0000000000011p644
+sin,-0x1.a73630af8f15cp-1,0x1.000000000001fp164
+sin,0x1.a73630af8f15cp-1,-0x1.000000000001fp164
+sin,0x1.1c548f9249e44p-2,0x1.0000000000038p380
+sin,-0x1.1c548f9249e44p-2,-0x1.0000000000038p380
+sin,0x1.ca965bd2c4dffp-3,0x1.0000000000118p380
+sin,-0x1.ca965bd2c4dffp-3,-0x1.0000000000118p380
+sin,-0x1.837b9dddc24dp-1,0x1.000000000012cp2
+sin,0x1.837b9dddc24dp-1,-0x1.000000000012cp2
+sin,0x1.d82c1784c3eccp-2,0x1.00000000001f8p700
+sin,-0x1.d82c1784c3eccp-2,-0x1.00000000001f8p700
+sin,0x1.fffeaaaaef2eep-8,0x1.00000000002p-7
+sin,-0x1.fffeaaaaef2eep-8,-0x1.00000000002p-7
+sin,-0x1.0871bddd90fc6p-1,0x1.00000000002p40
+sin,0x1.0871bddd90fc6p-1,-0x1.00000000002p40
+sin,0x1.fffeaaaaef2fp-8,0x1.0000000000201p-7
+sin,-0x1.fffeaaaaef2fp-8,-0x1.0000000000201p-7
+sin,0x1.fffeaaaaef33p-8,0x1.0000000000221p-7
+sin,-0x1.fffeaaaaef33p-8,-0x1.0000000000221p-7
+sin,0x1.fffeaaaaef362p-8,0x1.000000000023ap-7
+sin,-0x1.fffeaaaaef362p-8,-0x1.000000000023ap-7
+sin,0x1.e0c6edfa93601p-9,0x1.0000000004p45
+sin,-0x1.e0c6edfa93601p-9,-0x1.0000000004p45
+sin,0x1.ea1f618356db1p-5,0x1.0000000cp40
+sin,-0x1.ea1f618356db1p-5,-0x1.0000000cp40
+sin,0x1.faaeed7587542p-3,0x1.00000013c86f4p-2
+sin,-0x1.faaeed7587542p-3,-0x1.00000013c86f4p-2
+sin,0x1.540bc7785680bp-1,0x1.001p13
+sin,-0x1.540bc7785680bp-1,-0x1.001p13
+sin,-0x1.37a7cb907a2e5p-1,0x1.003p699
+sin,0x1.37a7cb907a2e5p-1,-0x1.003p699
+sin,-0x1.29e5845fc54b5p-1,0x1.0038p40
+sin,0x1.29e5845fc54b5p-1,-0x1.0038p40
+sin,0x1.ffe5ca4656491p-1,0x1.007p10
+sin,-0x1.ffe5ca4656491p-1,-0x1.007p10
+sin,0x1.ea4df82db014bp-1,0x1.007p25
+sin,-0x1.ea4df82db014bp-1,-0x1.007p25
+sin,0x1.fe757aef1c80cp-1,0x1.007p41
+sin,-0x1.fe757aef1c80cp-1,-0x1.007p41
+sin,0x1.e9b71805ec068p-7,0x1.00cp41
+sin,-0x1.e9b71805ec068p-7,-0x1.00cp41
+sin,0x1.b0b6d0a540583p-1,0x1.01c00000001p0
+sin,-0x1.b0b6d0a540583p-1,-0x1.01c00000001p0
+sin,0x1.fef0092627012p-3,0x1.02322e46da919p-2
+sin,-0x1.fef0092627012p-3,-0x1.02322e46da919p-2
+sin,0x1.ffc90059804a1p-3,0x1.02a236478p-2
+sin,-0x1.ffc90059804a1p-3,-0x1.02a236478p-2
+sin,0x1.ffd10a6b5429fp-3,0x1.02a65d08ca5e5p-2
+sin,-0x1.ffd10a6b5429fp-3,-0x1.02a65d08ca5e5p-2
+sin,0x1.ffd10ab302a3fp-3,0x1.02a65d2dce49ap-2
+sin,-0x1.ffd10ab302a3fp-3,-0x1.02a65d2dce49ap-2
+sin,0x1.ffe0b1764ca4cp-3,0x1.02ae7238ap-2
+sin,-0x1.ffe0b1764ca4cp-3,-0x1.02ae7238ap-2
+sin,-0x1.f68f0e26c0f6bp-3,0x1.0501d22221dacp621
+sin,0x1.f68f0e26c0f6bp-3,-0x1.0501d22221dacp621
+sin,0x1.b63c41f09eb75p-1,0x1.06ffffffffff8p0
+sin,-0x1.b63c41f09eb75p-1,-0x1.06ffffffffff8p0
+sin,-0x1.ffdc173adabb2p-1,0x1.07023d3d44215p12
+sin,0x1.ffdc173adabb2p-1,-0x1.07023d3d44215p12
+sin,0x1.0889e11bef135p-5,0x1.0895a7a3e8ae6p-5
+sin,-0x1.0889e11bef135p-5,-0x1.0895a7a3e8ae6p-5
+sin,0x1.08ca077c76445p-5,0x1.08d5d69840601p-5
+sin,-0x1.08ca077c76445p-5,-0x1.08d5d69840601p-5
+sin,-0x1.ff7fbe518023fp-1,0x1.0ep6
+sin,0x1.ff7fbe518023fp-1,-0x1.0ep6
+sin,-0x1.fd6c68b877afep-1,0x1.107ba49c346e4p9
+sin,0x1.fd6c68b877afep-1,-0x1.107ba49c346e4p9
+sin,-0x1.a2ba6bc70bce4p-1,0x1.149154477444p745
+sin,0x1.a2ba6bc70bce4p-1,-0x1.149154477444p745
+sin,0x1.165609790f235p-5,0x1.1663c0e51818p-5
+sin,-0x1.165609790f235p-5,-0x1.1663c0e51818p-5
+sin,-0x1.fc0523ff94e45p-1,0x1.1745d1745d176p238
+sin,0x1.fc0523ff94e45p-1,-0x1.1745d1745d176p238
+sin,0x1.f34a729c584bdp-1,0x1.17472a408a3ep97
+sin,-0x1.f34a729c584bdp-1,-0x1.17472a408a3ep97
+sin,0x1.177fae169fdf1p-5,0x1.178d91b6b992dp-5
+sin,-0x1.177fae169fdf1p-5,-0x1.178d91b6b992dp-5
+sin,0x1.177fae16a120fp-5,0x1.178d91b6bad4ep-5
+sin,-0x1.177fae16a120fp-5,-0x1.178d91b6bad4ep-5
+sin,0x1.177fae16a1f79p-5,0x1.178d91b6bbabap-5
+sin,-0x1.177fae16a1f79p-5,-0x1.178d91b6bbabap-5
+sin,0x1.177fae16a40ffp-5,0x1.178d91b6bdc45p-5
+sin,-0x1.177fae16a40ffp-5,-0x1.178d91b6bdc45p-5
+sin,0x1.297c768f2413p-1,0x1.19752dbee5f6ap933
+sin,-0x1.297c768f2413p-1,-0x1.19752dbee5f6ap933
+sin,0x1.b826df5cafafap-2,0x1.1b3009cfe4dbcp8
+sin,-0x1.b826df5cafafap-2,-0x1.1b3009cfe4dbcp8
+sin,0x1.b7a5956250b6bp-2,0x1.1f6475d95bf18p3
+sin,-0x1.b7a5956250b6bp-2,-0x1.1f6475d95bf18p3
+sin,0x1.4db6566b64548p-1,0x1.229148a452291p118
+sin,-0x1.4db6566b64548p-1,-0x1.229148a452291p118
+sin,0x1.1686fee2c49a8p-1,0x1.268p-1
+sin,-0x1.1686fee2c49a8p-1,-0x1.268p-1
+sin,0x1.22eb21a44d627p-2,0x1.26fb3844dd19p-2
+sin,-0x1.22eb21a44d627p-2,-0x1.26fb3844dd19p-2
+sin,0x1.d4a216d89b2b3p-1,0x1.27fffffffe6bp0
+sin,-0x1.d4a216d89b2b3p-1,-0x1.27fffffffe6bp0
+sin,-0x1.76c9b0f3a22f8p-1,0x1.284b84048d481p204
+sin,0x1.76c9b0f3a22f8p-1,-0x1.284b84048d481p204
+sin,-0x1.ff01226f97d33p-1,0x1.2999e3109cad4p2
+sin,0x1.ff01226f97d33p-1,-0x1.2999e3109cad4p2
+sin,0x1.2a8f11e7ae82cp-5,0x1.2aap-5
+sin,-0x1.2a8f11e7ae82cp-5,-0x1.2aap-5
+sin,0x1.2b03d1bf773dfp-5,0x1.2b14d3be0c23p-5
+sin,-0x1.2b03d1bf773dfp-5,-0x1.2b14d3be0c23p-5
+sin,-0x1.ffb90ee641792p-1,0x1.2b7cb44849981p2
+sin,0x1.ffb90ee641792p-1,-0x1.2b7cb44849981p2
+sin,-0x1.ffffff79e71a4p-1,0x1.2becc8685258p200
+sin,0x1.ffffff79e71a4p-1,-0x1.2becc8685258p200
+sin,-0x1.fff9edaf85b77p-1,0x1.2cfa14ce27cd5p2
+sin,0x1.fff9edaf85b77p-1,-0x1.2cfa14ce27cd5p2
+sin,0x1.2cbaaa4cebb52p-4,0x1.2dp-4
+sin,-0x1.2cbaaa4cebb52p-4,-0x1.2dp-4
+sin,-0x1.ffffbc177e01p-1,0x1.2d76d18721be8p2
+sin,0x1.ffffbc177e01p-1,-0x1.2d76d18721be8p2
+sin,0x1.745843dfafefdp-18,0x1.302a494e0909p97
+sin,-0x1.745843dfafefdp-18,-0x1.302a494e0909p97
+sin,0x1.ffcc568d42376p-1,0x1.31cc731cc731cp1000
+sin,-0x1.ffcc568d42376p-1,-0x1.31cc731cc731cp1000
+sin,0x1.b676077d4faf8p-1,0x1.328463d4f8ca6p441
+sin,-0x1.b676077d4faf8p-1,-0x1.328463d4f8ca6p441
+sin,-0x1.0p0,0x1.32ce90b32171ep18
+sin,0x1.0p0,-0x1.32ce90b32171ep18
+sin,0x1.35cbd3240d149p-5,0x1.35debd7f020ecp-5
+sin,-0x1.35cbd3240d149p-5,-0x1.35debd7f020ecp-5
+sin,0x1.3bb2086559faap-7,0x1.3bb3487893405p-7
+sin,-0x1.3bb2086559faap-7,-0x1.3bb3487893405p-7
+sin,0x1.3bb2086559facp-7,0x1.3bb3487893407p-7
+sin,-0x1.3bb2086559facp-7,-0x1.3bb3487893407p-7
+sin,0x1.dff197edc51d2p-16,0x1.3bb681d65aa6p100
+sin,-0x1.dff197edc51d2p-16,-0x1.3bb681d65aa6p100
+sin,-0x1.5d08d3dbb41bp-3,0x1.3f9aa8626042fp83
+sin,0x1.5d08d3dbb41bp-3,-0x1.3f9aa8626042fp83
+sin,0x1.fb503983f94bbp-3,0x1.3fep19
+sin,-0x1.fb503983f94bbp-3,-0x1.3fep19
+sin,-0x1.d3876eacc9ee7p-1,0x1.4285478f1e3c8p58
+sin,0x1.d3876eacc9ee7p-1,-0x1.4285478f1e3c8p58
+sin,0x1.42b66d54f69c1p-5,0x1.42cbcf45a169ep-5
+sin,-0x1.42b66d54f69c1p-5,-0x1.42cbcf45a169ep-5
+sin,0x1.b45e9e9427554p-1,0x1.43fffffffff6ap557
+sin,-0x1.b45e9e9427554p-1,-0x1.43fffffffff6ap557
+sin,0x1.43ffffffea603p-17,0x1.44p-17
+sin,-0x1.43ffffffea603p-17,-0x1.44p-17
+sin,-0x1.6a4e98d2d8b1cp-1,0x1.4748c08dc0976p200
+sin,0x1.6a4e98d2d8b1cp-1,-0x1.4748c08dc0976p200
+sin,-0x1.b57ca8aacf2a9p-1,0x1.478fc08p43
+sin,0x1.b57ca8aacf2a9p-1,-0x1.478fc08p43
+sin,0x1.ffe38008ef6b5p-1,0x1.4cf36d17c596ep200
+sin,-0x1.ffe38008ef6b5p-1,-0x1.4cf36d17c596ep200
+sin,0x1.d6457a3f12e6cp-1,0x1.4f0f308p488
+sin,-0x1.d6457a3f12e6cp-1,-0x1.4f0f308p488
+sin,0x1.4fffffffff9f9p-20,0x1.5p-20
+sin,-0x1.4fffffffff9f9p-20,-0x1.5p-20
+sin,-0x1.cbad095f503a2p-1,0x1.5143e25a488f1p3
+sin,0x1.cbad095f503a2p-1,-0x1.5143e25a488f1p3
+sin,-0x1.f942d6262e82ep-5,0x1.51f0f44da4df4p200
+sin,0x1.f942d6262e82ep-5,-0x1.51f0f44da4df4p200
+sin,-0x1.fc466ccaece8p-3,0x1.52ad6c5a3602fp16
+sin,0x1.fc466ccaece8p-3,-0x1.52ad6c5a3602fp16
+sin,0x1.d69c3cf4eecdep-1,0x1.52f00ep793
+sin,-0x1.d69c3cf4eecdep-1,-0x1.52f00ep793
+sin,0x1.e120292f3d495p-1,0x1.5555555555556p239
+sin,-0x1.e120292f3d495p-1,-0x1.5555555555556p239
+sin,-0x1.fd1d85b7ef004p-1,0x1.5a0000008p6
+sin,0x1.fd1d85b7ef004p-1,-0x1.5a0000008p6
+sin,0x1.5aff9664b07e2p-6,0x1.5b063ad2dd08fp-6
+sin,-0x1.5aff9664b07e2p-6,-0x1.5b063ad2dd08fp-6
+sin,-0x1.83f8bbb59f2f8p-1,0x1.5b179d75fa285p2
+sin,0x1.83f8bbb59f2f8p-1,-0x1.5b179d75fa285p2
+sin,0x1.fa865b0d99497p-1,0x1.5bb5967402f9cp79
+sin,-0x1.fa865b0d99497p-1,-0x1.5bb5967402f9cp79
+sin,0x1.e8a523fce884dp-2,0x1.5bea01p468
+sin,-0x1.e8a523fce884dp-2,-0x1.5bea01p468
+sin,-0x1.ff2ad941f0a41p-1,0x1.5f19fbc507af6p9
+sin,0x1.ff2ad941f0a41p-1,-0x1.5f19fbc507af6p9
+sin,-0x1.75ce4a0d0bd03p-1,0x1.60a610a658da9p889
+sin,0x1.75ce4a0d0bd03p-1,-0x1.60a610a658da9p889
+sin,-0x1.721586594ab48p-1,0x1.62ad7ce17143dp62
+sin,0x1.721586594ab48p-1,-0x1.62ad7ce17143dp62
+sin,0x1.b8d27019d1b9fp-2,0x1.645926cc1132cp9
+sin,-0x1.b8d27019d1b9fp-2,-0x1.645926cc1132cp9
+sin,0x1.647e09059c1eap-9,0x1.647e25d391f17p-9
+sin,-0x1.647e09059c1eap-9,-0x1.647e25d391f17p-9
+sin,-0x1.8d3b53ff85a82p-1,0x1.64ef438p142
+sin,0x1.8d3b53ff85a82p-1,-0x1.64ef438p142
+sin,-0x1.f7c8630e62a02p-1,0x1.6599665996658p3
+sin,0x1.f7c8630e62a02p-1,-0x1.6599665996658p3
+sin,0x1.67028e3602035p-5,0x1.672p-5
+sin,-0x1.67028e3602035p-5,-0x1.672p-5
+sin,0x1.bc60c8c33cb5fp-2,0x1.688ae6c138ea8p299
+sin,-0x1.bc60c8c33cb5fp-2,-0x1.688ae6c138ea8p299
+sin,-0x1.fc3b4bb8b012ep-1,0x1.6aa78p17
+sin,0x1.fc3b4bb8b012ep-1,-0x1.6aa78p17
+sin,0x1.0p0,0x1.6ac5b262ca1ffp849
+sin,-0x1.0p0,-0x1.6ac5b262ca1ffp849
+sin,-0x1.82317836a97c8p-1,0x1.6d88083749412p4
+sin,0x1.82317836a97c8p-1,-0x1.6d88083749412p4
+sin,0x1.6f781c78cc82bp-6,0x1.6f8p-6
+sin,-0x1.6f781c78cc82bp-6,-0x1.6f8p-6
+sin,-0x1.fdbe5085494aep-1,0x1.729aa6859d1f4p396
+sin,0x1.fdbe5085494aep-1,-0x1.729aa6859d1f4p396
+sin,-0x1.fffffae862b5p-1,0x1.73e2dbe9a2f8p10
+sin,0x1.fffffae862b5p-1,-0x1.73e2dbe9a2f8p10
+sin,0x1.769ac74459b06p-7,0x1.769cde0b90b8p-7
+sin,-0x1.769ac74459b06p-7,-0x1.769cde0b90b8p-7
+sin,0x1.769e8afb6a4ecp-5,0x1.76cp-5
+sin,-0x1.769e8afb6a4ecp-5,-0x1.76cp-5
+sin,0x1.fd562611f5bd4p-1,0x1.78001p0
+sin,-0x1.fd562611f5bd4p-1,-0x1.78001p0
+sin,0x1.fdba784ca00f2p-1,0x1.7ap0
+sin,-0x1.fdba784ca00f2p-1,-0x1.7ap0
+sin,0x1.f930c222a8683p-5,0x1.7abd870381c2dp38
+sin,-0x1.f930c222a8683p-5,-0x1.7abd870381c2dp38
+sin,0x1.ffeb2ff2b6923p-1,0x1.7dc945c21248p95
+sin,-0x1.ffeb2ff2b6923p-1,-0x1.7dc945c21248p95
+sin,0x1.b279153c23fb2p-2,0x1.7f73e1594b70cp98
+sin,-0x1.b279153c23fb2p-2,-0x1.7f73e1594b70cp98
+sin,-0x1.599fad35cf60bp-41,0x1.7f7ef77e83f1ap21
+sin,0x1.599fad35cf60bp-41,-0x1.7f7ef77e83f1ap21
+sin,0x1.feb7a9b2c6d8bp-1,0x1.8p0
+sin,-0x1.feb7a9b2c6d8bp-1,-0x1.8p0
+sin,0x1.f798d01ec615cp-1,0x1.8p6
+sin,-0x1.f798d01ec615cp-1,-0x1.8p6
+sin,0x1.fee1a2a977bcfp-1,0x1.8132ceb1c4f39p0
+sin,-0x1.fee1a2a977bcfp-1,-0x1.8132ceb1c4f39p0
+sin,-0x1.24245af4cd995p-52,0x1.81ae0dffa3b33p959
+sin,0x1.24245af4cd995p-52,-0x1.81ae0dffa3b33p959
+sin,0x1.85d41b0bf3091p-4,0x1.85ec5a399a2e6p1
+sin,-0x1.85d41b0bf3091p-4,-0x1.85ec5a399a2e6p1
+sin,0x1.1e42ae3cfbdc6p-24,0x1.86a0092754022p16
+sin,-0x1.1e42ae3cfbdc6p-24,-0x1.86a0092754022p16
+sin,-0x1.dbf4e594cefe1p-1,0x1.8720588p392
+sin,0x1.dbf4e594cefe1p-1,-0x1.8720588p392
+sin,0x1.44302d6a82d4p-9,0x1.8929354ebc6aap43
+sin,-0x1.44302d6a82d4p-9,-0x1.8929354ebc6aap43
+sin,0x1.8a52189ec3487p-5,0x1.8a791e4791e75p-5
+sin,-0x1.8a52189ec3487p-5,-0x1.8a791e4791e75p-5
+sin,-0x1.fe8566e538123p-1,0x1.8ba761438f5edp11
+sin,0x1.fe8566e538123p-1,-0x1.8ba761438f5edp11
+sin,0x1.fff42aca4cb5ap-1,0x1.8eaf16de6392p0
+sin,-0x1.fff42aca4cb5ap-1,-0x1.8eaf16de6392p0
+sin,0x1.fffb7d3f3a253p-1,0x1.9p0
+sin,-0x1.fffb7d3f3a253p-1,-0x1.9p0
+sin,-0x1.e815770667fd9p-4,0x1.91a5657fb6a9ap6
+sin,0x1.e815770667fd9p-4,-0x1.91a5657fb6a9ap6
+sin,-0x1.fffffffd311dcp-1,0x1.921fb54468847p37
+sin,0x1.fffffffd311dcp-1,-0x1.921fb54468847p37
+sin,0x1.ffffffff875e6p-17,0x1.921ff54442d18p2
+sin,-0x1.ffffffff875e6p-17,-0x1.921ff54442d18p2
+sin,0x1.812a5da3777cdp-8,0x1.928p2
+sin,-0x1.812a5da3777cdp-8,-0x1.928p2
+sin,0x1.fff9be8d82573p-1,0x1.94ap0
+sin,-0x1.fff9be8d82573p-1,-0x1.94ap0
+sin,0x1.947b0ace235f3p-5,0x1.94a5294a51bdep-5
+sin,-0x1.947b0ace235f3p-5,-0x1.94a5294a51bdep-5
+sin,0x1.c34f70e55a708p-2,0x1.94a5294a52948p100
+sin,-0x1.c34f70e55a708p-2,-0x1.94a5294a52948p100
+sin,0x1.950bcfc0f3d51p-5,0x1.95361b8f7697dp-5
+sin,-0x1.950bcfc0f3d51p-5,-0x1.95361b8f7697dp-5
+sin,0x1.6c548bfcce696p-1,0x1.956p-1
+sin,-0x1.6c548bfcce696p-1,-0x1.956p-1
+sin,0x1.ffeffdbf67ca6p-1,0x1.962p0
+sin,-0x1.ffeffdbf67ca6p-1,-0x1.962p0
+sin,0x1.9708213bf67f5p-5,0x1.97330d2ea16d9p-5
+sin,-0x1.9708213bf67f5p-5,-0x1.97330d2ea16d9p-5
+sin,0x1.972bf92713d51p-5,0x1.9756f073b6b61p-5
+sin,-0x1.972bf92713d51p-5,-0x1.9756f073b6b61p-5
+sin,0x1.976845ebe7119p-5,0x1.97935055cec1bp-5
+sin,-0x1.976845ebe7119p-5,-0x1.97935055cec1bp-5
+sin,0x1.97535cee51a43p-4,0x1.98p-4
+sin,-0x1.97535cee51a43p-4,-0x1.98p-4
+sin,0x1.6f494c3356177p-1,0x1.999999a42160cp-1
+sin,-0x1.6f494c3356177p-1,-0x1.999999a42160cp-1
+sin,0x1.6f494c37edd6ep-1,0x1.999999aab8f5p-1
+sin,-0x1.6f494c37edd6ep-1,-0x1.999999aab8f5p-1
+sin,0x1.6fa912bdeaab2p-1,0x1.9a2324b9c6326p-1
+sin,-0x1.6fa912bdeaab2p-1,-0x1.9a2324b9c6326p-1
+sin,0x1.70c7ef4ef9b34p-1,0x1.9bcp-1
+sin,-0x1.70c7ef4ef9b34p-1,-0x1.9bcp-1
+sin,0x1.ff28176ad3164p-1,0x1.a0d1d817d6c4ap0
+sin,-0x1.ff28176ad3164p-1,-0x1.a0d1d817d6c4ap0
+sin,0x1.749468a7248dep-1,0x1.a141c9de12fdfp-1
+sin,-0x1.749468a7248dep-1,-0x1.a141c9de12fdfp-1
+sin,0x1.754ebb7e73f46p-1,0x1.a251bc6766f2p-1
+sin,-0x1.754ebb7e73f46p-1,-0x1.a251bc6766f2p-1
+sin,-0x1.7c3bfefa74bd1p-1,0x1.a2689ae1b86ddp62
+sin,0x1.7c3bfefa74bd1p-1,-0x1.a2689ae1b86ddp62
+sin,-0x1.ffff4f3648e03p-1,0x1.a3f66180c455p100
+sin,0x1.ffff4f3648e03p-1,-0x1.a3f66180c455p100
+sin,-0x1.1cf463983c0e3p-3,0x1.a3fdd2a5286c3p1
+sin,0x1.1cf463983c0e3p-3,-0x1.a3fdd2a5286c3p1
+sin,0x1.feb7948d224d8p-1,0x1.a44p0
+sin,-0x1.feb7948d224d8p-1,-0x1.a44p0
+sin,0x1.78801e3e11665p-1,0x1.a701ef3c7d54bp-1
+sin,-0x1.78801e3e11665p-1,-0x1.a701ef3c7d54bp-1
+sin,-0x1.fff11e871d59cp-1,0x1.a8c01fd43cp537
+sin,0x1.fff11e871d59cp-1,-0x1.a8c01fd43cp537
+sin,0x1.fdfa4366eb733p-1,0x1.a8e29b7602f3bp0
+sin,-0x1.fdfa4366eb733p-1,-0x1.a8e29b7602f3bp0
+sin,0x1.fde98b94e7948p-1,0x1.a94p0
+sin,-0x1.fde98b94e7948p-1,-0x1.a94p0
+sin,0x1.7931cba100008p-2,0x1.aa445fce93b82p2
+sin,-0x1.7931cba100008p-2,-0x1.aa445fce93b82p2
+sin,0x1.7af3f76c7a708p-1,0x1.aaa3fbc359fbep-1
+sin,-0x1.7af3f76c7a708p-1,-0x1.aaa3fbc359fbep-1
+sin,0x1.fd74e53ae32fdp-6,0x1.abdd3dbd4d86p119
+sin,-0x1.fd74e53ae32fdp-6,-0x1.abdd3dbd4d86p119
+sin,0x1.7d4a7bf183a34p-1,0x1.ae2165a0c9f8ep-1
+sin,-0x1.7d4a7bf183a34p-1,-0x1.ae2165a0c9f8ep-1
+sin,0x1.b81410edc79e1p-2,0x1.ae8dfefcfe13bp2
+sin,-0x1.b81410edc79e1p-2,-0x1.ae8dfefcfe13bp2
+sin,-0x1.ff751561dc50ap-2,0x1.b5597f950ee8cp29
+sin,0x1.ff751561dc50ap-2,-0x1.b5597f950ee8cp29
+sin,0x1.027d184afb198p-52,0x1.bab62ed655019p970
+sin,-0x1.027d184afb198p-52,-0x1.bab62ed655019p970
+sin,0x1.bc572e5e413e1p-10,0x1.bc573c4ffffffp-10
+sin,-0x1.bc572e5e413e1p-10,-0x1.bc573c4ffffffp-10
+sin,0x1.fb300f1e39afep-1,0x1.bef5cd25ab1adp9
+sin,-0x1.fb300f1e39afep-1,-0x1.bef5cd25ab1adp9
+sin,0x1.b1baaf622d3a3p-2,0x1.bfdf6df2a24c1p-2
+sin,-0x1.b1baaf622d3a3p-2,-0x1.bfdf6df2a24c1p-2
+sin,0x1.88fb762c35ce4p-1,0x1.bfffffdffffffp-1
+sin,-0x1.88fb762c35ce4p-1,-0x1.bfffffdffffffp-1
+sin,0x1.fe0ebff99ab8dp-1,0x1.c2b489520e376p920
+sin,-0x1.fe0ebff99ab8dp-1,-0x1.c2b489520e376p920
+sin,0x1.cf7f749f2a836p-4,0x1.c54beb008547p5
+sin,-0x1.cf7f749f2a836p-4,-0x1.c54beb008547p5
+sin,0x1.b6facf6658915p-2,0x1.c5ad34f5f472ap-2
+sin,-0x1.b6facf6658915p-2,-0x1.c5ad34f5f472ap-2
+sin,0x1.b851cd9b84ee7p-2,0x1.c728fc2f34bd6p-2
+sin,-0x1.b851cd9b84ee7p-2,-0x1.c728fc2f34bd6p-2
+sin,0x1.ba21b53cf2ff3p-2,0x1.c92b0f6105089p-2
+sin,-0x1.ba21b53cf2ff3p-2,-0x1.c92b0f6105089p-2
+sin,0x1.c9a2b68e30ec7p-5,0x1.c9dfbbe9ec704p-5
+sin,-0x1.c9a2b68e30ec7p-5,-0x1.c9dfbbe9ec704p-5
+sin,0x1.f370115c9ab35p-1,0x1.caf31bd7ee217p0
+sin,-0x1.f370115c9ab35p-1,-0x1.caf31bd7ee217p0
+sin,-0x1.dd38a1f1d289bp-54,0x1.cb44e86bc192bp648
+sin,0x1.dd38a1f1d289bp-54,-0x1.cb44e86bc192bp648
+sin,0x1.dd38a1f1d289bp-53,0x1.cb44e86bc192bp649
+sin,-0x1.dd38a1f1d289bp-53,-0x1.cb44e86bc192bp649
+sin,0x1.c7885aef33a95p-3,0x1.cb6p-3
+sin,-0x1.c7885aef33a95p-3,-0x1.cb6p-3
+sin,0x1.cd279aa6196b6p-4,0x1.ce2271d2f662fp-4
+sin,-0x1.cd279aa6196b6p-4,-0x1.ce2271d2f662fp-4
+sin,0x1.930b705f9fad2p-1,0x1.d0000000004p-1
+sin,-0x1.930b705f9fad2p-1,-0x1.d0000000004p-1
+sin,0x1.7ef24c8e67d9ap-1,0x1.d01p199
+sin,-0x1.7ef24c8e67d9ap-1,-0x1.d01p199
+sin,0x1.ffff124c001abp-1,0x1.d024ba6f953cfp1000
+sin,-0x1.ffff124c001abp-1,-0x1.d024ba6f953cfp1000
+sin,-0x1.f83a0983dd15dp-2,0x1.d4067c60f471ep1
+sin,0x1.f83a0983dd15dp-2,-0x1.d4067c60f471ep1
+sin,0x1.d79b9896ff555p-5,0x1.d7de6263bcaabp-5
+sin,-0x1.d79b9896ff555p-5,-0x1.d7de6263bcaabp-5
+sin,0x1.ed0b908a2983p-1,0x1.d800000002274p0
+sin,-0x1.ed0b908a2983p-1,-0x1.d800000002274p0
+sin,-0x1.f2c217cbc7dcdp-1,0x1.d96e058p488
+sin,0x1.f2c217cbc7dcdp-1,-0x1.d96e058p488
+sin,0x1.98dcd09337793p-1,0x1.d98c4c612718dp-1
+sin,-0x1.98dcd09337793p-1,-0x1.d98c4c612718dp-1
+sin,0x1.db3ba8775ca26p-5,0x1.db8p-5
+sin,-0x1.db3ba8775ca26p-5,-0x1.db8p-5
+sin,-0x1.9fee37697d582p-2,0x1.de386d6090303p200
+sin,0x1.9fee37697d582p-2,-0x1.de386d6090303p200
+sin,-0x1.5361ee6553188p-53,0x1.de5e5054e921bp35
+sin,0x1.5361ee6553188p-53,-0x1.de5e5054e921bp35
+sin,0x1.fec48d5e769ecp-1,0x1.df77ddf77ddf4p10
+sin,-0x1.fec48d5e769ecp-1,-0x1.df77ddf77ddf4p10
+sin,-0x1.2902a83d72632p-1,0x1.e1562b0448a86p1
+sin,0x1.2902a83d72632p-1,-0x1.e1562b0448a86p1
+sin,0x1.9e26c7bc96b69p-1,0x1.e2700cdc86635p-1
+sin,-0x1.9e26c7bc96b69p-1,-0x1.e2700cdc86635p-1
+sin,0x1.e6494911eedd2p-7,0x1.e64ddaf7bd73p-7
+sin,-0x1.e6494911eedd2p-7,-0x1.e64ddaf7bd73p-7
+sin,0x1.eb26c690bda25p-5,0x1.eb7239bca8afap-5
+sin,-0x1.eb26c690bda25p-5,-0x1.eb7239bca8afap-5
+sin,0x1.c73238790a4cfp-3,0x1.ef7b83f7bdef4p3
+sin,-0x1.c73238790a4cfp-3,-0x1.ef7b83f7bdef4p3
+sin,0x1.ed1b575acb8c8p-3,0x1.f20000000109bp-3
+sin,-0x1.ed1b575acb8c8p-3,-0x1.f20000000109bp-3
+sin,0x1.c1b50a56c8809p-1,0x1.f40ca67a9e8d7p9
+sin,-0x1.c1b50a56c8809p-1,-0x1.f40ca67a9e8d7p9
+sin,0x1.e321fea643a96p-2,0x1.f7224d2c7754p-2
+sin,-0x1.e321fea643a96p-2,-0x1.f7224d2c7754p-2
+sin,0x1.c1269b020a108p-3,0x1.f78a0d05e60e2p6
+sin,-0x1.c1269b020a108p-3,-0x1.f78a0d05e60e2p6
+sin,0x1.f76cae28a0775p-5,0x1.f7bdef7bdf073p-5
+sin,-0x1.f76cae28a0775p-5,-0x1.f7bdef7bdf073p-5
+sin,0x1.e42c139dc2054p-2,0x1.f8502d5955443p-2
+sin,-0x1.e42c139dc2054p-2,-0x1.f8502d5955443p-2
+sin,0x1.0fa749e07f64p-9,0x1.f8fc824d2693bp61
+sin,-0x1.0fa749e07f64p-9,-0x1.f8fc824d2693bp61
+sin,0x1.ffa80324e2d8fp-1,0x1.f8fffffffffffp2
+sin,-0x1.ffa80324e2d8fp-1,-0x1.f8fffffffffffp2
+sin,-0x1.7cdf79d5e37b8p-1,0x1.fd8p1
+sin,0x1.7cdf79d5e37b8p-1,-0x1.fd8p1
+sin,0x1.fd3f48847a1d1p-5,0x1.fd9364d936596p-5
+sin,-0x1.fd3f48847a1d1p-5,-0x1.fd9364d936596p-5
+sin,0x1.f93ad471d262fp-3,0x1.fe8p-3
+sin,-0x1.f93ad471d262fp-3,-0x1.fe8p-3
+sin,0x1.83b3062414974p-1,0x1.febb646e2ee57p13
+sin,-0x1.83b3062414974p-1,-0x1.febb646e2ee57p13
+sin,0x1.3b45bd7449775p-1,0x1.feeffffffffc6p995
+sin,-0x1.3b45bd7449775p-1,-0x1.feeffffffffc6p995
+sin,-0x1.eefb59d143646p-1,0x1.ff8ffffffffffp7
+sin,0x1.eefb59d143646p-1,-0x1.ff8ffffffffffp7
+sin,-0x1.56433f0c6bceep-1,0x1.ff8ffffffffffp870
+sin,0x1.56433f0c6bceep-1,-0x1.ff8ffffffffffp870
+sin,-0x1.930006246a6cp-2,0x1.ffcfff8p19
+sin,0x1.930006246a6cp-2,-0x1.ffcfff8p19
+sin,0x1.ded37a1f0aa6dp-1,0x1.ffcfff8p365
+sin,-0x1.ded37a1f0aa6dp-1,-0x1.ffcfff8p365
+sin,-0x1.93e4d96b621ep-1,0x1.ffcffffffff6cp720
+sin,0x1.93e4d96b621ep-1,-0x1.ffcffffffff6cp720
+sin,0x1.9068b90e42606p-1,0x1.ffcfffffffff9p320
+sin,-0x1.9068b90e42606p-1,-0x1.ffcfffffffff9p320
+sin,0x1.cf81642e7421cp-1,0x1.ffcffffffffffp12
+sin,-0x1.cf81642e7421cp-1,-0x1.ffcffffffffffp12
+sin,0x1.ffffffe61fe61p-1,0x1.ffcffffffffffp404
+sin,-0x1.ffffffe61fe61p-1,-0x1.ffcffffffffffp404
+sin,-0x1.406ee9ae91e17p-1,0x1.ffeffffffffccp995
+sin,0x1.406ee9ae91e17p-1,-0x1.ffeffffffffccp995
+sin,0x1.fa9f6ca0ec44ep-3,0x1.ffeffffffffffp-3
+sin,-0x1.fa9f6ca0ec44ep-3,-0x1.ffeffffffffffp-3
+sin,0x1.6b491db8b66d9p-4,0x1.ffeffffffffffp55
+sin,-0x1.6b491db8b66d9p-4,-0x1.ffeffffffffffp55
+sin,0x1.fb0ab102cb13p-1,0x1.ffeffffffffffp180
+sin,-0x1.fb0ab102cb13p-1,-0x1.ffeffffffffffp180
+sin,0x1.e4315ec04635dp-3,0x1.ffeffffffffffp706
+sin,-0x1.e4315ec04635dp-3,-0x1.ffeffffffffffp706
+sin,0x1.ffffc39997ef6p-1,0x1.fff1fffffffffp41
+sin,-0x1.ffffc39997ef6p-1,-0x1.fff1fffffffffp41
+sin,0x1.fff163992831fp-7,0x1.fff6b89ffffffp-7
+sin,-0x1.fff163992831fp-7,-0x1.fff6b89ffffffp-7
+sin,-0x1.d9757a05fcc43p-1,0x1.fffdffff0001fp105
+sin,0x1.d9757a05fcc43p-1,-0x1.fffdffff0001fp105
+sin,-0x1.83791fe63a17ap-1,0x1.ffff0c0000002p1
+sin,0x1.83791fe63a17ap-1,-0x1.ffff0c0000002p1
+sin,-0x1.d9d3a85acc50dp-1,0x1.ffffc00000055p150
+sin,0x1.d9d3a85acc50dp-1,-0x1.ffffc00000055p150
+sin,-0x1.f25d858dcdee7p-3,0x1.ffffe3fffffffp40
+sin,0x1.f25d858dcdee7p-3,-0x1.ffffe3fffffffp40
+sin,0x1.d18f7bfe557ecp-1,0x1.ffffefffcffaep0
+sin,-0x1.d18f7bfe557ecp-1,-0x1.ffffefffcffaep0
+sin,-0x1.bc14ebf6bfb52p-4,0x1.fffffbfffffffp228
+sin,0x1.bc14ebf6bfb52p-4,-0x1.fffffbfffffffp228
+sin,0x1.bb887a06f6c51p-3,0x1.fffffbfffffffp735
+sin,-0x1.bb887a06f6c51p-3,-0x1.fffffbfffffffp735
+sin,0x1.ffaaadef54e2fp-5,0x1.fffffefffffffp-5
+sin,-0x1.ffaaadef54e2fp-5,-0x1.fffffefffffffp-5
+sin,0x1.d4a3c62c5be09p-1,0x1.ffffff8p119
+sin,-0x1.d4a3c62c5be09p-1,-0x1.ffffff8p119
+sin,0x1.cec20f197703fp-3,0x1.ffffff8p192
+sin,-0x1.cec20f197703fp-3,-0x1.ffffff8p192
+sin,0x1.d37aadc7c8662p-2,0x1.ffffff8p543
+sin,-0x1.d37aadc7c8662p-2,-0x1.ffffff8p543
+sin,0x1.fa8d2a4d0a202p-1,0x1.ffffffc0018ffp2
+sin,-0x1.fa8d2a4d0a202p-1,-0x1.ffffffc0018ffp2
+sin,0x1.fa8d2a029f978p-1,0x1.ffffffffeffffp2
+sin,-0x1.fa8d2a029f978p-1,-0x1.ffffffffeffffp2
+sin,-0x1.2763f02a2d1eap-4,0x1.fffffffff825p943
+sin,0x1.2763f02a2d1eap-4,-0x1.fffffffff825p943
+sin,0x1.fcff128f77ddbp-1,0x1.fffffffffe09dp320
+sin,-0x1.fcff128f77ddbp-1,-0x1.fffffffffe09dp320
+sin,-0x1.fcc0bfedd84a6p-1,0x1.fffffffffe6e3p720
+sin,0x1.fcc0bfedd84a6p-1,-0x1.fffffffffe6e3p720
+sin,0x1.aed548f090c1ep-1,0x1.ffffffffffe7fp-1
+sin,-0x1.aed548f090c1ep-1,-0x1.ffffffffffe7fp-1
+sin,-0x1.f5e11def99d2bp-1,0x1.ffffffffffeffp250
+sin,0x1.f5e11def99d2bp-1,-0x1.ffffffffffeffp250
+sin,0x1.8a9cbf48fec9fp-1,0x1.fffffffffff78p920
+sin,-0x1.8a9cbf48fec9fp-1,-0x1.fffffffffff78p920
+sin,-0x1.7eba5894844ccp-3,0x1.fffffffffff83p150
+sin,0x1.7eba5894844ccp-3,-0x1.fffffffffff83p150
+sin,0x1.92c4f06d2cdd1p-1,0x1.fffffffffffd5p995
+sin,-0x1.92c4f06d2cdd1p-1,-0x1.fffffffffffd5p995
+sin,-0x1.3d5f7deb1d3bbp-1,0x1.fffffffffffe8p720
+sin,0x1.3d5f7deb1d3bbp-1,-0x1.fffffffffffe8p720
+sin,-0x1.91349b0ae90e5p-1,0x1.fffffffffffebp920
+sin,0x1.91349b0ae90e5p-1,-0x1.fffffffffffebp920
+sin,-0x1.837b9dddc1e88p-1,0x1.ffffffffffff1p1
+sin,0x1.837b9dddc1e88p-1,-0x1.ffffffffffff1p1
+sin,0x1.510e062e7fa2p-1,0x1.ffffffffffff1p245
+sin,-0x1.510e062e7fa2p-1,-0x1.ffffffffffff1p245
+sin,0x1.eaee8744b05e5p-2,0x1.ffffffffffff3p-2
+sin,-0x1.eaee8744b05e5p-2,-0x1.ffffffffffff3p-2
+sin,0x1.8a4dee8f40628p-1,0x1.ffffffffffff4p845
+sin,-0x1.8a4dee8f40628p-1,-0x1.ffffffffffff4p845
+sin,0x1.5118d6bbde07ep-1,0x1.ffffffffffff4p1020
+sin,-0x1.5118d6bbde07ep-1,-0x1.ffffffffffff4p1020
+sin,-0x1.5cd5c53cf30a9p-1,0x1.ffffffffffff8p616
+sin,0x1.5cd5c53cf30a9p-1,-0x1.ffffffffffff8p616
+sin,0x1.ffffa1f0d7dafp-1,0x1.ffffffffffffcp475
+sin,-0x1.ffffa1f0d7dafp-1,-0x1.ffffffffffffcp475
+sin,0x1.51e9d840106d7p-1,0x1.ffffffffffffep970
+sin,-0x1.51e9d840106d7p-1,-0x1.ffffffffffffep970
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0p0,-0x0.0p0
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,-0x1.0000000000001p-1022,-0x1.0000000000001p-1022
+sin,0x1.0000000000001p-1022,0x1.0000000000001p-1022
+sin,-0x1.0p-1022,-0x1.0p-1022
+sin,0x1.0p-1022,0x1.0p-1022
+sin,-0x0.fffffffffffffp-1022,-0x0.fffffffffffffp-1022
+sin,0x0.fffffffffffffp-1022,0x0.fffffffffffffp-1022
+sin,0x0.fffffffffffffp-1022,0x0.fffffffffffffp-1022
+sin,-0x0.fffffffffffffp-1022,-0x0.fffffffffffffp-1022
+sin,0x1.0p-1022,0x1.0p-1022
+sin,-0x1.0p-1022,-0x1.0p-1022
+sin,0x1.0000000000001p-1022,0x1.0000000000001p-1022
+sin,-0x1.0000000000001p-1022,-0x1.0000000000001p-1022
+sin,0x1.9999996de8ca2p-13,0x1.999999999999ap-13
+sin,-0x1.9999996de8ca2p-13,-0x1.999999999999ap-13
+sin,0x1.999998ead65b9p-12,0x1.999999999999ap-12
+sin,-0x1.999998ead65b9p-12,-0x1.999999999999ap-12
+sin,0x1.3333320c49bacp-11,0x1.3333333333334p-11
+sin,-0x1.3333320c49bacp-11,-0x1.3333333333334p-11
+sin,0x1.999996de8ca29p-11,0x1.999999999999ap-11
+sin,-0x1.999996de8ca29p-11,-0x1.999999999999ap-11
+sin,0x1.fffffaaaaaaefp-11,0x1.0p-10
+sin,-0x1.fffffaaaaaaefp-11,-0x1.0p-10
+sin,0x1.33332e978d553p-10,0x1.3333333333333p-10
+sin,-0x1.33332e978d553p-10,-0x1.3333333333333p-10
+sin,0x1.66665f1529bp-10,0x1.6666666666666p-10
+sin,-0x1.66665f1529bp-10,-0x1.6666666666666p-10
+sin,0x1.99998ead65cep-10,0x1.9999999999999p-10
+sin,-0x1.99998ead65cep-10,-0x1.9999999999999p-10
+sin,0x1.ccccbd3f7d15dp-10,0x1.cccccccccccccp-10
+sin,-0x1.ccccbd3f7d15dp-10,-0x1.cccccccccccccp-10
+sin,0x1.0665ae9c7b44fp-7,0x1.0666666666666p-7
+sin,-0x1.0665ae9c7b44fp-7,-0x1.0666666666666p-7
+sin,0x1.ccc8e97b59f62p-7,0x1.cccccccccccccp-7
+sin,-0x1.ccc8e97b59f62p-7,-0x1.cccccccccccccp-7
+sin,0x1.4993e8a8ff79bp-6,0x1.4999999999999p-6
+sin,-0x1.4993e8a8ff79bp-6,-0x1.4999999999999p-6
+sin,0x1.acc044c56db0ep-6,0x1.accccccccccccp-6
+sin,-0x1.acc044c56db0ep-6,-0x1.accccccccccccp-6
+sin,0x1.07f44d67cf41bp-5,0x1.08p-5
+sin,-0x1.07f44d67cf41bp-5,-0x1.08p-5
+sin,0x1.3985fe46f1c87p-5,0x1.399999999999ap-5
+sin,-0x1.3985fe46f1c87p-5,-0x1.399999999999ap-5
+sin,0x1.6b14bde93ac5fp-5,0x1.6b33333333334p-5
+sin,-0x1.6b14bde93ac5fp-5,-0x1.6b33333333334p-5
+sin,0x1.9ca0153ed8397p-5,0x1.9cccccccccccep-5
+sin,-0x1.9ca0153ed8397p-5,-0x1.9cccccccccccep-5
+sin,0x1.ce278d4027d34p-5,0x1.ce66666666666p-5
+sin,-0x1.ce278d4027d34p-5,-0x1.ce66666666666p-5
+sin,0x1.43c1e9c171a66p-1,0x1.5e7fc4369bdadp-1
+sin,-0x1.43c1e9c171a66p-1,-0x1.5e7fc4369bdadp-1
+sin,0x1.ee3d6bcea09cap-1,0x1.4e7fc4369bdadp0
+sin,-0x1.ee3d6bcea09cap-1,-0x1.4e7fc4369bdadp0
+sin,0x1.df8e22ea809d6p-1,0x1.edbfa651e9c84p0
+sin,-0x1.df8e22ea809d6p-1,-0x1.edbfa651e9c84p0
+sin,0x1.1d3479eac7ae3p-1,0x1.467fc4369bdadp1
+sin,-0x1.1d3479eac7ae3p-1,-0x1.467fc4369bdadp1
+sin,-0x1.ffeaaaeeee84bp-6,0x1.961fb54442d18p1
+sin,0x1.ffeaaaeeee84bp-6,-0x1.961fb54442d18p1
+sin,-0x1.3734d32d49bd1p-1,0x1.e5bfa651e9c83p1
+sin,0x1.3734d32d49bd1p-1,-0x1.e5bfa651e9c83p1
+sin,-0x1.e9d25d19911e2p-1,0x1.1aafcbafc85f7p2
+sin,0x1.e9d25d19911e2p-1,-0x1.1aafcbafc85f7p2
+sin,-0x1.e4ecdc5a4e466p-1,0x1.427fc4369bdadp2
+sin,0x1.e4ecdc5a4e466p-1,-0x1.427fc4369bdadp2
+sin,-0x1.2a59f10344262p-1,0x1.6a4fbcbd6f562p2
+sin,0x1.2a59f10344262p-1,-0x1.6a4fbcbd6f562p2
+sin,-0x1.26312443bd35fp-1,0x1.6af2eff0a2896p2
+sin,0x1.26312443bd35fp-1,-0x1.6af2eff0a2896p2
+sin,-0x1.e18e660a5e2fbp-1,0x1.43c62a9d02414p2
+sin,0x1.e18e660a5e2fbp-1,-0x1.43c62a9d02414p2
+sin,-0x1.ee0e83a0198b7p-1,0x1.1c99654961f92p2
+sin,0x1.ee0e83a0198b7p-1,-0x1.1c99654961f92p2
+sin,-0x1.4727747338e46p-1,0x1.ead93feb8361fp1
+sin,0x1.4727747338e46p-1,-0x1.ead93feb8361fp1
+sin,-0x1.4ba2f75dda5fep-4,0x1.9c7fb54442d1ap1
+sin,0x1.4ba2f75dda5fep-4,-0x1.9c7fb54442d1ap1
+sin,0x1.034c4d633b4efp-1,0x1.4e262a9d02415p1
+sin,-0x1.034c4d633b4efp-1,-0x1.4e262a9d02415p1
+sin,0x1.d1e4cde2f3945p-1,0x1.ff993feb8362p0
+sin,-0x1.d1e4cde2f3945p-1,-0x1.ff993feb8362p0
+sin,0x1.f750235c94992p-1,0x1.62e62a9d02416p0
+sin,-0x1.f750235c94992p-1,-0x1.62e62a9d02416p0
+sin,0x1.65f7d571279b1p-1,0x1.8c662a9d02419p-1
+sin,-0x1.65f7d571279b1p-1,-0x1.8c662a9d02419p-1
+sin,-0x1.fe043f57369d7p-1,-0x1.a8aa1d11c44ffp0
+sin,0x1.fe043f57369d7p-1,0x1.a8aa1d11c44ffp0
+sin,-0x1.fff18f24f3e4cp-1,-0x1.95ec8b9e03d54p0
+sin,0x1.fff18f24f3e4cp-1,0x1.95ec8b9e03d54p0
+sin,-0x1.ff20d961624e7p-1,-0x1.832efa2a435a9p0
+sin,0x1.ff20d961624e7p-1,0x1.832efa2a435a9p0
+sin,-0x1.fb933c40107fdp-1,-0x1.707168b682dfep0
+sin,0x1.fb933c40107fdp-1,0x1.707168b682dfep0
+sin,-0x1.f54d971881ad7p-1,-0x1.5db3d742c2653p0
+sin,0x1.f54d971881ad7p-1,0x1.5db3d742c2653p0
+sin,-0x1.ec5883b7b6cf5p-1,-0x1.4af645cf01ea8p0
+sin,0x1.ec5883b7b6cf5p-1,0x1.4af645cf01ea8p0
+sin,-0x1.e0c04a94e1731p-1,-0x1.3838b45b416fdp0
+sin,0x1.e0c04a94e1731p-1,0x1.3838b45b416fdp0
+sin,-0x1.d294d1f96c7ecp-1,-0x1.257b22e780f52p0
+sin,0x1.d294d1f96c7ecp-1,0x1.257b22e780f52p0
+sin,-0x1.c1e9883373d7fp-1,-0x1.12bd9173c07abp0
+sin,0x1.c1e9883373d7fp-1,0x1.12bd9173c07abp0
+sin,-0x1.a2c289d9d055bp-1,-0x1.ea5c3ed5b385p-1
+sin,0x1.a2c289d9d055bp-1,0x1.ea5c3ed5b385p-1
+sin,-0x1.95f05257dbcb6p-1,-0x1.d4b87dab670ap-1
+sin,0x1.95f05257dbcb6p-1,0x1.d4b87dab670ap-1
+sin,-0x1.88647f26a6e0fp-1,-0x1.bf14bc811a8fp-1
+sin,0x1.88647f26a6e0fp-1,0x1.bf14bc811a8fp-1
+sin,-0x1.7a2541dfd4e75p-1,-0x1.a970fb56ce14p-1
+sin,0x1.7a2541dfd4e75p-1,0x1.a970fb56ce14p-1
+sin,-0x1.6b391e25bc26dp-1,-0x1.93cd3a2c8199p-1
+sin,0x1.6b391e25bc26dp-1,0x1.93cd3a2c8199p-1
+sin,-0x1.5ba6e6a8e7065p-1,-0x1.7e297902351ep-1
+sin,0x1.5ba6e6a8e7065p-1,0x1.7e297902351ep-1
+sin,-0x1.4b75ba096fa55p-1,-0x1.6885b7d7e8a3p-1
+sin,0x1.4b75ba096fa55p-1,0x1.6885b7d7e8a3p-1
+sin,-0x1.3aacff95a3123p-1,-0x1.52e1f6ad9c28p-1
+sin,0x1.3aacff95a3123p-1,0x1.52e1f6ad9c28p-1
+sin,-0x1.295463e769285p-1,-0x1.3d3e35834fadp-1
+sin,0x1.295463e769285p-1,0x1.3d3e35834fadp-1
+sin,-0x1.fc769b77e5885p-2,-0x1.0a0b02501c799p-1
+sin,0x1.fc769b77e5885p-2,0x1.0a0b02501c799p-1
+sin,-0x1.c853c78462de4p-2,-0x1.d8f7208e6b82cp-2
+sin,0x1.c853c78462de4p-2,0x1.d8f7208e6b82cp-2
+sin,-0x1.92aba90aaf272p-2,-0x1.9dd83c7c9e126p-2
+sin,0x1.92aba90aaf272p-2,0x1.9dd83c7c9e126p-2
+sin,-0x1.5bac064658f39p-2,-0x1.62b9586ad0a2p-2
+sin,0x1.5bac064658f39p-2,0x1.62b9586ad0a2p-2
+sin,-0x1.2383ca8078e58p-2,-0x1.279a74590331ap-2
+sin,0x1.2383ca8078e58p-2,0x1.279a74590331ap-2
+sin,-0x1.d4c5bc11d2372p-3,-0x1.d8f7208e6b829p-3
+sin,0x1.d4c5bc11d2372p-3,0x1.d8f7208e6b829p-3
+sin,-0x1.60f3faaf43024p-3,-0x1.62b9586ad0a1ep-3
+sin,0x1.60f3faaf43024p-3,0x1.62b9586ad0a1ep-3
+sin,-0x1.d7ea3de45a9d6p-4,-0x1.d8f7208e6b826p-4
+sin,0x1.d7ea3de45a9d6p-4,0x1.d8f7208e6b826p-4
+sin,-0x1.d8b3df489987ap-5,-0x1.d8f7208e6b82dp-5
+sin,0x1.d8b3df489987ap-5,0x1.d8f7208e6b82dp-5
+sin,0x1.d8b3df489987ap-5,0x1.d8f7208e6b82dp-5
+sin,-0x1.d8b3df489987ap-5,-0x1.d8f7208e6b82dp-5
+sin,0x1.d7ea3de45a9ddp-4,0x1.d8f7208e6b82dp-4
+sin,-0x1.d7ea3de45a9ddp-4,-0x1.d8f7208e6b82dp-4
+sin,0x1.60f3faaf43028p-3,0x1.62b9586ad0a22p-3
+sin,-0x1.60f3faaf43028p-3,-0x1.62b9586ad0a22p-3
+sin,0x1.d4c5bc11d2376p-3,0x1.d8f7208e6b82dp-3
+sin,-0x1.d4c5bc11d2376p-3,-0x1.d8f7208e6b82dp-3
+sin,0x1.2383ca8078e5ap-2,0x1.279a74590331cp-2
+sin,-0x1.2383ca8078e5ap-2,-0x1.279a74590331cp-2
+sin,0x1.5bac064658f3bp-2,0x1.62b9586ad0a22p-2
+sin,-0x1.5bac064658f3bp-2,-0x1.62b9586ad0a22p-2
+sin,0x1.92aba90aaf274p-2,0x1.9dd83c7c9e128p-2
+sin,-0x1.92aba90aaf274p-2,-0x1.9dd83c7c9e128p-2
+sin,0x1.c853c78462de6p-2,0x1.d8f7208e6b82ep-2
+sin,-0x1.c853c78462de6p-2,-0x1.d8f7208e6b82ep-2
+sin,0x1.fc769b77e5885p-2,0x1.0a0b02501c799p-1
+sin,-0x1.fc769b77e5885p-2,-0x1.0a0b02501c799p-1
+sin,0x1.295463e769281p-1,0x1.3d3e35834faccp-1
+sin,-0x1.295463e769281p-1,-0x1.3d3e35834faccp-1
+sin,0x1.3aacff95a312p-1,0x1.52e1f6ad9c27cp-1
+sin,-0x1.3aacff95a312p-1,-0x1.52e1f6ad9c27cp-1
+sin,0x1.4b75ba096fa52p-1,0x1.6885b7d7e8a2cp-1
+sin,-0x1.4b75ba096fa52p-1,-0x1.6885b7d7e8a2cp-1
+sin,0x1.5ba6e6a8e7062p-1,0x1.7e297902351dcp-1
+sin,-0x1.5ba6e6a8e7062p-1,-0x1.7e297902351dcp-1
+sin,0x1.6b391e25bc26ap-1,0x1.93cd3a2c8198cp-1
+sin,-0x1.6b391e25bc26ap-1,-0x1.93cd3a2c8198cp-1
+sin,0x1.7a2541dfd4e73p-1,0x1.a970fb56ce13cp-1
+sin,-0x1.7a2541dfd4e73p-1,-0x1.a970fb56ce13cp-1
+sin,0x1.88647f26a6e0dp-1,0x1.bf14bc811a8ecp-1
+sin,-0x1.88647f26a6e0dp-1,-0x1.bf14bc811a8ecp-1
+sin,0x1.95f05257dbcb4p-1,0x1.d4b87dab6709cp-1
+sin,-0x1.95f05257dbcb4p-1,-0x1.d4b87dab6709cp-1
+sin,0x1.a2c289d9d0558p-1,0x1.ea5c3ed5b384cp-1
+sin,-0x1.a2c289d9d0558p-1,-0x1.ea5c3ed5b384cp-1
+sin,0x1.c1e9883373d7fp-1,0x1.12bd9173c07abp0
+sin,-0x1.c1e9883373d7fp-1,-0x1.12bd9173c07abp0
+sin,0x1.d294d1f96c7efp-1,0x1.257b22e780f56p0
+sin,-0x1.d294d1f96c7efp-1,-0x1.257b22e780f56p0
+sin,0x1.e0c04a94e1733p-1,0x1.3838b45b41701p0
+sin,-0x1.e0c04a94e1733p-1,-0x1.3838b45b41701p0
+sin,0x1.ec5883b7b6cf7p-1,0x1.4af645cf01eacp0
+sin,-0x1.ec5883b7b6cf7p-1,-0x1.4af645cf01eacp0
+sin,0x1.f54d971881ad8p-1,0x1.5db3d742c2657p0
+sin,-0x1.f54d971881ad8p-1,-0x1.5db3d742c2657p0
+sin,0x1.fb933c40107fep-1,0x1.707168b682e02p0
+sin,-0x1.fb933c40107fep-1,-0x1.707168b682e02p0
+sin,0x1.ff20d961624e7p-1,0x1.832efa2a435adp0
+sin,-0x1.ff20d961624e7p-1,-0x1.832efa2a435adp0
+sin,0x1.fff18f24f3e4bp-1,0x1.95ec8b9e03d58p0
+sin,-0x1.fff18f24f3e4bp-1,-0x1.95ec8b9e03d58p0
+sin,0x1.fe043f57369d7p-1,0x1.a8aa1d11c44ffp0
+sin,-0x1.fe043f57369d7p-1,-0x1.a8aa1d11c44ffp0
+sin,0x1.b3d3695acc413p-1,0x1.04aff6d330942p0
+sin,-0x1.b3d3695acc413p-1,-0x1.04aff6d330942p0
+sin,0x1.b3d41972dc806p-1,0x1.04b09e98dcdb4p0
+sin,-0x1.b3d41972dc806p-1,-0x1.04b09e98dcdb4p0
+sin,0x1.b3d4c98a318fbp-1,0x1.04b1465e89226p0
+sin,-0x1.b3d4c98a318fbp-1,-0x1.04b1465e89226p0
+sin,0x1.b3d579a0cb6eep-1,0x1.04b1ee2435698p0
+sin,-0x1.b3d579a0cb6eep-1,-0x1.04b1ee2435698p0
+sin,0x1.b3d629b6aa1dap-1,0x1.04b295e9e1b0ap0
+sin,-0x1.b3d629b6aa1dap-1,-0x1.04b295e9e1b0ap0
+sin,0x1.b3d6d9cbcd9bap-1,0x1.04b33daf8df7cp0
+sin,-0x1.b3d6d9cbcd9bap-1,-0x1.04b33daf8df7cp0
+sin,0x1.b3d789e035e89p-1,0x1.04b3e5753a3eep0
+sin,-0x1.b3d789e035e89p-1,-0x1.04b3e5753a3eep0
+sin,0x1.b3d839f3e3043p-1,0x1.04b48d3ae686p0
+sin,-0x1.b3d839f3e3043p-1,-0x1.04b48d3ae686p0
+sin,0x1.b3d8ea06d4eep-1,0x1.04b5350092ccfp0
+sin,-0x1.b3d8ea06d4eep-1,-0x1.04b5350092ccfp0
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0p0,-0x0.0p0
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,0x1.1773d561fd506p-1,0x1.279a74590331bp-1
+sin,-0x1.1773d561fd506p-1,-0x1.279a74590331bp-1
+sin,0x1.1773d561fd507p-1,0x1.279a74590331cp-1
+sin,-0x1.1773d561fd507p-1,-0x1.279a74590331cp-1
+sin,0x1.1773d561fd508p-1,0x1.279a74590331dp-1
+sin,-0x1.1773d561fd508p-1,-0x1.279a74590331dp-1
+sin,0x1.f95b8e7107419p-1,0x1.bb67ae8584ca9p0
+sin,-0x1.f95b8e7107419p-1,-0x1.bb67ae8584ca9p0
+sin,0x1.f95b8e7107418p-1,0x1.bb67ae8584caap0
+sin,-0x1.f95b8e7107418p-1,-0x1.bb67ae8584caap0
+sin,0x1.f95b8e7107418p-1,0x1.bb67ae8584cabp0
+sin,-0x1.f95b8e7107418p-1,-0x1.bb67ae8584cabp0
+sin,0x1.b1d8305321616p-2,0x1.bffffffffffffp-2
+sin,-0x1.b1d8305321616p-2,-0x1.bffffffffffffp-2
+sin,0x1.b1d8305321617p-2,0x1.cp-2
+sin,-0x1.b1d8305321617p-2,-0x1.cp-2
+sin,0x1.b1d8305321617p-2,0x1.c000000000001p-2
+sin,-0x1.b1d8305321617p-2,-0x1.c000000000001p-2
+sin,0x1.44eb381cf386ap-1,0x1.5ffffffffffffp-1
+sin,-0x1.44eb381cf386ap-1,-0x1.5ffffffffffffp-1
+sin,0x1.44eb381cf386bp-1,0x1.6p-1
+sin,-0x1.44eb381cf386bp-1,-0x1.6p-1
+sin,0x1.44eb381cf386cp-1,0x1.6000000000001p-1
+sin,-0x1.44eb381cf386cp-1,-0x1.6000000000001p-1
+sin,0x1.dad902fa8ac86p-1,0x1.2ffffffffffffp0
+sin,-0x1.dad902fa8ac86p-1,-0x1.2ffffffffffffp0
+sin,0x1.dad902fa8ac87p-1,0x1.3p0
+sin,-0x1.dad902fa8ac87p-1,-0x1.3p0
+sin,0x1.dad902fa8ac88p-1,0x1.3000000000001p0
+sin,-0x1.dad902fa8ac88p-1,-0x1.3000000000001p0
+sin,0x1.4b707a7acdedp-1,0x1.37fffffffffffp1
+sin,-0x1.4b707a7acdedp-1,-0x1.37fffffffffffp1
+sin,0x1.4b707a7acdecdp-1,0x1.38p1
+sin,-0x1.4b707a7acdecdp-1,-0x1.38p1
+sin,0x1.4b707a7acdecap-1,0x1.3800000000001p1
+sin,-0x1.4b707a7acdecap-1,-0x1.3800000000001p1
+sin,0x1.066e7eb76f5c6p-4,0x1.069c8b46b3792p-4
+sin,-0x1.066e7eb76f5c6p-4,-0x1.069c8b46b3792p-4
+sin,0x1.05e4761ab8d8fp-3,0x1.069c8b46b3792p-3
+sin,-0x1.05e4761ab8d8fp-3,-0x1.069c8b46b3792p-3
+sin,0x1.877e2cd4f6fdap-3,0x1.89ead0ea0d35bp-3
+sin,-0x1.877e2cd4f6fdap-3,-0x1.89ead0ea0d35bp-3
+sin,0x1.03be06f97cbeep-2,0x1.069c8b46b3792p-2
+sin,-0x1.03be06f97cbeep-2,-0x1.069c8b46b3792p-2
+sin,0x1.42abba8c72fbcp-2,0x1.4843ae1860576p-2
+sin,-0x1.42abba8c72fbcp-2,-0x1.4843ae1860576p-2
+sin,0x1.8045fe64e62dcp-2,0x1.89ead0ea0d35ap-2
+sin,-0x1.8045fe64e62dcp-2,-0x1.89ead0ea0d35ap-2
+sin,0x1.bc4c04d71abbfp-2,0x1.cb91f3bbba13ep-2
+sin,-0x1.bc4c04d71abbfp-2,-0x1.cb91f3bbba13ep-2
+sin,0x1.f67ea975b86ap-2,0x1.069c8b46b3791p-1
+sin,-0x1.f67ea975b86ap-2,-0x1.069c8b46b3791p-1
+sin,0x1.175059bf0d425p-1,0x1.27701caf89e83p-1
+sin,-0x1.175059bf0d425p-1,-0x1.27701caf89e83p-1
+sin,0x1.323b8b1fb4ba2p-1,0x1.4843ae1860575p-1
+sin,-0x1.323b8b1fb4ba2p-1,-0x1.4843ae1860575p-1
+sin,0x1.4be4979c5efb3p-1,0x1.69173f8136c67p-1
+sin,-0x1.4be4979c5efb3p-1,-0x1.69173f8136c67p-1
+sin,0x1.643080d67acc1p-1,0x1.89ead0ea0d359p-1
+sin,-0x1.643080d67acc1p-1,-0x1.89ead0ea0d359p-1
+sin,0x1.7b05b7b6c612ep-1,0x1.aabe6252e3a4bp-1
+sin,-0x1.7b05b7b6c612ep-1,-0x1.aabe6252e3a4bp-1
+sin,0x1.904c37505de49p-1,0x1.cb91f3bbba13dp-1
+sin,-0x1.904c37505de49p-1,-0x1.cb91f3bbba13dp-1
+sin,0x1.a3ed9e252938ap-1,0x1.ec6585249082fp-1
+sin,-0x1.a3ed9e252938ap-1,-0x1.ec6585249082fp-1
+sin,0x1.b5d545b109bf9p-1,0x1.069c8b46b3791p0
+sin,-0x1.b5d545b109bf9p-1,-0x1.069c8b46b3791p0
+sin,0x1.c5f058230e7fdp-1,0x1.170653fb1eb0ap0
+sin,-0x1.c5f058230e7fdp-1,-0x1.170653fb1eb0ap0
+sin,0x1.d42de42dce134p-1,0x1.27701caf89e83p0
+sin,-0x1.d42de42dce134p-1,-0x1.27701caf89e83p0
+sin,0x1.e07eeeda109cbp-1,0x1.37d9e563f51fcp0
+sin,-0x1.e07eeeda109cbp-1,-0x1.37d9e563f51fcp0
+sin,0x1.ead6834909b93p-1,0x1.4843ae1860575p0
+sin,-0x1.ead6834909b93p-1,-0x1.4843ae1860575p0
+sin,0x1.f329c0558e968p-1,0x1.58ad76cccb8eep0
+sin,-0x1.f329c0558e968p-1,-0x1.58ad76cccb8eep0
+sin,0x1.f96fe405f1ac6p-1,0x1.69173f8136c67p0
+sin,-0x1.f96fe405f1ac6p-1,-0x1.69173f8136c67p0
+sin,0x1.fda254c27a01fp-1,0x1.79810835a1fep0
+sin,-0x1.fda254c27a01fp-1,-0x1.79810835a1fep0
+sin,0x1.ffbca846c4fcap-1,0x1.89ead0ea0d359p0
+sin,-0x1.ffbca846c4fcap-1,-0x1.89ead0ea0d359p0
+sin,0x1.ffbca846c4fcap-1,0x1.9a54999e786d2p0
+sin,-0x1.ffbca846c4fcap-1,-0x1.9a54999e786d2p0
+sin,0x1.fda254c27a02p-1,0x1.aabe6252e3a4bp0
+sin,-0x1.fda254c27a02p-1,-0x1.aabe6252e3a4bp0
+sin,0x1.f96fe405f1ac8p-1,0x1.bb282b074edc4p0
+sin,-0x1.f96fe405f1ac8p-1,-0x1.bb282b074edc4p0
+sin,0x1.f329c0558e96ap-1,0x1.cb91f3bbba13dp0
+sin,-0x1.f329c0558e96ap-1,-0x1.cb91f3bbba13dp0
+sin,0x1.ead6834909b96p-1,0x1.dbfbbc70254b6p0
+sin,-0x1.ead6834909b96p-1,-0x1.dbfbbc70254b6p0
+sin,0x1.e07eeeda109cfp-1,0x1.ec6585249082fp0
+sin,-0x1.e07eeeda109cfp-1,-0x1.ec6585249082fp0
+sin,0x1.d42de42dce139p-1,0x1.fccf4dd8fbba8p0
+sin,-0x1.d42de42dce139p-1,-0x1.fccf4dd8fbba8p0
+sin,0x1.c5f058230e801p-1,0x1.069c8b46b3791p1
+sin,-0x1.c5f058230e801p-1,-0x1.069c8b46b3791p1
+sin,0x1.b5d545b109bfdp-1,0x1.0ed16fa0e914ep1
+sin,-0x1.b5d545b109bfdp-1,-0x1.0ed16fa0e914ep1
+sin,0x1.a3ed9e252938dp-1,0x1.170653fb1eb0bp1
+sin,-0x1.a3ed9e252938dp-1,-0x1.170653fb1eb0bp1
+sin,0x1.904c37505de4cp-1,0x1.1f3b3855544c8p1
+sin,-0x1.904c37505de4cp-1,-0x1.1f3b3855544c8p1
+sin,0x1.7b05b7b6c613p-1,0x1.27701caf89e85p1
+sin,-0x1.7b05b7b6c613p-1,-0x1.27701caf89e85p1
+sin,0x1.643080d67acc1p-1,0x1.2fa50109bf842p1
+sin,-0x1.643080d67acc1p-1,-0x1.2fa50109bf842p1
+sin,0x1.4be4979c5efb2p-1,0x1.37d9e563f51ffp1
+sin,-0x1.4be4979c5efb2p-1,-0x1.37d9e563f51ffp1
+sin,0x1.323b8b1fb4b9fp-1,0x1.400ec9be2abbcp1
+sin,-0x1.323b8b1fb4b9fp-1,-0x1.400ec9be2abbcp1
+sin,0x1.175059bf0d42p-1,0x1.4843ae1860579p1
+sin,-0x1.175059bf0d42p-1,-0x1.4843ae1860579p1
+sin,0x1.f67ea975b8692p-2,0x1.5078927295f36p1
+sin,-0x1.f67ea975b8692p-2,-0x1.5078927295f36p1
+sin,0x1.bc4c04d71abadp-2,0x1.58ad76cccb8f3p1
+sin,-0x1.bc4c04d71abadp-2,-0x1.58ad76cccb8f3p1
+sin,0x1.8045fe64e62c6p-2,0x1.60e25b27012bp1
+sin,-0x1.8045fe64e62c6p-2,-0x1.60e25b27012bp1
+sin,0x1.42abba8c72fa1p-2,0x1.69173f8136c6dp1
+sin,-0x1.42abba8c72fa1p-2,-0x1.69173f8136c6dp1
+sin,0x1.03be06f97cbdp-2,0x1.714c23db6c62ap1
+sin,-0x1.03be06f97cbdp-2,-0x1.714c23db6c62ap1
+sin,0x1.877e2cd4f6f94p-3,0x1.79810835a1fe7p1
+sin,-0x1.877e2cd4f6f94p-3,-0x1.79810835a1fe7p1
+sin,0x1.05e4761ab8d42p-3,0x1.81b5ec8fd79a4p1
+sin,-0x1.05e4761ab8d42p-3,-0x1.81b5ec8fd79a4p1
+sin,0x1.066e7eb76f5ddp-4,0x1.89ead0ea0d35bp1
+sin,-0x1.066e7eb76f5ddp-4,-0x1.89ead0ea0d35bp1
+sin,0x1.03be06f97cbf1p-2,-0x1.81b5ec8fd799fp2
+sin,-0x1.03be06f97cbf1p-2,0x1.81b5ec8fd799fp2
+sin,0x1.f67ea975b86a2p-2,-0x1.714c23db6c626p2
+sin,-0x1.f67ea975b86a2p-2,0x1.714c23db6c626p2
+sin,0x1.643080d67acc2p-1,-0x1.60e25b27012adp2
+sin,-0x1.643080d67acc2p-1,0x1.60e25b27012adp2
+sin,0x1.b5d545b109bf9p-1,-0x1.5078927295f34p2
+sin,-0x1.b5d545b109bf9p-1,0x1.5078927295f34p2
+sin,0x1.ead6834909b93p-1,-0x1.400ec9be2abbbp2
+sin,-0x1.ead6834909b93p-1,0x1.400ec9be2abbbp2
+sin,0x1.ffbca846c4fcap-1,-0x1.2fa50109bf842p2
+sin,-0x1.ffbca846c4fcap-1,0x1.2fa50109bf842p2
+sin,0x1.f329c0558e96ap-1,-0x1.1f3b3855544c9p2
+sin,-0x1.f329c0558e96ap-1,0x1.1f3b3855544c9p2
+sin,0x1.c5f058230e802p-1,-0x1.0ed16fa0e915p2
+sin,-0x1.c5f058230e802p-1,0x1.0ed16fa0e915p2
+sin,0x1.7b05b7b6c6136p-1,-0x1.fccf4dd8fbbaep1
+sin,-0x1.7b05b7b6c6136p-1,0x1.fccf4dd8fbbaep1
+sin,0x1.175059bf0d42fp-1,-0x1.dbfbbc70254bcp1
+sin,-0x1.175059bf0d42fp-1,0x1.dbfbbc70254bcp1
+sin,0x1.42abba8c72fd2p-2,-0x1.bb282b074edcap1
+sin,-0x1.42abba8c72fd2p-2,0x1.bb282b074edcap1
+sin,0x1.066e7eb76f62bp-4,-0x1.9a54999e786d8p1
+sin,-0x1.066e7eb76f62bp-4,0x1.9a54999e786d8p1
+sin,-0x1.877e2cd4f6fa4p-3,-0x1.79810835a1fe6p1
+sin,0x1.877e2cd4f6fa4p-3,0x1.79810835a1fe6p1
+sin,-0x1.bc4c04d71aba6p-2,-0x1.58ad76cccb8f4p1
+sin,0x1.bc4c04d71aba6p-2,0x1.58ad76cccb8f4p1
+sin,-0x1.4be4979c5efa8p-1,-0x1.37d9e563f5202p1
+sin,0x1.4be4979c5efa8p-1,0x1.37d9e563f5202p1
+sin,-0x1.a3ed9e2529382p-1,-0x1.170653fb1eb1p1
+sin,0x1.a3ed9e2529382p-1,0x1.170653fb1eb1p1
+sin,-0x1.e07eeeda109c6p-1,-0x1.ec6585249083cp0
+sin,0x1.e07eeeda109c6p-1,0x1.ec6585249083cp0
+sin,-0x1.fda254c27a01ep-1,-0x1.aabe6252e3a58p0
+sin,0x1.fda254c27a01ep-1,0x1.aabe6252e3a58p0
+sin,-0x1.f96fe405f1acap-1,-0x1.69173f8136c74p0
+sin,0x1.f96fe405f1acap-1,0x1.69173f8136c74p0
+sin,-0x1.d42de42dce13fp-1,-0x1.27701caf89e9p0
+sin,0x1.d42de42dce13fp-1,0x1.27701caf89e9p0
+sin,-0x1.904c37505de59p-1,-0x1.cb91f3bbba157p-1
+sin,0x1.904c37505de59p-1,0x1.cb91f3bbba157p-1
+sin,-0x1.323b8b1fb4bb6p-1,-0x1.4843ae186058ep-1
+sin,0x1.323b8b1fb4bb6p-1,0x1.4843ae186058ep-1
+sin,-0x1.8045fe64e6309p-2,-0x1.89ead0ea0d38ap-2
+sin,0x1.8045fe64e6309p-2,0x1.89ead0ea0d38ap-2
+sin,-0x1.05e4761ab8decp-3,-0x1.069c8b46b37fp-3
+sin,0x1.05e4761ab8decp-3,0x1.069c8b46b37fp-3
+sin,0x1.05e4761ab8d32p-3,0x1.069c8b46b3734p-3
+sin,-0x1.05e4761ab8d32p-3,-0x1.069c8b46b3734p-3
+sin,0x1.8045fe64e62b2p-2,0x1.89ead0ea0d32cp-2
+sin,-0x1.8045fe64e62b2p-2,-0x1.89ead0ea0d32cp-2
+sin,0x1.323b8b1fb4b9p-1,0x1.4843ae186055fp-1
+sin,-0x1.323b8b1fb4b9p-1,-0x1.4843ae186055fp-1
+sin,0x1.904c37505de3cp-1,0x1.cb91f3bbba128p-1
+sin,-0x1.904c37505de3cp-1,-0x1.cb91f3bbba128p-1
+sin,0x1.d42de42dce12bp-1,0x1.27701caf89e78p0
+sin,-0x1.d42de42dce12bp-1,-0x1.27701caf89e78p0
+sin,0x1.f96fe405f1ac2p-1,0x1.69173f8136c5cp0
+sin,-0x1.f96fe405f1ac2p-1,-0x1.69173f8136c5cp0
+sin,0x1.fda254c27a022p-1,0x1.aabe6252e3a4p0
+sin,-0x1.fda254c27a022p-1,-0x1.aabe6252e3a4p0
+sin,0x1.e07eeeda109d7p-1,0x1.ec65852490824p0
+sin,-0x1.e07eeeda109d7p-1,-0x1.ec65852490824p0
+sin,0x1.a3ed9e252939ep-1,0x1.170653fb1eb04p1
+sin,-0x1.a3ed9e252939ep-1,-0x1.170653fb1eb04p1
+sin,0x1.4be4979c5efcdp-1,0x1.37d9e563f51f6p1
+sin,-0x1.4be4979c5efcdp-1,-0x1.37d9e563f51f6p1
+sin,0x1.bc4c04d71abfcp-2,0x1.58ad76cccb8e8p1
+sin,-0x1.bc4c04d71abfcp-2,-0x1.58ad76cccb8e8p1
+sin,0x1.877e2cd4f7061p-3,0x1.79810835a1fdap1
+sin,-0x1.877e2cd4f7061p-3,-0x1.79810835a1fdap1
+sin,-0x1.066e7eb76f4acp-4,0x1.9a54999e786ccp1
+sin,0x1.066e7eb76f4acp-4,-0x1.9a54999e786ccp1
+sin,-0x1.42abba8c72f77p-2,0x1.bb282b074edbep1
+sin,0x1.42abba8c72f77p-2,-0x1.bb282b074edbep1
+sin,-0x1.175059bf0d407p-1,0x1.dbfbbc70254bp1
+sin,0x1.175059bf0d407p-1,-0x1.dbfbbc70254bp1
+sin,-0x1.7b05b7b6c6116p-1,0x1.fccf4dd8fbba2p1
+sin,0x1.7b05b7b6c6116p-1,-0x1.fccf4dd8fbba2p1
+sin,-0x1.c5f058230e7ecp-1,0x1.0ed16fa0e914ap2
+sin,0x1.c5f058230e7ecp-1,-0x1.0ed16fa0e914ap2
+sin,-0x1.f329c0558e96p-1,0x1.1f3b3855544c3p2
+sin,0x1.f329c0558e96p-1,-0x1.1f3b3855544c3p2
+sin,-0x1.ffbca846c4fcbp-1,0x1.2fa50109bf83cp2
+sin,0x1.ffbca846c4fcbp-1,-0x1.2fa50109bf83cp2
+sin,-0x1.ead6834909ba1p-1,0x1.400ec9be2abb5p2
+sin,0x1.ead6834909ba1p-1,-0x1.400ec9be2abb5p2
+sin,-0x1.b5d545b109c12p-1,0x1.5078927295f2ep2
+sin,0x1.b5d545b109c12p-1,-0x1.5078927295f2ep2
+sin,-0x1.643080d67ace4p-1,0x1.60e25b27012a7p2
+sin,0x1.643080d67ace4p-1,-0x1.60e25b27012a7p2
+sin,-0x1.f67ea975b86f6p-2,0x1.714c23db6c62p2
+sin,0x1.f67ea975b86f6p-2,-0x1.714c23db6c62p2
+sin,-0x1.03be06f97cc4dp-2,0x1.81b5ec8fd7999p2
+sin,0x1.03be06f97cc4dp-2,-0x1.81b5ec8fd7999p2
+sin,0x1.efb26ef930c4cp-5,0x1.effffffffffffp-5
+sin,-0x1.efb26ef930c4cp-5,-0x1.effffffffffffp-5
+sin,0x1.efb26ef930c4dp-5,0x1.fp-5
+sin,-0x1.efb26ef930c4dp-5,-0x1.fp-5
+sin,0x1.efb26ef930c4ep-5,0x1.f000000000001p-5
+sin,-0x1.efb26ef930c4ep-5,-0x1.f000000000001p-5
+sin,0x1.f6baaa131de63p-4,0x1.f7fffffffffffp-4
+sin,-0x1.f6baaa131de63p-4,-0x1.f7fffffffffffp-4
+sin,0x1.f6baaa131de64p-4,0x1.f8p-4
+sin,-0x1.f6baaa131de64p-4,-0x1.f8p-4
+sin,0x1.f6baaa131de65p-4,0x1.f800000000001p-4
+sin,-0x1.f6baaa131de65p-4,-0x1.f800000000001p-4
+sin,0x1.4a8c3b4e9c7ffp-3,0x1.4bfffffffffffp-3
+sin,-0x1.4a8c3b4e9c7ffp-3,-0x1.4bfffffffffffp-3
+sin,0x1.4a8c3b4e9c8p-3,0x1.4cp-3
+sin,-0x1.4a8c3b4e9c8p-3,-0x1.4cp-3
+sin,0x1.4a8c3b4e9c801p-3,0x1.4c00000000001p-3
+sin,-0x1.4a8c3b4e9c801p-3,-0x1.4c00000000001p-3
+sin,0x1.2e9cd95baba32p-2,0x1.3333333333332p-2
+sin,-0x1.2e9cd95baba32p-2,-0x1.3333333333332p-2
+sin,0x1.2e9cd95baba33p-2,0x1.3333333333333p-2
+sin,-0x1.2e9cd95baba33p-2,-0x1.3333333333333p-2
+sin,0x1.2e9cd95baba34p-2,0x1.3333333333334p-2
+sin,-0x1.2e9cd95baba34p-2,-0x1.3333333333334p-2
+sin,0x1.3faefc7a5466fp-1,0x1.594317acc4ef8p-1
+sin,-0x1.3faefc7a5466fp-1,-0x1.594317acc4ef8p-1
+sin,0x1.3faefc7a5467p-1,0x1.594317acc4ef9p-1
+sin,-0x1.3faefc7a5467p-1,-0x1.594317acc4ef9p-1
+sin,0x1.3faefc7a5467p-1,0x1.594317acc4efap-1
+sin,-0x1.3faefc7a5467p-1,-0x1.594317acc4efap-1
+sin,0x1.6888a4e134b2ep-1,0x1.8ffffffffffffp-1
+sin,-0x1.6888a4e134b2ep-1,-0x1.8ffffffffffffp-1
+sin,0x1.6888a4e134b2fp-1,0x1.9p-1
+sin,-0x1.6888a4e134b2fp-1,-0x1.9p-1
+sin,0x1.6888a4e134b2fp-1,0x1.9000000000001p-1
+sin,-0x1.6888a4e134b2fp-1,-0x1.9000000000001p-1
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0p0,-0x0.0p0
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,0x1.91f65f10dd813p-5,0x1.921fb54442d17p-5
+sin,-0x1.91f65f10dd813p-5,-0x1.921fb54442d17p-5
+sin,0x1.91f65f10dd814p-5,0x1.921fb54442d18p-5
+sin,-0x1.91f65f10dd814p-5,-0x1.921fb54442d18p-5
+sin,0x1.91f65f10dd815p-5,0x1.921fb54442d19p-5
+sin,-0x1.91f65f10dd815p-5,-0x1.921fb54442d19p-5
+sin,0x1.917a6bc29b42bp-4,0x1.921fb54442d17p-4
+sin,-0x1.917a6bc29b42bp-4,-0x1.921fb54442d17p-4
+sin,0x1.917a6bc29b42cp-4,0x1.921fb54442d18p-4
+sin,-0x1.917a6bc29b42cp-4,-0x1.921fb54442d18p-4
+sin,0x1.917a6bc29b42dp-4,0x1.921fb54442d19p-4
+sin,-0x1.917a6bc29b42dp-4,-0x1.921fb54442d19p-4
+sin,0x1.8f8b83c69a609p-3,0x1.921fb54442d17p-3
+sin,-0x1.8f8b83c69a609p-3,-0x1.921fb54442d17p-3
+sin,0x1.8f8b83c69a60ap-3,0x1.921fb54442d18p-3
+sin,-0x1.8f8b83c69a60ap-3,-0x1.921fb54442d18p-3
+sin,0x1.8f8b83c69a60bp-3,0x1.921fb54442d19p-3
+sin,-0x1.8f8b83c69a60bp-3,-0x1.921fb54442d19p-3
+sin,0x1.87de2a6aea962p-2,0x1.921fb54442d17p-2
+sin,-0x1.87de2a6aea962p-2,-0x1.921fb54442d17p-2
+sin,0x1.87de2a6aea963p-2,0x1.921fb54442d18p-2
+sin,-0x1.87de2a6aea963p-2,-0x1.921fb54442d18p-2
+sin,0x1.87de2a6aea964p-2,0x1.921fb54442d19p-2
+sin,-0x1.87de2a6aea964p-2,-0x1.921fb54442d19p-2
+sin,0x1.6a09e667f3bccp-1,0x1.921fb54442d17p-1
+sin,-0x1.6a09e667f3bccp-1,-0x1.921fb54442d17p-1
+sin,0x1.6a09e667f3bccp-1,0x1.921fb54442d18p-1
+sin,-0x1.6a09e667f3bccp-1,-0x1.921fb54442d18p-1
+sin,0x1.6a09e667f3bcdp-1,0x1.921fb54442d19p-1
+sin,-0x1.6a09e667f3bcdp-1,-0x1.921fb54442d19p-1
+sin,0x1.0p0,0x1.921fb54442d17p0
+sin,-0x1.0p0,-0x1.921fb54442d17p0
+sin,0x1.0p0,0x1.921fb54442d18p0
+sin,-0x1.0p0,-0x1.921fb54442d18p0
+sin,0x1.0p0,0x1.921fb54442d19p0
+sin,-0x1.0p0,-0x1.921fb54442d19p0
+sin,0x1.469898cc51702p-51,0x1.921fb54442d17p1
+sin,-0x1.469898cc51702p-51,-0x1.921fb54442d17p1
+sin,0x1.1a62633145c07p-53,0x1.921fb54442d18p1
+sin,-0x1.1a62633145c07p-53,-0x1.921fb54442d18p1
+sin,-0x1.72cece675d1fdp-52,0x1.921fb54442d19p1
+sin,0x1.72cece675d1fdp-52,-0x1.921fb54442d19p1
+sin,-0x1.469898cc51702p-50,0x1.921fb54442d17p2
+sin,0x1.469898cc51702p-50,-0x1.921fb54442d17p2
+sin,-0x1.1a62633145c07p-52,0x1.921fb54442d18p2
+sin,0x1.1a62633145c07p-52,-0x1.921fb54442d18p2
+sin,0x1.72cece675d1fdp-51,0x1.921fb54442d19p2
+sin,-0x1.72cece675d1fdp-51,-0x1.921fb54442d19p2
+sin,-0x1.469898cc51702p-49,0x1.921fb54442d17p3
+sin,0x1.469898cc51702p-49,-0x1.921fb54442d17p3
+sin,-0x1.1a62633145c07p-51,0x1.921fb54442d18p3
+sin,0x1.1a62633145c07p-51,-0x1.921fb54442d18p3
+sin,0x1.72cece675d1fdp-50,0x1.921fb54442d19p3
+sin,-0x1.72cece675d1fdp-50,-0x1.921fb54442d19p3
+sin,-0x1.469898cc51702p-48,0x1.921fb54442d17p4
+sin,0x1.469898cc51702p-48,-0x1.921fb54442d17p4
+sin,-0x1.1a62633145c07p-50,0x1.921fb54442d18p4
+sin,0x1.1a62633145c07p-50,-0x1.921fb54442d18p4
+sin,0x1.72cece675d1fdp-49,0x1.921fb54442d19p4
+sin,-0x1.72cece675d1fdp-49,-0x1.921fb54442d19p4
+sin,-0x1.469898cc51702p-47,0x1.921fb54442d17p5
+sin,0x1.469898cc51702p-47,-0x1.921fb54442d17p5
+sin,-0x1.1a62633145c07p-49,0x1.921fb54442d18p5
+sin,0x1.1a62633145c07p-49,-0x1.921fb54442d18p5
+sin,0x1.72cece675d1fdp-48,0x1.921fb54442d19p5
+sin,-0x1.72cece675d1fdp-48,-0x1.921fb54442d19p5
+sin,-0x1.469898cc51702p-46,0x1.921fb54442d17p6
+sin,0x1.469898cc51702p-46,-0x1.921fb54442d17p6
+sin,-0x1.1a62633145c07p-48,0x1.921fb54442d18p6
+sin,0x1.1a62633145c07p-48,-0x1.921fb54442d18p6
+sin,0x1.72cece675d1fdp-47,0x1.921fb54442d19p6
+sin,-0x1.72cece675d1fdp-47,-0x1.921fb54442d19p6
+sin,-0x1.469898cc51702p-45,0x1.921fb54442d17p7
+sin,0x1.469898cc51702p-45,-0x1.921fb54442d17p7
+sin,-0x1.1a62633145c07p-47,0x1.921fb54442d18p7
+sin,0x1.1a62633145c07p-47,-0x1.921fb54442d18p7
+sin,0x1.72cece675d1fdp-46,0x1.921fb54442d19p7
+sin,-0x1.72cece675d1fdp-46,-0x1.921fb54442d19p7
+sin,0x1.6a09e667f3bdp-1,0x1.2d97c7f3321d1p1
+sin,-0x1.6a09e667f3bdp-1,-0x1.2d97c7f3321d1p1
+sin,0x1.6a09e667f3bcdp-1,0x1.2d97c7f3321d2p1
+sin,-0x1.6a09e667f3bcdp-1,-0x1.2d97c7f3321d2p1
+sin,0x1.6a09e667f3bcap-1,0x1.2d97c7f3321d3p1
+sin,-0x1.6a09e667f3bcap-1,-0x1.2d97c7f3321d3p1
+sin,-0x1.6a09e667f3bc9p-1,0x1.f6a7a2955385dp1
+sin,0x1.6a09e667f3bc9p-1,-0x1.f6a7a2955385dp1
+sin,-0x1.6a09e667f3bccp-1,0x1.f6a7a2955385ep1
+sin,0x1.6a09e667f3bccp-1,-0x1.f6a7a2955385ep1
+sin,-0x1.6a09e667f3bcep-1,0x1.f6a7a2955385fp1
+sin,0x1.6a09e667f3bcep-1,-0x1.f6a7a2955385fp1
+sin,-0x1.0p0,0x1.2d97c7f3321d1p2
+sin,0x1.0p0,-0x1.2d97c7f3321d1p2
+sin,-0x1.0p0,0x1.2d97c7f3321d2p2
+sin,0x1.0p0,-0x1.2d97c7f3321d2p2
+sin,-0x1.0p0,0x1.2d97c7f3321d3p2
+sin,0x1.0p0,-0x1.2d97c7f3321d3p2
+sin,-0x1.6a09e667f3bd4p-1,0x1.5fdbbe9bba774p2
+sin,0x1.6a09e667f3bd4p-1,-0x1.5fdbbe9bba774p2
+sin,-0x1.6a09e667f3bcep-1,0x1.5fdbbe9bba775p2
+sin,0x1.6a09e667f3bcep-1,-0x1.5fdbbe9bba775p2
+sin,-0x1.6a09e667f3bc8p-1,0x1.5fdbbe9bba776p2
+sin,0x1.6a09e667f3bc8p-1,-0x1.5fdbbe9bba776p2
+sin,0x1.6a09e667f3bc5p-1,0x1.c463abeccb2bap2
+sin,-0x1.6a09e667f3bc5p-1,-0x1.c463abeccb2bap2
+sin,0x1.6a09e667f3bcbp-1,0x1.c463abeccb2bbp2
+sin,-0x1.6a09e667f3bcbp-1,-0x1.c463abeccb2bbp2
+sin,0x1.6a09e667f3bd1p-1,0x1.c463abeccb2bcp2
+sin,-0x1.6a09e667f3bd1p-1,-0x1.c463abeccb2bcp2
+sin,0x1.0p0,0x1.f6a7a2955385dp2
+sin,-0x1.0p0,-0x1.f6a7a2955385dp2
+sin,0x1.0p0,0x1.f6a7a2955385ep2
+sin,-0x1.0p0,-0x1.f6a7a2955385ep2
+sin,0x1.0p0,0x1.f6a7a2955385fp2
+sin,-0x1.0p0,-0x1.f6a7a2955385fp2
+sin,0x1.6a09e667f3bdfp-1,0x1.1475cc9eedeffp3
+sin,-0x1.6a09e667f3bdfp-1,-0x1.1475cc9eedeffp3
+sin,0x1.6a09e667f3bd4p-1,0x1.1475cc9eedfp3
+sin,-0x1.6a09e667f3bd4p-1,-0x1.1475cc9eedfp3
+sin,0x1.6a09e667f3bc9p-1,0x1.1475cc9eedf01p3
+sin,-0x1.6a09e667f3bc9p-1,-0x1.1475cc9eedf01p3
+sin,0x1.34f272993d141p-49,0x1.2d97c7f3321d1p3
+sin,-0x1.34f272993d141p-49,-0x1.2d97c7f3321d1p3
+sin,0x1.a79394c9e8a0ap-52,0x1.2d97c7f3321d2p3
+sin,-0x1.a79394c9e8a0ap-52,-0x1.2d97c7f3321d2p3
+sin,-0x1.961b1acd85d7dp-50,0x1.2d97c7f3321d3p3
+sin,0x1.961b1acd85d7dp-50,-0x1.2d97c7f3321d3p3
+sin,-0x1.6a09e667f3bb9p-1,0x1.46b9c347764a2p3
+sin,0x1.6a09e667f3bb9p-1,-0x1.46b9c347764a2p3
+sin,-0x1.6a09e667f3bc4p-1,0x1.46b9c347764a3p3
+sin,0x1.6a09e667f3bc4p-1,-0x1.46b9c347764a3p3
+sin,-0x1.6a09e667f3bdp-1,0x1.46b9c347764a4p3
+sin,0x1.6a09e667f3bdp-1,-0x1.46b9c347764a4p3
+sin,-0x1.0p0,0x1.5fdbbe9bba774p3
+sin,0x1.0p0,-0x1.5fdbbe9bba774p3
+sin,-0x1.0p0,0x1.5fdbbe9bba775p3
+sin,0x1.0p0,-0x1.5fdbbe9bba775p3
+sin,-0x1.0p0,0x1.5fdbbe9bba776p3
+sin,0x1.0p0,-0x1.5fdbbe9bba776p3
+sin,-0x1.6a09e667f3bep-1,0x1.78fdb9effea45p3
+sin,0x1.6a09e667f3bep-1,-0x1.78fdb9effea45p3
+sin,-0x1.6a09e667f3bd5p-1,0x1.78fdb9effea46p3
+sin,0x1.6a09e667f3bd5p-1,-0x1.78fdb9effea46p3
+sin,-0x1.6a09e667f3bcap-1,0x1.78fdb9effea47p3
+sin,0x1.6a09e667f3bcap-1,-0x1.78fdb9effea47p3
+sin,0x1.6a09e667f3bb8p-1,0x1.ab41b09886fe8p3
+sin,-0x1.6a09e667f3bb8p-1,-0x1.ab41b09886fe8p3
+sin,0x1.6a09e667f3bc4p-1,0x1.ab41b09886fe9p3
+sin,-0x1.6a09e667f3bc4p-1,-0x1.ab41b09886fe9p3
+sin,0x1.6a09e667f3bcfp-1,0x1.ab41b09886feap3
+sin,-0x1.6a09e667f3bcfp-1,-0x1.ab41b09886feap3
+sin,0x1.0p0,0x1.c463abeccb2bap3
+sin,-0x1.0p0,-0x1.c463abeccb2bap3
+sin,0x1.0p0,0x1.c463abeccb2bbp3
+sin,-0x1.0p0,-0x1.c463abeccb2bbp3
+sin,0x1.0p0,0x1.c463abeccb2bcp3
+sin,-0x1.0p0,-0x1.c463abeccb2bcp3
+sin,0x1.6a09e667f3be1p-1,0x1.dd85a7410f58bp3
+sin,-0x1.6a09e667f3be1p-1,-0x1.dd85a7410f58bp3
+sin,0x1.6a09e667f3bd6p-1,0x1.dd85a7410f58cp3
+sin,-0x1.6a09e667f3bd6p-1,-0x1.dd85a7410f58cp3
+sin,0x1.6a09e667f3bcbp-1,0x1.dd85a7410f58dp3
+sin,-0x1.6a09e667f3bcbp-1,-0x1.dd85a7410f58dp3
+sin,0x1.583ebeff65cc2p-49,0x1.f6a7a2955385dp3
+sin,-0x1.583ebeff65cc2p-49,-0x1.f6a7a2955385dp3
+sin,0x1.60fafbfd97309p-51,0x1.f6a7a2955385ep3
+sin,-0x1.60fafbfd97309p-51,-0x1.f6a7a2955385ep3
+sin,-0x1.4f8282013467cp-50,0x1.f6a7a2955385fp3
+sin,0x1.4f8282013467cp-50,-0x1.f6a7a2955385fp3
+sin,-0x1.6a09e667f3ba1p-1,0x1.07e4cef4cbd96p4
+sin,0x1.6a09e667f3ba1p-1,-0x1.07e4cef4cbd96p4
+sin,-0x1.6a09e667f3bb8p-1,0x1.07e4cef4cbd97p4
+sin,0x1.6a09e667f3bb8p-1,-0x1.07e4cef4cbd97p4
+sin,-0x1.6a09e667f3bcep-1,0x1.07e4cef4cbd98p4
+sin,0x1.6a09e667f3bcep-1,-0x1.07e4cef4cbd98p4
+sin,-0x1.0p0,0x1.1475cc9eedeffp4
+sin,0x1.0p0,-0x1.1475cc9eedeffp4
+sin,-0x1.0p0,0x1.1475cc9eedfp4
+sin,0x1.0p0,-0x1.1475cc9eedfp4
+sin,-0x1.0p0,0x1.1475cc9eedf01p4
+sin,0x1.0p0,-0x1.1475cc9eedf01p4
+sin,-0x1.6a09e667f3bedp-1,0x1.2106ca4910068p4
+sin,0x1.6a09e667f3bedp-1,-0x1.2106ca4910068p4
+sin,-0x1.6a09e667f3bd7p-1,0x1.2106ca4910069p4
+sin,0x1.6a09e667f3bd7p-1,-0x1.2106ca4910069p4
+sin,-0x1.6a09e667f3bcp-1,0x1.2106ca491006ap4
+sin,0x1.6a09e667f3bcp-1,-0x1.2106ca491006ap4
+sin,-0x1.34f272993d141p-48,0x1.2d97c7f3321d1p4
+sin,0x1.34f272993d141p-48,-0x1.2d97c7f3321d1p4
+sin,-0x1.a79394c9e8a0ap-51,0x1.2d97c7f3321d2p4
+sin,0x1.a79394c9e8a0ap-51,-0x1.2d97c7f3321d2p4
+sin,0x1.961b1acd85d7dp-49,0x1.2d97c7f3321d3p4
+sin,-0x1.961b1acd85d7dp-49,-0x1.2d97c7f3321d3p4
+sin,0x1.6a09e667f3bap-1,0x1.3a28c59d54339p4
+sin,-0x1.6a09e667f3bap-1,-0x1.3a28c59d54339p4
+sin,0x1.6a09e667f3bb7p-1,0x1.3a28c59d5433ap4
+sin,-0x1.6a09e667f3bb7p-1,-0x1.3a28c59d5433ap4
+sin,0x1.6a09e667f3bcep-1,0x1.3a28c59d5433bp4
+sin,-0x1.6a09e667f3bcep-1,-0x1.3a28c59d5433bp4
+sin,0x1.0p0,0x1.46b9c347764a2p4
+sin,-0x1.0p0,-0x1.46b9c347764a2p4
+sin,0x1.0p0,0x1.46b9c347764a3p4
+sin,-0x1.0p0,-0x1.46b9c347764a3p4
+sin,0x1.0p0,0x1.46b9c347764a4p4
+sin,-0x1.0p0,-0x1.46b9c347764a4p4
+sin,0x1.6a09e667f3beep-1,0x1.534ac0f19860bp4
+sin,-0x1.6a09e667f3beep-1,-0x1.534ac0f19860bp4
+sin,0x1.6a09e667f3bd8p-1,0x1.534ac0f19860cp4
+sin,-0x1.6a09e667f3bd8p-1,-0x1.534ac0f19860cp4
+sin,0x1.6a09e667f3bc1p-1,0x1.534ac0f19860dp4
+sin,-0x1.6a09e667f3bc1p-1,-0x1.534ac0f19860dp4
+sin,0x1.3dc585b2c7422p-48,0x1.5fdbbe9bba774p4
+sin,-0x1.3dc585b2c7422p-48,-0x1.5fdbbe9bba774p4
+sin,0x1.ee2c2d963a10cp-51,0x1.5fdbbe9bba775p4
+sin,-0x1.ee2c2d963a10cp-51,-0x1.5fdbbe9bba775p4
+sin,-0x1.8474f49a717bdp-49,0x1.5fdbbe9bba776p4
+sin,0x1.8474f49a717bdp-49,-0x1.5fdbbe9bba776p4
+sin,-0x1.6a09e667f3b9fp-1,0x1.6c6cbc45dc8dcp4
+sin,0x1.6a09e667f3b9fp-1,-0x1.6c6cbc45dc8dcp4
+sin,-0x1.6a09e667f3bb6p-1,0x1.6c6cbc45dc8ddp4
+sin,0x1.6a09e667f3bb6p-1,-0x1.6c6cbc45dc8ddp4
+sin,-0x1.6a09e667f3bcdp-1,0x1.6c6cbc45dc8dep4
+sin,0x1.6a09e667f3bcdp-1,-0x1.6c6cbc45dc8dep4
+sin,-0x1.0p0,0x1.78fdb9effea45p4
+sin,0x1.0p0,-0x1.78fdb9effea45p4
+sin,-0x1.0p0,0x1.78fdb9effea46p4
+sin,0x1.0p0,-0x1.78fdb9effea46p4
+sin,-0x1.0p0,0x1.78fdb9effea47p4
+sin,0x1.0p0,-0x1.78fdb9effea47p4
+sin,-0x1.6a09e667f3befp-1,0x1.858eb79a20baep4
+sin,0x1.6a09e667f3befp-1,-0x1.858eb79a20baep4
+sin,-0x1.6a09e667f3bd8p-1,0x1.858eb79a20bafp4
+sin,0x1.6a09e667f3bd8p-1,-0x1.858eb79a20bafp4
+sin,-0x1.6a09e667f3bc2p-1,0x1.858eb79a20bbp4
+sin,0x1.6a09e667f3bc2p-1,-0x1.858eb79a20bbp4
+sin,0x1.fa7299b17573dp-1,0x1.fffffffffffffp62
+sin,-0x1.fa7299b17573dp-1,-0x1.fffffffffffffp62
+sin,0x1.fff6dfd42dc54p-1,0x1.0p63
+sin,-0x1.fff6dfd42dc54p-1,-0x1.0p63
+sin,0x1.e456b818e7397p-1,0x1.0000000000001p63
+sin,-0x1.e456b818e7397p-1,-0x1.0000000000001p63
+sin,-0x1.86dcca0d689e8p-1,0x1.fffffffffffffp26
+sin,0x1.86dcca0d689e8p-1,-0x1.fffffffffffffp26
+sin,-0x1.86dcc9babb0a4p-1,0x1.0p27
+sin,0x1.86dcc9babb0a4p-1,-0x1.0p27
+sin,-0x1.86dcc9155fe18p-1,0x1.0000000000001p27
+sin,0x1.86dcc9155fe18p-1,-0x1.0000000000001p27
+sin,-0x1.8f22f84d42da2p-1,0x1.fffffffffffffp23
+sin,0x1.8f22f84d42da2p-1,-0x1.fffffffffffffp23
+sin,-0x1.8f22f8433d6eep-1,0x1.0p24
+sin,0x1.8f22f8433d6eep-1,-0x1.0p24
+sin,-0x1.8f22f82f32986p-1,0x1.0000000000001p24
+sin,0x1.8f22f82f32986p-1,-0x1.0000000000001p24
+sin,-0x1.837b9dddc1eacp-1,0x1.fffffffffffffp1
+sin,0x1.837b9dddc1eacp-1,-0x1.fffffffffffffp1
+sin,-0x1.837b9dddc1eaep-1,0x1.0p2
+sin,0x1.837b9dddc1eaep-1,-0x1.0p2
+sin,-0x1.837b9dddc1eb4p-1,0x1.0000000000001p2
+sin,0x1.837b9dddc1eb4p-1,-0x1.0000000000001p2
+sin,0x1.d18f6ead1b447p-1,0x1.fffffffffffffp0
+sin,-0x1.d18f6ead1b447p-1,-0x1.fffffffffffffp0
+sin,0x1.d18f6ead1b446p-1,0x1.0p1
+sin,-0x1.d18f6ead1b446p-1,-0x1.0p1
+sin,0x1.d18f6ead1b444p-1,0x1.0000000000001p1
+sin,-0x1.d18f6ead1b444p-1,-0x1.0000000000001p1
+sin,0x1.aed548f090cedp-1,0x1.fffffffffffffp-1
+sin,-0x1.aed548f090cedp-1,-0x1.fffffffffffffp-1
+sin,0x1.aed548f090ceep-1,0x1.0p0
+sin,-0x1.aed548f090ceep-1,-0x1.0p0
+sin,0x1.aed548f090cefp-1,0x1.0000000000001p0
+sin,-0x1.aed548f090cefp-1,-0x1.0000000000001p0
+sin,0x1.eaee8744b05efp-2,0x1.fffffffffffffp-2
+sin,-0x1.eaee8744b05efp-2,-0x1.fffffffffffffp-2
+sin,0x1.eaee8744b05fp-2,0x1.0p-1
+sin,-0x1.eaee8744b05fp-2,-0x1.0p-1
+sin,0x1.eaee8744b05f2p-2,0x1.0000000000001p-1
+sin,-0x1.eaee8744b05f2p-2,-0x1.0000000000001p-1
+sin,0x1.faaeed4f31576p-3,0x1.fffffffffffffp-3
+sin,-0x1.faaeed4f31576p-3,-0x1.fffffffffffffp-3
+sin,0x1.faaeed4f31577p-3,0x1.0p-2
+sin,-0x1.faaeed4f31577p-3,-0x1.0p-2
+sin,0x1.faaeed4f31579p-3,0x1.0000000000001p-2
+sin,-0x1.faaeed4f31579p-3,-0x1.0000000000001p-2
+sin,0x1.feaaeee86ee35p-4,0x1.fffffffffffffp-4
+sin,-0x1.feaaeee86ee35p-4,-0x1.fffffffffffffp-4
+sin,0x1.feaaeee86ee36p-4,0x1.0p-3
+sin,-0x1.feaaeee86ee36p-4,-0x1.0p-3
+sin,0x1.feaaeee86ee38p-4,0x1.0000000000001p-3
+sin,-0x1.feaaeee86ee38p-4,-0x1.0000000000001p-3
+sin,0x1.ffaaaeeed4edap-5,0x1.fffffffffffffp-5
+sin,-0x1.ffaaaeeed4edap-5,-0x1.fffffffffffffp-5
+sin,0x1.ffaaaeeed4edbp-5,0x1.0p-4
+sin,-0x1.ffaaaeeed4edbp-5,-0x1.0p-4
+sin,0x1.ffaaaeeed4eddp-5,0x1.0000000000001p-4
+sin,-0x1.ffaaaeeed4eddp-5,-0x1.0000000000001p-4
+sin,0x1.ffeaaaeeee86ep-6,0x1.fffffffffffffp-6
+sin,-0x1.ffeaaaeeee86ep-6,-0x1.fffffffffffffp-6
+sin,0x1.ffeaaaeeee86fp-6,0x1.0p-5
+sin,-0x1.ffeaaaeeee86fp-6,-0x1.0p-5
+sin,0x1.ffeaaaeeee871p-6,0x1.0000000000001p-5
+sin,-0x1.ffeaaaeeee871p-6,-0x1.0000000000001p-5
+sin,0x1.fffaaaaeeeed4p-7,0x1.fffffffffffffp-7
+sin,-0x1.fffaaaaeeeed4p-7,-0x1.fffffffffffffp-7
+sin,0x1.fffaaaaeeeed5p-7,0x1.0p-6
+sin,-0x1.fffaaaaeeeed5p-7,-0x1.0p-6
+sin,0x1.fffaaaaeeeed7p-7,0x1.0000000000001p-6
+sin,-0x1.fffaaaaeeeed7p-7,-0x1.0000000000001p-6
+sin,0x1.fffffffaaaaaap-15,0x1.fffffffffffffp-15
+sin,-0x1.fffffffaaaaaap-15,-0x1.fffffffffffffp-15
+sin,0x1.fffffffaaaaabp-15,0x1.0p-14
+sin,-0x1.fffffffaaaaabp-15,-0x1.0p-14
+sin,0x1.fffffffaaaaadp-15,0x1.0000000000001p-14
+sin,-0x1.fffffffaaaaadp-15,-0x1.0000000000001p-14
+sin,0x1.fffffffffffffp-28,0x1.fffffffffffffp-28
+sin,-0x1.fffffffffffffp-28,-0x1.fffffffffffffp-28
+sin,0x1.0p-27,0x1.0p-27
+sin,-0x1.0p-27,-0x1.0p-27
+sin,0x1.0000000000001p-27,0x1.0000000000001p-27
+sin,-0x1.0000000000001p-27,-0x1.0000000000001p-27
+sin,0x1.fffffffffffffp-31,0x1.fffffffffffffp-31
+sin,-0x1.fffffffffffffp-31,-0x1.fffffffffffffp-31
+sin,0x1.0p-30,0x1.0p-30
+sin,-0x1.0p-30,-0x1.0p-30
+sin,0x1.0000000000001p-30,0x1.0000000000001p-30
+sin,-0x1.0000000000001p-30,-0x1.0000000000001p-30
+sin,-0x1.452fc98b34e97p-8,-0x1.fffffffffffffp1023
+sin,0x1.452fc98b34e97p-8,0x1.fffffffffffffp1023
+sin,0x1.452fc98b34e97p-8,0x1.fffffffffffffp1023
+sin,-0x1.452fc98b34e97p-8,-0x1.fffffffffffffp1023
+sin,0x1.452fc98b34e97p-8,0x1.fffffffffffffp1023
+sin,-0x1.452fc98b34e97p-8,-0x1.fffffffffffffp1023
+sin,0x1.daa3677c6ee8ap-1,0x1.ffffffffffffep1023
+sin,-0x1.daa3677c6ee8ap-1,-0x1.ffffffffffffep1023
+sin,0x1.1a62633145c07p-53,0x1.921fb54442d18p1
+sin,-0x1.1a62633145c07p-53,-0x1.921fb54442d18p1
+sin,0x1.0p0,0x1.921fb54442d18p0
+sin,-0x1.0p0,-0x1.921fb54442d18p0
+sin,0x1.aed548f090cefp-1,0x1.0000000000001p0
+sin,-0x1.aed548f090cefp-1,-0x1.0000000000001p0
+sin,0x1.aed548f090ceep-1,0x1.0p0
+sin,-0x1.aed548f090ceep-1,-0x1.0p0
+sin,0x1.aed548f090cedp-1,0x1.fffffffffffffp-1
+sin,-0x1.aed548f090cedp-1,-0x1.fffffffffffffp-1
+sin,0x1.6a09e667f3bccp-1,0x1.921fb54442d18p-1
+sin,-0x1.6a09e667f3bccp-1,-0x1.921fb54442d18p-1
+sin,0x1.0000000000001p-1022,0x1.0000000000001p-1022
+sin,-0x1.0000000000001p-1022,-0x1.0000000000001p-1022
+sin,0x1.0p-1022,0x1.0p-1022
+sin,-0x1.0p-1022,-0x1.0p-1022
+sin,0x0.fffffffffffffp-1022,0x0.fffffffffffffp-1022
+sin,-0x0.fffffffffffffp-1022,-0x0.fffffffffffffp-1022
+sin,0x0.ffffffffffffep-1022,0x0.ffffffffffffep-1022
+sin,-0x0.ffffffffffffep-1022,-0x0.ffffffffffffep-1022
+sin,0x0.0000000000002p-1022,0x0.0000000000002p-1022
+sin,-0x0.0000000000002p-1022,-0x0.0000000000002p-1022
+sin,0x0.0000000000001p-1022,0x0.0000000000001p-1022
+sin,-0x0.0000000000001p-1022,-0x0.0000000000001p-1022
+sin,0x0.0p0,0x0.0p0
+cos,0x1.c1a27ae836f13p-1,0x1.feb1f7920e248p-2
+cos,0x1.c1a27ae836f13p-1,-0x1.feb1f7920e248p-2
+cos,0x1.78daf01036d0dp-1,0x1.7cb7648526f99p-1
+cos,0x1.78daf01036d0dp-1,-0x1.7cb7648526f99p-1
+cos,0x1.ff8eb6a91ecbp-1,0x1.549ec0c0c5afap-5
+cos,0x1.ff8eb6a91ecbp-1,-0x1.549ec0c0c5afap-5
+cos,0x1.fed0476fc75cap-1,0x1.16e534ee3658p-4
+cos,0x1.fed0476fc75cap-1,-0x1.16e534ee3658p-4
+cos,0x1.f10fc61e2c78fp-1,0x1.efeef61d39ac2p-3
+cos,0x1.f10fc61e2c78fp-1,-0x1.efeef61d39ac2p-3
+cos,0x1.434a3645be208p-1,0x1.c65a170474549p-1
+cos,0x1.434a3645be208p-1,-0x1.c65a170474549p-1
+cos,0x1.337fc5b072c53p-3,0x1.6b8a6273d7c21p0
+cos,0x1.337fc5b072c53p-3,-0x1.6b8a6273d7c21p0
+cos,0x1.efa7cddb128fcp-1,-0x1.036f4ba7e90aap-2
+cos,0x1.efa7cddb128fcp-1,0x1.036f4ba7e90aap-2
+cos,0x1.0p0,-0x1.1500766c9df2p-31
+cos,0x1.0p0,0x1.1500766c9df2p-31
+cos,0x1.ec231802917bep-1,-0x1.1e2a1563e068ep-2
+cos,0x1.ec231802917bep-1,0x1.1e2a1563e068ep-2
+cos,0x1.dc044ac92b7fcp-8,-0x1.2115aa73f8d05p5
+cos,0x1.dc044ac92b7fcp-8,0x1.2115aa73f8d05p5
+cos,0x1.d1fa67c50dd53p-4,-0x1.34e3bcdf8f69ap2
+cos,0x1.d1fa67c50dd53p-4,0x1.34e3bcdf8f69ap2
+cos,0x1.e2f8d19fb8db8p-2,-0x1.380000000000bp7
+cos,0x1.e2f8d19fb8db8p-2,0x1.380000000000bp7
+cos,0x1.8da9c90c3eda1p-1,-0x1.440000004p6
+cos,0x1.8da9c90c3eda1p-1,0x1.440000004p6
+cos,0x1.b59b320603f83p-1,-0x1.550c8ee67a4c4p29
+cos,0x1.b59b320603f83p-1,0x1.550c8ee67a4c4p29
+cos,0x1.ffffff7af6c88p-1,-0x1.711789fdb2e8ap-13
+cos,0x1.ffffff7af6c88p-1,0x1.711789fdb2e8ap-13
+cos,0x1.c1b68ebb0b4fep-2,-0x1.77e000002p8
+cos,0x1.c1b68ebb0b4fep-2,0x1.77e000002p8
+cos,0x1.1161e1dad76dcp-4,-0x1.8106561931b43p0
+cos,0x1.1161e1dad76dcp-4,0x1.8106561931b43p0
+cos,0x1.f828c3226b3d7p-5,-0x1.825be2461cad4p0
+cos,0x1.f828c3226b3d7p-5,0x1.825be2461cad4p0
+cos,0x1.f2990d742e9fbp-5,-0x1.8288755803b08p0
+cos,0x1.f2990d742e9fbp-5,0x1.8288755803b08p0
+cos,-0x1.ff150dda7524dp-1,-0x1.8a75701f4ccd3p1
+cos,-0x1.ff150dda7524dp-1,0x1.8a75701f4ccd3p1
+cos,0x1.015c47c32b574p-1,-0x1.b389316f37f37p3
+cos,0x1.015c47c32b574p-1,0x1.b389316f37f37p3
+cos,0x1.d681a366a0534p-1,-0x1.c602c465d7d27p6
+cos,0x1.d681a366a0534p-1,0x1.c602c465d7d27p6
+cos,-0x1.84e896c7543d6p-1,-0x1.cfb81fe69664cp4
+cos,-0x1.84e896c7543d6p-1,0x1.cfb81fe69664cp4
+cos,0x1.fc5dcfddd54cp-1,-0x1.d08f2d86b12c6p13
+cos,0x1.fc5dcfddd54cp-1,0x1.d08f2d86b12c6p13
+cos,0x1.fe83235fbe016p-3,-0x1.de13f0943c494p99
+cos,0x1.fe83235fbe016p-3,0x1.de13f0943c494p99
+cos,-0x1.720321239ec5p-1,-0x1.de3c1f1285e8bp3
+cos,-0x1.720321239ec5p-1,0x1.de3c1f1285e8bp3
+cos,0x1.f7143c8bba407p-4,-0x1.fffffffffff7fp1023
+cos,0x1.f7143c8bba407p-4,0x1.fffffffffff7fp1023
+cos,-0x1.fffe62ecfab75p-1,-0x1.fffffffffffffp1023
+cos,-0x1.fffe62ecfab75p-1,0x1.fffffffffffffp1023
+cos,0x1.055e457ac1227p-5,0x1.0000000000001p51
+cos,0x1.055e457ac1227p-5,-0x1.0000000000001p51
+cos,0x1.c1528065b7d4ep-1,0x1.0000000000003p-1
+cos,0x1.c1528065b7d4ep-1,-0x1.0000000000003p-1
+cos,0x1.0p0,0x1.0000000000003p-32
+cos,0x1.0p0,-0x1.0000000000003p-32
+cos,0x1.fffea444bc05ep-1,0x1.000000000002p150
+cos,0x1.fffea444bc05ep-1,-0x1.000000000002p150
+cos,-0x1.ebddee876f434p-1,0x1.0000000000038p380
+cos,-0x1.ebddee876f434p-1,-0x1.0000000000038p380
+cos,-0x1.f2ffc51dc6968p-1,0x1.0000000000118p380
+cos,-0x1.f2ffc51dc6968p-1,-0x1.0000000000118p380
+cos,-0x1.f8fbb4d358b2p-1,0x1.00000000003ffp641
+cos,-0x1.f8fbb4d358b2p-1,-0x1.00000000003ffp641
+cos,-0x1.aa2265753e668p-2,0x1.0000000001p1
+cos,-0x1.aa2265753e668p-2,-0x1.0000000001p1
+cos,0x1.fd1242c25994dp-1,0x1.000000008p452
+cos,0x1.fd1242c25994dp-1,-0x1.000000008p452
+cos,0x1.fffc0001554dap-1,0x1.00000000effafp-7
+cos,0x1.fffc0001554dap-1,-0x1.00000000effafp-7
+cos,0x1.14a27f2925522p-1,0x1.00000114fefe2p0
+cos,0x1.14a27f2925522p-1,-0x1.00000114fefe2p0
+cos,0x1.bf81e0269c59dp-3,0x1.000007p40
+cos,0x1.bf81e0269c59dp-3,-0x1.000007p40
+cos,0x1.14a26ed1960d6p-1,0x1.00000acadb3d3p0
+cos,0x1.14a26ed1960d6p-1,-0x1.00000acadb3d3p0
+cos,0x1.ffffffffbfffep-1,0x1.00003p-17
+cos,0x1.ffffffffbfffep-1,-0x1.00003p-17
+cos,0x1.ffffffffeffffp-1,0x1.00003ffffffaep-18
+cos,0x1.ffffffffeffffp-1,-0x1.00003ffffffaep-18
+cos,0x1.ffffffffeffffp-1,0x1.00003ffffffffp-18
+cos,0x1.ffffffffeffffp-1,-0x1.00003ffffffffp-18
+cos,-0x1.dab7efeb35baep-2,0x1.00007ffffdeap41
+cos,-0x1.dab7efeb35baep-2,-0x1.00007ffffdeap41
+cos,0x1.fffffffffcp-1,0x1.0000ffff8p-19
+cos,0x1.fffffffffcp-1,-0x1.0000ffff8p-19
+cos,0x1.ffffffffffp-1,0x1.0003fff800051p-20
+cos,0x1.ffffffffffp-1,-0x1.0003fff800051p-20
+cos,0x1.ffffffffffp-1,0x1.0003fff800096p-20
+cos,0x1.ffffffffffp-1,-0x1.0003fff800096p-20
+cos,-0x1.fbf2b71a23a58p-2,0x1.000fd2p334
+cos,-0x1.fbf2b71a23a58p-2,-0x1.000fd2p334
+cos,0x1.fccc87eae7737p-5,0x1.003p514
+cos,0x1.fccc87eae7737p-5,-0x1.003p514
+cos,-0x1.a43f40d92b7edp-7,0x1.00600000015f4p41
+cos,-0x1.a43f40d92b7edp-7,-0x1.00600000015f4p41
+cos,0x1.c11cc38f40ab3p-1,0x1.007p-1
+cos,0x1.c11cc38f40ab3p-1,-0x1.007p-1
+cos,0x1.ffffffffffbfcp-1,0x1.007p-21
+cos,0x1.ffffffffffbfcp-1,-0x1.007p-21
+cos,0x1.e9ba98231f734p-8,0x1.00cp40
+cos,0x1.e9ba98231f734p-8,-0x1.00cp40
+cos,0x1.fefdf48ed649dp-1,0x1.011p-4
+cos,0x1.fefdf48ed649dp-1,-0x1.011p-4
+cos,-0x1.ffc16a0f12ff2p-1,0x1.011p996
+cos,-0x1.ffc16a0f12ff2p-1,-0x1.011p996
+cos,0x1.efd5b61a30a38p-1,0x1.02p-2
+cos,0x1.efd5b61a30a38p-1,-0x1.02p-2
+cos,0x1.c97b8161dc50ap-2,0x1.0204260c18307p59
+cos,0x1.c97b8161dc50ap-2,-0x1.0204260c18307p59
+cos,-0x1.bf26a3c9b9fbfp-2,0x1.02e78a321155ep1
+cos,-0x1.bf26a3c9b9fbfp-2,-0x1.02e78a321155ep1
+cos,0x1.fef806b1f84e5p-1,0x1.04p-4
+cos,0x1.fef806b1f84e5p-1,-0x1.04p-4
+cos,0x1.fe851fbf87d17p-1,0x1.04bde8bb80258p98
+cos,0x1.fe851fbf87d17p-1,-0x1.04bde8bb80258p98
+cos,0x1.70f6a51da8effp-1,0x1.077e749e37ceep236
+cos,0x1.70f6a51da8effp-1,-0x1.077e749e37ceep236
+cos,0x1.6b408c856bda6p-3,0x1.07f8p300
+cos,0x1.6b408c856bda6p-3,-0x1.07f8p300
+cos,0x1.2b2f965ae40fcp-1,0x1.07f9bea1b3546p27
+cos,0x1.2b2f965ae40fcp-1,-0x1.07f9bea1b3546p27
+cos,-0x1.4eed2f3fc76a8p-1,0x1.090d18372f2d5p4
+cos,-0x1.4eed2f3fc76a8p-1,-0x1.090d18372f2d5p4
+cos,0x1.fba59aecee5p-1,0x1.0b4p-3
+cos,0x1.fba59aecee5p-1,-0x1.0b4p-3
+cos,0x1.fffd1bcda7a7dp-1,0x1.0c0d5c2af3c2ep346
+cos,0x1.fffd1bcda7a7dp-1,-0x1.0c0d5c2af3c2ep346
+cos,-0x1.e4dfe83129286p-1,0x1.0d30596ee91fdp216
+cos,-0x1.e4dfe83129286p-1,-0x1.0d30596ee91fdp216
+cos,0x1.fb8432886a284p-2,0x1.0d6p0
+cos,0x1.fb8432886a284p-2,-0x1.0d6p0
+cos,0x1.ffffee202854p-1,0x1.0e9474c68831cp-10
+cos,0x1.ffffee202854p-1,-0x1.0e9474c68831cp-10
+cos,-0x1.b70d3d5584b1bp-2,0x1.113bae4049849p2
+cos,-0x1.b70d3d5584b1bp-2,-0x1.113bae4049849p2
+cos,0x1.fed8df58f626p-1,0x1.12eb87097654p-4
+cos,0x1.fed8df58f626p-1,-0x1.12eb87097654p-4
+cos,0x1.e536ae395dfcep-2,0x1.13cp0
+cos,0x1.e536ae395dfcep-2,-0x1.13cp0
+cos,0x1.fed0476fc75cap-1,0x1.16e534ee3658p-4
+cos,0x1.fed0476fc75cap-1,-0x1.16e534ee3658p-4
+cos,0x1.fb38e82e3193ap-1,0x1.17fffffffea98p-3
+cos,0x1.fb38e82e3193ap-1,-0x1.17fffffffea98p-3
+cos,0x1.fb38e82e3188p-1,0x1.18p-3
+cos,0x1.fb38e82e3188p-1,-0x1.18p-3
+cos,-0x1.e59647f1fe9c7p-1,0x1.1a191ebbb4d7fp7
+cos,-0x1.e59647f1fe9c7p-1,-0x1.1a191ebbb4d7fp7
+cos,-0x1.d0dca1f8715bep-4,0x1.1da84f2b7b1d8p7
+cos,-0x1.d0dca1f8715bep-4,-0x1.1da84f2b7b1d8p7
+cos,0x1.b917ebbc30e1ep-2,0x1.201e973251302p0
+cos,0x1.b917ebbc30e1ep-2,-0x1.201e973251302p0
+cos,0x1.fffadf12ff414p-1,0x1.21e02p-7
+cos,0x1.fffadf12ff414p-1,-0x1.21e02p-7
+cos,-0x1.598a4dab3de5ap-1,0x1.27e29a4b985bfp1
+cos,-0x1.598a4dab3de5ap-1,-0x1.27e29a4b985bfp1
+cos,0x1.fa95c1154abf5p-1,0x1.2a1f28dbfb6cp-3
+cos,0x1.fa95c1154abf5p-1,-0x1.2a1f28dbfb6cp-3
+cos,-0x1.6412293adb7bcp-1,0x1.2b8p1
+cos,-0x1.6412293adb7bcp-1,-0x1.2b8p1
+cos,0x1.fffa518a7d0e7p-1,0x1.31199def72f4dp-7
+cos,0x1.fffa518a7d0e7p-1,-0x1.31199def72f4dp-7
+cos,0x1.f36895fe177f8p-1,0x1.31260e1485014p4
+cos,0x1.f36895fe177f8p-1,-0x1.31260e1485014p4
+cos,0x1.d36207b4fee17p-4,0x1.34e964cd103bdp2
+cos,0x1.d36207b4fee17p-4,-0x1.34e964cd103bdp2
+cos,-0x1.84a37f4fa7616p-1,0x1.37618a0ba785p1
+cos,-0x1.84a37f4fa7616p-1,-0x1.37618a0ba785p1
+cos,-0x1.c830bbc99e229p-39,0x1.379704f5f1eb3p24
+cos,-0x1.c830bbc99e229p-39,-0x1.379704f5f1eb3p24
+cos,0x1.b5daaa233bd5p-3,0x1.3b61dd166d47p2
+cos,0x1.b5daaa233bd5p-3,-0x1.3b61dd166d47p2
+cos,-0x1.ffd00dc4db401p-4,0x1.3c011022acbdp37
+cos,-0x1.ffd00dc4db401p-4,-0x1.3c011022acbdp37
+cos,-0x1.14052b4016ff5p-1,0x1.3e7788e900b7p727
+cos,-0x1.14052b4016ff5p-1,-0x1.3e7788e900b7p727
+cos,0x1.ffffe6a5e4198p-1,0x1.423eafdcc2779p-10
+cos,0x1.ffffe6a5e4198p-1,-0x1.423eafdcc2779p-10
+cos,-0x1.fe09fc3d16feep-6,0x1.4321828c1b538p119
+cos,-0x1.fe09fc3d16feep-6,-0x1.4321828c1b538p119
+cos,0x1.b685d949a27ap-14,0x1.43506cb22975dp22
+cos,0x1.b685d949a27ap-14,-0x1.43506cb22975dp22
+cos,0x1.fe398090e203cp-1,0x1.439f63495786ap67
+cos,0x1.fe398090e203cp-1,-0x1.439f63495786ap67
+cos,0x1.fe6274e000974p-1,0x1.457538a6bd073p-4
+cos,0x1.fe6274e000974p-1,-0x1.457538a6bd073p-4
+cos,0x1.09fcb69359c0ap-1,0x1.478fc08p43
+cos,0x1.09fcb69359c0ap-1,-0x1.478fc08p43
+cos,-0x1.20c2158511e79p-9,0x1.48a45797cbe63p61
+cos,-0x1.20c2158511e79p-9,-0x1.48a45797cbe63p61
+cos,0x1.990d17aae253p-1,0x1.4a62e0e12c173p-1
+cos,0x1.990d17aae253p-1,-0x1.4a62e0e12c173p-1
+cos,0x1.fdd4f1e00b387p-3,0x1.4c596642a9488p9
+cos,0x1.fdd4f1e00b387p-3,-0x1.4c596642a9488p9
+cos,0x1.fe4f141032f38p-1,0x1.4dp-4
+cos,0x1.fe4f141032f38p-1,-0x1.4dp-4
+cos,0x1.94e9f45d43c14p-2,0x1.4f0f308p488
+cos,0x1.94e9f45d43c14p-2,-0x1.4f0f308p488
+cos,0x1.9355f69ad4326p-2,0x1.52f00ep793
+cos,0x1.9355f69ad4326p-2,-0x1.52f00ep793
+cos,0x1.1a19be8bea10ap-1,0x1.52f06c730ec02p2
+cos,0x1.1a19be8bea10ap-1,-0x1.52f06c730ec02p2
+cos,0x1.385d92ec0c734p-1,0x1.53e7d5845fe3dp220
+cos,0x1.385d92ec0c734p-1,-0x1.53e7d5845fe3dp220
+cos,0x1.fffffffffe2f1p-1,0x1.59p-20
+cos,0x1.fffffffffe2f1p-1,-0x1.59p-20
+cos,-0x1.ffd7bc28ded92p-1,0x1.592f1176f098p86
+cos,-0x1.ffd7bc28ded92p-1,-0x1.592f1176f098p86
+cos,-0x1.cee28b3d79799p-1,0x1.5999999dc09dcp1
+cos,-0x1.cee28b3d79799p-1,-0x1.5999999dc09dcp1
+cos,0x1.c1f1eb08c2604p-1,0x1.5bea01p468
+cos,0x1.c1f1eb08c2604p-1,-0x1.5bea01p468
+cos,0x1.fffe35ab09a65p-1,0x1.5cb80a6135e5ap1000
+cos,0x1.fffe35ab09a65p-1,-0x1.5cb80a6135e5ap1000
+cos,-0x1.07b85f606e75dp-3,0x1.5d5be48730d2dp13
+cos,-0x1.07b85f606e75dp-3,-0x1.5d5be48730d2dp13
+cos,0x1.ffffffffff862p-1,0x1.614p-21
+cos,0x1.ffffffffff862p-1,-0x1.614p-21
+cos,-0x1.dd3a806e89cf2p-1,0x1.62adc8a660364p1
+cos,-0x1.dd3a806e89cf2p-1,-0x1.62adc8a660364p1
+cos,-0x1.4308b14f4b6eep-1,0x1.64ef438p142
+cos,-0x1.4308b14f4b6eep-1,-0x1.64ef438p142
+cos,0x1.6623d2eb6add2p-3,0x1.652p0
+cos,0x1.6623d2eb6add2p-3,-0x1.652p0
+cos,0x1.fff832c50f472p-1,0x1.65865b2cb08a2p-7
+cos,0x1.fff832c50f472p-1,-0x1.65865b2cb08a2p-7
+cos,0x1.acc251be33023p-1,0x1.6a937daabc20ep375
+cos,0x1.acc251be33023p-1,-0x1.6a937daabc20ep375
+cos,-0x1.14ae72e6ba22fp-61,0x1.6ac5b262ca1ffp849
+cos,-0x1.14ae72e6ba22fp-61,-0x1.6ac5b262ca1ffp849
+cos,0x1.e0619960a11c6p-2,0x1.6f7bdef7bdef4p3
+cos,0x1.e0619960a11c6p-2,-0x1.6f7bdef7bdef4p3
+cos,0x1.8d23f97901a3p-1,0x1.739ce759ce738p200
+cos,0x1.8d23f97901a3p-1,-0x1.739ce759ce738p200
+cos,0x1.fffff78a14ba1p-1,0x1.7450c3f49d0b2p-11
+cos,0x1.fffff78a14ba1p-1,-0x1.7450c3f49d0b2p-11
+cos,0x1.d6f1c727fb2ccp-4,0x1.749fe53f963fdp0
+cos,0x1.d6f1c727fb2ccp-4,-0x1.749fe53f963fdp0
+cos,-0x1.f284b5028c184p-1,0x1.74af6725c6206p1
+cos,-0x1.f284b5028c184p-1,-0x1.74af6725c6206p1
+cos,-0x1.f3165a0b306b2p-1,0x1.7550d28ffccc4p1
+cos,-0x1.f3165a0b306b2p-1,-0x1.7550d28ffccc4p1
+cos,0x1.d66d2078ebdecp-1,0x1.775e397cd6aap6
+cos,0x1.d66d2078ebdecp-1,-0x1.775e397cd6aap6
+cos,0x1.7af9a13085f53p-1,0x1.799302bf7f29p-1
+cos,0x1.7af9a13085f53p-1,-0x1.799302bf7f29p-1
+cos,0x1.ffdd2fdac0c25p-1,0x1.799fffffffffdp-6
+cos,0x1.ffdd2fdac0c25p-1,-0x1.799fffffffffdp-6
+cos,0x1.fff744f185a73p-1,0x1.7a3692ca9449p-7
+cos,0x1.fff744f185a73p-1,-0x1.7a3692ca9449p-7
+cos,0x1.7a6b326b690fbp-1,0x1.7a66a638ac5b5p-1
+cos,0x1.7a6b326b690fbp-1,-0x1.7a66a638ac5b5p-1
+cos,0x1.671fdb64ffbeep-4,0x1.7ba65462b49ap0
+cos,0x1.671fdb64ffbeep-4,-0x1.7ba65462b49ap0
+cos,0x1.ffa55490f206ep-1,0x1.7cdf37cdf37c9p239
+cos,0x1.ffa55490f206ep-1,-0x1.7cdf37cdf37c9p239
+cos,0x1.4c5b5970a3a49p-4,0x1.7d542565f472ep0
+cos,0x1.4c5b5970a3a49p-4,-0x1.7d542565f472ep0
+cos,0x1.479a5667c63f6p-4,0x1.7da0751649058p0
+cos,0x1.479a5667c63f6p-4,-0x1.7da0751649058p0
+cos,0x1.fff717511dcb5p-1,0x1.7e0ddcda6cc0dp-7
+cos,0x1.fff717511dcb5p-1,-0x1.7e0ddcda6cc0dp-7
+cos,0x1.ffffffffff707p-1,0x1.7f6p-21
+cos,0x1.ffffffffff707p-1,-0x1.7f6p-21
+cos,-0x1.fff9e1554698p-1,0x1.7f90117d44c74p100
+cos,-0x1.fff9e1554698p-1,-0x1.7f90117d44c74p100
+cos,0x1.ffdc006bff7eap-1,0x1.7ffffffffef7ap-6
+cos,0x1.ffdc006bff7eap-1,-0x1.7ffffffffef7ap-6
+cos,0x1.ffdc006bff7e8p-1,0x1.7fffffffffa26p-6
+cos,0x1.ffdc006bff7e8p-1,-0x1.7fffffffffa26p-6
+cos,0x1.ffdc006bff7e7p-1,0x1.7ffffffffff8p-6
+cos,0x1.ffdc006bff7e7p-1,-0x1.7ffffffffff8p-6
+cos,0x1.760718ab44398p-1,0x1.80ep-1
+cos,0x1.760718ab44398p-1,-0x1.80ep-1
+cos,-0x1.0p0,0x1.81ae0dffa3b33p959
+cos,-0x1.0p0,-0x1.81ae0dffa3b33p959
+cos,-0x1.fbdc48125b345p-1,0x1.81d612289c5cfp1
+cos,-0x1.fbdc48125b345p-1,-0x1.81d612289c5cfp1
+cos,0x1.ff9e396651ccap-5,0x1.8220192270a0ep0
+cos,0x1.ff9e396651ccap-5,-0x1.8220192270a0ep0
+cos,0x1.fe2b26dddb5c9p-5,0x1.822bb780e9104p0
+cos,0x1.fe2b26dddb5c9p-5,-0x1.822bb780e9104p0
+cos,0x1.eb87cff7c9115p-5,0x1.82c119c4b8e49p0
+cos,0x1.eb87cff7c9115p-5,-0x1.82c119c4b8e49p0
+cos,0x1.eb87cff7a62b7p-5,0x1.82c119c4b9fc4p0
+cos,0x1.eb87cff7a62b7p-5,-0x1.82c119c4b9fc4p0
+cos,0x1.eb87cff795ab1p-5,0x1.82c119c4ba808p0
+cos,0x1.eb87cff795ab1p-5,-0x1.82c119c4ba808p0
+cos,0x1.de1d17ab0d6a5p-5,0x1.832c9fc76527p0
+cos,0x1.de1d17ab0d6a5p-5,-0x1.832c9fc76527p0
+cos,0x1.dc86e7bec0c45p-5,0x1.833956ce7d1f9p0
+cos,0x1.dc86e7bec0c45p-5,-0x1.833956ce7d1f9p0
+cos,0x1.db03cbb942a7bp-5,0x1.834574eb1c099p0
+cos,0x1.db03cbb942a7bp-5,-0x1.834574eb1c099p0
+cos,0x1.ce431710d1507p-5,0x1.83aba5688e13ep0
+cos,0x1.ce431710d1507p-5,-0x1.83aba5688e13ep0
+cos,0x1.cd46b3a77f6ddp-5,0x1.83b38bbafd75bp0
+cos,0x1.cd46b3a77f6ddp-5,-0x1.83b38bbafd75bp0
+cos,-0x1.ff29bc666bee7p-1,0x1.86a017cb1c31cp16
+cos,-0x1.ff29bc666bee7p-1,-0x1.86a017cb1c31cp16
+cos,-0x1.7968916e4c646p-2,0x1.8720588p392
+cos,-0x1.7968916e4c646p-2,-0x1.8720588p392
+cos,0x1.fb97c7e452918p-1,0x1.88a2288a22888p9
+cos,0x1.fb97c7e452918p-1,-0x1.88a2288a22888p9
+cos,-0x1.ae44a5f01bf63p-1,0x1.8cf013991c308p1000
+cos,-0x1.ae44a5f01bf63p-1,-0x1.8cf013991c308p1000
+cos,0x1.d96e82f71a9dcp-1,0x1.9p-2
+cos,0x1.d96e82f71a9dcp-1,-0x1.9p-2
+cos,0x1.0fd9d5c093df5p-7,0x1.9p0
+cos,0x1.0fd9d5c093df5p-7,-0x1.9p0
+cos,0x1.0fd9d5c05e5fdp-7,0x1.90000000006bp0
+cos,0x1.0fd9d5c05e5fdp-7,-0x1.90000000006bp0
+cos,0x1.bc8be725417d8p-1,0x1.900c206d44162p6
+cos,0x1.bc8be725417d8p-1,-0x1.900c206d44162p6
+cos,0x1.fffffffff63b6p-1,0x1.900c2af7baef3p-19
+cos,0x1.fffffffff63b6p-1,-0x1.900c2af7baef3p-19
+cos,0x1.bd464c9352d11p-1,0x1.900f11bd8955dp6
+cos,0x1.bd464c9352d11p-1,-0x1.900f11bd8955dp6
+cos,0x1.fffffda85cdd1p-1,0x1.910b35c3253d4p100
+cos,0x1.fffffda85cdd1p-1,-0x1.910b35c3253d4p100
+cos,0x1.1a62633145c07p-54,0x1.921fb54442d18p0
+cos,0x1.1a62633145c07p-54,-0x1.921fb54442d18p0
+cos,-0x1.2aeef4b9ea1aep-18,0x1.922p0
+cos,-0x1.2aeef4b9ea1aep-18,-0x1.922p0
+cos,-0x1.ffffffffd9048p-18,0x1.9220354442d18p0
+cos,-0x1.ffffffffd9048p-18,-0x1.9220354442d18p0
+cos,-0x1.0p0,0x1.9251f93aeb59dp12
+cos,-0x1.0p0,-0x1.9251f93aeb59dp12
+cos,0x1.ffb8c4d1f78a8p-1,0x1.943be221d909ap2
+cos,0x1.ffb8c4d1f78a8p-1,-0x1.943be221d909ap2
+cos,0x1.fff6011fdddabp-1,0x1.94af699302875p-7
+cos,0x1.fff6011fdddabp-1,-0x1.94af699302875p-7
+cos,0x1.d7954e7a3ee99p-1,0x1.999999ab7b0edp-2
+cos,0x1.d7954e7a3ee99p-1,-0x1.999999ab7b0edp-2
+cos,0x1.d7954e76c8e31p-1,0x1.999999bd4190bp-2
+cos,0x1.d7954e76c8e31p-1,-0x1.999999bd4190bp-2
+cos,0x1.fa23cfb820224p-1,0x1.9bd0f19479a24p2
+cos,0x1.fa23cfb820224p-1,-0x1.9bd0f19479a24p2
+cos,-0x1.6a09e667f3af1p-1,0x1.9c55835e7e83ep8
+cos,-0x1.6a09e667f3af1p-1,-0x1.9c55835e7e83ep8
+cos,0x1.fff59c1255809p-1,0x1.9c9942b14448dp-7
+cos,0x1.fff59c1255809p-1,-0x1.9c9942b14448dp-7
+cos,0x1.ffece5cab4ca5p-1,0x1.9d3d92485e2b5p523
+cos,0x1.ffece5cab4ca5p-1,-0x1.9d3d92485e2b5p523
+cos,-0x1.ff55301d3a781p-5,0x1.a0d068341a08p1000
+cos,-0x1.ff55301d3a781p-5,-0x1.a0d068341a08p1000
+cos,0x1.5a5615acd0dcp-1,0x1.a7ep-1
+cos,0x1.5a5615acd0dcp-1,-0x1.a7ep-1
+cos,0x1.766ad27a1de5p-14,0x1.a858343863965p119
+cos,0x1.766ad27a1de5p-14,-0x1.a858343863965p119
+cos,0x1.6bd4d5be72494p-1,0x1.ab190633d88eap3
+cos,0x1.6bd4d5be72494p-1,-0x1.ab190633d88eap3
+cos,0x1.ffffffffff4a5p-1,0x1.af4bd2f4bd2fp-21
+cos,0x1.ffffffffff4a5p-1,-0x1.af4bd2f4bd2fp-21
+cos,0x1.7ff2934ad29a8p-1,0x1.afa70300aee6p72
+cos,0x1.7ff2934ad29a8p-1,-0x1.afa70300aee6p72
+cos,0x1.ff866aebdce0ap-1,0x1.b5ab427cffb4cp94
+cos,0x1.ff866aebdce0ap-1,-0x1.b5ab427cffb4cp94
+cos,-0x1.f54f5227a4e84p-60,0x1.b951f1572eba5p23
+cos,-0x1.f54f5227a4e84p-60,-0x1.b951f1572eba5p23
+cos,0x1.fffd06d35579cp-1,0x1.b96e5b96e5b91p-8
+cos,0x1.fffd06d35579cp-1,-0x1.b96e5b96e5b91p-8
+cos,-0x1.7c4128e2aff4cp-1,0x1.ba3b18395d17bp8
+cos,-0x1.7c4128e2aff4cp-1,-0x1.ba3b18395d17bp8
+cos,-0x1.0p0,0x1.bab62ed655019p970
+cos,-0x1.0p0,-0x1.bab62ed655019p970
+cos,0x1.ffffff3e53446p-1,0x1.bd55aa411ab46p-13
+cos,0x1.ffffff3e53446p-1,-0x1.bd55aa411ab46p-13
+cos,-0x1.7fdb07b9f77ep-1,0x1.bd616d4fe95cdp36
+cos,-0x1.7fdb07b9f77ep-1,-0x1.bd616d4fe95cdp36
+cos,0x1.ffcf4da76222dp-1,0x1.beap-6
+cos,0x1.ffcf4da76222dp-1,-0x1.beap-6
+cos,-0x1.ddee13357ec6fp-1,0x1.c11516af585a4p1
+cos,-0x1.ddee13357ec6fp-1,-0x1.c11516af585a4p1
+cos,0x1.58cccec059da2p-1,0x1.c75e54de4c06ep2
+cos,0x1.58cccec059da2p-1,-0x1.c75e54de4c06ep2
+cos,-0x1.0p0,0x1.cb44e86bc192bp648
+cos,-0x1.0p0,-0x1.cb44e86bc192bp648
+cos,0x1.0p0,0x1.cb44e86bc192bp649
+cos,0x1.0p0,-0x1.cb44e86bc192bp649
+cos,-0x1.ca281d7fe44bp-1,0x1.cd5a6f8762affp1
+cos,-0x1.ca281d7fe44bp-1,-0x1.cd5a6f8762affp1
+cos,0x1.e80ad4fe54c72p-5,0x1.d0cb95f02ad77p464
+cos,0x1.e80ad4fe54c72p-5,-0x1.d0cb95f02ad77p464
+cos,0x1.0df8eb409efe4p-1,0x1.d31bd604903ap2
+cos,0x1.0df8eb409efe4p-1,-0x1.d31bd604903ap2
+cos,0x1.ff2ae968efe71p-1,0x1.d32f4610180f6p-5
+cos,0x1.ff2ae968efe71p-1,-0x1.d32f4610180f6p-5
+cos,-0x1.cec307a674d3fp-3,0x1.d96e058p488
+cos,-0x1.cec307a674d3fp-3,-0x1.d96e058p488
+cos,-0x1.ac8dbf9cdc955p-5,0x1.db0803c392b4cp15
+cos,-0x1.ac8dbf9cdc955p-5,-0x1.db0803c392b4cp15
+cos,-0x1.ac94870ca6317p-5,0x1.db0803c3ff51dp15
+cos,-0x1.ac94870ca6317p-5,-0x1.db0803c3ff51dp15
+cos,0x1.ff229073fd8b6p-1,0x1.dc4p-5
+cos,0x1.ff229073fd8b6p-1,-0x1.dc4p-5
+cos,0x1.ff21e5f976p-1,0x1.dcf73dcf73dccp-5
+cos,0x1.ff21e5f976p-1,-0x1.dcf73dcf73dccp-5
+cos,0x1.2f011326420e5p-1,0x1.dffffffffffffp-1
+cos,0x1.2f011326420e5p-1,-0x1.dffffffffffffp-1
+cos,0x1.f72c8e16dbc79p-1,0x1.e123691a7c4bep26
+cos,0x1.f72c8e16dbc79p-1,-0x1.e123691a7c4bep26
+cos,-0x1.4b0c6bb623f58p-2,0x1.e666666f9cf49p0
+cos,-0x1.4b0c6bb623f58p-2,-0x1.e666666f9cf49p0
+cos,0x1.fd74b55875885p-1,0x1.e83accfc50b7p995
+cos,0x1.fd74b55875885p-1,-0x1.e83accfc50b7p995
+cos,0x1.fff169b6ab7d1p-1,0x1.e8ep-7
+cos,0x1.fff169b6ab7d1p-1,-0x1.e8ep-7
+cos,0x1.7d39c9f1b0b3cp-1,0x1.eaf5ea5317442p4
+cos,0x1.7d39c9f1b0b3cp-1,-0x1.eaf5ea5317442p4
+cos,0x1.7f13af7081a68p-1,0x1.eb0c2b00b1b83p4
+cos,0x1.7f13af7081a68p-1,-0x1.eb0c2b00b1b83p4
+cos,-0x1.7ad7b88a1fe1p-1,0x1.ebc6b555311c4p15
+cos,-0x1.7ad7b88a1fe1p-1,-0x1.ebc6b555311c4p15
+cos,0x1.b06b2b58a2a24p-5,0x1.ef7bdef7bdef2p239
+cos,0x1.b06b2b58a2a24p-5,-0x1.ef7bdef7bdef2p239
+cos,0x1.fe6ded53172a7p-1,0x1.efbbeefbbeef8p15
+cos,0x1.fe6ded53172a7p-1,-0x1.efbbeefbbeef8p15
+cos,-0x1.fe2bcb87a7e16p-1,0x1.f07c1f07c1ef7p239
+cos,-0x1.fe2bcb87a7e16p-1,-0x1.f07c1f07c1ef7p239
+cos,-0x1.79d08d6b3a883p-1,0x1.f0f2b5e060b29p1
+cos,-0x1.79d08d6b3a883p-1,-0x1.f0f2b5e060b29p1
+cos,0x1.f0d11d321178ep-1,0x1.f4p-3
+cos,0x1.f0d11d321178ep-1,-0x1.f4p-3
+cos,0x1.e3ff5b15f723ep-4,0x1.f43d49f947e87p9
+cos,0x1.e3ff5b15f723ep-4,-0x1.f43d49f947e87p9
+cos,-0x1.6636c9f6a87aap-1,0x1.f7fffffffffffp1
+cos,-0x1.6636c9f6a87aap-1,-0x1.f7fffffffffffp1
+cos,0x1.ffc1be3309286p-1,0x1.f8fffffffffffp-6
+cos,0x1.ffc1be3309286p-1,-0x1.f8fffffffffffp-6
+cos,0x1.ffc1be3309285p-1,0x1.f9p-6
+cos,0x1.ffc1be3309285p-1,-0x1.f9p-6
+cos,-0x1.fffffffcab0d6p-1,0x1.fa0236523ce54p344
+cos,-0x1.fffffffcab0d6p-1,-0x1.fa0236523ce54p344
+cos,0x1.fc0d98ace2308p-1,0x1.fceab54d37dap-4
+cos,0x1.fc0d98ace2308p-1,-0x1.fceab54d37dap-4
+cos,-0x1.9589bca128b92p-4,0x1.fd0072fffffffp2
+cos,-0x1.9589bca128b92p-4,-0x1.fd0072fffffffp2
+cos,-0x1.4d304b07fc898p-2,0x1.fe0f827673422p62
+cos,-0x1.4d304b07fc898p-2,-0x1.fe0f827673422p62
+cos,0x1.c1a27ae836f13p-1,0x1.feb1f7920e248p-2
+cos,0x1.c1a27ae836f13p-1,-0x1.feb1f7920e248p-2
+cos,-0x1.936b64e955979p-1,0x1.feeffffffffc6p995
+cos,-0x1.936b64e955979p-1,-0x1.feeffffffffc6p995
+cos,0x1.fff007147ea57p-1,0x1.ff8ffffffffffp-7
+cos,0x1.fff007147ea57p-1,-0x1.ff8ffffffffffp-7
+cos,0x1.ffffc01bfe443p-1,0x1.ff8ffffffffffp-10
+cos,0x1.ffffc01bfe443p-1,-0x1.ff8ffffffffffp-10
+cos,0x1.7cc9fb75317aep-1,0x1.ff8ffffffffffp870
+cos,0x1.7cc9fb75317aep-1,-0x1.ff8ffffffffffp870
+cos,0x1.d6aea48015589p-1,0x1.ffcfff8p19
+cos,0x1.d6aea48015589p-1,-0x1.ffcfff8p19
+cos,-0x1.6a9972eee19bbp-2,0x1.ffcfff8p365
+cos,-0x1.6a9972eee19bbp-2,-0x1.ffcfff8p365
+cos,-0x1.3aaa15f7544b7p-1,0x1.ffcffffffff6cp720
+cos,-0x1.3aaa15f7544b7p-1,-0x1.ffcffffffff6cp720
+cos,0x1.3f164bce055c5p-1,0x1.ffcfffffffff9p320
+cos,0x1.3f164bce055c5p-1,-0x1.ffcfffffffff9p320
+cos,0x1.fffff002fff15p-1,0x1.ffcffffffffffp-11
+cos,0x1.fffff002fff15p-1,-0x1.ffcffffffffffp-11
+cos,-0x1.ffffff987f986p-1,0x1.ffcffffffffffp405
+cos,-0x1.ffffff987f986p-1,-0x1.ffcffffffffffp405
+cos,-0x1.ffff6235a25eep-1,0x1.ffcffffffffffp567
+cos,-0x1.ffff6235a25eep-1,-0x1.ffcffffffffffp567
+cos,0x1.fdf11ae4608b1p-3,0x1.ffefff8ffffffp16
+cos,0x1.fdf11ae4608b1p-3,-0x1.ffefff8ffffffp16
+cos,0x1.8f5525ab4583cp-1,0x1.ffeffffffffccp995
+cos,0x1.8f5525ab4583cp-1,-0x1.ffeffffffffccp995
+cos,0x1.a0af44a45c057p-8,0x1.ffeffffffffffp77
+cos,0x1.a0af44a45c057p-8,-0x1.ffeffffffffffp77
+cos,-0x1.df7546c31bf8dp-1,0x1.ffeffffffffffp122
+cos,-0x1.df7546c31bf8dp-1,-0x1.ffeffffffffffp122
+cos,-0x1.825a7bea27d5bp-1,0x1.ffeffffffffffp179
+cos,-0x1.825a7bea27d5bp-1,-0x1.ffeffffffffffp179
+cos,-0x1.1be2ab2078d54p-1,0x1.ffeffffffffffp238
+cos,-0x1.1be2ab2078d54p-1,-0x1.ffeffffffffffp238
+cos,-0x1.a4cc5f838f529p-7,0x1.fff0000002511p492
+cos,-0x1.a4cc5f838f529p-7,-0x1.fff0000002511p492
+cos,0x1.f16437d6119f9p-10,0x1.fff1fffffffffp41
+cos,0x1.f16437d6119f9p-10,-0x1.fff1fffffffffp41
+cos,0x1.898324c2f1cfcp-11,0x1.ffffc7fffffffp45
+cos,0x1.898324c2f1cfcp-11,-0x1.ffffc7fffffffp45
+cos,0x1.f0154c00688f8p-1,0x1.ffffdf1ffffffp-3
+cos,0x1.f0154c00688f8p-1,-0x1.ffffdf1ffffffp-3
+cos,0x1.ffc00157126a8p-1,0x1.fffff8fffffffp-6
+cos,0x1.ffc00157126a8p-1,-0x1.fffff8fffffffp-6
+cos,-0x1.e0d9f0f38c73fp-2,0x1.fffffbfffffffp968
+cos,-0x1.e0d9f0f38c73fp-2,-0x1.fffffbfffffffp968
+cos,0x1.fff4699dd560bp-1,0x1.fffffcfffffffp40
+cos,0x1.fff4699dd560bp-1,-0x1.fffffcfffffffp40
+cos,0x1.ff0015559f228p-1,0x1.ffffff000004p-5
+cos,0x1.ff0015559f228p-1,-0x1.ffffff000004p-5
+cos,-0x1.9c6951cccd39cp-2,0x1.ffffff8p119
+cos,-0x1.9c6951cccd39cp-2,-0x1.ffffff8p119
+cos,-0x1.f2c2263590035p-1,0x1.ffffff8p192
+cos,-0x1.f2c2263590035p-1,-0x1.ffffff8p192
+cos,0x1.c7884d6cfb551p-1,0x1.ffffff8p543
+cos,0x1.c7884d6cfb551p-1,-0x1.ffffff8p543
+cos,0x1.e66c79e776a1fp-2,0x1.ffffffc3fffffp500
+cos,0x1.e66c79e776a1fp-2,-0x1.ffffffc3fffffp500
+cos,0x1.c7c9a9c57c0b2p-3,0x1.ffffffe1fffffp700
+cos,0x1.c7c9a9c57c0b2p-3,-0x1.ffffffe1fffffp700
+cos,0x1.7bb28daf5f9aep-1,0x1.ffffffff0f0ffp400
+cos,0x1.7bb28daf5f9aep-1,-0x1.ffffffff0f0ffp400
+cos,0x1.fc015527d8bb3p-1,0x1.ffffffff3ffffp-4
+cos,0x1.fc015527d8bb3p-1,-0x1.ffffffff3ffffp-4
+cos,-0x1.ea5257eb66e3cp-1,0x1.ffffffff8ffffp3
+cos,-0x1.ea5257eb66e3cp-1,-0x1.ffffffff8ffffp3
+cos,-0x1.4eaa606dbef97p-1,0x1.fffffffffbcffp1
+cos,-0x1.4eaa606dbef97p-1,-0x1.fffffffffbcffp1
+cos,-0x1.fc9cd6b5f0095p-1,0x1.fffffffffe0b5p720
+cos,-0x1.fc9cd6b5f0095p-1,-0x1.fffffffffe0b5p720
+cos,0x1.e96ac045dd139p-3,0x1.fffffffffe7ffp41
+cos,0x1.e96ac045dd139p-3,-0x1.fffffffffe7ffp41
+cos,-0x1.fcaf39cfb94d5p-1,0x1.fffffffffee09p720
+cos,-0x1.fcaf39cfb94d5p-1,-0x1.fffffffffee09p720
+cos,0x1.8432232a6d1dap-1,0x1.ffffffffffdffp40
+cos,0x1.8432232a6d1dap-1,-0x1.ffffffffffdffp40
+cos,0x1.9e375143139dap-6,0x1.ffffffffffeffp41
+cos,0x1.9e375143139dap-6,-0x1.ffffffffffeffp41
+cos,0x1.fffc000155552p-1,0x1.fffffffffff4ap-8
+cos,0x1.fffc000155552p-1,-0x1.fffffffffff4ap-8
+cos,0x1.463a895c4ea5dp-1,0x1.fffffffffff78p920
+cos,0x1.463a895c4ea5dp-1,-0x1.fffffffffff78p920
+cos,0x1.3c1a48635cf38p-1,0x1.fffffffffffd5p995
+cos,0x1.3c1a48635cf38p-1,-0x1.fffffffffffd5p995
+cos,0x1.91c4e0708bd48p-1,0x1.fffffffffffe8p720
+cos,0x1.91c4e0708bd48p-1,-0x1.fffffffffffe8p720
+cos,-0x1.3e15cb849b5eap-1,0x1.fffffffffffebp920
+cos,-0x1.3e15cb849b5eap-1,-0x1.fffffffffffebp920
+cos,-0x1.816808349b80ep-1,0x1.ffffffffffff1p245
+cos,-0x1.816808349b80ep-1,-0x1.ffffffffffff1p245
+cos,0x1.4699c814c5f07p-1,0x1.ffffffffffff4p845
+cos,0x1.4699c814c5f07p-1,-0x1.ffffffffffff4p845
+cos,-0x1.815e92b7a2a01p-1,0x1.ffffffffffff4p1020
+cos,-0x1.815e92b7a2a01p-1,-0x1.ffffffffffff4p1020
+cos,-0x1.3e8d028153202p-10,0x1.ffffffffffffcp45
+cos,-0x1.3e8d028153202p-10,-0x1.ffffffffffffcp45
+cos,0x1.7d6765714c786p-1,0x1.ffffffffffffep105
+cos,0x1.7d6765714c786p-1,-0x1.ffffffffffffep105
+cos,-0x1.f869fb14d2569p-3,0x1.ffffffffffffep480
+cos,-0x1.f869fb14d2569p-3,-0x1.ffffffffffffep480
+cos,-0x1.80a75b369d3c4p-1,0x1.ffffffffffffep970
+cos,-0x1.80a75b369d3c4p-1,-0x1.ffffffffffffep970
+cos,-0x1.9dba69e853bd8p-4,0x1.0000000000001p42
+cos,-0x1.9dba69e853bd8p-4,-0x1.0000000000001p42
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0p0
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.0p0,-0x1.0000000000001p-1022
+cos,0x1.0p0,0x1.0000000000001p-1022
+cos,0x1.0p0,-0x1.0p-1022
+cos,0x1.0p0,0x1.0p-1022
+cos,0x1.0p0,-0x0.fffffffffffffp-1022
+cos,0x1.0p0,0x0.fffffffffffffp-1022
+cos,0x1.0p0,0x0.fffffffffffffp-1022
+cos,0x1.0p0,-0x0.fffffffffffffp-1022
+cos,0x1.0p0,0x1.0p-1022
+cos,0x1.0p0,-0x1.0p-1022
+cos,0x1.0p0,0x1.0000000000001p-1022
+cos,0x1.0p0,-0x1.0000000000001p-1022
+cos,0x1.ffffff5c28f5dp-1,0x1.999999999999ap-13
+cos,0x1.ffffff5c28f5dp-1,-0x1.999999999999ap-13
+cos,0x1.fffffd70a3d79p-1,0x1.999999999999ap-12
+cos,0x1.fffffd70a3d79p-1,-0x1.999999999999ap-12
+cos,0x1.fffffa3d70a6ap-1,0x1.3333333333334p-11
+cos,0x1.fffffa3d70a6ap-1,-0x1.3333333333334p-11
+cos,0x1.fffff5c28f64ep-1,0x1.999999999999ap-11
+cos,0x1.fffff5c28f64ep-1,-0x1.999999999999ap-11
+cos,0x1.fffff00000155p-1,0x1.0p-10
+cos,0x1.fffff00000155p-1,-0x1.0p-10
+cos,0x1.ffffe8f5c2bbap-1,0x1.3333333333333p-10
+cos,0x1.ffffe8f5c2bbap-1,-0x1.3333333333333p-10
+cos,0x1.ffffe0a3d75c3p-1,0x1.6666666666666p-10
+cos,0x1.ffffe0a3d75c3p-1,-0x1.6666666666666p-10
+cos,0x1.ffffd70a3dfc7p-1,0x1.9999999999999p-10
+cos,0x1.ffffd70a3dfc7p-1,-0x1.9999999999999p-10
+cos,0x1.ffffcc28f6a28p-1,0x1.cccccccccccccp-10
+cos,0x1.ffffcc28f6a28p-1,-0x1.cccccccccccccp-10
+cos,0x1.fffbcc2a6e87p-1,0x1.0666666666666p-7
+cos,0x1.fffbcc2a6e87p-1,-0x1.0666666666666p-7
+cos,0x1.fff30a4b6fcc1p-1,0x1.cccccccccccccp-7
+cos,0x1.fff30a4b6fcc1p-1,-0x1.cccccccccccccp-7
+cos,0x1.ffe57a780f38cp-1,0x1.4999999999999p-6
+cos,0x1.ffe57a780f38cp-1,-0x1.4999999999999p-6
+cos,0x1.ffd31cd0e1d63p-1,0x1.accccccccccccp-6
+cos,0x1.ffd31cd0e1d63p-1,-0x1.accccccccccccp-6
+cos,0x1.ffbbf18207543p-1,0x1.08p-5
+cos,0x1.ffbbf18207543p-1,-0x1.08p-5
+cos,0x1.ff9ff8c3299f5p-1,0x1.399999999999ap-5
+cos,0x1.ff9ff8c3299f5p-1,-0x1.399999999999ap-5
+cos,0x1.ff7f32d77c5b2p-1,0x1.6b33333333334p-5
+cos,0x1.ff7f32d77c5b2p-1,-0x1.6b33333333334p-5
+cos,0x1.ff59a00dbc409p-1,0x1.9cccccccccccep-5
+cos,0x1.ff59a00dbc409p-1,-0x1.9cccccccccccep-5
+cos,0x1.ff2f40c02e60fp-1,0x1.ce66666666666p-5
+cos,0x1.ff2f40c02e60fp-1,-0x1.ce66666666666p-5
+cos,0x1.8ca46c7d8975ep-1,0x1.5e7fc4369bdadp-1
+cos,0x1.8ca46c7d8975ep-1,-0x1.5e7fc4369bdadp-1
+cos,0x1.0b5d3802fc799p-2,0x1.4e7fc4369bdadp0
+cos,0x1.0b5d3802fc799p-2,-0x1.4e7fc4369bdadp0
+cos,-0x1.66b96f53323afp-2,0x1.edbfa651e9c84p0
+cos,-0x1.66b96f53323afp-2,-0x1.edbfa651e9c84p0
+cos,-0x1.a93554888c33p-1,0x1.467fc4369bdadp1
+cos,-0x1.a93554888c33p-1,-0x1.467fc4369bdadp1
+cos,-0x1.ffc00155527d3p-1,0x1.961fb54442d18p1
+cos,-0x1.ffc00155527d3p-1,-0x1.961fb54442d18p1
+cos,-0x1.96907c5c7c25cp-1,0x1.e5bfa651e9c83p1
+cos,-0x1.96907c5c7c25cp-1,-0x1.e5bfa651e9c83p1
+cos,-0x1.2a1e5a50f948dp-2,0x1.1aafcbafc85f7p2
+cos,-0x1.2a1e5a50f948dp-2,-0x1.1aafcbafc85f7p2
+cos,0x1.4894f695dc56cp-2,0x1.427fc4369bdadp2
+cos,0x1.4894f695dc56cp-2,-0x1.427fc4369bdadp2
+cos,0x1.a016ea3a692cep-1,0x1.6a4fbcbd6f562p2
+cos,0x1.a016ea3a692cep-1,-0x1.6a4fbcbd6f562p2
+cos,0x1.a30a69f5537ecp-1,0x1.6af2eff0a2896p2
+cos,0x1.a30a69f5537ecp-1,-0x1.6af2eff0a2896p2
+cos,0x1.5bd62e8b04ad6p-2,0x1.43c62a9d02414p2
+cos,0x1.5bd62e8b04ad6p-2,-0x1.43c62a9d02414p2
+cos,-0x1.0cb71f671e634p-2,0x1.1c99654961f92p2
+cos,-0x1.0cb71f671e634p-2,-0x1.1c99654961f92p2
+cos,-0x1.89d86aa8521c1p-1,0x1.ead93feb8361fp1
+cos,-0x1.89d86aa8521c1p-1,-0x1.ead93feb8361fp1
+cos,-0x1.fe51ac554a16bp-1,0x1.9c7fb54442d1ap1
+cos,-0x1.fe51ac554a16bp-1,-0x1.9c7fb54442d1ap1
+cos,-0x1.b97c04d08bc5dp-1,0x1.4e262a9d02415p1
+cos,-0x1.b97c04d08bc5dp-1,-0x1.4e262a9d02415p1
+cos,-0x1.a8ac8a3e58f6dp-2,0x1.ff993feb8362p0
+cos,-0x1.a8ac8a3e58f6dp-2,-0x1.ff993feb8362p0
+cos,0x1.77a8b9b3d254bp-3,0x1.62e62a9d02416p0
+cos,0x1.77a8b9b3d254bp-3,-0x1.62e62a9d02416p0
+cos,0x1.6e1061205dd79p-1,0x1.8c662a9d02419p-1
+cos,0x1.6e1061205dd79p-1,-0x1.8c662a9d02419p-1
+cos,-0x1.682f3cc3c7a09p-4,-0x1.a8aa1d11c44ffp0
+cos,-0x1.682f3cc3c7a09p-4,0x1.a8aa1d11c44ffp0
+cos,-0x1.e6669a270c36dp-7,-0x1.95ec8b9e03d54p0
+cos,-0x1.e6669a270c36dp-7,0x1.95ec8b9e03d54p0
+cos,0x1.ddd1ec25e209fp-5,-0x1.832efa2a435a9p0
+cos,0x1.ddd1ec25e209fp-5,0x1.832efa2a435a9p0
+cos,0x1.0cab9115640dap-3,-0x1.707168b682dfep0
+cos,0x1.0cab9115640dap-3,0x1.707168b682dfep0
+cos,0x1.a0723a95492eep-3,-0x1.5db3d742c2653p0
+cos,0x1.a0723a95492eep-3,0x1.5db3d742c2653p0
+cos,0x1.18fee96a1a586p-2,-0x1.4af645cf01ea8p0
+cos,0x1.18fee96a1a586p-2,0x1.4af645cf01ea8p0
+cos,0x1.6043621b13be3p-2,-0x1.3838b45b416fdp0
+cos,0x1.6043621b13be3p-2,0x1.3838b45b416fdp0
+cos,0x1.a5a4ccf40d9dap-2,-0x1.257b22e780f52p0
+cos,0x1.a5a4ccf40d9dap-2,0x1.257b22e780f52p0
+cos,0x1.e8c405f36f85cp-2,-0x1.12bd9173c07abp0
+cos,0x1.e8c405f36f85cp-2,0x1.12bd9173c07abp0
+cos,0x1.26976a6c4e0f8p-1,-0x1.ea5c3ed5b385p-1
+cos,0x1.26976a6c4e0f8p-1,0x1.ea5c3ed5b385p-1
+cos,0x1.3805a1882009fp-1,-0x1.d4b87dab670ap-1
+cos,0x1.3805a1882009fp-1,0x1.d4b87dab670ap-1
+cos,0x1.48e52e0a65bcbp-1,-0x1.bf14bc811a8fp-1
+cos,0x1.48e52e0a65bcbp-1,0x1.bf14bc811a8fp-1
+cos,0x1.592e58ea0a9efp-1,-0x1.a970fb56ce14p-1
+cos,0x1.592e58ea0a9efp-1,0x1.a970fb56ce14p-1
+cos,0x1.68d9afe052d1fp-1,-0x1.93cd3a2c8199p-1
+cos,0x1.68d9afe052d1fp-1,0x1.93cd3a2c8199p-1
+cos,0x1.77e008d0775e7p-1,-0x1.7e297902351ep-1
+cos,0x1.77e008d0775e7p-1,0x1.7e297902351ep-1
+cos,0x1.863a850e438fep-1,-0x1.6885b7d7e8a3p-1
+cos,0x1.863a850e438fep-1,0x1.6885b7d7e8a3p-1
+cos,0x1.93e2948233fcep-1,-0x1.52e1f6ad9c28p-1
+cos,0x1.93e2948233fcep-1,0x1.52e1f6ad9c28p-1
+cos,0x1.a0d1f8a9a791dp-1,-0x1.3d3e35834fadp-1
+cos,0x1.a0d1f8a9a791dp-1,0x1.3d3e35834fadp-1
+cos,0x1.bc6bd861e13dep-1,-0x1.0a0b02501c799p-1
+cos,0x1.bc6bd861e13dep-1,0x1.0a0b02501c799p-1
+cos,0x1.ca59c6fa3d9cep-1,-0x1.d8f7208e6b82cp-2
+cos,0x1.ca59c6fa3d9cep-1,0x1.d8f7208e6b82cp-2
+cos,0x1.d6c0b125791dp-1,-0x1.9dd83c7c9e126p-2
+cos,0x1.d6c0b125791dp-1,0x1.9dd83c7c9e126p-2
+cos,0x1.e196026182986p-1,-0x1.62b9586ad0a2p-2
+cos,0x1.e196026182986p-1,0x1.62b9586ad0a2p-2
+cos,0x1.ead07cc635696p-1,-0x1.279a74590331ap-2
+cos,0x1.ead07cc635696p-1,0x1.279a74590331ap-2
+cos,0x1.f26840e7b2189p-1,-0x1.d8f7208e6b829p-3
+cos,0x1.f26840e7b2189p-1,0x1.d8f7208e6b829p-3
+cos,0x1.f856d48db797ep-1,-0x1.62b9586ad0a1ep-3
+cos,0x1.f856d48db797ep-1,0x1.62b9586ad0a1ep-3
+cos,0x1.fc97283a42479p-1,-0x1.d8f7208e6b826p-4
+cos,0x1.fc97283a42479p-1,0x1.d8f7208e6b826p-4
+cos,0x1.ff259b7ab9f5p-1,-0x1.d8f7208e6b82dp-5
+cos,0x1.ff259b7ab9f5p-1,0x1.d8f7208e6b82dp-5
+cos,0x1.ff259b7ab9f5p-1,0x1.d8f7208e6b82dp-5
+cos,0x1.ff259b7ab9f5p-1,-0x1.d8f7208e6b82dp-5
+cos,0x1.fc97283a42479p-1,0x1.d8f7208e6b82dp-4
+cos,0x1.fc97283a42479p-1,-0x1.d8f7208e6b82dp-4
+cos,0x1.f856d48db797ep-1,0x1.62b9586ad0a22p-3
+cos,0x1.f856d48db797ep-1,-0x1.62b9586ad0a22p-3
+cos,0x1.f26840e7b2189p-1,0x1.d8f7208e6b82dp-3
+cos,0x1.f26840e7b2189p-1,-0x1.d8f7208e6b82dp-3
+cos,0x1.ead07cc635696p-1,0x1.279a74590331cp-2
+cos,0x1.ead07cc635696p-1,-0x1.279a74590331cp-2
+cos,0x1.e196026182985p-1,0x1.62b9586ad0a22p-2
+cos,0x1.e196026182985p-1,-0x1.62b9586ad0a22p-2
+cos,0x1.d6c0b125791dp-1,0x1.9dd83c7c9e128p-2
+cos,0x1.d6c0b125791dp-1,-0x1.9dd83c7c9e128p-2
+cos,0x1.ca59c6fa3d9cep-1,0x1.d8f7208e6b82ep-2
+cos,0x1.ca59c6fa3d9cep-1,-0x1.d8f7208e6b82ep-2
+cos,0x1.bc6bd861e13dep-1,0x1.0a0b02501c799p-1
+cos,0x1.bc6bd861e13dep-1,-0x1.0a0b02501c799p-1
+cos,0x1.a0d1f8a9a792p-1,0x1.3d3e35834faccp-1
+cos,0x1.a0d1f8a9a792p-1,-0x1.3d3e35834faccp-1
+cos,0x1.93e2948233fd1p-1,0x1.52e1f6ad9c27cp-1
+cos,0x1.93e2948233fd1p-1,-0x1.52e1f6ad9c27cp-1
+cos,0x1.863a850e439p-1,0x1.6885b7d7e8a2cp-1
+cos,0x1.863a850e439p-1,-0x1.6885b7d7e8a2cp-1
+cos,0x1.77e008d0775eap-1,0x1.7e297902351dcp-1
+cos,0x1.77e008d0775eap-1,-0x1.7e297902351dcp-1
+cos,0x1.68d9afe052d22p-1,0x1.93cd3a2c8198cp-1
+cos,0x1.68d9afe052d22p-1,-0x1.93cd3a2c8198cp-1
+cos,0x1.592e58ea0a9f2p-1,0x1.a970fb56ce13cp-1
+cos,0x1.592e58ea0a9f2p-1,-0x1.a970fb56ce13cp-1
+cos,0x1.48e52e0a65bcep-1,0x1.bf14bc811a8ecp-1
+cos,0x1.48e52e0a65bcep-1,-0x1.bf14bc811a8ecp-1
+cos,0x1.3805a188200a2p-1,0x1.d4b87dab6709cp-1
+cos,0x1.3805a188200a2p-1,-0x1.d4b87dab6709cp-1
+cos,0x1.26976a6c4e0fcp-1,0x1.ea5c3ed5b384cp-1
+cos,0x1.26976a6c4e0fcp-1,-0x1.ea5c3ed5b384cp-1
+cos,0x1.e8c405f36f85cp-2,0x1.12bd9173c07abp0
+cos,0x1.e8c405f36f85cp-2,-0x1.12bd9173c07abp0
+cos,0x1.a5a4ccf40d9cbp-2,0x1.257b22e780f56p0
+cos,0x1.a5a4ccf40d9cbp-2,-0x1.257b22e780f56p0
+cos,0x1.6043621b13bd4p-2,0x1.3838b45b41701p0
+cos,0x1.6043621b13bd4p-2,-0x1.3838b45b41701p0
+cos,0x1.18fee96a1a576p-2,0x1.4af645cf01eacp0
+cos,0x1.18fee96a1a576p-2,-0x1.4af645cf01eacp0
+cos,0x1.a0723a95492cfp-3,0x1.5db3d742c2657p0
+cos,0x1.a0723a95492cfp-3,-0x1.5db3d742c2657p0
+cos,0x1.0cab9115640bap-3,0x1.707168b682e02p0
+cos,0x1.0cab9115640bap-3,-0x1.707168b682e02p0
+cos,0x1.ddd1ec25e201fp-5,0x1.832efa2a435adp0
+cos,0x1.ddd1ec25e201fp-5,-0x1.832efa2a435adp0
+cos,-0x1.e6669a270c56dp-7,0x1.95ec8b9e03d58p0
+cos,-0x1.e6669a270c56dp-7,-0x1.95ec8b9e03d58p0
+cos,-0x1.682f3cc3c7a09p-4,0x1.a8aa1d11c44ffp0
+cos,-0x1.682f3cc3c7a09p-4,-0x1.a8aa1d11c44ffp0
+cos,0x1.0cb3469a29ea6p-1,0x1.04aff6d330942p0
+cos,0x1.0cb3469a29ea6p-1,-0x1.04aff6d330942p0
+cos,0x1.0cb228fa7f811p-1,0x1.04b09e98dcdb4p0
+cos,0x1.0cb228fa7f811p-1,-0x1.04b09e98dcdb4p0
+cos,0x1.0cb10b5a61b06p-1,0x1.04b1465e89226p0
+cos,0x1.0cb10b5a61b06p-1,-0x1.04b1465e89226p0
+cos,0x1.0cafedb9d078bp-1,0x1.04b1ee2435698p0
+cos,0x1.0cafedb9d078bp-1,-0x1.04b1ee2435698p0
+cos,0x1.0caed018cbda8p-1,0x1.04b295e9e1b0ap0
+cos,0x1.0caed018cbda8p-1,-0x1.04b295e9e1b0ap0
+cos,0x1.0cadb27753d65p-1,0x1.04b33daf8df7cp0
+cos,0x1.0cadb27753d65p-1,-0x1.04b33daf8df7cp0
+cos,0x1.0cac94d5686cbp-1,0x1.04b3e5753a3eep0
+cos,0x1.0cac94d5686cbp-1,-0x1.04b3e5753a3eep0
+cos,0x1.0cab7733099dfp-1,0x1.04b48d3ae686p0
+cos,0x1.0cab7733099dfp-1,-0x1.04b48d3ae686p0
+cos,0x1.0caa5990376bp-1,0x1.04b5350092ccfp0
+cos,0x1.0caa5990376bp-1,-0x1.04b5350092ccfp0
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0p0
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.ad02c771c35edp-1,0x1.279a74590331bp-1
+cos,0x1.ad02c771c35edp-1,-0x1.279a74590331bp-1
+cos,0x1.ad02c771c35edp-1,0x1.279a74590331cp-1
+cos,0x1.ad02c771c35edp-1,-0x1.279a74590331cp-1
+cos,0x1.ad02c771c35ecp-1,0x1.279a74590331dp-1
+cos,0x1.ad02c771c35ecp-1,-0x1.279a74590331dp-1
+cos,-0x1.48d1ddd2b2b4p-3,0x1.bb67ae8584ca9p0
+cos,-0x1.48d1ddd2b2b4p-3,-0x1.bb67ae8584ca9p0
+cos,-0x1.48d1ddd2b2b47p-3,0x1.bb67ae8584caap0
+cos,-0x1.48d1ddd2b2b47p-3,-0x1.bb67ae8584caap0
+cos,-0x1.48d1ddd2b2b4fp-3,0x1.bb67ae8584cabp0
+cos,-0x1.48d1ddd2b2b4fp-3,-0x1.bb67ae8584cabp0
+cos,0x1.cfc6cfa52adap-1,0x1.bffffffffffffp-2
+cos,0x1.cfc6cfa52adap-1,-0x1.bffffffffffffp-2
+cos,0x1.cfc6cfa52ad9fp-1,0x1.cp-2
+cos,0x1.cfc6cfa52ad9fp-1,-0x1.cp-2
+cos,0x1.cfc6cfa52ad9fp-1,0x1.c000000000001p-2
+cos,0x1.cfc6cfa52ad9fp-1,-0x1.c000000000001p-2
+cos,0x1.8bb105a5dc901p-1,0x1.5ffffffffffffp-1
+cos,0x1.8bb105a5dc901p-1,-0x1.5ffffffffffffp-1
+cos,0x1.8bb105a5dc9p-1,0x1.6p-1
+cos,0x1.8bb105a5dc9p-1,-0x1.6p-1
+cos,0x1.8bb105a5dc9p-1,0x1.6000000000001p-1
+cos,0x1.8bb105a5dc9p-1,-0x1.6000000000001p-1
+cos,0x1.7ef4842f0bcd1p-2,0x1.2ffffffffffffp0
+cos,0x1.7ef4842f0bcd1p-2,-0x1.2ffffffffffffp0
+cos,0x1.7ef4842f0bccdp-2,0x1.3p0
+cos,0x1.7ef4842f0bccdp-2,-0x1.3p0
+cos,0x1.7ef4842f0bccap-2,0x1.3000000000001p0
+cos,0x1.7ef4842f0bccap-2,-0x1.3000000000001p0
+cos,-0x1.863efa361dc22p-1,0x1.37fffffffffffp1
+cos,-0x1.863efa361dc22p-1,-0x1.37fffffffffffp1
+cos,-0x1.863efa361dc25p-1,0x1.38p1
+cos,-0x1.863efa361dc25p-1,-0x1.38p1
+cos,-0x1.863efa361dc28p-1,0x1.3800000000001p1
+cos,-0x1.863efa361dc28p-1,-0x1.3800000000001p1
+cos,0x1.fef2b2d21cf6cp-1,0x1.069c8b46b3792p-4
+cos,0x1.fef2b2d21cf6cp-1,-0x1.069c8b46b3792p-4
+cos,0x1.fbcbe693bd8edp-1,0x1.069c8b46b3792p-3
+cos,0x1.fbcbe693bd8edp-1,-0x1.069c8b46b3792p-3
+cos,0x1.f68eebfcbb5e8p-1,0x1.89ead0ea0d35bp-3
+cos,0x1.f68eebfcbb5e8p-1,-0x1.89ead0ea0d35bp-3
+cos,0x1.ef4145b4aedp-1,0x1.069c8b46b3792p-2
+cos,0x1.ef4145b4aedp-1,-0x1.069c8b46b3792p-2
+cos,0x1.e5eaa286fbbc6p-1,0x1.4843ae1860576p-2
+cos,0x1.e5eaa286fbbc6p-1,-0x1.4843ae1860576p-2
+cos,0x1.da94d54dd4c08p-1,0x1.89ead0ea0d35ap-2
+cos,0x1.da94d54dd4c08p-1,-0x1.89ead0ea0d35ap-2
+cos,0x1.cd4bca9cb5c71p-1,0x1.cb91f3bbba13ep-2
+cos,0x1.cd4bca9cb5c71p-1,-0x1.cb91f3bbba13ep-2
+cos,0x1.be1d7c3534c4p-1,0x1.069c8b46b3791p-1
+cos,0x1.be1d7c3534c4p-1,-0x1.069c8b46b3791p-1
+cos,0x1.ad19e2535aa96p-1,0x1.27701caf89e83p-1
+cos,0x1.ad19e2535aa96p-1,-0x1.27701caf89e83p-1
+cos,0x1.9a52e2e0fbcb4p-1,0x1.4843ae1860575p-1
+cos,0x1.9a52e2e0fbcb4p-1,-0x1.4843ae1860575p-1
+cos,0x1.85dc3ea1bbceap-1,0x1.69173f8136c67p-1
+cos,0x1.85dc3ea1bbceap-1,-0x1.69173f8136c67p-1
+cos,0x1.6fcb7c6b8b91ap-1,0x1.89ead0ea0d359p-1
+cos,0x1.6fcb7c6b8b91ap-1,-0x1.89ead0ea0d359p-1
+cos,0x1.5837d2817cf3p-1,0x1.aabe6252e3a4bp-1
+cos,0x1.5837d2817cf3p-1,-0x1.aabe6252e3a4bp-1
+cos,0x1.3f3a0e28bedd4p-1,0x1.cb91f3bbba13dp-1
+cos,0x1.3f3a0e28bedd4p-1,-0x1.cb91f3bbba13dp-1
+cos,0x1.24ec799171643p-1,0x1.ec6585249082fp-1
+cos,0x1.24ec799171643p-1,-0x1.ec6585249082fp-1
+cos,0x1.096ac02ec42c8p-1,0x1.069c8b46b3791p0
+cos,0x1.096ac02ec42c8p-1,-0x1.069c8b46b3791p0
+cos,0x1.d9a3a336edb76p-2,0x1.170653fb1eb0ap0
+cos,0x1.d9a3a336edb76p-2,-0x1.170653fb1eb0ap0
+cos,0x1.9e7f8652b4758p-2,0x1.27701caf89e83p0
+cos,0x1.9e7f8652b4758p-2,-0x1.27701caf89e83p0
+cos,0x1.61a76077aee08p-2,0x1.37d9e563f51fcp0
+cos,0x1.61a76077aee08p-2,-0x1.37d9e563f51fcp0
+cos,0x1.235b331d8f749p-2,0x1.4843ae1860575p0
+cos,0x1.235b331d8f749p-2,-0x1.4843ae1860575p0
+cos,0x1.c7b90e3024594p-3,0x1.58ad76cccb8eep0
+cos,0x1.c7b90e3024594p-3,-0x1.58ad76cccb8eep0
+cos,0x1.46dc4f4ce83dap-3,0x1.69173f8136c67p0
+cos,0x1.46dc4f4ce83dap-3,-0x1.69173f8136c67p0
+cos,0x1.894f70befbb9ap-4,0x1.79810835a1fep0
+cos,0x1.894f70befbb9ap-4,-0x1.79810835a1fep0
+cos,0x1.069107ae9333p-5,0x1.89ead0ea0d359p0
+cos,0x1.069107ae9333p-5,-0x1.89ead0ea0d359p0
+cos,-0x1.069107ae9327ep-5,0x1.9a54999e786d2p0
+cos,-0x1.069107ae9327ep-5,-0x1.9a54999e786d2p0
+cos,-0x1.894f70befbb41p-4,0x1.aabe6252e3a4bp0
+cos,-0x1.894f70befbb41p-4,-0x1.aabe6252e3a4bp0
+cos,-0x1.46dc4f4ce83afp-3,0x1.bb282b074edc4p0
+cos,-0x1.46dc4f4ce83afp-3,-0x1.bb282b074edc4p0
+cos,-0x1.c7b90e3024569p-3,0x1.cb91f3bbba13dp0
+cos,-0x1.c7b90e3024569p-3,-0x1.cb91f3bbba13dp0
+cos,-0x1.235b331d8f734p-2,0x1.dbfbbc70254b6p0
+cos,-0x1.235b331d8f734p-2,-0x1.dbfbbc70254b6p0
+cos,-0x1.61a76077aedf3p-2,0x1.ec6585249082fp0
+cos,-0x1.61a76077aedf3p-2,-0x1.ec6585249082fp0
+cos,-0x1.9e7f8652b4744p-2,0x1.fccf4dd8fbba8p0
+cos,-0x1.9e7f8652b4744p-2,-0x1.fccf4dd8fbba8p0
+cos,-0x1.d9a3a336edb66p-2,0x1.069c8b46b3791p1
+cos,-0x1.d9a3a336edb66p-2,-0x1.069c8b46b3791p1
+cos,-0x1.096ac02ec42c2p-1,0x1.0ed16fa0e914ep1
+cos,-0x1.096ac02ec42c2p-1,-0x1.0ed16fa0e914ep1
+cos,-0x1.24ec79917163ep-1,0x1.170653fb1eb0bp1
+cos,-0x1.24ec79917163ep-1,-0x1.170653fb1eb0bp1
+cos,-0x1.3f3a0e28bedd1p-1,0x1.1f3b3855544c8p1
+cos,-0x1.3f3a0e28bedd1p-1,-0x1.1f3b3855544c8p1
+cos,-0x1.5837d2817cf2fp-1,0x1.27701caf89e85p1
+cos,-0x1.5837d2817cf2fp-1,-0x1.27701caf89e85p1
+cos,-0x1.6fcb7c6b8b91ap-1,0x1.2fa50109bf842p1
+cos,-0x1.6fcb7c6b8b91ap-1,-0x1.2fa50109bf842p1
+cos,-0x1.85dc3ea1bbcebp-1,0x1.37d9e563f51ffp1
+cos,-0x1.85dc3ea1bbcebp-1,-0x1.37d9e563f51ffp1
+cos,-0x1.9a52e2e0fbcb6p-1,0x1.400ec9be2abbcp1
+cos,-0x1.9a52e2e0fbcb6p-1,-0x1.400ec9be2abbcp1
+cos,-0x1.ad19e2535aa9ap-1,0x1.4843ae1860579p1
+cos,-0x1.ad19e2535aa9ap-1,-0x1.4843ae1860579p1
+cos,-0x1.be1d7c3534c44p-1,0x1.5078927295f36p1
+cos,-0x1.be1d7c3534c44p-1,-0x1.5078927295f36p1
+cos,-0x1.cd4bca9cb5c76p-1,0x1.58ad76cccb8f3p1
+cos,-0x1.cd4bca9cb5c76p-1,-0x1.58ad76cccb8f3p1
+cos,-0x1.da94d54dd4c0dp-1,0x1.60e25b27012bp1
+cos,-0x1.da94d54dd4c0dp-1,-0x1.60e25b27012bp1
+cos,-0x1.e5eaa286fbbcbp-1,0x1.69173f8136c6dp1
+cos,-0x1.e5eaa286fbbcbp-1,-0x1.69173f8136c6dp1
+cos,-0x1.ef4145b4aed04p-1,0x1.714c23db6c62ap1
+cos,-0x1.ef4145b4aed04p-1,-0x1.714c23db6c62ap1
+cos,-0x1.f68eebfcbb5ecp-1,0x1.79810835a1fe7p1
+cos,-0x1.f68eebfcbb5ecp-1,-0x1.79810835a1fe7p1
+cos,-0x1.fbcbe693bd8efp-1,0x1.81b5ec8fd79a4p1
+cos,-0x1.fbcbe693bd8efp-1,-0x1.81b5ec8fd79a4p1
+cos,-0x1.fef2b2d21cf6cp-1,0x1.89ead0ea0d35bp1
+cos,-0x1.fef2b2d21cf6cp-1,-0x1.89ead0ea0d35bp1
+cos,0x1.ef4145b4aecffp-1,-0x1.81b5ec8fd799fp2
+cos,0x1.ef4145b4aecffp-1,0x1.81b5ec8fd799fp2
+cos,0x1.be1d7c3534c4p-1,-0x1.714c23db6c626p2
+cos,0x1.be1d7c3534c4p-1,0x1.714c23db6c626p2
+cos,0x1.6fcb7c6b8b919p-1,-0x1.60e25b27012adp2
+cos,0x1.6fcb7c6b8b919p-1,0x1.60e25b27012adp2
+cos,0x1.096ac02ec42c8p-1,-0x1.5078927295f34p2
+cos,0x1.096ac02ec42c8p-1,0x1.5078927295f34p2
+cos,0x1.235b331d8f748p-2,-0x1.400ec9be2abbbp2
+cos,0x1.235b331d8f748p-2,0x1.400ec9be2abbbp2
+cos,0x1.069107ae9332cp-5,-0x1.2fa50109bf842p2
+cos,0x1.069107ae9332cp-5,0x1.2fa50109bf842p2
+cos,-0x1.c7b90e3024569p-3,-0x1.1f3b3855544c9p2
+cos,-0x1.c7b90e3024569p-3,0x1.1f3b3855544c9p2
+cos,-0x1.d9a3a336edb63p-2,-0x1.0ed16fa0e915p2
+cos,-0x1.d9a3a336edb63p-2,0x1.0ed16fa0e915p2
+cos,-0x1.5837d2817cf28p-1,-0x1.fccf4dd8fbbaep1
+cos,-0x1.5837d2817cf28p-1,0x1.fccf4dd8fbbaep1
+cos,-0x1.ad19e2535aa9p-1,-0x1.dbfbbc70254bcp1
+cos,-0x1.ad19e2535aa9p-1,0x1.dbfbbc70254bcp1
+cos,-0x1.e5eaa286fbbc3p-1,-0x1.bb282b074edcap1
+cos,-0x1.e5eaa286fbbc3p-1,0x1.bb282b074edcap1
+cos,-0x1.fef2b2d21cf6bp-1,-0x1.9a54999e786d8p1
+cos,-0x1.fef2b2d21cf6bp-1,0x1.9a54999e786d8p1
+cos,-0x1.f68eebfcbb5ebp-1,-0x1.79810835a1fe6p1
+cos,-0x1.f68eebfcbb5ebp-1,0x1.79810835a1fe6p1
+cos,-0x1.cd4bca9cb5c77p-1,-0x1.58ad76cccb8f4p1
+cos,-0x1.cd4bca9cb5c77p-1,0x1.58ad76cccb8f4p1
+cos,-0x1.85dc3ea1bbcf3p-1,-0x1.37d9e563f5202p1
+cos,-0x1.85dc3ea1bbcf3p-1,0x1.37d9e563f5202p1
+cos,-0x1.24ec79917164ep-1,-0x1.170653fb1eb1p1
+cos,-0x1.24ec79917164ep-1,0x1.170653fb1eb1p1
+cos,-0x1.61a76077aee24p-2,-0x1.ec6585249083cp0
+cos,-0x1.61a76077aee24p-2,0x1.ec6585249083cp0
+cos,-0x1.894f70befbc1p-4,-0x1.aabe6252e3a58p0
+cos,-0x1.894f70befbc1p-4,0x1.aabe6252e3a58p0
+cos,0x1.46dc4f4ce8374p-3,-0x1.69173f8136c74p0
+cos,0x1.46dc4f4ce8374p-3,0x1.69173f8136c74p0
+cos,0x1.9e7f8652b4729p-2,-0x1.27701caf89e9p0
+cos,0x1.9e7f8652b4729p-2,0x1.27701caf89e9p0
+cos,0x1.3f3a0e28bedcp-1,-0x1.cb91f3bbba157p-1
+cos,0x1.3f3a0e28bedcp-1,0x1.cb91f3bbba157p-1
+cos,0x1.9a52e2e0fbca5p-1,-0x1.4843ae186058ep-1
+cos,0x1.9a52e2e0fbca5p-1,0x1.4843ae186058ep-1
+cos,0x1.da94d54dd4bffp-1,-0x1.89ead0ea0d38ap-2
+cos,0x1.da94d54dd4bffp-1,0x1.89ead0ea0d38ap-2
+cos,0x1.fbcbe693bd8eap-1,-0x1.069c8b46b37fp-3
+cos,0x1.fbcbe693bd8eap-1,0x1.069c8b46b37fp-3
+cos,0x1.fbcbe693bd8fp-1,0x1.069c8b46b3734p-3
+cos,0x1.fbcbe693bd8fp-1,-0x1.069c8b46b3734p-3
+cos,0x1.da94d54dd4c11p-1,0x1.89ead0ea0d32cp-2
+cos,0x1.da94d54dd4c11p-1,-0x1.89ead0ea0d32cp-2
+cos,0x1.9a52e2e0fbcc1p-1,0x1.4843ae186055fp-1
+cos,0x1.9a52e2e0fbcc1p-1,-0x1.4843ae186055fp-1
+cos,0x1.3f3a0e28bede4p-1,0x1.cb91f3bbba128p-1
+cos,0x1.3f3a0e28bede4p-1,-0x1.cb91f3bbba128p-1
+cos,0x1.9e7f8652b478p-2,0x1.27701caf89e78p0
+cos,0x1.9e7f8652b478p-2,-0x1.27701caf89e78p0
+cos,0x1.46dc4f4ce8431p-3,0x1.69173f8136c5cp0
+cos,0x1.46dc4f4ce8431p-3,-0x1.69173f8136c5cp0
+cos,-0x1.894f70befba92p-4,0x1.aabe6252e3a4p0
+cos,-0x1.894f70befba92p-4,-0x1.aabe6252e3a4p0
+cos,-0x1.61a76077aedcap-2,0x1.ec65852490824p0
+cos,-0x1.61a76077aedcap-2,-0x1.ec65852490824p0
+cos,-0x1.24ec799171627p-1,0x1.170653fb1eb04p1
+cos,-0x1.24ec799171627p-1,-0x1.170653fb1eb04p1
+cos,-0x1.85dc3ea1bbcd3p-1,0x1.37d9e563f51f6p1
+cos,-0x1.85dc3ea1bbcd3p-1,-0x1.37d9e563f51f6p1
+cos,-0x1.cd4bca9cb5c63p-1,0x1.58ad76cccb8e8p1
+cos,-0x1.cd4bca9cb5c63p-1,-0x1.58ad76cccb8e8p1
+cos,-0x1.f68eebfcbb5e2p-1,0x1.79810835a1fdap1
+cos,-0x1.f68eebfcbb5e2p-1,-0x1.79810835a1fdap1
+cos,-0x1.fef2b2d21cf6ep-1,0x1.9a54999e786ccp1
+cos,-0x1.fef2b2d21cf6ep-1,-0x1.9a54999e786ccp1
+cos,-0x1.e5eaa286fbbd2p-1,0x1.bb282b074edbep1
+cos,-0x1.e5eaa286fbbd2p-1,-0x1.bb282b074edbep1
+cos,-0x1.ad19e2535aaaap-1,0x1.dbfbbc70254bp1
+cos,-0x1.ad19e2535aaaap-1,-0x1.dbfbbc70254bp1
+cos,-0x1.5837d2817cf4bp-1,0x1.fccf4dd8fbba2p1
+cos,-0x1.5837d2817cf4bp-1,-0x1.fccf4dd8fbba2p1
+cos,-0x1.d9a3a336edbb8p-2,0x1.0ed16fa0e914ap2
+cos,-0x1.d9a3a336edbb8p-2,-0x1.0ed16fa0e914ap2
+cos,-0x1.c7b90e3024625p-3,0x1.1f3b3855544c3p2
+cos,-0x1.c7b90e3024625p-3,-0x1.1f3b3855544c3p2
+cos,0x1.069107ae9302dp-5,0x1.2fa50109bf83cp2
+cos,0x1.069107ae9302dp-5,-0x1.2fa50109bf83cp2
+cos,0x1.235b331d8f6ecp-2,0x1.400ec9be2abb5p2
+cos,0x1.235b331d8f6ecp-2,-0x1.400ec9be2abb5p2
+cos,0x1.096ac02ec429fp-1,0x1.5078927295f2ep2
+cos,0x1.096ac02ec429fp-1,-0x1.5078927295f2ep2
+cos,0x1.6fcb7c6b8b8f7p-1,0x1.60e25b27012a7p2
+cos,0x1.6fcb7c6b8b8f7p-1,-0x1.60e25b27012a7p2
+cos,0x1.be1d7c3534c28p-1,0x1.714c23db6c62p2
+cos,0x1.be1d7c3534c28p-1,-0x1.714c23db6c62p2
+cos,0x1.ef4145b4aecf3p-1,0x1.81b5ec8fd7999p2
+cos,0x1.ef4145b4aecf3p-1,-0x1.81b5ec8fd7999p2
+cos,0x1.ff0fd2c96adfcp-1,0x1.effffffffffffp-5
+cos,0x1.ff0fd2c96adfcp-1,-0x1.effffffffffffp-5
+cos,0x1.ff0fd2c96adfcp-1,0x1.fp-5
+cos,0x1.ff0fd2c96adfcp-1,-0x1.fp-5
+cos,0x1.ff0fd2c96adfcp-1,0x1.f000000000001p-5
+cos,0x1.ff0fd2c96adfcp-1,-0x1.f000000000001p-5
+cos,0x1.fc210055467fep-1,0x1.f7fffffffffffp-4
+cos,0x1.fc210055467fep-1,-0x1.f7fffffffffffp-4
+cos,0x1.fc210055467fep-1,0x1.f8p-4
+cos,0x1.fc210055467fep-1,-0x1.f8p-4
+cos,0x1.fc210055467fep-1,0x1.f800000000001p-4
+cos,0x1.fc210055467fep-1,-0x1.f800000000001p-4
+cos,0x1.f94984b2552e2p-1,0x1.4bfffffffffffp-3
+cos,0x1.f94984b2552e2p-1,-0x1.4bfffffffffffp-3
+cos,0x1.f94984b2552e2p-1,0x1.4cp-3
+cos,0x1.f94984b2552e2p-1,-0x1.4cp-3
+cos,0x1.f94984b2552e2p-1,0x1.4c00000000001p-3
+cos,0x1.f94984b2552e2p-1,-0x1.4c00000000001p-3
+cos,0x1.e921dd42f09bbp-1,0x1.3333333333332p-2
+cos,0x1.e921dd42f09bbp-1,-0x1.3333333333332p-2
+cos,0x1.e921dd42f09bap-1,0x1.3333333333333p-2
+cos,0x1.e921dd42f09bap-1,-0x1.3333333333333p-2
+cos,0x1.e921dd42f09bap-1,0x1.3333333333334p-2
+cos,0x1.e921dd42f09bap-1,-0x1.3333333333334p-2
+cos,0x1.8feedb86bf0efp-1,0x1.594317acc4ef8p-1
+cos,0x1.8feedb86bf0efp-1,-0x1.594317acc4ef8p-1
+cos,0x1.8feedb86bf0efp-1,0x1.594317acc4ef9p-1
+cos,0x1.8feedb86bf0efp-1,-0x1.594317acc4ef9p-1
+cos,0x1.8feedb86bf0eep-1,0x1.594317acc4efap-1
+cos,0x1.8feedb86bf0eep-1,-0x1.594317acc4efap-1
+cos,0x1.6b898fa9efb5ep-1,0x1.8ffffffffffffp-1
+cos,0x1.6b898fa9efb5ep-1,-0x1.8ffffffffffffp-1
+cos,0x1.6b898fa9efb5dp-1,0x1.9p-1
+cos,0x1.6b898fa9efb5dp-1,-0x1.9p-1
+cos,0x1.6b898fa9efb5cp-1,0x1.9000000000001p-1
+cos,0x1.6b898fa9efb5cp-1,-0x1.9000000000001p-1
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0p0
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.ff621e3796d7ep-1,0x1.921fb54442d17p-5
+cos,0x1.ff621e3796d7ep-1,-0x1.921fb54442d17p-5
+cos,0x1.ff621e3796d7ep-1,0x1.921fb54442d18p-5
+cos,0x1.ff621e3796d7ep-1,-0x1.921fb54442d18p-5
+cos,0x1.ff621e3796d7ep-1,0x1.921fb54442d19p-5
+cos,0x1.ff621e3796d7ep-1,-0x1.921fb54442d19p-5
+cos,0x1.fd88da3d12526p-1,0x1.921fb54442d17p-4
+cos,0x1.fd88da3d12526p-1,-0x1.921fb54442d17p-4
+cos,0x1.fd88da3d12526p-1,0x1.921fb54442d18p-4
+cos,0x1.fd88da3d12526p-1,-0x1.921fb54442d18p-4
+cos,0x1.fd88da3d12526p-1,0x1.921fb54442d19p-4
+cos,0x1.fd88da3d12526p-1,-0x1.921fb54442d19p-4
+cos,0x1.f6297cff75cbp-1,0x1.921fb54442d17p-3
+cos,0x1.f6297cff75cbp-1,-0x1.921fb54442d17p-3
+cos,0x1.f6297cff75cbp-1,0x1.921fb54442d18p-3
+cos,0x1.f6297cff75cbp-1,-0x1.921fb54442d18p-3
+cos,0x1.f6297cff75cbp-1,0x1.921fb54442d19p-3
+cos,0x1.f6297cff75cbp-1,-0x1.921fb54442d19p-3
+cos,0x1.d906bcf328d46p-1,0x1.921fb54442d17p-2
+cos,0x1.d906bcf328d46p-1,-0x1.921fb54442d17p-2
+cos,0x1.d906bcf328d46p-1,0x1.921fb54442d18p-2
+cos,0x1.d906bcf328d46p-1,-0x1.921fb54442d18p-2
+cos,0x1.d906bcf328d46p-1,0x1.921fb54442d19p-2
+cos,0x1.d906bcf328d46p-1,-0x1.921fb54442d19p-2
+cos,0x1.6a09e667f3bcep-1,0x1.921fb54442d17p-1
+cos,0x1.6a09e667f3bcep-1,-0x1.921fb54442d17p-1
+cos,0x1.6a09e667f3bcdp-1,0x1.921fb54442d18p-1
+cos,0x1.6a09e667f3bcdp-1,-0x1.921fb54442d18p-1
+cos,0x1.6a09e667f3bccp-1,0x1.921fb54442d19p-1
+cos,0x1.6a09e667f3bccp-1,-0x1.921fb54442d19p-1
+cos,0x1.469898cc51702p-52,0x1.921fb54442d17p0
+cos,0x1.469898cc51702p-52,-0x1.921fb54442d17p0
+cos,0x1.1a62633145c07p-54,0x1.921fb54442d18p0
+cos,0x1.1a62633145c07p-54,-0x1.921fb54442d18p0
+cos,-0x1.72cece675d1fdp-53,0x1.921fb54442d19p0
+cos,-0x1.72cece675d1fdp-53,-0x1.921fb54442d19p0
+cos,-0x1.0p0,0x1.921fb54442d17p1
+cos,-0x1.0p0,-0x1.921fb54442d17p1
+cos,-0x1.0p0,0x1.921fb54442d18p1
+cos,-0x1.0p0,-0x1.921fb54442d18p1
+cos,-0x1.0p0,0x1.921fb54442d19p1
+cos,-0x1.0p0,-0x1.921fb54442d19p1
+cos,0x1.0p0,0x1.921fb54442d17p2
+cos,0x1.0p0,-0x1.921fb54442d17p2
+cos,0x1.0p0,0x1.921fb54442d18p2
+cos,0x1.0p0,-0x1.921fb54442d18p2
+cos,0x1.0p0,0x1.921fb54442d19p2
+cos,0x1.0p0,-0x1.921fb54442d19p2
+cos,0x1.0p0,0x1.921fb54442d17p3
+cos,0x1.0p0,-0x1.921fb54442d17p3
+cos,0x1.0p0,0x1.921fb54442d18p3
+cos,0x1.0p0,-0x1.921fb54442d18p3
+cos,0x1.0p0,0x1.921fb54442d19p3
+cos,0x1.0p0,-0x1.921fb54442d19p3
+cos,0x1.0p0,0x1.921fb54442d17p4
+cos,0x1.0p0,-0x1.921fb54442d17p4
+cos,0x1.0p0,0x1.921fb54442d18p4
+cos,0x1.0p0,-0x1.921fb54442d18p4
+cos,0x1.0p0,0x1.921fb54442d19p4
+cos,0x1.0p0,-0x1.921fb54442d19p4
+cos,0x1.0p0,0x1.921fb54442d17p5
+cos,0x1.0p0,-0x1.921fb54442d17p5
+cos,0x1.0p0,0x1.921fb54442d18p5
+cos,0x1.0p0,-0x1.921fb54442d18p5
+cos,0x1.0p0,0x1.921fb54442d19p5
+cos,0x1.0p0,-0x1.921fb54442d19p5
+cos,0x1.0p0,0x1.921fb54442d17p6
+cos,0x1.0p0,-0x1.921fb54442d17p6
+cos,0x1.0p0,0x1.921fb54442d18p6
+cos,0x1.0p0,-0x1.921fb54442d18p6
+cos,0x1.0p0,0x1.921fb54442d19p6
+cos,0x1.0p0,-0x1.921fb54442d19p6
+cos,0x1.0p0,0x1.921fb54442d17p7
+cos,0x1.0p0,-0x1.921fb54442d17p7
+cos,0x1.0p0,0x1.921fb54442d18p7
+cos,0x1.0p0,-0x1.921fb54442d18p7
+cos,0x1.0p0,0x1.921fb54442d19p7
+cos,0x1.0p0,-0x1.921fb54442d19p7
+cos,-0x1.6a09e667f3bc9p-1,0x1.2d97c7f3321d1p1
+cos,-0x1.6a09e667f3bc9p-1,-0x1.2d97c7f3321d1p1
+cos,-0x1.6a09e667f3bccp-1,0x1.2d97c7f3321d2p1
+cos,-0x1.6a09e667f3bccp-1,-0x1.2d97c7f3321d2p1
+cos,-0x1.6a09e667f3bcfp-1,0x1.2d97c7f3321d3p1
+cos,-0x1.6a09e667f3bcfp-1,-0x1.2d97c7f3321d3p1
+cos,-0x1.6a09e667f3bdp-1,0x1.f6a7a2955385dp1
+cos,-0x1.6a09e667f3bdp-1,-0x1.f6a7a2955385dp1
+cos,-0x1.6a09e667f3bcep-1,0x1.f6a7a2955385ep1
+cos,-0x1.6a09e667f3bcep-1,-0x1.f6a7a2955385ep1
+cos,-0x1.6a09e667f3bcbp-1,0x1.f6a7a2955385fp1
+cos,-0x1.6a09e667f3bcbp-1,-0x1.f6a7a2955385fp1
+cos,-0x1.34f272993d141p-50,0x1.2d97c7f3321d1p2
+cos,-0x1.34f272993d141p-50,-0x1.2d97c7f3321d1p2
+cos,-0x1.a79394c9e8a0ap-53,0x1.2d97c7f3321d2p2
+cos,-0x1.a79394c9e8a0ap-53,-0x1.2d97c7f3321d2p2
+cos,0x1.961b1acd85d7dp-51,0x1.2d97c7f3321d3p2
+cos,0x1.961b1acd85d7dp-51,-0x1.2d97c7f3321d3p2
+cos,0x1.6a09e667f3bc6p-1,0x1.5fdbbe9bba774p2
+cos,0x1.6a09e667f3bc6p-1,-0x1.5fdbbe9bba774p2
+cos,0x1.6a09e667f3bcbp-1,0x1.5fdbbe9bba775p2
+cos,0x1.6a09e667f3bcbp-1,-0x1.5fdbbe9bba775p2
+cos,0x1.6a09e667f3bd1p-1,0x1.5fdbbe9bba776p2
+cos,0x1.6a09e667f3bd1p-1,-0x1.5fdbbe9bba776p2
+cos,0x1.6a09e667f3bd4p-1,0x1.c463abeccb2bap2
+cos,0x1.6a09e667f3bd4p-1,-0x1.c463abeccb2bap2
+cos,0x1.6a09e667f3bcep-1,0x1.c463abeccb2bbp2
+cos,0x1.6a09e667f3bcep-1,-0x1.c463abeccb2bbp2
+cos,0x1.6a09e667f3bc9p-1,0x1.c463abeccb2bcp2
+cos,0x1.6a09e667f3bc9p-1,-0x1.c463abeccb2bcp2
+cos,0x1.583ebeff65cc2p-50,0x1.f6a7a2955385dp2
+cos,0x1.583ebeff65cc2p-50,-0x1.f6a7a2955385dp2
+cos,0x1.60fafbfd97309p-52,0x1.f6a7a2955385ep2
+cos,0x1.60fafbfd97309p-52,-0x1.f6a7a2955385ep2
+cos,-0x1.4f8282013467cp-51,0x1.f6a7a2955385fp2
+cos,-0x1.4f8282013467cp-51,-0x1.f6a7a2955385fp2
+cos,-0x1.6a09e667f3bb9p-1,0x1.1475cc9eedeffp3
+cos,-0x1.6a09e667f3bb9p-1,-0x1.1475cc9eedeffp3
+cos,-0x1.6a09e667f3bc5p-1,0x1.1475cc9eedfp3
+cos,-0x1.6a09e667f3bc5p-1,-0x1.1475cc9eedfp3
+cos,-0x1.6a09e667f3bdp-1,0x1.1475cc9eedf01p3
+cos,-0x1.6a09e667f3bdp-1,-0x1.1475cc9eedf01p3
+cos,-0x1.0p0,0x1.2d97c7f3321d1p3
+cos,-0x1.0p0,-0x1.2d97c7f3321d1p3
+cos,-0x1.0p0,0x1.2d97c7f3321d2p3
+cos,-0x1.0p0,-0x1.2d97c7f3321d2p3
+cos,-0x1.0p0,0x1.2d97c7f3321d3p3
+cos,-0x1.0p0,-0x1.2d97c7f3321d3p3
+cos,-0x1.6a09e667f3bep-1,0x1.46b9c347764a2p3
+cos,-0x1.6a09e667f3bep-1,-0x1.46b9c347764a2p3
+cos,-0x1.6a09e667f3bd5p-1,0x1.46b9c347764a3p3
+cos,-0x1.6a09e667f3bd5p-1,-0x1.46b9c347764a3p3
+cos,-0x1.6a09e667f3bc9p-1,0x1.46b9c347764a4p3
+cos,-0x1.6a09e667f3bc9p-1,-0x1.46b9c347764a4p3
+cos,-0x1.3dc585b2c7422p-49,0x1.5fdbbe9bba774p3
+cos,-0x1.3dc585b2c7422p-49,-0x1.5fdbbe9bba774p3
+cos,-0x1.ee2c2d963a10cp-52,0x1.5fdbbe9bba775p3
+cos,-0x1.ee2c2d963a10cp-52,-0x1.5fdbbe9bba775p3
+cos,0x1.8474f49a717bdp-50,0x1.5fdbbe9bba776p3
+cos,0x1.8474f49a717bdp-50,-0x1.5fdbbe9bba776p3
+cos,0x1.6a09e667f3bb9p-1,0x1.78fdb9effea45p3
+cos,0x1.6a09e667f3bb9p-1,-0x1.78fdb9effea45p3
+cos,0x1.6a09e667f3bc4p-1,0x1.78fdb9effea46p3
+cos,0x1.6a09e667f3bc4p-1,-0x1.78fdb9effea46p3
+cos,0x1.6a09e667f3bcfp-1,0x1.78fdb9effea47p3
+cos,0x1.6a09e667f3bcfp-1,-0x1.78fdb9effea47p3
+cos,0x1.6a09e667f3be1p-1,0x1.ab41b09886fe8p3
+cos,0x1.6a09e667f3be1p-1,-0x1.ab41b09886fe8p3
+cos,0x1.6a09e667f3bd6p-1,0x1.ab41b09886fe9p3
+cos,0x1.6a09e667f3bd6p-1,-0x1.ab41b09886fe9p3
+cos,0x1.6a09e667f3bcap-1,0x1.ab41b09886feap3
+cos,0x1.6a09e667f3bcap-1,-0x1.ab41b09886feap3
+cos,0x1.4f6babe5db9e2p-49,0x1.c463abeccb2bap3
+cos,0x1.4f6babe5db9e2p-49,-0x1.c463abeccb2bap3
+cos,0x1.3daeaf976e788p-51,0x1.c463abeccb2bbp3
+cos,0x1.3daeaf976e788p-51,-0x1.c463abeccb2bbp3
+cos,-0x1.6128a83448c3cp-50,0x1.c463abeccb2bcp3
+cos,-0x1.6128a83448c3cp-50,-0x1.c463abeccb2bcp3
+cos,-0x1.6a09e667f3bb8p-1,0x1.dd85a7410f58bp3
+cos,-0x1.6a09e667f3bb8p-1,-0x1.dd85a7410f58bp3
+cos,-0x1.6a09e667f3bc3p-1,0x1.dd85a7410f58cp3
+cos,-0x1.6a09e667f3bc3p-1,-0x1.dd85a7410f58cp3
+cos,-0x1.6a09e667f3bcep-1,0x1.dd85a7410f58dp3
+cos,-0x1.6a09e667f3bcep-1,-0x1.dd85a7410f58dp3
+cos,-0x1.0p0,0x1.f6a7a2955385dp3
+cos,-0x1.0p0,-0x1.f6a7a2955385dp3
+cos,-0x1.0p0,0x1.f6a7a2955385ep3
+cos,-0x1.0p0,-0x1.f6a7a2955385ep3
+cos,-0x1.0p0,0x1.f6a7a2955385fp3
+cos,-0x1.0p0,-0x1.f6a7a2955385fp3
+cos,-0x1.6a09e667f3bf8p-1,0x1.07e4cef4cbd96p4
+cos,-0x1.6a09e667f3bf8p-1,-0x1.07e4cef4cbd96p4
+cos,-0x1.6a09e667f3be2p-1,0x1.07e4cef4cbd97p4
+cos,-0x1.6a09e667f3be2p-1,-0x1.07e4cef4cbd97p4
+cos,-0x1.6a09e667f3bcbp-1,0x1.07e4cef4cbd98p4
+cos,-0x1.6a09e667f3bcbp-1,-0x1.07e4cef4cbd98p4
+cos,-0x1.b088e90c77fd1p-48,0x1.1475cc9eedeffp4
+cos,-0x1.b088e90c77fd1p-48,-0x1.1475cc9eedeffp4
+cos,-0x1.6111d218effa2p-49,0x1.1475cc9eedfp4
+cos,-0x1.6111d218effa2p-49,-0x1.1475cc9eedfp4
+cos,0x1.3ddc5bce200bbp-50,0x1.1475cc9eedf01p4
+cos,0x1.3ddc5bce200bbp-50,-0x1.1475cc9eedf01p4
+cos,0x1.6a09e667f3bacp-1,0x1.2106ca4910068p4
+cos,0x1.6a09e667f3bacp-1,-0x1.2106ca4910068p4
+cos,0x1.6a09e667f3bc3p-1,0x1.2106ca4910069p4
+cos,0x1.6a09e667f3bc3p-1,-0x1.2106ca4910069p4
+cos,0x1.6a09e667f3bd9p-1,0x1.2106ca491006ap4
+cos,0x1.6a09e667f3bd9p-1,-0x1.2106ca491006ap4
+cos,0x1.0p0,0x1.2d97c7f3321d1p4
+cos,0x1.0p0,-0x1.2d97c7f3321d1p4
+cos,0x1.0p0,0x1.2d97c7f3321d2p4
+cos,0x1.0p0,-0x1.2d97c7f3321d2p4
+cos,0x1.0p0,0x1.2d97c7f3321d3p4
+cos,0x1.0p0,-0x1.2d97c7f3321d3p4
+cos,0x1.6a09e667f3bf9p-1,0x1.3a28c59d54339p4
+cos,0x1.6a09e667f3bf9p-1,-0x1.3a28c59d54339p4
+cos,0x1.6a09e667f3be2p-1,0x1.3a28c59d5433ap4
+cos,0x1.6a09e667f3be2p-1,-0x1.3a28c59d5433ap4
+cos,0x1.6a09e667f3bccp-1,0x1.3a28c59d5433bp4
+cos,0x1.6a09e667f3bccp-1,-0x1.3a28c59d5433bp4
+cos,0x1.b95bfc26022b1p-48,0x1.46b9c347764a2p4
+cos,0x1.b95bfc26022b1p-48,-0x1.46b9c347764a2p4
+cos,0x1.72b7f84c04563p-49,0x1.46b9c347764a3p4
+cos,0x1.72b7f84c04563p-49,-0x1.46b9c347764a3p4
+cos,-0x1.1a900f67f753ap-50,0x1.46b9c347764a4p4
+cos,-0x1.1a900f67f753ap-50,-0x1.46b9c347764a4p4
+cos,-0x1.6a09e667f3babp-1,0x1.534ac0f19860bp4
+cos,-0x1.6a09e667f3babp-1,-0x1.534ac0f19860bp4
+cos,-0x1.6a09e667f3bc2p-1,0x1.534ac0f19860cp4
+cos,-0x1.6a09e667f3bc2p-1,-0x1.534ac0f19860cp4
+cos,-0x1.6a09e667f3bd8p-1,0x1.534ac0f19860dp4
+cos,-0x1.6a09e667f3bd8p-1,-0x1.534ac0f19860dp4
+cos,-0x1.0p0,0x1.5fdbbe9bba774p4
+cos,-0x1.0p0,-0x1.5fdbbe9bba774p4
+cos,-0x1.0p0,0x1.5fdbbe9bba775p4
+cos,-0x1.0p0,-0x1.5fdbbe9bba775p4
+cos,-0x1.0p0,0x1.5fdbbe9bba776p4
+cos,-0x1.0p0,-0x1.5fdbbe9bba776p4
+cos,-0x1.6a09e667f3bfap-1,0x1.6c6cbc45dc8dcp4
+cos,-0x1.6a09e667f3bfap-1,-0x1.6c6cbc45dc8dcp4
+cos,-0x1.6a09e667f3be3p-1,0x1.6c6cbc45dc8ddp4
+cos,-0x1.6a09e667f3be3p-1,-0x1.6c6cbc45dc8ddp4
+cos,-0x1.6a09e667f3bcdp-1,0x1.6c6cbc45dc8dep4
+cos,-0x1.6a09e667f3bcdp-1,-0x1.6c6cbc45dc8dep4
+cos,-0x1.c22f0f3f8c592p-48,0x1.78fdb9effea45p4
+cos,-0x1.c22f0f3f8c592p-48,-0x1.78fdb9effea45p4
+cos,-0x1.845e1e7f18b23p-49,0x1.78fdb9effea46p4
+cos,-0x1.845e1e7f18b23p-49,-0x1.78fdb9effea46p4
+cos,0x1.ee8786039d373p-51,0x1.78fdb9effea47p4
+cos,0x1.ee8786039d373p-51,-0x1.78fdb9effea47p4
+cos,0x1.6a09e667f3baap-1,0x1.858eb79a20baep4
+cos,0x1.6a09e667f3baap-1,-0x1.858eb79a20baep4
+cos,0x1.6a09e667f3bc1p-1,0x1.858eb79a20bafp4
+cos,0x1.6a09e667f3bc1p-1,-0x1.858eb79a20bafp4
+cos,0x1.6a09e667f3bd8p-1,0x1.858eb79a20bbp4
+cos,0x1.6a09e667f3bd8p-1,-0x1.858eb79a20bbp4
+cos,-0x1.2ccaf641d4262p-3,0x1.fffffffffffffp62
+cos,-0x1.2ccaf641d4262p-3,-0x1.fffffffffffffp62
+cos,0x1.82aa375b3c33ep-7,0x1.0p63
+cos,0x1.82aa375b3c33ep-7,-0x1.0p63
+cos,0x1.4c0622a6e35dep-2,0x1.0000000000001p63
+cos,0x1.4c0622a6e35dep-2,-0x1.0000000000001p63
+cos,0x1.4ab650b8c6073p-1,0x1.fffffffffffffp26
+cos,0x1.4ab650b8c6073p-1,-0x1.fffffffffffffp26
+cos,0x1.4ab6511a7d39bp-1,0x1.0p27
+cos,0x1.4ab6511a7d39bp-1,-0x1.0p27
+cos,0x1.4ab651ddeb9e6p-1,0x1.0000000000001p27
+cos,0x1.4ab651ddeb9e6p-1,-0x1.0000000000001p27
+cos,0x1.40ad67e777b1ep-1,0x1.fffffffffffffp23
+cos,0x1.40ad67e777b1ep-1,-0x1.fffffffffffffp23
+cos,0x1.40ad67f3f0c9ap-1,0x1.0p24
+cos,0x1.40ad67f3f0c9ap-1,-0x1.0p24
+cos,0x1.40ad680ce2f92p-1,0x1.0000000000001p24
+cos,0x1.40ad680ce2f92p-1,-0x1.0000000000001p24
+cos,-0x1.4eaa606db24c4p-1,0x1.fffffffffffffp1
+cos,-0x1.4eaa606db24c4p-1,-0x1.fffffffffffffp1
+cos,-0x1.4eaa606db24c1p-1,0x1.0p2
+cos,-0x1.4eaa606db24c1p-1,-0x1.0p2
+cos,-0x1.4eaa606db24bbp-1,0x1.0000000000001p2
+cos,-0x1.4eaa606db24bbp-1,-0x1.0000000000001p2
+cos,-0x1.aa22657537201p-2,0x1.fffffffffffffp0
+cos,-0x1.aa22657537201p-2,-0x1.fffffffffffffp0
+cos,-0x1.aa22657537205p-2,0x1.0p1
+cos,-0x1.aa22657537205p-2,-0x1.0p1
+cos,-0x1.aa2265753720cp-2,0x1.0000000000001p1
+cos,-0x1.aa2265753720cp-2,-0x1.0000000000001p1
+cos,0x1.14a280fb5068cp-1,0x1.fffffffffffffp-1
+cos,0x1.14a280fb5068cp-1,-0x1.fffffffffffffp-1
+cos,0x1.14a280fb5068cp-1,0x1.0p0
+cos,0x1.14a280fb5068cp-1,-0x1.0p0
+cos,0x1.14a280fb5068ap-1,0x1.0000000000001p0
+cos,0x1.14a280fb5068ap-1,-0x1.0000000000001p0
+cos,0x1.c1528065b7d5p-1,0x1.fffffffffffffp-2
+cos,0x1.c1528065b7d5p-1,-0x1.fffffffffffffp-2
+cos,0x1.c1528065b7d5p-1,0x1.0p-1
+cos,0x1.c1528065b7d5p-1,-0x1.0p-1
+cos,0x1.c1528065b7d4fp-1,0x1.0000000000001p-1
+cos,0x1.c1528065b7d4fp-1,-0x1.0000000000001p-1
+cos,0x1.f01549f7deea2p-1,0x1.fffffffffffffp-3
+cos,0x1.f01549f7deea2p-1,-0x1.fffffffffffffp-3
+cos,0x1.f01549f7deea1p-1,0x1.0p-2
+cos,0x1.f01549f7deea1p-1,-0x1.0p-2
+cos,0x1.f01549f7deea1p-1,0x1.0000000000001p-2
+cos,0x1.f01549f7deea1p-1,-0x1.0000000000001p-2
+cos,0x1.fc015527d5bd3p-1,0x1.fffffffffffffp-4
+cos,0x1.fc015527d5bd3p-1,-0x1.fffffffffffffp-4
+cos,0x1.fc015527d5bd3p-1,0x1.0p-3
+cos,0x1.fc015527d5bd3p-1,-0x1.0p-3
+cos,0x1.fc015527d5bd3p-1,0x1.0000000000001p-3
+cos,0x1.fc015527d5bd3p-1,-0x1.0000000000001p-3
+cos,0x1.ff0015549f4d3p-1,0x1.fffffffffffffp-5
+cos,0x1.ff0015549f4d3p-1,-0x1.fffffffffffffp-5
+cos,0x1.ff0015549f4d3p-1,0x1.0p-4
+cos,0x1.ff0015549f4d3p-1,-0x1.0p-4
+cos,0x1.ff0015549f4d3p-1,0x1.0000000000001p-4
+cos,0x1.ff0015549f4d3p-1,-0x1.0000000000001p-4
+cos,0x1.ffc00155527d3p-1,0x1.fffffffffffffp-6
+cos,0x1.ffc00155527d3p-1,-0x1.fffffffffffffp-6
+cos,0x1.ffc00155527d3p-1,0x1.0p-5
+cos,0x1.ffc00155527d3p-1,-0x1.0p-5
+cos,0x1.ffc00155527d3p-1,0x1.0000000000001p-5
+cos,0x1.ffc00155527d3p-1,-0x1.0000000000001p-5
+cos,0x1.fff000155549fp-1,0x1.fffffffffffffp-7
+cos,0x1.fff000155549fp-1,-0x1.fffffffffffffp-7
+cos,0x1.fff000155549fp-1,0x1.0p-6
+cos,0x1.fff000155549fp-1,-0x1.0p-6
+cos,0x1.fff000155549fp-1,0x1.0000000000001p-6
+cos,0x1.fff000155549fp-1,-0x1.0000000000001p-6
+cos,0x1.fffffffp-1,0x1.fffffffffffffp-15
+cos,0x1.fffffffp-1,-0x1.fffffffffffffp-15
+cos,0x1.fffffffp-1,0x1.0p-14
+cos,0x1.fffffffp-1,-0x1.0p-14
+cos,0x1.fffffffp-1,0x1.0000000000001p-14
+cos,0x1.fffffffp-1,-0x1.0000000000001p-14
+cos,0x1.0p0,0x1.fffffffffffffp-28
+cos,0x1.0p0,-0x1.fffffffffffffp-28
+cos,0x1.0p0,0x1.0p-27
+cos,0x1.0p0,-0x1.0p-27
+cos,0x1.0p0,0x1.0000000000001p-27
+cos,0x1.0p0,-0x1.0000000000001p-27
+cos,0x1.0p0,0x1.fffffffffffffp-31
+cos,0x1.0p0,-0x1.fffffffffffffp-31
+cos,0x1.0p0,0x1.0p-30
+cos,0x1.0p0,-0x1.0p-30
+cos,0x1.0p0,0x1.0000000000001p-30
+cos,0x1.0p0,-0x1.0000000000001p-30
+cos,-0x1.fffe62ecfab75p-1,-0x1.fffffffffffffp1023
+cos,-0x1.fffe62ecfab75p-1,0x1.fffffffffffffp1023
+cos,-0x1.fffe62ecfab75p-1,0x1.fffffffffffffp1023
+cos,-0x1.fffe62ecfab75p-1,-0x1.fffffffffffffp1023
+cos,-0x1.fffe62ecfab75p-1,0x1.fffffffffffffp1023
+cos,-0x1.fffe62ecfab75p-1,-0x1.fffffffffffffp1023
+cos,0x1.7ffdfb4c5309p-2,0x1.ffffffffffffep1023
+cos,0x1.7ffdfb4c5309p-2,-0x1.ffffffffffffep1023
+cos,-0x1.0p0,0x1.921fb54442d18p1
+cos,-0x1.0p0,-0x1.921fb54442d18p1
+cos,0x1.1a62633145c07p-54,0x1.921fb54442d18p0
+cos,0x1.1a62633145c07p-54,-0x1.921fb54442d18p0
+cos,0x1.14a280fb5068ap-1,0x1.0000000000001p0
+cos,0x1.14a280fb5068ap-1,-0x1.0000000000001p0
+cos,0x1.14a280fb5068cp-1,0x1.0p0
+cos,0x1.14a280fb5068cp-1,-0x1.0p0
+cos,0x1.14a280fb5068cp-1,0x1.fffffffffffffp-1
+cos,0x1.14a280fb5068cp-1,-0x1.fffffffffffffp-1
+cos,0x1.6a09e667f3bcdp-1,0x1.921fb54442d18p-1
+cos,0x1.6a09e667f3bcdp-1,-0x1.921fb54442d18p-1
+cos,0x1.0p0,0x1.0000000000001p-1022
+cos,0x1.0p0,-0x1.0000000000001p-1022
+cos,0x1.0p0,0x1.0p-1022
+cos,0x1.0p0,-0x1.0p-1022
+cos,0x1.0p0,0x0.fffffffffffffp-1022
+cos,0x1.0p0,-0x0.fffffffffffffp-1022
+cos,0x1.0p0,0x0.ffffffffffffep-1022
+cos,0x1.0p0,-0x0.ffffffffffffep-1022
+cos,0x1.0p0,0x0.0000000000002p-1022
+cos,0x1.0p0,-0x0.0000000000002p-1022
+cos,0x1.0p0,0x0.0000000000001p-1022
+cos,0x1.0p0,-0x0.0000000000001p-1022
+cos,0x1.0p0,0x0.0p0
+cos,0x1.0p0,-0x0.0p0
+exp,0x1.0000000000002p0,0x1.ffffffffffffep-52
+exp,0x1.000000000012p0,0x1.1ffffffffff5ep-44
+exp,0x1.000000000208p0,0x1.03fffffffef7fp-39
+exp,0x1.00000000c1b59p0,0x1.836b2fff6d6cbp-33
+exp,0x1.000000033d397p0,0x1.9e9cbbfd6080bp-31
+exp,0x1.003af6c37c1d3p0,0x1.d77fd13d27fffp-11
+exp,0x1.016b4df3299d8p0,0x1.6a4d1af9cc989p-8
+exp,0x1.0ca4a41663fep0,0x1.8ae823850230bp-5
+exp,0x1.1538ea18a4585p0,0x1.46370d915991bp-4
+exp,0x1.47408cb9583cep0,0x1.f6e4c3ced7c72p-3
+exp,0x1.27c2e4bc1ee7p1,0x1.accfbe46b4efp-1
+exp,0x1.557d4acd7e556p2,0x1.aca7ae8da5a7bp0
+exp,0x1.91a8dff540ff7p2,0x1.d6336a88077aap0
+exp,0x1.8ede492d96072p3,0x1.42ee3c7dc4946p1
+exp,0x1.ac50b409c8aeep8,0x1.83d4bcdebb3f4p2
+exp,0x1.f3e558cf4de54p-23,-0x1.e8bdbfcd9144ep3
+exp,0x1.951c6dc5d24e2p-9,-0x1.71e0b869b5e79p2
+exp,0x1.1064b2c103ddap-3,-0x1.02393d5976769p1
+exp,0x1.3ef1e9b3a81c8p-2,-0x1.2a9cad9998262p0
+exp,0x1.534d4de870713p-3,-0x1.cc37ef7de7501p0
+exp,0x1.2217147b85eaap-1,-0x1.22e24fa3d5cf9p-1
+exp,0x1.9403fd0ee51c8p-2,-0x1.dc2b5df1f7d3dp-1
+exp,0x1.baded30cbf1c4p-1,-0x1.290ea09e36479p-3
+exp,0x1.ffe5d0bb7eabfp-1,-0x1.a2fefefd580dfp-13
+exp,0x1.ffffff84b39c5p-1,-0x1.ed318efb627eap-27
+exp,0x1.fffffffad0ae6p-1,-0x1.4bd46601ae1efp-31
+exp,0x1.ffffffffff7p-1,-0x1.2000000000288p-42
+exp,0x1.fffffffffffdp-1,-0x1.8000000000012p-48
+exp,0x1.ffffffffffffcp-1,-0x1.0000000000001p-51
+exp,0x1.0000000000001p0,0x1.fffffffffffffp-53
+exp,0x1.000000000002p0,0x1.fffffffffffep-48
+exp,0x1.000000017ffe8p0,0x1.7ffe7ffee0024p-32
+exp,0x1.0000000180018p0,0x1.80017ffedffdcp-32
+exp,0x1.00000075e9f64p0,0x1.d7a7d893609e5p-26
+exp,0x1.0006e83736f8cp0,0x1.ba07d73250de7p-14
+exp,0x1.de7cd6751029ap16,0x1.76e7e5d7b6eacp3
+exp,0x1.1d71965f516aep19,0x1.a8ead058bc6b8p3
+exp,0x1.a8c02e974c315p25,0x1.1d5c2daebe367p4
+exp,0x1.b890ca8637ae2p40,0x1.c44ce0d716a1ap4
+exp,0x1.f03f56a88b5d8p-1,-0x1.0000000000001p-5
+exp,0x1.ff003ff556aa8p-1,-0x1.000000000000ap-9
+exp,0x1.8ebef9eac81fcp-1,-0x1.0000000000025p-2
+exp,0x1.fc03fd56a469cp-1,-0x1.0000000171051p-7
+exp,0x1.78b5612dbee01p-2,-0x1.0000018p0
+exp,0x1.969c870ea9f5ap-93,-0x1.000001e3ep6
+exp,0x1.78af867bc511ep-2,-0x1.0003fcp0
+exp,0x1.fffffffffefffp-1,-0x1.00080000004p-41
+exp,0x1.789214093c81ep-2,-0x1.0018p0
+exp,0x1.8e298e52fcce8p-1,-0x1.018p-2
+exp,0x1.aa6ffb0ba51ap-24,-0x1.0201p4
+exp,0x1.dd7a46b8d85d6p-376,-0x1.04p8
+exp,0x1.33e96ca3bcf3ep-1,-0x1.045b94872413p-1
+exp,0x1.ef2f652dc2606p-1,-0x1.118e05cfa3e8p-5
+exp,0x1.a5d2ce977bbe2p-7,-0x1.169156e17b9b9p2
+exp,0x1.a0207cf4190f7p-7,-0x1.17701b3bf0502p2
+exp,0x1.fb97e1ff8cbbap-1,-0x1.1b4p-7
+exp,0x1.bcff09ae30c46p-1,-0x1.1f4p-3
+exp,0x1.fee70cf5e86efp-833,-0x1.2059ad42c3cf7p9
+exp,0x1.7ccd3f3340746p-1,-0x1.2f269d2ca38d2p-2
+exp,0x1.09cdb36e977bcp-14,-0x1.3553cf1828b0bp3
+exp,0x1.f9dc5cd546d9cp-449,-0x1.368ac083128fcp8
+exp,0x1.f1c53c907f6f5p-15,-0x1.376e8f679ae16p3
+exp,0x1.f24595954e662p-8,-0x1.3844f67495f7dp2
+exp,0x1.fb56521290a22p-905,-0x1.394e9e1b089d7p9
+exp,0x1.dc1658ff6e07p-114,-0x1.3997ea51e5271p6
+exp,0x1.ec8b3c090f8b9p-1,-0x1.3d5de560e1906p-5
+exp,0x1.af411bf985221p-951,-0x1.4954aa552a96p9
+exp,0x1.e1b71d238d508p-957,-0x1.4b5ad6a9ad6adp9
+exp,0x1.cc666a3519cap-973,-0x1.50ec32686a834p9
+exp,0x1.22462bd5f72b1p-976,-0x1.52316872b0222p9
+exp,0x1.c1ebc18610302p-981,-0x1.53b4ed3b4ec77p9
+exp,0x1.8d015bcaf9e19p-981,-0x1.53c4f13c4f079p9
+exp,0x1.fd5835460ed49p-989,-0x1.566ad4a41becp9
+exp,0x1.58733fbc088fp-994,-0x1.585883e7b3b38p9
+exp,0x1.b052090690482p-32,-0x1.5a81ecf68beccp4
+exp,0x1.df6154bc644dbp-1015,-0x1.5f75629af4eb7p9
+exp,0x0.ffa586d1b841ap-1022,-0x1.6232eb1c432f2p9
+exp,0x0.b12f6ea63a89fp-1022,-0x1.6261d7dbf48ccp9
+exp,0x1.d572d24973be2p-1,-0x1.6364b8f747e32p-4
+exp,0x1.ee4dd79224578p-9,-0x1.6524796b40895p2
+exp,0x1.f660c59b2945p-5,-0x1.6551daae369cep1
+exp,0x0.0003540e0893ep-1022,-0x1.672463f141607p9
+exp,0x1.d4e7fc331b732p-1,-0x1.6820c99c1dc16p-4
+exp,0x1.fcc448acf4765p-528,-0x1.6d4b7e82c3f02p8
+exp,0x1.7fff5a1bffcb2p-529,-0x1.6e44f765fda76p8
+exp,0x1.fa4ecd8ae5718p-1,-0x1.6e56e725b8304p-7
+exp,0x1.e8d2dafd017cep-3,-0x1.6ecp0
+exp,0x0.0000000001215p-1022,-0x1.7p9
+exp,0x0.000000000000ep-1022,-0x1.72e42p9
+exp,0x1.a349b2329c678p-273,-0x1.7978bac71121cp7
+exp,0x1.d2a6d5ea995c2p-1,-0x1.7bde79e0f970cp-4
+exp,0x1.b776dc64c76d2p-3,-0x1.8ap0
+exp,0x1.4446fcf7da68ap-72,-0x1.8d5c84f0bac8cp5
+exp,0x1.e72a0b68bb82cp-73,-0x1.8fa68b444723p5
+exp,0x1.fc33d5e1ca6dfp-75,-0x1.9a671693b946bp5
+exp,0x1.e6981fd6ef79cp-1,-0x1.a0ec89f897a75p-5
+exp,0x1.f2b9d3b6cf227p-1,-0x1.ae6p-6
+exp,0x1.e5034c8d191bcp-1,-0x1.bb9706e2f1bb4p-5
+exp,0x1.f24dc90f9fbecp-1,-0x1.bc3edad2e1efbp-6
+exp,0x1.71f237d64a6ecp-11,-0x1.d0697edbe0052p2
+exp,0x1.f12c0d3addaa4p-1,-0x1.e18p-6
+exp,0x1.f110dd9073d72p-1,-0x1.e5p-6
+exp,0x1.f3aa7a860574cp-705,-0x1.e7fffffffffffp8
+exp,0x1.f0f898d55117p-1,-0x1.e82p-6
+exp,0x1.ff814fff18dadp-1,-0x1.fafebfafebfbp-11
+exp,0x1.ffffffff01c07p-1,-0x1.fc7f1fc7f2p-34
+exp,0x1.7907d4148bd92p-2,-0x1.ff8ffffffffffp-1
+exp,0x1.ffffffffffff8p-1,-0x1.ff8ffffffffffp-51
+exp,0x1.e0fbb03a0c27ep-1,-0x1.ffeffffffffffp-5
+exp,0x1.ffffffffff001p-1,-0x1.ffeffffffffffp-42
+exp,0x1.ffffffffffp-1,-0x1.fff00000008p-42
+exp,0x1.0p0,-0x1.fff8e61eadd48p-101
+exp,0x1.fffffffffc001p-1,-0x1.fffbfffffffffp-40
+exp,0x1.fffffffffcp-1,-0x1.fffff1fffffffp-40
+exp,0x1.ff800ffeaac01p-1,-0x1.ffffffffffda5p-11
+exp,0x1.e355bbaee8d86p-24,-0x1.fffffffffff7dp3
+exp,0x1.78b56362cef3ep-2,-0x1.ffffffffffff8p-1
+exp,0x1.0p0,-0x0.ffffffffffffep-1022
+exp,0x1.42eb9f39afbacp-185,-0x1.ffffffffffffep6
+exp,0x1.0p0,0x1.0p-53
+exp,0x1.95e54c5dd4218p184,0x1.0p7
+exp,0x1.9476504ba8857p738,0x1.0000000000001p9
+exp,0x1.0100802ab5578p0,0x1.0000000000003p-8
+exp,0x1.0000004000001p0,0x1.0000000000007p-26
+exp,0x1.d8e64b8f26c12p2,0x1.000000008p1
+exp,0x1.749ea7e015bc2p11,0x1.00000001p3
+exp,0x1.0f2ebd2c65d9ap23,0x1.00000002p4
+exp,0x1.0f2ec1473afeap23,0x1.0000004p4
+exp,0x1.0000000001p0,0x1.0008p-40
+exp,0x1.00000000008p0,0x1.001p-41
+exp,0x1.0000000000001p0,0x1.001p-53
+exp,0x1.a8bf81a597eddp184,0x1.00173eab3623ap7
+exp,0x1.75e54175aabb4p11,0x1.001cp3
+exp,0x1.60008fbed6c52p1,0x1.02f8af8af8affp0
+exp,0x1.04184bb80ff44p0,0x1.04p-6
+exp,0x1.0000084000221p0,0x1.08p-21
+exp,0x1.2338ab9b7432p0,0x1.08000001d0fc8p-3
+exp,0x1.acc91bfa7c54cp0,0x1.0814419d6a65ap-1
+exp,0x1.a4e4693413b9ap400,0x1.15c18de877563p8
+exp,0x1.0000000000004p0,0x1.1ffffffffffffp-50
+exp,0x1.eaa521edf1bc2p846,0x1.2586ca9cf411bp9
+exp,0x1.fca9c47016cb1p26,0x1.2b55c037ebb9dp4
+exp,0x1.fcbb1e5c8d535p26,0x1.2b564bee0a6cap4
+exp,0x1.cc0f9d911f1d1p0,0x1.2c2p-1
+exp,0x1.b68a28b09fe94p6,0x1.2c9e33f794769p2
+exp,0x1.d2e035b1892d6p0,0x1.33a74ff06fb66p-1
+exp,0x1.6acde844356cap3,0x1.36cce3c3925p1
+exp,0x1.06dadee28c11cp7,0x1.38389c48b0fcep2
+exp,0x1.c78f37f07cea6p904,0x1.3997381d7d94fp9
+exp,0x1.bfe0c519166c4p1,0x1.40a339c81cecbp0
+exp,0x1.fbc9c30603087p927,0x1.419dbcc48677p9
+exp,0x1.f1ef9c8a4fdaep930,0x1.42a565e456e04p9
+exp,0x1.da134d5a4d1e2p934,0x1.44020100804p9
+exp,0x1.f4ec44194b642p938,0x1.456bf23e02428p9
+exp,0x1.ea91d9533b394p939,0x1.45c1feef8086cp9
+exp,0x1.cb419b9279b36p943,0x1.471c71c71c71cp9
+exp,0x1.6d14308828322p29,0x1.474c9cc44cc25p4
+exp,0x1.c0194b4186e28p956,0x1.4b9ab1781203p9
+exp,0x1.15c605853476cp0,0x1.4e59dc7e2b053p-4
+exp,0x1.6dee38735a6d4p972,0x1.510c5465d984bp9
+exp,0x1.f1e96be2a52cdp0,0x1.549b0f5742382p-1
+exp,0x1.f253c5990aad2p0,0x1.55085fb86501ap-1
+exp,0x1.279b1c43a2662p993,0x1.58383126e94bfp9
+exp,0x1.6fd5ab59153f4p996,0x1.595e5795e592bp9
+exp,0x1.5ecf187653954p1004,0x1.5c1e0f0783c1p9
+exp,0x1.f2a3c29fc6d72p1008,0x1.5dadf5d1e452cp9
+exp,0x1.edcb14879613ep1009,0x1.5e056ed40e56ep9
+exp,0x1.fcc7e5ca80b1fp0,0x1.5fa97bb4e906p-1
+exp,0x1.f8b5c987a3d88p3,0x1.610e47e1325dcp1
+exp,0x1.f1e9d8cf24fcep7,0x1.611b19dcc53e4p2
+exp,0x1.ffc045692e8ap1023,0x1.62e41fffffffap9
+exp,0x1.ffc045693009dp1023,0x1.62e42p9
+exp,0x1.ffc04569a2fb8p1023,0x1.62e42000001ccp9
+exp,0x1.fffffffffeb2ap1023,0x1.62e42fefa39eap9
+exp,0x1.00000b40003f5p0,0x1.68p-21
+exp,0x1.17e62f70bec9ap8,0x1.689a7dc5921b8p2
+exp,0x1.6daaa1336a315p264,0x1.6eb1de69ace32p7
+exp,0x1.72a9dadea7498p0,0x1.7bp-2
+exp,0x1.1ed3fe64fc53ap2,0x1.7fffffffffff9p0
+exp,0x1.0000000000001p0,0x1.7ffffffffffffp-52
+exp,0x1.fe31152b7ef6bp553,0x1.8p8
+exp,0x1.74d77b76d9516p0,0x1.81p-2
+exp,0x1.f0e3e5b6c17cp556,0x1.820d92fc4b42ap8
+exp,0x1.00000000c1b59p0,0x1.836b2fff6d6cbp-33
+exp,0x1.78b69d690db7ap570,0x1.8b7aee631f489p8
+exp,0x1.4dad95877ae08p144,0x1.905011e0df629p6
+exp,0x1.fcbb8778f6121p144,0x1.91fffp6
+exp,0x1.7a5b2771e0a16p4,0x1.94e54738fb4b7p1
+exp,0x1.7d676a26fe5cap0,0x1.984p-2
+exp,0x1.698764128a444p147,0x1.98f381d7db44fp6
+exp,0x1.44e5a752f9e1fp9,0x1.9e8186b267a28p2
+exp,0x1.8023d298e373p0,0x1.9f91c1449c421p-2
+exp,0x1.df9bd06daf8cep299,0x1.9fc1f212d70f6p7
+exp,0x1.81a4fbca9dcdcp0,0x1.a392789eafce9p-2
+exp,0x1.825f354ccf6f3p0,0x1.a5807ca1392b2p-2
+exp,0x1.3c1e2876834aap0,0x1.bp-3
+exp,0x1.1c7e1aca53796p0,0x1.b04p-4
+exp,0x1.a2d50b8b2880ep331,0x1.cbd917ccad096p7
+exp,0x1.419c8a8da1b7ap1,0x1.d7b677e333d38p-1
+exp,0x1.41d1b8b4649ecp1,0x1.d80b1a6330bebp-1
+exp,0x1.bf3447921fd3ap10,0x1.df50d9af9e41p2
+exp,0x1.9919794bc862ap0,0x1.e0081ebc3264ep-2
+exp,0x1.76a62bad715b4p5,0x1.ec5bb209e5707p1
+exp,0x1.c701554c761aap2,0x1.f62p0
+exp,0x1.c3dda3c952b92p727,0x1.f87c7820d8446p8
+exp,0x1.d28c6097b9d56p2,0x1.fc89dc1aa909cp0
+exp,0x1.4231178c2349p734,0x1.fcfffffffffffp8
+exp,0x1.04034591911e8p0,0x1.fda6dfe27ffffp-7
+exp,0x1.a5b5691c4b0fp0,0x1.ff1dd1fffffffp-2
+exp,0x1.0000000000004p0,0x1.ff8ffffffffffp-51
+exp,0x1.6d4fd9ab47c92p738,0x1.ffe5effffffffp8
+exp,0x1.0000000000fffp0,0x1.ffefffffff001p-41
+exp,0x1.74418bce788ecp11,0x1.ffeffffffffffp2
+exp,0x1.0000000001p0,0x1.fffp-41
+exp,0x1.0000000001p0,0x1.ffffe3fffffffp-41
+exp,0x1.d8e64b8d21852p2,0x1.ffffffffe7fffp0
+exp,0x1.0p0,0x0.ffffffffffffep-1022
+exp,0x1.0p0,0x1.ffffffffffffep-54
+exp,0x1.0p0,0x1.fffffffffffffp-54
+exp,0x1.304d6aeca2525p69,0x1.7ffffffffffffp5
+exp,0x1.304d6aeca254bp69,0x1.8p5
+exp,0x1.304d6aeca2571p69,0x1.8000000000001p5
+exp,0x1.f8e6c24b558efp-76,-0x1.a000000000001p5
+exp,0x1.f8e6c24b5592ep-76,-0x1.ap5
+exp,0x1.f8e6c24b5596dp-76,-0x1.9ffffffffffffp5
+exp,0x1.55779b984f396p115,0x1.3ffffffffffffp6
+exp,0x1.55779b984f3ebp115,0x1.4p6
+exp,0x1.55779b984f44p115,0x1.4000000000001p6
+exp,0x1.07b7112bc1fbcp-127,-0x1.6000000000001p6
+exp,0x1.07b7112bc1ffep-127,-0x1.6p6
+exp,0x1.07b7112bc204p-127,-0x1.5ffffffffffffp6
+exp,0x1.40a4b9c271508p923,0x1.3ffffffffffffp9
+exp,0x1.40a4b9c27178ap923,0x1.4p9
+exp,0x1.40a4b9c271a0bp923,0x1.4000000000001p9
+exp,0x1.44a3824e525d6p-1016,-0x1.6000000000001p9
+exp,0x1.44a3824e5285fp-1016,-0x1.6p9
+exp,0x1.44a3824e52ae8p-1016,-0x1.5ffffffffffffp9
+exp,0x1.03996528e072bp75,0x1.9ffffffffffffp5
+exp,0x1.03996528e074cp75,0x1.ap5
+exp,0x1.03996528e076cp75,0x1.a000000000001p5
+exp,0x1.aebabae3a417fp-70,-0x1.8000000000001p5
+exp,0x1.aebabae3a41b5p-70,-0x1.8p5
+exp,0x1.aebabae3a41eap-70,-0x1.7ffffffffffffp5
+exp,0x1.f1056dc7bf1b1p126,0x1.5ffffffffffffp6
+exp,0x1.f1056dc7bf22dp126,0x1.6p6
+exp,0x1.f1056dc7bf2aap126,0x1.6000000000001p6
+exp,0x1.7fd974d372de4p-116,-0x1.4000000000001p6
+exp,0x1.7fd974d372e44p-116,-0x1.4p6
+exp,0x1.7fd974d372ea4p-116,-0x1.3ffffffffffffp6
+exp,0x1.93bf4ec282bd4p1015,0x1.5ffffffffffffp9
+exp,0x1.93bf4ec282efbp1015,0x1.6p9
+exp,0x1.93bf4ec283223p1015,0x1.6000000000001p9
+exp,0x1.98c72ca0cab15p-924,-0x1.4000000000001p9
+exp,0x1.98c72ca0cae46p-924,-0x1.4p9
+exp,0x1.98c72ca0cb178p-924,-0x1.3ffffffffffffp9
+exp,0x1.61013a44a981cp-822,-0x1.1cb90bfbe8e7cp9
+exp,0x1.8087717a7f08ap-905,-0x1.397217f7d1cf8p9
+exp,0x1.a2de59d854521p-988,-0x1.562b23f3bab73p9
+exp,0x1.fffffffffffffp-2,-0x1.62e42fefa39fp-1
+exp,0x1.0p-1,-0x1.62e42fefa39efp-1
+exp,0x1.0000000000001p-1,-0x1.62e42fefa39eep-1
+exp,0x1.6a09e667f3bccp-1,-0x1.62e42fefa39fp-2
+exp,0x1.6a09e667f3bccp-1,-0x1.62e42fefa39efp-2
+exp,0x1.6a09e667f3bcdp-1,-0x1.62e42fefa39eep-2
+exp,0x1.ae89f995ad3adp-1,-0x1.62e42fefa39fp-3
+exp,0x1.ae89f995ad3aep-1,-0x1.62e42fefa39efp-3
+exp,0x1.ae89f995ad3aep-1,-0x1.62e42fefa39eep-3
+exp,0x1.d5818dcfba487p-1,-0x1.62e42fefa39fp-4
+exp,0x1.d5818dcfba487p-1,-0x1.62e42fefa39efp-4
+exp,0x1.d5818dcfba487p-1,-0x1.62e42fefa39eep-4
+exp,0x1.ea4afa2a490dap-1,-0x1.62e42fefa39fp-5
+exp,0x1.ea4afa2a490dap-1,-0x1.62e42fefa39efp-5
+exp,0x1.ea4afa2a490dap-1,-0x1.62e42fefa39eep-5
+exp,0x1.f50765b6e454p-1,-0x1.62e42fefa39fp-6
+exp,0x1.f50765b6e454p-1,-0x1.62e42fefa39efp-6
+exp,0x1.f50765b6e454p-1,-0x1.62e42fefa39eep-6
+exp,0x1.059b0d3158574p0,0x1.62e42fefa39eep-6
+exp,0x1.059b0d3158574p0,0x1.62e42fefa39efp-6
+exp,0x1.059b0d3158574p0,0x1.62e42fefa39fp-6
+exp,0x1.0b5586cf9890fp0,0x1.62e42fefa39eep-5
+exp,0x1.0b5586cf9890fp0,0x1.62e42fefa39efp-5
+exp,0x1.0b5586cf9890fp0,0x1.62e42fefa39fp-5
+exp,0x1.172b83c7d517bp0,0x1.62e42fefa39eep-4
+exp,0x1.172b83c7d517bp0,0x1.62e42fefa39efp-4
+exp,0x1.172b83c7d517bp0,0x1.62e42fefa39fp-4
+exp,0x1.306fe0a31b715p0,0x1.62e42fefa39eep-3
+exp,0x1.306fe0a31b715p0,0x1.62e42fefa39efp-3
+exp,0x1.306fe0a31b715p0,0x1.62e42fefa39fp-3
+exp,0x1.6a09e667f3bccp0,0x1.62e42fefa39eep-2
+exp,0x1.6a09e667f3bccp0,0x1.62e42fefa39efp-2
+exp,0x1.6a09e667f3bcdp0,0x1.62e42fefa39fp-2
+exp,0x1.fffffffffffffp0,0x1.62e42fefa39eep-1
+exp,0x1.0p1,0x1.62e42fefa39efp-1
+exp,0x1.0p1,0x1.62e42fefa39fp-1
+exp,0x1.ffffffffffffep1,0x1.62e42fefa39eep0
+exp,0x1.0p2,0x1.62e42fefa39efp0
+exp,0x1.0000000000001p2,0x1.62e42fefa39fp0
+exp,0x1.ffffffffffffbp3,0x1.62e42fefa39eep1
+exp,0x1.fffffffffffffp3,0x1.62e42fefa39efp1
+exp,0x1.0000000000002p4,0x1.62e42fefa39fp1
+exp,0x1.ffffffffffff6p7,0x1.62e42fefa39eep2
+exp,0x1.ffffffffffffep7,0x1.62e42fefa39efp2
+exp,0x1.0000000000003p8,0x1.62e42fefa39fp2
+exp,0x1.fffffffffffedp15,0x1.62e42fefa39eep3
+exp,0x1.ffffffffffffdp15,0x1.62e42fefa39efp3
+exp,0x1.0000000000006p16,0x1.62e42fefa39fp3
+exp,0x1.fffffffffffd9p31,0x1.62e42fefa39eep4
+exp,0x1.ffffffffffff9p31,0x1.62e42fefa39efp4
+exp,0x1.000000000000dp32,0x1.62e42fefa39fp4
+exp,0x1.ffffffffffb2ap1023,0x1.62e42fefa39eep9
+exp,0x1.fffffffffff2ap1023,0x1.62e42fefa39efp9
+exp,0x0.000000000000ep-1022,-0x1.72e42fefa39fp9
+exp,0x0.000000000000ep-1022,-0x1.72e42fefa39efp9
+exp,0x0.000000000000ep-1022,-0x1.72e42fefa39eep9
+exp,0x1.8ebef9eac820ap-1,-0x1.0000000000001p-2
+exp,0x1.8ebef9eac820bp-1,-0x1.0p-2
+exp,0x1.8ebef9eac820bp-1,-0x1.fffffffffffffp-3
+exp,0x1.c3d6a24ed8221p-1,-0x1.0000000000001p-3
+exp,0x1.c3d6a24ed8222p-1,-0x1.0p-3
+exp,0x1.c3d6a24ed8222p-1,-0x1.fffffffffffffp-4
+exp,0x1.e0fabfbc702a4p-1,-0x1.0000000000001p-4
+exp,0x1.e0fabfbc702a4p-1,-0x1.0p-4
+exp,0x1.e0fabfbc702a4p-1,-0x1.fffffffffffffp-5
+exp,0x1.f03f56a88b5d8p-1,-0x1.0000000000001p-5
+exp,0x1.f03f56a88b5d8p-1,-0x1.0p-5
+exp,0x1.f03f56a88b5d8p-1,-0x1.fffffffffffffp-6
+exp,0x1.f80feabfeefa5p-1,-0x1.0000000000001p-6
+exp,0x1.f80feabfeefa5p-1,-0x1.0p-6
+exp,0x1.f80feabfeefa5p-1,-0x1.fffffffffffffp-7
+exp,0x1.fc03fd56aa225p-1,-0x1.0000000000001p-7
+exp,0x1.fc03fd56aa225p-1,-0x1.0p-7
+exp,0x1.fc03fd56aa225p-1,-0x1.fffffffffffffp-8
+exp,0x1.fe00ffaabffbcp-1,-0x1.0000000000001p-8
+exp,0x1.fe00ffaabffbcp-1,-0x1.0p-8
+exp,0x1.fe00ffaabffbcp-1,-0x1.fffffffffffffp-9
+exp,0x1.ff003ff556aa9p-1,-0x1.0000000000001p-9
+exp,0x1.ff003ff556aa9p-1,-0x1.0p-9
+exp,0x1.ff003ff556aa9p-1,-0x1.fffffffffffffp-10
+exp,0x1.ff800ffeaacp-1,-0x1.0000000000001p-10
+exp,0x1.ff800ffeaacp-1,-0x1.0p-10
+exp,0x1.ff800ffeaacp-1,-0x1.fffffffffffffp-11
+exp,0x1.fff0003fff555p-1,-0x1.0000000000001p-13
+exp,0x1.fff0003fff555p-1,-0x1.0p-13
+exp,0x1.fff0003fff555p-1,-0x1.fffffffffffffp-14
+exp,0x1.48b5e3c3e8186p0,0x1.fffffffffffffp-3
+exp,0x1.48b5e3c3e8186p0,0x1.0p-2
+exp,0x1.48b5e3c3e8187p0,0x1.0000000000001p-2
+exp,0x1.2216045b6f5cdp0,0x1.fffffffffffffp-4
+exp,0x1.2216045b6f5cdp0,0x1.0p-3
+exp,0x1.2216045b6f5cdp0,0x1.0000000000001p-3
+exp,0x1.1082b577d34edp0,0x1.fffffffffffffp-5
+exp,0x1.1082b577d34eep0,0x1.0p-4
+exp,0x1.1082b577d34eep0,0x1.0000000000001p-4
+exp,0x1.08205601127edp0,0x1.fffffffffffffp-6
+exp,0x1.08205601127edp0,0x1.0p-5
+exp,0x1.08205601127edp0,0x1.0000000000001p-5
+exp,0x1.04080ab55de39p0,0x1.fffffffffffffp-7
+exp,0x1.04080ab55de39p0,0x1.0p-6
+exp,0x1.04080ab55de39p0,0x1.0000000000001p-6
+exp,0x1.0202015600446p0,0x1.fffffffffffffp-8
+exp,0x1.0202015600446p0,0x1.0p-7
+exp,0x1.0202015600446p0,0x1.0000000000001p-7
+exp,0x1.0100802ab5577p0,0x1.fffffffffffffp-9
+exp,0x1.0100802ab5577p0,0x1.0p-8
+exp,0x1.0100802ab5577p0,0x1.0000000000001p-8
+exp,0x1.0080200556001p0,0x1.fffffffffffffp-10
+exp,0x1.0080200556001p0,0x1.0p-9
+exp,0x1.0080200556001p0,0x1.0000000000001p-9
+exp,0x1.00400800aab55p0,0x1.fffffffffffffp-11
+exp,0x1.00400800aab55p0,0x1.0p-10
+exp,0x1.00400800aab55p0,0x1.0000000000001p-10
+exp,0x1.0008002000555p0,0x1.fffffffffffffp-14
+exp,0x1.0008002000555p0,0x1.0p-13
+exp,0x1.0008002000555p0,0x1.0000000000001p-13
+exp,0x1.44109edb206a9p-739,-0x1.0000000000001p9
+exp,0x1.44109edb20931p-739,-0x1.0p9
+exp,0x1.44109edb20a76p-739,-0x1.fffffffffffffp8
+exp,0x1.9755956ad4d05p-370,-0x1.0000000000001p8
+exp,0x1.9755956ad4e9cp-370,-0x1.0p8
+exp,0x1.9755956ad4f68p-370,-0x1.fffffffffffffp7
+exp,0x1.42eb9f39afa6ap-185,-0x1.0000000000001p7
+exp,0x1.42eb9f39afb0bp-185,-0x1.0p7
+exp,0x1.42eb9f39afb5cp-185,-0x1.fffffffffffffp6
+exp,0x1.969d47321e466p-93,-0x1.0000000000001p6
+exp,0x1.969d47321e4ccp-93,-0x1.0p6
+exp,0x1.969d47321e4fep-93,-0x1.fffffffffffffp5
+exp,0x1.c8464f761642fp-47,-0x1.0000000000001p5
+exp,0x1.c8464f7616468p-47,-0x1.0p5
+exp,0x1.c8464f7616485p-47,-0x1.fffffffffffffp4
+exp,0x1.e355bbaee85adp-24,-0x1.0000000000001p4
+exp,0x1.e355bbaee85cbp-24,-0x1.0p4
+exp,0x1.e355bbaee85dap-24,-0x1.fffffffffffffp3
+exp,0x1.5fc21041027a2p-12,-0x1.0000000000001p3
+exp,0x1.5fc21041027adp-12,-0x1.0p3
+exp,0x1.5fc21041027b2p-12,-0x1.fffffffffffffp2
+exp,0x1.2c155b8213cfp-6,-0x1.0000000000001p2
+exp,0x1.2c155b8213cf4p-6,-0x1.0p2
+exp,0x1.2c155b8213cf7p-6,-0x1.fffffffffffffp1
+exp,0x1.152aaa3bf81c9p-3,-0x1.0000000000001p1
+exp,0x1.152aaa3bf81ccp-3,-0x1.0p1
+exp,0x1.152aaa3bf81cdp-3,-0x1.fffffffffffffp0
+exp,0x1.78b56362cef36p-2,-0x1.0000000000001p0
+exp,0x1.78b56362cef38p-2,-0x1.0p0
+exp,0x1.78b56362cef38p-2,-0x1.fffffffffffffp-1
+exp,0x1.9476504ba839ap738,0x1.fffffffffffffp8
+exp,0x1.9476504ba852ep738,0x1.0p9
+exp,0x1.9476504ba8857p738,0x1.0000000000001p9
+exp,0x1.41c7a8814be19p369,0x1.fffffffffffffp7
+exp,0x1.41c7a8814bebap369,0x1.0p8
+exp,0x1.41c7a8814bffcp369,0x1.0000000000001p8
+exp,0x1.95e54c5dd41b2p184,0x1.fffffffffffffp6
+exp,0x1.95e54c5dd4218p184,0x1.0p7
+exp,0x1.95e54c5dd42e2p184,0x1.0000000000001p7
+exp,0x1.425982cf597a5p92,0x1.fffffffffffffp5
+exp,0x1.425982cf597cdp92,0x1.0p6
+exp,0x1.425982cf5981ep92,0x1.0000000000001p6
+exp,0x1.1f43fcc4b661bp46,0x1.fffffffffffffp4
+exp,0x1.1f43fcc4b662cp46,0x1.0p5
+exp,0x1.1f43fcc4b665p46,0x1.0000000000001p5
+exp,0x1.0f2ebd0a80018p23,0x1.fffffffffffffp3
+exp,0x1.0f2ebd0a8002p23,0x1.0p4
+exp,0x1.0f2ebd0a80031p23,0x1.0000000000001p4
+exp,0x1.749ea7d470c68p11,0x1.fffffffffffffp2
+exp,0x1.749ea7d470c6ep11,0x1.0p3
+exp,0x1.749ea7d470c7ap11,0x1.0000000000001p3
+exp,0x1.b4c902e273a55p5,0x1.fffffffffffffp1
+exp,0x1.b4c902e273a58p5,0x1.0p2
+exp,0x1.b4c902e273a5fp5,0x1.0000000000001p2
+exp,0x1.d8e64b8d4ddacp2,0x1.fffffffffffffp0
+exp,0x1.d8e64b8d4ddaep2,0x1.0p1
+exp,0x1.d8e64b8d4ddb2p2,0x1.0000000000001p1
+exp,0x1.5bf0a8b145769p1,0x1.fffffffffffffp-1
+exp,0x1.5bf0a8b14576ap1,0x1.0p0
+exp,0x1.5bf0a8b14576bp1,0x1.0000000000001p0
+exp,0x1.ffc045692fc9ep1023,0x1.62e41ffffffffp9
+exp,0x1.ffc045693009dp1023,0x1.62e42p9
+exp,0x1.ffc045693049dp1023,0x1.62e4200000001p9
+exp,0x0.000000000000ep-1022,-0x1.72e4200000001p9
+exp,0x0.000000000000ep-1022,-0x1.72e42p9
+exp,0x0.000000000000ep-1022,-0x1.72e41ffffffffp9
+exp,0x1.724046eb09339p4,0x1.921fb54442d18p1
+exp,0x1.33dedc855935fp2,0x1.921fb54442d18p0
+exp,0x1.5bf0a8b14576bp1,0x1.0000000000001p0
+exp,0x1.5bf0a8b14576ap1,0x1.0p0
+exp,0x1.5bf0a8b145769p1,0x1.fffffffffffffp-1
+exp,0x1.18bd669471caap1,0x1.921fb54442d18p-1
+exp,0x1.0p0,0x1.0000000000001p-1022
+exp,0x1.0p0,0x1.0p-1022
+exp,0x1.0p0,0x0.fffffffffffffp-1022
+exp,0x1.0p0,0x0.ffffffffffffep-1022
+exp,0x1.0p0,0x0.0000000000002p-1022
+exp,0x1.0p0,0x0.0000000000001p-1022
+exp,0x1.0p0,0x0.0p0
+exp,0x1.0p0,-0x0.0p0
+exp,0x1.0p0,-0x0.0000000000001p-1022
+exp,0x1.0p0,-0x0.0000000000002p-1022
+exp,0x1.0p0,-0x0.ffffffffffffep-1022
+exp,0x1.0p0,-0x0.fffffffffffffp-1022
+exp,0x1.0p0,-0x1.0p-1022
+exp,0x1.0p0,-0x1.0000000000001p-1022
+exp,0x1.d2e171cf04879p-2,-0x1.921fb54442d18p-1
+exp,0x1.78b56362cef38p-2,-0x1.fffffffffffffp-1
+exp,0x1.78b56362cef38p-2,-0x1.0p0
+exp,0x1.78b56362cef36p-2,-0x1.0000000000001p0
+exp,0x1.a9bcc46f767ep-3,-0x1.921fb54442d18p0
+exp,0x1.620227b598efap-5,-0x1.921fb54442d18p1
+exp,0x0.0p0,-0x1.ffffffffffffep1023
+exp,0x0.0p0,-0x1.fffffffffffffp1023
+exp,0x1.fffffffffff2ap1023,0x1.62e42fefa39efp9
+exp,0x1.000000000007cp-1022,-0x1.6232bdd7abcd2p9
+exp,0x0.ffffffffffe7cp-1022,-0x1.6232bdd7abcd3p9
+abs,0x1.5bf0a8b145769p1,0x1.5bf0a8b145769p1,2.718281828459045
+abs,0x1.5bf0a8b145769p1,-0x1.5bf0a8b145769p1,-2.718281828459045
+abs,0x0.0p0,0x0.0p0,0.0
+abs,0x0.0p0,-0x0.0p0,-0.0
+abs,0x1.0p0,0x1.0p0,1.0
+abs,0x1.0p0,-0x1.0p0,-1.0
+abs,0x1.0p-1,-0x1.0p-1,-0.5
+abs,0x1.0p-1,0x1.0p-1,0.5
+abs,0x1.921fb54442d18p2,-0x1.921fb54442d18p2,-6.283185307179586
+abs,0x1.2d97c7f3321d2p2,-0x1.2d97c7f3321d2p2,-4.71238898038469
+abs,0x1.921fb54442d18p1,-0x1.921fb54442d18p1,-3.141592653589793
+abs,0x1.921fb54442d18p0,-0x1.921fb54442d18p0,-1.5707963267948966
+abs,0x0.0p0,0x0.0p0,0.0
+abs,0x1.921fb54442d18p0,0x1.921fb54442d18p0,1.5707963267948966
+abs,0x1.921fb54442d18p1,0x1.921fb54442d18p1,3.141592653589793
+abs,0x1.2d97c7f3321d2p2,0x1.2d97c7f3321d2p2,4.71238898038469
+abs,0x1.921fb54442d18p2,0x1.921fb54442d18p2,6.283185307179586
+acos,0x1.921fb54442d18p0,0x0.0p0,0.0
+acos,0x1.921fb54442d18p0,-0x0.0p0,-0.0
+acos,0x0.0p0,0x1.0p0,1.0
+acos,0x1.921fb54442d18p1,-0x1.0p0,-1.0
+acos,0x1.0c152382d7366p1,-0x1.0p-1,-0.5
+acos,0x1.0c152382d7366p0,0x1.0p-1,0.5
+acos,0x1.921fb54442d18p0,0x0.0p0,0.0
+asin,0x0.0p0,0x0.0p0,0.0
+asin,-0x0.0p0,-0x0.0p0,-0.0
+asin,0x1.921fb54442d18p0,0x1.0p0,1.0
+asin,-0x1.921fb54442d18p0,-0x1.0p0,-1.0
+asin,-0x1.0c152382d7366p-1,-0x1.0p-1,-0.5
+asin,0x1.0c152382d7366p-1,0x1.0p-1,0.5
+asin,0x0.0p0,0x0.0p0,0.0
+atan,0x1.37e1637253389p0,0x1.5bf0a8b145769p1,2.718281828459045
+atan,-0x1.37e1637253389p0,-0x1.5bf0a8b145769p1,-2.718281828459045
+atan,0x0.0p0,0x0.0p0,0.0
+atan,-0x0.0p0,-0x0.0p0,-0.0
+atan,0x1.921fb54442d18p-1,0x1.0p0,1.0
+atan,-0x1.921fb54442d18p-1,-0x1.0p0,-1.0
+atan,-0x1.dac670561bb4fp-2,-0x1.0p-1,-0.5
+atan,0x1.dac670561bb4fp-2,0x1.0p-1,0.5
+atan,-0x1.69b8154baf42ep0,-0x1.921fb54442d18p2,-6.283185307179586
+atan,-0x1.5c97d37d98aa4p0,-0x1.2d97c7f3321d2p2,-4.71238898038469
+atan,-0x1.433b8a322ddd2p0,-0x1.921fb54442d18p1,-3.141592653589793
+atan,-0x1.00fe987ed02ffp0,-0x1.921fb54442d18p0,-1.5707963267948966
+atan,0x0.0p0,0x0.0p0,0.0
+atan,0x1.00fe987ed02ffp0,0x1.921fb54442d18p0,1.5707963267948966
+atan,0x1.433b8a322ddd2p0,0x1.921fb54442d18p1,3.141592653589793
+atan,0x1.5c97d37d98aa4p0,0x1.2d97c7f3321d2p2,4.71238898038469
+atan,0x1.69b8154baf42ep0,0x1.921fb54442d18p2,6.283185307179586
+cos,-0x1.d2cec9a554007p-1,0x1.5bf0a8b145769p1,2.718281828459045
+cos,-0x1.d2cec9a554007p-1,-0x1.5bf0a8b145769p1,-2.718281828459045
+cos,0x1.0p0,0x0.0p0,0.0
+cos,0x1.0p0,-0x0.0p0,-0.0
+cos,0x1.14a280fb5068cp-1,0x1.0p0,1.0
+cos,0x1.14a280fb5068cp-1,-0x1.0p0,-1.0
+cos,0x1.c1528065b7d5p-1,-0x1.0p-1,-0.5
+cos,0x1.c1528065b7d5p-1,0x1.0p-1,0.5
+cos,0x1.0p0,-0x1.921fb54442d18p2,-6.283185307179586
+cos,-0x1.a79394c9e8a0ap-53,-0x1.2d97c7f3321d2p2,-4.71238898038469
+cos,-0x1.0p0,-0x1.921fb54442d18p1,-3.141592653589793
+cos,0x1.1a62633145c07p-54,-0x1.921fb54442d18p0,-1.5707963267948966
+cos,0x1.0p0,0x0.0p0,0.0
+cos,0x1.1a62633145c07p-54,0x1.921fb54442d18p0,1.5707963267948966
+cos,-0x1.0p0,0x1.921fb54442d18p1,3.141592653589793
+cos,-0x1.a79394c9e8a0ap-53,0x1.2d97c7f3321d2p2,4.71238898038469
+cos,0x1.0p0,0x1.921fb54442d18p2,6.283185307179586
+cosh,0x1.e70c4a4f41685p2,0x1.5bf0a8b145769p1,2.718281828459045
+cosh,0x1.e70c4a4f41685p2,-0x1.5bf0a8b145769p1,-2.718281828459045
+cosh,0x1.0p0,0x0.0p0,0.0
+cosh,0x1.0p0,-0x0.0p0,-0.0
+cosh,0x1.8b07551d9f551p0,0x1.0p0,1.0
+cosh,0x1.8b07551d9f551p0,-0x1.0p0,-1.0
+cosh,0x1.20ac1862ae8dp0,-0x1.0p-1,-0.5
+cosh,0x1.20ac1862ae8dp0,0x1.0p-1,0.5
+cosh,0x1.0bbf2bc2b69c6p8,-0x1.921fb54442d18p2,-6.283185307179586
+cosh,0x1.bd4e9aa3e9cdbp5,-0x1.2d97c7f3321d2p2,-4.71238898038469
+cosh,0x1.72f147fee4p3,-0x1.921fb54442d18p1,-3.141592653589793
+cosh,0x1.412cc2a8d4e9ep1,-0x1.921fb54442d18p0,-1.5707963267948966
+cosh,0x1.0p0,0x0.0p0,0.0
+cosh,0x1.412cc2a8d4e9ep1,0x1.921fb54442d18p0,1.5707963267948966
+cosh,0x1.72f147fee4p3,0x1.921fb54442d18p1,3.141592653589793
+cosh,0x1.bd4e9aa3e9cdbp5,0x1.2d97c7f3321d2p2,4.71238898038469
+cosh,0x1.0bbf2bc2b69c6p8,0x1.921fb54442d18p2,6.283185307179586
+exp,0x1.e4efb75e4527ap3,0x1.5bf0a8b145769p1,2.718281828459045
+exp,0x1.0e49787e20548p-4,-0x1.5bf0a8b145769p1,-2.718281828459045
+exp,0x1.0p0,0x0.0p0,0.0
+exp,0x1.0p0,-0x0.0p0,-0.0
+exp,0x1.5bf0a8b14576ap1,0x1.0p0,1.0
+exp,0x1.78b56362cef38p-2,-0x1.0p0,-1.0
+exp,0x1.368b2fc6f960ap-1,-0x1.0p-1,-0.5
+exp,0x1.a61298e1e069cp0,0x1.0p-1,0.5
+exp,0x1.e989f5d6dff5ep-10,-0x1.921fb54442d18p2,-6.283185307179586
+exp,0x1.265d4e92b6b9cp-7,-0x1.2d97c7f3321d2p2,-4.71238898038469
+exp,0x1.620227b598efap-5,-0x1.921fb54442d18p1,-3.141592653589793
+exp,0x1.a9bcc46f767ep-3,-0x1.921fb54442d18p0,-1.5707963267948966
+exp,0x1.0p0,0x0.0p0,0.0
+exp,0x1.33dedc855935fp2,0x1.921fb54442d18p0,1.5707963267948966
+exp,0x1.724046eb09339p4,0x1.921fb54442d18p1,3.141592653589793
+exp,0x1.bd4567b97538p6,0x1.2d97c7f3321d2p2,4.71238898038469
+exp,0x1.0bbeee9177e18p9,0x1.921fb54442d18p2,6.283185307179586
+log,0x1.0p0,0x1.5bf0a8b145769p1,2.718281828459045
+log,0x0.0p0,0x1.0p0,1.0
+log,-0x1.62e42fefa39efp-1,0x1.0p-1,0.5
+log,0x1.ce6bb25aa1315p-2,0x1.921fb54442d18p0,1.5707963267948966
+log,0x1.250d048e7a1bdp0,0x1.921fb54442d18p1,3.141592653589793
+log,0x1.8cd99441787dp0,0x1.2d97c7f3321d2p2,4.71238898038469
+log,0x1.d67f1c864beb4p0,0x1.921fb54442d18p2,6.283185307179586
+log10,0x1.bcb7b1526e50ep-2,0x1.5bf0a8b145769p1,2.718281828459045
+log10,0x0.0p0,0x1.0p0,1.0
+log10,-0x1.34413509f79ffp-2,0x1.0p-1,0.5
+log10,0x1.91a74c4f85377p-3,0x1.921fb54442d18p0,1.5707963267948966
+log10,0x1.fd14db31ba3bap-2,0x1.921fb54442d18p1,3.141592653589793
+log10,0x1.58b30fc65ffdcp-1,0x1.2d97c7f3321d2p2,4.71238898038469
+log10,0x1.98ab081dd8eddp-1,0x1.921fb54442d18p2,6.283185307179586
+sin,0x1.a4a3d9c2131dfp-2,0x1.5bf0a8b145769p1,2.718281828459045
+sin,-0x1.a4a3d9c2131dfp-2,-0x1.5bf0a8b145769p1,-2.718281828459045
+sin,0x0.0p0,0x0.0p0,0.0
+sin,-0x0.0p0,-0x0.0p0,-0.0
+sin,0x1.aed548f090ceep-1,0x1.0p0,1.0
+sin,-0x1.aed548f090ceep-1,-0x1.0p0,-1.0
+sin,-0x1.eaee8744b05fp-2,-0x1.0p-1,-0.5
+sin,0x1.eaee8744b05fp-2,0x1.0p-1,0.5
+sin,0x1.1a62633145c07p-52,-0x1.921fb54442d18p2,-6.283185307179586
+sin,0x1.0p0,-0x1.2d97c7f3321d2p2,-4.71238898038469
+sin,-0x1.1a62633145c07p-53,-0x1.921fb54442d18p1,-3.141592653589793
+sin,-0x1.0p0,-0x1.921fb54442d18p0,-1.5707963267948966
+sin,0x0.0p0,0x0.0p0,0.0
+sin,0x1.0p0,0x1.921fb54442d18p0,1.5707963267948966
+sin,0x1.1a62633145c07p-53,0x1.921fb54442d18p1,3.141592653589793
+sin,-0x1.0p0,0x1.2d97c7f3321d2p2,4.71238898038469
+sin,-0x1.1a62633145c07p-52,0x1.921fb54442d18p2,6.283185307179586
+sinh,0x1.e2d3246d48e6fp2,0x1.5bf0a8b145769p1,2.718281828459045
+sinh,-0x1.e2d3246d48e6fp2,-0x1.5bf0a8b145769p1,-2.718281828459045
+sinh,0x0.0p0,0x0.0p0,0.0
+sinh,-0x0.0p0,-0x0.0p0,-0.0
+sinh,0x1.2cd9fc44eb982p0,0x1.0p0,1.0
+sinh,-0x1.2cd9fc44eb982p0,-0x1.0p0,-1.0
+sinh,-0x1.0acd00fe63b97p-1,-0x1.0p-1,-0.5
+sinh,0x1.0acd00fe63b97p-1,0x1.0p-1,0.5
+sinh,-0x1.0bbeb1603926ap8,-0x1.921fb54442d18p2,-6.283185307179586
+sinh,-0x1.bd3c34cf00a25p5,-0x1.2d97c7f3321d2p2,-4.71238898038469
+sinh,-0x1.718f45d72e672p3,-0x1.921fb54442d18p1,-3.141592653589793
+sinh,-0x1.2690f661dd82p1,-0x1.921fb54442d18p0,-1.5707963267948966
+sinh,0x0.0p0,0x0.0p0,0.0
+sinh,0x1.2690f661dd82p1,0x1.921fb54442d18p0,1.5707963267948966
+sinh,0x1.718f45d72e672p3,0x1.921fb54442d18p1,3.141592653589793
+sinh,0x1.bd3c34cf00a25p5,0x1.2d97c7f3321d2p2,4.71238898038469
+sinh,0x1.0bbeb1603926ap8,0x1.921fb54442d18p2,6.283185307179586
+sqrt,0x1.a61298e1e069cp0,0x1.5bf0a8b145769p1,2.718281828459045
+sqrt,0x0.0p0,0x0.0p0,0.0
+sqrt,-0x0.0p0,-0x0.0p0,-0.0
+sqrt,0x1.0p0,0x1.0p0,1.0
+sqrt,0x1.6a09e667f3bcdp-1,0x1.0p-1,0.5
+sqrt,0x0.0p0,0x0.0p0,0.0
+sqrt,0x1.40d931ff62705p0,0x1.921fb54442d18p0,1.5707963267948966
+sqrt,0x1.c5bf891b4ef6ap0,0x1.921fb54442d18p1,3.141592653589793
+sqrt,0x1.15dce5d1822ccp1,0x1.2d97c7f3321d2p2,4.71238898038469
+sqrt,0x1.40d931ff62705p1,0x1.921fb54442d18p2,6.283185307179586
+tan,-0x1.cd5cdb683b402p-2,0x1.5bf0a8b145769p1,2.718281828459045
+tan,0x1.cd5cdb683b402p-2,-0x1.5bf0a8b145769p1,-2.718281828459045
+tan,0x0.0p0,0x0.0p0,0.0
+tan,-0x0.0p0,-0x0.0p0,-0.0
+tan,0x1.8eb245cbee3a6p0,0x1.0p0,1.0
+tan,-0x1.8eb245cbee3a6p0,-0x1.0p0,-1.0
+tan,-0x1.17b4f5bf3474ap-1,-0x1.0p-1,-0.5
+tan,0x1.17b4f5bf3474ap-1,0x1.0p-1,0.5
+tan,0x1.1a62633145c07p-52,-0x1.921fb54442d18p2,-6.283185307179586
+tan,-0x1.3570efd768923p52,-0x1.2d97c7f3321d2p2,-4.71238898038469
+tan,0x1.1a62633145c07p-53,-0x1.921fb54442d18p1,-3.141592653589793
+tan,-0x1.d02967c31cdb5p53,-0x1.921fb54442d18p0,-1.5707963267948966
+tan,0x0.0p0,0x0.0p0,0.0
+tan,0x1.d02967c31cdb5p53,0x1.921fb54442d18p0,1.5707963267948966
+tan,-0x1.1a62633145c07p-53,0x1.921fb54442d18p1,3.141592653589793
+tan,0x1.3570efd768923p52,0x1.2d97c7f3321d2p2,4.71238898038469
+tan,-0x1.1a62633145c07p-52,0x1.921fb54442d18p2,6.283185307179586
+tanh,0x1.fb8f76b1e2ab6p-1,0x1.5bf0a8b145769p1,2.718281828459045
+tanh,-0x1.fb8f76b1e2ab6p-1,-0x1.5bf0a8b145769p1,-2.718281828459045
+tanh,0x0.0p0,0x0.0p0,0.0
+tanh,-0x0.0p0,-0x0.0p0,-0.0
+tanh,0x1.85efab514f394p-1,0x1.0p0,1.0
+tanh,-0x1.85efab514f394p-1,-0x1.0p0,-1.0
+tanh,-0x1.d9353d7568af3p-2,-0x1.0p-1,-0.5
+tanh,0x1.d9353d7568af3p-2,0x1.0p-1,0.5
+tanh,-0x1.ffff15f81f9abp-1,-0x1.921fb54442d18p2,-6.283185307179586
+tanh,-0x1.ffead8c8b7e1ep-1,-0x1.2d97c7f3321d2p2,-4.71238898038469
+tanh,-0x1.fe175fa29281p-1,-0x1.921fb54442d18p1,-3.141592653589793
+tanh,-0x1.d594fdae482bap-1,-0x1.921fb54442d18p0,-1.5707963267948966
+tanh,0x0.0p0,0x0.0p0,0.0
+tanh,0x1.d594fdae482bap-1,0x1.921fb54442d18p0,1.5707963267948966
+tanh,0x1.fe175fa29281p-1,0x1.921fb54442d18p1,3.141592653589793
+tanh,0x1.ffead8c8b7e1ep-1,0x1.2d97c7f3321d2p2,4.71238898038469
+tanh,0x1.ffff15f81f9abp-1,0x1.921fb54442d18p2,6.283185307179586
diff --git a/luni/src/test/resources/org/apache/harmony/tests/java/lang/test#.properties b/luni/src/test/resources/org/apache/harmony/tests/java/lang/test#.properties
new file mode 100644
index 0000000..299569a
--- /dev/null
+++ b/luni/src/test/resources/org/apache/harmony/tests/java/lang/test#.properties
@@ -0,0 +1 @@
+This is a resource file with a # in the name \ No newline at end of file
diff --git a/luni/src/test/resources/org/apache/harmony/tests/java/lang/test.properties b/luni/src/test/resources/org/apache/harmony/tests/java/lang/test.properties
new file mode 100644
index 0000000..2a248d0
--- /dev/null
+++ b/luni/src/test/resources/org/apache/harmony/tests/java/lang/test.properties
@@ -0,0 +1 @@
+This is just a resource file for getResource() tests \ No newline at end of file
diff --git a/luni/src/test/resources/serialization/java/text/DecimalFormat.ser b/luni/src/test/resources/serialization/java/text/DecimalFormat.ser
deleted file mode 100644
index c20fa78..0000000
--- a/luni/src/test/resources/serialization/java/text/DecimalFormat.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/java/text/DecimalFormatSymbols.ser b/luni/src/test/resources/serialization/java/text/DecimalFormatSymbols.ser
deleted file mode 100644
index 6e086af..0000000
--- a/luni/src/test/resources/serialization/java/text/DecimalFormatSymbols.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.0.ser b/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.0.ser
deleted file mode 100644
index b9a4d75..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.0.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.1.ser b/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.1.ser
deleted file mode 100644
index 6fe88ee..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.1.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.2.ser b/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.2.ser
deleted file mode 100644
index 8ef8f0b..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.2.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.3.ser b/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.3.ser
deleted file mode 100644
index 00ac616..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.golden.3.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.ser b/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.ser
deleted file mode 100644
index 8ef8f0b..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/util/UUIDTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/util/UUIDTest.golden.ser
deleted file mode 100644
index 9947a3a..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/luni/tests/java/util/UUIDTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.golden.ser
deleted file mode 100644
index 80e8f7c..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.golden.ser
deleted file mode 100644
index 2e0fc6d..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.golden.ser
deleted file mode 100644
index c29debf..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.golden.ser
deleted file mode 100644
index fbbc876..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.golden.ser
deleted file mode 100644
index 9bd539c..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.golden.ser
deleted file mode 100644
index 6dbac7d..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.golden.ser
deleted file mode 100644
index 40288df..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.golden.ser
deleted file mode 100644
index 1f1e73b..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.golden.ser
deleted file mode 100644
index ea5b80a..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.golden.ser
deleted file mode 100644
index 1831746..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.golden.ser
deleted file mode 100644
index 9e17263..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.golden.ser
deleted file mode 100644
index 4024191..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.golden.ser
deleted file mode 100644
index c15c66b..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.golden.ser
deleted file mode 100644
index 89ed091..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.golden.ser
deleted file mode 100644
index 022d3bc..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.golden.ser
deleted file mode 100644
index 5cf767c..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.golden.ser
deleted file mode 100644
index 34a42e9..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.golden.ser
deleted file mode 100644
index 69d1a57..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.golden.ser
deleted file mode 100644
index b5cc027..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.golden.ser
deleted file mode 100644
index 9c0e175..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.golden.ser
deleted file mode 100644
index 2a24deb..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.golden.ser
deleted file mode 100644
index 1dd6a01..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.golden.ser
deleted file mode 100644
index a95c4e4..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.golden.ser
deleted file mode 100644
index 6f4a4e3..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.golden.ser
deleted file mode 100644
index 59e4d0b..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.golden.ser
deleted file mode 100644
index e2f0dec..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.golden.ser
deleted file mode 100644
index 7933fb9..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.golden.ser b/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.golden.ser
deleted file mode 100644
index 07c63bb..0000000
--- a/luni/src/test/resources/serialization/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDClass.ser b/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDClass.ser
deleted file mode 100644
index b93df24..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDClass.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDConstructors.ser b/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDConstructors.ser
deleted file mode 100644
index a333f4e..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDConstructors.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDFields.ser b/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDFields.ser
deleted file mode 100644
index 7f93135..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDFields.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDInterfaces.ser b/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDInterfaces.ser
deleted file mode 100644
index c579d14..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDInterfaces.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDMethods.ser b/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDMethods.ser
deleted file mode 100644
index 48618eb..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/io/testComputeSUIDMethods.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/util/EnumMapTest.golden.ser b/luni/src/test/resources/serialization/tests/api/java/util/EnumMapTest.golden.ser
deleted file mode 100644
index 76f7668..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/util/EnumMapTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/util/EnumSetTest.golden.ser b/luni/src/test/resources/serialization/tests/api/java/util/EnumSetTest.golden.ser
deleted file mode 100644
index 66040e5..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/util/EnumSetTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/util/HashSetTest.golden.ser b/luni/src/test/resources/serialization/tests/api/java/util/HashSetTest.golden.ser
deleted file mode 100644
index 5d76a32..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/util/HashSetTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/api/java/util/IdentityHashMapTest.golden.ser b/luni/src/test/resources/serialization/tests/api/java/util/IdentityHashMapTest.golden.ser
deleted file mode 100644
index 8f27937..0000000
--- a/luni/src/test/resources/serialization/tests/api/java/util/IdentityHashMapTest.golden.ser
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/serialization/tests/security/cert/CertificateRevocationExceptionTest.golden.ser b/luni/src/test/resources/serialization/tests/security/cert/CertificateRevocationExceptionTest.golden.ser
new file mode 100644
index 0000000..f9f2746
--- /dev/null
+++ b/luni/src/test/resources/serialization/tests/security/cert/CertificateRevocationExceptionTest.golden.ser
Binary files differ
diff --git a/luni/src/test/resources/tests/api/java/lang/reflect/dex1.bytes b/luni/src/test/resources/tests/api/java/lang/reflect/dex1.bytes
deleted file mode 100644
index dfff949..0000000
--- a/luni/src/test/resources/tests/api/java/lang/reflect/dex1.bytes
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/resources/tests/resources/java/util/zip/EmptyArchive.zip b/luni/src/test/resources/tests/resources/java/util/zip/EmptyArchive.zip
new file mode 100644
index 0000000..15cb0ec
--- /dev/null
+++ b/luni/src/test/resources/tests/resources/java/util/zip/EmptyArchive.zip
Binary files differ