/**
* Returns an iterator over all the elements (both expired and
* unexpired) in this queue. The iterator does not return the
- * elements in any particular order. The returned
- * Iterator is a "weakly consistent" iterator that will
- * never throw {@link ConcurrentModificationException}, and
- * guarantees to traverse elements as they existed upon
- * construction of the iterator, and may (but is not guaranteed
- * to) reflect any modifications subsequent to construction.
+ * elements in any particular order.
+ *
+ * The returned iterator is a "weakly consistent" iterator that
+ * will never throw {@link java.util.ConcurrentModificationException
+ * ConcurrentModificationException}, and guarantees to traverse
+ * elements as they existed upon construction of the iterator, and
+ * may (but is not guaranteed to) reflect any modifications
+ * subsequent to construction.
*
* @return an iterator over the elements in this queue
*/
diff --git a/src/share/classes/java/util/concurrent/Exchanger.java b/src/share/classes/java/util/concurrent/Exchanger.java
index c4563a8ae9b695c10eac43e63bcf1fceb1dcaaa8..8648278b75566f5363986e84551a16a8c1acff8b 100644
--- a/src/share/classes/java/util/concurrent/Exchanger.java
+++ b/src/share/classes/java/util/concurrent/Exchanger.java
@@ -355,7 +355,9 @@ public class Exchanger {
else if (y == null && // Try to occupy
slot.compareAndSet(null, me)) {
if (index == 0) // Blocking wait for slot 0
- return timed? awaitNanos(me, slot, nanos): await(me, slot);
+ return timed ?
+ awaitNanos(me, slot, nanos) :
+ await(me, slot);
Object v = spinWait(me, slot); // Spin wait for non-0
if (v != CANCEL)
return v;
@@ -597,8 +599,8 @@ public class Exchanger {
* dormant until one of two things happens:
*
* - Some other thread enters the exchange; or
- *
- Some other thread {@linkplain Thread#interrupt interrupts} the current
- * thread.
+ *
- Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread.
*
* If the current thread:
*
@@ -616,7 +618,7 @@ public class Exchanger {
*/
public V exchange(V x) throws InterruptedException {
if (!Thread.interrupted()) {
- Object v = doExchange(x == null? NULL_ITEM : x, false, 0);
+ Object v = doExchange((x == null) ? NULL_ITEM : x, false, 0);
if (v == NULL_ITEM)
return null;
if (v != CANCEL)
@@ -671,7 +673,7 @@ public class Exchanger {
public V exchange(V x, long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException {
if (!Thread.interrupted()) {
- Object v = doExchange(x == null? NULL_ITEM : x,
+ Object v = doExchange((x == null) ? NULL_ITEM : x,
true, unit.toNanos(timeout));
if (v == NULL_ITEM)
return null;
diff --git a/src/share/classes/java/util/concurrent/Executor.java b/src/share/classes/java/util/concurrent/Executor.java
index 85b3277f43d57e38ca1668422c7253cf31289697..5e67fbcdd08fe60aa75f4281d7fc8b2f4b42796d 100644
--- a/src/share/classes/java/util/concurrent/Executor.java
+++ b/src/share/classes/java/util/concurrent/Executor.java
@@ -79,37 +79,37 @@ package java.util.concurrent;
* serializes the submission of tasks to a second executor,
* illustrating a composite executor.
*
- *
+ * {@code
* class SerialExecutor implements Executor {
- * final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
- * final Executor executor;
- * Runnable active;
- *
- * SerialExecutor(Executor executor) {
- * this.executor = executor;
- * }
- *
- * public synchronized void execute(final Runnable r) {
- * tasks.offer(new Runnable() {
- * public void run() {
- * try {
- * r.run();
- * } finally {
- * scheduleNext();
- * }
- * }
- * });
- * if (active == null) {
- * scheduleNext();
+ * final Queue tasks = new ArrayDeque();
+ * final Executor executor;
+ * Runnable active;
+ *
+ * SerialExecutor(Executor executor) {
+ * this.executor = executor;
+ * }
+ *
+ * public synchronized void execute(final Runnable r) {
+ * tasks.offer(new Runnable() {
+ * public void run() {
+ * try {
+ * r.run();
+ * } finally {
+ * scheduleNext();
* }
+ * }
+ * });
+ * if (active == null) {
+ * scheduleNext();
* }
+ * }
*
- * protected synchronized void scheduleNext() {
- * if ((active = tasks.poll()) != null) {
- * executor.execute(active);
- * }
+ * protected synchronized void scheduleNext() {
+ * if ((active = tasks.poll()) != null) {
+ * executor.execute(active);
* }
- * }
+ * }
+ * }}
*
* The Executor implementations provided in this package
* implement {@link ExecutorService}, which is a more extensive
diff --git a/src/share/classes/java/util/concurrent/ExecutorCompletionService.java b/src/share/classes/java/util/concurrent/ExecutorCompletionService.java
index 4d37c999018f6bf4b1ab469498cac82e68c0fff9..9908a8cfcdd2e45098a7692ebfe92247406d54a0 100644
--- a/src/share/classes/java/util/concurrent/ExecutorCompletionService.java
+++ b/src/share/classes/java/util/concurrent/ExecutorCompletionService.java
@@ -197,7 +197,8 @@ public class ExecutorCompletionService implements CompletionService {
return completionQueue.poll();
}
- public Future poll(long timeout, TimeUnit unit) throws InterruptedException {
+ public Future poll(long timeout, TimeUnit unit)
+ throws InterruptedException {
return completionQueue.poll(timeout, unit);
}
diff --git a/src/share/classes/java/util/concurrent/Executors.java b/src/share/classes/java/util/concurrent/Executors.java
index efa2f78f86f34533a0b154370bbabb2284f31586..75a490086ae6c828c3dc83dbc7ab475c33f66803 100644
--- a/src/share/classes/java/util/concurrent/Executors.java
+++ b/src/share/classes/java/util/concurrent/Executors.java
@@ -83,7 +83,7 @@ public class Executors {
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
- * @throws IllegalArgumentException if nThreads <= 0
+ * @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
@@ -108,7 +108,7 @@ public class Executors {
* @param threadFactory the factory to use when creating new threads
* @return the newly created thread pool
* @throws NullPointerException if threadFactory is null
- * @throws IllegalArgumentException if nThreads <= 0
+ * @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
@@ -242,7 +242,7 @@ public class Executors {
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle.
* @return a newly created scheduled thread pool
- * @throws IllegalArgumentException if corePoolSize < 0
+ * @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
@@ -256,7 +256,7 @@ public class Executors {
* @param threadFactory the factory to use when the executor
* creates a new thread.
* @return a newly created scheduled thread pool
- * @throws IllegalArgumentException if corePoolSize < 0
+ * @throws IllegalArgumentException if {@code corePoolSize < 0}
* @throws NullPointerException if threadFactory is null
*/
public static ScheduledExecutorService newScheduledThreadPool(
@@ -562,8 +562,8 @@ public class Executors {
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
- group = (s != null)? s.getThreadGroup() :
- Thread.currentThread().getThreadGroup();
+ group = (s != null) ? s.getThreadGroup() :
+ Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
@@ -669,7 +669,7 @@ public class Executors {
FinalizableDelegatedExecutorService(ExecutorService executor) {
super(executor);
}
- protected void finalize() {
+ protected void finalize() {
super.shutdown();
}
}
diff --git a/src/share/classes/java/util/concurrent/Future.java b/src/share/classes/java/util/concurrent/Future.java
index 9d3d1ff741b72dd6153c95da0b47c01071c96f94..4abd3f4e1741ad577f05f56f0c6f3f64cacf5d31 100644
--- a/src/share/classes/java/util/concurrent/Future.java
+++ b/src/share/classes/java/util/concurrent/Future.java
@@ -47,21 +47,21 @@ package java.util.concurrent;
* computation has completed, the computation cannot be cancelled.
* If you would like to use a Future for the sake
* of cancellability but not provide a usable result, you can
- * declare types of the form Future<?> and
+ * declare types of the form {@code Future>} and
* return null as a result of the underlying task.
*
*
* Sample Usage (Note that the following classes are all
* made-up.)
- *
+ * {@code
* interface ArchiveSearcher { String search(String target); }
* class App {
* ExecutorService executor = ...
* ArchiveSearcher searcher = ...
* void showSearch(final String target)
* throws InterruptedException {
- * Future<String> future
- * = executor.submit(new Callable<String>() {
+ * Future future
+ * = executor.submit(new Callable() {
* public String call() {
* return searcher.search(target);
* }});
@@ -70,20 +70,18 @@ package java.util.concurrent;
* displayText(future.get()); // use future
* } catch (ExecutionException ex) { cleanup(); return; }
* }
- * }
- *
+ * }}
*
* The {@link FutureTask} class is an implementation of Future that
* implements Runnable, and so may be executed by an Executor.
* For example, the above construction with submit could be replaced by:
- *
- * FutureTask<String> future =
- * new FutureTask<String>(new Callable<String>() {
+ * {@code
+ * FutureTask future =
+ * new FutureTask(new Callable() {
* public String call() {
* return searcher.search(target);
* }});
- * executor.execute(future);
- *
+ * executor.execute(future);}
*
* Memory consistency effects: Actions taken by the asynchronous computation
* happen-before
diff --git a/src/share/classes/java/util/concurrent/FutureTask.java b/src/share/classes/java/util/concurrent/FutureTask.java
index c77b6d3ced4205eafabc77f82da4a94dcbd0a4dd..dd7a51edf712686fa929d2a249893bed12f9ec38 100644
--- a/src/share/classes/java/util/concurrent/FutureTask.java
+++ b/src/share/classes/java/util/concurrent/FutureTask.java
@@ -85,7 +85,7 @@ public class FutureTask implements RunnableFuture {
* @param result the result to return on successful completion. If
* you don't need a particular result, consider using
* constructions of the form:
- * Future<?> f = new FutureTask<Object>(runnable, null)
+ * {@code Future> f = new FutureTask(runnable, null)}
* @throws NullPointerException if runnable is null
*/
public FutureTask(Runnable runnable, V result) {
diff --git a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java
index 13901e842f72a910e1d4c42aab9770741e6b9e36..8051ccaa8483f71f0f873515a27f1880b051ab6f 100644
--- a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java
+++ b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java
@@ -1004,12 +1004,13 @@ public class LinkedBlockingDeque
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
- * The returned {@code Iterator} is a "weakly consistent" iterator that
+ *
+ * The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
- * ConcurrentModificationException},
- * and guarantees to traverse elements as they existed upon
- * construction of the iterator, and may (but is not guaranteed to)
- * reflect any modifications subsequent to construction.
+ * ConcurrentModificationException}, and guarantees to traverse
+ * elements as they existed upon construction of the iterator, and
+ * may (but is not guaranteed to) reflect any modifications
+ * subsequent to construction.
*
* @return an iterator over the elements in this deque in proper sequence
*/
@@ -1021,12 +1022,13 @@ public class LinkedBlockingDeque
* Returns an iterator over the elements in this deque in reverse
* sequential order. The elements will be returned in order from
* last (tail) to first (head).
- * The returned {@code Iterator} is a "weakly consistent" iterator that
+ *
+ * The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
- * ConcurrentModificationException},
- * and guarantees to traverse elements as they existed upon
- * construction of the iterator, and may (but is not guaranteed to)
- * reflect any modifications subsequent to construction.
+ * ConcurrentModificationException}, and guarantees to traverse
+ * elements as they existed upon construction of the iterator, and
+ * may (but is not guaranteed to) reflect any modifications
+ * subsequent to construction.
*/
public Iterator descendingIterator() {
return new DescendingItr();
diff --git a/src/share/classes/java/util/concurrent/RecursiveAction.java b/src/share/classes/java/util/concurrent/RecursiveAction.java
index 40bcc88f0f8fe4a29fa48d8dd514b74a6ecdb5ff..e13bc4b55781dd332a23163e8d4c4ae7d306af0a 100644
--- a/src/share/classes/java/util/concurrent/RecursiveAction.java
+++ b/src/share/classes/java/util/concurrent/RecursiveAction.java
@@ -159,7 +159,9 @@ public abstract class RecursiveAction extends ForkJoinTask {
protected abstract void compute();
/**
- * Always returns null.
+ * Always returns {@code null}.
+ *
+ * @return {@code null} always
*/
public final Void getRawResult() { return null; }
diff --git a/src/share/classes/java/util/concurrent/ScheduledExecutorService.java b/src/share/classes/java/util/concurrent/ScheduledExecutorService.java
index a8d2f4041831f29b625998e7d48176779927fa32..e9d5d150afc99067c534d7405449507e6f8aa9f1 100644
--- a/src/share/classes/java/util/concurrent/ScheduledExecutorService.java
+++ b/src/share/classes/java/util/concurrent/ScheduledExecutorService.java
@@ -72,24 +72,23 @@ import java.util.*;
* Here is a class with a method that sets up a ScheduledExecutorService
* to beep every ten seconds for an hour:
*
- *
+ * {@code
* import static java.util.concurrent.TimeUnit.*;
* class BeeperControl {
- * private final ScheduledExecutorService scheduler =
- * Executors.newScheduledThreadPool(1);
+ * private final ScheduledExecutorService scheduler =
+ * Executors.newScheduledThreadPool(1);
*
- * public void beepForAnHour() {
- * final Runnable beeper = new Runnable() {
- * public void run() { System.out.println("beep"); }
- * };
- * final ScheduledFuture<?> beeperHandle =
- * scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
- * scheduler.schedule(new Runnable() {
- * public void run() { beeperHandle.cancel(true); }
- * }, 60 * 60, SECONDS);
- * }
- * }
- *
+ * public void beepForAnHour() {
+ * final Runnable beeper = new Runnable() {
+ * public void run() { System.out.println("beep"); }
+ * };
+ * final ScheduledFuture> beeperHandle =
+ * scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
+ * scheduler.schedule(new Runnable() {
+ * public void run() { beeperHandle.cancel(true); }
+ * }, 60 * 60, SECONDS);
+ * }
+ * }}
*
* @since 1.5
* @author Doug Lea
diff --git a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java
index 67c23fe99d79351d2bf83318761f4baf521ac3e2..46961b7aa40a43bf01bd9c0107b1ea618e4d6cb5 100644
--- a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java
+++ b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java
@@ -62,8 +62,8 @@ import java.util.*;
* time of cancellation.
*
* Successive executions of a task scheduled via
- * scheduleAtFixedRate or
- * scheduleWithFixedDelay do not overlap. While different
+ * {@code scheduleAtFixedRate} or
+ * {@code scheduleWithFixedDelay} do not overlap. While different
* executions may be performed by different threads, the effects of
* prior executions happen-before
@@ -436,7 +436,7 @@ public class ScheduledThreadPoolExecutor
* @throws NullPointerException if {@code threadFactory} is null
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
- ThreadFactory threadFactory) {
+ ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
@@ -453,7 +453,7 @@ public class ScheduledThreadPoolExecutor
* @throws NullPointerException if {@code handler} is null
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
- RejectedExecutionHandler handler) {
+ RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), handler);
}
@@ -473,8 +473,8 @@ public class ScheduledThreadPoolExecutor
* {@code handler} is null
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
- ThreadFactory threadFactory,
- RejectedExecutionHandler handler) {
+ ThreadFactory threadFactory,
+ RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), threadFactory, handler);
}
diff --git a/src/share/classes/java/util/concurrent/Semaphore.java b/src/share/classes/java/util/concurrent/Semaphore.java
index 96a4719148d7397f8469ab773beb1e1be2671959..56c233fb3a7ba7ede0fe838fa78f8a5c7d495185 100644
--- a/src/share/classes/java/util/concurrent/Semaphore.java
+++ b/src/share/classes/java/util/concurrent/Semaphore.java
@@ -223,7 +223,7 @@ public class Semaphore implements java.io.Serializable {
/**
* NonFair version
*/
- final static class NonfairSync extends Sync {
+ static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L;
NonfairSync(int permits) {
@@ -238,7 +238,7 @@ public class Semaphore implements java.io.Serializable {
/**
* Fair version
*/
- final static class FairSync extends Sync {
+ static final class FairSync extends Sync {
private static final long serialVersionUID = 2014338818796000944L;
FairSync(int permits) {
@@ -282,7 +282,7 @@ public class Semaphore implements java.io.Serializable {
* else {@code false}
*/
public Semaphore(int permits, boolean fair) {
- sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
+ sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
/**
diff --git a/src/share/classes/java/util/concurrent/ThreadLocalRandom.java b/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
index c8a67dd651022703ce4bddcf8235fbbbedec4b2f..69f5fbcb40481b1350ba7921f8c7a9f7e260096e 100644
--- a/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
+++ b/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
@@ -63,9 +63,9 @@ import java.util.Random;
*/
public class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
diff --git a/src/share/classes/java/util/concurrent/TimeUnit.java b/src/share/classes/java/util/concurrent/TimeUnit.java
index 5a18a5b01c01c45c0675213f35d44be898199b35..236e553bc6c6b773971bcee742822c0645200476 100644
--- a/src/share/classes/java/util/concurrent/TimeUnit.java
+++ b/src/share/classes/java/util/concurrent/TimeUnit.java
@@ -53,12 +53,12 @@ package java.util.concurrent;
* java.util.concurrent.locks.Lock lock} is not available:
*
*
Lock lock = ...;
- * if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...
+ * if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...
*
* while this code will timeout in 50 seconds:
*
* Lock lock = ...;
- * if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...
+ * if (lock.tryLock(50L, TimeUnit.SECONDS)) ...
*
*
* Note however, that there is no guarantee that a particular timeout
@@ -291,7 +291,8 @@ public enum TimeUnit {
abstract int excessNanos(long d, long m);
/**
- * Performs a timed Object.wait using this time unit.
+ * Performs a timed {@link Object#wait(long, int) Object.wait}
+ * using this time unit.
* This is a convenience method that converts timeout arguments
* into the form required by the Object.wait method.
*
@@ -299,21 +300,22 @@ public enum TimeUnit {
* method (see {@link BlockingQueue#poll BlockingQueue.poll})
* using:
*
- * public synchronized Object poll(long timeout, TimeUnit unit) throws InterruptedException {
- * while (empty) {
- * unit.timedWait(this, timeout);
- * ...
- * }
- * }
+ * {@code
+ * public synchronized Object poll(long timeout, TimeUnit unit)
+ * throws InterruptedException {
+ * while (empty) {
+ * unit.timedWait(this, timeout);
+ * ...
+ * }
+ * }}
*
* @param obj the object to wait on
* @param timeout the maximum time to wait. If less than
* or equal to zero, do not wait at all.
- * @throws InterruptedException if interrupted while waiting.
- * @see Object#wait(long, int)
+ * @throws InterruptedException if interrupted while waiting
*/
public void timedWait(Object obj, long timeout)
- throws InterruptedException {
+ throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
@@ -322,17 +324,18 @@ public enum TimeUnit {
}
/**
- * Performs a timed Thread.join using this time unit.
+ * Performs a timed {@link Thread#join(long, int) Thread.join}
+ * using this time unit.
* This is a convenience method that converts time arguments into the
* form required by the Thread.join method.
+ *
* @param thread the thread to wait for
* @param timeout the maximum time to wait. If less than
* or equal to zero, do not wait at all.
- * @throws InterruptedException if interrupted while waiting.
- * @see Thread#join(long, int)
+ * @throws InterruptedException if interrupted while waiting
*/
public void timedJoin(Thread thread, long timeout)
- throws InterruptedException {
+ throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
@@ -341,13 +344,14 @@ public enum TimeUnit {
}
/**
- * Performs a Thread.sleep using this unit.
+ * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
+ * this time unit.
* This is a convenience method that converts time arguments into the
* form required by the Thread.sleep method.
+ *
* @param timeout the minimum time to sleep. If less than
* or equal to zero, do not sleep at all.
- * @throws InterruptedException if interrupted while sleeping.
- * @see Thread#sleep
+ * @throws InterruptedException if interrupted while sleeping
*/
public void sleep(long timeout) throws InterruptedException {
if (timeout > 0) {
diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java
index 9073254b12264bf163b55716d1fb8ec7818db4f6..7ea3a8012d5f40712be2a7804adecdebd6ac01b5 100644
--- a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java
+++ b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java
@@ -55,7 +55,7 @@ import java.lang.reflect.*;
* @author Doug Lea
* @param The type of the object holding the updatable field
*/
-public abstract class AtomicIntegerFieldUpdater {
+public abstract class AtomicIntegerFieldUpdater {
/**
* Creates and returns an updater for objects with the given field.
* The Class argument is needed to check that reflective types and
@@ -279,7 +279,7 @@ public abstract class AtomicIntegerFieldUpdater {
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
- } catch(Exception ex) {
+ } catch (Exception ex) {
throw new RuntimeException(ex);
}
diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java
index 8a81dbc9a8834e59a5eba639c40bca989a6f2cd2..22a1d5eecbea767bc38f5891d91a6e8b23c9bef4 100644
--- a/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java
+++ b/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java
@@ -55,7 +55,7 @@ import java.lang.reflect.*;
* @author Doug Lea
* @param The type of the object holding the updatable field
*/
-public abstract class AtomicLongFieldUpdater {
+public abstract class AtomicLongFieldUpdater {
/**
* Creates and returns an updater for objects with the given field.
* The Class argument is needed to check that reflective types and
@@ -278,7 +278,7 @@ public abstract class AtomicLongFieldUpdater {
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
- } catch(Exception ex) {
+ } catch (Exception ex) {
throw new RuntimeException(ex);
}
@@ -331,7 +331,7 @@ public abstract class AtomicLongFieldUpdater {
if (cclass.isInstance(obj)) {
return;
}
- throw new RuntimeException (
+ throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
@@ -361,7 +361,7 @@ public abstract class AtomicLongFieldUpdater {
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
- } catch(Exception ex) {
+ } catch (Exception ex) {
throw new RuntimeException(ex);
}
@@ -387,7 +387,7 @@ public abstract class AtomicLongFieldUpdater {
public boolean compareAndSet(T obj, long expect, long update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
- synchronized(this) {
+ synchronized (this) {
long v = unsafe.getLong(obj, offset);
if (v != expect)
return false;
@@ -402,7 +402,7 @@ public abstract class AtomicLongFieldUpdater {
public void set(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
- synchronized(this) {
+ synchronized (this) {
unsafe.putLong(obj, offset, newValue);
}
}
@@ -413,7 +413,7 @@ public abstract class AtomicLongFieldUpdater {
public long get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
- synchronized(this) {
+ synchronized (this) {
return unsafe.getLong(obj, offset);
}
}
@@ -422,7 +422,7 @@ public abstract class AtomicLongFieldUpdater {
if (cclass.isInstance(obj)) {
return;
}
- throw new RuntimeException (
+ throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java
index ec2083294707cb00d7f5abd6b768516b20d5364f..c58fd30139f487bb7392a11d8ad04a913e6cc37a 100644
--- a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java
+++ b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java
@@ -45,13 +45,13 @@ import java.lang.reflect.*;
* independently subject to atomic updates. For example, a tree node
* might be declared as
*
- *
+ * {@code
* class Node {
* private volatile Node left, right;
*
- * private static final AtomicReferenceFieldUpdater<Node, Node> leftUpdater =
+ * private static final AtomicReferenceFieldUpdater leftUpdater =
* AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "left");
- * private static AtomicReferenceFieldUpdater<Node, Node> rightUpdater =
+ * private static AtomicReferenceFieldUpdater rightUpdater =
* AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "right");
*
* Node getLeft() { return left; }
@@ -59,8 +59,7 @@ import java.lang.reflect.*;
* return leftUpdater.compareAndSet(this, expect, update);
* }
* // ... and so on
- * }
- *
+ * }}
*
* Note that the guarantees of the {@code compareAndSet}
* method in this class are weaker than in other atomic classes.
@@ -74,7 +73,7 @@ import java.lang.reflect.*;
* @param The type of the object holding the updatable field
* @param The type of the field
*/
-public abstract class AtomicReferenceFieldUpdater {
+public abstract class AtomicReferenceFieldUpdater {
/**
* Creates and returns an updater for objects with the given field.
@@ -291,7 +290,7 @@ public abstract class AtomicReferenceFieldUpdater {
if (cclass.isInstance(obj)) {
return;
}
- throw new RuntimeException (
+ throw new RuntimeException(
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
diff --git a/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
index c45c2cef1f4739f085ffdc86aada4f3f25dbbecf..605276e27b517b60c40b4dd3b0e0fed03653d14c 100644
--- a/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
+++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
@@ -990,7 +990,8 @@ public abstract class AbstractQueuedLongSynchronizer
* can represent anything you like.
* @throws InterruptedException if the current thread is interrupted
*/
- public final void acquireInterruptibly(long arg) throws InterruptedException {
+ public final void acquireInterruptibly(long arg)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
@@ -1014,7 +1015,8 @@ public abstract class AbstractQueuedLongSynchronizer
* @return {@code true} if acquired; {@code false} if timed out
* @throws InterruptedException if the current thread is interrupted
*/
- public final boolean tryAcquireNanos(long arg, long nanosTimeout) throws InterruptedException {
+ public final boolean tryAcquireNanos(long arg, long nanosTimeout)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) ||
@@ -1070,7 +1072,8 @@ public abstract class AbstractQueuedLongSynchronizer
* you like.
* @throws InterruptedException if the current thread is interrupted
*/
- public final void acquireSharedInterruptibly(long arg) throws InterruptedException {
+ public final void acquireSharedInterruptibly(long arg)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
@@ -1093,7 +1096,8 @@ public abstract class AbstractQueuedLongSynchronizer
* @return {@code true} if acquired; {@code false} if timed out
* @throws InterruptedException if the current thread is interrupted
*/
- public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout) throws InterruptedException {
+ public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquireShared(arg) >= 0 ||
@@ -1841,7 +1845,8 @@ public abstract class AbstractQueuedLongSynchronizer
* - If interrupted while blocked in step 4, throw InterruptedException.
*
*/
- public final long awaitNanos(long nanosTimeout) throws InterruptedException {
+ public final long awaitNanos(long nanosTimeout)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
@@ -1885,7 +1890,8 @@ public abstract class AbstractQueuedLongSynchronizer
*
- If timed out while blocked in step 4, return false, else true.
*
*/
- public final boolean awaitUntil(Date deadline) throws InterruptedException {
+ public final boolean awaitUntil(Date deadline)
+ throws InterruptedException {
if (deadline == null)
throw new NullPointerException();
long abstime = deadline.getTime();
@@ -1928,7 +1934,8 @@ public abstract class AbstractQueuedLongSynchronizer
*
- If timed out while blocked in step 4, return false, else true.
*
*/
- public final boolean await(long time, TimeUnit unit) throws InterruptedException {
+ public final boolean await(long time, TimeUnit unit)
+ throws InterruptedException {
if (unit == null)
throw new NullPointerException();
long nanosTimeout = unit.toNanos(time);
@@ -2084,7 +2091,7 @@ public abstract class AbstractQueuedLongSynchronizer
/**
* CAS waitStatus field of a node.
*/
- private final static boolean compareAndSetWaitStatus(Node node,
+ private static final boolean compareAndSetWaitStatus(Node node,
int expect,
int update) {
return unsafe.compareAndSwapInt(node, waitStatusOffset,
@@ -2094,7 +2101,7 @@ public abstract class AbstractQueuedLongSynchronizer
/**
* CAS next field of a node.
*/
- private final static boolean compareAndSetNext(Node node,
+ private static final boolean compareAndSetNext(Node node,
Node expect,
Node update) {
return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
diff --git a/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
index d17c5d08d0ea11723e93fdd1c24d8c53d9acc035..8075aea7dea47df3fa62fd0b2e2d95ea76dc6a6c 100644
--- a/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
+++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
@@ -265,7 +265,7 @@ import sun.misc.Unsafe;
* boolean isSignalled() { return getState() != 0; }
*
* protected int tryAcquireShared(int ignore) {
- * return isSignalled()? 1 : -1;
+ * return isSignalled() ? 1 : -1;
* }
*
* protected boolean tryReleaseShared(int ignore) {
@@ -1213,7 +1213,8 @@ public abstract class AbstractQueuedSynchronizer
* can represent anything you like.
* @throws InterruptedException if the current thread is interrupted
*/
- public final void acquireInterruptibly(int arg) throws InterruptedException {
+ public final void acquireInterruptibly(int arg)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
@@ -1237,7 +1238,8 @@ public abstract class AbstractQueuedSynchronizer
* @return {@code true} if acquired; {@code false} if timed out
* @throws InterruptedException if the current thread is interrupted
*/
- public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
+ public final boolean tryAcquireNanos(int arg, long nanosTimeout)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) ||
@@ -1293,7 +1295,8 @@ public abstract class AbstractQueuedSynchronizer
* you like.
* @throws InterruptedException if the current thread is interrupted
*/
- public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
+ public final void acquireSharedInterruptibly(int arg)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
@@ -1316,7 +1319,8 @@ public abstract class AbstractQueuedSynchronizer
* @return {@code true} if acquired; {@code false} if timed out
* @throws InterruptedException if the current thread is interrupted
*/
- public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException {
+ public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquireShared(arg) >= 0 ||
@@ -2062,7 +2066,8 @@ public abstract class AbstractQueuedSynchronizer
*
- If interrupted while blocked in step 4, throw InterruptedException.
*
*/
- public final long awaitNanos(long nanosTimeout) throws InterruptedException {
+ public final long awaitNanos(long nanosTimeout)
+ throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
@@ -2106,7 +2111,8 @@ public abstract class AbstractQueuedSynchronizer
*
- If timed out while blocked in step 4, return false, else true.
*
*/
- public final boolean awaitUntil(Date deadline) throws InterruptedException {
+ public final boolean awaitUntil(Date deadline)
+ throws InterruptedException {
if (deadline == null)
throw new NullPointerException();
long abstime = deadline.getTime();
@@ -2149,7 +2155,8 @@ public abstract class AbstractQueuedSynchronizer
*
- If timed out while blocked in step 4, return false, else true.
*
*/
- public final boolean await(long time, TimeUnit unit) throws InterruptedException {
+ public final boolean await(long time, TimeUnit unit)
+ throws InterruptedException {
if (unit == null)
throw new NullPointerException();
long nanosTimeout = unit.toNanos(time);
@@ -2305,7 +2312,7 @@ public abstract class AbstractQueuedSynchronizer
/**
* CAS waitStatus field of a node.
*/
- private final static boolean compareAndSetWaitStatus(Node node,
+ private static final boolean compareAndSetWaitStatus(Node node,
int expect,
int update) {
return unsafe.compareAndSwapInt(node, waitStatusOffset,
@@ -2315,7 +2322,7 @@ public abstract class AbstractQueuedSynchronizer
/**
* CAS next field of a node.
*/
- private final static boolean compareAndSetNext(Node node,
+ private static final boolean compareAndSetNext(Node node,
Node expect,
Node update) {
return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
diff --git a/src/share/classes/java/util/concurrent/locks/LockSupport.java b/src/share/classes/java/util/concurrent/locks/LockSupport.java
index 9751f418c17270ced5511dcf844f7c2470b4f107..9c966406b313d0ab39c0c60cc83a127bceb34a9f 100644
--- a/src/share/classes/java/util/concurrent/locks/LockSupport.java
+++ b/src/share/classes/java/util/concurrent/locks/LockSupport.java
@@ -200,8 +200,8 @@ public class LockSupport {
*
- Some other thread invokes {@link #unpark unpark} with the
* current thread as the target; or
*
- *
- Some other thread {@linkplain Thread#interrupt interrupts} the current
- * thread; or
+ *
- Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread; or
*
*
- The specified waiting time elapses; or
*
diff --git a/src/share/classes/java/util/concurrent/locks/ReentrantLock.java b/src/share/classes/java/util/concurrent/locks/ReentrantLock.java
index 9cc3bf4d011159dae01f1ebd73090c1a1002100e..4cbc562b82015113a30083570f71c442ea966e44 100644
--- a/src/share/classes/java/util/concurrent/locks/ReentrantLock.java
+++ b/src/share/classes/java/util/concurrent/locks/ReentrantLock.java
@@ -116,7 +116,7 @@ public class ReentrantLock implements Lock, java.io.Serializable {
* into fair and nonfair versions below. Uses AQS state to
* represent the number of holds on the lock.
*/
- static abstract class Sync extends AbstractQueuedSynchronizer {
+ abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
@@ -200,7 +200,7 @@ public class ReentrantLock implements Lock, java.io.Serializable {
/**
* Sync object for non-fair locks
*/
- final static class NonfairSync extends Sync {
+ static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
@@ -222,7 +222,7 @@ public class ReentrantLock implements Lock, java.io.Serializable {
/**
* Sync object for fair locks
*/
- final static class FairSync extends Sync {
+ static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
@@ -269,7 +269,7 @@ public class ReentrantLock implements Lock, java.io.Serializable {
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
- sync = (fair)? new FairSync() : new NonfairSync();
+ sync = fair ? new FairSync() : new NonfairSync();
}
/**
@@ -440,7 +440,8 @@ public class ReentrantLock implements Lock, java.io.Serializable {
* @throws NullPointerException if the time unit is null
*
*/
- public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
+ public boolean tryLock(long timeout, TimeUnit unit)
+ throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
diff --git a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
index b327b65c4de00b85693c4dc6a0a37eb63aefdbbd..39b9c0e894dfaf8080e20ba2d9a2cb8b2da14035 100644
--- a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
+++ b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
@@ -155,7 +155,7 @@ import java.util.*;
* }
* // Downgrade by acquiring read lock before releasing write lock
* rwl.readLock().lock();
- * } finally {
+ * } finally {
* rwl.writeLock().unlock(); // Unlock write, still hold read
* }
* }
@@ -215,7 +215,8 @@ import java.util.*;
* @author Doug Lea
*
*/
-public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
+public class ReentrantReadWriteLock
+ implements ReadWriteLock, java.io.Serializable {
private static final long serialVersionUID = -6992448646407690164L;
/** Inner class providing readlock */
private final ReentrantReadWriteLock.ReadLock readerLock;
@@ -251,7 +252,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
* Synchronization implementation for ReentrantReadWriteLock.
* Subclassed into fair and nonfair versions.
*/
- static abstract class Sync extends AbstractQueuedSynchronizer {
+ abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 6317671515068378041L;
/*
@@ -618,7 +619,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
final Thread getOwner() {
// Must read state before owner to ensure memory consistency
- return ((exclusiveCount(getState()) == 0)?
+ return ((exclusiveCount(getState()) == 0) ?
null :
getExclusiveOwnerThread());
}
@@ -669,7 +670,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
/**
* Nonfair version of Sync
*/
- final static class NonfairSync extends Sync {
+ static final class NonfairSync extends Sync {
private static final long serialVersionUID = -8159625535654395037L;
final boolean writerShouldBlock() {
return false; // writers can always barge
@@ -689,7 +690,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
/**
* Fair version of Sync
*/
- final static class FairSync extends Sync {
+ static final class FairSync extends Sync {
private static final long serialVersionUID = -2274990926593161451L;
final boolean writerShouldBlock() {
return hasQueuedPredecessors();
@@ -702,7 +703,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
/**
* The lock returned by method {@link ReentrantReadWriteLock#readLock}.
*/
- public static class ReadLock implements Lock, java.io.Serializable {
+ public static class ReadLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -5992448646407690164L;
private final Sync sync;
@@ -867,7 +868,8 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
* @throws NullPointerException if the time unit is null
*
*/
- public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
+ public boolean tryLock(long timeout, TimeUnit unit)
+ throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
@@ -908,7 +910,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
/**
* The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
*/
- public static class WriteLock implements Lock, java.io.Serializable {
+ public static class WriteLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -4992448646407690164L;
private final Sync sync;
@@ -1108,7 +1110,8 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
* @throws NullPointerException if the time unit is null
*
*/
- public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
+ public boolean tryLock(long timeout, TimeUnit unit)
+ throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
diff --git a/src/share/classes/javax/security/auth/Policy.java b/src/share/classes/javax/security/auth/Policy.java
index 6c508b2ce95eb5cd68ae57ee9e21c0250893796d..88264b3fc49e9d1f17b5f8bd7f9c43a901ca9d7c 100644
--- a/src/share/classes/javax/security/auth/Policy.java
+++ b/src/share/classes/javax/security/auth/Policy.java
@@ -25,6 +25,9 @@
package javax.security.auth;
+import java.security.Security;
+import sun.security.util.Debug;
+
/**
*
This is an abstract class for representing the system policy for
* Subject-based authorization. A subclass implementation
@@ -159,6 +162,10 @@ public abstract class Policy {
private static Policy policy;
private static ClassLoader contextClassLoader;
+ // true if a custom (not com.sun.security.auth.PolicyFile) system-wide
+ // policy object is set
+ private static boolean isCustomPolicy;
+
static {
contextClassLoader = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction() {
@@ -234,6 +241,8 @@ public abstract class Policy {
contextClassLoader).newInstance();
}
});
+ isCustomPolicy =
+ !finalClass.equals("com.sun.security.auth.PolicyFile");
} catch (Exception e) {
throw new SecurityException
(sun.security.util.ResourcesMgr.getString
@@ -265,6 +274,46 @@ public abstract class Policy {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(new AuthPermission("setPolicy"));
Policy.policy = policy;
+ // all non-null policy objects are assumed to be custom
+ isCustomPolicy = policy != null ? true : false;
+ }
+
+ /**
+ * Returns true if a custom (not com.sun.security.auth.PolicyFile)
+ * system-wide policy object has been set or installed. This method is
+ * called by SubjectDomainCombiner to provide backwards compatibility for
+ * developers that provide their own javax.security.auth.Policy
+ * implementations.
+ *
+ * @return true if a custom (not com.sun.security.auth.PolicyFile)
+ * system-wide policy object has been set; false otherwise
+ */
+ static boolean isCustomPolicySet(Debug debug) {
+ if (policy != null) {
+ if (debug != null && isCustomPolicy) {
+ debug.println("Providing backwards compatibility for " +
+ "javax.security.auth.policy implementation: " +
+ policy.toString());
+ }
+ return isCustomPolicy;
+ }
+ // check if custom policy has been set using auth.policy.provider prop
+ String policyClass = java.security.AccessController.doPrivileged
+ (new java.security.PrivilegedAction() {
+ public String run() {
+ return Security.getProperty("auth.policy.provider");
+ }
+ });
+ if (policyClass != null
+ && !policyClass.equals("com.sun.security.auth.PolicyFile")) {
+ if (debug != null) {
+ debug.println("Providing backwards compatibility for " +
+ "javax.security.auth.policy implementation: " +
+ policyClass);
+ }
+ return true;
+ }
+ return false;
}
/**
diff --git a/src/share/classes/javax/security/auth/SubjectDomainCombiner.java b/src/share/classes/javax/security/auth/SubjectDomainCombiner.java
index 00d57f6c6daa59684d91a6a69842995cd2f72bcd..9dc82fc0153a37f72c6114847a4ecec21e569f68 100644
--- a/src/share/classes/javax/security/auth/SubjectDomainCombiner.java
+++ b/src/share/classes/javax/security/auth/SubjectDomainCombiner.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -26,8 +26,6 @@
package javax.security.auth;
import java.security.AccessController;
-import java.security.AccessControlContext;
-import java.security.AllPermission;
import java.security.Permission;
import java.security.Permissions;
import java.security.PermissionCollection;
@@ -35,10 +33,8 @@ import java.security.Policy;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
-import java.lang.ClassLoader;
import java.security.Security;
import java.util.Set;
-import java.util.Iterator;
import java.util.WeakHashMap;
import java.lang.ref.WeakReference;
@@ -61,7 +57,8 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner {
"\t[SubjectDomainCombiner]");
// Note: check only at classloading time, not dynamically during combine()
- private static final boolean useJavaxPolicy = compatPolicy();
+ private static final boolean useJavaxPolicy =
+ javax.security.auth.Policy.isCustomPolicySet(debug);
// Relevant only when useJavaxPolicy is true
private static final boolean allowCaching =
@@ -202,8 +199,8 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner {
return null;
}
- // maintain backwards compatibility for people who provide
- // their own javax.security.auth.Policy implementations
+ // maintain backwards compatibility for developers who provide
+ // their own custom javax.security.auth.Policy implementations
if (useJavaxPolicy) {
return combineJavaxPolicy(currentDomains, assignedDomains);
}
@@ -476,8 +473,7 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner {
String s = AccessController.doPrivileged
(new PrivilegedAction() {
public String run() {
- return java.security.Security.getProperty
- ("cache.auth.policy");
+ return Security.getProperty("cache.auth.policy");
}
});
if (s != null) {
@@ -488,29 +484,6 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner {
return true;
}
- // maintain backwards compatibility for people who provide
- // their own javax.security.auth.Policy implementations
- private static boolean compatPolicy() {
- javax.security.auth.Policy javaxPolicy = AccessController.doPrivileged
- (new PrivilegedAction() {
- public javax.security.auth.Policy run() {
- return javax.security.auth.Policy.getPolicy();
- }
- });
-
- if (!(javaxPolicy instanceof com.sun.security.auth.PolicyFile)) {
- if (debug != null) {
- debug.println("Providing backwards compatibility for " +
- "javax.security.auth.policy implementation: " +
- javaxPolicy.toString());
- }
-
- return true;
- } else {
- return false;
- }
- }
-
private static void printInputDomains(ProtectionDomain[] currentDomains,
ProtectionDomain[] assignedDomains) {
if (currentDomains == null || currentDomains.length == 0) {
diff --git a/src/share/classes/javax/swing/GroupLayout.java b/src/share/classes/javax/swing/GroupLayout.java
index 7628076a99473e2a368b816f09d82aea90967220..9219932776ed301462aa613e838a81df0d352019 100644
--- a/src/share/classes/javax/swing/GroupLayout.java
+++ b/src/share/classes/javax/swing/GroupLayout.java
@@ -653,6 +653,10 @@ public class GroupLayout implements LayoutManager2 {
*/
public ParallelGroup createParallelGroup(Alignment alignment,
boolean resizable){
+ if (alignment == null) {
+ throw new IllegalArgumentException("alignment must be non null");
+ }
+
if (alignment == Alignment.BASELINE) {
return new BaselineGroup(resizable);
}
diff --git a/src/share/classes/javax/swing/JComponent.java b/src/share/classes/javax/swing/JComponent.java
index 6f017402ec7e01e9d8f6b1bc480a35ae7c38e0e8..78fddfcb11bb877c93da708b0fb05fa7d65ca947 100644
--- a/src/share/classes/javax/swing/JComponent.java
+++ b/src/share/classes/javax/swing/JComponent.java
@@ -4734,6 +4734,8 @@ public abstract class JComponent extends Container implements Serializable,
* Notifies this component that it now has a parent component.
* When this method is invoked, the chain of parent components is
* set up with KeyboardAction event listeners.
+ * This method is called by the toolkit internally and should
+ * not be called directly by programs.
*
* @see #registerKeyboardAction
*/
@@ -4750,6 +4752,8 @@ public abstract class JComponent extends Container implements Serializable,
* Notifies this component that it no longer has a parent component.
* When this method is invoked, any KeyboardActions
* set up in the the chain of parent components are removed.
+ * This method is called by the toolkit internally and should
+ * not be called directly by programs.
*
* @see #registerKeyboardAction
*/
diff --git a/src/share/classes/javax/swing/Popup.java b/src/share/classes/javax/swing/Popup.java
index a77d574d72ecb4d45d77603ecad34d236913ee20..83cd7d6d789c6e9462fc241799e783f86a57adb4 100644
--- a/src/share/classes/javax/swing/Popup.java
+++ b/src/share/classes/javax/swing/Popup.java
@@ -156,7 +156,8 @@ public class Popup {
component.setLocation(ownerX, ownerY);
component.getContentPane().add(contents, BorderLayout.CENTER);
- contents.invalidate();
+ component.invalidate();
+ component.validate();
if(component.isVisible()) {
// Do not call pack() if window is not visible to
// avoid early native peer creation
diff --git a/src/share/classes/javax/swing/text/DefaultHighlighter.java b/src/share/classes/javax/swing/text/DefaultHighlighter.java
index d90128b82ac17f81f6503b5334405eba9d8a5dde..dc68ae474fd60305ae2e796cc0ad6ef44b1a93ae 100644
--- a/src/share/classes/javax/swing/text/DefaultHighlighter.java
+++ b/src/share/classes/javax/swing/text/DefaultHighlighter.java
@@ -113,6 +113,14 @@ public class DefaultHighlighter extends LayeredHighlighter {
* @exception BadLocationException if the specified location is invalid
*/
public Object addHighlight(int p0, int p1, Highlighter.HighlightPainter p) throws BadLocationException {
+ if (p0 < 0) {
+ throw new BadLocationException("Invalid start offset", p0);
+ }
+
+ if (p1 < p0) {
+ throw new BadLocationException("Invalid end offset", p1);
+ }
+
Document doc = component.getDocument();
HighlightInfo i = (getDrawsLayeredHighlights() &&
(p instanceof LayeredHighlighter.LayerPainter)) ?
@@ -217,6 +225,14 @@ public class DefaultHighlighter extends LayeredHighlighter {
* @exception BadLocationException if the specified location is invalid
*/
public void changeHighlight(Object tag, int p0, int p1) throws BadLocationException {
+ if (p0 < 0) {
+ throw new BadLocationException("Invalid beginning of the range", p0);
+ }
+
+ if (p1 < p0) {
+ throw new BadLocationException("Invalid end of the range", p1);
+ }
+
Document doc = component.getDocument();
if (tag instanceof LayeredHighlightInfo) {
LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag;
diff --git a/src/share/classes/sun/awt/UngrabEvent.java b/src/share/classes/sun/awt/UngrabEvent.java
index e27e04068304e6aabdaebbd2be39de5a8ab1911a..7c1b8ecf9f515092238f9c7841c4dcf982bec1dd 100644
--- a/src/share/classes/sun/awt/UngrabEvent.java
+++ b/src/share/classes/sun/awt/UngrabEvent.java
@@ -40,8 +40,10 @@ import java.awt.Component;
* To listen for this event, install AWTEventListener with {@value sun.awt.SunToolkit#GRAB_EVENT_MASK}
*/
public class UngrabEvent extends AWTEvent {
+ private final static int UNGRAB_EVENT_ID = 1998;
+
public UngrabEvent(Component source) {
- super(source, 0xffff);
+ super(source, UNGRAB_EVENT_ID);
}
public String toString() {
diff --git a/src/share/classes/sun/launcher/LauncherHelper.java b/src/share/classes/sun/launcher/LauncherHelper.java
index cba795968c69c0875894aed1da6f67ebe74ac60f..dbaebc0ee862d9a465cc4b7ae77cef0e8987425f 100644
--- a/src/share/classes/sun/launcher/LauncherHelper.java
+++ b/src/share/classes/sun/launcher/LauncherHelper.java
@@ -44,8 +44,16 @@ import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.math.RoundingMode;
import java.util.ResourceBundle;
import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
@@ -59,6 +67,17 @@ public enum LauncherHelper {
private static StringBuilder outBuf = new StringBuilder();
private static ResourceBundle javarb = null;
+
+ private static final String INDENT = " ";
+ private static final String VM_SETTINGS = "VM settings:";
+ private static final String PROP_SETTINGS = "Property settings:";
+ private static final String LOCALE_SETTINGS = "Locale settings:";
+
+ private static final long K = 1024;
+ private static final long M = K * K;
+ private static final long G = M * K;
+ private static final long T = G * K;
+
private static synchronized ResourceBundle getLauncherResourceBundle() {
if (javarb == null) {
javarb = ResourceBundle.getBundle(defaultBundleName);
@@ -66,6 +85,184 @@ public enum LauncherHelper {
return javarb;
}
+ /*
+ * A method called by the launcher to print out the standard settings,
+ * by default -XshowSettings is equivalent to -XshowSettings:all,
+ * Specific information may be gotten by using suboptions with possible
+ * values vm, properties and locale.
+ *
+ * printToStderr: choose between stdout and stderr
+ *
+ * optionFlag: specifies which options to print default is all other
+ * possible values are vm, properties, locale.
+ *
+ * maxHeapSize: in bytes, as set by the launcher, a zero-value indicates
+ * this code should determine this value, using a suitable method.
+ *
+ * stackSize: in bytes, as set by the launcher, a zero-value indicates
+ * this code determine this value, using a suitable method.
+ */
+ static void showSettings(boolean printToStderr, String optionFlag,
+ long maxHeapSize, long stackSize, boolean isServer) {
+
+ PrintStream ostream = (printToStderr) ? System.err : System.out;
+ String opts[] = optionFlag.split(":");
+ String optStr = (opts.length > 1 && opts[1] != null)
+ ? opts[1].trim()
+ : "all";
+ switch (optStr) {
+ case "vm":
+ printVmSettings(ostream, maxHeapSize, stackSize, isServer);
+ break;
+ case "properties":
+ printProperties(ostream);
+ break;
+ case "locale":
+ printLocale(ostream);
+ break;
+ default:
+ printVmSettings(ostream, maxHeapSize, stackSize, isServer);
+ printProperties(ostream);
+ printLocale(ostream);
+ break;
+ }
+ }
+
+ /*
+ * prints the main vm settings subopt/section
+ */
+ private static void printVmSettings(PrintStream ostream, long maxHeapSize,
+ long stackSize, boolean isServer) {
+
+ ostream.println(VM_SETTINGS);
+ if (stackSize != 0L) {
+ ostream.println(INDENT + "Stack Size: " + scaleValue(stackSize));
+ }
+ if (maxHeapSize != 0L) {
+ ostream.println(INDENT + "Max. Heap Size: " + scaleValue(maxHeapSize));
+ } else {
+ ostream.println(INDENT + "Max. Heap Size (Estimated): "
+ + scaleValue(Runtime.getRuntime().maxMemory()));
+ }
+ ostream.println(INDENT + "Ergonomics Machine Class: "
+ + ((isServer) ? "server" : "client"));
+ ostream.println(INDENT + "Using VM: "
+ + System.getProperty("java.vm.name"));
+ ostream.println();
+ }
+
+ /*
+ * scale the incoming values to a human readable form, represented as
+ * K, M, G and T, see java.c parse_size for the scaled values and
+ * suffixes.
+ */
+
+ private static String scaleValue(double v) {
+ MathContext mc2 = new MathContext(3, RoundingMode.HALF_EVEN);
+
+ if (v >= K && v < M) {
+ return (new BigDecimal(v / K, mc2)).toPlainString() + "K";
+ } else if (v >= M && v < G) {
+ return (new BigDecimal(v / M, mc2)).toPlainString() + "M";
+ } else if (v >= G && v < T) {
+ return (new BigDecimal(v / G, mc2)).toPlainString() + "G";
+ } else if (v >= T) {
+ return (new BigDecimal(v / T, mc2)).toPlainString() + "T";
+ } else {
+ return String.format("%.0f", v);
+ }
+ }
+
+ /*
+ * prints the properties subopt/section
+ */
+ private static void printProperties(PrintStream ostream) {
+ Properties p = System.getProperties();
+ ostream.println(PROP_SETTINGS);
+ List sortedPropertyKeys = new ArrayList<>();
+ sortedPropertyKeys.addAll(p.stringPropertyNames());
+ Collections.sort(sortedPropertyKeys);
+ for (String x : sortedPropertyKeys) {
+ printPropertyValue(ostream, x, p.getProperty(x));
+ }
+ ostream.println();
+ }
+
+ private static boolean isPath(String key) {
+ return key.endsWith(".dirs") || key.endsWith(".path");
+ }
+
+ private static void printPropertyValue(PrintStream ostream,
+ String key, String value) {
+ ostream.print(INDENT + key + " = ");
+ if (key.equals("line.separator")) {
+ byte[] bytes = value.getBytes();
+ for (byte b : bytes) {
+ switch (b) {
+ case 0xd:
+ ostream.print("CR ");
+ break;
+ case 0xa:
+ ostream.print("LF ");
+ break;
+ default:
+ ostream.printf("0x%02X", b & 0xff);
+ break;
+ }
+ }
+ ostream.println();
+ return;
+ }
+ if (!isPath(key)) {
+ ostream.println(value);
+ return;
+ }
+ // pretty print the path values as a list
+ String[] values = value.split(System.getProperty("path.separator"));
+ int len = values.length;
+ for (int i = 0 ; i < len ; i++) {
+ if (i == 0) { // first line treated specially
+ ostream.println(values[i]);
+ } else { // following lines prefix with indents
+ ostream.print(INDENT + INDENT);
+ ostream.println(values[i]);
+ }
+ }
+ }
+
+ /*
+ * prints the locale subopt/section
+ */
+ private static void printLocale(PrintStream ostream) {
+ Locale locale = Locale.getDefault();
+ ostream.println(LOCALE_SETTINGS);
+ ostream.println(INDENT + "default locale = " + locale.getDisplayLanguage());
+ printLocales(ostream);
+ ostream.println();
+ }
+
+ private static void printLocales(PrintStream ostream) {
+ Locale[] locales = Locale.getAvailableLocales();
+ final int len = locales == null ? 0 : locales.length;
+ if (len < 1 ) {
+ return;
+ }
+ ostream.print(INDENT + "available locales = ");
+ final int last = len - 1 ;
+ for (int i = 0; i < last ; i++) {
+ ostream.print(locales[i]);
+ if (i != last) {
+ ostream.print(", ");
+ }
+ // print columns of 8
+ if ((i + 1) % 8 == 0) {
+ ostream.println();
+ ostream.print(INDENT + INDENT);
+ }
+ }
+ ostream.println(locales[last]);
+ }
+
/**
* A private helper method to get a localized message and also
* apply any arguments that we might pass.
diff --git a/src/share/classes/sun/launcher/resources/launcher.properties b/src/share/classes/sun/launcher/resources/launcher.properties
index e89d147a5bba82b96edc51d297343ec426729607..17ba48a13842ea68a03ea9231f69fc344b550e7e 100644
--- a/src/share/classes/sun/launcher/resources/launcher.properties
+++ b/src/share/classes/sun/launcher/resources/launcher.properties
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 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
@@ -97,7 +97,15 @@ java.launcher.X.usage=\
\ -Xcheck:jni perform additional checks for JNI functions\n\
\ -Xshare:off do not attempt to use shared class data\n\
\ -Xshare:auto use shared class data if possible (default)\n\
-\ -Xshare:on require using shared class data, otherwise fail.\n\n\
+\ -Xshare:on require using shared class data, otherwise fail.\n\
+\ -XshowSettings show all settings and continue\n\
+\ -XshowSettings:all\n\
+\ show all settings and continue\n\
+\ -XshowSettings:vm show all vm related settings and continue\n\
+\ -XshowSettings:properties\n\
+\ show all property settings and continue\n\
+\ -XshowSettings:locale\n\
+\ show all locale related settings and continue\n\n\
The -X options are non-standard and subject to change without notice.\n
java.launcher.cls.error1=\
diff --git a/src/share/classes/sun/misc/FpUtils.java b/src/share/classes/sun/misc/FpUtils.java
index 72ac47eee368e02c825fa9953f442410887dd6e0..21ea7c29a4431a7afb964fd03c57d2e345f6d5fa 100644
--- a/src/share/classes/sun/misc/FpUtils.java
+++ b/src/share/classes/sun/misc/FpUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -29,9 +29,9 @@ import sun.misc.FloatConsts;
import sun.misc.DoubleConsts;
/**
- * The class FpUtils contains static utility methods for
- * manipulating and inspecting float and
- * double floating-point numbers. These methods include
+ * The class {@code FpUtils} contains static utility methods for
+ * manipulating and inspecting {@code float} and
+ * {@code double} floating-point numbers. These methods include
* functionality recommended or required by the IEEE 754
* floating-point standard.
*
@@ -136,7 +136,7 @@ public class FpUtils {
// tests for exception cases.
/**
- * Returns unbiased exponent of a double.
+ * Returns unbiased exponent of a {@code double}.
*/
public static int getExponent(double d){
/*
@@ -149,7 +149,7 @@ public class FpUtils {
}
/**
- * Returns unbiased exponent of a float.
+ * Returns unbiased exponent of a {@code float}.
*/
public static int getExponent(float f){
/*
@@ -185,15 +185,15 @@ public class FpUtils {
* Returns the first floating-point argument with the sign of the
* second floating-point argument. Note that unlike the {@link
* FpUtils#copySign(double, double) copySign} method, this method
- * does not require NaN sign arguments to be treated
+ * does not require NaN {@code sign} arguments to be treated
* as positive values; implementations are permitted to treat some
* NaN arguments as positive and other NaN arguments as negative
* to allow greater performance.
*
* @param magnitude the parameter providing the magnitude of the result
* @param sign the parameter providing the sign of the result
- * @return a value with the magnitude of magnitude
- * and the sign of sign.
+ * @return a value with the magnitude of {@code magnitude}
+ * and the sign of {@code sign}.
* @author Joseph D. Darcy
*/
public static double rawCopySign(double magnitude, double sign) {
@@ -208,15 +208,15 @@ public class FpUtils {
* Returns the first floating-point argument with the sign of the
* second floating-point argument. Note that unlike the {@link
* FpUtils#copySign(float, float) copySign} method, this method
- * does not require NaN sign arguments to be treated
+ * does not require NaN {@code sign} arguments to be treated
* as positive values; implementations are permitted to treat some
* NaN arguments as positive and other NaN arguments as negative
* to allow greater performance.
*
* @param magnitude the parameter providing the magnitude of the result
* @param sign the parameter providing the sign of the result
- * @return a value with the magnitude of magnitude
- * and the sign of sign.
+ * @return a value with the magnitude of {@code magnitude}
+ * and the sign of {@code sign}.
* @author Joseph D. Darcy
*/
public static float rawCopySign(float magnitude, float sign) {
@@ -230,129 +230,129 @@ public class FpUtils {
/* ***************************************************************** */
/**
- * Returns true if the argument is a finite
- * floating-point value; returns false otherwise (for
+ * Returns {@code true} if the argument is a finite
+ * floating-point value; returns {@code false} otherwise (for
* NaN and infinity arguments).
*
- * @param d the double value to be tested
- * @return true if the argument is a finite
- * floating-point value, false otherwise.
+ * @param d the {@code double} value to be tested
+ * @return {@code true} if the argument is a finite
+ * floating-point value, {@code false} otherwise.
*/
public static boolean isFinite(double d) {
return Math.abs(d) <= DoubleConsts.MAX_VALUE;
}
/**
- * Returns true if the argument is a finite
- * floating-point value; returns false otherwise (for
+ * Returns {@code true} if the argument is a finite
+ * floating-point value; returns {@code false} otherwise (for
* NaN and infinity arguments).
*
- * @param f the float value to be tested
- * @return true if the argument is a finite
- * floating-point value, false otherwise.
+ * @param f the {@code float} value to be tested
+ * @return {@code true} if the argument is a finite
+ * floating-point value, {@code false} otherwise.
*/
public static boolean isFinite(float f) {
return Math.abs(f) <= FloatConsts.MAX_VALUE;
}
/**
- * Returns true if the specified number is infinitely
- * large in magnitude, false otherwise.
+ * Returns {@code true} if the specified number is infinitely
+ * large in magnitude, {@code false} otherwise.
*
* Note that this method is equivalent to the {@link
* Double#isInfinite(double) Double.isInfinite} method; the
* functionality is included in this class for convenience.
*
* @param d the value to be tested.
- * @return true if the value of the argument is positive
- * infinity or negative infinity; false otherwise.
+ * @return {@code true} if the value of the argument is positive
+ * infinity or negative infinity; {@code false} otherwise.
*/
public static boolean isInfinite(double d) {
return Double.isInfinite(d);
}
/**
- * Returns true if the specified number is infinitely
- * large in magnitude, false otherwise.
+ * Returns {@code true} if the specified number is infinitely
+ * large in magnitude, {@code false} otherwise.
*
*
Note that this method is equivalent to the {@link
* Float#isInfinite(float) Float.isInfinite} method; the
* functionality is included in this class for convenience.
*
* @param f the value to be tested.
- * @return true if the argument is positive infinity or
- * negative infinity; false otherwise.
+ * @return {@code true} if the argument is positive infinity or
+ * negative infinity; {@code false} otherwise.
*/
public static boolean isInfinite(float f) {
return Float.isInfinite(f);
}
/**
- * Returns true if the specified number is a
- * Not-a-Number (NaN) value, false otherwise.
+ * Returns {@code true} if the specified number is a
+ * Not-a-Number (NaN) value, {@code false} otherwise.
*
*
Note that this method is equivalent to the {@link
* Double#isNaN(double) Double.isNaN} method; the functionality is
* included in this class for convenience.
*
* @param d the value to be tested.
- * @return true if the value of the argument is NaN;
- * false otherwise.
+ * @return {@code true} if the value of the argument is NaN;
+ * {@code false} otherwise.
*/
public static boolean isNaN(double d) {
return Double.isNaN(d);
}
/**
- * Returns true if the specified number is a
- * Not-a-Number (NaN) value, false otherwise.
+ * Returns {@code true} if the specified number is a
+ * Not-a-Number (NaN) value, {@code false} otherwise.
*
*
Note that this method is equivalent to the {@link
* Float#isNaN(float) Float.isNaN} method; the functionality is
* included in this class for convenience.
*
* @param f the value to be tested.
- * @return true if the argument is NaN;
- * false otherwise.
+ * @return {@code true} if the argument is NaN;
+ * {@code false} otherwise.
*/
public static boolean isNaN(float f) {
return Float.isNaN(f);
}
/**
- * Returns true if the unordered relation holds
+ * Returns {@code true} if the unordered relation holds
* between the two arguments. When two floating-point values are
* unordered, one value is neither less than, equal to, nor
* greater than the other. For the unordered relation to be true,
- * at least one argument must be a NaN.
+ * at least one argument must be a {@code NaN}.
*
* @param arg1 the first argument
* @param arg2 the second argument
- * @return true if at least one argument is a NaN,
- * false otherwise.
+ * @return {@code true} if at least one argument is a NaN,
+ * {@code false} otherwise.
*/
public static boolean isUnordered(double arg1, double arg2) {
return isNaN(arg1) || isNaN(arg2);
}
/**
- * Returns true if the unordered relation holds
+ * Returns {@code true} if the unordered relation holds
* between the two arguments. When two floating-point values are
* unordered, one value is neither less than, equal to, nor
* greater than the other. For the unordered relation to be true,
- * at least one argument must be a NaN.
+ * at least one argument must be a {@code NaN}.
*
* @param arg1 the first argument
* @param arg2 the second argument
- * @return true if at least one argument is a NaN,
- * false otherwise.
+ * @return {@code true} if at least one argument is a NaN,
+ * {@code false} otherwise.
*/
public static boolean isUnordered(float arg1, float arg2) {
return isNaN(arg1) || isNaN(arg2);
}
/**
- * Returns unbiased exponent of a double; for
+ * Returns unbiased exponent of a {@code double}; for
* subnormal values, the number is treated as if it were
* normalized. That is for all finite, non-zero, positive numbers
* x, scalb(x, -ilogb(x)) is
@@ -378,7 +378,6 @@ public class FpUtils {
return (1<<30); // 2^30
else // infinite value
return (1<<28); // 2^28
- // break;
case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal
if(d == 0.0) {
@@ -414,18 +413,16 @@ public class FpUtils {
exponent < DoubleConsts.MIN_EXPONENT);
return exponent;
}
- // break;
default:
assert( exponent >= DoubleConsts.MIN_EXPONENT &&
exponent <= DoubleConsts.MAX_EXPONENT);
return exponent;
- // break;
}
}
/**
- * Returns unbiased exponent of a float; for
+ * Returns unbiased exponent of a {@code float}; for
* subnormal values, the number is treated as if it were
* normalized. That is for all finite, non-zero, positive numbers
* x, scalb(x, -ilogb(x)) is
@@ -451,7 +448,6 @@ public class FpUtils {
return (1<<30); // 2^30
else // infinite value
return (1<<28); // 2^28
- // break;
case FloatConsts.MIN_EXPONENT-1: // zero or subnormal
if(f == 0.0f) {
@@ -487,13 +483,11 @@ public class FpUtils {
exponent < FloatConsts.MIN_EXPONENT);
return exponent;
}
- // break;
default:
assert( exponent >= FloatConsts.MIN_EXPONENT &&
exponent <= FloatConsts.MAX_EXPONENT);
return exponent;
- // break;
}
}
@@ -534,22 +528,22 @@ public class FpUtils {
*/
/**
- * Return d ×
- * 2scale_factor rounded as if performed
+ * Return {@code d} ×
+ * 2{@code scale_factor} rounded as if performed
* by a single correctly rounded floating-point multiply to a
* member of the double value set. See §4.2.3
* of the Java
* Language Specification for a discussion of floating-point
* value sets. If the exponent of the result is between the
- * double's minimum exponent and maximum exponent,
+ * {@code double}'s minimum exponent and maximum exponent,
* the answer is calculated exactly. If the exponent of the
- * result would be larger than doubles's maximum
+ * result would be larger than {@code doubles}'s maximum
* exponent, an infinity is returned. Note that if the result is
- * subnormal, precision may be lost; that is, when scalb(x,
- * n) is subnormal, scalb(scalb(x, n), -n) may
+ * subnormal, precision may be lost; that is, when {@code scalb(x,
+ * n)} is subnormal, {@code scalb(scalb(x, n), -n)} may
* not equal x. When the result is non-NaN, the result has
- * the same sign as d.
+ * the same sign as {@code d}.
*
*
* Special cases:
@@ -562,8 +556,8 @@ public class FpUtils {
*
*
* @param d number to be scaled by a power of two.
- * @param scale_factor power of 2 used to scale d
- * @return d * 2scale_factor
+ * @param scale_factor power of 2 used to scale {@code d}
+ * @return {@code d * }2{@code scale_factor}
* @author Joseph D. Darcy
*/
public static double scalb(double d, int scale_factor) {
@@ -644,22 +638,22 @@ public class FpUtils {
}
/**
- * Return f ×
- * 2scale_factor rounded as if performed
+ * Return {@code f} ×
+ * 2{@code scale_factor} rounded as if performed
* by a single correctly rounded floating-point multiply to a
* member of the float value set. See §4.2.3
* of the Java
* Language Specification for a discussion of floating-point
* value set. If the exponent of the result is between the
- * float's minimum exponent and maximum exponent, the
+ * {@code float}'s minimum exponent and maximum exponent, the
* answer is calculated exactly. If the exponent of the result
- * would be larger than float's maximum exponent, an
+ * would be larger than {@code float}'s maximum exponent, an
* infinity is returned. Note that if the result is subnormal,
- * precision may be lost; that is, when scalb(x, n)
- * is subnormal, scalb(scalb(x, n), -n) may not equal
+ * precision may be lost; that is, when {@code scalb(x, n)}
+ * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal
* x. When the result is non-NaN, the result has the same
- * sign as f.
+ * sign as {@code f}.
*
*
* Special cases:
@@ -672,8 +666,8 @@ public class FpUtils {
*
*
* @param f number to be scaled by a power of two.
- * @param scale_factor power of 2 used to scale f
- * @return f * 2scale_factor
+ * @param scale_factor power of 2 used to scale {@code f}
+ * @return {@code f * }2{@code scale_factor}
* @author Joseph D. Darcy
*/
public static float scalb(float f, int scale_factor) {
@@ -709,34 +703,34 @@ public class FpUtils {
*
* - If either argument is a NaN, then NaN is returned.
*
- *
- If both arguments are signed zeros,
direction
+ * - If both arguments are signed zeros, {@code direction}
* is returned unchanged (as implied by the requirement of
* returning the second argument if the arguments compare as
* equal).
*
- *
- If
start is
- * ±Double.MIN_VALUE and direction
+ * - If {@code start} is
+ * ±{@code Double.MIN_VALUE} and {@code direction}
* has a value such that the result should have a smaller
- * magnitude, then a zero with the same sign as
start
+ * magnitude, then a zero with the same sign as {@code start}
* is returned.
*
- * - If
start is infinite and
- * direction has a value such that the result should
- * have a smaller magnitude, Double.MAX_VALUE with the
- * same sign as start is returned.
+ * - If {@code start} is infinite and
+ * {@code direction} has a value such that the result should
+ * have a smaller magnitude, {@code Double.MAX_VALUE} with the
+ * same sign as {@code start} is returned.
*
- *
- If
start is equal to ±
- * Double.MAX_VALUE and direction has a
+ * - If {@code start} is equal to ±
+ * {@code Double.MAX_VALUE} and {@code direction} has a
* value such that the result should have a larger magnitude, an
- * infinity with same sign as
start is returned.
+ * infinity with same sign as {@code start} is returned.
*
*
* @param start starting floating-point value
* @param direction value indicating which of
- * start's neighbors or start should
+ * {@code start}'s neighbors or {@code start} should
* be returned
- * @return The floating-point number adjacent to start in the
- * direction of direction.
+ * @return The floating-point number adjacent to {@code start} in the
+ * direction of {@code direction}.
* @author Joseph D. Darcy
*/
public static double nextAfter(double start, double direction) {
@@ -809,34 +803,34 @@ public class FpUtils {
*
* - If either argument is a NaN, then NaN is returned.
*
- *
- If both arguments are signed zeros, a
float
- * zero with the same sign as direction is returned
+ * - If both arguments are signed zeros, a {@code float}
+ * zero with the same sign as {@code direction} is returned
* (as implied by the requirement of returning the second argument
* if the arguments compare as equal).
*
- *
- If
start is
- * ±Float.MIN_VALUE and direction
+ * - If {@code start} is
+ * ±{@code Float.MIN_VALUE} and {@code direction}
* has a value such that the result should have a smaller
- * magnitude, then a zero with the same sign as
start
+ * magnitude, then a zero with the same sign as {@code start}
* is returned.
*
- * - If
start is infinite and
- * direction has a value such that the result should
- * have a smaller magnitude, Float.MAX_VALUE with the
- * same sign as start is returned.
+ * - If {@code start} is infinite and
+ * {@code direction} has a value such that the result should
+ * have a smaller magnitude, {@code Float.MAX_VALUE} with the
+ * same sign as {@code start} is returned.
*
- *
- If
start is equal to ±
- * Float.MAX_VALUE and direction has a
+ * - If {@code start} is equal to ±
+ * {@code Float.MAX_VALUE} and {@code direction} has a
* value such that the result should have a larger magnitude, an
- * infinity with same sign as
start is returned.
+ * infinity with same sign as {@code start} is returned.
*
*
* @param start starting floating-point value
* @param direction value indicating which of
- * start's neighbors or start should
+ * {@code start}'s neighbors or {@code start} should
* be returned
- * @return The floating-point number adjacent to start in the
- * direction of direction.
+ * @return The floating-point number adjacent to {@code start} in the
+ * direction of {@code direction}.
* @author Joseph D. Darcy
*/
public static float nextAfter(float start, double direction) {
@@ -900,12 +894,12 @@ public class FpUtils {
}
/**
- * Returns the floating-point value adjacent to d in
+ * Returns the floating-point value adjacent to {@code d} in
* the direction of positive infinity. This method is
- * semantically equivalent to nextAfter(d,
- * Double.POSITIVE_INFINITY); however, a nextUp
+ * semantically equivalent to {@code nextAfter(d,
+ * Double.POSITIVE_INFINITY)}; however, a {@code nextUp}
* implementation may run faster than its equivalent
- * nextAfter call.
+ * {@code nextAfter} call.
*
* Special Cases:
*
@@ -915,7 +909,7 @@ public class FpUtils {
* positive infinity.
*
* - If the argument is zero, the result is
- *
Double.MIN_VALUE
+ * {@code Double.MIN_VALUE}
*
*
*
@@ -935,12 +929,12 @@ public class FpUtils {
}
/**
- * Returns the floating-point value adjacent to f in
+ * Returns the floating-point value adjacent to {@code f} in
* the direction of positive infinity. This method is
- * semantically equivalent to nextAfter(f,
- * Double.POSITIVE_INFINITY); however, a nextUp
+ * semantically equivalent to {@code nextAfter(f,
+ * Double.POSITIVE_INFINITY)}; however, a {@code nextUp}
* implementation may run faster than its equivalent
- * nextAfter call.
+ * {@code nextAfter} call.
*
* Special Cases:
*
@@ -950,7 +944,7 @@ public class FpUtils {
* positive infinity.
*
* - If the argument is zero, the result is
- *
Float.MIN_VALUE
+ * {@code Float.MIN_VALUE}
*
*
*
@@ -970,12 +964,12 @@ public class FpUtils {
}
/**
- * Returns the floating-point value adjacent to d in
+ * Returns the floating-point value adjacent to {@code d} in
* the direction of negative infinity. This method is
- * semantically equivalent to nextAfter(d,
- * Double.NEGATIVE_INFINITY); however, a
- * nextDown implementation may run faster than its
- * equivalent nextAfter call.
+ * semantically equivalent to {@code nextAfter(d,
+ * Double.NEGATIVE_INFINITY)}; however, a
+ * {@code nextDown} implementation may run faster than its
+ * equivalent {@code nextAfter} call.
*
* Special Cases:
*
@@ -985,7 +979,7 @@ public class FpUtils {
* negative infinity.
*
* - If the argument is zero, the result is
- *
-Double.MIN_VALUE
+ * {@code -Double.MIN_VALUE}
*
*
*
@@ -1007,12 +1001,12 @@ public class FpUtils {
}
/**
- * Returns the floating-point value adjacent to f in
+ * Returns the floating-point value adjacent to {@code f} in
* the direction of negative infinity. This method is
- * semantically equivalent to nextAfter(f,
- * Float.NEGATIVE_INFINITY); however, a
- * nextDown implementation may run faster than its
- * equivalent nextAfter call.
+ * semantically equivalent to {@code nextAfter(f,
+ * Float.NEGATIVE_INFINITY)}; however, a
+ * {@code nextDown} implementation may run faster than its
+ * equivalent {@code nextAfter} call.
*
* Special Cases:
*
@@ -1022,7 +1016,7 @@ public class FpUtils {
* negative infinity.
*
* - If the argument is zero, the result is
- *
-Float.MIN_VALUE
+ * {@code -Float.MIN_VALUE}
*
*
*
@@ -1046,13 +1040,13 @@ public class FpUtils {
/**
* Returns the first floating-point argument with the sign of the
* second floating-point argument. For this method, a NaN
- * sign argument is always treated as if it were
+ * {@code sign} argument is always treated as if it were
* positive.
*
* @param magnitude the parameter providing the magnitude of the result
* @param sign the parameter providing the sign of the result
- * @return a value with the magnitude of magnitude
- * and the sign of sign.
+ * @return a value with the magnitude of {@code magnitude}
+ * and the sign of {@code sign}.
* @author Joseph D. Darcy
* @since 1.5
*/
@@ -1063,13 +1057,13 @@ public class FpUtils {
/**
* Returns the first floating-point argument with the sign of the
* second floating-point argument. For this method, a NaN
- * sign argument is always treated as if it were
+ * {@code sign} argument is always treated as if it were
* positive.
*
* @param magnitude the parameter providing the magnitude of the result
* @param sign the parameter providing the sign of the result
- * @return a value with the magnitude of magnitude
- * and the sign of sign.
+ * @return a value with the magnitude of {@code magnitude}
+ * and the sign of {@code sign}.
* @author Joseph D. Darcy
*/
public static float copySign(float magnitude, float sign) {
@@ -1078,8 +1072,8 @@ public class FpUtils {
/**
* Returns the size of an ulp of the argument. An ulp of a
- * double value is the positive distance between this
- * floating-point value and the double value next
+ * {@code double} value is the positive distance between this
+ * floating-point value and the {@code double} value next
* larger in magnitude. Note that for non-NaN x,
* ulp(-x) == ulp(x).
*
@@ -1089,8 +1083,8 @@ public class FpUtils {
* If the argument is positive or negative infinity, then the
* result is positive infinity.
* If the argument is positive or negative zero, then the result is
- * Double.MIN_VALUE.
- * If the argument is ±Double.MAX_VALUE, then
+ * {@code Double.MIN_VALUE}.
+ * If the argument is ±{@code Double.MAX_VALUE}, then
* the result is equal to 2971.
*
*
@@ -1105,11 +1099,9 @@ public class FpUtils {
switch(exp) {
case DoubleConsts.MAX_EXPONENT+1: // NaN or infinity
return Math.abs(d);
- // break;
case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal
return Double.MIN_VALUE;
- // break
default:
assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT;
@@ -1126,14 +1118,13 @@ public class FpUtils {
return Double.longBitsToDouble(1L <<
(exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) ));
}
- // break
}
}
/**
* Returns the size of an ulp of the argument. An ulp of a
- * float value is the positive distance between this
- * floating-point value and the float value next
+ * {@code float} value is the positive distance between this
+ * floating-point value and the {@code float} value next
* larger in magnitude. Note that for non-NaN x,
* ulp(-x) == ulp(x).
*
@@ -1143,8 +1134,8 @@ public class FpUtils {
* If the argument is positive or negative infinity, then the
* result is positive infinity.
* If the argument is positive or negative zero, then the result is
- * Float.MIN_VALUE.
- * If the argument is ±Float.MAX_VALUE, then
+ * {@code Float.MIN_VALUE}.
+ * If the argument is ±{@code Float.MAX_VALUE}, then
* the result is equal to 2104.
*
*
@@ -1159,11 +1150,9 @@ public class FpUtils {
switch(exp) {
case FloatConsts.MAX_EXPONENT+1: // NaN or infinity
return Math.abs(f);
- // break;
case FloatConsts.MIN_EXPONENT-1: // zero or subnormal
return FloatConsts.MIN_VALUE;
- // break
default:
assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT;
@@ -1180,7 +1169,6 @@ public class FpUtils {
return Float.intBitsToFloat(1 <<
(exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) ));
}
- // break
}
}
diff --git a/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java b/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java
index 2e06969253cab1fa7642133d6b7bd510a3d72aa6..047bb61e865b482f298c54609cd378357c15e944 100644
--- a/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java
+++ b/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java
@@ -235,8 +235,6 @@ abstract class AsynchronousSocketChannelImpl
if (remoteAddress == null)
throw new NotYetConnectedException();
- if (timeout < 0L)
- throw new IllegalArgumentException("Negative timeout");
boolean hasSpaceToRead = isScatteringRead || dst.hasRemaining();
boolean shutdown = false;
@@ -342,8 +340,6 @@ abstract class AsynchronousSocketChannelImpl
if (isOpen()) {
if (remoteAddress == null)
throw new NotYetConnectedException();
- if (timeout < 0L)
- throw new IllegalArgumentException("Negative timeout");
// check and update state
synchronized (writeLock) {
if (writeKilled)
diff --git a/src/share/classes/sun/nio/ch/FileChannelImpl.java b/src/share/classes/sun/nio/ch/FileChannelImpl.java
index e37fe799d84b3c8f5dc0d610becc0f1ea6503be0..32d0be649d3fb8616e27239c017bdc9b5488affa 100644
--- a/src/share/classes/sun/nio/ch/FileChannelImpl.java
+++ b/src/share/classes/sun/nio/ch/FileChannelImpl.java
@@ -39,13 +39,12 @@ import sun.security.action.GetPropertyAction;
public class FileChannelImpl
extends FileChannel
{
-
- // Used to make native read and write calls
- private static final FileDispatcher nd;
-
// Memory allocation size for mapping buffers
private static final long allocationGranularity;
+ // Used to make native read and write calls
+ private final FileDispatcher nd;
+
// File descriptor
private final FileDescriptor fd;
@@ -63,22 +62,29 @@ public class FileChannelImpl
private final Object positionLock = new Object();
private FileChannelImpl(FileDescriptor fd, boolean readable,
- boolean writable, Object parent)
+ boolean writable, boolean append, Object parent)
{
this.fd = fd;
this.readable = readable;
this.writable = writable;
this.parent = parent;
+ this.nd = new FileDispatcherImpl(append);
}
- // Invoked by getChannel() methods
- // of java.io.File{Input,Output}Stream and RandomAccessFile
- //
+ // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel()
public static FileChannel open(FileDescriptor fd,
boolean readable, boolean writable,
Object parent)
{
- return new FileChannelImpl(fd, readable, writable, parent);
+ return new FileChannelImpl(fd, readable, writable, false, parent);
+ }
+
+ // Used by FileOutputStream.getChannel
+ public static FileChannel open(FileDescriptor fd,
+ boolean readable, boolean writable,
+ boolean append, Object parent)
+ {
+ return new FileChannelImpl(fd, readable, writable, append, parent);
}
private void ensureOpen() throws IOException {
@@ -704,6 +710,9 @@ public class FileChannelImpl
private static class Unmapper
implements Runnable
{
+ // may be required to close file
+ private static final NativeDispatcher nd = new FileDispatcherImpl();
+
// keep track of mapped buffer usage
static volatile int count;
static volatile long totalSize;
@@ -1119,7 +1128,6 @@ public class FileChannelImpl
static {
Util.load();
allocationGranularity = initIDs();
- nd = new FileDispatcherImpl();
}
}
diff --git a/src/share/classes/sun/security/rsa/RSASignature.java b/src/share/classes/sun/security/rsa/RSASignature.java
index 74a42c0a3f5bfb6497dc151816285cf9e527f4fc..c510413a2151733b3a4cd1104be3360147b5ffad 100644
--- a/src/share/classes/sun/security/rsa/RSASignature.java
+++ b/src/share/classes/sun/security/rsa/RSASignature.java
@@ -185,6 +185,11 @@ public abstract class RSASignature extends SignatureSpi {
// verify the data and return the result. See JCA doc
protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
+ if (sigBytes.length != RSACore.getByteLength(publicKey)) {
+ throw new SignatureException("Signature length not correct: got " +
+ sigBytes.length + " but was expecting " +
+ RSACore.getByteLength(publicKey));
+ }
byte[] digest = getDigestValue();
try {
byte[] decrypted = RSACore.rsa(sigBytes, publicKey);
diff --git a/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
index b9528df5146a86df15e14c4a3ec509d9f0c9848f..1c0d6921091962a28f1194aa53f0d8402c06d4d3 100644
--- a/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
+++ b/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
@@ -103,7 +103,8 @@ final class RSAClientKeyExchange extends HandshakeMessage {
String s = ((protocolVersion.v >= ProtocolVersion.TLS12.v) ?
"SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
KeyGenerator kg = JsseJce.getKeyGenerator(s);
- kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor));
+ kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor),
+ generator);
preMaster = kg.generateKey();
Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
diff --git a/src/share/classes/sun/security/tools/JarSigner.java b/src/share/classes/sun/security/tools/JarSigner.java
index 89b9c7e75d739af18b5393a5b892cc239032acd2..03809d37812182380d614733938569d2c8a36b52 100644
--- a/src/share/classes/sun/security/tools/JarSigner.java
+++ b/src/share/classes/sun/security/tools/JarSigner.java
@@ -658,7 +658,9 @@ public class JarSigner {
boolean inScope = (inStoreOrScope & IN_SCOPE) != 0;
notSignedByAlias |= (inStoreOrScope & NOT_ALIAS) != 0;
- aliasNotInStore |= isSigned && (!inStore && !inScope);
+ if (keystore != null) {
+ aliasNotInStore |= isSigned && (!inStore && !inScope);
+ }
// Only used when -verbose provided
StringBuffer sb = null;
@@ -723,7 +725,7 @@ public class JarSigner {
if (signatureRelated(name)) {
// Entries inside META-INF and other unsigned
// entries are grouped separately.
- label = "-" + label.substring(1);
+ label = "-" + label;
}
// The label finally contains 2 parts separated by '|':
@@ -752,7 +754,7 @@ public class JarSigner {
List files = s.getValue();
String key = s.getKey();
if (key.charAt(0) == '-') { // the signature-related group
- key = ' ' + key.substring(1);
+ key = key.substring(1);
}
int pipe = key.indexOf('|');
if (verbose.equals("all")) {
@@ -889,7 +891,7 @@ public class JarSigner {
* Note: no newline character at the end
*/
String printCert(String tab, Certificate c, boolean checkValidityPeriod,
- long now) {
+ long now, boolean checkUsage) {
StringBuilder certStr = new StringBuilder();
String space = rb.getString("SPACE");
@@ -959,24 +961,26 @@ public class JarSigner {
}
certStr.append("]");
- boolean[] bad = new boolean[3];
- checkCertUsage(x509Cert, bad);
- if (bad[0] || bad[1] || bad[2]) {
- String x = "";
- if (bad[0]) {
- x ="KeyUsage";
- }
- if (bad[1]) {
- if (x.length() > 0) x = x + ", ";
- x = x + "ExtendedKeyUsage";
- }
- if (bad[2]) {
- if (x.length() > 0) x = x + ", ";
- x = x + "NetscapeCertType";
- }
- certStr.append("\n").append(tab)
+ if (checkUsage) {
+ boolean[] bad = new boolean[3];
+ checkCertUsage(x509Cert, bad);
+ if (bad[0] || bad[1] || bad[2]) {
+ String x = "";
+ if (bad[0]) {
+ x ="KeyUsage";
+ }
+ if (bad[1]) {
+ if (x.length() > 0) x = x + ", ";
+ x = x + "ExtendedKeyUsage";
+ }
+ if (bad[2]) {
+ if (x.length() > 0) x = x + ", ";
+ x = x + "NetscapeCertType";
+ }
+ certStr.append("\n").append(tab)
.append(MessageFormat.format(rb.getString(
".{0}.extension.does.not.support.code.signing."), x));
+ }
}
}
return certStr.toString();
@@ -1335,7 +1339,7 @@ public class JarSigner {
certUrl);
}
System.out.println(rb.getString("TSA.certificate.") +
- printCert("", tsaCert, false, 0));
+ printCert("", tsaCert, false, 0, false));
}
if (signingMechanism != null) {
System.out.println(
@@ -1544,10 +1548,13 @@ public class JarSigner {
s.append(printTimestamp(tab, timestamp));
s.append('\n');
}
- // display the certificate(s)
+ // display the certificate(s). The first one is end-enity cert and
+ // its KeyUsage should be checked.
+ boolean first = true;
for (Certificate c : certs) {
- s.append(printCert(tab, c, true, now));
+ s.append(printCert(tab, c, true, now, first));
s.append('\n');
+ first = false;
}
try {
CertPath cp = certificateFactory.generateCertPath(certs);
@@ -1847,7 +1854,7 @@ public class JarSigner {
// We don't meant to print anything, the next call
// checks validity and keyUsage etc
- printCert("", certChain[0], true, 0);
+ printCert("", certChain[0], true, 0, true);
try {
CertPath cp = certificateFactory.generateCertPath(Arrays.asList(certChain));
diff --git a/src/share/classes/sun/security/tools/policytool/PolicyTool.java b/src/share/classes/sun/security/tools/policytool/PolicyTool.java
index e04316317a880e7daa6d9302b7659678d22dc613..f310504a2047b1dbc2ad6a80fe32bf9cd182197b 100644
--- a/src/share/classes/sun/security/tools/policytool/PolicyTool.java
+++ b/src/share/classes/sun/security/tools/policytool/PolicyTool.java
@@ -49,7 +49,7 @@ import javax.security.auth.x500.X500Principal;
/**
* PolicyTool may be used by users and administrators to configure the
* overall java security policy (currently stored in the policy file).
- * Using PolicyTool administators may add and remove policies from
+ * Using PolicyTool administrators may add and remove policies from
* the policy file.
*
* @see java.security.Policy
@@ -1343,11 +1343,6 @@ class ToolDialog extends Dialog {
PolicyTool.rb.getString
("Actions.");
- /* gridbag index for display OverWriteFile (OW) components */
- public static final int OW_LABEL = 0;
- public static final int OW_OK_BUTTON = 1;
- public static final int OW_CANCEL_BUTTON = 2;
-
/* gridbag index for display PolicyEntry (PE) components */
public static final int PE_CODEBASE_LABEL = 0;
public static final int PE_CODEBASE_TEXTFIELD = 1;
@@ -1522,44 +1517,6 @@ class ToolDialog extends Dialog {
return null;
}
- /**
- * ask user if they want to overwrite an existing file
- */
- void displayOverWriteFileDialog(String filename, int nextEvent) {
-
- // find where the PolicyTool gui is
- Point location = tw.getLocationOnScreen();
- setBounds(location.x + 75, location.y + 100, 400, 150);
- setLayout(new GridBagLayout());
-
- // ask the user if they want to over write the existing file
- MessageFormat form = new MessageFormat(PolicyTool.rb.getString
- ("OK.to.overwrite.existing.file.filename."));
- Object[] source = {filename};
- Label label = new Label(form.format(source));
- tw.addNewComponent(this, label, OW_LABEL,
- 0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- tw.TOP_PADDING);
-
- // OK button
- Button button = new Button(PolicyTool.rb.getString("OK"));
- button.addActionListener(new OverWriteFileOKButtonListener
- (tool, tw, this, filename, nextEvent));
- tw.addNewComponent(this, button, OW_OK_BUTTON,
- 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
- tw.TOP_PADDING);
-
- // Cancel button
- // -- if the user hits cancel, do NOT go on to the next event
- button = new Button(PolicyTool.rb.getString("Cancel"));
- button.addActionListener(new CancelButtonListener(this));
- tw.addNewComponent(this, button, OW_CANCEL_BUTTON,
- 1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
- tw.TOP_PADDING);
-
- setVisible(true);
- }
-
/**
* pop up a dialog so the user can enter info to add a new PolicyEntry
* - if edit is TRUE, then the user is editing an existing entry
@@ -2339,47 +2296,39 @@ class ToolDialog extends Dialog {
return;
// get the entered filename
- String filename = new String(fd.getDirectory() + fd.getFile());
+ File saveAsFile = new File(fd.getDirectory(), fd.getFile());
+ String filename = saveAsFile.getPath();
fd.dispose();
- // see if the file already exists
- File saveAsFile = new File(filename);
- if (saveAsFile.exists()) {
- // display a dialog box for the user to enter policy info
- ToolDialog td = new ToolDialog
- (PolicyTool.rb.getString("Overwrite.File"), tool, tw, true);
- td.displayOverWriteFileDialog(filename, nextEvent);
- } else {
- try {
- // save the policy entries to a file
- tool.savePolicy(filename);
+ try {
+ // save the policy entries to a file
+ tool.savePolicy(filename);
- // display status
- MessageFormat form = new MessageFormat(PolicyTool.rb.getString
- ("Policy.successfully.written.to.filename"));
- Object[] source = {filename};
- tw.displayStatusDialog(null, form.format(source));
+ // display status
+ MessageFormat form = new MessageFormat(PolicyTool.rb.getString
+ ("Policy.successfully.written.to.filename"));
+ Object[] source = {filename};
+ tw.displayStatusDialog(null, form.format(source));
- // display the new policy filename
- TextField newFilename = (TextField)tw.getComponent
- (tw.MW_FILENAME_TEXTFIELD);
- newFilename.setText(filename);
- tw.setVisible(true);
+ // display the new policy filename
+ TextField newFilename = (TextField)tw.getComponent
+ (tw.MW_FILENAME_TEXTFIELD);
+ newFilename.setText(filename);
+ tw.setVisible(true);
- // now continue with the originally requested command
- // (QUIT, NEW, or OPEN)
- userSaveContinue(tool, tw, this, nextEvent);
+ // now continue with the originally requested command
+ // (QUIT, NEW, or OPEN)
+ userSaveContinue(tool, tw, this, nextEvent);
- } catch (FileNotFoundException fnfe) {
- if (filename == null || filename.equals("")) {
- tw.displayErrorDialog(null, new FileNotFoundException
- (PolicyTool.rb.getString("null.filename")));
- } else {
- tw.displayErrorDialog(null, fnfe);
- }
- } catch (Exception ee) {
- tw.displayErrorDialog(null, ee);
+ } catch (FileNotFoundException fnfe) {
+ if (filename == null || filename.equals("")) {
+ tw.displayErrorDialog(null, new FileNotFoundException
+ (PolicyTool.rb.getString("null.filename")));
+ } else {
+ tw.displayErrorDialog(null, fnfe);
}
+ } catch (Exception ee) {
+ tw.displayErrorDialog(null, ee);
}
}
@@ -2494,7 +2443,7 @@ class ToolDialog extends Dialog {
return;
// get the entered filename
- String policyFile = new String(fd.getDirectory() + fd.getFile());
+ String policyFile = new File(fd.getDirectory(), fd.getFile()).getPath();
try {
// open the policy file
@@ -2861,67 +2810,6 @@ class MainWindowListener implements ActionListener {
}
}
-/**
- * Event handler for OverWriteFileOKButton button
- */
-class OverWriteFileOKButtonListener implements ActionListener {
-
- private PolicyTool tool;
- private ToolWindow tw;
- private ToolDialog td;
- private String filename;
- private int nextEvent;
-
- OverWriteFileOKButtonListener(PolicyTool tool, ToolWindow tw,
- ToolDialog td, String filename, int nextEvent) {
- this.tool = tool;
- this.tw = tw;
- this.td = td;
- this.filename = filename;
- this.nextEvent = nextEvent;
- }
-
- public void actionPerformed(ActionEvent e) {
- try {
- // save the policy entries to a file
- tool.savePolicy(filename);
-
- // display status
- MessageFormat form = new MessageFormat
- (PolicyTool.rb.getString
- ("Policy.successfully.written.to.filename"));
- Object[] source = {filename};
- tw.displayStatusDialog(null, form.format(source));
-
- // display the new policy filename
- TextField newFilename = (TextField)tw.getComponent
- (tw.MW_FILENAME_TEXTFIELD);
- newFilename.setText(filename);
- tw.setVisible(true);
-
- // now continue with the originally requested command
- // (QUIT, NEW, or OPEN)
- td.setVisible(false);
- td.dispose();
- td.userSaveContinue(tool, tw, td, nextEvent);
-
- } catch (FileNotFoundException fnfe) {
- if (filename == null || filename.equals("")) {
- tw.displayErrorDialog(null, new FileNotFoundException
- (PolicyTool.rb.getString("null.filename")));
- } else {
- tw.displayErrorDialog(null, fnfe);
- }
- td.setVisible(false);
- td.dispose();
- } catch (Exception ee) {
- tw.displayErrorDialog(null, ee);
- td.setVisible(false);
- td.dispose();
- }
- }
-}
-
/**
* Event handler for AddEntryDoneButton button
*
diff --git a/src/share/classes/sun/security/util/ManifestEntryVerifier.java b/src/share/classes/sun/security/util/ManifestEntryVerifier.java
index 3952ccee86dbc85b3d145b787e8948e6cad9c38d..2fe98e500357c12b313c57deba8df4b6b786a320 100644
--- a/src/share/classes/sun/security/util/ManifestEntryVerifier.java
+++ b/src/share/classes/sun/security/util/ManifestEntryVerifier.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -185,7 +185,10 @@ public class ManifestEntryVerifier {
Hashtable sigFileSigners)
throws JarException
{
- if (skip) return null;
+ // MANIFEST.MF should not be skipped. It has signers.
+ if (skip && !entry.getName().equals(JarFile.MANIFEST_NAME)) {
+ return null;
+ }
if (signers != null)
return signers;
diff --git a/src/share/classes/sun/security/util/SignatureFileVerifier.java b/src/share/classes/sun/security/util/SignatureFileVerifier.java
index b0a334ee49804f2bb0473b21ab5b3b585aa4d27e..d3ce9013e1570a1bdf90a597e605f9fcf6526fdc 100644
--- a/src/share/classes/sun/security/util/SignatureFileVerifier.java
+++ b/src/share/classes/sun/security/util/SignatureFileVerifier.java
@@ -265,6 +265,9 @@ public class SignatureFileVerifier {
debug.println("processSignature unsigned name = "+name);
}
}
+
+ // MANIFEST.MF is always regarded as signed
+ updateSigners(newSigners, signers, JarFile.MANIFEST_NAME);
}
/**
diff --git a/src/share/demo/nio/zipfs/Demo.java b/src/share/demo/nio/zipfs/Demo.java
index 99669d1fdf224dd6518f9a8553b51e376a75d1a0..fd2ba7311b10082c5bbda04d1e49ef1db9600549 100644
--- a/src/share/demo/nio/zipfs/Demo.java
+++ b/src/share/demo/nio/zipfs/Demo.java
@@ -45,12 +45,7 @@ import static java.nio.file.StandardCopyOption.*;
/*
* ZipFileSystem usage demo
*
- * java [-cp .../zipfs.jar:./] Demo action ZipfileName [...]
- *
- * To deploy the provider, either copy the zipfs.jar into JDK/JRE
- * extensions directory or add
- * /demo/nio/ZipFileSystem/zipfs.jar
- * into your class path as showed above.
+ * java Demo action ZipfileName [...]
*
* @author Xueming Shen
*/
@@ -153,14 +148,11 @@ public class Demo {
Action action = Action.valueOf(args[0]);
Map env = env = new HashMap<>();
if (action == Action.create)
- env.put("createNew", true);
+ env.put("create", "true");
if (action == Action.tlist || action == Action.twalk)
env.put("buildDirTree", true);
+ FileSystem fs = FileSystems.newFileSystem(Paths.get(args[1]), env, null);
- FileSystem fs = FileSystems.newFileSystem(
- URI.create("zip" + Paths.get(args[1]).toUri().toString().substring(4)),
- env,
- null);
try {
FileSystem fs2;
Path path, src, dst;
@@ -207,19 +199,13 @@ public class Demo {
src.copyTo(dst, COPY_ATTRIBUTES);
break;
case zzmove:
- fs2 = FileSystems.newFileSystem(
- URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)),
- env,
- null);
+ fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null);
//sf1.getPath(args[3]).moveTo(fs2.getPath(args[3]));
z2zmove(fs, fs2, args[3]);
fs2.close();
break;
case zzcopy:
- fs2 = FileSystems.newFileSystem(
- URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)),
- env,
- null);
+ fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null);
//sf1.getPath(args[3]).copyTo(fs2.getPath(args[3]));
z2zcopy(fs, fs2, args[3]);
fs2.close();
diff --git a/src/share/demo/nio/zipfs/README.txt b/src/share/demo/nio/zipfs/README.txt
index d5517bf7baeb481e4c601863944fee63c733421e..9a216e48d704aa4f8dbcab7812df5ebb8d4018cd 100644
--- a/src/share/demo/nio/zipfs/README.txt
+++ b/src/share/demo/nio/zipfs/README.txt
@@ -1,10 +1,6 @@
ZipFileSystem is a file system provider that treats the contents of a zip or
JAR file as a java.nio.file.FileSystem.
-To deploy the provider you must copy zipfs.jar into your extensions
-directory or else add /demo/nio/zipfs/zipfs.jar
-to your class path.
-
The factory methods defined by the java.nio.file.FileSystems class can be
used to create a FileSystem, eg:
@@ -15,9 +11,9 @@ used to create a FileSystem, eg:
-or
- // locate file system by URI
+ // locate file system by the legacy JAR URL syntax
Map env = Collections.emptyMap();
- URI uri = URI.create("zip:///mydir/foo.jar");
+ URI uri = URI.create("jar:file:/mydir/foo.jar");
FileSystem fs = FileSystems.newFileSystem(uri, env);
Once a FileSystem is created then classes in the java.nio.file package
@@ -26,4 +22,6 @@ can be used to access files in the zip/JAR file, eg:
Path mf = fs.getPath("/META-INF/MANIFEST.MF");
InputStream in = mf.newInputStream();
+See Demo.java for more interesting usages.
+
diff --git a/src/share/demo/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider b/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider
similarity index 50%
rename from src/share/demo/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider
rename to src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider
index ace131aa0fd72ee57c88e85000f1f54840b5c138..58ee3a6b9727d7215c65474d48a1eb7239da1ebf 100644
--- a/src/share/demo/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider
+++ b/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider
@@ -1,3 +1,2 @@
com.sun.nio.zipfs.ZipFileSystemProvider
-com.sun.nio.zipfs.JarFileSystemProvider
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipCoder.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipCoder.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileStore.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileStore.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
similarity index 99%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
index eddc5ac938229cfb040d3de799f6e9e6fdf934fa..21094011c01be0c31af45821ee912b9a0a425610 100644
--- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java
+++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
@@ -91,11 +91,11 @@ public class ZipFileSystem extends FileSystem {
throws IOException
{
// configurable env setup
+ this.createNew = "true".equals(env.get("create"));
+ this.nameEncoding = env.containsKey("encoding") ?
+ (String)env.get("encoding") : "UTF-8";
this.buildDirTree = TRUE.equals(env.get("buildDirTreea"));
this.useTempFile = TRUE.equals(env.get("useTempFile"));
- this.createNew = TRUE.equals(env.get("createNew"));
- this.nameEncoding = env.containsKey("nameEncoding") ?
- (String)env.get("nameEncoding") : "UTF-8";
this.defaultDir = env.containsKey("default.dir") ?
(String)env.get("default.dir") : "/";
if (this.defaultDir.charAt(0) != '/')
@@ -1176,7 +1176,9 @@ public class ZipFileSystem extends FileSystem {
} else {
os.write(buf, 0, LOCHDR); // write out the loc header
locoff += LOCHDR;
- size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf);
+ // use e.csize, LOCSIZ(buf) is zero if FLAG_DATADESCR is on
+ // size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf);
+ size += LOCNAM(buf) + LOCEXT(buf) + e.csize;
written = LOCHDR + size;
}
int n;
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java
similarity index 88%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java
index 08c3a17648c2f0e3e2e72d8b678b940968be6923..cf39b07cae7540cb0cf95c366d3e6cf10409a0d8 100644
--- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java
+++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java
@@ -63,7 +63,7 @@ public class ZipFileSystemProvider extends FileSystemProvider {
@Override
public String getScheme() {
- return "zip";
+ return "jar";
}
protected Path uriToPath(URI uri) {
@@ -72,10 +72,14 @@ public class ZipFileSystemProvider extends FileSystemProvider {
throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'");
}
try {
- return Paths.get(new URI("file", uri.getHost(), uri.getPath(), null))
- .toAbsolutePath();
+ // only support legacy JAR URL syntax jar:{uri}!/{entry} for now
+ String spec = uri.getSchemeSpecificPart();
+ int sep = spec.indexOf("!/");
+ if (sep != -1)
+ spec = spec.substring(0, sep);
+ return Paths.get(new URI(spec)).toAbsolutePath();
} catch (URISyntaxException e) {
- throw new AssertionError(e); //never thrown
+ throw new IllegalArgumentException(e.getMessage(), e);
}
}
@@ -119,14 +123,14 @@ public class ZipFileSystemProvider extends FileSystemProvider {
@Override
public Path getPath(URI uri) {
- FileSystem fs = getFileSystem(uri);
- String fragment = uri.getFragment();
- if (fragment == null) {
+
+ String spec = uri.getSchemeSpecificPart();
+ int sep = spec.indexOf("!/");
+ if (sep == -1)
throw new IllegalArgumentException("URI: "
+ uri
- + " does not contain path fragment ex. zip:///c:/foo.zip#/BAR");
- }
- return fs.getPath(fragment);
+ + " does not contain path info ex. jar:file:/c:/foo.zip!/BAR");
+ return getFileSystem(uri).getPath(spec.substring(sep + 1));
}
@Override
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java
similarity index 98%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java
index dd18cc9f4440044337b006ae815da5a29d9e709e..56954e1d9eab231dbdd1416837650b90ccfffcbc 100644
--- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java
+++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java
@@ -33,9 +33,7 @@ package com.sun.nio.zipfs;
import java.nio.file.Paths;
import java.util.Collections;
-import java.util.Iterator;
import java.util.Map;
-import com.sun.nio.zipfs.ZipFileSystem.Entry;
import static com.sun.nio.zipfs.ZipConstants.*;
import static com.sun.nio.zipfs.ZipUtils.*;
@@ -172,7 +170,7 @@ public class ZipInfo {
static void printExtra(byte[] extra, int off, int len) {
int end = off + len;
- while (off + 4 < end) {
+ while (off + 4 <= end) {
int tag = SH(extra, off);
int sz = SH(extra, off + 2);
print(" [tag=0x%04x, sz=%d, data= ", tag, sz);
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
similarity index 98%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
index 5fba2fafa9aef2c022b056e3418bd66153328b4c..a2c766f0da2f92666f533461c4332c984f2be13d 100644
--- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java
+++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
@@ -191,13 +191,12 @@ public class ZipPath extends Path {
@Override
public URI toUri() {
- String zfPath = zfs.toString();
- if (File.separatorChar == '\\') // replace all separators by '/'
- zfPath = "/" + zfPath.replace("\\", "/");
try {
- return new URI("zip", "",
- zfPath,
- zfs.getString(toAbsolutePath().path));
+ return new URI("jar",
+ zfs.getZipFile().toUri() +
+ "!" +
+ zfs.getString(toAbsolutePath().path),
+ null);
} catch (Exception ex) {
throw new AssertionError(ex);
}
diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java
similarity index 100%
rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java
rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java
diff --git a/src/share/demo/zipfs b/src/share/demo/zipfs
new file mode 100644
index 0000000000000000000000000000000000000000..fd2ba7311b10082c5bbda04d1e49ef1db9600549
--- /dev/null
+++ b/src/share/demo/zipfs
@@ -0,0 +1,703 @@
+/*
+ * Copyright (c) 2010 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
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.file.*;
+import java.nio.file.attribute.*;
+import java.net.*;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+import static java.nio.file.StandardOpenOption.*;
+import static java.nio.file.StandardCopyOption.*;
+
+/*
+ * ZipFileSystem usage demo
+ *
+ * java Demo action ZipfileName [...]
+ *
+ * @author Xueming Shen
+ */
+
+public class Demo {
+
+ static enum Action {
+ rename, //
+ // rename entry src to dst inside zipfile
+
+ movein, //
+ // move an external src file into zipfile
+ // as entry dst
+
+ moveout, //
+ // move a zipfile entry src out to dst
+
+ copy, //
+ // copy entry src to dst inside zipfile
+
+ copyin, //
+ // copy an external src file into zipfile
+ // as entry dst
+
+ copyin_attrs, //
+ // copy an external src file into zipfile
+ // as entry dst, with attributes (timestamp)
+
+ copyout, //
+ // copy zipfile entry src" out to file dst
+
+ copyout_attrs, //
+
+ zzmove, //
+ // move entry path/dir from zfsrc to zfdst
+
+ zzcopy, //
+ // copy path from zipfile zfsrc to zipfile
+ // zfdst
+
+ attrs, //
+ // printout the attributes of entry path
+
+ attrsspace, //
+ // printout the storespace attrs of entry path
+
+ setmtime, //
+ // set the lastModifiedTime of entry path
+
+ setatime, //
+ setctime, //
+
+ lsdir, //
+ // list dir's direct child files/dirs
+
+ mkdir, //
+
+ mkdirs, //
+
+ rmdirs, //
+
+ list, //
+ // recursively list all entries of dir
+ // via DirectoryStream
+
+ tlist, //
+ // list with buildDirTree=true
+
+ vlist, //
+ // recursively verbose list all entries of
+ // dir via DirectoryStream
+
+ walk, //
+ // recursively walk all entries of dir
+ // via Files.walkFileTree
+
+ twalk, //
+ // walk with buildDirTree=true
+
+ extract, //
+
+ update, //
+
+ delete, //
+
+ add, //
+
+ create, //
+ // create a new zipfile if it doesn't exit
+ // and then add the file(s) into it.
+
+ attrs2, //
+ // test different ways to print attrs
+
+ prof,
+ }
+
+ public static void main(String[] args) throws Throwable {
+
+ Action action = Action.valueOf(args[0]);
+ Map env = env = new HashMap<>();
+ if (action == Action.create)
+ env.put("create", "true");
+ if (action == Action.tlist || action == Action.twalk)
+ env.put("buildDirTree", true);
+ FileSystem fs = FileSystems.newFileSystem(Paths.get(args[1]), env, null);
+
+ try {
+ FileSystem fs2;
+ Path path, src, dst;
+ boolean isRename = false;
+ switch (action) {
+ case rename:
+ src = fs.getPath(args[2]);
+ dst = fs.getPath(args[3]);
+ src.moveTo(dst);
+ break;
+ case moveout:
+ src = fs.getPath(args[2]);
+ dst = Paths.get(args[3]);
+ src.moveTo(dst);
+ break;
+ case movein:
+ src = Paths.get(args[2]);
+ dst = fs.getPath(args[3]);
+ src.moveTo(dst);
+ break;
+ case copy:
+ src = fs.getPath(args[2]);
+ dst = fs.getPath(args[3]);
+ src.copyTo(dst);
+ break;
+ case copyout:
+ src = fs.getPath(args[2]);
+ dst = Paths.get(args[3]);
+ src.copyTo(dst);
+ break;
+ case copyin:
+ src = Paths.get(args[2]);
+ dst = fs.getPath(args[3]);
+ src.copyTo(dst);
+ break;
+ case copyin_attrs:
+ src = Paths.get(args[2]);
+ dst = fs.getPath(args[3]);
+ src.copyTo(dst, COPY_ATTRIBUTES);
+ break;
+ case copyout_attrs:
+ src = fs.getPath(args[2]);
+ dst = Paths.get(args[3]);
+ src.copyTo(dst, COPY_ATTRIBUTES);
+ break;
+ case zzmove:
+ fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null);
+ //sf1.getPath(args[3]).moveTo(fs2.getPath(args[3]));
+ z2zmove(fs, fs2, args[3]);
+ fs2.close();
+ break;
+ case zzcopy:
+ fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null);
+ //sf1.getPath(args[3]).copyTo(fs2.getPath(args[3]));
+ z2zcopy(fs, fs2, args[3]);
+ fs2.close();
+ break;
+ case attrs:
+ for (int i = 2; i < args.length; i++) {
+ path = fs.getPath(args[i]);
+ System.out.println(path);
+ System.out.println(
+ Attributes.readBasicFileAttributes(path).toString());
+ }
+ break;
+ case setmtime:
+ DateFormat df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
+ Date newDatetime = df.parse(args[2]);
+ for (int i = 3; i < args.length; i++) {
+ path = fs.getPath(args[i]);
+ path.setAttribute("lastModifiedTime",
+ FileTime.fromMillis(newDatetime.getTime()));
+ System.out.println(
+ Attributes.readBasicFileAttributes(path).toString());
+ }
+ break;
+ case setctime:
+ df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
+ newDatetime = df.parse(args[2]);
+ for (int i = 3; i < args.length; i++) {
+ path = fs.getPath(args[i]);
+ path.setAttribute("creationTime",
+ FileTime.fromMillis(newDatetime.getTime()));
+ System.out.println(
+ Attributes.readBasicFileAttributes(path).toString());
+ }
+ break;
+ case setatime:
+ df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
+ newDatetime = df.parse(args[2]);
+ for (int i = 3; i < args.length; i++) {
+ path = fs.getPath(args[i]);
+ path.setAttribute("lastAccessTime",
+ FileTime.fromMillis(newDatetime.getTime()));
+ System.out.println(
+ Attributes.readBasicFileAttributes(path).toString());
+ }
+ break;
+ case attrsspace:
+ path = fs.getPath("/");
+ FileStore fstore = path.getFileStore();
+ //System.out.println(fstore.getFileStoreAttributeView(FileStoreSpaceAttributeView.class)
+ // .readAttributes());
+ // or
+ System.out.printf("filestore[%s]%n", fstore.name());
+ System.out.printf(" totalSpace: %d%n",
+ (Long)fstore.getAttribute("space:totalSpace"));
+ System.out.printf(" usableSpace: %d%n",
+ (Long)fstore.getAttribute("space:usableSpace"));
+ System.out.printf(" unallocSpace: %d%n",
+ (Long)fstore.getAttribute("space:unallocatedSpace"));
+ break;
+ case list:
+ case tlist:
+ if (args.length < 3)
+ list(fs.getPath("/"), false);
+ else
+ list(fs.getPath(args[2]), false);
+ break;
+ case vlist:
+ if (args.length < 3)
+ list(fs.getPath("/"), true);
+ else
+ list(fs.getPath(args[2]), true);
+ break;
+ case twalk:
+ case walk:
+ walk(fs.getPath((args.length > 2)? args[2] : "/"));
+ break;
+ case extract:
+ if (args.length == 2) {
+ extract(fs, "/");
+ } else {
+ for (int i = 2; i < args.length; i++) {
+ extract(fs, args[i]);
+ }
+ }
+ break;
+ case delete:
+ for (int i = 2; i < args.length; i++)
+ fs.getPath(args[i]).delete();
+ break;
+ case create:
+ case add:
+ case update:
+ for (int i = 2; i < args.length; i++) {
+ update(fs, args[i]);
+ }
+ break;
+ case lsdir:
+ path = fs.getPath(args[2]);
+ final String fStr = (args.length > 3)?args[3]:"";
+ DirectoryStream ds = path.newDirectoryStream(
+ new DirectoryStream.Filter() {
+ public boolean accept(Path path) {
+ return path.toString().contains(fStr);
+ }
+ });
+ for (Path p : ds)
+ System.out.println(p);
+ break;
+ case mkdir:
+ fs.getPath(args[2]).createDirectory();
+ break;
+ case mkdirs:
+ mkdirs(fs.getPath(args[2]));
+ break;
+ case attrs2:
+ for (int i = 2; i < args.length; i++) {
+ path = fs.getPath(args[i]);
+ System.out.printf("%n%s%n", path);
+ System.out.println("-------(1)---------");
+ System.out.println(
+ Attributes.readBasicFileAttributes(path).toString());
+ System.out.println("-------(2)---------");
+ Map map = path.readAttributes("zip:*");
+ for (Map.Entry e : map.entrySet()) {
+ System.out.printf(" %s : %s%n", e.getKey(), e.getValue());
+ }
+ System.out.println("-------(3)---------");
+ map = path.readAttributes("size,lastModifiedTime,isDirectory");
+ for (Map.Entry e : map.entrySet()) {
+ System.out.printf(" %s : %s%n", e.getKey(), e.getValue());
+ }
+ }
+ break;
+ case prof:
+ list(fs.getPath("/"), false);
+ while (true) {
+ Thread.sleep(10000);
+ //list(fs.getPath("/"), true);
+ System.out.println("sleeping...");
+ }
+ }
+ } catch (Exception x) {
+ x.printStackTrace();
+ } finally {
+ if (fs != null)
+ fs.close();
+ }
+ }
+
+ private static byte[] getBytes(String name) {
+ return name.getBytes();
+ }
+
+ private static String getString(byte[] name) {
+ return new String(name);
+ }
+
+ private static void walk(Path path) throws IOException
+ {
+ Files.walkFileTree(
+ path,
+ new SimpleFileVisitor() {
+ private int indent = 0;
+ private void indent() {
+ int n = 0;
+ while (n++ < indent)
+ System.out.printf(" ");
+ }
+
+ @Override
+ public FileVisitResult visitFile(Path file,
+ BasicFileAttributes attrs)
+ {
+ indent();
+ System.out.printf("%s%n", file.getName().toString());
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult preVisitDirectory(Path dir,
+ BasicFileAttributes attrs)
+ {
+ indent();
+ System.out.printf("[%s]%n", dir.toString());
+ indent += 2;
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(Path dir,
+ IOException ioe)
+ {
+ indent -= 2;
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ }
+
+ private static void update(FileSystem fs, String path) throws Throwable{
+ Path src = FileSystems.getDefault().getPath(path);
+ if (Boolean.TRUE.equals(src.getAttribute("isDirectory"))) {
+ DirectoryStream ds = src.newDirectoryStream();
+ for (Path child : ds)
+ update(fs, child.toString());
+ ds.close();
+ } else {
+ Path dst = fs.getPath(path);
+ Path parent = dst.getParent();
+ if (parent != null && parent.notExists())
+ mkdirs(parent);
+ src.copyTo(dst, REPLACE_EXISTING);
+ }
+ }
+
+ private static void extract(FileSystem fs, String path) throws Throwable{
+ Path src = fs.getPath(path);
+ if (Boolean.TRUE.equals(src.getAttribute("isDirectory"))) {
+ DirectoryStream ds = src.newDirectoryStream();
+ for (Path child : ds)
+ extract(fs, child.toString());
+ ds.close();
+ } else {
+ if (path.startsWith("/"))
+ path = path.substring(1);
+ Path dst = FileSystems.getDefault().getPath(path);
+ Path parent = dst.getParent();
+ if (parent.notExists())
+ mkdirs(parent);
+ src.copyTo(dst, REPLACE_EXISTING);
+ }
+ }
+
+ // use DirectoryStream
+ private static void z2zcopy(FileSystem src, FileSystem dst, String path)
+ throws IOException
+ {
+ Path srcPath = src.getPath(path);
+ Path dstPath = dst.getPath(path);
+
+ if (Boolean.TRUE.equals(srcPath.getAttribute("isDirectory"))) {
+ if (!dstPath.exists()) {
+ try {
+ mkdirs(dstPath);
+ } catch (FileAlreadyExistsException x) {}
+ }
+ DirectoryStream ds = srcPath.newDirectoryStream();
+ for (Path child : ds) {
+ z2zcopy(src, dst,
+ path + (path.endsWith("/")?"":"/") + child.getName());
+ }
+ ds.close();
+ } else {
+ //System.out.println("copying..." + path);
+ srcPath.copyTo(dstPath);
+ }
+ }
+
+ // use TreeWalk to move
+ private static void z2zmove(FileSystem src, FileSystem dst, String path)
+ throws IOException
+ {
+ final Path srcPath = src.getPath(path).toAbsolutePath();
+ final Path dstPath = dst.getPath(path).toAbsolutePath();
+
+ Files.walkFileTree(srcPath, new SimpleFileVisitor() {
+
+ @Override
+ public FileVisitResult visitFile(Path file,
+ BasicFileAttributes attrs)
+ {
+ Path dst = srcPath.relativize(file);
+ dst = dstPath.resolve(dst);
+ try {
+ Path parent = dstPath.getParent();
+ if (parent != null && parent.notExists())
+ mkdirs(parent);
+ file.moveTo(dst);
+ } catch (IOException x) {
+ x.printStackTrace();
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult preVisitDirectory(Path dir,
+ BasicFileAttributes attrs)
+ {
+ Path dst = srcPath.relativize(dir);
+ dst = dstPath.resolve(dst);
+ try {
+
+ if (dst.notExists())
+ mkdirs(dst);
+ } catch (IOException x) {
+ x.printStackTrace();
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(Path dir,
+ IOException ioe)
+ throws IOException
+ {
+ try {
+ dir.delete();
+ } catch (IOException x) {
+ //x.printStackTrace();
+ }
+ return FileVisitResult.CONTINUE;
+ }
+ });
+
+ }
+
+ private static void mkdirs(Path path) throws IOException {
+ path = path.toAbsolutePath();
+ Path parent = path.getParent();
+ if (parent != null) {
+ if (parent.notExists())
+ mkdirs(parent);
+ }
+ path.createDirectory();
+ }
+
+ private static void rmdirs(Path path) throws IOException {
+ while (path != null && path.getNameCount() != 0) {
+ path.delete();
+ path = path.getParent();
+ }
+ }
+
+ private static void list(Path path, boolean verbose ) throws IOException {
+ if (!"/".equals(path.toString())) {
+ System.out.printf(" %s%n", path.toString());
+ if (verbose)
+ System.out.println(Attributes.readBasicFileAttributes(path).toString());
+ }
+ if (path.notExists())
+ return;
+ if (Attributes.readBasicFileAttributes(path).isDirectory()) {
+ DirectoryStream ds = path.newDirectoryStream();
+ for (Path child : ds)
+ list(child, verbose);
+ ds.close();
+ }
+ }
+
+ // check the content of two paths are equal
+ private static void checkEqual(Path src, Path dst) throws IOException
+ {
+ //System.out.printf("checking <%s> vs <%s>...%n",
+ // src.toString(), dst.toString());
+
+ //streams
+ InputStream isSrc = src.newInputStream();
+ InputStream isDst = dst.newInputStream();
+ byte[] bufSrc = new byte[8192];
+ byte[] bufDst = new byte[8192];
+
+ try {
+ int nSrc = 0;
+ while ((nSrc = isSrc.read(bufSrc)) != -1) {
+ int nDst = 0;
+ while (nDst < nSrc) {
+ int n = isDst.read(bufDst, nDst, nSrc - nDst);
+ if (n == -1) {
+ System.out.printf("checking <%s> vs <%s>...%n",
+ src.toString(), dst.toString());
+ throw new RuntimeException("CHECK FAILED!");
+ }
+ nDst += n;
+ }
+ while (--nSrc >= 0) {
+ if (bufSrc[nSrc] != bufDst[nSrc]) {
+ System.out.printf("checking <%s> vs <%s>...%n",
+ src.toString(), dst.toString());
+ throw new RuntimeException("CHECK FAILED!");
+ }
+ nSrc--;
+ }
+ }
+ } finally {
+ isSrc.close();
+ isDst.close();
+ }
+
+ // channels
+ SeekableByteChannel chSrc = src.newByteChannel();
+ SeekableByteChannel chDst = dst.newByteChannel();
+ if (chSrc.size() != chDst.size()) {
+ System.out.printf("src[%s].size=%d, dst[%s].size=%d%n",
+ chSrc.toString(), chSrc.size(),
+ chDst.toString(), chDst.size());
+ throw new RuntimeException("CHECK FAILED!");
+ }
+ ByteBuffer bbSrc = ByteBuffer.allocate(8192);
+ ByteBuffer bbDst = ByteBuffer.allocate(8192);
+
+ try {
+ int nSrc = 0;
+ while ((nSrc = chSrc.read(bbSrc)) != -1) {
+ int nDst = chDst.read(bbDst);
+ if (nSrc != nDst) {
+ System.out.printf("checking <%s> vs <%s>...%n",
+ src.toString(), dst.toString());
+ throw new RuntimeException("CHECK FAILED!");
+ }
+ while (--nSrc >= 0) {
+ if (bbSrc.get(nSrc) != bbDst.get(nSrc)) {
+ System.out.printf("checking <%s> vs <%s>...%n",
+ src.toString(), dst.toString());
+ throw new RuntimeException("CHECK FAILED!");
+ }
+ nSrc--;
+ }
+ bbSrc.flip();
+ bbDst.flip();
+ }
+ } catch (IOException x) {
+ x.printStackTrace();
+ } finally {
+ chSrc.close();
+ chDst.close();
+ }
+ }
+
+ private static void fchCopy(Path src, Path dst) throws IOException
+ {
+ Set read = new HashSet<>();
+ read.add(READ);
+ Set openwrite = new HashSet<>();
+ openwrite.add(CREATE_NEW);
+ openwrite.add(WRITE);
+
+ FileChannel srcFc = src.getFileSystem()
+ .provider()
+ .newFileChannel(src, read);
+ FileChannel dstFc = dst.getFileSystem()
+ .provider()
+ .newFileChannel(dst, openwrite);
+
+ try {
+ ByteBuffer bb = ByteBuffer.allocate(8192);
+ while (srcFc.read(bb) >= 0) {
+ bb.flip();
+ dstFc.write(bb);
+ bb.clear();
+ }
+ } finally {
+ srcFc.close();
+ dstFc.close();
+ }
+ }
+
+ private static void chCopy(Path src, Path dst) throws IOException
+ {
+ Set read = new HashSet<>();
+ read.add(READ);
+ Set openwrite = new HashSet<>();
+ openwrite.add(CREATE_NEW);
+ openwrite.add(WRITE);
+
+ SeekableByteChannel srcCh = src.newByteChannel(read);
+ SeekableByteChannel dstCh = dst.newByteChannel(openwrite);
+
+ try {
+ ByteBuffer bb = ByteBuffer.allocate(8192);
+ while (srcCh.read(bb) >= 0) {
+ bb.flip();
+ dstCh.write(bb);
+ bb.clear();
+ }
+ } finally {
+ srcCh.close();
+ dstCh.close();
+ }
+ }
+
+ private static void streamCopy(Path src, Path dst) throws IOException
+ {
+ InputStream isSrc = src.newInputStream();
+ OutputStream osDst = dst.newOutputStream();
+ byte[] buf = new byte[8192];
+ try {
+ int n = 0;
+ while ((n = isSrc.read(buf)) != -1) {
+ osDst.write(buf, 0, n);
+ }
+ } finally {
+ isSrc.close();
+ osDst.close();
+ }
+ }
+}
diff --git a/src/share/native/java/io/RandomAccessFile.c b/src/share/native/java/io/RandomAccessFile.c
index a8c3390b677a3acc62001ffbf09b77ce73e96aa0..437bab6b8318992c3aef42c12f20ecd1c14cfb2f 100644
--- a/src/share/native/java/io/RandomAccessFile.c
+++ b/src/share/native/java/io/RandomAccessFile.c
@@ -76,13 +76,13 @@ Java_java_io_RandomAccessFile_readBytes(JNIEnv *env,
JNIEXPORT void JNICALL
Java_java_io_RandomAccessFile_write(JNIEnv *env, jobject this, jint byte) {
- writeSingle(env, this, byte, raf_fd);
+ writeSingle(env, this, byte, JNI_FALSE, raf_fd);
}
JNIEXPORT void JNICALL
Java_java_io_RandomAccessFile_writeBytes(JNIEnv *env,
jobject this, jbyteArray bytes, jint off, jint len) {
- writeBytes(env, this, bytes, off, len, raf_fd);
+ writeBytes(env, this, bytes, off, len, JNI_FALSE, raf_fd);
}
JNIEXPORT jlong JNICALL
diff --git a/src/share/native/java/io/io_util.c b/src/share/native/java/io/io_util.c
index 986416e20d839c2126d738e031e7d61dd3292163..cef7d272ba24f8785f19c520bca331a5d1383429 100644
--- a/src/share/native/java/io/io_util.c
+++ b/src/share/native/java/io/io_util.c
@@ -127,7 +127,7 @@ readBytes(JNIEnv *env, jobject this, jbyteArray bytes,
}
void
-writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid) {
+writeSingle(JNIEnv *env, jobject this, jint byte, jboolean append, jfieldID fid) {
// Discard the 24 high-order bits of byte. See OutputStream#write(int)
char c = (char) byte;
jint n;
@@ -136,7 +136,11 @@ writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid) {
JNU_ThrowIOException(env, "Stream Closed");
return;
}
- n = IO_Write(fd, &c, 1);
+ if (append == JNI_TRUE) {
+ n = IO_Append(fd, &c, 1);
+ } else {
+ n = IO_Write(fd, &c, 1);
+ }
if (n == JVM_IO_ERR) {
JNU_ThrowIOExceptionWithLastError(env, "Write error");
} else if (n == JVM_IO_INTR) {
@@ -146,7 +150,7 @@ writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid) {
void
writeBytes(JNIEnv *env, jobject this, jbyteArray bytes,
- jint off, jint len, jfieldID fid)
+ jint off, jint len, jboolean append, jfieldID fid)
{
jint n;
char stackBuf[BUF_SIZE];
@@ -185,7 +189,11 @@ writeBytes(JNIEnv *env, jobject this, jbyteArray bytes,
JNU_ThrowIOException(env, "Stream Closed");
break;
}
- n = IO_Write(fd, buf+off, len);
+ if (append == JNI_TRUE) {
+ n = IO_Append(fd, buf+off, len);
+ } else {
+ n = IO_Write(fd, buf+off, len);
+ }
if (n == JVM_IO_ERR) {
JNU_ThrowIOExceptionWithLastError(env, "Write error");
break;
diff --git a/src/share/native/java/io/io_util.h b/src/share/native/java/io/io_util.h
index 436acdff16d21d73b2015d5692a44dbb3c3cd4c1..b98c5274a4818dd31f12e9a46b023f318699455e 100644
--- a/src/share/native/java/io/io_util.h
+++ b/src/share/native/java/io/io_util.h
@@ -41,9 +41,9 @@ extern jfieldID IO_handle_fdID;
jint readSingle(JNIEnv *env, jobject this, jfieldID fid);
jint readBytes(JNIEnv *env, jobject this, jbyteArray bytes, jint off,
jint len, jfieldID fid);
-void writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid);
+void writeSingle(JNIEnv *env, jobject this, jint byte, jboolean append, jfieldID fid);
void writeBytes(JNIEnv *env, jobject this, jbyteArray bytes, jint off,
- jint len, jfieldID fid);
+ jint len, jboolean append, jfieldID fid);
void fileOpen(JNIEnv *env, jobject this, jstring path, jfieldID fid, int flags);
void throwFileNotFoundException(JNIEnv *env, jstring path);
diff --git a/src/share/native/java/util/zip/Deflater.c b/src/share/native/java/util/zip/Deflater.c
index f0923c447ba1fb27149beabb6f1578f66534bebd..e12d540a5444865d1135e22bb1e74d3a119f7cbe 100644
--- a/src/share/native/java/util/zip/Deflater.c
+++ b/src/share/native/java/util/zip/Deflater.c
@@ -132,14 +132,17 @@ Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr,
in_buf = (jbyte *) malloc(this_len);
if (in_buf == 0) {
- JNU_ThrowOutOfMemoryError(env, 0);
+ // Throw OOME only when length is not zero
+ if (this_len != 0)
+ JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
(*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
out_buf = (jbyte *) malloc(len);
if (out_buf == 0) {
free(in_buf);
- JNU_ThrowOutOfMemoryError(env, 0);
+ if (len != 0)
+ JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
@@ -173,7 +176,8 @@ Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr,
jboolean finish = (*env)->GetBooleanField(env, this, finishID);
in_buf = (jbyte *) malloc(this_len);
if (in_buf == 0) {
- JNU_ThrowOutOfMemoryError(env, 0);
+ if (this_len != 0)
+ JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
(*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
@@ -181,7 +185,8 @@ Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr,
out_buf = (jbyte *) malloc(len);
if (out_buf == 0) {
free(in_buf);
- JNU_ThrowOutOfMemoryError(env, 0);
+ if (len != 0)
+ JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
diff --git a/src/share/native/java/util/zip/Inflater.c b/src/share/native/java/util/zip/Inflater.c
index 78619f4ac0f0d7f9f1bd4ef9c2922251ae511f60..c1667a022e842defbeac6db191139172f2e36028 100644
--- a/src/share/native/java/util/zip/Inflater.c
+++ b/src/share/native/java/util/zip/Inflater.c
@@ -135,7 +135,8 @@ Java_java_util_zip_Inflater_inflateBytes(JNIEnv *env, jobject this, jlong addr,
in_buf = (jbyte *) malloc(in_len);
if (in_buf == 0) {
- JNU_ThrowOutOfMemoryError(env, 0);
+ if (in_len != 0)
+ JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
(*env)->GetByteArrayRegion(env, this_buf, this_off, in_len, in_buf);
@@ -143,7 +144,8 @@ Java_java_util_zip_Inflater_inflateBytes(JNIEnv *env, jobject this, jlong addr,
out_buf = (jbyte *) malloc(len);
if (out_buf == 0) {
free(in_buf);
- JNU_ThrowOutOfMemoryError(env, 0);
+ if (len != 0)
+ JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
diff --git a/src/solaris/classes/java/lang/ProcessImpl.java b/src/solaris/classes/java/lang/ProcessImpl.java
index 5c291b138c31419097ea64e9f8a6b58d9090da6a..ed0c6397677007a2e6529dbe7f907115cfe3ddc3 100644
--- a/src/solaris/classes/java/lang/ProcessImpl.java
+++ b/src/solaris/classes/java/lang/ProcessImpl.java
@@ -111,7 +111,8 @@ final class ProcessImpl {
else if (redirects[1] == Redirect.INHERIT)
std_fds[1] = 1;
else {
- f1 = redirects[1].toFileOutputStream();
+ f1 = new FileOutputStream(redirects[1].file(),
+ redirects[1].append());
std_fds[1] = fdAccess.get(f1.getFD());
}
@@ -120,7 +121,8 @@ final class ProcessImpl {
else if (redirects[2] == Redirect.INHERIT)
std_fds[2] = 2;
else {
- f2 = redirects[2].toFileOutputStream();
+ f2 = new FileOutputStream(redirects[2].file(),
+ redirects[2].append());
std_fds[2] = fdAccess.get(f2.getFD());
}
}
diff --git a/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java b/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java
index 57a0492ddee0fc045174645bad2c478d07f82de1..f67efb57fb687b6982e343dd0f4f4c3082099827 100644
--- a/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java
+++ b/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java
@@ -42,11 +42,19 @@ class GtkFileDialogPeer extends XDialogPeer implements FileDialogPeer {
private FileDialog fd;
+ // A pointer to the native GTK FileChooser widget
+ private volatile long widget = 0L;
+
public GtkFileDialogPeer(FileDialog fd) {
super((Dialog) fd);
this.fd = fd;
}
+ private static native void initIDs();
+ static {
+ initIDs();
+ }
+
private native void run(String title, int mode, String dir, String file,
FilenameFilter filter, boolean isMultipleMode);
diff --git a/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java b/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java
index 6f17340372e3692b443802073415c94ed2a757dd..f56d317cc91106563daa298ade43f6e6ddf8fa10 100644
--- a/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java
+++ b/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java
@@ -35,6 +35,13 @@ class FileDispatcherImpl extends FileDispatcher
init();
}
+ FileDispatcherImpl(boolean append) {
+ /* append is ignored */
+ }
+
+ FileDispatcherImpl() {
+ }
+
int read(FileDescriptor fd, long address, int len) throws IOException {
return read0(fd, address, len);
}
diff --git a/src/solaris/native/java/io/FileOutputStream_md.c b/src/solaris/native/java/io/FileOutputStream_md.c
index 1d71052ec5651005840f82ce5b1b2db9fb8323ac..ffc2011797ddb9e02f5eeffecac77e1f7ce344a0 100644
--- a/src/solaris/native/java/io/FileOutputStream_md.c
+++ b/src/solaris/native/java/io/FileOutputStream_md.c
@@ -60,14 +60,14 @@ Java_java_io_FileOutputStream_open(JNIEnv *env, jobject this,
}
JNIEXPORT void JNICALL
-Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte) {
- writeSingle(env, this, byte, fos_fd);
+Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte, jboolean append) {
+ writeSingle(env, this, byte, append, fos_fd);
}
JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_writeBytes(JNIEnv *env,
- jobject this, jbyteArray bytes, jint off, jint len) {
- writeBytes(env, this, bytes, off, len, fos_fd);
+ jobject this, jbyteArray bytes, jint off, jint len, jboolean append) {
+ writeBytes(env, this, bytes, off, len, append, fos_fd);
}
JNIEXPORT void JNICALL
diff --git a/src/solaris/native/java/io/io_util_md.h b/src/solaris/native/java/io/io_util_md.h
index 378fbcb1ebc24f4a3dbfcd4ceea7a2fb93ec1561..b5fe90e6a7387b89505703d44962010bdfca85d8 100644
--- a/src/solaris/native/java/io/io_util_md.h
+++ b/src/solaris/native/java/io/io_util_md.h
@@ -53,8 +53,9 @@
#define THIS_FD(obj) (*env)->GetIntField(env, obj, IO_fd_fdID)
/*
- * Route the routines through HPI
+ * Route the routines through VM
*/
+#define IO_Append JVM_Write
#define IO_Write JVM_Write
#define IO_Sync JVM_Sync
#define IO_Read JVM_Read
diff --git a/src/solaris/native/sun/awt/awt_MToolkit.c b/src/solaris/native/sun/awt/awt_MToolkit.c
index 744646cf38ff5c3a77e4fbd00f5c442b4e8f4596..3a7c117b23bd1ff9acd6b789221f357b5a4a25c6 100644
--- a/src/solaris/native/sun/awt/awt_MToolkit.c
+++ b/src/solaris/native/sun/awt/awt_MToolkit.c
@@ -2773,11 +2773,6 @@ Java_sun_awt_motif_MToolkit_init(JNIEnv *env, jobject this,
}
}
- /*
- scrollBugWorkAround =
- (strcmp(XServerVendor(awt_display), "Sun Microsystems, Inc.") == 0
- && XVendorRelease(awt_display) == 3400);
- */
scrollBugWorkAround = TRUE;
/*
diff --git a/src/solaris/native/sun/awt/fontpath.c b/src/solaris/native/sun/awt/fontpath.c
index e7236e4a6ff3cce8e197827f82db38f09685b40e..22157d35a4e3f6bc19749f6ee581c5f59ef36771 100644
--- a/src/solaris/native/sun/awt/fontpath.c
+++ b/src/solaris/native/sun/awt/fontpath.c
@@ -557,7 +557,8 @@ JNIEXPORT jstring JNICALL Java_sun_awt_X11FontManager_getFontPath
#ifndef HEADLESS
static int isSunXServer() {
#ifdef __solaris__
- return (strcmp("Sun Microsystems, Inc.", ServerVendor(awt_display)) == 0 &&
+ return ((strncmp(ServerVendor(awt_display), "Sun Microsystems, Inc.", 22) == 0) ||
+ (strncmp(ServerVendor(awt_display), "Oracle Corporation", 18) == 0) &&
VendorRelease(awt_display) >= 6410);
#else
return 0;
diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c
index 0c26096e58009cb3852cee3ed4b94865cfa40f6c..890284e570e423f7123035c75cd775f449e723ce 100644
--- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c
+++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c
@@ -4,13 +4,29 @@
#include
#include "gtk2_interface.h"
#include "sun_awt_X11_GtkFileDialogPeer.h"
+#include "debug_assert.h"
static JavaVM *jvm;
-static GtkWidget *dialog = NULL;
/* To cache some method IDs */
static jmethodID filenameFilterCallbackMethodID = NULL;
static jmethodID setFileInternalMethodID = NULL;
+static jfieldID widgetFieldID = NULL;
+
+JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs
+(JNIEnv *env, jclass cx)
+{
+ filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx,
+ "filenameFilterCallback", "(Ljava/lang/String;)Z");
+ DASSERT(filenameFilterCallbackMethodID != NULL);
+
+ setFileInternalMethodID = (*env)->GetMethodID(env, cx,
+ "setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V");
+ DASSERT(setFileInternalMethodID != NULL);
+
+ widgetFieldID = (*env)->GetFieldID(env, cx, "widget", "J");
+ DASSERT(widgetFieldID != NULL);
+}
static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gpointer obj)
{
@@ -20,30 +36,17 @@ static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gp
env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2);
- if (filenameFilterCallbackMethodID == NULL) {
- cx = (*env)->GetObjectClass(env, (jobject) obj);
- if (cx == NULL) {
- JNU_ThrowInternalError(env, "Could not get file filter class");
- return 0;
- }
-
- filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx,
- "filenameFilterCallback", "(Ljava/lang/String;)Z");
- if (filenameFilterCallbackMethodID == NULL) {
- JNU_ThrowInternalError(env,
- "Could not get filenameFilterCallback method id");
- return 0;
- }
- }
-
filename = (*env)->NewStringUTF(env, filter_info->filename);
return (*env)->CallBooleanMethod(env, obj, filenameFilterCallbackMethodID,
filename);
}
-static void quit(gboolean isSignalHandler)
+static void quit(JNIEnv * env, jobject jpeer, gboolean isSignalHandler)
{
+ GtkWidget * dialog = (GtkWidget*)jlong_to_ptr(
+ (*env)->GetLongField(env, jpeer, widgetFieldID));
+
if (dialog != NULL)
{
// Callbacks from GTK signals are made within the GTK lock
@@ -57,7 +60,8 @@ static void quit(gboolean isSignalHandler)
fp_gtk_widget_destroy (dialog);
fp_gtk_main_quit ();
- dialog = NULL;
+
+ (*env)->SetLongField(env, jpeer, widgetFieldID, 0);
if (!isSignalHandler) {
fp_gdk_threads_leave();
@@ -73,7 +77,7 @@ static void quit(gboolean isSignalHandler)
JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_quit
(JNIEnv * env, jobject jpeer)
{
- quit(FALSE);
+ quit(env, jpeer, FALSE);
}
/**
@@ -132,24 +136,8 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj)
if (responseId == GTK_RESPONSE_ACCEPT) {
current_folder = fp_gtk_file_chooser_get_current_folder(
- GTK_FILE_CHOOSER(dialog));
- filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog));
- }
-
- if (setFileInternalMethodID == NULL) {
- cx = (*env)->GetObjectClass(env, (jobject) obj);
- if (cx == NULL) {
- JNU_ThrowInternalError(env, "Could not get GTK peer class");
- return;
- }
-
- setFileInternalMethodID = (*env)->GetMethodID(env, cx,
- "setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V");
- if (setFileInternalMethodID == NULL) {
- JNU_ThrowInternalError(env,
- "Could not get setFileInternalMethodID method id");
- return;
- }
+ GTK_FILE_CHOOSER(aDialog));
+ filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(aDialog));
}
jcurrent_folder = (*env)->NewStringUTF(env, current_folder);
@@ -159,7 +147,7 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj)
jfilenames);
fp_g_free(current_folder);
- quit(TRUE);
+ quit(env, (jobject)obj, TRUE);
}
/*
@@ -172,6 +160,7 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer,
jstring jtitle, jint mode, jstring jdir, jstring jfile,
jobject jfilter, jboolean multiple)
{
+ GtkWidget *dialog = NULL;
GtkFileFilter *filter;
if (jvm == NULL) {
@@ -233,8 +222,12 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer,
fp_g_signal_connect(G_OBJECT(dialog), "response", G_CALLBACK(
handle_response), jpeer);
+
+ (*env)->SetLongField(env, jpeer, widgetFieldID, ptr_to_jlong(dialog));
+
fp_gtk_widget_show(dialog);
fp_gtk_main();
fp_gdk_threads_leave();
}
+
diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h
index 91334b4ebeec3bfbe9ec58d0c8940f49297932e2..7c3c2338d10d4a85ed286520141b32db94d0962f 100644
--- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h
+++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h
@@ -9,6 +9,14 @@ extern "C"
{
#endif
+/*
+ * Class: sun_awt_X11_GtkFileDialogPeer
+ * Method: initIDs
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs
+(JNIEnv *, jclass);
+
/*
* Class: sun_awt_X11_GtkFileDialogPeer
* Method: run
diff --git a/src/solaris/native/sun/xawt/XWindow.c b/src/solaris/native/sun/xawt/XWindow.c
index 4a66d4d7e6bf6c903a82271e8ac386ab9c64c9e0..d33c87f424c9393535c75fd8a758b711c6c27767 100644
--- a/src/solaris/native/sun/xawt/XWindow.c
+++ b/src/solaris/native/sun/xawt/XWindow.c
@@ -766,7 +766,9 @@ adjustKeySym(XEvent *event, KeySym *keysym)
static Boolean
isXsunServer(XEvent *event) {
if( awt_ServerDetected ) return awt_IsXsun;
- if( strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 32) ) {
+ if( (strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 22) != 0) &&
+ (strncmp( ServerVendor( event->xkey.display ), "Oracle Corporation", 18) != 0) )
+ {
awt_ServerDetected = True;
awt_IsXsun = False;
return False;
diff --git a/src/windows/classes/java/lang/ProcessImpl.java b/src/windows/classes/java/lang/ProcessImpl.java
index c0a0daa09a8428bd9a2086cb0287a6eba454ee3c..b3357dd0c9d58dc5f2d0af2aba3fe8ae9e7c5178 100644
--- a/src/windows/classes/java/lang/ProcessImpl.java
+++ b/src/windows/classes/java/lang/ProcessImpl.java
@@ -35,6 +35,8 @@ import java.io.FileDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.lang.ProcessBuilder.Redirect;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
/* This class is for the exclusive use of ProcessBuilder.start() to
* create new processes.
@@ -47,6 +49,35 @@ final class ProcessImpl extends Process {
private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
= sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
+ /**
+ * Open a file for writing. If {@code append} is {@code true} then the file
+ * is opened for atomic append directly and a FileOutputStream constructed
+ * with the resulting handle. This is because a FileOutputStream created
+ * to append to a file does not open the file in a manner that guarantees
+ * that writes by the child process will be atomic.
+ */
+ private static FileOutputStream newFileOutputStream(File f, boolean append)
+ throws IOException
+ {
+ if (append) {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkWrite(f.getPath());
+ long handle = openForAtomicAppend(f.getPath());
+ final FileDescriptor fd = new FileDescriptor();
+ fdAccess.setHandle(fd, handle);
+ return AccessController.doPrivileged(
+ new PrivilegedAction() {
+ public FileOutputStream run() {
+ return new FileOutputStream(fd);
+ }
+ }
+ );
+ } else {
+ return new FileOutputStream(f);
+ }
+ }
+
// System-dependent portion of ProcessBuilder.start()
static Process start(String cmdarray[],
java.util.Map environment,
@@ -82,7 +113,8 @@ final class ProcessImpl extends Process {
else if (redirects[1] == Redirect.INHERIT)
stdHandles[1] = fdAccess.getHandle(FileDescriptor.out);
else {
- f1 = redirects[1].toFileOutputStream();
+ f1 = newFileOutputStream(redirects[1].file(),
+ redirects[1].append());
stdHandles[1] = fdAccess.getHandle(f1.getFD());
}
@@ -91,7 +123,8 @@ final class ProcessImpl extends Process {
else if (redirects[2] == Redirect.INHERIT)
stdHandles[2] = fdAccess.getHandle(FileDescriptor.err);
else {
- f2 = redirects[2].toFileOutputStream();
+ f2 = newFileOutputStream(redirects[2].file(),
+ redirects[2].append());
stdHandles[2] = fdAccess.getHandle(f2.getFD());
}
}
@@ -251,5 +284,15 @@ final class ProcessImpl extends Process {
boolean redirectErrorStream)
throws IOException;
+ /**
+ * Opens a file for atomic append. The file is created if it doesn't
+ * already exist.
+ *
+ * @param file the file to open or create
+ * @return the native HANDLE
+ */
+ private static native long openForAtomicAppend(String path)
+ throws IOException;
+
private static native boolean closeHandle(long handle);
}
diff --git a/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java b/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java
index 2cdc8f8fe9fcffc66ff034f13fcff1e41e9b5b0d..43f0745be4084fb6b04a4351b86e59ed02551fe1 100644
--- a/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java
+++ b/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java
@@ -35,6 +35,20 @@ class FileDispatcherImpl extends FileDispatcher
Util.load();
}
+ /**
+ * Indicates if the dispatcher should first advance the file position
+ * to the end of file when writing.
+ */
+ private final boolean append;
+
+ FileDispatcherImpl(boolean append) {
+ this.append = append;
+ }
+
+ FileDispatcherImpl() {
+ this(false);
+ }
+
int read(FileDescriptor fd, long address, int len)
throws IOException
{
@@ -54,7 +68,7 @@ class FileDispatcherImpl extends FileDispatcher
}
int write(FileDescriptor fd, long address, int len) throws IOException {
- return write0(fd, address, len);
+ return write0(fd, address, len, append);
}
int pwrite(FileDescriptor fd, long address, int len,
@@ -66,7 +80,7 @@ class FileDispatcherImpl extends FileDispatcher
}
long writev(FileDescriptor fd, long address, int len) throws IOException {
- return writev0(fd, address, len);
+ return writev0(fd, address, len, append);
}
int force(FileDescriptor fd, boolean metaData) throws IOException {
@@ -116,13 +130,13 @@ class FileDispatcherImpl extends FileDispatcher
static native long readv0(FileDescriptor fd, long address, int len)
throws IOException;
- static native int write0(FileDescriptor fd, long address, int len)
+ static native int write0(FileDescriptor fd, long address, int len, boolean append)
throws IOException;
static native int pwrite0(FileDescriptor fd, long address, int len,
long position) throws IOException;
- static native long writev0(FileDescriptor fd, long address, int len)
+ static native long writev0(FileDescriptor fd, long address, int len, boolean append)
throws IOException;
static native int force0(FileDescriptor fd, boolean metaData)
diff --git a/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java b/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java
index 3795a6f40d2e9552e10f6624e2886a7b0f1d7ba8..736ea7b1ea0562336af9af8fd90e2420f026ec3d 100644
--- a/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java
+++ b/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java
@@ -157,7 +157,7 @@ class WindowsChannelFactory {
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
- return FileChannelImpl.open(fdObj, flags.read, flags.write, null);
+ return FileChannelImpl.open(fdObj, flags.read, flags.write, flags.append, null);
}
/**
@@ -230,7 +230,7 @@ class WindowsChannelFactory {
if (flags.read)
dwDesiredAccess |= GENERIC_READ;
if (flags.write)
- dwDesiredAccess |= (flags.append) ? FILE_APPEND_DATA : GENERIC_WRITE;
+ dwDesiredAccess |= GENERIC_WRITE;
int dwShareMode = 0;
if (flags.shareRead)
diff --git a/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java b/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java
index 9bcc935a1ca2f9fe5e9a9725d229aaf778a31933..216c3a30c1273b908801649438ce18d7bbc04a45 100644
--- a/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java
+++ b/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java
@@ -129,7 +129,7 @@ public class Ktab {
ktab.deleteEntry();
break;
default:
- ktab.printHelp();
+ ktab.error("A command must be provided");
}
}
@@ -232,7 +232,7 @@ public class Ktab {
append = true;
break;
default:
- printHelp();
+ error("Unknown command: " + args[i]);
break;
}
} else { // optional standalone arguments
diff --git a/src/windows/native/java/io/FileOutputStream_md.c b/src/windows/native/java/io/FileOutputStream_md.c
index 221ba504f5f22f3c7377e57c94b6bf48ee676833..23c754d466739bfa796cc3bf9003191707cb2a60 100644
--- a/src/windows/native/java/io/FileOutputStream_md.c
+++ b/src/windows/native/java/io/FileOutputStream_md.c
@@ -61,14 +61,15 @@ Java_java_io_FileOutputStream_open(JNIEnv *env, jobject this,
}
JNIEXPORT void JNICALL
-Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte) {
- writeSingle(env, this, byte, fos_fd);
+Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte, jboolean append) {
+ writeSingle(env, this, byte, append, fos_fd);
}
JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_writeBytes(JNIEnv *env,
- jobject this, jbyteArray bytes, jint off, jint len) {
- writeBytes(env, this, bytes, off, len, fos_fd);
+ jobject this, jbyteArray bytes, jint off, jint len, jboolean append)
+{
+ writeBytes(env, this, bytes, off, len, append, fos_fd);
}
JNIEXPORT void JNICALL
diff --git a/src/windows/native/java/io/io_util_md.c b/src/windows/native/java/io/io_util_md.c
index 722913f775a3a2491bdc8382ac1165cc831d05ee..2679e7b951700986fc28fd75ceba546f71872f2a 100644
--- a/src/windows/native/java/io/io_util_md.c
+++ b/src/windows/native/java/io/io_util_md.c
@@ -225,14 +225,7 @@ pathToNTPath(JNIEnv *env, jstring path, jboolean throwFNFE) {
jlong
winFileHandleOpen(JNIEnv *env, jstring path, int flags)
{
- /* To implement O_APPEND, we use the strategy from
- http://msdn2.microsoft.com/en-us/library/aa363858.aspx
- "You can get atomic append by opening a file with
- FILE_APPEND_DATA access and _without_ FILE_WRITE_DATA access.
- If you do this then all writes will ignore the current file
- pointer and be done at the end-of file." */
const DWORD access =
- (flags & O_APPEND) ? (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA) :
(flags & O_WRONLY) ? GENERIC_WRITE :
(flags & O_RDWR) ? (GENERIC_READ | GENERIC_WRITE) :
GENERIC_READ;
@@ -307,7 +300,6 @@ handleStdinAvailable(jlong, long *);
int
handleAvailable(jlong fd, jlong *pbytes) {
- jlong current, end;
HANDLE h = (HANDLE)fd;
DWORD type = 0;
@@ -327,18 +319,17 @@ handleAvailable(jlong fd, jlong *pbytes) {
}
/* Handle is for regular file */
if (type == FILE_TYPE_DISK) {
- long highPos = 0;
- DWORD sizeLow = 0;
- DWORD sizeHigh = 0;
- DWORD lowPos = SetFilePointer(h, 0, &highPos, FILE_CURRENT);
- if (lowPos == ((DWORD)-1)) {
+ jlong current, end;
+
+ LARGE_INTEGER filesize;
+ current = handleLseek(fd, 0, SEEK_CUR);
+ if (current < 0) {
return FALSE;
}
- current = (((jlong)highPos) << 32) | lowPos;
- end = GetFileSize(h, &sizeHigh);
- if (sizeLow == ((DWORD)-1)) {
+ if (GetFileSizeEx(h, &filesize) == 0) {
return FALSE;
}
+ end = long_to_jlong(filesize.QuadPart);
*pbytes = end - current;
return TRUE;
}
@@ -511,24 +502,42 @@ handleRead(jlong fd, void *buf, jint len)
return read;
}
-JNIEXPORT
-size_t
-handleWrite(jlong fd, const void *buf, jint len)
+static size_t writeInternal(jlong fd, const void *buf, jint len, jboolean append)
{
BOOL result = 0;
DWORD written = 0;
HANDLE h = (HANDLE)fd;
if (h != INVALID_HANDLE_VALUE) {
- result = WriteFile(h, /* File handle to write */
- buf, /* pointers to the buffers */
- len, /* number of bytes to write */
- &written, /* receives number of bytes written */
- NULL); /* no overlapped struct */
+ OVERLAPPED ov;
+ LPOVERLAPPED lpOv;
+ if (append == JNI_TRUE) {
+ ov.Offset = (DWORD)0xFFFFFFFF;
+ ov.OffsetHigh = (DWORD)0xFFFFFFFF;
+ ov.hEvent = NULL;
+ lpOv = &ov;
+ } else {
+ lpOv = NULL;
+ }
+ result = WriteFile(h, /* File handle to write */
+ buf, /* pointers to the buffers */
+ len, /* number of bytes to write */
+ &written, /* receives number of bytes written */
+ lpOv); /* overlapped struct */
}
if ((h == INVALID_HANDLE_VALUE) || (result == 0)) {
return -1;
}
- return written;
+ return (size_t)written;
+}
+
+JNIEXPORT
+size_t handleWrite(jlong fd, const void *buf, jint len) {
+ return writeInternal(fd, buf, len, JNI_FALSE);
+}
+
+JNIEXPORT
+size_t handleAppend(jlong fd, const void *buf, jint len) {
+ return writeInternal(fd, buf, len, JNI_TRUE);
}
jint
@@ -558,6 +567,7 @@ handleClose(JNIEnv *env, jobject this, jfieldID fid)
jlong
handleLseek(jlong fd, jlong offset, jint whence)
{
+ LARGE_INTEGER pos, distance;
DWORD lowPos = 0;
long highPos = 0;
DWORD op = FILE_CURRENT;
@@ -573,13 +583,9 @@ handleLseek(jlong fd, jlong offset, jint whence)
op = FILE_BEGIN;
}
- lowPos = (DWORD)offset;
- highPos = (long)(offset >> 32);
- lowPos = SetFilePointer(h, lowPos, &highPos, op);
- if (lowPos == ((DWORD)-1)) {
- if (GetLastError() != ERROR_SUCCESS) {
- return -1;
- }
+ distance.QuadPart = offset;
+ if (SetFilePointerEx(h, distance, &pos, op) == 0) {
+ return -1;
}
- return (((jlong)highPos) << 32) | lowPos;
+ return long_to_jlong(pos.QuadPart);
}
diff --git a/src/windows/native/java/io/io_util_md.h b/src/windows/native/java/io/io_util_md.h
index 6b6b89b6397a998eb28b335dcc553df5c79ffae0..97a68c2febae0cdba5f5335b9a56ab4e42ad66c4 100644
--- a/src/windows/native/java/io/io_util_md.h
+++ b/src/windows/native/java/io/io_util_md.h
@@ -41,6 +41,7 @@ JNIEXPORT int handleSync(jlong fd);
int handleSetLength(jlong fd, jlong length);
JNIEXPORT size_t handleRead(jlong fd, void *buf, jint len);
JNIEXPORT size_t handleWrite(jlong fd, const void *buf, jint len);
+JNIEXPORT size_t handleAppend(jlong fd, const void *buf, jint len);
jint handleClose(JNIEnv *env, jobject this, jfieldID fid);
jlong handleLseek(jlong fd, jlong offset, jint whence);
@@ -74,8 +75,9 @@ jlong winFileHandleOpen(JNIEnv *env, jstring path, int flags);
#define THIS_FD(obj) (*env)->GetLongField(env, obj, IO_handle_fdID)
/*
- * Route the routines away from HPI layer
+ * Route the routines away from VM
*/
+#define IO_Append handleAppend
#define IO_Write handleWrite
#define IO_Sync handleSync
#define IO_Read handleRead
diff --git a/src/windows/native/java/lang/ProcessImpl_md.c b/src/windows/native/java/lang/ProcessImpl_md.c
index e5fe23e71ec842515a3851557cbc77a11bbdadcb..afc5e7d2529acda414732ac0c78f4fac37e7aa20 100644
--- a/src/windows/native/java/lang/ProcessImpl_md.c
+++ b/src/windows/native/java/lang/ProcessImpl_md.c
@@ -315,3 +315,51 @@ Java_java_lang_ProcessImpl_closeHandle(JNIEnv *env, jclass ignored, jlong handle
{
return CloseHandle((HANDLE) handle);
}
+
+/**
+ * Returns a copy of the Unicode characters of a string. Fow now this
+ * function doesn't handle long path names and other issues.
+ */
+static WCHAR* getPath(JNIEnv *env, jstring ps) {
+ WCHAR *pathbuf = NULL;
+ const jchar *chars = (*(env))->GetStringChars(env, ps, NULL);
+ if (chars != NULL) {
+ size_t pathlen = wcslen(chars);
+ pathbuf = (WCHAR*)malloc((pathlen + 6) * sizeof(WCHAR));
+ if (pathbuf == NULL) {
+ JNU_ThrowOutOfMemoryError(env, NULL);
+ } else {
+ wcscpy(pathbuf, chars);
+ }
+ (*env)->ReleaseStringChars(env, ps, chars);
+ }
+ return pathbuf;
+}
+
+JNIEXPORT jlong JNICALL
+Java_java_lang_ProcessImpl_openForAtomicAppend(JNIEnv *env, jclass ignored, jstring path)
+{
+ const DWORD access = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA);
+ const DWORD sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
+ const DWORD disposition = OPEN_ALWAYS;
+ const DWORD flagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
+ HANDLE h;
+ WCHAR *pathbuf = getPath(env, path);
+ if (pathbuf == NULL) {
+ /* Exception already pending */
+ return -1;
+ }
+ h = CreateFileW(
+ pathbuf, /* Wide char path name */
+ access, /* Read and/or write permission */
+ sharing, /* File sharing flags */
+ NULL, /* Security attributes */
+ disposition, /* creation disposition */
+ flagsAndAttributes, /* flags and attributes */
+ NULL);
+ free(pathbuf);
+ if (h == INVALID_HANDLE_VALUE) {
+ JNU_ThrowIOExceptionWithLastError(env, "CreateFileW");
+ }
+ return ptr_to_jlong(h);
+}
diff --git a/src/windows/native/sun/nio/ch/FileDispatcherImpl.c b/src/windows/native/sun/nio/ch/FileDispatcherImpl.c
index f4d0b17d63b94a599c4c07f2b6fe36fac26e1ae5..2a146c284facabd6c441aa8cd379554188918db9 100644
--- a/src/windows/native/sun/nio/ch/FileDispatcherImpl.c
+++ b/src/windows/native/sun/nio/ch/FileDispatcherImpl.c
@@ -184,18 +184,28 @@ Java_sun_nio_ch_FileDispatcherImpl_pread0(JNIEnv *env, jclass clazz, jobject fdo
JNIEXPORT jint JNICALL
Java_sun_nio_ch_FileDispatcherImpl_write0(JNIEnv *env, jclass clazz, jobject fdo,
- jlong address, jint len)
+ jlong address, jint len, jboolean append)
{
BOOL result = 0;
DWORD written = 0;
HANDLE h = (HANDLE)(handleval(env, fdo));
if (h != INVALID_HANDLE_VALUE) {
+ OVERLAPPED ov;
+ LPOVERLAPPED lpOv;
+ if (append == JNI_TRUE) {
+ ov.Offset = (DWORD)0xFFFFFFFF;
+ ov.OffsetHigh = (DWORD)0xFFFFFFFF;
+ ov.hEvent = NULL;
+ lpOv = &ov;
+ } else {
+ lpOv = NULL;
+ }
result = WriteFile(h, /* File handle to write */
(LPCVOID)address, /* pointers to the buffers */
len, /* number of bytes to write */
&written, /* receives number of bytes written */
- NULL); /* no overlapped struct */
+ lpOv); /* overlapped struct */
}
if ((h == INVALID_HANDLE_VALUE) || (result == 0)) {
@@ -207,7 +217,7 @@ Java_sun_nio_ch_FileDispatcherImpl_write0(JNIEnv *env, jclass clazz, jobject fdo
JNIEXPORT jlong JNICALL
Java_sun_nio_ch_FileDispatcherImpl_writev0(JNIEnv *env, jclass clazz, jobject fdo,
- jlong address, jint len)
+ jlong address, jint len, jboolean append)
{
BOOL result = 0;
DWORD written = 0;
@@ -219,7 +229,16 @@ Java_sun_nio_ch_FileDispatcherImpl_writev0(JNIEnv *env, jclass clazz, jobject fd
int i = 0;
DWORD num = 0;
struct iovec *iovecp = (struct iovec *)jlong_to_ptr(address);
-
+ OVERLAPPED ov;
+ LPOVERLAPPED lpOv;
+ if (append == JNI_TRUE) {
+ ov.Offset = (DWORD)0xFFFFFFFF;
+ ov.OffsetHigh = (DWORD)0xFFFFFFFF;
+ ov.hEvent = NULL;
+ lpOv = &ov;
+ } else {
+ lpOv = NULL;
+ }
for(i=0; i 0) {
totalWritten += written;
}
@@ -444,9 +463,10 @@ Java_sun_nio_ch_FileDispatcherImpl_closeByHandle(JNIEnv *env, jclass clazz,
}
JNIEXPORT jlong JNICALL
-Java_sun_nio_ch_FileDispatcherImpl_duplicateHandle(JNIEnv *env, jclass this, jlong hFile)
+Java_sun_nio_ch_FileDispatcherImpl_duplicateHandle(JNIEnv *env, jclass this, jlong handle)
{
HANDLE hProcess = GetCurrentProcess();
+ HANDLE hFile = jlong_to_ptr(handle);
HANDLE hResult;
BOOL res = DuplicateHandle(hProcess, hFile, hProcess, &hResult, 0, FALSE,
DUPLICATE_SAME_ACCESS);
diff --git a/src/windows/native/sun/windows/awt_Component.cpp b/src/windows/native/sun/windows/awt_Component.cpp
index 71307cb9e58b81de1eb24defea433100f8637fb7..fd75b8d52ee75fd5587764ee36e96cccf9e71676 100644
--- a/src/windows/native/sun/windows/awt_Component.cpp
+++ b/src/windows/native/sun/windows/awt_Component.cpp
@@ -6084,63 +6084,67 @@ void AwtComponent::SetParent(void * param) {
void AwtComponent::_SetRectangularShape(void *param)
{
- JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+ if (!AwtToolkit::IsMainThread()) {
+ AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_SetRectangularShape, param);
+ } else {
+ JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
- SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param;
- jobject self = data->component;
- jint x1 = data->x1;
- jint x2 = data->x2;
- jint y1 = data->y1;
- jint y2 = data->y2;
- jobject region = data->region;
+ SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param;
+ jobject self = data->component;
+ jint x1 = data->x1;
+ jint x2 = data->x2;
+ jint y1 = data->y1;
+ jint y2 = data->y2;
+ jobject region = data->region;
- AwtComponent *c = NULL;
+ AwtComponent *c = NULL;
- PDATA pData;
- JNI_CHECK_PEER_GOTO(self, ret);
+ PDATA pData;
+ JNI_CHECK_PEER_GOTO(self, ret);
- c = (AwtComponent *)pData;
- if (::IsWindow(c->GetHWnd())) {
- HRGN hRgn = NULL;
- if (region || x1 || x2 || y1 || y2) {
- // If all the params are zeros, the shape must be simply reset.
- // Otherwise, convert it into a region.
- RGNDATA *pRgnData = NULL;
- RGNDATAHEADER *pRgnHdr;
-
- /* reserving memory for the worst case */
- size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1));
- pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) +
- sizeof(RECT_T) * worstBufferSize);
- pRgnHdr = (RGNDATAHEADER *) pRgnData;
-
- pRgnHdr->dwSize = sizeof(RGNDATAHEADER);
- pRgnHdr->iType = RDH_RECTANGLES;
- pRgnHdr->nRgnSize = 0;
- pRgnHdr->rcBound.top = 0;
- pRgnHdr->rcBound.left = 0;
- pRgnHdr->rcBound.bottom = LONG(y2 - y1);
- pRgnHdr->rcBound.right = LONG(x2 - x1);
-
- RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER));
- pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize);
-
- hRgn = ::ExtCreateRegion(NULL,
- sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData);
-
- free(pRgnData);
- }
+ c = (AwtComponent *)pData;
+ if (::IsWindow(c->GetHWnd())) {
+ HRGN hRgn = NULL;
+ if (region || x1 || x2 || y1 || y2) {
+ // If all the params are zeros, the shape must be simply reset.
+ // Otherwise, convert it into a region.
+ RGNDATA *pRgnData = NULL;
+ RGNDATAHEADER *pRgnHdr;
+
+ /* reserving memory for the worst case */
+ size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1));
+ pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) +
+ sizeof(RECT_T) * worstBufferSize);
+ pRgnHdr = (RGNDATAHEADER *) pRgnData;
+
+ pRgnHdr->dwSize = sizeof(RGNDATAHEADER);
+ pRgnHdr->iType = RDH_RECTANGLES;
+ pRgnHdr->nRgnSize = 0;
+ pRgnHdr->rcBound.top = 0;
+ pRgnHdr->rcBound.left = 0;
+ pRgnHdr->rcBound.bottom = LONG(y2 - y1);
+ pRgnHdr->rcBound.right = LONG(x2 - x1);
+
+ RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER));
+ pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize);
+
+ hRgn = ::ExtCreateRegion(NULL,
+ sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData);
+
+ free(pRgnData);
+ }
- ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE);
- }
+ ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE);
+ }
ret:
- env->DeleteGlobalRef(self);
- if (region) {
- env->DeleteGlobalRef(region);
- }
+ env->DeleteGlobalRef(self);
+ if (region) {
+ env->DeleteGlobalRef(region);
+ }
- delete data;
+ delete data;
+ }
}
void AwtComponent::_SetZOrder(void *param) {
diff --git a/src/windows/native/sun/windows/awt_Robot.cpp b/src/windows/native/sun/windows/awt_Robot.cpp
index bef6f13ede5e79ffb85d3d66d5e96a437be61a67..bab9f61b8b780c7b2460eec9890dc0dbfd76e862 100644
--- a/src/windows/native/sun/windows/awt_Robot.cpp
+++ b/src/windows/native/sun/windows/awt_Robot.cpp
@@ -194,9 +194,9 @@ inline jint AwtRobot::WinToJavaPixel(USHORT r, USHORT g, USHORT b)
jint AwtRobot::GetRGBPixel( jint x, jint y)
{
- HDC hdc = GetDC(NULL);
+ HDC hdc = ::CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
COLORREF ref = ::GetPixel( hdc, x, y );
- ReleaseDC(NULL,hdc);
+ ::DeleteDC(hdc);
jint value = WinToJavaPixel(GetRValue(ref), GetGValue(ref), GetBValue(ref));
return value;
}
diff --git a/test/com/sun/jndi/ldap/InvalidLdapFilters.java b/test/com/sun/jndi/ldap/InvalidLdapFilters.java
index 5cadd3ad5b29c46b163fc00572640eab9d5fb4de..e0e0e906a653593a583f9ded3bbe1e3cc6429eb6 100644
--- a/test/com/sun/jndi/ldap/InvalidLdapFilters.java
+++ b/test/com/sun/jndi/ldap/InvalidLdapFilters.java
@@ -48,6 +48,8 @@
* @run main/othervm InvalidLdapFilters valid (sn;lang-en:dn:2.4.6.8.10:=Barney)
* @run main/othervm InvalidLdapFilters valid
(&(objectClass=Person)(|(sn=Jensen)(cn=Bab*)))
+ * @run main/othervm InvalidLdapFilters valid
+ (orcluserapplnprovstatus;EMAIL_email=PROVISIONING_FAILURE)
* @run main/othervm InvalidLdapFilters invalid "(&(cn=Robert Dean)))"
* @run main/othervm InvalidLdapFilters invalid (&|(cn=Bob))
* @run main/othervm InvalidLdapFilters invalid (&&(cn=Bob))
diff --git a/test/demo/zipfs/Basic.java b/test/demo/zipfs/Basic.java
index 91f8af274eeedec25d058756d47c6fd260999b65..8341b939273aed546195ad786c6d7225b739225a 100644
--- a/test/demo/zipfs/Basic.java
+++ b/test/demo/zipfs/Basic.java
@@ -40,24 +40,24 @@ public class Basic {
boolean found = false;
for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
- if (provider.getScheme().equalsIgnoreCase("zip")) {
+ if (provider.getScheme().equalsIgnoreCase("jar")) {
found = true;
break;
}
}
if (!found)
- throw new RuntimeException("'zip' provider not installed");
+ throw new RuntimeException("'jar' provider not installed");
// Test: FileSystems#newFileSystem(FileRef)
Map env = new HashMap();
FileSystems.newFileSystem(zipfile, env, null).close();
// Test: FileSystems#newFileSystem(URI)
- URI uri = URI.create("zip" + zipfile.toUri().toString().substring(4));
+ URI uri = new URI("jar", zipfile.toUri().toString(), null);
FileSystem fs = FileSystems.newFileSystem(uri, env, null);
// Test: exercise toUri method
- String expected = uri.toString() + "#/foo";
+ String expected = uri.toString() + "!/foo";
String actual = fs.getPath("/foo").toUri().toString();
if (!actual.equals(expected)) {
throw new RuntimeException("toUri returned '" + actual +
diff --git a/test/demo/zipfs/ZipFSTester.java b/test/demo/zipfs/ZipFSTester.java
index 76a8d7aeed3f5e6e62f759c02fa26391cc9049b3..8c5a104bac233a30910d122d1f12c1013273608f 100644
--- a/test/demo/zipfs/ZipFSTester.java
+++ b/test/demo/zipfs/ZipFSTester.java
@@ -58,7 +58,7 @@ public class ZipFSTester {
// clone a fs and test on it
Path tmpfsPath = getTempPath();
Map env = new HashMap();
- env.put("createNew", true);
+ env.put("create", "true");
FileSystem fs0 = newZipFileSystem(tmpfsPath, env);
z2zcopy(fs, fs0, "/", 0);
fs0.close(); // sync to file
@@ -147,7 +147,7 @@ public class ZipFSTester {
// create a new filesystem, copy everything from fs
Map env = new HashMap();
- env.put("createNew", true);
+ env.put("create", "true");
FileSystem fs0 = newZipFileSystem(fs1Path, env);
final FileSystem fs2 = newZipFileSystem(fs2Path, env);
@@ -282,11 +282,7 @@ public class ZipFSTester {
private static FileSystem newZipFileSystem(Path path, Map env)
throws IOException
{
- return FileSystems.newFileSystem(
- URI.create("zip" +
- path.toUri().toString().substring(4)),
- env,
- null);
+ return FileSystems.newFileSystem(path, env, null);
}
private static Path getTempPath() throws IOException
diff --git a/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java b/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java
new file mode 100644
index 0000000000000000000000000000000000000000..751b38e338bb5241e73ad249a8d1c539fd2f3c09
--- /dev/null
+++ b/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 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.
+ */
+
+/*
+ @test
+ @bug 6988428
+ @summary Tests whether shape is always set
+ @author anthony.petrov@oracle.com: area=awt.toplevel
+ @run main ShapeNotSetSometimes
+*/
+
+
+import java.awt.*;
+import java.awt.event.InputEvent;
+import java.awt.geom.*;
+
+
+public class ShapeNotSetSometimes {
+
+ private Frame backgroundFrame;
+ private Frame window;
+ private static final Color BACKGROUND_COLOR = Color.BLUE;
+ private Shape shape;
+ private int[][] pointsToCheck;
+
+ private static Robot robot;
+
+ public ShapeNotSetSometimes() throws Exception {
+ EventQueue.invokeAndWait(new Runnable() {
+ public void run() {
+ initializeGUI();
+ }
+ });
+ }
+
+ private void initializeGUI() {
+ backgroundFrame = new BackgroundFrame();
+ backgroundFrame.setUndecorated(true);
+ backgroundFrame.setSize(300, 300);
+ backgroundFrame.setLocation(20, 400);
+ backgroundFrame.setVisible(true);
+
+ shape = null;
+ String shape_name = null;
+ Area a;
+ GeneralPath gp;
+ shape_name = "Rounded-corners";
+ a = new Area();
+ a.add(new Area(new Rectangle2D.Float(50, 0, 100, 150)));
+ a.add(new Area(new Rectangle2D.Float(0, 50, 200, 50)));
+ a.add(new Area(new Ellipse2D.Float(0, 0, 100, 100)));
+ a.add(new Area(new Ellipse2D.Float(0, 50, 100, 100)));
+ a.add(new Area(new Ellipse2D.Float(100, 0, 100, 100)));
+ a.add(new Area(new Ellipse2D.Float(100, 50, 100, 100)));
+ shape = a;
+ pointsToCheck = new int[][] {
+ // inside shape
+ {106, 86}, {96, 38}, {76, 107}, {180, 25}, {24, 105},
+ {196, 77}, {165, 50}, {14, 113}, {89, 132}, {167, 117},
+ // outside shape
+ {165, 196}, {191, 163}, {146, 185}, {61, 170}, {148, 171},
+ {82, 172}, {186, 11}, {199, 141}, {13, 173}, {187, 3}
+ };
+
+ window = new TestFrame();
+ window.setUndecorated(true);
+ window.setSize(200, 200);
+ window.setLocation(70, 450);
+ window.setShape(shape);
+ window.setVisible(true);
+
+ System.out.println("Checking " + window.getClass().getSuperclass().getName() + " with " + shape_name + " shape (" + window.getShape() + ")...");
+ }
+
+ class BackgroundFrame extends Frame {
+
+ @Override
+ public void paint(Graphics g) {
+
+ g.setColor(BACKGROUND_COLOR);
+ g.fillRect(0, 0, 300, 300);
+
+ super.paint(g);
+ }
+ }
+
+ class TestFrame extends Frame {
+
+ @Override
+ public void paint(Graphics g) {
+
+ g.setColor(Color.WHITE);
+ g.fillRect(0, 0, 200, 200);
+
+ super.paint(g);
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ robot = new Robot();
+
+ for(int i = 0; i < 100; i++) {
+ System.out.println("Attempt " + i);
+ new ShapeNotSetSometimes().doTest();
+ }
+ }
+
+ private void doTest() throws Exception {
+ Point wls = backgroundFrame.getLocationOnScreen();
+
+ robot.mouseMove(wls.x + 5, wls.y + 5);
+ robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
+ robot.delay(10);
+ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
+ robot.delay(500);
+
+ EventQueue.invokeAndWait(new Runnable() {
+ public void run() {
+ window.requestFocus();
+ }
+ });
+
+ robot.waitForIdle();
+ try {
+ Thread.sleep(300);
+ } catch (InterruptedException e) {
+ // ignore this one
+ }
+
+ // check transparency
+ final int COUNT_TARGET = 10;
+
+ // checking outside points only
+ for(int i = COUNT_TARGET; i < COUNT_TARGET * 2; i++) {
+ int x = pointsToCheck[i][0];
+ int y = pointsToCheck[i][1];
+ boolean inside = i < COUNT_TARGET;
+ Color c = robot.getPixelColor(window.getX() + x, window.getY() + y);
+ System.out.println("checking " + x + ", " + y + ", color = " + c);
+ if (inside && BACKGROUND_COLOR.equals(c) || !inside && !BACKGROUND_COLOR.equals(c)) {
+ System.out.println("window.getX() = " + window.getX() + ", window.getY() = " + window.getY());
+ System.err.println("Checking for transparency failed: point: " +
+ (window.getX() + x) + ", " + (window.getY() + y) +
+ ", color = " + c + (inside ? " is of un" : " is not of ") +
+ "expected background color " + BACKGROUND_COLOR);
+ throw new RuntimeException("Test failed. The shape has not been applied.");
+ }
+ }
+
+ EventQueue.invokeAndWait(new Runnable() {
+ public void run() {
+ backgroundFrame.dispose();
+ window.dispose();
+ }
+ });
+ }
+}
diff --git a/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java b/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java
new file mode 100644
index 0000000000000000000000000000000000000000..34a7b7690570f6082ba3d5615c7f393de869e7b8
--- /dev/null
+++ b/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 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.
+ */
+
+/*
+ @test
+ @bug 6960516
+ @summary check if the ungrab event has the ID < AWTEvent.RESERVED_ID_MAX
+ @author Andrei Dmitriev : area=awt.event
+ @run main UngrabID
+*/
+
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+
+public class UngrabID {
+ public static void main(String[] args){
+ Frame f = new Frame("Dummy");
+ sun.awt.UngrabEvent event = new sun.awt.UngrabEvent(f);
+ if (event.getID() > AWTEvent.RESERVED_ID_MAX) {
+ System.out.println( " Event ID : "+event.getID() + " " + event.toString());
+ throw new RuntimeException(" Ungrab Event ID should be less than AWTEvent.RESERVED_ID_MAX ("+AWTEvent.RESERVED_ID_MAX+"). Actual value : "+event.getID() + " Event:" + event.toString());
+ }
+ System.out.println("Test passed. ");
+ }
+}
diff --git a/test/java/io/FileInputStream/LargeFileAvailable.java b/test/java/io/FileInputStream/LargeFileAvailable.java
new file mode 100644
index 0000000000000000000000000000000000000000..35c9ce47483bc234609a67ae3ba22ea5208b2542
--- /dev/null
+++ b/test/java/io/FileInputStream/LargeFileAvailable.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 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.
+ */
+
+/*
+ * @test
+ * @bug 6402006
+ * @summary Test if available returns correct value when reading
+ * a large file.
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import static java.nio.file.StandardOpenOption.*;
+
+public class LargeFileAvailable {
+ private static final long FILESIZE = 7405576182L;
+ public static void main(String args[]) throws Exception {
+ File file = createLargeFile(FILESIZE);
+ try (FileInputStream fis = new FileInputStream(file)) {
+ if (file.length() != FILESIZE) {
+ throw new RuntimeException("unexpected file size = " + file.length());
+ }
+
+ long bigSkip = 3110608882L;
+ long remaining = FILESIZE;
+ remaining -= skipBytes(fis, bigSkip, remaining);
+ remaining -= skipBytes(fis, 10L, remaining);
+ remaining -= skipBytes(fis, bigSkip, remaining);
+ if (fis.available() != (int) remaining) {
+ throw new RuntimeException("available() returns " +
+ fis.available() +
+ " but expected " + remaining);
+ }
+ } finally {
+ file.delete();
+ }
+ }
+
+ // Skip toSkip number of bytes and expect that the available() method
+ // returns avail number of bytes.
+ private static long skipBytes(InputStream is, long toSkip, long avail)
+ throws IOException {
+ long skip = is.skip(toSkip);
+ if (skip != toSkip) {
+ throw new RuntimeException("skip() returns " + skip +
+ " but expected " + toSkip);
+ }
+ long remaining = avail - skip;
+ int expected = remaining >= Integer.MAX_VALUE
+ ? Integer.MAX_VALUE
+ : (int) remaining;
+
+ System.out.println("Skipped " + skip + " bytes " +
+ " available() returns " + expected +
+ " remaining=" + remaining);
+ if (is.available() != expected) {
+ throw new RuntimeException("available() returns " +
+ is.available() + " but expected " + expected);
+ }
+ return skip;
+ }
+
+ private static File createLargeFile(long filesize) throws Exception {
+ // Create a large file as a sparse file if possible
+ File largefile = File.createTempFile("largefile", null);
+ // re-create as a sparse file
+ largefile.toPath().delete();
+ try (FileChannel fc =
+ FileChannel.open(largefile.toPath(),
+ CREATE_NEW, WRITE, SPARSE)) {
+ ByteBuffer bb = ByteBuffer.allocate(1).put((byte)1);
+ bb.rewind();
+ int rc = fc.write(bb, filesize-1);
+ if (rc != 1) {
+ throw new RuntimeException("Failed to write 1 byte to the large file");
+ }
+ }
+ return largefile;
+ }
+}
diff --git a/test/java/io/Serializable/cloneArray/CloneArray.java b/test/java/io/Serializable/cloneArray/CloneArray.java
new file mode 100644
index 0000000000000000000000000000000000000000..650ac3ccb9f8e7f7e473618fcda6d4e3460df239
--- /dev/null
+++ b/test/java/io/Serializable/cloneArray/CloneArray.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 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.
+ */
+
+
+/* @test
+ * @bug 6990094
+ * @summary Verify ObjectInputStream.cloneArray works on many kinds of arrays
+ * @author Stuart Marks, Joseph D. Darcy
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+
+public class CloneArray {
+ static Object replacement;
+
+ static class Resolver implements Serializable {
+ private Object readResolve() throws ObjectStreamException {
+ return replacement;
+ }
+ }
+
+ private static void test(Object rep)
+ throws IOException, ClassNotFoundException {
+
+ try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ try(ObjectOutputStream oos = new ObjectOutputStream(baos)) {
+ oos.writeObject(new Resolver());
+ oos.writeObject(new Resolver());
+ }
+
+ Object o1;
+ Object o2;
+ try(ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ ObjectInputStream ois = new ObjectInputStream(bais)) {
+ replacement = rep;
+ o1 = ois.readUnshared();
+ o2 = ois.readUnshared();
+ }
+
+ if (o1 == o2)
+ throw new AssertionError("o1 and o2 must not be identical");
+ }
+ }
+
+ public static void main(String[] args)
+ throws IOException, ClassNotFoundException {
+ Object[] replacements = {
+ new byte[] {1},
+ new char[] {'2'},
+ new short[] {3},
+ new int[] {4},
+ new long[] {5},
+ new float[] {6.0f},
+ new double[] {7.0},
+ new boolean[] {true},
+ new Object[] {"A string."}
+ };
+
+ for(Object replacement : replacements) {
+ test(replacement);
+ }
+ }
+}
diff --git a/test/java/nio/channels/AsynchronousSocketChannel/Basic.java b/test/java/nio/channels/AsynchronousSocketChannel/Basic.java
index e8f23f46866a4e333b3c68eb771ec3d3b1682591..b38e34efbc052bc83026e99db983014f608b9048 100644
--- a/test/java/nio/channels/AsynchronousSocketChannel/Basic.java
+++ b/test/java/nio/channels/AsynchronousSocketChannel/Basic.java
@@ -22,7 +22,7 @@
*/
/* @test
- * @bug 4607272 6842687
+ * @bug 4607272 6842687 6878369
* @summary Unit test for AsynchronousSocketChannel
* @run main/timeout=600 Basic
*/
@@ -712,52 +712,57 @@ public class Basic {
}
static void testTimeout() throws Exception {
+ System.out.println("-- timeouts --");
+ testTimeout(Integer.MIN_VALUE, TimeUnit.SECONDS);
+ testTimeout(-1L, TimeUnit.SECONDS);
+ testTimeout(0L, TimeUnit.SECONDS);
+ testTimeout(2L, TimeUnit.SECONDS);
+ }
+
+ static void testTimeout(final long timeout, final TimeUnit unit) throws Exception {
Server server = new Server();
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get();
- System.out.println("-- timeout when reading --");
-
ByteBuffer dst = ByteBuffer.allocate(512);
final AtomicReference readException = new AtomicReference();
- // this read should timeout
- ch.read(dst, 3, TimeUnit.SECONDS, (Void)null,
- new CompletionHandler()
- {
+ // this read should timeout if value is > 0
+ ch.read(dst, timeout, unit, null, new CompletionHandler() {
public void completed(Integer result, Void att) {
- throw new RuntimeException("Should not complete");
+ readException.set(new RuntimeException("Should not complete"));
}
public void failed(Throwable exc, Void att) {
readException.set(exc);
}
});
- // wait for exception
- while (readException.get() == null) {
- Thread.sleep(100);
- }
- if (!(readException.get() instanceof InterruptedByTimeoutException))
- throw new RuntimeException("InterruptedByTimeoutException expected");
+ if (timeout > 0L) {
+ // wait for exception
+ while (readException.get() == null) {
+ Thread.sleep(100);
+ }
+ if (!(readException.get() instanceof InterruptedByTimeoutException))
+ throw new RuntimeException("InterruptedByTimeoutException expected");
- // after a timeout then further reading should throw unspecified runtime exception
- boolean exceptionThrown = false;
- try {
- ch.read(dst);
- } catch (RuntimeException x) {
- exceptionThrown = true;
+ // after a timeout then further reading should throw unspecified runtime exception
+ boolean exceptionThrown = false;
+ try {
+ ch.read(dst);
+ } catch (RuntimeException x) {
+ exceptionThrown = true;
+ }
+ if (!exceptionThrown)
+ throw new RuntimeException("RuntimeException expected after timeout.");
+ } else {
+ Thread.sleep(1000);
+ Throwable exc = readException.get();
+ if (exc != null)
+ throw new RuntimeException(exc);
}
- if (!exceptionThrown)
- throw new RuntimeException("RuntimeException expected after timeout.");
-
-
- System.out.println("-- timeout when writing --");
final AtomicReference writeException = new AtomicReference();
- final long timeout = 5;
- final TimeUnit unit = TimeUnit.SECONDS;
-
// write bytes to fill socket buffer
ch.write(genBuffer(), timeout, unit, ch,
new CompletionHandler()
@@ -769,24 +774,32 @@ public class Basic {
writeException.set(exc);
}
});
+ if (timeout > 0) {
+ // wait for exception
+ while (writeException.get() == null) {
+ Thread.sleep(100);
+ }
+ if (!(writeException.get() instanceof InterruptedByTimeoutException))
+ throw new RuntimeException("InterruptedByTimeoutException expected");
- // wait for exception
- while (writeException.get() == null) {
- Thread.sleep(100);
- }
- if (!(writeException.get() instanceof InterruptedByTimeoutException))
- throw new RuntimeException("InterruptedByTimeoutException expected");
-
- // after a timeout then further writing should throw unspecified runtime exception
- exceptionThrown = false;
- try {
- ch.write(genBuffer());
- } catch (RuntimeException x) {
- exceptionThrown = true;
+ // after a timeout then further writing should throw unspecified runtime exception
+ boolean exceptionThrown = false;
+ try {
+ ch.write(genBuffer());
+ } catch (RuntimeException x) {
+ exceptionThrown = true;
+ }
+ if (!exceptionThrown)
+ throw new RuntimeException("RuntimeException expected after timeout.");
+ } else {
+ Thread.sleep(1000);
+ Throwable exc = writeException.get();
+ if (exc != null)
+ throw new RuntimeException(exc);
}
- if (!exceptionThrown)
- throw new RuntimeException("RuntimeException expected after timeout.");
+ // clean-up
+ server.accept().close();
ch.close();
server.close();
}
diff --git a/test/java/nio/channels/FileChannel/AtomicAppend.java b/test/java/nio/channels/FileChannel/AtomicAppend.java
new file mode 100644
index 0000000000000000000000000000000000000000..1420318d5d7efbf971814ecef816c9f6b5748e85
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/AtomicAppend.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 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.
+ */
+
+/*
+ * @test
+ * @summary Check that appends are atomic
+ */
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.util.Random;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import static java.nio.file.StandardOpenOption.*;
+
+public class AtomicAppend {
+ static final Random rand = new Random();
+
+ // Open file for appending, returning FileChannel
+ static FileChannel newFileChannel(File file) throws IOException {
+ if (rand.nextBoolean()) {
+ return new FileOutputStream(file, true).getChannel();
+ } else {
+ return FileChannel.open(file.toPath(), APPEND);
+ }
+ }
+
+ // Open file for append, returning OutputStream
+ static OutputStream newOutputStream(File file) throws IOException {
+ if (rand.nextBoolean()) {
+ return new FileOutputStream(file, true);
+ } else {
+ return file.toPath().newOutputStream(APPEND);
+ }
+ }
+
+ // write a byte to the given channel
+ static void write(FileChannel fc, int b) throws IOException {
+ ByteBuffer buf = ByteBuffer.allocate(1);
+ buf.put((byte)b);
+ buf.flip();
+ if (rand.nextBoolean()) {
+ ByteBuffer[] bufs = new ByteBuffer[1];
+ bufs[0] = buf;
+ fc.write(bufs);
+ } else {
+ fc.write(buf);
+ }
+ }
+
+ public static void main(String[] args) throws Throwable {
+ final int nThreads = 16;
+ final int writes = 1000;
+ final File file = File.createTempFile("foo", null);
+ try {
+ ExecutorService pool = Executors.newFixedThreadPool(nThreads);
+ for (int i = 0; i < nThreads; i++)
+ pool.execute(new Runnable() { public void run() {
+ try {
+ // randomly choose FileChannel or OutputStream
+ if (rand.nextBoolean()) {
+ try (FileChannel fc = newFileChannel(file)) {
+ for (int j=0; j newSize) {
- if (c.position() != newSize)
- throw new RuntimeException("Position greater than size");
- } else {
- if (c.position() != position)
- throw new RuntimeException("Truncate changed position");
+ if (position > newSize) {
+ if (fc.position() != newSize)
+ throw new RuntimeException("Position greater than size");
+ } else {
+ if (fc.position() != position)
+ throw new RuntimeException("Truncate changed position");
+ };
}
+ }
+ }
+
+ /**
+ * Test behavior of truncate method when file is opened for append
+ */
+ static void appendTest(File blah) throws Exception {
+ for (int i=0; i<10; i++) {
+ long testSize = generator.nextInt(1000) + 10;
+ initTestFile(blah, testSize);
+ FileChannel fc = (i < 5) ?
+ new FileOutputStream(blah, true).getChannel() :
+ FileChannel.open(blah.toPath(), APPEND);
+ try (fc) {
+ // truncate file
+ long newSize = generator.nextInt((int)testSize);
+ fc.truncate(newSize);
+ if (fc.size() != newSize)
+ throw new RuntimeException("Truncate failed");
- c.close();
- fis.close();
+ // write one byte
+ ByteBuffer buf = ByteBuffer.allocate(1);
+ buf.put((byte)'x');
+ buf.flip();
+ fc.write(buf);
+ if (fc.size() != (newSize+1))
+ throw new RuntimeException("Unexpected size");
+ }
}
- blah.delete();
}
/**
diff --git a/test/java/util/concurrent/BlockingQueue/Interrupt.java b/test/java/util/concurrent/BlockingQueue/Interrupt.java
index 418515ded51fa1479fb893bf00f6564fe04ec90f..aafa92c42ed6c1df1b871717a31456feb256cf60 100644
--- a/test/java/util/concurrent/BlockingQueue/Interrupt.java
+++ b/test/java/util/concurrent/BlockingQueue/Interrupt.java
@@ -136,5 +136,5 @@ public class Interrupt {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class Fun {abstract void f() throws Throwable;}
+ private abstract static class Fun {abstract void f() throws Throwable;}
}
diff --git a/test/java/util/concurrent/BlockingQueue/LoopHelpers.java b/test/java/util/concurrent/BlockingQueue/LoopHelpers.java
index f6bac816a7babe3f6b058ac3aa74ce76bb1979e2..5bf6d0dbbee5900c0abe3cfa9a55aa6d8313e645 100644
--- a/test/java/util/concurrent/BlockingQueue/LoopHelpers.java
+++ b/test/java/util/concurrent/BlockingQueue/LoopHelpers.java
@@ -79,9 +79,9 @@ class LoopHelpers {
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
diff --git a/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java b/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java
index f6bac816a7babe3f6b058ac3aa74ce76bb1979e2..5bf6d0dbbee5900c0abe3cfa9a55aa6d8313e645 100644
--- a/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java
+++ b/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java
@@ -79,9 +79,9 @@ class LoopHelpers {
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
diff --git a/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java b/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java
index e9ca263c91088e424d95d4ef06ae0ba246103c82..c6075c131b94a45119d763def02734e235fa6ad2 100644
--- a/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java
+++ b/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java
@@ -34,7 +34,7 @@
/*
* @test
* @bug 4486658
- * @compile MapCheck.java
+ * @compile -source 1.5 MapCheck.java
* @run main/timeout=240 MapCheck
* @summary Times and checks basic map operations
*/
@@ -64,7 +64,7 @@ public class MapCheck {
if (args.length > 0) {
try {
mapClass = Class.forName(args[0]);
- } catch(ClassNotFoundException e) {
+ } catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + args[0] + " not found.");
}
}
@@ -102,7 +102,7 @@ public class MapCheck {
try {
Map m = (Map)cl.newInstance();
return m;
- } catch(Exception e) {
+ } catch (Exception e) {
throw new RuntimeException("Can't instantiate " + cl + ": " + e);
}
}
@@ -139,7 +139,7 @@ public class MapCheck {
}
}
timer.finish();
- reallyAssert (sum == expect * iters);
+ reallyAssert(sum == expect * iters);
}
static void t2(String nm, int n, Map s, Object[] key, int expect) {
@@ -149,7 +149,7 @@ public class MapCheck {
if (s.remove(key[i]) != null) ++sum;
}
timer.finish();
- reallyAssert (sum == expect);
+ reallyAssert(sum == expect);
}
static void t3(String nm, int n, Map s, Object[] key, int expect) {
@@ -159,7 +159,7 @@ public class MapCheck {
if (s.put(key[i], absent[i & absentMask]) == null) ++sum;
}
timer.finish();
- reallyAssert (sum == expect);
+ reallyAssert(sum == expect);
}
static void t4(String nm, int n, Map s, Object[] key, int expect) {
@@ -169,7 +169,7 @@ public class MapCheck {
if (s.containsKey(key[i])) ++sum;
}
timer.finish();
- reallyAssert (sum == expect);
+ reallyAssert(sum == expect);
}
static void t5(String nm, int n, Map s, Object[] key, int expect) {
@@ -179,7 +179,7 @@ public class MapCheck {
if (s.remove(key[i]) != null) ++sum;
}
timer.finish();
- reallyAssert (sum == expect);
+ reallyAssert(sum == expect);
}
static void t6(String nm, int n, Map s, Object[] k1, Object[] k2) {
@@ -190,7 +190,7 @@ public class MapCheck {
if (s.get(k2[i & absentMask]) != null) ++sum;
}
timer.finish();
- reallyAssert (sum == n);
+ reallyAssert(sum == n);
}
static void t7(String nm, int n, Map s, Object[] k1, Object[] k2) {
@@ -201,7 +201,7 @@ public class MapCheck {
if (s.containsKey(k2[i & absentMask])) ++sum;
}
timer.finish();
- reallyAssert (sum == n);
+ reallyAssert(sum == n);
}
static void t8(String nm, int n, Map s, Object[] key, int expect) {
@@ -211,7 +211,7 @@ public class MapCheck {
if (s.get(key[i]) != null) ++sum;
}
timer.finish();
- reallyAssert (sum == expect);
+ reallyAssert(sum == expect);
}
@@ -223,7 +223,7 @@ public class MapCheck {
for (int i = 0; i < absentSize; i += step)
if (s.containsValue(absent[i])) ++sum;
timer.finish();
- reallyAssert (sum != 0);
+ reallyAssert(sum != 0);
}
@@ -235,7 +235,7 @@ public class MapCheck {
if (ks.contains(key[i])) ++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
@@ -243,37 +243,37 @@ public class MapCheck {
int sum = 0;
timer.start("Iter Key ", size);
for (Iterator it = s.keySet().iterator(); it.hasNext(); ) {
- if(it.next() != MISSING)
+ if (it.next() != MISSING)
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
static void ittest2(Map s, int size) {
int sum = 0;
timer.start("Iter Value ", size);
for (Iterator it = s.values().iterator(); it.hasNext(); ) {
- if(it.next() != MISSING)
+ if (it.next() != MISSING)
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
static void ittest3(Map s, int size) {
int sum = 0;
timer.start("Iter Entry ", size);
for (Iterator it = s.entrySet().iterator(); it.hasNext(); ) {
- if(it.next() != MISSING)
+ if (it.next() != MISSING)
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
static void ittest4(Map s, int size, int pos) {
IdentityHashMap seen = new IdentityHashMap(size);
- reallyAssert (s.size() == size);
+ reallyAssert(s.size() == size);
int sum = 0;
timer.start("Iter XEntry ", size);
Iterator it = s.entrySet().iterator();
@@ -287,9 +287,9 @@ public class MapCheck {
if (x != MISSING)
++sum;
}
- reallyAssert (s.containsKey(k));
+ reallyAssert(s.containsKey(k));
it.remove();
- reallyAssert (!s.containsKey(k));
+ reallyAssert(!s.containsKey(k));
while (it.hasNext()) {
Map.Entry x = (Map.Entry)(it.next());
Object k2 = x.getKey();
@@ -298,12 +298,12 @@ public class MapCheck {
++sum;
}
- reallyAssert (s.size() == size-1);
+ reallyAssert(s.size() == size-1);
s.put(k, v);
- reallyAssert (seen.size() == size);
+ reallyAssert(seen.size() == size);
timer.finish();
- reallyAssert (sum == size);
- reallyAssert (s.size() == size);
+ reallyAssert(sum == size);
+ reallyAssert(s.size() == size);
}
@@ -324,7 +324,7 @@ public class MapCheck {
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
static void entest2(Hashtable ht, int size) {
@@ -335,7 +335,7 @@ public class MapCheck {
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
@@ -349,7 +349,7 @@ public class MapCheck {
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
static void entest4(Hashtable ht, int size) {
@@ -361,7 +361,7 @@ public class MapCheck {
++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
}
static void entest(Map s, int size) {
@@ -409,13 +409,13 @@ public class MapCheck {
timer.start("Iter Equals ", size * 2);
boolean eqt = s2.equals(s) && s.equals(s2);
- reallyAssert (eqt);
+ reallyAssert(eqt);
timer.finish();
timer.start("Iter HashCode ", size * 2);
int shc = s.hashCode();
int s2hc = s2.hashCode();
- reallyAssert (shc == s2hc);
+ reallyAssert(shc == s2hc);
timer.finish();
timer.start("Put (present) ", size);
@@ -430,7 +430,7 @@ public class MapCheck {
if (es2.contains(entry)) ++sum;
}
timer.finish();
- reallyAssert (sum == size);
+ reallyAssert(sum == size);
t6("Get ", size, s2, key, absent);
@@ -438,13 +438,13 @@ public class MapCheck {
s2.put(key[size-1], absent[0]);
timer.start("Iter Equals ", size * 2);
eqt = s2.equals(s) && s.equals(s2);
- reallyAssert (!eqt);
+ reallyAssert(!eqt);
timer.finish();
timer.start("Iter HashCode ", size * 2);
int s1h = s.hashCode();
int s2h = s2.hashCode();
- reallyAssert (s1h != s2h);
+ reallyAssert(s1h != s2h);
timer.finish();
s2.put(key[size-1], hold);
@@ -455,12 +455,12 @@ public class MapCheck {
es.remove(s2i.next());
timer.finish();
- reallyAssert (s.isEmpty());
+ reallyAssert(s.isEmpty());
timer.start("Clear ", size);
s2.clear();
timer.finish();
- reallyAssert (s2.isEmpty() && s.isEmpty());
+ reallyAssert(s2.isEmpty() && s.isEmpty());
}
static void stest(Map s, int size) throws Exception {
@@ -489,7 +489,7 @@ public class MapCheck {
System.out.print(time + "ms");
if (s instanceof IdentityHashMap) return;
- reallyAssert (s.equals(m));
+ reallyAssert(s.equals(m));
}
diff --git a/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java b/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java
index 5f3d375515e7ecf2321fc1809d7f88f51f0fd8e9..53ed2919a9d82b1ef0580b8730b7cf5565bf10cb 100644
--- a/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java
+++ b/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java
@@ -34,7 +34,7 @@
/*
* @test
* @bug 4486658
- * @compile MapLoops.java
+ * @compile -source 1.5 MapLoops.java
* @run main/timeout=1600 MapLoops
* @summary Exercise multithreaded maps, by default ConcurrentHashMap.
* Multithreaded hash table test. Each thread does a random walk
@@ -225,7 +225,7 @@ public class MapLoops {
barrier.await();
}
catch (Throwable throwable) {
- synchronized(System.err) {
+ synchronized (System.err) {
System.err.println("--------------------------------");
throwable.printStackTrace();
}
diff --git a/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java b/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java
index f6bac816a7babe3f6b058ac3aa74ce76bb1979e2..5bf6d0dbbee5900c0abe3cfa9a55aa6d8313e645 100644
--- a/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java
+++ b/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java
@@ -79,9 +79,9 @@ class LoopHelpers {
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
diff --git a/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java b/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java
index ad063ea237aab85723e093d0fc53955ef1dae4a8..7bc8fab638b6995943ff4390928f82a455706dec 100644
--- a/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java
+++ b/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java
@@ -66,7 +66,7 @@ public class EqualsRace {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class CheckedThread extends Thread {
+ private abstract static class CheckedThread extends Thread {
public abstract void realRun() throws Throwable;
public void run() {
try { realRun(); } catch (Throwable t) { unexpected(t); }}}
diff --git a/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java b/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java
index afde87549ed374e79abdae14621349b9760152a1..6d13dac3cca70e94efe46ae0912cdab9cceb0668 100644
--- a/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java
+++ b/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java
@@ -125,7 +125,7 @@ public class RacingCows {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class CheckedThread extends Thread {
+ private abstract static class CheckedThread extends Thread {
public abstract void realRun() throws Throwable;
public void run() {
try { realRun(); } catch (Throwable t) { unexpected(t); }}}
diff --git a/test/java/util/concurrent/CyclicBarrier/Basic.java b/test/java/util/concurrent/CyclicBarrier/Basic.java
index b20a81ea2ffe314defba39e8b0ed7234bb8df86b..f0459d613d531c32bb1853f5779dbe36598efbbd 100644
--- a/test/java/util/concurrent/CyclicBarrier/Basic.java
+++ b/test/java/util/concurrent/CyclicBarrier/Basic.java
@@ -83,7 +83,7 @@ public class Basic {
//----------------------------------------------------------------
// Convenience methods for creating threads that call CyclicBarrier.await
//----------------------------------------------------------------
- private static abstract class Awaiter extends Thread {
+ private abstract static class Awaiter extends Thread {
static AtomicInteger count = new AtomicInteger(1);
{
@@ -417,14 +417,14 @@ public class Basic {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- static abstract class Fun { abstract void f() throws Throwable; }
+ abstract static class Fun { abstract void f() throws Throwable; }
private static void THROWS(Class extends Throwable> k, Fun... fs) {
for (Fun f : fs)
try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
- private static abstract class CheckedThread extends Thread {
+ private abstract static class CheckedThread extends Thread {
abstract void realRun() throws Throwable;
public void run() {
try {realRun();} catch (Throwable t) {unexpected(t);}}}
diff --git a/test/java/util/concurrent/Exchanger/ExchangeLoops.java b/test/java/util/concurrent/Exchanger/ExchangeLoops.java
index b207b8c2d92f494c15ce51fd0c24a21ae3d08707..2055c056ca33215aae45ea7648b7372107484f46 100644
--- a/test/java/util/concurrent/Exchanger/ExchangeLoops.java
+++ b/test/java/util/concurrent/Exchanger/ExchangeLoops.java
@@ -34,7 +34,7 @@
/*
* @test
* @bug 4486658
- * @compile ExchangeLoops.java
+ * @compile -source 1.5 ExchangeLoops.java
* @run main/timeout=720 ExchangeLoops
* @summary checks to make sure a pipeline of exchangers passes data.
*/
@@ -78,9 +78,9 @@ public class ExchangeLoops {
final Exchanger right;
final CyclicBarrier barrier;
volatile int result;
- Stage (Exchanger left,
- Exchanger right,
- CyclicBarrier b, int iters) {
+ Stage(Exchanger left,
+ Exchanger right,
+ CyclicBarrier b, int iters) {
this.left = left;
this.right = right;
barrier = b;
diff --git a/test/java/util/concurrent/Exchanger/LoopHelpers.java b/test/java/util/concurrent/Exchanger/LoopHelpers.java
index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644
--- a/test/java/util/concurrent/Exchanger/LoopHelpers.java
+++ b/test/java/util/concurrent/Exchanger/LoopHelpers.java
@@ -78,9 +78,9 @@ class LoopHelpers {
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
diff --git a/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java b/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java
index 2c67ba5697d34270eadb9345d5587b005331f098..71c45e75f7fa3e7a28d804dc5ec8543587e50e4e 100644
--- a/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java
+++ b/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java
@@ -34,7 +34,7 @@
/*
* @test
* @bug 4965960
- * @compile ExecutorCompletionServiceLoops.java
+ * @compile -source 1.5 ExecutorCompletionServiceLoops.java
* @run main/timeout=3600 ExecutorCompletionServiceLoops
* @summary Exercise ExecutorCompletionServiceLoops
*/
diff --git a/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java b/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java
index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644
--- a/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java
+++ b/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java
@@ -78,9 +78,9 @@ class LoopHelpers {
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
diff --git a/test/java/util/concurrent/Executors/Throws.java b/test/java/util/concurrent/Executors/Throws.java
index c310ad5c9ec801884e592d54c39b2b23bc66bc72..d98537931ee39f2139deb39cd2ea91681d29df08 100644
--- a/test/java/util/concurrent/Executors/Throws.java
+++ b/test/java/util/concurrent/Executors/Throws.java
@@ -122,7 +122,7 @@ public class Throws {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class Fun {abstract void f() throws Throwable;}
+ private abstract static class Fun {abstract void f() throws Throwable;}
static void THROWS(Class extends Throwable> k, Fun... fs) {
for (Fun f : fs)
try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
diff --git a/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java b/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java
index bd6c2e839da52eac2987c2d9d85d2f0c1e6042c8..4c6f12ba29d44486b50791b5fcb0b4a71ff79d76 100644
--- a/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java
+++ b/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java
@@ -87,7 +87,7 @@ public class BlockingTaskExecutor {
* A helper class with a method to wait for a notification.
*
* The notification is received via the
- * sendNotification method.
+ * {@code sendNotification} method.
*/
static class NotificationReceiver {
/** Has the notifiee been notified? */
diff --git a/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java b/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java
index c12f5cde94463d5ffc6e097b7c318e4658a6a3d1..6a0ca8c93df8c466dd66cce3fd4255ffa43e46fe 100644
--- a/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java
+++ b/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java
@@ -34,7 +34,7 @@
/*
* @test
* @bug 4486658
- * @compile CancelledFutureLoops.java
+ * @compile -source 1.5 CancelledFutureLoops.java
* @run main/timeout=2000 CancelledFutureLoops
* @summary Checks for responsiveness of futures to cancellation.
* Runs under the assumption that ITERS computations require more than
@@ -64,10 +64,10 @@ public final class CancelledFutureLoops {
try {
new FutureLoop(i).test();
}
- catch(BrokenBarrierException bb) {
+ catch (BrokenBarrierException bb) {
// OK; ignore
}
- catch(ExecutionException ee) {
+ catch (ExecutionException ee) {
// OK; ignore
}
Thread.sleep(TIMEOUT);
diff --git a/test/java/util/concurrent/FutureTask/Customized.java b/test/java/util/concurrent/FutureTask/Customized.java
index 1f1f8fb49391aa81922d203a7379c17ddc753951..5d107c58ad1ec473c83cb6b2b790b289c650ab2e 100644
--- a/test/java/util/concurrent/FutureTask/Customized.java
+++ b/test/java/util/concurrent/FutureTask/Customized.java
@@ -203,7 +203,7 @@ public class Customized {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class Fun {abstract void f() throws Throwable;}
+ private abstract static class Fun {abstract void f() throws Throwable;}
static void THROWS(Class extends Throwable> k, Fun... fs) {
for (Fun f : fs)
try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
diff --git a/test/java/util/concurrent/FutureTask/LoopHelpers.java b/test/java/util/concurrent/FutureTask/LoopHelpers.java
index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644
--- a/test/java/util/concurrent/FutureTask/LoopHelpers.java
+++ b/test/java/util/concurrent/FutureTask/LoopHelpers.java
@@ -78,9 +78,9 @@ class LoopHelpers {
* Basically same as java.util.Random.
*/
public static class SimpleRandom {
- private final static long multiplier = 0x5DEECE66DL;
- private final static long addend = 0xBL;
- private final static long mask = (1L << 48) - 1;
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
static final AtomicLong seq = new AtomicLong(1);
private long seed = System.nanoTime() + seq.getAndIncrement();
diff --git a/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java b/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java
index 2e0854b0fc7c21618fc87b8e1a115c71ae05abfc..bc34d00965fc0a7a5bd89b4add0617f15c60be35 100644
--- a/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java
+++ b/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java
@@ -161,11 +161,8 @@ public class DelayOverflow {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
- Class> k = new Object(){}.getClass().getEnclosingClass();
- try {k.getMethod("instanceMain",String[].class)
- .invoke( k.newInstance(), (Object) args);}
- catch (Throwable e) {throw e.getCause();}}
- public void instanceMain(String[] args) throws Throwable {
+ new DelayOverflow().instanceMain(args);}
+ void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java b/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java
index 40d11e04b311b42619226b3f1157be6839b59540..4c69a594bcbad6670146287bc62a125ff41324b2 100644
--- a/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java
+++ b/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java
@@ -36,9 +36,9 @@ import java.util.concurrent.atomic.*;
import static java.util.concurrent.TimeUnit.*;
public class ConfigChanges {
- final static ThreadGroup tg = new ThreadGroup("pool");
+ static final ThreadGroup tg = new ThreadGroup("pool");
- final static Random rnd = new Random();
+ static final Random rnd = new Random();
static void report(ThreadPoolExecutor tpe) {
try {
@@ -241,7 +241,7 @@ public class ConfigChanges {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class Fun {abstract void f() throws Throwable;}
+ private abstract static class Fun {abstract void f() throws Throwable;}
static void THROWS(Class extends Throwable> k, Fun... fs) {
for (Fun f : fs)
try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
diff --git a/test/java/util/concurrent/ThreadPoolExecutor/Custom.java b/test/java/util/concurrent/ThreadPoolExecutor/Custom.java
index 108ca7bd4fc6ce100bf4e712dddf267e86e514c7..d60bdcefdea872d9c4e829464c54e4f29a72f25a 100644
--- a/test/java/util/concurrent/ThreadPoolExecutor/Custom.java
+++ b/test/java/util/concurrent/ThreadPoolExecutor/Custom.java
@@ -43,7 +43,7 @@ public class Custom {
private static class CustomTask extends FutureTask {
- public final static AtomicInteger births = new AtomicInteger(0);
+ public static final AtomicInteger births = new AtomicInteger(0);
CustomTask(Callable c) { super(c); births.getAndIncrement(); }
CustomTask(Runnable r, V v) { super(r, v); births.getAndIncrement(); }
}
@@ -63,7 +63,7 @@ public class Custom {
}
private static class CustomSTPE extends ScheduledThreadPoolExecutor {
- public final static AtomicInteger decorations = new AtomicInteger(0);
+ public static final AtomicInteger decorations = new AtomicInteger(0);
CustomSTPE() {
super(threadCount);
}
@@ -89,7 +89,7 @@ public class Custom {
return count;
}
- private final static int threadCount = 10;
+ private static final int threadCount = 10;
public static void main(String[] args) throws Throwable {
CustomTPE tpe = new CustomTPE();
diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java b/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java
index 94c71e72605af2a110f4f7423d470d56a98e4cfd..a0c3b53d5e14fcb0f88cecf4b85e08d9b691fa4c 100644
--- a/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java
+++ b/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java
@@ -37,10 +37,10 @@ public class ScheduledTickleService {
// We get intermittent ClassCastException if greater than 1
// because of calls to compareTo
- private final static int concurrency = 2;
+ private static final int concurrency = 2;
// Record when tasks are done
- public final static CountDownLatch done = new CountDownLatch(concurrency);
+ public static final CountDownLatch done = new CountDownLatch(concurrency);
public static void realMain(String... args) throws InterruptedException {
// our tickle service
diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java b/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java
index b2a8313893cf8ec08ee9e4ef1b332369f25814f7..04b08ef6f379749774cede4c88164a4811d7039c 100644
--- a/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java
+++ b/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java
@@ -40,7 +40,7 @@ public class ShutdownNowExecuteRace {
static volatile boolean quit = false;
static volatile ThreadPoolExecutor pool = null;
- final static Runnable sleeper = new Runnable() { public void run() {
+ static final Runnable sleeper = new Runnable() { public void run() {
final long ONE_HOUR = 1000L * 60L * 60L;
try { Thread.sleep(ONE_HOUR); }
catch (InterruptedException ie) {}
@@ -81,14 +81,14 @@ public class ShutdownNowExecuteRace {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
- private static abstract class Fun {abstract void f() throws Throwable;}
+ private abstract static class Fun {abstract void f() throws Throwable;}
static void THROWS(Class extends Throwable> k, Fun... fs) {
for (Fun f : fs)
try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
- private static abstract class CheckedThread extends Thread {
+ private abstract static class CheckedThread extends Thread {
abstract void realRun() throws Throwable;
public void run() {
try {realRun();} catch (Throwable t) {unexpected(t);}}}
diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java b/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java
index 6ff46c95c6bf0f3bf9c0248bb405e82bc160f033..534bf59f52ef9613584f4070a4c42d76bdc3d065 100644
--- a/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java
+++ b/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java
@@ -35,7 +35,7 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class ThrowingTasks {
- final static Random rnd = new Random();
+ static final Random rnd = new Random();
@SuppressWarnings("serial")
static class UncaughtExceptions
@@ -65,16 +65,16 @@ public class ThrowingTasks {
}
}
- final static UncaughtExceptions uncaughtExceptions
+ static final UncaughtExceptions uncaughtExceptions
= new UncaughtExceptions();
- final static UncaughtExceptionsTable uncaughtExceptionsTable
+ static final UncaughtExceptionsTable uncaughtExceptionsTable
= new UncaughtExceptionsTable();
- final static AtomicLong totalUncaughtExceptions
+ static final AtomicLong totalUncaughtExceptions
= new AtomicLong(0);
- final static CountDownLatch uncaughtExceptionsLatch
+ static final CountDownLatch uncaughtExceptionsLatch
= new CountDownLatch(24);
- final static Thread.UncaughtExceptionHandler handler
+ static final Thread.UncaughtExceptionHandler handler
= new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
check(! Thread.currentThread().isInterrupted());
@@ -84,19 +84,19 @@ public class ThrowingTasks {
uncaughtExceptionsLatch.countDown();
}};
- final static ThreadGroup tg = new ThreadGroup("Flaky");
+ static final ThreadGroup tg = new ThreadGroup("Flaky");
- final static ThreadFactory tf = new ThreadFactory() {
+ static final ThreadFactory tf = new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(tg, r);
t.setUncaughtExceptionHandler(handler);
return t;
}};
- final static RuntimeException rte = new RuntimeException();
- final static Error error = new Error();
- final static Throwable weird = new Throwable();
- final static Exception checkedException = new Exception();
+ static final RuntimeException rte = new RuntimeException();
+ static final Error error = new Error();
+ static final Throwable weird = new Throwable();
+ static final Exception checkedException = new Exception();
static class Thrower implements Runnable {
Throwable t;
@@ -105,13 +105,13 @@ public class ThrowingTasks {
public void run() { if (t != null) Thread.currentThread().stop(t); }
}
- final static Thrower noThrower = new Thrower(null);
- final static Thrower rteThrower = new Thrower(rte);
- final static Thrower errorThrower = new Thrower(error);
- final static Thrower weirdThrower = new Thrower(weird);
- final static Thrower checkedThrower = new Thrower(checkedException);
+ static final Thrower noThrower = new Thrower(null);
+ static final Thrower rteThrower = new Thrower(rte);
+ static final Thrower errorThrower = new Thrower(error);
+ static final Thrower weirdThrower = new Thrower(weird);
+ static final Thrower checkedThrower = new Thrower(checkedException);
- final static List throwers = Arrays.asList(
+ static final List