* getProxySelector
* The ability to get the proxy selector used to make decisions
* on which proxies to use when making network connections.
diff --git a/jdk/src/share/classes/java/net/URI.java b/jdk/src/share/classes/java/net/URI.java
index 111269d8b93..3465e1ab879 100644
--- a/jdk/src/share/classes/java/net/URI.java
+++ b/jdk/src/share/classes/java/net/URI.java
@@ -991,7 +991,7 @@ public final class URI
* authority and path are taken from the given URI.
*
* Otherwise the new URI's authority component is copied from
- * this URI, and its path is computed as follows:
+ * this URI, and its path is computed as follows:
*
*
*
@@ -1005,7 +1005,7 @@ public final class URI
* path and then normalizing the result as if by invoking the {@link
* #normalize() normalize} method.
*
- *
+ *
*
*
*
@@ -1511,7 +1511,7 @@ public final class URI
* fragments.
*
* Two hierarchical URIs with identical schemes are ordered
- * according to the ordering of their authority components:
+ * according to the ordering of their authority components:
*
*
*
@@ -1526,7 +1526,7 @@ public final class URI
* the URIs are ordered according to the ordering of their authority
* components.
*
- *
+ *
*
* Finally, two hierarchical URIs with identical schemes and
* authority components are ordered according to the ordering of their
diff --git a/jdk/src/share/classes/java/net/package.html b/jdk/src/share/classes/java/net/package.html
index 7c7058d7b1c..12dfe9803d0 100644
--- a/jdk/src/share/classes/java/net/package.html
+++ b/jdk/src/share/classes/java/net/package.html
@@ -31,18 +31,18 @@ Provides the classes for implementing networking applications.
The java.net package can be roughly divided in two sections:
- A Low Level API , which deals with the following abstractions:
+ A Low Level API , which deals with the following abstractions:
Addresses , which are networking identifiers, like IP addresses.
Sockets , which are basic bidirectional data communication mechanisms.
Interfaces , which describe network interfaces.
-
- A High Level API , which deals with the following abstractions:
+
+ A High Level API , which deals with the following abstractions:
URIs , which represent Universal Resource Identifiers.
URLs , which represent Universal Resource Locators.
Connections , which represents connections to the resource pointed to by URLs .
-
+
Addresses
Addresses are used throughout the java.net APIs as either host identifiers, or socket endpoint identifiers.
diff --git a/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java b/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java
index 1ca3417cce2..3e90769d329 100644
--- a/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java
+++ b/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java
@@ -48,12 +48,12 @@ import java.util.Collections;
*
* An asynchronous file channel does not have a current position
* within the file. Instead, the file position is specified to each read and
- * write methd that initiate asynchronous operations. A {@link CompletionHandler}
+ * write method that initiates asynchronous operations. A {@link CompletionHandler}
* is specified as a parameter and is invoked to consume the result of the I/O
* operation. This class also defines read and write methods that initiate
* asynchronous operations, returning a {@link Future} to represent the pending
* result of the operation. The {@code Future} may be used to check if the
- * operation has completed, to wait for its completion.
+ * operation has completed, wait for its completion, and retrieve the result.
*
*
In addition to read and write operations, this class defines the
* following operations:
@@ -73,13 +73,13 @@ import java.util.Collections;
* which tasks are submitted to handle I/O events and dispatch to completion
* handlers that consume the results of I/O operations on the channel. The
* completion handler for an I/O operation initiated on a channel is guaranteed
- * to be invoked by one threads in the thread pool (This ensures that the
+ * to be invoked by one of the threads in the thread pool (This ensures that the
* completion handler is run by a thread with the expected identity ).
* Where an I/O operation completes immediately, and the initiating thread is
* itself a thread in the thread pool, then the completion handler may be invoked
* directly by the initiating thread. When an {@code AsynchronousFileChannel} is
* created without specifying a thread pool then the channel is associated with
- * a system-dependent and default thread pool that may be shared with other
+ * a system-dependent default thread pool that may be shared with other
* channels. The default thread pool is configured by the system properties
* defined by the {@link AsynchronousChannelGroup} class.
*
diff --git a/jdk/src/share/classes/java/nio/channels/SocketChannel.java b/jdk/src/share/classes/java/nio/channels/SocketChannel.java
index fe044c4741d..b582c6d656a 100644
--- a/jdk/src/share/classes/java/nio/channels/SocketChannel.java
+++ b/jdk/src/share/classes/java/nio/channels/SocketChannel.java
@@ -182,10 +182,13 @@ public abstract class SocketChannel
SocketChannel sc = open();
try {
sc.connect(remote);
- } finally {
- if (!sc.isConnected()) {
- try { sc.close(); } catch (IOException x) { }
+ } catch (Throwable x) {
+ try {
+ sc.close();
+ } catch (Throwable suppressed) {
+ x.addSuppressed(suppressed);
}
+ throw x;
}
assert sc.isConnected();
return sc;
diff --git a/jdk/src/share/classes/java/nio/file/CopyMoveHelper.java b/jdk/src/share/classes/java/nio/file/CopyMoveHelper.java
index 70ca6ee50ad..54bfe085962 100644
--- a/jdk/src/share/classes/java/nio/file/CopyMoveHelper.java
+++ b/jdk/src/share/classes/java/nio/file/CopyMoveHelper.java
@@ -135,11 +135,13 @@ class CopyMoveHelper {
view.setTimes(attrs.lastModifiedTime(),
attrs.lastAccessTime(),
attrs.creationTime());
- } catch (IOException x) {
+ } catch (Throwable x) {
// rollback
try {
Files.delete(target);
- } catch (IOException ignore) { }
+ } catch (Throwable suppressed) {
+ x.addSuppressed(suppressed);
+ }
throw x;
}
}
diff --git a/jdk/src/share/classes/java/nio/file/Files.java b/jdk/src/share/classes/java/nio/file/Files.java
index 357529ac9cf..3e19ca3e515 100644
--- a/jdk/src/share/classes/java/nio/file/Files.java
+++ b/jdk/src/share/classes/java/nio/file/Files.java
@@ -129,17 +129,18 @@ public final class Files {
*
* Path path = ...
*
- * // replace an existing file or create the file if it doesn't initially exist
+ * // truncate and overwrite an existing file, or create the file if
+ * // it doesn't initially exist
* OutputStream out = Files.newOutputStream(path);
*
* // append to an existing file, fail if the file does not exist
* out = Files.newOutputStream(path, APPEND);
*
* // append to an existing file, create file if it doesn't initially exist
- * out = Files.newOutputStream(CREATE, APPEND);
+ * out = Files.newOutputStream(path, CREATE, APPEND);
*
* // always create new file, failing if it already exists
- * out = Files.newOutputStream(CREATE_NEW);
+ * out = Files.newOutputStream(path, CREATE_NEW);
*
*
* @param path
@@ -793,7 +794,8 @@ public final class Files {
FileAttribute>... attrs)
throws IOException
{
- return TempFileHelper.createTempFile(dir, prefix, suffix, attrs);
+ return TempFileHelper.createTempFile(Objects.requireNonNull(dir),
+ prefix, suffix, attrs);
}
/**
@@ -890,13 +892,14 @@ public final class Files {
FileAttribute>... attrs)
throws IOException
{
- return TempFileHelper.createTempDirectory(dir, prefix, attrs);
+ return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir),
+ prefix, attrs);
}
/**
* Creates a new directory in the default temporary-file directory, using
- * the given prefix and suffix to generate its name. The resulting {@code
- * Path} is associated with the default {@code FileSystem}.
+ * the given prefix to generate its name. The resulting {@code Path} is
+ * associated with the default {@code FileSystem}.
*
* This method works in exactly the manner specified by {@link
* #createTempDirectory(Path,String,FileAttribute[])} method for the case
@@ -2583,7 +2586,7 @@ public final class Files {
* walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor)
*
* In other words, it does not follow symbolic links, and visits all levels
- * of the file level.
+ * of the file tree.
*
* @param start
* the starting file
@@ -3005,7 +3008,7 @@ public final class Files {
* or after some bytes have been written to the file.
*
*
Usage example : By default the method creates a new file or
- * overrides an existing file. Suppose you instead want to append bytes
+ * overwrites an existing file. Suppose you instead want to append bytes
* to an existing file:
*
* Path path = ...
diff --git a/jdk/src/share/classes/java/security/CodeSigner.java b/jdk/src/share/classes/java/security/CodeSigner.java
index 75a9df9d24b..0b233d321fa 100644
--- a/jdk/src/share/classes/java/security/CodeSigner.java
+++ b/jdk/src/share/classes/java/security/CodeSigner.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,7 @@
package java.security;
import java.io.*;
-import java.security.cert.CRL;
import java.security.cert.CertPath;
-import sun.misc.JavaSecurityCodeSignerAccess;
-import sun.misc.SharedSecrets;
/**
* This class encapsulates information about a code signer.
@@ -167,44 +164,6 @@ public final class CodeSigner implements Serializable {
return sb.toString();
}
- // A private attribute attached to this CodeSigner object. Can be accessed
- // through SharedSecrets.getJavaSecurityCodeSignerAccess().[g|s]etCRLs
- //
- // Currently called in SignatureFileVerifier.getSigners
- private transient CRL[] crls;
-
- /**
- * Sets the CRLs attached
- * @param crls, null to clear
- */
- void setCRLs(CRL[] crls) {
- this.crls = crls;
- }
-
- /**
- * Returns the CRLs attached
- * @return the crls, initially null
- */
- CRL[] getCRLs() {
- return crls;
- }
-
- // Set up JavaSecurityCodeSignerAccess in SharedSecrets
- static {
- SharedSecrets.setJavaSecurityCodeSignerAccess(
- new JavaSecurityCodeSignerAccess() {
- @Override
- public void setCRLs(CodeSigner signer, CRL[] crls) {
- signer.setCRLs(crls);
- }
-
- @Override
- public CRL[] getCRLs(CodeSigner signer) {
- return signer.getCRLs();
- }
- });
- }
-
// Explicitly reset hash code value to -1
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
diff --git a/jdk/src/share/classes/java/util/Currency.java b/jdk/src/share/classes/java/util/Currency.java
index b3058053afa..e9ce7005df6 100644
--- a/jdk/src/share/classes/java/util/Currency.java
+++ b/jdk/src/share/classes/java/util/Currency.java
@@ -233,7 +233,9 @@ public final class Currency implements Serializable {
"currency.properties");
if (propFile.exists()) {
Properties props = new Properties();
- props.load(new FileReader(propFile));
+ try (FileReader fr = new FileReader(propFile)) {
+ props.load(fr);
+ }
Set keys = props.stringPropertyNames();
Pattern propertiesPattern =
Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])");
diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java
index 2158084f9f9..1030fac0423 100644
--- a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java
@@ -272,13 +272,6 @@ public class ConcurrentLinkedDeque
private static final Node PREV_TERMINATOR, NEXT_TERMINATOR;
- static {
- PREV_TERMINATOR = new Node(null);
- PREV_TERMINATOR.next = PREV_TERMINATOR;
- NEXT_TERMINATOR = new Node(null);
- NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
- }
-
@SuppressWarnings("unchecked")
Node prevTerminator() {
return (Node) PREV_TERMINATOR;
@@ -294,6 +287,9 @@ public class ConcurrentLinkedDeque
volatile E item;
volatile Node next;
+ Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR
+ }
+
/**
* Constructs a new node. Uses relaxed write because item can
* only be seen after publication via casNext or casPrev.
@@ -324,14 +320,25 @@ public class ConcurrentLinkedDeque
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE =
- sun.misc.Unsafe.getUnsafe();
- private static final long prevOffset =
- objectFieldOffset(UNSAFE, "prev", Node.class);
- private static final long itemOffset =
- objectFieldOffset(UNSAFE, "item", Node.class);
- private static final long nextOffset =
- objectFieldOffset(UNSAFE, "next", Node.class);
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long prevOffset;
+ private static final long itemOffset;
+ private static final long nextOffset;
+
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = Node.class;
+ prevOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("prev"));
+ itemOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("item"));
+ nextOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("next"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/**
@@ -1422,14 +1429,6 @@ public class ConcurrentLinkedDeque
initHeadTail(h, t);
}
- // Unsafe mechanics
-
- private static final sun.misc.Unsafe UNSAFE =
- sun.misc.Unsafe.getUnsafe();
- private static final long headOffset =
- objectFieldOffset(UNSAFE, "head", ConcurrentLinkedDeque.class);
- private static final long tailOffset =
- objectFieldOffset(UNSAFE, "tail", ConcurrentLinkedDeque.class);
private boolean casHead(Node cmp, Node val) {
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
@@ -1439,15 +1438,25 @@ public class ConcurrentLinkedDeque
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
}
- static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
- String field, Class> klazz) {
+ // Unsafe mechanics
+
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long headOffset;
+ private static final long tailOffset;
+ static {
+ PREV_TERMINATOR = new Node();
+ PREV_TERMINATOR.next = PREV_TERMINATOR;
+ NEXT_TERMINATOR = new Node();
+ NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
try {
- return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
- } catch (NoSuchFieldException e) {
- // Convert Exception to corresponding Error
- NoSuchFieldError error = new NoSuchFieldError(field);
- error.initCause(e);
- throw error;
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = ConcurrentLinkedDeque.class;
+ headOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("head"));
+ tailOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("tail"));
+ } catch (Exception e) {
+ throw new Error(e);
}
}
}
diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java
index b7beda274da..54bd8cbfff5 100644
--- a/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java
@@ -194,12 +194,22 @@ public class ConcurrentLinkedQueue extends AbstractQueue
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE =
- sun.misc.Unsafe.getUnsafe();
- private static final long nextOffset =
- objectFieldOffset(UNSAFE, "next", Node.class);
- private static final long itemOffset =
- objectFieldOffset(UNSAFE, "item", Node.class);
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long itemOffset;
+ private static final long nextOffset;
+
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = Node.class;
+ itemOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("item"));
+ nextOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("next"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/**
@@ -790,14 +800,6 @@ public class ConcurrentLinkedQueue extends AbstractQueue
throw new NullPointerException();
}
- // Unsafe mechanics
-
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long headOffset =
- objectFieldOffset(UNSAFE, "head", ConcurrentLinkedQueue.class);
- private static final long tailOffset =
- objectFieldOffset(UNSAFE, "tail", ConcurrentLinkedQueue.class);
-
private boolean casTail(Node cmp, Node val) {
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
}
@@ -806,15 +808,21 @@ public class ConcurrentLinkedQueue extends AbstractQueue
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
}
- static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
- String field, Class> klazz) {
+ // Unsafe mechanics
+
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long headOffset;
+ private static final long tailOffset;
+ static {
try {
- return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
- } catch (NoSuchFieldException e) {
- // Convert Exception to corresponding Error
- NoSuchFieldError error = new NoSuchFieldError(field);
- error.initCause(e);
- throw error;
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = ConcurrentLinkedQueue.class;
+ headOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("head"));
+ tailOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("tail"));
+ } catch (Exception e) {
+ throw new Error(e);
}
}
}
diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java
index 64d28cf6040..f1b11140291 100644
--- a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListMap.java
@@ -507,13 +507,24 @@ public class ConcurrentSkipListMap extends AbstractMap
return new AbstractMap.SimpleImmutableEntry(key, v);
}
- // Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long valueOffset =
- objectFieldOffset(UNSAFE, "value", Node.class);
- private static final long nextOffset =
- objectFieldOffset(UNSAFE, "next", Node.class);
+ // UNSAFE mechanics
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long valueOffset;
+ private static final long nextOffset;
+
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = Node.class;
+ valueOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("value"));
+ nextOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("next"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/* ---------------- Indexing -------------- */
@@ -580,10 +591,18 @@ public class ConcurrentSkipListMap extends AbstractMap
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long rightOffset =
- objectFieldOffset(UNSAFE, "right", Index.class);
-
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long rightOffset;
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = Index.class;
+ rightOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("right"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/* ---------------- Head nodes -------------- */
@@ -3082,20 +3101,16 @@ public class ConcurrentSkipListMap extends AbstractMap
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long headOffset =
- objectFieldOffset(UNSAFE, "head", ConcurrentSkipListMap.class);
-
- static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
- String field, Class> klazz) {
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long headOffset;
+ static {
try {
- return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
- } catch (NoSuchFieldException e) {
- // Convert Exception to corresponding Error
- NoSuchFieldError error = new NoSuchFieldError(field);
- error.initCause(e);
- throw error;
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = ConcurrentSkipListMap.class;
+ headOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("head"));
+ } catch (Exception e) {
+ throw new Error(e);
}
}
-
}
diff --git a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java
index 09f8dc6f5b2..04b845c3f87 100644
--- a/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java
@@ -470,16 +470,20 @@ public class ConcurrentSkipListSet
}
// Support for resetting map in clone
- private static final Unsafe unsafe = Unsafe.getUnsafe();
+ private void setMap(ConcurrentNavigableMap map) {
+ UNSAFE.putObjectVolatile(this, mapOffset, map);
+ }
+
+ private static final sun.misc.Unsafe UNSAFE;
private static final long mapOffset;
static {
try {
- mapOffset = unsafe.objectFieldOffset
- (ConcurrentSkipListSet.class.getDeclaredField("m"));
- } catch (Exception ex) { throw new Error(ex); }
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = ConcurrentSkipListSet.class;
+ mapOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("m"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
}
- private void setMap(ConcurrentNavigableMap map) {
- unsafe.putObjectVolatile(this, mapOffset, map);
- }
-
}
diff --git a/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java
index 8c5193538fa..e39cbeeb2d7 100644
--- a/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java
+++ b/jdk/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java
@@ -1318,16 +1318,19 @@ public class CopyOnWriteArrayList
}
// Support for resetting lock while deserializing
- private static final Unsafe unsafe = Unsafe.getUnsafe();
+ private void resetLock() {
+ UNSAFE.putObjectVolatile(this, lockOffset, new ReentrantLock());
+ }
+ private static final sun.misc.Unsafe UNSAFE;
private static final long lockOffset;
static {
try {
- lockOffset = unsafe.objectFieldOffset
- (CopyOnWriteArrayList.class.getDeclaredField("lock"));
- } catch (Exception ex) { throw new Error(ex); }
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = CopyOnWriteArrayList.class;
+ lockOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("lock"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
}
- private void resetLock() {
- unsafe.putObjectVolatile(this, lockOffset, new ReentrantLock());
- }
-
}
diff --git a/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java b/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java
index fec92a8b189..7571978169b 100644
--- a/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java
+++ b/jdk/src/share/classes/java/util/concurrent/LinkedTransferQueue.java
@@ -525,16 +525,27 @@ public class LinkedTransferQueue extends AbstractQueue
return false;
}
- // Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long nextOffset =
- objectFieldOffset(UNSAFE, "next", Node.class);
- private static final long itemOffset =
- objectFieldOffset(UNSAFE, "item", Node.class);
- private static final long waiterOffset =
- objectFieldOffset(UNSAFE, "waiter", Node.class);
-
private static final long serialVersionUID = -3375979862319811754L;
+
+ // Unsafe mechanics
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long itemOffset;
+ private static final long nextOffset;
+ private static final long waiterOffset;
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = Node.class;
+ itemOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("item"));
+ nextOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("next"));
+ waiterOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("waiter"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/** head of the queue; null until first enqueue */
@@ -1312,23 +1323,22 @@ public class LinkedTransferQueue extends AbstractQueue
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long headOffset =
- objectFieldOffset(UNSAFE, "head", LinkedTransferQueue.class);
- private static final long tailOffset =
- objectFieldOffset(UNSAFE, "tail", LinkedTransferQueue.class);
- private static final long sweepVotesOffset =
- objectFieldOffset(UNSAFE, "sweepVotes", LinkedTransferQueue.class);
-
- static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
- String field, Class> klazz) {
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long headOffset;
+ private static final long tailOffset;
+ private static final long sweepVotesOffset;
+ static {
try {
- return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
- } catch (NoSuchFieldException e) {
- // Convert Exception to corresponding Error
- NoSuchFieldError error = new NoSuchFieldError(field);
- error.initCause(e);
- throw error;
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = LinkedTransferQueue.class;
+ headOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("head"));
+ tailOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("tail"));
+ sweepVotesOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("sweepVotes"));
+ } catch (Exception e) {
+ throw new Error(e);
}
}
}
diff --git a/jdk/src/share/classes/java/util/concurrent/Phaser.java b/jdk/src/share/classes/java/util/concurrent/Phaser.java
index d5725b3e1a2..7e362219179 100644
--- a/jdk/src/share/classes/java/util/concurrent/Phaser.java
+++ b/jdk/src/share/classes/java/util/concurrent/Phaser.java
@@ -1137,18 +1137,16 @@ public class Phaser {
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long stateOffset =
- objectFieldOffset("state", Phaser.class);
-
- private static long objectFieldOffset(String field, Class> klazz) {
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long stateOffset;
+ static {
try {
- return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
- } catch (NoSuchFieldException e) {
- // Convert Exception to corresponding Error
- NoSuchFieldError error = new NoSuchFieldError(field);
- error.initCause(e);
- throw error;
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = Phaser.class;
+ stateOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("state"));
+ } catch (Exception e) {
+ throw new Error(e);
}
}
}
diff --git a/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java b/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java
index 60928ac8a74..5ad7fa71d71 100644
--- a/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java
+++ b/jdk/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java
@@ -963,21 +963,16 @@ public class PriorityBlockingQueue extends AbstractQueue
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long allocationSpinLockOffset =
- objectFieldOffset(UNSAFE, "allocationSpinLock",
- PriorityBlockingQueue.class);
-
- static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
- String field, Class> klazz) {
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long allocationSpinLockOffset;
+ static {
try {
- return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
- } catch (NoSuchFieldException e) {
- // Convert Exception to corresponding Error
- NoSuchFieldError error = new NoSuchFieldError(field);
- error.initCause(e);
- throw error;
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = PriorityBlockingQueue.class;
+ allocationSpinLockOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("allocationSpinLock"));
+ } catch (Exception e) {
+ throw new Error(e);
}
}
-
}
diff --git a/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java b/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java
index 47b352f9e35..d02f56d9b72 100644
--- a/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java
+++ b/jdk/src/share/classes/java/util/concurrent/SynchronousQueue.java
@@ -279,12 +279,22 @@ public class SynchronousQueue extends AbstractQueue
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long nextOffset =
- objectFieldOffset(UNSAFE, "next", SNode.class);
- private static final long matchOffset =
- objectFieldOffset(UNSAFE, "match", SNode.class);
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long matchOffset;
+ private static final long nextOffset;
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = SNode.class;
+ matchOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("match"));
+ nextOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("next"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/** The head (top) of the stack */
@@ -498,10 +508,18 @@ public class SynchronousQueue extends AbstractQueue
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long headOffset =
- objectFieldOffset(UNSAFE, "head", TransferStack.class);
-
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long headOffset;
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = TransferStack.class;
+ headOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("head"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/** Dual Queue */
@@ -558,11 +576,22 @@ public class SynchronousQueue extends AbstractQueue
}
// Unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long nextOffset =
- objectFieldOffset(UNSAFE, "next", QNode.class);
- private static final long itemOffset =
- objectFieldOffset(UNSAFE, "item", QNode.class);
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long itemOffset;
+ private static final long nextOffset;
+
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = QNode.class;
+ itemOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("item"));
+ nextOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("next"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/** Head of queue */
@@ -791,15 +820,24 @@ public class SynchronousQueue extends AbstractQueue
}
}
- // unsafe mechanics
- private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
- private static final long headOffset =
- objectFieldOffset(UNSAFE, "head", TransferQueue.class);
- private static final long tailOffset =
- objectFieldOffset(UNSAFE, "tail", TransferQueue.class);
- private static final long cleanMeOffset =
- objectFieldOffset(UNSAFE, "cleanMe", TransferQueue.class);
-
+ private static final sun.misc.Unsafe UNSAFE;
+ private static final long headOffset;
+ private static final long tailOffset;
+ private static final long cleanMeOffset;
+ static {
+ try {
+ UNSAFE = sun.misc.Unsafe.getUnsafe();
+ Class k = TransferQueue.class;
+ headOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("head"));
+ tailOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("tail"));
+ cleanMeOffset = UNSAFE.objectFieldOffset
+ (k.getDeclaredField("cleanMe"));
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
}
/**
diff --git a/jdk/src/share/classes/java/util/jar/JarFile.java b/jdk/src/share/classes/java/util/jar/JarFile.java
index a5795c72763..79d0f84b7e1 100644
--- a/jdk/src/share/classes/java/util/jar/JarFile.java
+++ b/jdk/src/share/classes/java/util/jar/JarFile.java
@@ -376,9 +376,9 @@ class JarFile extends ZipFile {
*/
private byte[] getBytes(ZipEntry ze) throws IOException {
byte[] b = new byte[(int)ze.getSize()];
- DataInputStream is = new DataInputStream(super.getInputStream(ze));
- is.readFully(b, 0, b.length);
- is.close();
+ try (DataInputStream is = new DataInputStream(super.getInputStream(ze))) {
+ is.readFully(b, 0, b.length);
+ }
return b;
}
@@ -480,10 +480,10 @@ class JarFile extends ZipFile {
JarEntry manEntry = getManEntry();
if (manEntry != null) {
byte[] b = new byte[(int)manEntry.getSize()];
- DataInputStream dis = new DataInputStream(
- super.getInputStream(manEntry));
- dis.readFully(b, 0, b.length);
- dis.close();
+ try (DataInputStream dis = new DataInputStream(
+ super.getInputStream(manEntry))) {
+ dis.readFully(b, 0, b.length);
+ }
int last = b.length - src.length;
int i = 0;
diff --git a/jdk/src/share/classes/java/util/zip/ZipEntry.java b/jdk/src/share/classes/java/util/zip/ZipEntry.java
index 0a86f2d447d..7d05c9dd632 100644
--- a/jdk/src/share/classes/java/util/zip/ZipEntry.java
+++ b/jdk/src/share/classes/java/util/zip/ZipEntry.java
@@ -26,7 +26,6 @@
package java.util.zip;
import java.util.Date;
-import sun.misc.BootClassLoaderHook;
/**
* This class is used to represent a ZIP file entry.
diff --git a/jdk/src/share/classes/javax/crypto/SecretKeyFactory.java b/jdk/src/share/classes/javax/crypto/SecretKeyFactory.java
index 1d00db7badb..bf32bae08c5 100644
--- a/jdk/src/share/classes/javax/crypto/SecretKeyFactory.java
+++ b/jdk/src/share/classes/javax/crypto/SecretKeyFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -61,7 +61,6 @@ import sun.security.jca.GetInstance.Instance;
* Every implementation of the Java platform is required to support the
* following standard SecretKeyFactory algorithms:
*
diff --git a/jdk/src/share/classes/sun/misc/BootClassLoaderHook.java b/jdk/src/share/classes/sun/misc/BootClassLoaderHook.java
deleted file mode 100644
index 0df465c3e66..00000000000
--- a/jdk/src/share/classes/sun/misc/BootClassLoaderHook.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.misc;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URLStreamHandlerFactory;
-import sun.misc.URLClassPath;
-
-/**
- * BootClassLoaderHook defines an interface for a hook to inject
- * into the bootstrap class loader.
- *
- * With jkernel now removed, no hook is set
- */
-public abstract class BootClassLoaderHook {
- private static BootClassLoaderHook bootLoaderHook = null;
- public static synchronized BootClassLoaderHook getHook() {
- return bootLoaderHook;
- }
-
- public static synchronized void setHook(BootClassLoaderHook hook) {
- if (!VM.isBooted()) {
- throw new InternalError("hook can only be set after VM is booted");
- }
- if (bootLoaderHook != null) {
- throw new InternalError("hook should not be reinitialized");
- }
- bootLoaderHook = hook;
- }
-
- protected BootClassLoaderHook() {
- }
-
- /**
- * A method to be invoked before a class loader loads
- * a bootstrap class.
- *
- * @param classname the binary name of the class
- */
- public static void preLoadClass(String classname) {
- BootClassLoaderHook hook = getHook();
- if (hook != null) {
- hook.loadBootstrapClass(classname);
- }
- }
-
- /**
- * A method to be invoked before a class loader loads
- * a resource.
- *
- * @param resourcename the resource name
- */
- public static void preLoadResource(String resourcename) {
- BootClassLoaderHook hook = getHook();
- if (hook != null) {
- hook.getBootstrapResource(resourcename);
- }
- }
-
- /**
- * A method to be invoked before a library is loaded.
- *
- * @param libname the name of the library
- */
- public static void preLoadLibrary(String libname) {
- BootClassLoaderHook hook = getHook();
- if (hook != null) {
- hook.loadLibrary(libname);
- }
- }
-
- /**
- * Returns a pathname of a JAR or class that the hook loads
- * per this loadClass request; or null.
- *
- * @param classname the binary name of the class
- */
- public abstract String loadBootstrapClass(String className);
-
- /**
- * Returns a pathname of a resource file that the hook loads
- * per this getResource request; or null.
- *
- * @param resourceName the resource name
- */
- public abstract String getBootstrapResource(String resourceName);
-
- /**
- * Returns true if the hook successfully performs an operation per
- * this loadLibrary request; or false if it fails.
- *
- * @param libname the name of the library
- */
- public abstract boolean loadLibrary(String libname);
-
- /**
- * Returns a bootstrap class path constructed by the hook.
- *
- * @param bcp VM's bootstrap class path
- * @param factory Launcher's URL stream handler
- */
- public abstract URLClassPath getBootstrapClassPath(URLClassPath bcp,
- URLStreamHandlerFactory factory);
-
- /**
- * Returns true if the current thread is in the process of doing
- * a prefetching operation.
- */
- public abstract boolean isCurrentThreadPrefetching();
-
- /**
- * Returns true if the hook successfully prefetches the specified file.
- *
- * @param name a platform independent pathname
- */
- public abstract boolean prefetchFile(String name);
-}
diff --git a/jdk/src/share/classes/sun/misc/Launcher.java b/jdk/src/share/classes/sun/misc/Launcher.java
index 93a6b168f33..81da69490fe 100644
--- a/jdk/src/share/classes/sun/misc/Launcher.java
+++ b/jdk/src/share/classes/sun/misc/Launcher.java
@@ -38,7 +38,6 @@ import java.util.StringTokenizer;
import java.util.Set;
import java.util.Vector;
import java.security.AccessController;
-import java.security.AllPermission;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.AccessControlContext;
@@ -117,18 +116,6 @@ public class Launcher {
return loader;
}
- public static void addURLToAppClassLoader(URL u) {
- AccessController.checkPermission(new AllPermission());
- ClassLoader loader = Launcher.getLauncher().getClassLoader();
- ((Launcher.AppClassLoader) loader).addAppURL(u);
- }
-
- public static void addURLToExtClassLoader(URL u) {
- AccessController.checkPermission(new AllPermission());
- ClassLoader loader = Launcher.getLauncher().getClassLoader();
- ((Launcher.ExtClassLoader) loader.getParent()).addExtURL(u);
- }
-
/*
* The class loader used for loading installed extensions.
*/
@@ -247,11 +234,6 @@ public class Launcher {
return null;
}
- protected Class findClass(String name) throws ClassNotFoundException {
- BootClassLoaderHook.preLoadClass(name);
- return super.findClass(name);
- }
-
private static AccessControlContext getContext(File[] dirs)
throws IOException
{
@@ -316,7 +298,6 @@ public class Launcher {
public Class loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
- BootClassLoaderHook.preLoadClass(name);
int i = name.lastIndexOf('.');
if (i != -1) {
SecurityManager sm = System.getSecurityManager();
@@ -373,10 +354,6 @@ public class Launcher {
return acc;
}
-
- void addAppURL(URL url) {
- super.addURL(url);
- }
}
private static class BootClassPathHolder {
@@ -413,11 +390,7 @@ public class Launcher {
}
public static URLClassPath getBootstrapClassPath() {
- URLClassPath bcp = BootClassPathHolder.bcp;
- // if DownloadManager is installed, return the bootstrap class path
- // maintained by the Java kernel
- BootClassLoaderHook hook = BootClassLoaderHook.getHook();
- return hook == null ? bcp : hook.getBootstrapClassPath(bcp, factory);
+ return BootClassPathHolder.bcp;
}
private static URL[] pathToURLs(File[] path) {
diff --git a/jdk/src/share/classes/sun/misc/SharedSecrets.java b/jdk/src/share/classes/sun/misc/SharedSecrets.java
index 77c0aa8a095..2335b2d68b5 100644
--- a/jdk/src/share/classes/sun/misc/SharedSecrets.java
+++ b/jdk/src/share/classes/sun/misc/SharedSecrets.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,6 @@ package sun.misc;
import java.util.jar.JarFile;
import java.io.Console;
import java.io.FileDescriptor;
-import java.security.CodeSigner;
import java.security.ProtectionDomain;
/** A repository of "shared secrets", which are a mechanism for
@@ -49,7 +48,6 @@ public class SharedSecrets {
private static JavaNioAccess javaNioAccess;
private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess;
private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess;
- private static JavaSecurityCodeSignerAccess javaSecurityCodeSignerAccess;
public static JavaUtilJarAccess javaUtilJarAccess() {
if (javaUtilJarAccess == null) {
@@ -127,16 +125,4 @@ public class SharedSecrets {
unsafe.ensureClassInitialized(ProtectionDomain.class);
return javaSecurityProtectionDomainAccess;
}
-
- public static void setJavaSecurityCodeSignerAccess
- (JavaSecurityCodeSignerAccess jscsa) {
- javaSecurityCodeSignerAccess = jscsa;
- }
-
- public static JavaSecurityCodeSignerAccess
- getJavaSecurityCodeSignerAccess() {
- if (javaSecurityCodeSignerAccess == null)
- unsafe.ensureClassInitialized(CodeSigner.class);
- return javaSecurityCodeSignerAccess;
- }
}
diff --git a/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java b/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java
index 97b8242a9fa..95e01018986 100644
--- a/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java
+++ b/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java
@@ -69,32 +69,33 @@ class ChunkedInputStream extends LeftOverInputStream {
*/
private int readChunkHeader () throws IOException {
boolean gotCR = false;
- char c;
+ int c;
char[] len_arr = new char [16];
int len_size = 0;
boolean end_of_len = false;
- while ((c=(char)in.read())!= -1) {
+ while ((c=in.read())!= -1) {
+ char ch = (char) c;
if (len_size == len_arr.length -1) {
throw new IOException ("invalid chunk header");
}
if (gotCR) {
- if (c == LF) {
+ if (ch == LF) {
int l = numeric (len_arr, len_size);
return l;
} else {
gotCR = false;
}
if (!end_of_len) {
- len_arr[len_size++] = c;
+ len_arr[len_size++] = ch;
}
} else {
- if (c == CR) {
+ if (ch == CR) {
gotCR = true;
- } else if (c == ';') {
+ } else if (ch == ';') {
end_of_len = true;
} else if (!end_of_len) {
- len_arr[len_size++] = c;
+ len_arr[len_size++] = ch;
}
}
}
diff --git a/jdk/src/share/classes/sun/nio/ch/FileChannelImpl.java b/jdk/src/share/classes/sun/nio/ch/FileChannelImpl.java
index b15086eab12..c52fff788e9 100644
--- a/jdk/src/share/classes/sun/nio/ch/FileChannelImpl.java
+++ b/jdk/src/share/classes/sun/nio/ch/FileChannelImpl.java
@@ -475,8 +475,8 @@ public class FileChannelImpl
assert !target.isOpen();
try {
close();
- } catch (IOException ignore) {
- // nothing we can do
+ } catch (Throwable suppressed) {
+ e.addSuppressed(suppressed);
}
throw e;
} catch (IOException ioe) {
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java
index 3d2525f3f07..5257859e30e 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -42,14 +42,12 @@ import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
* Cipher implementation class. This class currently supports
* DES, DESede, AES, ARCFOUR, and Blowfish.
*
- * This class is designed to support ECB and CBC with NoPadding and
- * PKCS5Padding for both. It will use its own padding impl if the
- * native mechanism does not support padding.
+ * This class is designed to support ECB, CBC, CTR with NoPadding
+ * and ECB, CBC with PKCS5Padding. It will use its own padding impl
+ * if the native mechanism does not support padding.
*
- * Note that PKCS#11 current only supports ECB and CBC. There are no
- * provisions for other modes such as CFB, OFB, PCBC, or CTR mode.
- * However, CTR could be implemented relatively easily (and efficiently)
- * on top of ECB mode in this class, if need be.
+ * Note that PKCS#11 currently only supports ECB, CBC, and CTR.
+ * There are no provisions for other modes such as CFB, OFB, and PCBC.
*
* @author Andreas Sterbenz
* @since 1.5
@@ -60,6 +58,8 @@ final class P11Cipher extends CipherSpi {
private final static int MODE_ECB = 3;
// mode constant for CBC mode
private final static int MODE_CBC = 4;
+ // mode constant for CTR mode
+ private final static int MODE_CTR = 5;
// padding constant for NoPadding
private final static int PAD_NONE = 5;
@@ -157,7 +157,7 @@ final class P11Cipher extends CipherSpi {
private byte[] padBuffer;
private int padBufferLen;
- // original IV, if in MODE_CBC
+ // original IV, if in MODE_CBC or MODE_CTR
private byte[] iv;
// number of bytes buffered internally by the native mechanism and padBuffer
@@ -213,6 +213,8 @@ final class P11Cipher extends CipherSpi {
("CBC mode not supported with stream ciphers");
}
result = MODE_CBC;
+ } else if (mode.equals("CTR")) {
+ result = MODE_CTR;
} else {
throw new NoSuchAlgorithmException("Unsupported mode " + mode);
}
@@ -228,6 +230,10 @@ final class P11Cipher extends CipherSpi {
if (padding.equals("NOPADDING")) {
paddingType = PAD_NONE;
} else if (padding.equals("PKCS5PADDING")) {
+ if (this.blockMode == MODE_CTR) {
+ throw new NoSuchPaddingException
+ ("PKCS#5 padding not supported with CTR mode");
+ }
paddingType = PAD_PKCS5;
if (mechanism != CKM_DES_CBC_PAD && mechanism != CKM_DES3_CBC_PAD &&
mechanism != CKM_AES_CBC_PAD) {
@@ -348,11 +354,14 @@ final class P11Cipher extends CipherSpi {
("IV not used in ECB mode");
}
}
- } else { // MODE_CBC
+ } else { // MODE_CBC or MODE_CTR
if (iv == null) {
if (encrypt == false) {
- throw new InvalidAlgorithmParameterException
- ("IV must be specified for decryption in CBC mode");
+ String exMsg =
+ (blockMode == MODE_CBC ?
+ "IV must be specified for decryption in CBC mode" :
+ "IV must be specified for decryption in CTR mode");
+ throw new InvalidAlgorithmParameterException(exMsg);
}
// generate random IV
if (random == null) {
@@ -410,13 +419,15 @@ final class P11Cipher extends CipherSpi {
if (session == null) {
session = token.getOpSession();
}
+ CK_MECHANISM mechParams = (blockMode == MODE_CTR?
+ new CK_MECHANISM(mechanism, new CK_AES_CTR_PARAMS(iv)) :
+ new CK_MECHANISM(mechanism, iv));
+
try {
if (encrypt) {
- token.p11.C_EncryptInit(session.id(),
- new CK_MECHANISM(mechanism, iv), p11Key.keyID);
+ token.p11.C_EncryptInit(session.id(), mechParams, p11Key.keyID);
} else {
- token.p11.C_DecryptInit(session.id(),
- new CK_MECHANISM(mechanism, iv), p11Key.keyID);
+ token.p11.C_DecryptInit(session.id(), mechParams, p11Key.keyID);
}
} catch (PKCS11Exception ex) {
// release session when initialization failed
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
index 18f3ab450ef..d9dc4e77ef7 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -62,6 +62,11 @@ final class P11RSACipher extends CipherSpi {
// mode constant for public key decryption (verifying)
private final static int MODE_VERIFY = 4;
+ // padding type constant for NoPadding
+ private final static int PAD_NONE = 1;
+ // padding type constant for PKCS1Padding
+ private final static int PAD_PKCS1 = 2;
+
// token instance
private final Token token;
@@ -77,6 +82,9 @@ final class P11RSACipher extends CipherSpi {
// mode, one of MODE_* above
private int mode;
+ // padding, one of PAD_* above
+ private int padType;
+
private byte[] buffer;
private int bufOfs;
@@ -113,8 +121,10 @@ final class P11RSACipher extends CipherSpi {
protected void engineSetPadding(String padding)
throws NoSuchPaddingException {
String lowerPadding = padding.toLowerCase(Locale.ENGLISH);
- if (lowerPadding.equals("pkcs1Padding")) {
- // empty
+ if (lowerPadding.equals("pkcs1padding")) {
+ padType = PAD_PKCS1;
+ } else if (lowerPadding.equals("nopadding")) {
+ padType = PAD_NONE;
} else {
throw new NoSuchPaddingException("Unsupported padding " + padding);
}
@@ -209,7 +219,8 @@ final class P11RSACipher extends CipherSpi {
int n = (p11Key.keyLength() + 7) >> 3;
outputSize = n;
buffer = new byte[n];
- maxInputSize = encrypt ? (n - PKCS1_MIN_PADDING_LENGTH) : n;
+ maxInputSize = ((padType == PAD_PKCS1 && encrypt) ?
+ (n - PKCS1_MIN_PADDING_LENGTH) : n);
try {
initialize();
} catch (PKCS11Exception e) {
diff --git a/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java b/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java
index 55843b95c58..d54c5617309 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -621,12 +621,16 @@ public final class SunPKCS11 extends AuthProvider {
m(CKM_AES_CBC_PAD, CKM_AES_CBC));
d(CIP, "AES/ECB", P11Cipher, s("AES"),
m(CKM_AES_ECB));
+ d(CIP, "AES/CTR/NoPadding", P11Cipher,
+ m(CKM_AES_CTR));
d(CIP, "Blowfish/CBC", P11Cipher,
m(CKM_BLOWFISH_CBC));
// XXX RSA_X_509, RSA_OAEP not yet supported
- d(CIP, "RSA/ECB/PKCS1Padding", P11RSACipher,
+ d(CIP, "RSA/ECB/PKCS1Padding", P11RSACipher, s("RSA"),
m(CKM_RSA_PKCS));
+ d(CIP, "RSA/ECB/NoPadding", P11RSACipher,
+ m(CKM_RSA_X_509));
d(SIG, "RawDSA", P11Signature, s("NONEwithDSA"),
m(CKM_DSA));
diff --git a/jdk/src/share/classes/sun/misc/JavaSecurityCodeSignerAccess.java b/jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java
similarity index 51%
rename from jdk/src/share/classes/sun/misc/JavaSecurityCodeSignerAccess.java
rename to jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java
index 67305d3baaf..7208f481c2a 100644
--- a/jdk/src/share/classes/sun/misc/JavaSecurityCodeSignerAccess.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -22,12 +22,45 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package sun.misc;
-import java.security.CodeSigner;
-import java.security.cert.CRL;
+package sun.security.pkcs11.wrapper;
-public interface JavaSecurityCodeSignerAccess {
- void setCRLs(CodeSigner signer, CRL[] crls);
- CRL[] getCRLs(CodeSigner signer);
+/**
+ * This class represents the necessary parameters required by
+ * the CKM_AES_CTR mechanism as defined in CK_AES_CTR_PARAMS structure.
+ * PKCS#11 structure:
+ *
+ * typedef struct CK_AES_CTR_PARAMS {
+ * CK_ULONG ulCounterBits;
+ * CK_BYTE cb[16];
+ * } CK_AES_CTR_PARAMS;
+ *
+ *
+ * @author Yu-Ching Valerie Peng
+ * @since 1.7
+ */
+public class CK_AES_CTR_PARAMS {
+
+ private final long ulCounterBits;
+ private final byte cb[];
+
+ public CK_AES_CTR_PARAMS(byte[] cb) {
+ ulCounterBits = 128;
+ this.cb = cb.clone();
+ }
+
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+
+ buffer.append(Constants.INDENT);
+ buffer.append("ulCounterBits: ");
+ buffer.append(ulCounterBits);
+ buffer.append(Constants.NEWLINE);
+
+ buffer.append(Constants.INDENT);
+ buffer.append("cb: ");
+ buffer.append(Functions.toHexString(cb));
+
+ return buffer.toString();
+ }
}
diff --git a/jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java b/jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java
index b84c5e99c15..3322d19b00c 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@@ -48,6 +48,7 @@
package sun.security.pkcs11.wrapper;
import java.math.BigInteger;
+import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
/**
* class CK_MECHANISM specifies a particular mechanism and any parameters it
@@ -127,6 +128,10 @@ public class CK_MECHANISM {
init(mechanism, params);
}
+ public CK_MECHANISM(long mechanism, CK_AES_CTR_PARAMS params) {
+ init(mechanism, params);
+ }
+
private void init(long mechanism, Object pParameter) {
this.mechanism = mechanism;
this.pParameter = pParameter;
diff --git a/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java b/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java
index f5bf7f1034d..98e9fe0651b 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@@ -47,8 +47,6 @@
package sun.security.pkcs11.wrapper;
-
-
/**
* This interface holds constants of the PKCS#11 v2.11 standard.
* This is mainly the content of the 'pkcs11t.h' header file.
@@ -306,6 +304,10 @@ public interface PKCS11Constants {
public static final long CKK_VENDOR_DEFINED = 0x80000000L;
+ // new for v2.20 amendment 3
+ //public static final long CKK_CAMELLIA = 0x00000025L;
+ //public static final long CKK_ARIA = 0x00000026L;
+
// pseudo key type ANY (for template manager)
public static final long PCKK_ANY = 0x7FFFFF22L;
@@ -690,6 +692,34 @@ public interface PKCS11Constants {
public static final long CKM_VENDOR_DEFINED = 0x80000000L;
+ // new for v2.20 amendment 3
+ public static final long CKM_SHA224 = 0x00000255L;
+ public static final long CKM_SHA224_HMAC = 0x00000256L;
+ public static final long CKM_SHA224_HMAC_GENERAL = 0x00000257L;
+ public static final long CKM_SHA224_KEY_DERIVATION = 0x00000396L;
+ public static final long CKM_SHA224_RSA_PKCS = 0x00000046L;
+ public static final long CKM_SHA224_RSA_PKCS_PSS = 0x00000047L;
+ public static final long CKM_AES_CTR = 0x00001086L;
+ /*
+ public static final long CKM_CAMELLIA_KEY_GEN = 0x00000550L;
+ public static final long CKM_CAMELLIA_ECB = 0x00000551L;
+ public static final long CKM_CAMELLIA_CBC = 0x00000552L;
+ public static final long CKM_CAMELLIA_MAC = 0x00000553L;
+ public static final long CKM_CAMELLIA_MAC_GENERAL = 0x00000554L;
+ public static final long CKM_CAMELLIA_CBC_PAD = 0x00000555L;
+ public static final long CKM_CAMELLIA_ECB_ENCRYPT_DATA = 0x00000556L;
+ public static final long CKM_CAMELLIA_CBC_ENCRYPT_DATA = 0x00000557L;
+ public static final long CKM_CAMELLIA_CTR = 0x00000558L;
+ public static final long CKM_ARIA_KEY_GEN = 0x00000560L;
+ public static final long CKM_ARIA_ECB = 0x00000561L;
+ public static final long CKM_ARIA_CBC = 0x00000562L;
+ public static final long CKM_ARIA_MAC = 0x00000563L;
+ public static final long CKM_ARIA_MAC_GENERAL = 0x00000564L;
+ public static final long CKM_ARIA_CBC_PAD = 0x00000565L;
+ public static final long CKM_ARIA_ECB_ENCRYPT_DATA = 0x00000566L;
+ public static final long CKM_ARIA_CBC_ENCRYPT_DATA = 0x00000567L;
+ */
+
// NSS private
public static final long CKM_NSS_TLS_PRF_GENERAL = 0x80000373L;
@@ -881,7 +911,8 @@ public interface PKCS11Constants {
/* The following MGFs are defined */
public static final long CKG_MGF1_SHA1 = 0x00000001L;
-
+ // new for v2.20 amendment 3
+ public static final long CKG_MGF1_SHA224 = 0x00000005L;
/* The following encoding parameter sources are defined */
public static final long CKZ_DATA_SPECIFIED = 0x00000001L;
diff --git a/jdk/src/share/classes/sun/security/tools/JarSigner.java b/jdk/src/share/classes/sun/security/tools/JarSigner.java
index 42d3bf57fd8..4d0e032819e 100644
--- a/jdk/src/share/classes/sun/security/tools/JarSigner.java
+++ b/jdk/src/share/classes/sun/security/tools/JarSigner.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,6 @@
package sun.security.tools;
import java.io.*;
-import java.security.cert.X509CRL;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;
@@ -36,7 +35,6 @@ import java.net.URISyntaxException;
import java.text.Collator;
import java.text.MessageFormat;
import java.security.cert.Certificate;
-import java.security.cert.CRL;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.*;
@@ -58,7 +56,6 @@ import java.util.Map.Entry;
import sun.security.x509.*;
import sun.security.util.*;
import sun.misc.BASE64Encoder;
-import sun.misc.SharedSecrets;
/**
@@ -117,13 +114,11 @@ public class JarSigner {
static final int SIGNED_BY_ALIAS = 0x08; // signer is in alias list
X509Certificate[] certChain; // signer's cert chain (when composing)
- Set crls; // signer provided CRLs
PrivateKey privateKey; // private key
KeyStore store; // the keystore specified by -keystore
// or the default keystore, never null
String keystore; // key store file
- List crlfiles = new ArrayList<>(); // CRL files to add
boolean nullStream = false; // null keystore input stream (NONE)
boolean token = false; // token-based keystore
String jarfile; // jar files to sign or verify
@@ -151,7 +146,6 @@ public class JarSigner {
boolean signManifest = true; // "sign" the whole manifest
boolean externalSF = true; // leave the .SF out of the PKCS7 block
boolean strict = false; // treat warnings as error
- boolean autoCRL = false; // Automatcially add CRL defined in cert
// read zip entry raw bytes
private ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
@@ -232,29 +226,6 @@ public class JarSigner {
} else {
loadKeyStore(keystore, true);
getAliasInfo(alias);
- crls = new HashSet();
- if (crlfiles.size() > 0 || autoCRL) {
- CertificateFactory fac =
- CertificateFactory.getInstance("X509");
- List list = new ArrayList<>();
- for (String file: crlfiles) {
- Collection extends CRL> tmp = KeyTool.loadCRLs(file);
- for (CRL crl: tmp) {
- if (crl instanceof X509CRL) {
- crls.add((X509CRL)crl);
- }
- }
- }
- if (autoCRL) {
- List crlsFromCert =
- KeyTool.readCRLsFromCert(certChain[0]);
- for (CRL crl: crlsFromCert) {
- if (crl instanceof X509CRL) {
- crls.add((X509CRL)crl);
- }
- }
- }
- }
// load the alternative signing mechanism
if (altSignerClass != null) {
@@ -396,13 +367,6 @@ public class JarSigner {
} else if (collator.compare(flags, "-digestalg") ==0) {
if (++n == args.length) usageNoArg();
digestalg = args[n];
- } else if (collator.compare(flags, "-crl") ==0) {
- if ("auto".equals(modifier)) {
- autoCRL = true;
- } else {
- if (++n == args.length) usageNoArg();
- crlfiles.add(args[n]);
- }
} else if (collator.compare(flags, "-certs") ==0) {
showcerts = true;
} else if (collator.compare(flags, "-strict") ==0) {
@@ -548,9 +512,6 @@ public class JarSigner {
System.out.println(rb.getString
(".sigalg.algorithm.name.of.signature.algorithm"));
System.out.println();
- System.out.println(rb.getString
- (".crl.auto.file.include.CRL.in.signed.jar"));
- System.out.println();
System.out.println(rb.getString
(".verify.verify.a.signed.JAR.file"));
System.out.println();
@@ -691,20 +652,6 @@ public class JarSigner {
if (showcerts) {
sb.append(si);
sb.append('\n');
- CRL[] crls = SharedSecrets
- .getJavaSecurityCodeSignerAccess()
- .getCRLs(signer);
- if (crls != null) {
- for (CRL crl: crls) {
- if (crl instanceof X509CRLImpl) {
- sb.append(tab).append("[");
- sb.append(String.format(
- rb.getString("with.a.CRL.including.d.entries"),
- ((X509CRLImpl)crl).getRevokedCertificates().size()))
- .append("]\n");
- }
- }
- }
}
}
} else if (showcerts && !verbose.equals("all")) {
@@ -1284,7 +1231,7 @@ public class JarSigner {
try {
block =
- sf.generateBlock(privateKey, sigalg, certChain, crls,
+ sf.generateBlock(privateKey, sigalg, certChain,
externalSF, tsaUrl, tsaCert, signingMechanism, args,
zipFile);
} catch (SocketTimeoutException e) {
@@ -2249,7 +2196,6 @@ class SignatureFile {
public Block generateBlock(PrivateKey privateKey,
String sigalg,
X509Certificate[] certChain,
- Set crls,
boolean externalSF, String tsaUrl,
X509Certificate tsaCert,
ContentSigner signingMechanism,
@@ -2257,7 +2203,7 @@ class SignatureFile {
throws NoSuchAlgorithmException, InvalidKeyException, IOException,
SignatureException, CertificateException
{
- return new Block(this, privateKey, sigalg, certChain, crls, externalSF,
+ return new Block(this, privateKey, sigalg, certChain, externalSF,
tsaUrl, tsaCert, signingMechanism, args, zipFile);
}
@@ -2271,8 +2217,7 @@ class SignatureFile {
* Construct a new signature block.
*/
Block(SignatureFile sfg, PrivateKey privateKey, String sigalg,
- X509Certificate[] certChain, Set crls,
- boolean externalSF, String tsaUrl,
+ X509Certificate[] certChain, boolean externalSF, String tsaUrl,
X509Certificate tsaCert, ContentSigner signingMechanism,
String[] args, ZipFile zipFile)
throws NoSuchAlgorithmException, InvalidKeyException, IOException,
@@ -2359,7 +2304,7 @@ class SignatureFile {
// Assemble parameters for the signing mechanism
ContentSignerParameters params =
new JarSignerParameters(args, tsaUri, tsaCert, signature,
- signatureAlgorithm, certChain, crls, content, zipFile);
+ signatureAlgorithm, certChain, content, zipFile);
// Generate the signature block
block = signingMechanism.generateSignedData(
@@ -2400,7 +2345,6 @@ class JarSignerParameters implements ContentSignerParameters {
private byte[] signature;
private String signatureAlgorithm;
private X509Certificate[] signerCertificateChain;
- private Set crls;
private byte[] content;
private ZipFile source;
@@ -2409,8 +2353,7 @@ class JarSignerParameters implements ContentSignerParameters {
*/
JarSignerParameters(String[] args, URI tsa, X509Certificate tsaCertificate,
byte[] signature, String signatureAlgorithm,
- X509Certificate[] signerCertificateChain, Set crls,
- byte[] content,
+ X509Certificate[] signerCertificateChain, byte[] content,
ZipFile source) {
if (signature == null || signatureAlgorithm == null ||
@@ -2423,7 +2366,6 @@ class JarSignerParameters implements ContentSignerParameters {
this.signature = signature;
this.signatureAlgorithm = signatureAlgorithm;
this.signerCertificateChain = signerCertificateChain;
- this.crls = crls;
this.content = content;
this.source = source;
}
@@ -2499,13 +2441,4 @@ class JarSignerParameters implements ContentSignerParameters {
public ZipFile getSource() {
return source;
}
-
- @Override
- public Set getCRLs() {
- if (crls == null) {
- return Collections.emptySet();
- } else {
- return Collections.unmodifiableSet(crls);
- }
- }
}
diff --git a/jdk/src/share/classes/sun/security/tools/JarSignerResources.java b/jdk/src/share/classes/sun/security/tools/JarSignerResources.java
index 9eb14cce3c6..c3d8a6e38ec 100644
--- a/jdk/src/share/classes/sun/security/tools/JarSignerResources.java
+++ b/jdk/src/share/classes/sun/security/tools/JarSignerResources.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -74,8 +74,6 @@ public class JarSignerResources extends java.util.ListResourceBundle {
"[-digestalg ] name of digest algorithm"},
{".sigalg.algorithm.name.of.signature.algorithm",
"[-sigalg ] name of signature algorithm"},
- {".crl.auto.file.include.CRL.in.signed.jar",
- "[-crl[:auto| ] include CRL in signed jar"},
{".verify.verify.a.signed.JAR.file",
"[-verify] verify a signed JAR file"},
{".verbose.suboptions.verbose.output.when.signing.verifying.",
@@ -193,7 +191,6 @@ public class JarSignerResources extends java.util.ListResourceBundle {
{"using.an.alternative.signing.mechanism",
"using an alternative signing mechanism"},
{"entry.was.signed.on", "entry was signed on {0}"},
- {"with.a.CRL.including.d.entries", "with a CRL including %d entries"},
{"Warning.", "Warning: "},
{"This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.",
"This jar contains unsigned entries which have not been integrity-checked. "},
diff --git a/jdk/src/share/classes/sun/security/tools/KeyTool.java b/jdk/src/share/classes/sun/security/tools/KeyTool.java
index 897d407a1c2..50349173a41 100644
--- a/jdk/src/share/classes/sun/security/tools/KeyTool.java
+++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
package sun.security.tools;
-import sun.misc.SharedSecrets;
import java.io.*;
import java.security.CodeSigner;
import java.security.KeyStore;
@@ -2311,16 +2310,6 @@ public final class KeyTool {
out.println();
}
}
- CRL[] crls = SharedSecrets
- .getJavaSecurityCodeSignerAccess()
- .getCRLs(signer);
- if (crls != null) {
- out.println(rb.getString("CRLs."));
- out.println();
- for (CRL crl: crls) {
- printCRL(crl, out);
- }
- }
}
}
}
diff --git a/jdk/src/share/classes/sun/security/tools/TimestampedSigner.java b/jdk/src/share/classes/sun/security/tools/TimestampedSigner.java
index f0a75836972..6d5eb63b7fd 100644
--- a/jdk/src/share/classes/sun/security/tools/TimestampedSigner.java
+++ b/jdk/src/share/classes/sun/security/tools/TimestampedSigner.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,6 @@ import java.security.cert.X509Certificate;
import java.util.List;
import com.sun.jarsigner.*;
-import java.security.cert.X509CRL;
import java.util.Arrays;
import sun.security.pkcs.*;
import sun.security.timestamp.*;
@@ -238,9 +237,8 @@ public final class TimestampedSigner extends ContentSigner {
AlgorithmId[] algorithms = {digestAlgorithmId};
// Create the PKCS #7 signed data message
- PKCS7 p7 =
- new PKCS7(algorithms, contentInfo, signerCertificateChain,
- parameters.getCRLs().toArray(new X509CRL[parameters.getCRLs().size()]), signerInfos);
+ PKCS7 p7 = new PKCS7(algorithms, contentInfo, signerCertificateChain,
+ null, signerInfos);
ByteArrayOutputStream p7out = new ByteArrayOutputStream();
p7.encodeSignedData(p7out);
diff --git a/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java b/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java
index f60fcb75f8b..96f425a46b5 100644
--- a/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java
+++ b/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java
@@ -37,7 +37,6 @@ import java.util.jar.*;
import sun.security.pkcs.*;
import sun.security.timestamp.TimestampToken;
import sun.misc.BASE64Decoder;
-import sun.misc.SharedSecrets;
import sun.security.jca.Providers;
@@ -486,12 +485,7 @@ public class SignatureFileVerifier {
signers = new ArrayList();
}
// Append the new code signer
- CodeSigner signer = new CodeSigner(certChain, getTimestamp(info));
- if (block.getCRLs() != null) {
- SharedSecrets.getJavaSecurityCodeSignerAccess().setCRLs(
- signer, block.getCRLs());
- }
- signers.add(signer);
+ signers.add(new CodeSigner(certChain, getTimestamp(info)));
if (debug != null) {
debug.println("Signature Block Certificate: " +
diff --git a/jdk/src/share/classes/sun/tools/native2ascii/Main.java b/jdk/src/share/classes/sun/tools/native2ascii/Main.java
index 2d127344b1a..d19d27a6406 100644
--- a/jdk/src/share/classes/sun/tools/native2ascii/Main.java
+++ b/jdk/src/share/classes/sun/tools/native2ascii/Main.java
@@ -94,7 +94,7 @@ public class Main {
* Run the converter
*/
public synchronized boolean convert(String argv[]){
- Vector v = new Vector(2);
+ List v = new ArrayList<>(2);
File outputFile = null;
boolean createOutputFile = false;
@@ -115,7 +115,7 @@ public class Main {
usage();
return false;
}
- v.addElement(argv[i]);
+ v.add(argv[i]);
}
}
if (encodingString == null)
@@ -126,11 +126,11 @@ public class Main {
initializeConverter();
if (v.size() == 1)
- inputFileName = (String)v.elementAt(0);
+ inputFileName = v.get(0);
if (v.size() == 2) {
- inputFileName = (String)v.elementAt(0);
- outputFileName = (String)v.elementAt(1);
+ inputFileName = v.get(0);
+ outputFileName = v.get(1);
createOutputFile = true;
}
@@ -363,9 +363,7 @@ public class Main {
private String formatMsg(String key, String arg) {
String msg = getMsg(key);
- String[] args = new String[1];
- args[0] = arg;
- return MessageFormat.format(msg, (Object)args);
+ return MessageFormat.format(msg, arg);
}
diff --git a/jdk/src/share/classes/sun/util/calendar/LocalGregorianCalendar.java b/jdk/src/share/classes/sun/util/calendar/LocalGregorianCalendar.java
index 6710dbae3bc..de5f749608c 100644
--- a/jdk/src/share/classes/sun/util/calendar/LocalGregorianCalendar.java
+++ b/jdk/src/share/classes/sun/util/calendar/LocalGregorianCalendar.java
@@ -127,7 +127,9 @@ public class LocalGregorianCalendar extends BaseCalendar {
calendarProps = (Properties) AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
Properties props = new Properties();
- props.load(new FileInputStream(fname));
+ try (FileInputStream fis = new FileInputStream(fname)) {
+ props.load(fis);
+ }
return props;
}
});
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
index 10f6bd477a9..543220fc63a 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
+++ b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -76,7 +76,7 @@ public class ZipDirectoryStream implements DirectoryStream {
} catch (IOException e) {
throw new IllegalStateException(e);
}
- return new Iterator<>() {
+ return new Iterator() {
private Path next;
@Override
public boolean hasNext() {
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
index 40afd8afb84..fc43fd87ccf 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
+++ b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
@@ -112,11 +112,8 @@ public class ZipFileSystem extends FileSystem {
}
// sm and existence check
zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.READ);
- try {
- zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.WRITE);
- } catch (AccessDeniedException x) {
+ if (!Files.isWritable(zfpath))
this.readOnly = true;
- }
this.zc = ZipCoder.get(nameEncoding);
this.defaultdir = new ZipPath(this, getBytes(defaultDir));
this.ch = Files.newByteChannel(zfpath, READ);
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
index b03ba2929eb..1232a27ff1f 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
+++ b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -590,7 +590,7 @@ public class ZipPath implements Path {
@Override
public Iterator iterator() {
- return new Iterator<>() {
+ return new Iterator() {
private int i = 0;
@Override
diff --git a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c
index 4abc1507388..c32a278b585 100644
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@@ -694,6 +694,46 @@ CK_SSL3_KEY_MAT_PARAMS jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject
return ckParam ;
}
+/*
+ * converts the Java CK_AES_CTR_PARAMS object to a CK_AES_CTR_PARAMS structure
+ *
+ * @param env - used to call JNI funktions to get the Java classes and objects
+ * @param jParam - the Java CK_AES_CTR_PARAMS object to convert
+ * @param ckpParam - pointer to the new CK_AES_CTR_PARAMS structure
+ */
+void jAesCtrParamsToCKAesCtrParam(JNIEnv *env, jobject jParam,
+ CK_AES_CTR_PARAMS_PTR ckpParam) {
+ jclass jAesCtrParamsClass;
+ jfieldID fieldID;
+ jlong jCounterBits;
+ jobject jCb;
+ CK_BYTE_PTR ckBytes;
+ CK_ULONG ckTemp;
+
+ /* get ulCounterBits */
+ jAesCtrParamsClass = (*env)->FindClass(env, CLASS_AES_CTR_PARAMS);
+ if (jAesCtrParamsClass == NULL) { return; }
+ fieldID = (*env)->GetFieldID(env, jAesCtrParamsClass, "ulCounterBits", "J");
+ if (fieldID == NULL) { return; }
+ jCounterBits = (*env)->GetLongField(env, jParam, fieldID);
+
+ /* get cb */
+ fieldID = (*env)->GetFieldID(env, jAesCtrParamsClass, "cb", "[B");
+ if (fieldID == NULL) { return; }
+ jCb = (*env)->GetObjectField(env, jParam, fieldID);
+
+ /* populate java values */
+ ckpParam->ulCounterBits = jLongToCKULong(jCounterBits);
+ jByteArrayToCKByteArray(env, jCb, &ckBytes, &ckTemp);
+ if ((*env)->ExceptionCheck(env)) { return; }
+ if (ckTemp != 16) {
+ TRACE1("ERROR: WRONG CTR IV LENGTH %d", ckTemp);
+ } else {
+ memcpy(ckpParam->cb, ckBytes, ckTemp);
+ free(ckBytes);
+ }
+}
+
/*
* converts a Java CK_MECHANISM object into a CK_MECHANISM structure
*
@@ -937,12 +977,10 @@ void jMechanismParameterToCKMechanismParameterSlow(JNIEnv *env, jobject jParam,
{
/* get all Java mechanism parameter classes */
jclass jVersionClass, jSsl3MasterKeyDeriveParamsClass, jSsl3KeyMatParamsClass;
- jclass jTlsPrfParamsClass, jRsaPkcsOaepParamsClass, jPbeParamsClass;
- jclass jPkcs5Pbkd2ParamsClass, jRsaPkcsPssParamsClass;
+ jclass jTlsPrfParamsClass, jAesCtrParamsClass, jRsaPkcsOaepParamsClass;
+ jclass jPbeParamsClass, jPkcs5Pbkd2ParamsClass, jRsaPkcsPssParamsClass;
jclass jEcdh1DeriveParamsClass, jEcdh2DeriveParamsClass;
jclass jX942Dh1DeriveParamsClass, jX942Dh2DeriveParamsClass;
-
- /* get all Java mechanism parameter classes */
TRACE0("\nDEBUG: jMechanismParameterToCKMechanismParameter");
/* most common cases, i.e. NULL/byte[]/long, are already handled by
@@ -1046,6 +1084,33 @@ void jMechanismParameterToCKMechanismParameterSlow(JNIEnv *env, jobject jParam,
return;
}
+ jAesCtrParamsClass = (*env)->FindClass(env, CLASS_AES_CTR_PARAMS);
+ if (jAesCtrParamsClass == NULL) { return; }
+ if ((*env)->IsInstanceOf(env, jParam, jAesCtrParamsClass)) {
+ /*
+ * CK_AES_CTR_PARAMS
+ */
+ CK_AES_CTR_PARAMS_PTR ckpParam;
+
+ ckpParam = (CK_AES_CTR_PARAMS_PTR) malloc(sizeof(CK_AES_CTR_PARAMS));
+ if (ckpParam == NULL) {
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return;
+ }
+
+ /* convert jParameter to CKParameter */
+ jAesCtrParamsToCKAesCtrParam(env, jParam, ckpParam);
+ if ((*env)->ExceptionCheck(env)) {
+ free(ckpParam);
+ return;
+ }
+
+ /* get length and pointer of parameter */
+ *ckpLength = sizeof(CK_AES_CTR_PARAMS);
+ *ckpParamPtr = ckpParam;
+ return;
+ }
+
jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
if (jRsaPkcsOaepParamsClass == NULL) { return; }
if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsOaepParamsClass)) {
diff --git a/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs-11v2-20a3.h b/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs-11v2-20a3.h
new file mode 100644
index 00000000000..0486fdf6a63
--- /dev/null
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs-11v2-20a3.h
@@ -0,0 +1,124 @@
+/* pkcs-11v2-20a3.h include file for the PKCS #11 Version 2.20 Amendment 3
+ document. */
+
+/* $Revision: 1.4 $ */
+
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki) Version 2.20 Amendment 3" in all material mentioning or
+ * referencing this software.
+
+ * RSA Security Inc. makes no representations concerning either the
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+ */
+
+/* This file is preferably included after inclusion of pkcs11.h */
+
+#ifndef _PKCS_11V2_20A3_H_
+#define _PKCS_11V2_20A3_H_ 1
+
+/* Are the definitions of this file already included in pkcs11t.h ? */
+#ifndef CKK_CAMELLIA
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Key types */
+
+/* Camellia is new for PKCS #11 v2.20 amendment 3 */
+#define CKK_CAMELLIA 0x00000025
+/* ARIA is new for PKCS #11 v2.20 amendment 3 */
+#define CKK_ARIA 0x00000026
+
+
+/* Mask-generating functions */
+
+/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
+#define CKG_MGF1_SHA224 0x00000005
+
+
+/* Mechanism Identifiers */
+
+/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_SHA224 0x00000255
+#define CKM_SHA224_HMAC 0x00000256
+#define CKM_SHA224_HMAC_GENERAL 0x00000257
+
+/* SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_SHA224_KEY_DERIVATION 0x00000396
+
+/* SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3 */
+#define CKM_SHA224_RSA_PKCS 0x00000046
+#define CKM_SHA224_RSA_PKCS_PSS 0x00000047
+
+/* AES counter mode is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_AES_CTR 0x00001086
+
+/* Camellia is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_CAMELLIA_KEY_GEN 0x00000550
+#define CKM_CAMELLIA_ECB 0x00000551
+#define CKM_CAMELLIA_CBC 0x00000552
+#define CKM_CAMELLIA_MAC 0x00000553
+#define CKM_CAMELLIA_MAC_GENERAL 0x00000554
+#define CKM_CAMELLIA_CBC_PAD 0x00000555
+#define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556
+#define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557
+#define CKM_CAMELLIA_CTR 0x00000558
+
+/* ARIA is new for PKCS #11 v2.20 amendment 3 */
+#define CKM_ARIA_KEY_GEN 0x00000560
+#define CKM_ARIA_ECB 0x00000561
+#define CKM_ARIA_CBC 0x00000562
+#define CKM_ARIA_MAC 0x00000563
+#define CKM_ARIA_MAC_GENERAL 0x00000564
+#define CKM_ARIA_CBC_PAD 0x00000565
+#define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566
+#define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567
+
+
+/* Mechanism parameters */
+
+/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_AES_CTR_PARAMS {
+ CK_ULONG ulCounterBits;
+ CK_BYTE cb[16];
+} CK_AES_CTR_PARAMS;
+
+typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR;
+
+/* CK_CAMELLIA_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_CAMELLIA_CTR_PARAMS {
+ CK_ULONG ulCounterBits;
+ CK_BYTE cb[16];
+} CK_CAMELLIA_CTR_PARAMS;
+
+typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR;
+
+/* CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS {
+ CK_BYTE iv[16];
+ CK_BYTE_PTR pData;
+ CK_ULONG length;
+} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+/* CK_ARIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
+typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS {
+ CK_BYTE iv[16];
+ CK_BYTE_PTR pData;
+ CK_ULONG length;
+} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#endif
diff --git a/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h b/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h
index 98598d807f5..ff6d550d523 100644
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@@ -153,6 +153,7 @@
#include "p11_md.h"
#include "pkcs11.h"
+#include "pkcs-11v2-20a3.h"
#include
#include
@@ -272,6 +273,7 @@
#define CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_SSL3_MASTER_KEY_DERIVE_PARAMS"
#define CLASS_SSL3_KEY_MAT_PARAMS "sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_PARAMS"
#define CLASS_TLS_PRF_PARAMS "sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS"
+#define CLASS_AES_CTR_PARAMS "sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS"
/* function to convert a PKCS#11 return value other than CK_OK into a Java Exception
* or to throw a PKCS11RuntimeException
diff --git a/jdk/src/solaris/classes/java/util/prefs/FileSystemPreferences.java b/jdk/src/solaris/classes/java/util/prefs/FileSystemPreferences.java
index 32e4b032929..53a19b5f5bd 100644
--- a/jdk/src/solaris/classes/java/util/prefs/FileSystemPreferences.java
+++ b/jdk/src/solaris/classes/java/util/prefs/FileSystemPreferences.java
@@ -571,9 +571,9 @@ class FileSystemPreferences extends AbstractPreferences {
long newLastSyncTime = 0;
try {
newLastSyncTime = prefsFile.lastModified();
- FileInputStream fis = new FileInputStream(prefsFile);
- XmlSupport.importMap(fis, m);
- fis.close();
+ try (FileInputStream fis = new FileInputStream(prefsFile)) {
+ XmlSupport.importMap(fis, m);
+ }
} catch(Exception e) {
if (e instanceof InvalidPreferencesFormatException) {
getLogger().warning("Invalid preferences format in "
@@ -618,9 +618,9 @@ class FileSystemPreferences extends AbstractPreferences {
if (!dir.exists() && !dir.mkdirs())
throw new BackingStoreException(dir +
" create failed.");
- FileOutputStream fos = new FileOutputStream(tmpFile);
- XmlSupport.exportMap(fos, prefsCache);
- fos.close();
+ try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
+ XmlSupport.exportMap(fos, prefsCache);
+ }
if (!tmpFile.renameTo(prefsFile))
throw new BackingStoreException("Can't rename " +
tmpFile + " to " + prefsFile);
diff --git a/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java b/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java
index 119146b68f4..ee3731a0c2e 100644
--- a/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java
+++ b/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java
@@ -236,7 +236,9 @@ class UnixAsynchronousServerSocketChannelImpl
} catch (SecurityException x) {
try {
ch.close();
- } catch (IOException ignore) { }
+ } catch (Throwable suppressed) {
+ x.addSuppressed(suppressed);
+ }
throw x;
}
return ch;
diff --git a/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java b/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java
index 4d887890ccd..37caeeb9bce 100644
--- a/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java
+++ b/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java
@@ -137,7 +137,7 @@ class UnixAsynchronousSocketChannelImpl
return port;
}
- // register for events if there are outstanding I/O operations
+ // register events for outstanding I/O operations, caller already owns updateLock
private void updateEvents() {
assert Thread.holdsLock(updateLock);
int events = 0;
@@ -149,6 +149,13 @@ class UnixAsynchronousSocketChannelImpl
port.startPoll(fdVal, events);
}
+ // register events for outstanding I/O operations
+ private void lockAndUpdateEvents() {
+ synchronized (updateLock) {
+ updateEvents();
+ }
+ }
+
// invoke to finish read and/or write operations
private void finish(boolean mayInvokeDirect,
boolean readable,
@@ -255,10 +262,11 @@ class UnixAsynchronousSocketChannelImpl
// close channel if connection cannot be established
try {
close();
- } catch (IOException ignore) { }
+ } catch (Throwable suppressed) {
+ e.addSuppressed(suppressed);
+ }
}
-
// invoke handler and set result
CompletionHandler handler = connectHandler;
Object att = connectAttachment;
@@ -345,7 +353,9 @@ class UnixAsynchronousSocketChannelImpl
if (e != null) {
try {
close();
- } catch (IOException ignore) { }
+ } catch (Throwable suppressed) {
+ e.addSuppressed(suppressed);
+ }
}
if (handler == null) {
return CompletedFuture.withResult(null, e);
@@ -399,9 +409,8 @@ class UnixAsynchronousSocketChannelImpl
exc = x;
} finally {
// restart poll in case of concurrent write
- synchronized (updateLock) {
- updateEvents();
- }
+ if (!(exc instanceof AsynchronousCloseException))
+ lockAndUpdateEvents();
end();
}
@@ -595,9 +604,8 @@ class UnixAsynchronousSocketChannelImpl
exc = x;
} finally {
// restart poll in case of concurrent write
- synchronized (updateLock) {
- updateEvents();
- }
+ if (!(exc instanceof AsynchronousCloseException))
+ lockAndUpdateEvents();
end();
}
diff --git a/jdk/src/solaris/native/java/net/Inet4AddressImpl.c b/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
index 8514eef39ac..e6eaa0aa2f5 100644
--- a/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
+++ b/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -77,22 +77,24 @@ Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
*/
#endif /* __linux__ */
struct hostent res, res2, *hp;
- char buf[HENT_BUF_SIZE];
- char buf2[HENT_BUF_SIZE];
+ // these buffers must be pointer-aligned so they are declared
+ // with pointer type
+ char *buf[HENT_BUF_SIZE/(sizeof (char *))];
+ char *buf2[HENT_BUF_SIZE/(sizeof (char *))];
int h_error=0;
#ifdef __GLIBC__
- gethostbyname_r(hostname, &res, buf, sizeof(buf), &hp, &h_error);
+ gethostbyname_r(hostname, &res, (char*)buf, sizeof(buf), &hp, &h_error);
#else
- hp = gethostbyname_r(hostname, &res, buf, sizeof(buf), &h_error);
+ hp = gethostbyname_r(hostname, &res, (char*)buf, sizeof(buf), &h_error);
#endif
if (hp) {
#ifdef __GLIBC__
gethostbyaddr_r(hp->h_addr, hp->h_length, AF_INET,
- &res2, buf2, sizeof(buf2), &hp, &h_error);
+ &res2, (char*)buf2, sizeof(buf2), &hp, &h_error);
#else
hp = gethostbyaddr_r(hp->h_addr, hp->h_length, AF_INET,
- &res2, buf2, sizeof(buf2), &h_error);
+ &res2, (char*)buf2, sizeof(buf2), &h_error);
#endif
if (hp) {
/*
@@ -136,7 +138,9 @@ Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
const char *hostname;
jobjectArray ret = 0;
struct hostent res, *hp = 0;
- char buf[HENT_BUF_SIZE];
+ // this buffer must be pointer-aligned so is declared
+ // with pointer type
+ char *buf[HENT_BUF_SIZE/(sizeof (char *))];
/* temporary buffer, on the off chance we need to expand */
char *tmp = NULL;
@@ -176,9 +180,9 @@ Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
/* Try once, with our static buffer. */
#ifdef __GLIBC__
- gethostbyname_r(hostname, &res, buf, sizeof(buf), &hp, &h_error);
+ gethostbyname_r(hostname, &res, (char*)buf, sizeof(buf), &hp, &h_error);
#else
- hp = gethostbyname_r(hostname, &res, buf, sizeof(buf), &h_error);
+ hp = gethostbyname_r(hostname, &res, (char*)buf, sizeof(buf), &h_error);
#endif
/* With the re-entrant system calls, it's possible that the buffer
@@ -251,7 +255,9 @@ Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
jstring ret = NULL;
jint addr;
struct hostent hent, *hp = 0;
- char buf[HENT_BUF_SIZE];
+ // this buffer must be pointer-aligned so is declared
+ // with pointer type
+ char *buf[HENT_BUF_SIZE/(sizeof (char *))];
int h_error = 0;
char *tmp = NULL;
@@ -273,10 +279,10 @@ Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
addr = htonl(addr);
#ifdef __GLIBC__
gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &hent,
- buf, sizeof(buf), &hp, &h_error);
+ (char*)buf, sizeof(buf), &hp, &h_error);
#else
hp = gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &hent,
- buf, sizeof(buf), &h_error);
+ (char*)buf, sizeof(buf), &h_error);
#endif
/* With the re-entrant system calls, it's possible that the buffer
* we pass to it is not large enough to hold an exceptionally
diff --git a/jdk/src/solaris/native/java/net/NetworkInterface.c b/jdk/src/solaris/native/java/net/NetworkInterface.c
index d85ca799d4e..ba1c3c7aa8e 100644
--- a/jdk/src/solaris/native/java/net/NetworkInterface.c
+++ b/jdk/src/solaris/native/java/net/NetworkInterface.c
@@ -45,7 +45,6 @@
#ifdef __linux__
#include
#include
-#include
#include
#include
#endif
@@ -1100,7 +1099,7 @@ static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
#ifdef AF_INET6
static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
FILE *f;
- char addr6[40], devname[20];
+ char addr6[40], devname[21];
char addr6p[8][5];
int plen, scope, dad_status, if_idx;
uint8_t ipv6addr[16];
diff --git a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
index 03e3a64c0c8..0eb2a9be890 100644
--- a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
@@ -34,8 +34,8 @@
#include
#endif
#ifdef __linux__
-#include
-#include
+#include
+#include
#include
#include
diff --git a/jdk/src/solaris/native/java/net/PlainSocketImpl.c b/jdk/src/solaris/native/java/net/PlainSocketImpl.c
index 018e264ef7e..9aca8060962 100644
--- a/jdk/src/solaris/native/java/net/PlainSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainSocketImpl.c
@@ -42,8 +42,8 @@
#include
#endif
#ifdef __linux__
-#include
-#include
+#include
+#include
#endif
#include "jvm.h"
diff --git a/jdk/src/solaris/native/java/net/linux_close.c b/jdk/src/solaris/native/java/net/linux_close.c
index 02d4fe5883d..1385519ef60 100644
--- a/jdk/src/solaris/native/java/net/linux_close.c
+++ b/jdk/src/solaris/native/java/net/linux_close.c
@@ -112,7 +112,7 @@ static void __attribute((constructor)) init() {
*/
static inline fdEntry_t *getFdEntry(int fd)
{
- if (fd < 0 || fd > fdCount) {
+ if (fd < 0 || fd >= fdCount) {
return NULL;
}
return &fdTable[fd];
diff --git a/jdk/src/solaris/native/java/net/net_util_md.c b/jdk/src/solaris/native/java/net/net_util_md.c
index 8367f05470b..8e035b368f1 100644
--- a/jdk/src/solaris/native/java/net/net_util_md.c
+++ b/jdk/src/solaris/native/java/net/net_util_md.c
@@ -608,7 +608,7 @@ static void initLoopbackRoutes() {
{
/* now find the scope_id for "lo" */
- char devname[20];
+ char devname[21];
char addr6p[8][5];
int plen, scope, dad_status, if_idx;
@@ -651,7 +651,7 @@ static int nifs = 0; /* number of entries used in array */
static void initLocalIfs () {
FILE *f;
unsigned char staddr [16];
- char ifname [32];
+ char ifname [33];
struct localinterface *lif=0;
int index, x1, x2, x3;
unsigned int u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,ua,ub,uc,ud,ue,uf;
@@ -660,7 +660,7 @@ static void initLocalIfs () {
return ;
}
while (fscanf (f, "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x "
- "%d %x %x %x %s",&u0,&u1,&u2,&u3,&u4,&u5,&u6,&u7,
+ "%d %x %x %x %32s",&u0,&u1,&u2,&u3,&u4,&u5,&u6,&u7,
&u8,&u9,&ua,&ub,&uc,&ud,&ue,&uf,
&index, &x1, &x2, &x3, ifname) == 21) {
staddr[0] = (unsigned char)u0;
@@ -1102,7 +1102,7 @@ int getDefaultIPv6Interface(struct in6_addr *target_addr) {
* index.
*/
if (match) {
- char devname[20];
+ char devname[21];
char addr6p[8][5];
int plen, scope, dad_status, if_idx;
diff --git a/jdk/src/windows/classes/sun/nio/ch/PendingIoCache.java b/jdk/src/windows/classes/sun/nio/ch/PendingIoCache.java
index 3d78a733c8c..7a4b1e3e319 100644
--- a/jdk/src/windows/classes/sun/nio/ch/PendingIoCache.java
+++ b/jdk/src/windows/classes/sun/nio/ch/PendingIoCache.java
@@ -110,8 +110,7 @@ class PendingIoCache {
if (closed)
return;
- // handle the case that where there are I/O operations that have
- // not completed.
+ // handle case where I/O operations that have not completed.
if (!pendingIoMap.isEmpty())
clearPendingIoMap();
@@ -132,7 +131,9 @@ class PendingIoCache {
closePending = true;
try {
this.wait(50);
- } catch (InterruptedException x) { }
+ } catch (InterruptedException x) {
+ Thread.currentThread().interrupt();
+ }
closePending = false;
if (pendingIoMap.isEmpty())
return;
diff --git a/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java b/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java
index 694b23a34a9..82405875928 100644
--- a/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java
+++ b/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java
@@ -439,6 +439,7 @@ public class WindowsAsynchronousFileChannelImpl
address = ((DirectBuffer)buf).address();
}
+ boolean pending = false;
try {
begin();
@@ -449,6 +450,7 @@ public class WindowsAsynchronousFileChannelImpl
n = readFile(handle, address, rem, position, overlapped);
if (n == IOStatus.UNAVAILABLE) {
// I/O is pending
+ pending = true;
return;
} else if (n == IOStatus.EOF) {
result.setResult(n);
@@ -460,14 +462,15 @@ public class WindowsAsynchronousFileChannelImpl
// failed to initiate read
result.setFailure(toIOException(x));
} finally {
+ if (!pending) {
+ // release resources
+ if (overlapped != 0L)
+ ioCache.remove(overlapped);
+ releaseBufferIfSubstituted();
+ }
end();
}
- // release resources
- if (overlapped != 0L)
- ioCache.remove(overlapped);
- releaseBufferIfSubstituted();
-
// invoke completion handler
Invoker.invoke(result);
}
diff --git a/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java b/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java
index 28d3c074549..2cc9cf026af 100644
--- a/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java
+++ b/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java
@@ -239,14 +239,14 @@ class WindowsAsynchronousSocketChannelImpl
result.setResult(null);
}
} catch (Throwable x) {
+ if (overlapped != 0L)
+ ioCache.remove(overlapped);
exc = x;
} finally {
end();
}
if (exc != null) {
- if (overlapped != 0L)
- ioCache.remove(overlapped);
closeChannel();
result.setFailure(toIOException(exc));
}
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsFileStore.java b/jdk/src/windows/classes/sun/nio/fs/WindowsFileStore.java
index 8b3c2fb4b19..07eb73231ce 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsFileStore.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsFileStore.java
@@ -201,13 +201,12 @@ class WindowsFileStore
if (!(ob instanceof WindowsFileStore))
return false;
WindowsFileStore other = (WindowsFileStore)ob;
- return this.volInfo.volumeSerialNumber() == other.volInfo.volumeSerialNumber();
+ return root.equals(other.root);
}
@Override
public int hashCode() {
- // reveals VSN without permission check - okay?
- return volInfo.volumeSerialNumber();
+ return root.hashCode();
}
@Override
diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt
index 46b8cc1e855..27518785b07 100644
--- a/jdk/test/ProblemList.txt
+++ b/jdk/test/ProblemList.txt
@@ -380,30 +380,9 @@ java/io/File/MaxPathLength.java windows-all
# jdk_nio
-# 6944810
-java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java windows-all
-
# 6963118
java/nio/channels/Selector/Wakeup.java windows-all
-# The asynchronous I/O implementation on Windows requires Windows XP or newer.
-# We can remove the following once all Windows 2000 machines have been
-# decommissioned.
-java/nio/channels/AsynchronousChannelGroup/Basic.java windows-5.0
-java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java windows-5.0
-java/nio/channels/AsynchronousChannelGroup/Identity.java windows-5.0
-java/nio/channels/AsynchronousChannelGroup/Restart.java windows-5.0
-java/nio/channels/AsynchronousChannelGroup/Unbounded.java windows-5.0
-java/nio/channels/AsynchronousDatagramChannel/Basic.java windows-5.0
-java/nio/channels/AsynchronousFileChannel/Lock.java windows-5.0
-java/nio/channels/AsynchronousServerSocketChannel/Basic.java windows-5.0
-java/nio/channels/AsynchronousServerSocketChannel/WithSecurityManager.java windows-5.0
-java/nio/channels/AsynchronousSocketChannel/Basic.java windows-5.0
-java/nio/channels/AsynchronousSocketChannel/DieBeforeComplete.java windows-5.0
-java/nio/channels/AsynchronousSocketChannel/Leaky.java windows-5.0
-java/nio/channels/AsynchronousSocketChannel/StressLoopback.java windows-5.0
-java/nio/channels/Channels/Basic2.java windows-5.0
-
# 6959891
com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
@@ -625,9 +604,6 @@ sun/security/tools/keytool/emptysubject.sh generic-all
# Timeout on solaris-sparcv9 or exception thrown
com/sun/crypto/provider/Cipher/RSA/TestOAEP_KAT.java solaris-all
-# File 6535697.test input stream left open? windows samevm
-java/security/cert/CertificateFactory/openssl/OpenSSLCert.java generic-all
-
# Leaving file open: SerialVersion.current, windows samevm
java/security/BasicPermission/SerialVersion.java generic-all
@@ -717,6 +693,7 @@ sun/tools/jconsole/ResourceCheckTest.sh generic-all
# Filed 6933803
java/util/concurrent/ThreadPoolExecutor/CoreThreadTimeOut.java generic-all
+# Filed 7022325
# Fails with assertion error on windows
# 11 separate stacktraces created... file reuse problem?
java/util/zip/ZipFile/ReadLongZipFileName.java generic-all
diff --git a/jdk/test/com/sun/jndi/ldap/NoWaitForReplyTest.java b/jdk/test/com/sun/jndi/ldap/NoWaitForReplyTest.java
new file mode 100644
index 00000000000..bb772c09bc5
--- /dev/null
+++ b/jdk/test/com/sun/jndi/ldap/NoWaitForReplyTest.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 6748156
+ * @summary add an new JNDI property to control the boolean flag WaitForReply
+ */
+
+import java.net.Socket;
+import java.net.ServerSocket;
+import java.io.*;
+import javax.naming.*;
+import javax.naming.directory.*;
+import java.util.Hashtable;
+
+public class NoWaitForReplyTest {
+
+ public static void main(String[] args) throws Exception {
+
+ boolean passed = false;
+
+ // start the LDAP server
+ DummyServer ldapServer = new DummyServer();
+ ldapServer.start();
+
+ // Set up the environment for creating the initial context
+ Hashtable env = new Hashtable(11);
+ env.put(Context.PROVIDER_URL, "ldap://localhost:" +
+ ldapServer.getPortNumber());
+ env.put(Context.INITIAL_CONTEXT_FACTORY,
+ "com.sun.jndi.ldap.LdapCtxFactory");
+
+ // Wait up to 10 seconds for a response from the LDAP server
+ env.put("com.sun.jndi.ldap.read.timeout", "10000");
+
+ // Don't wait until the first search reply is received
+ env.put("com.sun.jndi.ldap.search.waitForReply", "false");
+
+ // Send the LDAP search request without first authenticating (no bind)
+ env.put("java.naming.ldap.version", "3");
+
+
+ try {
+
+ // Create initial context
+ System.out.println("Client: connecting to the server");
+ DirContext ctx = new InitialDirContext(env);
+
+ SearchControls scl = new SearchControls();
+ scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
+ System.out.println("Client: performing search");
+ NamingEnumeration answer =
+ ctx.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
+
+ // Server will never reply: either we waited in the call above until
+ // the timeout (fail) or we did not wait and reached here (pass).
+ passed = true;
+ System.out.println("Client: did not wait until first reply");
+
+ // Close the context when we're done
+ ctx.close();
+
+ } catch (NamingException e) {
+ // timeout (ignore)
+ }
+ ldapServer.interrupt();
+
+ if (!passed) {
+ throw new Exception(
+ "Test FAILED: should not have waited until first search reply");
+ }
+ System.out.println("Test PASSED");
+ }
+
+ static class DummyServer extends Thread {
+
+ private final ServerSocket serverSocket;
+
+ DummyServer() throws IOException {
+ this.serverSocket = new ServerSocket(0);
+ System.out.println("Server: listening on port " + serverSocket.getLocalPort());
+ }
+
+ public int getPortNumber() {
+ return serverSocket.getLocalPort();
+ }
+
+ public void run() {
+ try (Socket socket = serverSocket.accept()) {
+ System.out.println("Server: accepted a connection");
+ InputStream in = socket.getInputStream();
+
+ while (!isInterrupted()) {
+ in.skip(in.available());
+ }
+
+ } catch (Exception e) {
+ // ignore
+
+ } finally {
+ System.out.println("Server: shutting down");
+ try {
+ serverSocket.close();
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+ }
+ }
+}
diff --git a/jdk/test/java/io/File/SetLastModified.java b/jdk/test/java/io/File/SetLastModified.java
index 3ca72c9d516..fada781a202 100644
--- a/jdk/test/java/io/File/SetLastModified.java
+++ b/jdk/test/java/io/File/SetLastModified.java
@@ -105,9 +105,9 @@ public class SetLastModified {
System.getProperty("os.name").startsWith("Windows") ? 0L : 3L*G;
long pos = 0L;
while (pos <= MAX_POSITION) {
- FileChannel fc = new FileOutputStream(f).getChannel();
- fc.position(pos).write(ByteBuffer.wrap("x".getBytes()));
- fc.close();
+ try (FileChannel fc = new FileOutputStream(f).getChannel()) {
+ fc.position(pos).write(ByteBuffer.wrap("x".getBytes()));
+ }
ot = f.lastModified();
System.out.format("check with file size: %d\n", f.length());
if (!f.setLastModified(nt))
diff --git a/jdk/test/java/io/FileOutputStream/AtomicAppend.java b/jdk/test/java/io/FileOutputStream/AtomicAppend.java
index 627c9440040..c5f18e6cd98 100644
--- a/jdk/test/java/io/FileOutputStream/AtomicAppend.java
+++ b/jdk/test/java/io/FileOutputStream/AtomicAppend.java
@@ -47,12 +47,12 @@ public class AtomicAppend {
for (int i = 0; i < nThreads; i++)
es.execute(new Runnable() { public void run() {
try {
- FileOutputStream s = new FileOutputStream(file, true);
- for (int j = 0; j < 1000; j++) {
- s.write((int) 'x');
- s.flush();
+ try (FileOutputStream s = new FileOutputStream(file, true)) {
+ for (int j = 0; j < 1000; j++) {
+ s.write((int) 'x');
+ s.flush();
+ }
}
- s.close();
} catch (Throwable t) { unexpected(t); }}});
es.shutdown();
es.awaitTermination(10L, TimeUnit.MINUTES);
diff --git a/jdk/test/java/io/OutputStreamWriter/Encode.java b/jdk/test/java/io/OutputStreamWriter/Encode.java
index 07897607af0..fda2d03cc54 100644
--- a/jdk/test/java/io/OutputStreamWriter/Encode.java
+++ b/jdk/test/java/io/OutputStreamWriter/Encode.java
@@ -35,8 +35,9 @@ public class Encode implements Runnable {
new Encode();
}
+ final ServerSocket ss = new ServerSocket(0);
+
Encode() throws Exception {
- ss = new ServerSocket(0);
(new Thread(this)).start();
String toEncode = "\uD800\uDC00 \uD801\uDC01 ";
String enc1 = URLEncoder.encode(toEncode, "UTF-8");
@@ -47,27 +48,31 @@ public class Encode implements Runnable {
"/missing.nothtml";
HttpURLConnection uc = (HttpURLConnection)new URL(url).openConnection();
uc.connect();
- String enc2 = URLEncoder.encode(toEncode, "UTF-8");
- if (!enc1.equals(enc2))
- throw new RuntimeException("test failed");
- uc.disconnect();
+ try {
+ String enc2 = URLEncoder.encode(toEncode, "UTF-8");
+ if (!enc1.equals(enc2)) {
+ System.out.println("test failed");
+ throw new RuntimeException("test failed");
+ }
+ } finally {
+ uc.disconnect();
+ }
}
- ServerSocket ss;
-
public void run() {
- try {
- Socket s = ss.accept();
- BufferedReader in = new BufferedReader(
- new InputStreamReader(s.getInputStream()));
+ try (ServerSocket serv = ss;
+ Socket s = serv.accept();
+ BufferedReader in =
+ new BufferedReader(new InputStreamReader(s.getInputStream())))
+ {
String req = in.readLine();
- PrintStream out = new PrintStream(new BufferedOutputStream(
- s.getOutputStream()));
- out.print("HTTP/1.1 403 Forbidden\r\n");
- out.print("\r\n");
- out.flush();
- s.close();
- ss.close();
+ try (OutputStream os = s.getOutputStream();
+ BufferedOutputStream bos = new BufferedOutputStream(os);
+ PrintStream out = new PrintStream(bos))
+ {
+ out.print("HTTP/1.1 403 Forbidden\r\n");
+ out.print("\r\n");
+ }
} catch (Exception e) {
e.printStackTrace();
}
diff --git a/jdk/test/java/io/PrintStream/EncodingConstructor.java b/jdk/test/java/io/PrintStream/EncodingConstructor.java
index d4c36889877..a4b9c884295 100644
--- a/jdk/test/java/io/PrintStream/EncodingConstructor.java
+++ b/jdk/test/java/io/PrintStream/EncodingConstructor.java
@@ -34,11 +34,11 @@ public class EncodingConstructor {
public static void main(String args[]) throws Exception {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bo, false, "UTF-8");
String s = "xyzzy";
int n = s.length();
- ps.print(s);
- ps.close();
+ try (PrintStream ps = new PrintStream(bo, false, "UTF-8")) {
+ ps.print(s);
+ }
byte[] ba = bo.toByteArray();
if (ba.length != n)
throw new Exception("Length mismatch: " + n + " " + ba.length);
diff --git a/jdk/test/java/io/PrintStream/FailingConstructors.java b/jdk/test/java/io/PrintStream/FailingConstructors.java
index 1022bb9d311..70f04b2ec14 100644
--- a/jdk/test/java/io/PrintStream/FailingConstructors.java
+++ b/jdk/test/java/io/PrintStream/FailingConstructors.java
@@ -35,6 +35,8 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
+import java.nio.file.Files;
+import java.nio.file.Path;
public class FailingConstructors {
static final String fileName = "FailingConstructorsTest";
@@ -45,14 +47,13 @@ public class FailingConstructors {
test(false, new File(fileName));
/* create the file and write its contents */
- File file = File.createTempFile(fileName, null);
- file.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(FILE_CONTENTS.getBytes());
- fos.close();
-
- test(true, file);
- file.delete();
+ Path path = Files.createTempFile(fileName, null);
+ try {
+ Files.write(path, FILE_CONTENTS.getBytes());
+ test(true, path.toFile());
+ } finally {
+ Files.delete(path);
+ }
}
private static void test(boolean exists, File file) throws Throwable {
diff --git a/jdk/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java b/jdk/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java
index 073caf7ffd7..47f79ea713d 100644
--- a/jdk/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java
+++ b/jdk/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java
@@ -27,7 +27,7 @@
* @build install/SerialDriver.java test/SerialDriver.java extension/ExtendedObjectInputStream.java
* @summary Enable resolveClass() to accommodate package renaming.
* This fix enables one to implement a resolveClass method that maps a
- * Serialiazable class within a serialization stream to the same class
+ * Serializable class within a serialization stream to the same class
* in a different package within the JVM runtime. See run shell script
* for instructions on how to run this test.
*/
@@ -86,16 +86,15 @@ public class SerialDriver implements Serializable {
File f = new File("stream.ser");
if (serialize) {
// Serialize the subclass
- try {
- FileOutputStream fo = new FileOutputStream(f);
- ObjectOutputStream so = new ObjectOutputStream(fo);
+ try (FileOutputStream fo = new FileOutputStream(f);
+ ObjectOutputStream so = new ObjectOutputStream(fo))
+ {
so.writeObject(obj);
/* Skip arrays since they do not work with rename yet.
The serialVersionUID changes due to the name change
and there is no way to set the serialVersionUID for an
array. */
so.writeObject(array);
- so.flush();
} catch (Exception e) {
System.out.println(e);
throw e;
@@ -103,16 +102,14 @@ public class SerialDriver implements Serializable {
}
if (deserialize) {
// Deserialize the subclass
- try {
- FileInputStream fi = new FileInputStream(f);
- ExtendedObjectInputStream si =
- new ExtendedObjectInputStream(fi);
+ try (FileInputStream fi = new FileInputStream(f);
+ ExtendedObjectInputStream si = new ExtendedObjectInputStream(fi))
+ {
si.addRenamedClassName("test.SerialDriver", "install.SerialDriver");
si.addRenamedClassName("[Ltest.SerialDriver;",
"[Linstall.SerialDriver");
obj = (SerialDriver) si.readObject();
array = (SerialDriver[]) si.readObject();
- si.close();
} catch (Exception e) {
System.out.println(e);
throw e;
diff --git a/jdk/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java b/jdk/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java
index 44e2392aa9c..533df16511d 100644
--- a/jdk/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java
+++ b/jdk/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java
@@ -27,7 +27,7 @@
* @build install/SerialDriver.java test/SerialDriver.java extension/ExtendedObjectInputStream.java
* @summary Enable resolveClass() to accommodate package renaming.
* This fix enables one to implement a resolveClass method that maps a
- * Serialiazable class within a serialization stream to the same class
+ * Serializable class within a serialization stream to the same class
* in a different package within the JVM runtime. See run shell script
* for instructions on how to run this test.
*/
@@ -83,14 +83,13 @@ public class SerialDriver implements Serializable {
File f = new File("stream.ser");
if (serialize) {
// Serialize the subclass
- try {
- FileOutputStream fo = new FileOutputStream(f);
- ObjectOutputStream so = new ObjectOutputStream(fo);
+ try (FileOutputStream fo = new FileOutputStream(f);
+ ObjectOutputStream so = new ObjectOutputStream(fo))
+ {
so.writeObject(obj);
/* Comment out since renaming arrays does not work
since it changes the serialVersionUID. */
so.writeObject(array);
- so.flush();
} catch (Exception e) {
System.out.println(e);
throw e;
@@ -98,16 +97,15 @@ public class SerialDriver implements Serializable {
}
if (deserialize) {
// Deserialize the subclass
- try {
- FileInputStream fi = new FileInputStream(f);
- ExtendedObjectInputStream si = new ExtendedObjectInputStream(fi);
+ try (FileInputStream fi = new FileInputStream(f);
+ ExtendedObjectInputStream si = new ExtendedObjectInputStream(fi))
+ {
si.addRenamedClassName("install.SerialDriver",
"test.SerialDriver");
si.addRenamedClassName("[Linstall.SerialDriver;",
"[Ltest.SerialDriver");
obj = (SerialDriver) si.readObject();
array = (SerialDriver[]) si.readObject();
- si.close();
} catch (Exception e) {
System.out.println(e);
throw e;
diff --git a/jdk/test/java/lang/Character/CheckScript.java b/jdk/test/java/lang/Character/CheckScript.java
index a286643c8cf..6d0f650d169 100644
--- a/jdk/test/java/lang/Character/CheckScript.java
+++ b/jdk/test/java/lang/Character/CheckScript.java
@@ -12,40 +12,43 @@ import java.lang.Character.UnicodeScript;
public class CheckScript {
- public static void main(String[] args) throws Exception {
-
- BufferedReader sbfr = null;
+ static BufferedReader open(String[] args) throws FileNotFoundException {
if (args.length == 0) {
- sbfr = new BufferedReader(new FileReader(new File(System.getProperty("test.src", "."), "Scripts.txt")));
+ return new BufferedReader(new FileReader(new File(System.getProperty("test.src", "."), "Scripts.txt")));
} else if (args.length == 1) {
- sbfr = new BufferedReader(new FileReader(args[0]));
+ return new BufferedReader(new FileReader(args[0]));
} else {
System.out.println("java CharacterScript Scripts.txt");
throw new RuntimeException("Datafile name should be specified.");
}
+ }
+
+ public static void main(String[] args) throws Exception {
+
Matcher m = Pattern.compile("(\\p{XDigit}+)(?:\\.{2}(\\p{XDigit}+))?\\s+;\\s+(\\w+)\\s+#.*").matcher("");
String line = null;
HashMap> scripts = new HashMap<>();
- while ((line = sbfr.readLine()) != null) {
- if (line.length() <= 1 || line.charAt(0) == '#') {
- continue;
- }
- m.reset(line);
- if (m.matches()) {
- int start = Integer.parseInt(m.group(1), 16);
- int end = (m.group(2)==null)?start
- :Integer.parseInt(m.group(2), 16);
- String name = m.group(3).toLowerCase(Locale.ENGLISH);
- ArrayList ranges = scripts.get(name);
- if (ranges == null) {
- ranges = new ArrayList();
- scripts.put(name, ranges);
+ try (BufferedReader sbfr = open(args)) {
+ while ((line = sbfr.readLine()) != null) {
+ if (line.length() <= 1 || line.charAt(0) == '#') {
+ continue;
+ }
+ m.reset(line);
+ if (m.matches()) {
+ int start = Integer.parseInt(m.group(1), 16);
+ int end = (m.group(2)==null)?start
+ :Integer.parseInt(m.group(2), 16);
+ String name = m.group(3).toLowerCase(Locale.ENGLISH);
+ ArrayList ranges = scripts.get(name);
+ if (ranges == null) {
+ ranges = new ArrayList();
+ scripts.put(name, ranges);
+ }
+ ranges.add(start);
+ ranges.add(end);
}
- ranges.add(start);
- ranges.add(end);
}
}
- sbfr.close();
// check all defined ranges
Integer[] ZEROSIZEARRAY = new Integer[0];
for (String name : scripts.keySet()) {
diff --git a/jdk/test/java/lang/ProcessBuilder/Basic.java b/jdk/test/java/lang/ProcessBuilder/Basic.java
index ebe65fb5bad..7ba90e8e8a2 100644
--- a/jdk/test/java/lang/ProcessBuilder/Basic.java
+++ b/jdk/test/java/lang/ProcessBuilder/Basic.java
@@ -26,7 +26,7 @@
* @bug 4199068 4738465 4937983 4930681 4926230 4931433 4932663 4986689
* 5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313
* 6464154 6523983 6206031 4960438 6631352 6631966 6850957 6850958
- * 4947220
+ * 4947220 7018606
* @summary Basic tests for Process and Environment Variable code
* @run main/othervm/timeout=300 Basic
* @author Martin Buchholz
@@ -47,6 +47,9 @@ import static java.util.AbstractMap.SimpleImmutableEntry;
public class Basic {
+ /* used for Windows only */
+ static final String systemRoot = System.getenv("SystemRoot");
+
private static String commandOutput(Reader r) throws Throwable {
StringBuilder sb = new StringBuilder();
int c;
@@ -1073,7 +1076,11 @@ public class Basic {
try {
ProcessBuilder pb = new ProcessBuilder();
pb.environment().clear();
- equal(getenvInChild(pb), "");
+ String expected = Windows.is() ? "SystemRoot="+systemRoot+",": "";
+ if (Windows.is()) {
+ pb.environment().put("SystemRoot", systemRoot);
+ }
+ equal(getenvInChild(pb), expected);
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
@@ -1561,13 +1568,21 @@ public class Basic {
List childArgs = new ArrayList(javaChildArgs);
childArgs.add("System.getenv()");
String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
- String[] envp = {"=ExitValue=3", "=C:=\\"};
+ String[] envp;
+ String[] envpWin = {"=ExitValue=3", "=C:=\\", "SystemRoot="+systemRoot};
+ String[] envpOth = {"=ExitValue=3", "=C:=\\"};
+ if (Windows.is()) {
+ envp = envpWin;
+ } else {
+ envp = envpOth;
+ }
Process p = Runtime.getRuntime().exec(cmdp, envp);
- String expected = Windows.is() ? "=C:=\\,=ExitValue=3," : "=C:=\\,";
+ String expected = Windows.is() ? "=C:=\\,SystemRoot="+systemRoot+",=ExitValue=3," : "=C:=\\,";
equal(commandOutput(p), expected);
if (Windows.is()) {
ProcessBuilder pb = new ProcessBuilder(childArgs);
pb.environment().clear();
+ pb.environment().put("SystemRoot", systemRoot);
pb.environment().put("=ExitValue", "3");
pb.environment().put("=C:", "\\");
equal(commandOutput(pb), expected);
@@ -1591,10 +1606,18 @@ public class Basic {
List childArgs = new ArrayList(javaChildArgs);
childArgs.add("System.getenv()");
String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
- String[] envp = {"LC_ALL=C\u0000\u0000", // Yuck!
+ String[] envpWin = {"SystemRoot="+systemRoot, "LC_ALL=C\u0000\u0000", // Yuck!
"FO\u0000=B\u0000R"};
+ String[] envpOth = {"LC_ALL=C\u0000\u0000", // Yuck!
+ "FO\u0000=B\u0000R"};
+ String[] envp;
+ if (Windows.is()) {
+ envp = envpWin;
+ } else {
+ envp = envpOth;
+ }
Process p = Runtime.getRuntime().exec(cmdp, envp);
- check(commandOutput(p).equals("LC_ALL=C,"),
+ check(commandOutput(p).equals(Windows.is() ? "SystemRoot="+systemRoot+",LC_ALL=C," : "LC_ALL=C,"),
"Incorrect handling of envstrings containing NULs");
} catch (Throwable t) { unexpected(t); }
@@ -2144,6 +2167,7 @@ public class Basic {
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
+
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
diff --git a/jdk/test/java/lang/Runtime/shutdown/ShutdownHooks.java b/jdk/test/java/lang/Runtime/shutdown/ShutdownHooks.java
index a198d98b872..bfe2b60e3ee 100644
--- a/jdk/test/java/lang/Runtime/shutdown/ShutdownHooks.java
+++ b/jdk/test/java/lang/Runtime/shutdown/ShutdownHooks.java
@@ -43,9 +43,9 @@ public class ShutdownHooks {
file = new File(dir, args[1]);
// write to file
System.out.println("writing to "+ file);
- PrintWriter pw = new PrintWriter(file);
- pw.println("Shutdown begins");
- pw.close();
+ try (PrintWriter pw = new PrintWriter(file)) {
+ pw.println("Shutdown begins");
+ }
}
public static class Cleaner extends Thread {
@@ -56,10 +56,8 @@ public class ShutdownHooks {
// register the DeleteOnExitHook while the application
// shutdown hook is running
file.deleteOnExit();
- try {
- PrintWriter pw = new PrintWriter(file);
+ try (PrintWriter pw = new PrintWriter(file)) {
pw.println("file is being deleted");
- pw.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
diff --git a/jdk/test/java/lang/Thread/StartOOMTest.java b/jdk/test/java/lang/Thread/StartOOMTest.java
index fd6c070baef..57edd723c31 100644
--- a/jdk/test/java/lang/Thread/StartOOMTest.java
+++ b/jdk/test/java/lang/Thread/StartOOMTest.java
@@ -22,11 +22,14 @@
*/
/*
- * @test
- * @bug 6379235
- * @ignore until 6721694 is fixed
- * @run main/othervm -server -Xmx32m -Xms32m -Xss256m StartOOMTest
- * @summary ThreadGroup accounting mistake possible with failure of Thread.start()
+ * This test is relatively useful for verifying 6379235, but
+ * is too resource intensive, especially on 64 bit systems,
+ * to be run automatically, see 6721694.
+ *
+ * When run it should be typically be run with the server vm
+ * and a relatively small java heap, and a large stack size
+ * ( to provoke the OOM quicker ).
+ * java -server -Xmx32m -Xms32m -Xss256m StartOOMTest
*/
import java.util.*;
diff --git a/jdk/test/java/lang/instrument/BootClassPath/Setup.java b/jdk/test/java/lang/instrument/BootClassPath/Setup.java
index 90beff135ea..3ef40f13217 100644
--- a/jdk/test/java/lang/instrument/BootClassPath/Setup.java
+++ b/jdk/test/java/lang/instrument/BootClassPath/Setup.java
@@ -62,31 +62,33 @@ public class Setup {
* Create manifest file with Boot-Class-Path encoding the
* sub-directory name.
*/
- FileOutputStream out = new FileOutputStream(manifestFile);
- out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
+ try (FileOutputStream out = new FileOutputStream(manifestFile)) {
+ out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
- byte[] premainBytes = ("Premain-Class: " + premainClass + "\n").getBytes("UTF-8");
- out.write(premainBytes);
+ byte[] premainBytes =
+ ("Premain-Class: " + premainClass + "\n").getBytes("UTF-8");
+ out.write(premainBytes);
- out.write( "Boot-Class-Path: ".getBytes("UTF-8") );
+ out.write( "Boot-Class-Path: ".getBytes("UTF-8") );
- byte[] value = bootClassPath.getBytes("UTF-8");
- for (int i=0; i it = infoList.iterator(); it.hasNext(); ) {
- Info info = it.next();
- if (!info.className.equals(currentClassName)) {
- dataOut.writeInt(123456); // class name marker
- currentClassName = info.className;
- dataOut.writeUTF(currentClassName);
+ dataOut.writeInt(infoList.size());
+ for (Iterator it = infoList.iterator(); it.hasNext(); ) {
+ Info info = it.next();
+ if (!info.className.equals(currentClassName)) {
+ dataOut.writeInt(123456); // class name marker
+ currentClassName = info.className;
+ dataOut.writeUTF(currentClassName);
+ }
+ dataOut.writeInt(info.location);
+ dataOut.writeUTF(info.methodName);
}
- dataOut.writeInt(info.location);
- dataOut.writeUTF(info.methodName);
}
- dataOut.close();
}
public byte[] bytecodes(String className, String methodName, int location) {
diff --git a/jdk/test/java/math/BigInteger/BigIntegerTest.java b/jdk/test/java/math/BigInteger/BigIntegerTest.java
index ba35c7bbdbe..c23563f2208 100644
--- a/jdk/test/java/math/BigInteger/BigIntegerTest.java
+++ b/jdk/test/java/math/BigInteger/BigIntegerTest.java
@@ -645,26 +645,17 @@ public class BigIntegerTest {
BigInteger b2 = null;
File f = new File("serialtest");
- FileOutputStream fos = new FileOutputStream(f);
- try {
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- try {
+
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(b1);
oos.flush();
- } finally {
- oos.close();
}
- FileInputStream fis = new FileInputStream(f);
- try {
- ObjectInputStream ois = new ObjectInputStream(fis);
- try {
- b2 = (BigInteger)ois.readObject();
- } finally {
- ois.close();
- }
- } finally {
- fis.close();
+ try (FileInputStream fis = new FileInputStream(f);
+ ObjectInputStream ois = new ObjectInputStream(fis))
+ {
+ b2 = (BigInteger)ois.readObject();
}
if (!b1.equals(b2) ||
@@ -673,8 +664,6 @@ public class BigIntegerTest {
System.err.println("Serialized failed for hex " +
b1.toString(16));
}
- } finally {
- fos.close();
}
f.delete();
}
@@ -683,29 +672,17 @@ public class BigIntegerTest {
BigInteger b1 = fetchNumber(rnd.nextInt(100));
BigInteger b2 = null;
File f = new File("serialtest");
- FileOutputStream fos = new FileOutputStream(f);
- try {
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- try {
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(b1);
oos.flush();
- } finally {
- oos.close();
}
- FileInputStream fis = new FileInputStream(f);
- try {
- ObjectInputStream ois = new ObjectInputStream(fis);
- try {
- b2 = (BigInteger)ois.readObject();
- } finally {
- ois.close();
- }
- } finally {
- fis.close();
+ try (FileInputStream fis = new FileInputStream(f);
+ ObjectInputStream ois = new ObjectInputStream(fis))
+ {
+ b2 = (BigInteger)ois.readObject();
}
- } finally {
- fos.close();
}
if (!b1.equals(b2) ||
diff --git a/jdk/test/java/net/URLConnection/RedirectLimit.java b/jdk/test/java/net/URLConnection/RedirectLimit.java
index 1df973f8bc0..5fe65a1a914 100644
--- a/jdk/test/java/net/URLConnection/RedirectLimit.java
+++ b/jdk/test/java/net/URLConnection/RedirectLimit.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -36,105 +36,81 @@ import java.io.*;
import java.net.*;
class RedirLimitServer extends Thread {
+ static final int TIMEOUT = 10 * 1000;
+ static final int NUM_REDIRECTS = 9;
- ServerSocket s;
- Socket s1;
- InputStream is;
- OutputStream os;
- int port;
- int nredirects = 9;
-
- String reply1 = "HTTP/1.1 307 Temporary Redirect\r\n" +
+ static final String reply1 = "HTTP/1.1 307 Temporary Redirect\r\n" +
"Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
"Server: Apache/1.3.14 (Unix)\r\n" +
"Location: http://localhost:";
- String reply2 = ".html\r\n" +
+ static final String reply2 = ".html\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
"Hello";
-
- RedirLimitServer (ServerSocket y) {
- s = y;
- port = s.getLocalPort();
- }
-
- String reply3 = "HTTP/1.1 200 Ok\r\n" +
+ static final String reply3 = "HTTP/1.1 200 Ok\r\n" +
"Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" +
"Server: Apache/1.3.14 (Unix)\r\n" +
"Connection: close\r\n" +
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n" +
"World";
- public void run () {
+ final ServerSocket ss;
+ final int port;
+
+ RedirLimitServer(ServerSocket ss) {
+ this.ss = ss;
+ port = ss.getLocalPort();
+ }
+
+ public void run() {
try {
- s.setSoTimeout (2000);
- for (int i=0; i[])null);
+ throw new RuntimeException("NullPointerException expected");
+ } catch (NullPointerException ignore) { }
+ try {
+ Files.createTempFile("blah", ".tmp", new FileAttribute>[] { null });
+ throw new RuntimeException("NullPointerException expected");
+ } catch (NullPointerException ignore) { }
+ try {
+ Files.createTempDirectory("blah", (FileAttribute>[])null);
+ throw new RuntimeException("NullPointerException expected");
+ } catch (NullPointerException ignore) { }
+ try {
+ Files.createTempDirectory("blah", new FileAttribute>[] { null });
+ throw new RuntimeException("NullPointerException expected");
+ } catch (NullPointerException ignore) { }
+ try {
+ Files.createTempFile((Path)null, "blah", ".tmp");
+ throw new RuntimeException("NullPointerException expected");
+ } catch (NullPointerException ignore) { }
+ try {
+ Files.createTempDirectory((Path)null, "blah");
+ throw new RuntimeException("NullPointerException expected");
+ } catch (NullPointerException ignore) { }
}
}
diff --git a/jdk/test/java/security/cert/CertificateFactory/openssl/OpenSSLCert.java b/jdk/test/java/security/cert/CertificateFactory/openssl/OpenSSLCert.java
index 92fbef6b98a..1f19292da33 100644
--- a/jdk/test/java/security/cert/CertificateFactory/openssl/OpenSSLCert.java
+++ b/jdk/test/java/security/cert/CertificateFactory/openssl/OpenSSLCert.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,8 @@
*/
import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.Arrays;
import java.security.cert.CertificateFactory;
@@ -46,24 +48,20 @@ public class OpenSSLCert {
}
static void test(String... files) throws Exception {
- FileOutputStream fout = new FileOutputStream(OUTFILE);
- for (String file: files) {
- FileInputStream fin = new FileInputStream(
- new File(System.getProperty("test.src", "."), file));
- byte[] buffer = new byte[4096];
- while (true) {
- int len = fin.read(buffer);
- if (len < 0) break;
- fout.write(buffer, 0, len);
+ try (FileOutputStream fout = new FileOutputStream(OUTFILE)) {
+ String here = System.getProperty("test.src", "");
+ for (String file: files) {
+ Files.copy(Paths.get(here, file), fout);
}
- fin.close();
}
- fout.close();
- System.out.println("Testing " + Arrays.toString(files) + "...");
- if (CertificateFactory.getInstance("X509")
- .generateCertificates(new FileInputStream(OUTFILE))
- .size() != files.length) {
- throw new Exception("Not same number");
+ try (FileInputStream fin = new FileInputStream(OUTFILE)) {
+ System.out.println("Testing " + Arrays.toString(files) + "...");
+ if (CertificateFactory.getInstance("X509")
+ .generateCertificates(fin)
+ .size() != files.length) {
+ throw new Exception("Not same number");
+ }
}
+ Files.delete(Paths.get(OUTFILE));
}
}
diff --git a/jdk/test/java/util/Collection/MOAT.java b/jdk/test/java/util/Collection/MOAT.java
index a85afa3c8d2..ce7975635a8 100644
--- a/jdk/test/java/util/Collection/MOAT.java
+++ b/jdk/test/java/util/Collection/MOAT.java
@@ -28,6 +28,8 @@
* 6431845 4802633 6570566 6570575 6570631 6570924 6691185 6691215
* @summary Run many tests on many Collection and Map implementations
* @author Martin Buchholz
+ * @run main MOAT
+ * @run main/othervm -XX:+AggressiveOpts MOAT
*/
/* Mother Of All (Collection) Tests
diff --git a/jdk/test/java/util/Currency/ValidateISO4217.java b/jdk/test/java/util/Currency/ValidateISO4217.java
index c92b06226fe..486741fdd2c 100644
--- a/jdk/test/java/util/Currency/ValidateISO4217.java
+++ b/jdk/test/java/util/Currency/ValidateISO4217.java
@@ -111,57 +111,58 @@ public class ValidateISO4217 {
static void test1() throws Exception {
- FileReader fr = new FileReader(new File(System.getProperty("test.src", "."), datafile));
- BufferedReader in = new BufferedReader(fr);
- String line;
- SimpleDateFormat format = null;
+ try (FileReader fr = new FileReader(new File(System.getProperty("test.src", "."), datafile));
+ BufferedReader in = new BufferedReader(fr))
+ {
+ String line;
+ SimpleDateFormat format = null;
- while ((line = in.readLine()) != null) {
- if (line.length() == 0 || line.charAt(0) == '#') {
- continue;
- }
+ while ((line = in.readLine()) != null) {
+ if (line.length() == 0 || line.charAt(0) == '#') {
+ continue;
+ }
- StringTokenizer tokens = new StringTokenizer(line, "\t");
- String country = tokens.nextToken();
- if (country.length() != 2) {
- continue;
- }
+ StringTokenizer tokens = new StringTokenizer(line, "\t");
+ String country = tokens.nextToken();
+ if (country.length() != 2) {
+ continue;
+ }
- String currency;
- String numeric;
- String minorUnit;
- int tokensCount = tokens.countTokens();
- if (tokensCount < 3) {
- currency = "";
- numeric = "0";
- minorUnit = "0";
- } else {
- currency = tokens.nextToken();
- numeric = tokens.nextToken();
- minorUnit = tokens.nextToken();
- testCurrencies.add(Currency.getInstance(currency));
+ String currency;
+ String numeric;
+ String minorUnit;
+ int tokensCount = tokens.countTokens();
+ if (tokensCount < 3) {
+ currency = "";
+ numeric = "0";
+ minorUnit = "0";
+ } else {
+ currency = tokens.nextToken();
+ numeric = tokens.nextToken();
+ minorUnit = tokens.nextToken();
+ testCurrencies.add(Currency.getInstance(currency));
- // check for the cutover
- if (tokensCount > 3) {
- if (format == null) {
- format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
- format.setTimeZone(TimeZone.getTimeZone("GMT"));
- format.setLenient(false);
- }
- if (format.parse(tokens.nextToken()).getTime() <
- System.currentTimeMillis()) {
- currency = tokens.nextToken();
- numeric = tokens.nextToken();
- minorUnit = tokens.nextToken();
- testCurrencies.add(Currency.getInstance(currency));
+ // check for the cutover
+ if (tokensCount > 3) {
+ if (format == null) {
+ format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
+ format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ format.setLenient(false);
+ }
+ if (format.parse(tokens.nextToken()).getTime() <
+ System.currentTimeMillis()) {
+ currency = tokens.nextToken();
+ numeric = tokens.nextToken();
+ minorUnit = tokens.nextToken();
+ testCurrencies.add(Currency.getInstance(currency));
+ }
}
}
+ int index = toIndex(country);
+ testCountryCurrency(country, currency, Integer.parseInt(numeric),
+ Integer.parseInt(minorUnit), index);
}
- int index = toIndex(country);
- testCountryCurrency(country, currency, Integer.parseInt(numeric),
- Integer.parseInt(minorUnit), index);
}
- in.close();
for (int i = 0; i < additionalCodes.length; i++) {
int index = toIndex(additionalCodes[i][0]);
diff --git a/jdk/test/java/util/Formatter/FailingConstructors.java b/jdk/test/java/util/Formatter/FailingConstructors.java
index 8ef99f146a4..29e34bc179e 100644
--- a/jdk/test/java/util/Formatter/FailingConstructors.java
+++ b/jdk/test/java/util/Formatter/FailingConstructors.java
@@ -34,6 +34,7 @@ import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
+import java.nio.file.Files;
import java.util.Formatter;
public class FailingConstructors {
@@ -47,9 +48,7 @@ public class FailingConstructors {
/* create the file and write its contents */
File file = File.createTempFile(fileName, null);
file.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(FILE_CONTENTS.getBytes());
- fos.close();
+ Files.write(file.toPath(), FILE_CONTENTS.getBytes());
test(true, file);
file.delete();
diff --git a/jdk/test/java/util/Locale/LocaleEnhanceTest.java b/jdk/test/java/util/Locale/LocaleEnhanceTest.java
index 5d816bc2eee..0ee6ed24dca 100644
--- a/jdk/test/java/util/Locale/LocaleEnhanceTest.java
+++ b/jdk/test/java/util/Locale/LocaleEnhanceTest.java
@@ -1204,14 +1204,12 @@ public class LocaleEnhanceTest extends LocaleTestFmwk {
locale = new Locale(lang, country, variant);
}
- // desrialize
- try {
- FileInputStream fis = new FileInputStream(testfile);
- ObjectInputStream ois = new ObjectInputStream(fis);
-
+ // deserialize
+ try (FileInputStream fis = new FileInputStream(testfile);
+ ObjectInputStream ois = new ObjectInputStream(fis))
+ {
Object o = ois.readObject();
assertEquals("Deserialize Java 6 Locale " + locale, o, locale);
- ois.close();
} catch (Exception e) {
errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage());
}
diff --git a/jdk/test/java/util/ResourceBundle/Bug6204853.java b/jdk/test/java/util/ResourceBundle/Bug6204853.java
index ca13fa65015..4ba5386c8e5 100644
--- a/jdk/test/java/util/ResourceBundle/Bug6204853.java
+++ b/jdk/test/java/util/ResourceBundle/Bug6204853.java
@@ -39,24 +39,19 @@ import java.util.PropertyResourceBundle;
public final class Bug6204853 {
public Bug6204853() {
- try {
- String srcDir = System.getProperty("test.src", ".");
- FileInputStream fis8859_1 =
- new FileInputStream(new File(srcDir, "Bug6204853.properties"));
- FileInputStream fisUtf8 =
- new FileInputStream(new File(srcDir, "Bug6204853_Utf8.properties"));
- InputStreamReader isrUtf8 = new InputStreamReader(fisUtf8, "UTF-8");
-
+ String srcDir = System.getProperty("test.src", ".");
+ try (FileInputStream fis8859_1 =
+ new FileInputStream(new File(srcDir, "Bug6204853.properties"));
+ FileInputStream fisUtf8 =
+ new FileInputStream(new File(srcDir, "Bug6204853_Utf8.properties"));
+ InputStreamReader isrUtf8 = new InputStreamReader(fisUtf8, "UTF-8"))
+ {
PropertyResourceBundle bundleUtf8 = new PropertyResourceBundle(isrUtf8);
PropertyResourceBundle bundle = new PropertyResourceBundle(fis8859_1);
String[] arrayUtf8 = createKeyValueArray(bundleUtf8);
String[] array = createKeyValueArray(bundle);
- isrUtf8.close();
- fisUtf8.close();
- fis8859_1.close();
-
if (!Arrays.equals(arrayUtf8, array)) {
throw new RuntimeException("PropertyResourceBundle constructed from a UTF-8 encoded property file is not equal to the one constructed from ISO-8859-1 encoded property file.");
}
diff --git a/jdk/test/java/util/Scanner/FailingConstructors.java b/jdk/test/java/util/Scanner/FailingConstructors.java
index 476c000ae1a..d74f5c79cc4 100644
--- a/jdk/test/java/util/Scanner/FailingConstructors.java
+++ b/jdk/test/java/util/Scanner/FailingConstructors.java
@@ -33,6 +33,7 @@ import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.nio.file.Files;
import java.util.Scanner;
public class FailingConstructors {
@@ -46,9 +47,7 @@ public class FailingConstructors {
/* create the file and write its contents */
File file = File.createTempFile(fileName, null);
file.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(FILE_CONTENTS.getBytes());
- fos.close();
+ Files.write(file.toPath(), FILE_CONTENTS.getBytes());
test(true, file);
file.delete();
diff --git a/jdk/test/java/util/jar/JarEntry/GetMethodsReturnClones.java b/jdk/test/java/util/jar/JarEntry/GetMethodsReturnClones.java
index ea9accf763d..dfbeeee0a80 100644
--- a/jdk/test/java/util/jar/JarEntry/GetMethodsReturnClones.java
+++ b/jdk/test/java/util/jar/JarEntry/GetMethodsReturnClones.java
@@ -40,22 +40,21 @@ public class GetMethodsReturnClones {
System.getProperty("file.separator");
public static void main(String[] args) throws Exception {
- JarFile jf = new JarFile(BASE + "test.jar", true);
-
- byte[] buffer = new byte[8192];
- Enumeration e = jf.entries();
- List entries = new ArrayList();
- while (e.hasMoreElements()) {
- JarEntry je = e.nextElement();
- entries.add(je);
- InputStream is = jf.getInputStream(je);
- while (is.read(buffer, 0, buffer.length) != -1) {
- // we just read. this will throw a SecurityException
- // if a signature/digest check fails.
+ List entries = new ArrayList<>();
+ try (JarFile jf = new JarFile(BASE + "test.jar", true)) {
+ byte[] buffer = new byte[8192];
+ Enumeration e = jf.entries();
+ while (e.hasMoreElements()) {
+ JarEntry je = e.nextElement();
+ entries.add(je);
+ try (InputStream is = jf.getInputStream(je)) {
+ while (is.read(buffer, 0, buffer.length) != -1) {
+ // we just read. this will throw a SecurityException
+ // if a signature/digest check fails.
+ }
+ }
}
- is.close();
}
- jf.close();
for (JarEntry je : entries) {
Certificate[] certs = je.getCertificates();
diff --git a/jdk/test/java/util/jar/JarFile/ScanSignedJar.java b/jdk/test/java/util/jar/JarFile/ScanSignedJar.java
index 63576a13924..b13a2313418 100644
--- a/jdk/test/java/util/jar/JarFile/ScanSignedJar.java
+++ b/jdk/test/java/util/jar/JarFile/ScanSignedJar.java
@@ -37,25 +37,25 @@ import java.util.jar.*;
public class ScanSignedJar {
public static void main(String[] args) throws Exception {
- JarFile file = new JarFile(new File(System.getProperty("test.src","."),
- "bogus-signerinfo-attr.jar"));
- byte[] buffer = new byte[8192];
boolean isSigned = false;
+ try (JarFile file = new JarFile(new File(System.getProperty("test.src","."),
+ "bogus-signerinfo-attr.jar"))) {
+ byte[] buffer = new byte[8192];
- for (Enumeration entries = file.entries(); entries.hasMoreElements();) {
- JarEntry entry = (JarEntry) entries.nextElement();
- InputStream jis = file.getInputStream(entry);
- while (jis.read(buffer, 0, buffer.length) != -1) {
- // read the jar entry
+ for (Enumeration entries = file.entries(); entries.hasMoreElements();) {
+ JarEntry entry = (JarEntry) entries.nextElement();
+ try (InputStream jis = file.getInputStream(entry)) {
+ while (jis.read(buffer, 0, buffer.length) != -1) {
+ // read the jar entry
+ }
+ }
+ if (entry.getCertificates() != null) {
+ isSigned = true;
+ }
+ System.out.println((isSigned ? "[signed] " : "\t ") +
+ entry.getName());
}
- jis.close();
- if (entry.getCertificates() != null) {
- isSigned = true;
- }
- System.out.println((isSigned ? "[signed] " : "\t ") +
- entry.getName());
}
- file.close();
if (isSigned) {
System.out.println("\nJAR file has signed entries");
diff --git a/jdk/test/java/util/zip/Available.java b/jdk/test/java/util/zip/Available.java
index 836d139fad7..2a78bd0d8e8 100644
--- a/jdk/test/java/util/zip/Available.java
+++ b/jdk/test/java/util/zip/Available.java
@@ -44,14 +44,17 @@ public class Available {
File f = new File(System.getProperty("test.src", "."), "input.jar");
// test ZipInputStream
- ZipInputStream z = new ZipInputStream(new FileInputStream(f));
- z.getNextEntry();
- tryAvail(z);
+ try (FileInputStream fis = new FileInputStream(f);
+ ZipInputStream z = new ZipInputStream(fis))
+ {
+ z.getNextEntry();
+ tryAvail(z);
+ }
// test InflaterInputStream
- ZipFile zfile = new ZipFile(f);
- tryAvail(zfile.getInputStream(zfile.getEntry("Available.java")));
- z.close();
+ try (ZipFile zfile = new ZipFile(f)) {
+ tryAvail(zfile.getInputStream(zfile.getEntry("Available.java")));
+ }
}
static void tryAvail(InputStream in) throws Exception {
@@ -67,20 +70,21 @@ public class Available {
// To reproduce 4401122
private static void test2() throws Exception {
File f = new File(System.getProperty("test.src", "."), "input.jar");
- ZipFile zf = new ZipFile(f);
- InputStream in = zf.getInputStream(zf.getEntry("Available.java"));
+ try (ZipFile zf = new ZipFile(f)) {
+ InputStream in = zf.getInputStream(zf.getEntry("Available.java"));
- int initialAvailable = in.available();
- in.read();
- if (in.available() != initialAvailable - 1)
- throw new RuntimeException("Available not decremented.");
- for(int j=0; j 0)
throw new Exception("Unexpected NON-EOF");
- s.close();
} catch (Throwable t) { trouble = t; }}};
compressor.start(); uncompressor.start();
diff --git a/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java b/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java
index 4377554e9c8..6eac7489872 100644
--- a/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java
+++ b/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java
@@ -44,9 +44,9 @@ public class GZIPInputStreamRead {
rnd.nextBytes(src);
srcBAOS.write(src);
- GZIPOutputStream gzos = new GZIPOutputStream(dstBAOS);
- gzos.write(src);
- gzos.close();
+ try (GZIPOutputStream gzos = new GZIPOutputStream(dstBAOS)) {
+ gzos.write(src);
+ }
}
byte[] srcBytes = srcBAOS.toByteArray();
byte[] dstBytes = dstBAOS.toByteArray();
@@ -75,26 +75,26 @@ public class GZIPInputStreamRead {
int readBufSize, int gzisBufSize)
throws Throwable
{
- GZIPInputStream gzis = new GZIPInputStream(
- new ByteArrayInputStream(dst),
- gzisBufSize);
- byte[] result = new byte[src.length + 10];
- byte[] buf = new byte[readBufSize];
- int n = 0;
- int off = 0;
+ try (ByteArrayInputStream bais = new ByteArrayInputStream(dst);
+ GZIPInputStream gzis = new GZIPInputStream(bais, gzisBufSize))
+ {
+ byte[] result = new byte[src.length + 10];
+ byte[] buf = new byte[readBufSize];
+ int n = 0;
+ int off = 0;
- while ((n = gzis.read(buf, 0, buf.length)) != -1) {
- System.arraycopy(buf, 0, result, off, n);
- off += n;
- // no range check, if overflow, let it fail
+ while ((n = gzis.read(buf, 0, buf.length)) != -1) {
+ System.arraycopy(buf, 0, result, off, n);
+ off += n;
+ // no range check, if overflow, let it fail
+ }
+ if (off != src.length || gzis.available() != 0 ||
+ !Arrays.equals(src, Arrays.copyOf(result, off))) {
+ throw new RuntimeException(
+ "GZIPInputStream reading failed! " +
+ ", src.len=" + src.length +
+ ", read=" + off);
+ }
}
- if (off != src.length || gzis.available() != 0 ||
- !Arrays.equals(src, Arrays.copyOf(result, off))) {
- throw new RuntimeException(
- "GZIPInputStream reading failed! " +
- ", src.len=" + src.length +
- ", read=" + off);
- }
- gzis.close();
}
}
diff --git a/jdk/test/java/util/zip/InflateIn_DeflateOut.java b/jdk/test/java/util/zip/InflateIn_DeflateOut.java
index 41ff618a0e0..1e4ef2bd073 100644
--- a/jdk/test/java/util/zip/InflateIn_DeflateOut.java
+++ b/jdk/test/java/util/zip/InflateIn_DeflateOut.java
@@ -134,14 +134,14 @@ public class InflateIn_DeflateOut {
PairedOutputStream pos = new PairedOutputStream(pis);
pis.setPairedOutputStream(pos);
- DeflaterOutputStream dos = new DeflaterOutputStream(pos, true);
byte[] data = new byte[random.nextInt(1024 * 1024)];
byte[] buf = new byte[data.length];
random.nextBytes(data);
- dos.write(data);
- dos.close();
+ try (DeflaterOutputStream dos = new DeflaterOutputStream(pos, true)) {
+ dos.write(data);
+ }
check(readFully(iis, buf, buf.length));
check(Arrays.equals(data, buf));
}
diff --git a/jdk/test/java/util/zip/InfoZip.java b/jdk/test/java/util/zip/InfoZip.java
index aea1d32dcdf..c7abba251ef 100644
--- a/jdk/test/java/util/zip/InfoZip.java
+++ b/jdk/test/java/util/zip/InfoZip.java
@@ -85,41 +85,37 @@ public class InfoZip {
//----------------------------------------------------------------
File f = new File("InfoZip.zip");
- OutputStream os = new FileOutputStream(f);
- os.write(new byte[]
- {'P', 'K', 3, 4, 10, 0, 0, 0, 0, 0, -68, 8, 'k',
- '2', 'V', -7, 'm', 9, 20, 0, 0, 0, 20, 0, 0, 0,
- 8, 0, 21, 0, 's', 'o', 'm', 'e', 'F', 'i', 'l', 'e', 'U',
- 'T', 9, 0, 3, 't', '_', '1', 'B', 't', '_', '1', 'B', 'U',
- 'x', 4, 0, -14, 'v', 26, 4, 'M', 'e', 's', 's', 'a', 'g',
- 'e', ' ', 'i', 'n', ' ', 'a', ' ', 'B', 'o', 't', 't', 'l', 'e',
- 10, 'P', 'K', 1, 2, 23, 3, 10, 0, 0, 0, 0, 0,
- -68, 8, 'k', '2', 'V', -7, 'm', 9, 20, 0, 0, 0, 20,
- 0, 0, 0, 8, 0, 13, 0, 0, 0, 0, 0, 1, 0,
- 0, 0, -92, -127, 0, 0, 0, 0, 's', 'o', 'm', 'e', 'F',
- 'i', 'l', 'e', 'U', 'T', 5, 0, 3, 't', '_', '1', 'B', 'U',
- 'x', 0, 0, 'P', 'K', 5, 6, 0, 0, 0, 0, 1, 0,
- 1, 0, 'C', 0, 0, 0, 'O', 0, 0, 0, 0, 0, });
- os.close();
+ try (OutputStream os = new FileOutputStream(f)) {
+ os.write(new byte[]
+ {'P', 'K', 3, 4, 10, 0, 0, 0, 0, 0, -68, 8, 'k',
+ '2', 'V', -7, 'm', 9, 20, 0, 0, 0, 20, 0, 0, 0,
+ 8, 0, 21, 0, 's', 'o', 'm', 'e', 'F', 'i', 'l', 'e', 'U',
+ 'T', 9, 0, 3, 't', '_', '1', 'B', 't', '_', '1', 'B', 'U',
+ 'x', 4, 0, -14, 'v', 26, 4, 'M', 'e', 's', 's', 'a', 'g',
+ 'e', ' ', 'i', 'n', ' ', 'a', ' ', 'B', 'o', 't', 't', 'l', 'e',
+ 10, 'P', 'K', 1, 2, 23, 3, 10, 0, 0, 0, 0, 0,
+ -68, 8, 'k', '2', 'V', -7, 'm', 9, 20, 0, 0, 0, 20,
+ 0, 0, 0, 8, 0, 13, 0, 0, 0, 0, 0, 1, 0,
+ 0, 0, -92, -127, 0, 0, 0, 0, 's', 'o', 'm', 'e', 'F',
+ 'i', 'l', 'e', 'U', 'T', 5, 0, 3, 't', '_', '1', 'B', 'U',
+ 'x', 0, 0, 'P', 'K', 5, 6, 0, 0, 0, 0, 1, 0,
+ 1, 0, 'C', 0, 0, 0, 'O', 0, 0, 0, 0, 0, });
+ }
- ZipFile zf = new ZipFile(f);
ZipEntry ze = null;
- try {
+ try (ZipFile zf = new ZipFile(f)) {
Enumeration extends ZipEntry> entries = zf.entries();
ze = entries.nextElement();
check(! entries.hasMoreElements());
checkZipEntry(ze, contents(zf, ze));
- } finally {
- zf.close();
}
- ZipInputStream is = new ZipInputStream(new FileInputStream(f));
- try {
+ try (FileInputStream fis = new FileInputStream(f);
+ ZipInputStream is = new ZipInputStream(fis))
+ {
ze = is.getNextEntry();
checkZipEntry(ze, contents(is));
check(is.getNextEntry() == null);
- } finally {
- is.close();
}
f.delete();
System.out.printf("passed = %d, failed = %d%n", passed, failed);
diff --git a/jdk/test/java/util/zip/LargeZip.java b/jdk/test/java/util/zip/LargeZip.java
index a7754e3a98f..a4f00d23a41 100644
--- a/jdk/test/java/util/zip/LargeZip.java
+++ b/jdk/test/java/util/zip/LargeZip.java
@@ -98,19 +98,21 @@ public class LargeZip {
}
data = baos.toByteArray();
- ZipOutputStream zos = new ZipOutputStream(
- new BufferedOutputStream(new FileOutputStream(largeFile)));
- long length = 0;
- while (length < fileSize) {
- ZipEntry ze = new ZipEntry("entry-" + length);
- lastEntryName = ze.getName();
- zos.putNextEntry(ze);
- zos.write(data, 0, data.length);
- zos.closeEntry();
- length = largeFile.length();
+ try (FileOutputStream fos = new FileOutputStream(largeFile);
+ BufferedOutputStream bos = new BufferedOutputStream(fos);
+ ZipOutputStream zos = new ZipOutputStream(bos))
+ {
+ long length = 0;
+ while (length < fileSize) {
+ ZipEntry ze = new ZipEntry("entry-" + length);
+ lastEntryName = ze.getName();
+ zos.putNextEntry(ze);
+ zos.write(data, 0, data.length);
+ zos.closeEntry();
+ length = largeFile.length();
+ }
+ System.out.println("Last entry written is " + lastEntryName);
}
- System.out.println("Last entry written is " + lastEntryName);
- zos.close();
}
static void readLargeZip1() throws Throwable {
@@ -143,33 +145,35 @@ public class LargeZip {
static void readLargeZip2() throws Throwable {
- ZipInputStream zis = new ZipInputStream(
- new BufferedInputStream(new FileInputStream(largeFile)));
- ZipEntry entry = null;
- String entryName = null;
- int count = 0;
- while ((entry = zis.getNextEntry()) != null) {
- entryName = entry.getName();
- if (entryName.equals(lastEntryName)) {
- break;
+ try (FileInputStream fis = new FileInputStream(largeFile);
+ BufferedInputStream bis = new BufferedInputStream(fis);
+ ZipInputStream zis = new ZipInputStream(bis))
+ {
+ ZipEntry entry = null;
+ String entryName = null;
+ int count = 0;
+ while ((entry = zis.getNextEntry()) != null) {
+ entryName = entry.getName();
+ if (entryName.equals(lastEntryName)) {
+ break;
+ }
+ count++;
}
- count++;
- }
- System.out.println("Number of entries read: " + count);
- System.out.println("Last entry read is " + entryName);
- check(!entry.isDirectory());
+ System.out.println("Number of entries read: " + count);
+ System.out.println("Last entry read is " + entryName);
+ check(!entry.isDirectory());
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte buf[] = new byte[4096];
- int len;
- while ((len = zis.read(buf)) >= 0) {
- baos.write(buf, 0, len);
+ byte buf[] = new byte[4096];
+ int len;
+ while ((len = zis.read(buf)) >= 0) {
+ baos.write(buf, 0, len);
+ }
+ baos.close();
+ check(Arrays.equals(data, baos.toByteArray()));
+ check(zis.getNextEntry() == null);
}
- baos.close();
- check(Arrays.equals(data, baos.toByteArray()));
- check(zis.getNextEntry() == null);
- zis.close();
}
diff --git a/jdk/test/java/util/zip/TestEmptyZip.java b/jdk/test/java/util/zip/TestEmptyZip.java
index 44cf59cad6b..ff4406c976c 100644
--- a/jdk/test/java/util/zip/TestEmptyZip.java
+++ b/jdk/test/java/util/zip/TestEmptyZip.java
@@ -78,67 +78,49 @@ public class TestEmptyZip {
pass();
}
}
- ZipInputStream zis = null;
- try {
- zis = new ZipInputStream(new FileInputStream(f));
+ try (FileInputStream fis = new FileInputStream(f);
+ ZipInputStream zis = new ZipInputStream(fis))
+ {
ZipEntry ze = zis.getNextEntry();
check(ze == null);
} catch (IOException ex) {
unexpected(ex);
- } finally {
- if (zis != null) zis.close();
}
}
static void write(File f) throws Exception {
- ZipOutputStream zos = null;
- try {
- zos = new ZipOutputStream(new FileOutputStream(f));
+ try (FileOutputStream fis = new FileOutputStream(f);
+ ZipOutputStream zos = new ZipOutputStream(fis))
+ {
zos.finish();
- zos.close();
pass();
} catch (Exception ex) {
unexpected(ex);
- } finally {
- if (zos != null) {
- zos.close();
- }
}
}
static void readFile(File f) throws Exception {
- ZipFile zf = null;
- try {
- zf = new ZipFile(f);
+ try (ZipFile zf = new ZipFile(f)) {
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
fail();
}
- zf.close();
pass();
} catch (Exception ex) {
unexpected(ex);
- } finally {
- if (zf != null) {
- zf.close();
- }
}
}
static void readStream(File f) throws Exception {
- ZipInputStream zis = null;
- try {
- zis = new ZipInputStream(new FileInputStream(f));
+ try (FileInputStream fis = new FileInputStream(f);
+ ZipInputStream zis = new ZipInputStream(fis))
+ {
ZipEntry ze = zis.getNextEntry();
check(ze == null);
byte[] buf = new byte[1024];
check(zis.read(buf, 0, 1024) == -1);
- } finally {
- if (zis != null) {
- zis.close();
- }
}
}
diff --git a/jdk/test/java/util/zip/ZipCoding.java b/jdk/test/java/util/zip/ZipCoding.java
index c65d1ac333c..a21a8f2b31f 100644
--- a/jdk/test/java/util/zip/ZipCoding.java
+++ b/jdk/test/java/util/zip/ZipCoding.java
@@ -57,59 +57,58 @@ public class ZipCoding {
String name, String comment, byte[] bb)
throws Exception
{
- ZipInputStream zis = new ZipInputStream(is, cs);
- ZipEntry e = zis.getNextEntry();
- if (e == null || ! name.equals(e.getName()))
- throw new RuntimeException("ZipIS name doesn't match!");
- byte[] bBuf = new byte[bb.length << 1];
- int n = zis.read(bBuf, 0, bBuf.length);
- if (n != bb.length ||
- !Arrays.equals(bb, Arrays.copyOf(bBuf, n))) {
- throw new RuntimeException("ZipIS content doesn't match!");
+ try (ZipInputStream zis = new ZipInputStream(is, cs)) {
+ ZipEntry e = zis.getNextEntry();
+ if (e == null || ! name.equals(e.getName()))
+ throw new RuntimeException("ZipIS name doesn't match!");
+ byte[] bBuf = new byte[bb.length << 1];
+ int n = zis.read(bBuf, 0, bBuf.length);
+ if (n != bb.length ||
+ !Arrays.equals(bb, Arrays.copyOf(bBuf, n))) {
+ throw new RuntimeException("ZipIS content doesn't match!");
+ }
}
- zis.close();
}
static void testZipFile(File f, Charset cs,
String name, String comment, byte[] bb)
throws Exception
{
- ZipFile zf = new ZipFile(f, cs);
- Enumeration extends ZipEntry> zes = zf.entries();
- ZipEntry e = (ZipEntry)zes.nextElement();
- if (! name.equals(e.getName()) ||
- ! comment.equals(e.getComment()))
- throw new RuntimeException("ZipFile: name/comment doesn't match!");
- InputStream is = zf.getInputStream(e);
- if (is == null)
- throw new RuntimeException("ZipFile: getIS failed!");
- byte[] bBuf = new byte[bb.length << 1];
- int n = 0;
- int nn =0;
- while ((nn = is.read(bBuf, n, bBuf.length-n)) != -1) {
- n += nn;
+ try (ZipFile zf = new ZipFile(f, cs)) {
+ Enumeration extends ZipEntry> zes = zf.entries();
+ ZipEntry e = (ZipEntry)zes.nextElement();
+ if (! name.equals(e.getName()) ||
+ ! comment.equals(e.getComment()))
+ throw new RuntimeException("ZipFile: name/comment doesn't match!");
+ InputStream is = zf.getInputStream(e);
+ if (is == null)
+ throw new RuntimeException("ZipFile: getIS failed!");
+ byte[] bBuf = new byte[bb.length << 1];
+ int n = 0;
+ int nn =0;
+ while ((nn = is.read(bBuf, n, bBuf.length-n)) != -1) {
+ n += nn;
+ }
+ if (n != bb.length ||
+ !Arrays.equals(bb, Arrays.copyOf(bBuf, n))) {
+ throw new RuntimeException("ZipFile content doesn't match!");
+ }
}
- if (n != bb.length ||
- !Arrays.equals(bb, Arrays.copyOf(bBuf, n))) {
- throw new RuntimeException("ZipFile content doesn't match!");
- }
- zf.close();
}
static void test(String csn, String name, String comment)
throws Exception
{
- byte[] bb = "This is the conent of the zipfile".getBytes("ISO-8859-1");
+ byte[] bb = "This is the content of the zipfile".getBytes("ISO-8859-1");
Charset cs = Charset.forName(csn);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ZipOutputStream zos = new ZipOutputStream(baos, cs);
-
- ZipEntry e = new ZipEntry(name);
- e.setComment(comment);
- zos.putNextEntry(e);
- zos.write(bb, 0, bb.length);
- zos.closeEntry();
- zos.close();
+ try (ZipOutputStream zos = new ZipOutputStream(baos, cs)) {
+ ZipEntry e = new ZipEntry(name);
+ e.setComment(comment);
+ zos.putNextEntry(e);
+ zos.write(bb, 0, bb.length);
+ zos.closeEntry();
+ }
ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
testZipInputStream(bis, cs, name, comment, bb);
@@ -121,9 +120,9 @@ public class ZipCoding {
File f = new File(new File(System.getProperty("test.dir", ".")),
"zfcoding.zip");
- FileOutputStream fos = new FileOutputStream(f);
- baos.writeTo(fos);
- fos.close();
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ baos.writeTo(fos);
+ }
testZipFile(f, cs, name, comment, bb);
if ("utf-8".equals(csn)) {
testZipFile(f, Charset.forName("MS932"), name, comment, bb);
diff --git a/jdk/test/java/util/zip/ZipFile/Assortment.java b/jdk/test/java/util/zip/ZipFile/Assortment.java
index 0605e2e3e13..bb0d9fa8eb4 100644
--- a/jdk/test/java/util/zip/ZipFile/Assortment.java
+++ b/jdk/test/java/util/zip/ZipFile/Assortment.java
@@ -201,13 +201,12 @@ public class Assortment {
//----------------------------------------------------------------
// Write zip file using ZipOutputStream
//----------------------------------------------------------------
- ZipOutputStream zos = new ZipOutputStream(
- new FileOutputStream(zipName));
-
- for (Entry e : entries)
- e.write(zos);
-
- zos.close();
+ try (FileOutputStream fos = new FileOutputStream(zipName);
+ ZipOutputStream zos = new ZipOutputStream(fos))
+ {
+ for (Entry e : entries)
+ e.write(zos);
+ }
//----------------------------------------------------------------
// Verify zip file contents using JarFile class
diff --git a/jdk/test/java/util/zip/ZipFile/Comment.java b/jdk/test/java/util/zip/ZipFile/Comment.java
index d48cef20856..61a02521caa 100644
--- a/jdk/test/java/util/zip/ZipFile/Comment.java
+++ b/jdk/test/java/util/zip/ZipFile/Comment.java
@@ -57,16 +57,15 @@ public class Comment {
private static void writeZipFile(String name, String comment)
throws IOException
{
- ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(name));
- try {
+ try (FileOutputStream fos = new FileOutputStream(name);
+ ZipOutputStream zos = new ZipOutputStream(fos))
+ {
zos.setComment(comment);
ZipEntry ze = new ZipEntry(entryName);
ze.setMethod(ZipEntry.DEFLATED);
zos.putNextEntry(ze);
new DataOutputStream(zos).writeUTF(entryContents);
zos.closeEntry();
- } finally {
- zos.close();
}
}
@@ -74,30 +73,30 @@ public class Comment {
throws Exception
{
// Check that Zip entry was correctly written.
- ZipFile zipFile = new ZipFile(name);
- ZipEntry zipEntry = zipFile.getEntry(entryName);
- InputStream is = zipFile.getInputStream(zipEntry);
- String result = new DataInputStream(is).readUTF();
- if (!result.equals(entryContents))
- throw new Exception("Entry contents corrupted");
+ try (ZipFile zipFile = new ZipFile(name)) {
+ ZipEntry zipEntry = zipFile.getEntry(entryName);
+ InputStream is = zipFile.getInputStream(zipEntry);
+ String result = new DataInputStream(is).readUTF();
+ if (!result.equals(entryContents))
+ throw new Exception("Entry contents corrupted");
+ }
- // Check that comment length was correctly written.
- RandomAccessFile file = new RandomAccessFile(name, "r");
- file.seek(file.length() - comment.length()
- - ZipFile.ENDHDR + ZipFile.ENDCOM);
- int b1 = file.readUnsignedByte();
- int b2 = file.readUnsignedByte();
- if (b1 + (b2 << 8) != comment.length())
- throw new Exception("Zip file comment length corrupted");
+ try (RandomAccessFile file = new RandomAccessFile(name, "r")) {
+ // Check that comment length was correctly written.
+ file.seek(file.length() - comment.length()
+ - ZipFile.ENDHDR + ZipFile.ENDCOM);
+ int b1 = file.readUnsignedByte();
+ int b2 = file.readUnsignedByte();
+ if (b1 + (b2 << 8) != comment.length())
+ throw new Exception("Zip file comment length corrupted");
- // Check that comment was correctly written.
- file.seek(file.length() - comment.length());
- byte [] bytes = new byte [comment.length()];
- file.readFully(bytes);
- zipFile.close();
- file.close();
- if (! comment.equals(new String(bytes, "UTF8")))
- throw new Exception("Zip file comment corrupted");
+ // Check that comment was correctly written.
+ file.seek(file.length() - comment.length());
+ byte [] bytes = new byte [comment.length()];
+ file.readFully(bytes);
+ if (! comment.equals(new String(bytes, "UTF8")))
+ throw new Exception("Zip file comment corrupted");
+ }
}
private static String buildComment(int length) {
diff --git a/jdk/test/java/util/zip/ZipFile/CopyJar.java b/jdk/test/java/util/zip/ZipFile/CopyJar.java
index be88b3dd366..217fd730531 100644
--- a/jdk/test/java/util/zip/ZipFile/CopyJar.java
+++ b/jdk/test/java/util/zip/ZipFile/CopyJar.java
@@ -31,18 +31,18 @@ import java.util.zip.*;
public class CopyJar {
public static void main(String args[]) throws Exception {
- ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
- "input.jar"));
- ZipEntry ze = zf.getEntry("ReleaseInflater.java");
- ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream());
- InputStream in = zf.getInputStream(ze);
- byte[] b = new byte[128];
- int n;
- zos.putNextEntry(ze);
- while((n = in.read(b)) != -1) {
- zos.write(b, 0, n);
+ try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
+ "input.jar"))) {
+ ZipEntry ze = zf.getEntry("ReleaseInflater.java");
+ ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream());
+ InputStream in = zf.getInputStream(ze);
+ byte[] b = new byte[128];
+ int n;
+ zos.putNextEntry(ze);
+ while((n = in.read(b)) != -1) {
+ zos.write(b, 0, n);
+ }
+ zos.close();
}
- zos.close();
- zf.close();
}
}
diff --git a/jdk/test/java/util/zip/ZipFile/CorruptedZipFiles.java b/jdk/test/java/util/zip/ZipFile/CorruptedZipFiles.java
index a53fdbee9e9..51d17508fb8 100644
--- a/jdk/test/java/util/zip/ZipFile/CorruptedZipFiles.java
+++ b/jdk/test/java/util/zip/ZipFile/CorruptedZipFiles.java
@@ -47,21 +47,19 @@ public class CorruptedZipFiles {
}
public static void main(String[] args) throws Exception {
- ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("x.zip"));
- try {
+ try (FileOutputStream fos = new FileOutputStream("x.zip");
+ ZipOutputStream zos = new ZipOutputStream(fos))
+ {
ZipEntry e = new ZipEntry("x");
zos.putNextEntry(e);
zos.write((int)'x');
- } finally {
- zos.close();
}
int len = (int)(new File("x.zip").length());
byte[] good = new byte[len];
- FileInputStream fis = new FileInputStream("x.zip");
- fis.read(good);
- fis.close();
- fis = null;
+ try (FileInputStream fis = new FileInputStream("x.zip")) {
+ fis.read(good);
+ }
new File("x.zip").delete();
int endpos = len - ENDHDR;
@@ -150,17 +148,14 @@ public class CorruptedZipFiles {
boolean getInputStream) {
String zipName = "bad" + (uniquifier++) + ".zip";
try {
- FileOutputStream fos = new FileOutputStream(zipName);
- fos.write(data);
- fos.close();
- ZipFile zf = new ZipFile(zipName);
- try {
+ try (FileOutputStream fos = new FileOutputStream(zipName)) {
+ fos.write(data);
+ }
+ try (ZipFile zf = new ZipFile(zipName)) {
if (getInputStream) {
InputStream is = zf.getInputStream(new ZipEntry("x"));
is.read();
}
- } finally {
- zf.close();
}
fail("Failed to throw expected ZipException");
} catch (ZipException e) {
@@ -170,8 +165,7 @@ public class CorruptedZipFiles {
unexpected(e);
} catch (Throwable t) {
unexpected(t);
- }
- finally {
+ } finally {
new File(zipName).delete();
}
}
diff --git a/jdk/test/java/util/zip/ZipFile/DeleteTempJar.java b/jdk/test/java/util/zip/ZipFile/DeleteTempJar.java
index f5e79b30bf7..9d504cb7e92 100644
--- a/jdk/test/java/util/zip/ZipFile/DeleteTempJar.java
+++ b/jdk/test/java/util/zip/ZipFile/DeleteTempJar.java
@@ -53,34 +53,34 @@ public class DeleteTempJar
{
final File zf = File.createTempFile("deletetemp", ".jar");
zf.deleteOnExit();
- JarOutputStream jos = new JarOutputStream(
- new FileOutputStream(zf));
- JarEntry je = new JarEntry("entry");
- jos.putNextEntry(je);
- jos.write("hello, world".getBytes("ASCII"));
- jos.close();
+ try (FileOutputStream fos = new FileOutputStream(zf);
+ JarOutputStream jos = new JarOutputStream(fos))
+ {
+ JarEntry je = new JarEntry("entry");
+ jos.putNextEntry(je);
+ jos.write("hello, world".getBytes("ASCII"));
+ }
HttpServer server = HttpServer.create(
new InetSocketAddress((InetAddress) null, 0), 0);
HttpContext context = server.createContext("/",
new HttpHandler() {
public void handle(HttpExchange e) {
- try {
- FileInputStream fis = new FileInputStream(zf);
- e.sendResponseHeaders(200, zf.length());
- OutputStream os = e.getResponseBody();
- byte[] buf = new byte[1024];
- int count = 0;
- while ((count = fis.read(buf)) != -1) {
- os.write(buf, 0, count);
+ try (FileInputStream fis = new FileInputStream(zf)) {
+ e.sendResponseHeaders(200, zf.length());
+ OutputStream os = e.getResponseBody();
+ byte[] buf = new byte[1024];
+ int count = 0;
+ while ((count = fis.read(buf)) != -1) {
+ os.write(buf, 0, count);
+ }
+ } catch (Exception ex) {
+ unexpected(ex);
+ } finally {
+ e.close();
}
- fis.close();
- e.close();
- } catch (Exception ex) {
- unexpected(ex);
}
- }
- });
+ });
server.start();
URL url = new URL("jar:http://localhost:"
diff --git a/jdk/test/java/util/zip/ZipFile/EnumAfterClose.java b/jdk/test/java/util/zip/ZipFile/EnumAfterClose.java
index 6f4d3d09a9e..5d112dea12e 100644
--- a/jdk/test/java/util/zip/ZipFile/EnumAfterClose.java
+++ b/jdk/test/java/util/zip/ZipFile/EnumAfterClose.java
@@ -33,10 +33,12 @@ import java.util.Enumeration;
public class EnumAfterClose {
public static void main(String args[]) throws Exception {
- ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
- "input.zip"));
- Enumeration e = zf.entries();
- zf.close();
+ Enumeration e;
+ try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
+ "input.zip"))) {
+ e = zf.entries();
+ }
+ // ensure that the ZipFile is closed before checking the Enumeration
try {
if (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry)e.nextElement();
diff --git a/jdk/test/java/util/zip/ZipFile/GetDirEntry.java b/jdk/test/java/util/zip/ZipFile/GetDirEntry.java
index 7d87f9dbbc5..0b2af4ffe28 100644
--- a/jdk/test/java/util/zip/ZipFile/GetDirEntry.java
+++ b/jdk/test/java/util/zip/ZipFile/GetDirEntry.java
@@ -32,12 +32,12 @@ import java.util.zip.*;
public class GetDirEntry {
public static void main(String args[]) throws Exception {
- ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
- "input.jar"));
- ZipEntry ze = zf.getEntry("META-INF");
- if (ze == null) {
- throw new Exception("failed to find a directory entry");
+ try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
+ "input.jar"))) {
+ ZipEntry ze = zf.getEntry("META-INF");
+ if (ze == null) {
+ throw new Exception("failed to find a directory entry");
+ }
}
- zf.close();
}
}
diff --git a/jdk/test/java/util/zip/ZipFile/LargeZipFile.java b/jdk/test/java/util/zip/ZipFile/LargeZipFile.java
index 6e1b54456bb..2df4ca75486 100644
--- a/jdk/test/java/util/zip/ZipFile/LargeZipFile.java
+++ b/jdk/test/java/util/zip/ZipFile/LargeZipFile.java
@@ -93,51 +93,50 @@ public class LargeZipFile {
baos.write(bb.array(), 0, DATA_SIZE);
}
data = baos.toByteArray();
-
- ZipOutputStream zos = new ZipOutputStream(
- new BufferedOutputStream(new FileOutputStream(largeFile)));
- long length = 0;
- while (length < fileSize) {
- ZipEntry ze = new ZipEntry("entry-" + length);
- lastEntryName = ze.getName();
- zos.putNextEntry(ze);
- zos.write(data, 0, data.length);
- zos.closeEntry();
- length = largeFile.length();
+ try (FileOutputStream fos = new FileOutputStream(largeFile);
+ BufferedOutputStream bos = new BufferedOutputStream(fos);
+ ZipOutputStream zos = new ZipOutputStream(bos))
+ {
+ long length = 0;
+ while (length < fileSize) {
+ ZipEntry ze = new ZipEntry("entry-" + length);
+ lastEntryName = ze.getName();
+ zos.putNextEntry(ze);
+ zos.write(data, 0, data.length);
+ zos.closeEntry();
+ length = largeFile.length();
+ }
+ System.out.println("Last entry written is " + lastEntryName);
}
- System.out.println("Last entry written is " + lastEntryName);
- zos.close();
}
static void readLargeZip() throws Throwable {
- ZipFile zipFile = new ZipFile(largeFile);
- ZipEntry entry = null;
- String entryName = null;
- int count = 0;
- Enumeration extends ZipEntry> entries = zipFile.entries();
- while (entries.hasMoreElements()) {
- entry = entries.nextElement();
- entryName = entry.getName();
- count++;
- }
- System.out.println("Number of entries read: " + count);
- System.out.println("Last entry read is " + entryName);
- check(!entry.isDirectory());
- if (check(entryName.equals(lastEntryName))) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- InputStream is = zipFile.getInputStream(entry);
- byte buf[] = new byte[4096];
- int len;
- while ((len = is.read(buf)) >= 0) {
- baos.write(buf, 0, len);
+ try (ZipFile zipFile = new ZipFile(largeFile)) {
+ ZipEntry entry = null;
+ String entryName = null;
+ int count = 0;
+ Enumeration extends ZipEntry> entries = zipFile.entries();
+ while (entries.hasMoreElements()) {
+ entry = entries.nextElement();
+ entryName = entry.getName();
+ count++;
+ }
+ System.out.println("Number of entries read: " + count);
+ System.out.println("Last entry read is " + entryName);
+ check(!entry.isDirectory());
+ if (check(entryName.equals(lastEntryName))) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ InputStream is = zipFile.getInputStream(entry);
+ byte buf[] = new byte[4096];
+ int len;
+ while ((len = is.read(buf)) >= 0) {
+ baos.write(buf, 0, len);
+ }
+ baos.close();
+ is.close();
+ check(Arrays.equals(data, baos.toByteArray()));
}
- baos.close();
- is.close();
- check(Arrays.equals(data, baos.toByteArray()));
}
- try {
- zipFile.close();
- } catch (IOException ioe) {/* what can you do */ }
}
//--------------------- Infrastructure ---------------------------
diff --git a/jdk/test/java/util/zip/ZipFile/ManyEntries.java b/jdk/test/java/util/zip/ZipFile/ManyEntries.java
index 4d36e7ac621..df741ad0dce 100644
--- a/jdk/test/java/util/zip/ZipFile/ManyEntries.java
+++ b/jdk/test/java/util/zip/ZipFile/ManyEntries.java
@@ -55,10 +55,10 @@ public class ManyEntries {
File zipFile = new File(++uniquifier + ".zip");
try {
zipFile.delete();
- ZipOutputStream zos = new ZipOutputStream(
- new BufferedOutputStream(
- new FileOutputStream(zipFile)));
- try {
+ try (FileOutputStream fos = new FileOutputStream(zipFile);
+ BufferedOutputStream bos = new BufferedOutputStream(fos);
+ ZipOutputStream zos = new ZipOutputStream(bos))
+ {
for (int i = 0; i < N; i++) {
ZipEntry e = new ZipEntry("DIR/"+i);
e.setMethod(method);
@@ -75,13 +75,9 @@ public class ManyEntries {
zos.putNextEntry(e);
zos.write(i);
}
- } finally {
- zos.close();
- zos = null;
}
- ZipFile zip = zip = new ZipFile(zipFile);
- try {
+ try (ZipFile zip = new ZipFile(zipFile)) {
if (! (zip.size() == N))
throw new Exception("Bad ZipFile size: " + zip.size());
Enumeration entries = zip.entries();
@@ -104,11 +100,8 @@ public class ManyEntries {
}
if (entries.hasMoreElements())
throw new Exception("too many elements");
- } finally {
- zip.close();
}
- }
- finally {
+ } finally {
zipFile.delete();
}
}
diff --git a/jdk/test/java/util/zip/ZipFile/ManyZipFiles.java b/jdk/test/java/util/zip/ZipFile/ManyZipFiles.java
index 1052f6998bd..27f35b77368 100644
--- a/jdk/test/java/util/zip/ZipFile/ManyZipFiles.java
+++ b/jdk/test/java/util/zip/ZipFile/ManyZipFiles.java
@@ -51,14 +51,14 @@ public class ManyZipFiles {
// Create some zip data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ZipOutputStream zos = new ZipOutputStream(baos);
- ZipEntry ze = new ZipEntry("test");
- zos.putNextEntry(ze);
- byte[] hello = "hello, world".getBytes("ASCII");
- zos.write(hello, 0, hello.length);
- zos.closeEntry();
- zos.finish();
- zos.close();
+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {
+ ZipEntry ze = new ZipEntry("test");
+ zos.putNextEntry(ze);
+ byte[] hello = "hello, world".getBytes("ASCII");
+ zos.write(hello, 0, hello.length);
+ zos.closeEntry();
+ zos.finish();
+ }
byte[] data = baos.toByteArray();
ZipFile zips[] = new ZipFile[numFiles];
@@ -90,9 +90,9 @@ public class ManyZipFiles {
for (int i = 0; i < numFiles; i++) {
File f = File.createTempFile("test", ".zip", tmpdir);
f.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(f);
- fos.write(data, 0, data.length);
- fos.close();
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ fos.write(data, 0, data.length);
+ }
try {
zips[i] = new ZipFile(f);
} catch (Throwable t) {
@@ -102,11 +102,12 @@ public class ManyZipFiles {
}
}
} finally {
- // This finally block is due to bug 4171239. On windows, if the
+ // This finally block is due to bug 4171239. On Windows, if the
// file is still open at the end of the VM, deleteOnExit won't
// take place. "new ZipFile(...)" opens the zip file, so we have
- // to explicity close those opened above. This finally block can
- // be removed when 4171239 is fixed.
+ // to explicitly close those opened above. This finally block can
+ // be removed when 4171239 is fixed. See also 6357433, against which
+ // 4171239 was closed as a duplicate.
for (int i = 0; i < numFiles; i++) {
if (zips[i] != null) {
try {
diff --git a/jdk/test/java/util/zip/ZipFile/ReadAfterClose.java b/jdk/test/java/util/zip/ZipFile/ReadAfterClose.java
index 035f8f8c69c..4391db7e9e2 100644
--- a/jdk/test/java/util/zip/ZipFile/ReadAfterClose.java
+++ b/jdk/test/java/util/zip/ZipFile/ReadAfterClose.java
@@ -34,10 +34,13 @@ import java.util.*;
public class ReadAfterClose {
public static void main(String[] argv) throws Exception {
- ZipFile zf = new ZipFile(new File(System.getProperty("test.src","."),"crash.jar"));
- ZipEntry zent = zf.getEntry("Test.java");
- InputStream in = zf.getInputStream(zent);
- zf.close();
+ InputStream in;
+ try (ZipFile zf = new ZipFile(
+ new File(System.getProperty("test.src","."),"crash.jar"))) {
+ ZipEntry zent = zf.getEntry("Test.java");
+ in = zf.getInputStream(zent);
+ }
+ // ensure zf is closed at this point
try {
in.read();
} catch (IOException e) {
diff --git a/jdk/test/java/util/zip/ZipFile/ReadZip.java b/jdk/test/java/util/zip/ZipFile/ReadZip.java
index 9f525c87600..9ee4cccfc75 100644
--- a/jdk/test/java/util/zip/ZipFile/ReadZip.java
+++ b/jdk/test/java/util/zip/ZipFile/ReadZip.java
@@ -27,6 +27,10 @@
*/
import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
import java.util.zip.*;
public class ReadZip {
@@ -38,71 +42,62 @@ public class ReadZip {
}
public static void main(String args[]) throws Exception {
- ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
- "input.zip"));
+ try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."),
+ "input.zip"))) {
+ // Make sure we throw NPE on null objects
+ try { unreached (zf.getEntry(null)); }
+ catch (NullPointerException e) {}
- // Make sure we throw NPE on null objects
- try { unreached (zf.getEntry(null)); }
- catch (NullPointerException e) {}
+ try { unreached (zf.getInputStream(null)); }
+ catch (NullPointerException e) {}
- try { unreached (zf.getInputStream(null)); }
- catch (NullPointerException e) {}
-
- ZipEntry ze = zf.getEntry("ReadZip.java");
- if (ze == null) {
- throw new Exception("cannot read from zip file");
+ ZipEntry ze = zf.getEntry("ReadZip.java");
+ if (ze == null) {
+ throw new Exception("cannot read from zip file");
+ }
}
- zf.close();
// Make sure we can read the zip file that has some garbage
// bytes padded at the end.
- FileInputStream fis = new FileInputStream(
- new File(System.getProperty("test.src", "."),
- "input.zip"));
- File newZip = new File(System.getProperty("test.dir", "."),
- "input2.zip");
- FileOutputStream fos = new FileOutputStream(newZip);
+ File newZip = new File(System.getProperty("test.dir", "."), "input2.zip");
+ Files.copy(Paths.get(System.getProperty("test.src", ""), "input.zip"),
+ newZip.toPath(), StandardCopyOption.REPLACE_EXISTING);
- byte[] buf = new byte[1024];
- int n = 0;
- while ((n = fis.read(buf)) != -1) {
- fos.write(buf, 0, n);
- }
- fis.close();
// pad some bytes
- fos.write(1); fos.write(3); fos.write(5); fos.write(7);
- fos.close();
- try {
- zf = new ZipFile(newZip);
- ze = zf.getEntry("ReadZip.java");
+ try (OutputStream os = Files.newOutputStream(newZip.toPath(),
+ StandardOpenOption.APPEND)) {
+ os.write(1); os.write(3); os.write(5); os.write(7);
+ }
+
+ try (ZipFile zf = new ZipFile(newZip)) {
+ ZipEntry ze = zf.getEntry("ReadZip.java");
if (ze == null) {
throw new Exception("cannot read from zip file");
}
} finally {
- zf.close();
newZip.delete();
}
// Read zip file comment
try {
+ try (FileOutputStream fos = new FileOutputStream(newZip);
+ ZipOutputStream zos = new ZipOutputStream(fos))
+ {
+ ZipEntry ze = new ZipEntry("ZipEntry");
+ zos.putNextEntry(ze);
+ zos.write(1); zos.write(2); zos.write(3); zos.write(4);
+ zos.closeEntry();
+ zos.setComment("This is the comment for testing");
+ }
- ZipOutputStream zos = new ZipOutputStream(
- new FileOutputStream(newZip));
- ze = new ZipEntry("ZipEntry");
- zos.putNextEntry(ze);
- zos.write(1); zos.write(2); zos.write(3); zos.write(4);
- zos.closeEntry();
- zos.setComment("This is the comment for testing");
- zos.close();
-
- zf = new ZipFile(newZip);
- ze = zf.getEntry("ZipEntry");
- if (ze == null)
- throw new Exception("cannot read entry from zip file");
- if (!"This is the comment for testing".equals(zf.getComment()))
- throw new Exception("cannot read comment from zip file");
+ try (ZipFile zf = new ZipFile(newZip)) {
+ ZipEntry ze = zf.getEntry("ZipEntry");
+ if (ze == null)
+ throw new Exception("cannot read entry from zip file");
+ if (!"This is the comment for testing".equals(zf.getComment()))
+ throw new Exception("cannot read comment from zip file");
+ }
} finally {
- zf.close();
newZip.delete();
}
diff --git a/jdk/test/java/util/zip/ZipFile/ShortRead.java b/jdk/test/java/util/zip/ZipFile/ShortRead.java
index b365b9e50b6..e857f7f552a 100644
--- a/jdk/test/java/util/zip/ZipFile/ShortRead.java
+++ b/jdk/test/java/util/zip/ZipFile/ShortRead.java
@@ -38,27 +38,29 @@ public class ShortRead {
try {
final String entryName = "abc";
final String data = "Data disponible";
- final ZipOutputStream zos =
- new ZipOutputStream(new FileOutputStream(zFile));
- zos.putNextEntry(new ZipEntry(entryName));
- zos.write(data.getBytes("ASCII"));
- zos.closeEntry();
- zos.close();
+ try (FileOutputStream fos = new FileOutputStream(zFile);
+ ZipOutputStream zos = new ZipOutputStream(fos))
+ {
+ zos.putNextEntry(new ZipEntry(entryName));
+ zos.write(data.getBytes("ASCII"));
+ zos.closeEntry();
+ }
- final ZipFile zipFile = new ZipFile(zFile);
- final ZipEntry zentry = zipFile.getEntry(entryName);
- final InputStream inputStream = zipFile.getInputStream(zentry);
- System.out.printf("size=%d csize=%d available=%d%n",
- zentry.getSize(),
- zentry.getCompressedSize(),
- inputStream.available());
- byte[] buf = new byte[data.length()];
- final int count = inputStream.read(buf);
- if (! new String(buf, "ASCII").equals(data) ||
- count != data.length())
- throw new Exception("short read?");
- zipFile.close();
+ try (ZipFile zipFile = new ZipFile(zFile)) {
+ final ZipEntry zentry = zipFile.getEntry(entryName);
+ final InputStream inputStream = zipFile.getInputStream(zentry);
+ System.out.printf("size=%d csize=%d available=%d%n",
+ zentry.getSize(),
+ zentry.getCompressedSize(),
+ inputStream.available());
+ byte[] buf = new byte[data.length()];
+ final int count = inputStream.read(buf);
+ if (! new String(buf, "ASCII").equals(data) ||
+ count != data.length())
+ throw new Exception("short read?");
+ }
+ } finally {
+ zFile.delete();
}
- finally { zFile.delete(); }
}
}
diff --git a/jdk/test/java/util/zip/zip.java b/jdk/test/java/util/zip/zip.java
index 0ac91c5c130..62fb71398a7 100644
--- a/jdk/test/java/util/zip/zip.java
+++ b/jdk/test/java/util/zip/zip.java
@@ -322,57 +322,57 @@ public class zip {
void create(OutputStream out) throws IOException
{
- ZipOutputStream zos = new ZipOutputStream(out, cs);
- if (flag0) {
- zos.setMethod(ZipOutputStream.STORED);
+ try (ZipOutputStream zos = new ZipOutputStream(out, cs)) {
+ if (flag0) {
+ zos.setMethod(ZipOutputStream.STORED);
+ }
+ for (File file: entries) {
+ addFile(zos, file);
+ }
}
- for (File file: entries) {
- addFile(zos, file);
- }
- zos.close();
}
boolean update(InputStream in, OutputStream out) throws IOException
{
- ZipInputStream zis = new ZipInputStream(in, cs);
- ZipOutputStream zos = new ZipOutputStream(out, cs);
- ZipEntry e = null;
- byte[] buf = new byte[1024];
- int n = 0;
- boolean updateOk = true;
+ try (ZipInputStream zis = new ZipInputStream(in, cs);
+ ZipOutputStream zos = new ZipOutputStream(out, cs))
+ {
+ ZipEntry e = null;
+ byte[] buf = new byte[1024];
+ int n = 0;
+ boolean updateOk = true;
- // put the old entries first, replace if necessary
- while ((e = zis.getNextEntry()) != null) {
- String name = e.getName();
- if (!entryMap.containsKey(name)) { // copy the old stuff
- // do our own compression
- ZipEntry e2 = new ZipEntry(name);
- e2.setMethod(e.getMethod());
- e2.setTime(e.getTime());
- e2.setComment(e.getComment());
- e2.setExtra(e.getExtra());
- if (e.getMethod() == ZipEntry.STORED) {
- e2.setSize(e.getSize());
- e2.setCrc(e.getCrc());
+ // put the old entries first, replace if necessary
+ while ((e = zis.getNextEntry()) != null) {
+ String name = e.getName();
+ if (!entryMap.containsKey(name)) { // copy the old stuff
+ // do our own compression
+ ZipEntry e2 = new ZipEntry(name);
+ e2.setMethod(e.getMethod());
+ e2.setTime(e.getTime());
+ e2.setComment(e.getComment());
+ e2.setExtra(e.getExtra());
+ if (e.getMethod() == ZipEntry.STORED) {
+ e2.setSize(e.getSize());
+ e2.setCrc(e.getCrc());
+ }
+ zos.putNextEntry(e2);
+ while ((n = zis.read(buf, 0, buf.length)) != -1) {
+ zos.write(buf, 0, n);
+ }
+ } else { // replace with the new files
+ File f = entryMap.get(name);
+ addFile(zos, f);
+ entryMap.remove(name);
+ entries.remove(f);
}
- zos.putNextEntry(e2);
- while ((n = zis.read(buf, 0, buf.length)) != -1) {
- zos.write(buf, 0, n);
- }
- } else { // replace with the new files
- File f = entryMap.get(name);
+ }
+
+ // add the remaining new files
+ for (File f: entries) {
addFile(zos, f);
- entryMap.remove(name);
- entries.remove(f);
}
}
-
- // add the remaining new files
- for (File f: entries) {
- addFile(zos, f);
- }
- zis.close();
- zos.close();
return updateOk;
}
@@ -517,25 +517,25 @@ public class zip {
}
void extract(String fname, String files[]) throws IOException {
- ZipFile zf = new ZipFile(fname, cs);
- Set dirs = newDirSet();
- Enumeration extends ZipEntry> zes = zf.entries();
- while (zes.hasMoreElements()) {
- ZipEntry e = zes.nextElement();
- InputStream is;
- if (files == null) {
- dirs.add(extractFile(zf.getInputStream(e), e));
- } else {
- String name = e.getName();
- for (String file : files) {
- if (name.startsWith(file)) {
- dirs.add(extractFile(zf.getInputStream(e), e));
- break;
+ try (ZipFile zf = new ZipFile(fname, cs)) {
+ Set dirs = newDirSet();
+ Enumeration extends ZipEntry> zes = zf.entries();
+ while (zes.hasMoreElements()) {
+ ZipEntry e = zes.nextElement();
+ InputStream is;
+ if (files == null) {
+ dirs.add(extractFile(zf.getInputStream(e), e));
+ } else {
+ String name = e.getName();
+ for (String file : files) {
+ if (name.startsWith(file)) {
+ dirs.add(extractFile(zf.getInputStream(e), e));
+ break;
+ }
}
}
}
}
- zf.close();
updateLastModifiedTime(dirs);
}
@@ -607,12 +607,12 @@ public class zip {
}
void list(String fname, String files[]) throws IOException {
- ZipFile zf = new ZipFile(fname, cs);
- Enumeration extends ZipEntry> zes = zf.entries();
- while (zes.hasMoreElements()) {
- printEntry(zes.nextElement(), files);
+ try (ZipFile zf = new ZipFile(fname, cs)) {
+ Enumeration extends ZipEntry> zes = zf.entries();
+ while (zes.hasMoreElements()) {
+ printEntry(zes.nextElement(), files);
+ }
}
- zf.close();
}
void printEntry(ZipEntry e, String[] files) throws IOException {
diff --git a/jdk/test/sun/misc/BootClassLoaderHook/TestHook.java b/jdk/test/sun/misc/BootClassLoaderHook/TestHook.java
deleted file mode 100644
index da5f505d843..00000000000
--- a/jdk/test/sun/misc/BootClassLoaderHook/TestHook.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-import java.io.File;
-import java.util.TreeSet;
-import java.util.Set;
-import java.net.URLStreamHandlerFactory;
-import sun.misc.BootClassLoaderHook;
-import sun.misc.URLClassPath;
-
-
-/* @test
- * @bug 6888802
- * @summary Sanity test of BootClassLoaderHook interface
- *
- * @build TestHook
- * @run main TestHook
- */
-
-public class TestHook extends BootClassLoaderHook {
-
- private static final TestHook hook = new TestHook();
- private static Set names = new TreeSet();
- private static final String LOGRECORD_CLASS =
- "java.util.logging.LogRecord";
- private static final String NONEXIST_RESOURCE =
- "non.exist.resource";
- private static final String LIBHELLO = "hello";
-
- public static void main(String[] args) throws Exception {
- BootClassLoaderHook.setHook(hook);
- if (BootClassLoaderHook.getHook() == null) {
- throw new RuntimeException("Null boot classloader hook ");
- }
-
- testHook();
-
- if (!names.contains(LOGRECORD_CLASS)) {
- throw new RuntimeException("loadBootstrapClass for " + LOGRECORD_CLASS + " not called");
- }
-
- if (!names.contains(NONEXIST_RESOURCE)) {
- throw new RuntimeException("getBootstrapResource for " + NONEXIST_RESOURCE + " not called");
- }
- if (!names.contains(LIBHELLO)) {
- throw new RuntimeException("loadLibrary for " + LIBHELLO + " not called");
- }
-
- Set copy = new TreeSet();
- copy.addAll(names);
- for (String s : copy) {
- System.out.println(" Loaded " + s);
- }
- }
-
- private static void testHook() throws Exception {
- Class.forName(LOGRECORD_CLASS);
- ClassLoader.getSystemResource(NONEXIST_RESOURCE);
- try {
- System.loadLibrary(LIBHELLO);
- } catch (UnsatisfiedLinkError e) {
- }
- }
-
- public String loadBootstrapClass(String className) {
- names.add(className);
- return null;
- }
-
- public String getBootstrapResource(String resourceName) {
- names.add(resourceName);
- return null;
- }
-
- public boolean loadLibrary(String libname) {
- names.add(libname);
- return false;
- }
-
- public URLClassPath getBootstrapClassPath(URLClassPath bcp,
- URLStreamHandlerFactory factory) {
- return bcp;
- }
-
- public boolean isCurrentThreadPrefetching() {
- return false;
- }
-
- public boolean prefetchFile(String name) {
- return false;
- }
-}
diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java
index f1adba35d23..4f27ff5de0c 100644
--- a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java
+++ b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/**
* @test
- * @bug 4898468
+ * @bug 4898468 6994008
* @summary basic test for RSA cipher
* @author Andreas Sterbenz
* @library ..
@@ -38,9 +38,12 @@ import javax.crypto.*;
public class TestRSACipher extends PKCS11Test {
+ private static final String[] RSA_ALGOS =
+ { "RSA/ECB/PKCS1Padding", "RSA" };
+
public void main(Provider p) throws Exception {
try {
- Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
+ Cipher.getInstance(RSA_ALGOS[0], p);
} catch (GeneralSecurityException e) {
System.out.println("Not supported by provider, skipping");
return;
@@ -55,57 +58,58 @@ public class TestRSACipher extends PKCS11Test {
b = new byte[16];
random.nextBytes(b);
- Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
- Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
+ for (String rsaAlgo: RSA_ALGOS) {
+ Cipher c1 = Cipher.getInstance(rsaAlgo, p);
+ Cipher c2 = Cipher.getInstance(rsaAlgo, "SunJCE");
- c1.init(Cipher.ENCRYPT_MODE, publicKey);
- e = c1.doFinal(b);
- c1.init(Cipher.DECRYPT_MODE, privateKey);
- d = c1.doFinal(e);
- match(b, d);
- c2.init(Cipher.DECRYPT_MODE, privateKey);
- d = c2.doFinal(e);
- match(b, d);
-
- // invalid data
- c1.init(Cipher.DECRYPT_MODE, publicKey);
- try {
+ c1.init(Cipher.ENCRYPT_MODE, publicKey);
+ e = c1.doFinal(b);
+ c1.init(Cipher.DECRYPT_MODE, privateKey);
d = c1.doFinal(e);
- throw new Exception("completed call");
- } catch (BadPaddingException ee) {
- ee.printStackTrace();
- }
+ match(b, d);
+ c2.init(Cipher.DECRYPT_MODE, privateKey);
+ d = c2.doFinal(e);
+ match(b, d);
- c1.init(Cipher.ENCRYPT_MODE, privateKey);
- e = c1.doFinal(b);
- c1.init(Cipher.DECRYPT_MODE, publicKey);
- d = c1.doFinal(e);
- match(b, d);
- c2.init(Cipher.DECRYPT_MODE, publicKey);
- d = c2.doFinal(e);
- match(b, d);
+ // invalid data
+ c1.init(Cipher.DECRYPT_MODE, publicKey);
+ try {
+ d = c1.doFinal(e);
+ throw new Exception("completed call");
+ } catch (BadPaddingException ee) {
+ ee.printStackTrace();
+ }
- // reinit tests
- c1.init(Cipher.ENCRYPT_MODE, privateKey);
- c1.init(Cipher.ENCRYPT_MODE, privateKey);
- e = c1.doFinal(b);
- e = c1.doFinal(b);
- c1.update(b);
- c1.update(b);
- c1.init(Cipher.ENCRYPT_MODE, privateKey);
- e = c1.doFinal();
- e = c1.doFinal();
- c1.update(b);
- e = c1.doFinal();
+ c1.init(Cipher.ENCRYPT_MODE, privateKey);
+ e = c1.doFinal(b);
+ c1.init(Cipher.DECRYPT_MODE, publicKey);
+ d = c1.doFinal(e);
+ match(b, d);
+ c2.init(Cipher.DECRYPT_MODE, publicKey);
+ d = c2.doFinal(e);
+ match(b, d);
- c1.update(new byte[256]);
- try {
+ // reinit tests
+ c1.init(Cipher.ENCRYPT_MODE, privateKey);
+ c1.init(Cipher.ENCRYPT_MODE, privateKey);
+ e = c1.doFinal(b);
+ e = c1.doFinal(b);
+ c1.update(b);
+ c1.update(b);
+ c1.init(Cipher.ENCRYPT_MODE, privateKey);
+ e = c1.doFinal();
+ e = c1.doFinal();
+ c1.update(b);
e = c1.doFinal();
- throw new Exception("completed call");
- } catch (IllegalBlockSizeException ee) {
- System.out.println(ee);
- }
+ c1.update(new byte[256]);
+ try {
+ e = c1.doFinal();
+ throw new Exception("completed call");
+ } catch (IllegalBlockSizeException ee) {
+ System.out.println(ee);
+ }
+ }
}
private static void match(byte[] b1, byte[] b2) throws Exception {
diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java
index 159bb50a029..c00b39942cc 100644
--- a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java
+++ b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/**
* @test
- * @bug 6572331
+ * @bug 6572331 6994008
* @summary basic test for RSA cipher key wrapping functionality
* @author Valerie Peng
* @library ..
@@ -38,47 +38,48 @@ import javax.crypto.spec.SecretKeySpec;
public class TestRSACipherWrap extends PKCS11Test {
- private static final String RSA_ALGO = "RSA/ECB/PKCS1Padding";
+ private static final String[] RSA_ALGOS =
+ { "RSA/ECB/PKCS1Padding", "RSA" };
public void main(Provider p) throws Exception {
try {
- Cipher.getInstance(RSA_ALGO, p);
+ Cipher.getInstance(RSA_ALGOS[0], p);
} catch (GeneralSecurityException e) {
- System.out.println("Not supported by provider, skipping");
+ System.out.println(RSA_ALGOS[0] + " unsupported, skipping");
return;
}
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
- PublicKey publicKey = kp.getPublic();
- PrivateKey privateKey = kp.getPrivate();
- Cipher cipherPKCS11 = Cipher.getInstance(RSA_ALGO, p);
- Cipher cipherJce = Cipher.getInstance(RSA_ALGO, "SunJCE");
+ for (String rsaAlgo: RSA_ALGOS) {
+ Cipher cipherPKCS11 = Cipher.getInstance(rsaAlgo, p);
+ Cipher cipherJce = Cipher.getInstance(rsaAlgo, "SunJCE");
- String algos[] = {"AES", "RC2", "Blowfish"};
- int keySizes[] = {128, 256};
+ String algos[] = {"AES", "RC2", "Blowfish"};
+ int keySizes[] = {128, 256};
- for (int j = 0; j < algos.length; j++) {
- String algorithm = algos[j];
- KeyGenerator keygen =
+ for (int j = 0; j < algos.length; j++) {
+ String algorithm = algos[j];
+ KeyGenerator keygen =
KeyGenerator.getInstance(algorithm);
- for (int i = 0; i < keySizes.length; i++) {
- SecretKey secretKey = null;
- System.out.print("Generate " + keySizes[i] + "-bit " +
+ for (int i = 0; i < keySizes.length; i++) {
+ SecretKey secretKey = null;
+ System.out.print("Generate " + keySizes[i] + "-bit " +
algorithm + " key using ");
- try {
- keygen.init(keySizes[i]);
- secretKey = keygen.generateKey();
- System.out.println(keygen.getProvider().getName());
- } catch (InvalidParameterException ipe) {
- secretKey = new SecretKeySpec(new byte[32], algorithm);
- System.out.println("SecretKeySpec class");
+ try {
+ keygen.init(keySizes[i]);
+ secretKey = keygen.generateKey();
+ System.out.println(keygen.getProvider().getName());
+ } catch (InvalidParameterException ipe) {
+ secretKey = new SecretKeySpec(new byte[32], algorithm);
+ System.out.println("SecretKeySpec class");
+ }
+ test(kp, secretKey, cipherPKCS11, cipherJce);
+ test(kp, secretKey, cipherPKCS11, cipherPKCS11);
+ test(kp, secretKey, cipherJce, cipherPKCS11);
}
- test(kp, secretKey, cipherPKCS11, cipherJce);
- test(kp, secretKey, cipherPKCS11, cipherPKCS11);
- test(kp, secretKey, cipherJce, cipherPKCS11);
}
}
}
diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java b/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java
new file mode 100644
index 00000000000..d1dd0206031
--- /dev/null
+++ b/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 6994008
+ * @summary basic test for RSA/ECB/NoPadding cipher
+ * @author Valerie Peng
+ * @library ..
+ */
+
+import javax.crypto.*;
+import java.io.*;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.*;
+import java.util.*;
+
+public class TestRawRSACipher extends PKCS11Test {
+
+ public void main(Provider p) throws Exception {
+ try {
+ Cipher.getInstance("RSA/ECB/NoPadding", p);
+ } catch (GeneralSecurityException e) {
+ System.out.println("Not supported by provider, skipping");
+ return;
+ }
+
+ final int KEY_LEN = 1024;
+ KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", p);
+ kpGen.initialize(KEY_LEN);
+ KeyPair kp = kpGen.generateKeyPair();
+ Random random = new Random();
+ byte[] plainText, cipherText, recoveredText;
+ plainText = new byte[KEY_LEN/8];
+ random.nextBytes(plainText);
+ plainText[0] = 0; // to ensure that it's less than modulus
+
+ Cipher c1 = Cipher.getInstance("RSA/ECB/NoPadding", p);
+ Cipher c2 = Cipher.getInstance("RSA/ECB/NoPadding", "SunJCE");
+
+ c1.init(Cipher.ENCRYPT_MODE, kp.getPublic());
+ c2.init(Cipher.DECRYPT_MODE, kp.getPrivate());
+
+ cipherText = c1.doFinal(plainText);
+ recoveredText = c2.doFinal(cipherText);
+ if (!Arrays.equals(plainText, recoveredText)) {
+ throw new RuntimeException("E/D Test against SunJCE Failed!");
+ }
+
+ c2.init(Cipher.ENCRYPT_MODE, kp.getPublic());
+ c1.init(Cipher.DECRYPT_MODE, kp.getPrivate());
+ cipherText = c2.doFinal(plainText);
+ recoveredText = c1.doFinal(cipherText);
+ if (!Arrays.equals(plainText, recoveredText)) {
+ throw new RuntimeException("D/E Test against SunJCE Failed!");
+ }
+
+ System.out.println("Test Passed");
+ }
+
+ public static void main(String[] args) throws Exception {
+ main(new TestRawRSACipher());
+ }
+}
diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java
index b8a6dcced66..14e41cdddd2 100644
--- a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java
+++ b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/**
* @test %I% %E%
- * @bug 4898461
+ * @bug 4898461 6604496
* @summary basic test for symmetric ciphers with padding
* @author Valerie Peng
* @library ..
@@ -70,9 +70,13 @@ public class TestSymmCiphers extends PKCS11Test {
new CI("DES/ECB/PKCS5Padding", "DES", 6400),
new CI("DESede/ECB/PKCS5Padding", "DESede", 400),
new CI("AES/ECB/PKCS5Padding", "AES", 64),
+
new CI("DES", "DES", 6400),
new CI("DESede", "DESede", 408),
- new CI("AES", "AES", 128)
+ new CI("AES", "AES", 128),
+
+ new CI("AES/CTR/NoPadding", "AES", 3200)
+
};
private static StringBuffer debugBuf = new StringBuffer();
diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java
index 5c2e939e8bd..5f94ea48f57 100644
--- a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java
+++ b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/**
* @test
- * @bug 4898484
+ * @bug 4898484 6604496
* @summary basic test for symmetric ciphers with no padding
* @author Valerie Peng
* @library ..
@@ -59,7 +59,8 @@ public class TestSymmCiphersNoPad extends PKCS11Test {
new CI("DES/CBC/NoPadding", "DES", 400),
new CI("DESede/CBC/NoPadding", "DESede", 160),
new CI("AES/CBC/NoPadding", "AES", 4800),
- new CI("Blowfish/CBC/NoPadding", "Blowfish", 24)
+ new CI("Blowfish/CBC/NoPadding", "Blowfish", 24),
+ new CI("AES/CTR/NoPadding", "AES", 1600)
};
private static StringBuffer debugBuf;
diff --git a/jdk/test/sun/security/tools/jarsigner/crl.sh b/jdk/test/sun/security/tools/jarsigner/crl.sh
index b563c523cc4..2d7f5237ba3 100644
--- a/jdk/test/sun/security/tools/jarsigner/crl.sh
+++ b/jdk/test/sun/security/tools/jarsigner/crl.sh
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -32,9 +32,6 @@ if [ "${TESTJAVA}" = "" ] ; then
fi
# set platform-dependent variables
-# PF: platform name, say, solaris-sparc
-
-PF=""
OS=`uname -s`
case "$OS" in
@@ -47,54 +44,28 @@ case "$OS" in
esac
KS=crl.jks
-JFILE=crl.jar
KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit -keystore $KS"
-JAR=$TESTJAVA${FS}bin${FS}jar
-JARSIGNER=$TESTJAVA${FS}bin${FS}jarsigner
-rm $KS $JFILE 2> /dev/null
+rm $KS 2> /dev/null
-# Generates some crl files, each containing two entries
+# Test keytool -gencrl
$KT -alias a -dname CN=a -keyalg rsa -genkey -validity 300
-$KT -alias a -gencrl -id 1:1 -id 2:2 -file crl1
-$KT -alias a -gencrl -id 3:3 -id 4:4 -file crl2
-$KT -alias b -dname CN=b -keyalg rsa -genkey -validity 300
-$KT -alias b -gencrl -id 5:1 -id 6:2 -file crl3
+$KT -alias a -gencrl -id 1:1 -id 2:2 -file crl1 || exit 1
+$KT -alias a -gencrl -id 3:3 -id 4:4 -file crl2 || exit 2
+$KT -alias a -gencrl -id 5:1 -id 6:2 -file crl3 || exit 4
-cat > ToURI.java < uri
-$KT -alias c -dname CN=c -keyalg rsa -genkey -validity 300 \
- -ext crl=uri:`cat uri`
+# Test keytool -printcrl
-echo A > A
+$KT -printcrl -file crl1 || exit 5
+$KT -printcrl -file crl2 || exit 6
+$KT -printcrl -file crl3 || exit 7
-# Test -crl:auto, cRLDistributionPoints is a local file
-$JAR cvf $JFILE A
-$JARSIGNER -keystore $KS -storepass changeit $JFILE c \
- -crl:auto || exit 1
-$JARSIGNER -keystore $KS -verify -debug -strict $JFILE || exit 6
-$KT -printcert -jarfile $JFILE | grep CRLs || exit 7
+# Test keytool -ext crl
-# Test -crl
-
-$JAR cvf $JFILE A
-$JARSIGNER -keystore $KS -storepass changeit $JFILE a \
- -crl crl1 -crl crl2 || exit 2
-$JARSIGNER -keystore $KS -storepass changeit $JFILE b \
- -crl crl3 -crl crl2 || exit 3
-$JARSIGNER -keystore $KS -verify -debug -strict $JFILE || exit 3
-$KT -printcert -jarfile $JFILE | grep CRLs || exit 4
-CRLCOUNT=`$KT -printcert -jarfile $JFILE | grep SerialNumber | wc -l`
-if [ $CRLCOUNT != 8 ]; then exit 5; fi
+$KT -alias b -dname CN=c -keyalg rsa -genkey -validity 300 \
+ -ext crl=uri:http://www.example.com/crl || exit 10
exit 0
diff --git a/jdk/test/sun/security/tools/keytool/NewSize7.java b/jdk/test/sun/security/tools/keytool/NewSize7.java
index d9ff1f55402..ab8ef5cb59a 100644
--- a/jdk/test/sun/security/tools/keytool/NewSize7.java
+++ b/jdk/test/sun/security/tools/keytool/NewSize7.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,8 @@
import java.io.File;
import java.io.FileInputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
@@ -42,8 +44,10 @@ public class NewSize7 {
" -alias a -dname cn=c -storepass changeit" +
" -keypass changeit -keyalg rsa").split(" "));
KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(new FileInputStream(FILE), null);
- new File(FILE).delete();
+ try (FileInputStream fin = new FileInputStream(FILE)) {
+ ks.load(fin, null);
+ }
+ Files.delete(Paths.get(FILE));
RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
if (r.getModulus().bitLength() != 2048) {
throw new Exception("Bad keysize");
diff --git a/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh b/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh
index 8c32cf8423d..82ee282bda3 100644
--- a/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh
+++ b/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh
@@ -24,7 +24,7 @@
#
# @test
-# @bug 4630463 4630971 4636448 4701617 4721296 4710890 6247817
+# @bug 4630463 4630971 4636448 4701617 4721296 4710890 6247817 7021987
# @summary Tests miscellaneous native2ascii bugfixes and regressions
@@ -100,6 +100,15 @@ rm -f x.*
$N2A -reverse -encoding MS932 $TESTSRC/A2N_4701617 x.out
check 4701617 $TESTSRC/A2N_4701617.expected x.out
+# Check that the inputfile appears in the error message when not found
+
+badin="DoesNotExist"
+$N2A $badin x.out | grep "$badin" > /dev/null
+if [ $? != 0 ]; then
+ echo "\"$badin\" expected to appear in error message"
+ exit 1
+fi
+
# for win32 only ensure when output file pre-exists that
# native2ascii tool will simply overwrite with the expected
# output file (fixed bugID 4710890)