diff options
author | Miguel de Icaza <miguel@gnome.org> | 2016-02-27 23:38:24 +0300 |
---|---|---|
committer | Miguel de Icaza <miguel@gnome.org> | 2016-02-27 23:38:24 +0300 |
commit | 94d4a298ad560f8674d746dea2d51e26e0a97f2a (patch) | |
tree | ae303637d83843abf98938b07eb9808880cea9fa /openjdk/sun | |
parent | c9edfe788667d5777e97e3f2fd195080d06dd32c (diff) |
Remove unused filesmaster-signed
Diffstat (limited to 'openjdk/sun')
102 files changed, 0 insertions, 35210 deletions
diff --git a/openjdk/sun/awt/AppContext.java b/openjdk/sun/awt/AppContext.java deleted file mode 100644 index 23c86c90..00000000 --- a/openjdk/sun/awt/AppContext.java +++ /dev/null @@ -1,868 +0,0 @@ -/* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt; - -import java.awt.EventQueue; -import java.awt.Window; -import java.awt.SystemTray; -import java.awt.TrayIcon; -import java.awt.Toolkit; -import java.awt.GraphicsEnvironment; -import java.awt.event.InvocationEvent; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Collections; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Map; -import java.util.Set; -import java.util.HashSet; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyChangeListener; -import sun.util.logging.PlatformLogger; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * The AppContext is a table referenced by ThreadGroup which stores - * application service instances. (If you are not writing an application - * service, or don't know what one is, please do not use this class.) - * The AppContext allows applet access to what would otherwise be - * potentially dangerous services, such as the ability to peek at - * EventQueues or change the look-and-feel of a Swing application.<p> - * - * Most application services use a singleton object to provide their - * services, either as a default (such as getSystemEventQueue or - * getDefaultToolkit) or as static methods with class data (System). - * The AppContext works with the former method by extending the concept - * of "default" to be ThreadGroup-specific. Application services - * lookup their singleton in the AppContext.<p> - * - * For example, here we have a Foo service, with its pre-AppContext - * code:<p> - * <code><pre> - * public class Foo { - * private static Foo defaultFoo = new Foo(); - * - * public static Foo getDefaultFoo() { - * return defaultFoo; - * } - * - * ... Foo service methods - * }</pre></code><p> - * - * The problem with the above is that the Foo service is global in scope, - * so that applets and other untrusted code can execute methods on the - * single, shared Foo instance. The Foo service therefore either needs - * to block its use by untrusted code using a SecurityManager test, or - * restrict its capabilities so that it doesn't matter if untrusted code - * executes it.<p> - * - * Here's the Foo class written to use the AppContext:<p> - * <code><pre> - * public class Foo { - * public static Foo getDefaultFoo() { - * Foo foo = (Foo)AppContext.getAppContext().get(Foo.class); - * if (foo == null) { - * foo = new Foo(); - * getAppContext().put(Foo.class, foo); - * } - * return foo; - * } - * - * ... Foo service methods - * }</pre></code><p> - * - * Since a separate AppContext can exist for each ThreadGroup, trusted - * and untrusted code have access to different Foo instances. This allows - * untrusted code access to "system-wide" services -- the service remains - * within the AppContext "sandbox". For example, say a malicious applet - * wants to peek all of the key events on the EventQueue to listen for - * passwords; if separate EventQueues are used for each ThreadGroup - * using AppContexts, the only key events that applet will be able to - * listen to are its own. A more reasonable applet request would be to - * change the Swing default look-and-feel; with that default stored in - * an AppContext, the applet's look-and-feel will change without - * disrupting other applets or potentially the browser itself.<p> - * - * Because the AppContext is a facility for safely extending application - * service support to applets, none of its methods may be blocked by a - * a SecurityManager check in a valid Java implementation. Applets may - * therefore safely invoke any of its methods without worry of being - * blocked. - * - * Note: If a SecurityManager is installed which derives from - * sun.awt.AWTSecurityManager, it may override the - * AWTSecurityManager.getAppContext() method to return the proper - * AppContext based on the execution context, in the case where - * the default ThreadGroup-based AppContext indexing would return - * the main "system" AppContext. For example, in an applet situation, - * if a system thread calls into an applet, rather than returning the - * main "system" AppContext (the one corresponding to the system thread), - * an installed AWTSecurityManager may return the applet's AppContext - * based on the execution context. - * - * @author Thomas Ball - * @author Fred Ecks - */ -public final class AppContext { - private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.AppContext"); - - /* Since the contents of an AppContext are unique to each Java - * session, this class should never be serialized. */ - - /* - * The key to put()/get() the Java EventQueue into/from the AppContext. - */ - public static final Object EVENT_QUEUE_KEY = new StringBuffer("EventQueue"); - - /* - * The keys to store EventQueue push/pop lock and condition. - */ - public final static Object EVENT_QUEUE_LOCK_KEY = new StringBuilder("EventQueue.Lock"); - public final static Object EVENT_QUEUE_COND_KEY = new StringBuilder("EventQueue.Condition"); - - /* A map of AppContexts, referenced by ThreadGroup. - */ - private static final Map<ThreadGroup, AppContext> threadGroup2appContext = - Collections.synchronizedMap(new IdentityHashMap<ThreadGroup, AppContext>()); - - /** - * Returns a set containing all <code>AppContext</code>s. - */ - public static Set<AppContext> getAppContexts() { - synchronized (threadGroup2appContext) { - return new HashSet<AppContext>(threadGroup2appContext.values()); - } - } - - /* The main "system" AppContext, used by everything not otherwise - contained in another AppContext. It is implicitly created for - standalone apps only (i.e. not applets) - */ - private static volatile AppContext mainAppContext = null; - - /* - * The hash map associated with this AppContext. A private delegate - * is used instead of subclassing HashMap so as to avoid all of - * HashMap's potentially risky methods, such as clear(), elements(), - * putAll(), etc. - */ - private final HashMap table = new HashMap(); - - private final ThreadGroup threadGroup; - - /** - * If any <code>PropertyChangeListeners</code> have been registered, - * the <code>changeSupport</code> field describes them. - * - * @see #addPropertyChangeListener - * @see #removePropertyChangeListener - * @see #firePropertyChange - */ - private PropertyChangeSupport changeSupport = null; - - public static final String DISPOSED_PROPERTY_NAME = "disposed"; - public static final String GUI_DISPOSED = "guidisposed"; - - private enum State { - VALID, - BEING_DISPOSED, - DISPOSED - }; - - private volatile State state = State.VALID; - - public boolean isDisposed() { - return state == State.DISPOSED; - } - - /* - * The total number of AppContexts, system-wide. This number is - * incremented at the beginning of the constructor, and decremented - * at the end of dispose(). getAppContext() checks to see if this - * number is 1. If so, it returns the sole AppContext without - * checking Thread.currentThread(). - */ - private static final AtomicInteger numAppContexts = new AtomicInteger(0); - - /* - * The context ClassLoader that was used to create this AppContext. - */ - private final ClassLoader contextClassLoader; - - /** - * Constructor for AppContext. This method is <i>not</i> public, - * nor should it ever be used as such. The proper way to construct - * an AppContext is through the use of SunToolkit.createNewAppContext. - * A ThreadGroup is created for the new AppContext, a Thread is - * created within that ThreadGroup, and that Thread calls - * SunToolkit.createNewAppContext before calling anything else. - * That creates both the new AppContext and its EventQueue. - * - * @param threadGroup The ThreadGroup for the new AppContext - * @see sun.awt.SunToolkit - * @since 1.2 - */ - AppContext(ThreadGroup threadGroup) { - numAppContexts.incrementAndGet(); - - this.threadGroup = threadGroup; - threadGroup2appContext.put(threadGroup, this); - - this.contextClassLoader = - AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - - // Initialize push/pop lock and its condition to be used by all the - // EventQueues within this AppContext - Lock eventQueuePushPopLock = new ReentrantLock(); - put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock); - Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition(); - put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond); - } - - private static final ThreadLocal<AppContext> threadAppContext = - new ThreadLocal<AppContext>(); - - private final static void initMainAppContext() { - // On the main Thread, we get the ThreadGroup, make a corresponding - // AppContext, and instantiate the Java EventQueue. This way, legacy - // code is unaffected by the move to multiple AppContext ability. - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - ThreadGroup currentThreadGroup = - Thread.currentThread().getThreadGroup(); - ThreadGroup parentThreadGroup = currentThreadGroup.getParent(); - while (parentThreadGroup != null) { - // Find the root ThreadGroup to construct our main AppContext - currentThreadGroup = parentThreadGroup; - parentThreadGroup = currentThreadGroup.getParent(); - } - - mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup); - return null; - } - }); - } - - /** - * Returns the appropriate AppContext for the caller, - * as determined by its ThreadGroup. If the main "system" AppContext - * would be returned and there's an AWTSecurityManager installed, it - * is called to get the proper AppContext based on the execution - * context. - * - * @return the AppContext for the caller. - * @see java.lang.ThreadGroup - * @since 1.2 - */ - public final static AppContext getAppContext() { - // we are standalone app, return the main app context - if (numAppContexts.get() == 1 && mainAppContext != null) { - return mainAppContext; - } - - AppContext appContext = threadAppContext.get(); - - if (null == appContext) { - appContext = AccessController.doPrivileged(new PrivilegedAction<AppContext>() - { - public AppContext run() { - // Get the current ThreadGroup, and look for it and its - // parents in the hash from ThreadGroup to AppContext -- - // it should be found, because we use createNewContext() - // when new AppContext objects are created. - ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); - ThreadGroup threadGroup = currentThreadGroup; - - // Special case: we implicitly create the main app context - // if no contexts have been created yet. This covers standalone apps - // and excludes applets because by the time applet starts - // a number of contexts have already been created by the plugin. - if (numAppContexts.get() == 0) { - // This check is not necessary, its purpose is to help - // Plugin devs to catch all the cases of main AC creation. - if (System.getProperty("javaplugin.version") == null && - System.getProperty("javawebstart.version") == null) { - initMainAppContext(); - } - } - - AppContext context = threadGroup2appContext.get(threadGroup); - while (context == null) { - threadGroup = threadGroup.getParent(); - if (threadGroup == null) { - return null; - } - context = threadGroup2appContext.get(threadGroup); - } - - // In case we did anything in the above while loop, we add - // all the intermediate ThreadGroups to threadGroup2appContext - // so we won't spin again. - for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) { - threadGroup2appContext.put(tg, context); - } - - // Now we're done, so we cache the latest key/value pair. - threadAppContext.set(context); - - return context; - } - }); - } - - return appContext; - } - - /** - * Returns true if the specified AppContext is the main AppContext. - * - * @param ctx the context to compare with the main context - * @return true if the specified AppContext is the main AppContext. - * @since 1.8 - */ - public final static boolean isMainContext(AppContext ctx) { - return (ctx != null && ctx == mainAppContext); - } - - private final static AppContext getExecutionAppContext() { - SecurityManager securityManager = System.getSecurityManager(); - if ((securityManager != null) && - (securityManager instanceof AWTSecurityManager)) - { - AWTSecurityManager awtSecMgr = (AWTSecurityManager) securityManager; - AppContext secAppContext = awtSecMgr.getAppContext(); - return secAppContext; // Return what we're told - } - return null; - } - - private long DISPOSAL_TIMEOUT = 5000; // Default to 5-second timeout - // for disposal of all Frames - // (we wait for this time twice, - // once for dispose(), and once - // to clear the EventQueue). - - private long THREAD_INTERRUPT_TIMEOUT = 1000; - // Default to 1-second timeout for all - // interrupted Threads to exit, and another - // 1 second for all stopped Threads to die. - - /** - * Disposes of this AppContext, all of its top-level Frames, and - * all Threads and ThreadGroups contained within it. - * - * This method must be called from a Thread which is not contained - * within this AppContext. - * - * @exception IllegalThreadStateException if the current thread is - * contained within this AppContext - * @since 1.2 - */ - public void dispose() throws IllegalThreadStateException { - // Check to be sure that the current Thread isn't in this AppContext - if (this.threadGroup.parentOf(Thread.currentThread().getThreadGroup())) { - throw new IllegalThreadStateException( - "Current Thread is contained within AppContext to be disposed." - ); - } - - synchronized(this) { - if (this.state != State.VALID) { - return; // If already disposed or being disposed, bail. - } - - this.state = State.BEING_DISPOSED; - } - - final PropertyChangeSupport changeSupport = this.changeSupport; - if (changeSupport != null) { - changeSupport.firePropertyChange(DISPOSED_PROPERTY_NAME, false, true); - } - - // First, we post an InvocationEvent to be run on the - // EventDispatchThread which disposes of all top-level Frames and TrayIcons - - final Object notificationLock = new Object(); - - Runnable runnable = new Runnable() { - public void run() { - Window[] windowsToDispose = Window.getOwnerlessWindows(); - for (Window w : windowsToDispose) { - try { - w.dispose(); - } catch (Throwable t) { - log.finer("exception occured while disposing app context", t); - } - } - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported()) - { - SystemTray systemTray = SystemTray.getSystemTray(); - TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons(); - for (TrayIcon ti : trayIconsToDispose) { - systemTray.remove(ti); - } - } - return null; - } - }); - // Alert PropertyChangeListeners that the GUI has been disposed. - if (changeSupport != null) { - changeSupport.firePropertyChange(GUI_DISPOSED, false, true); - } - synchronized(notificationLock) { - notificationLock.notifyAll(); // Notify caller that we're done - } - } - }; - synchronized(notificationLock) { - SunToolkit.postEvent(this, - new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); - try { - notificationLock.wait(DISPOSAL_TIMEOUT); - } catch (InterruptedException e) { } - } - - // Next, we post another InvocationEvent to the end of the - // EventQueue. When it's executed, we know we've executed all - // events in the queue. - - runnable = new Runnable() { public void run() { - synchronized(notificationLock) { - notificationLock.notifyAll(); // Notify caller that we're done - } - } }; - synchronized(notificationLock) { - SunToolkit.postEvent(this, - new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); - try { - notificationLock.wait(DISPOSAL_TIMEOUT); - } catch (InterruptedException e) { } - } - - // We are done with posting events, so change the state to disposed - synchronized(this) { - this.state = State.DISPOSED; - } - - // Next, we interrupt all Threads in the ThreadGroup - this.threadGroup.interrupt(); - // Note, the EventDispatchThread we've interrupted may dump an - // InterruptedException to the console here. This needs to be - // fixed in the EventDispatchThread, not here. - - // Next, we sleep 10ms at a time, waiting for all of the active - // Threads in the ThreadGroup to exit. - - long startTime = System.currentTimeMillis(); - long endTime = startTime + THREAD_INTERRUPT_TIMEOUT; - while ((this.threadGroup.activeCount() > 0) && - (System.currentTimeMillis() < endTime)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { } - } - - // Then, we stop any remaining Threads - this.threadGroup.stop(); - - // Next, we sleep 10ms at a time, waiting for all of the active - // Threads in the ThreadGroup to die. - - startTime = System.currentTimeMillis(); - endTime = startTime + THREAD_INTERRUPT_TIMEOUT; - while ((this.threadGroup.activeCount() > 0) && - (System.currentTimeMillis() < endTime)) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { } - } - - // Next, we remove this and all subThreadGroups from threadGroup2appContext - int numSubGroups = this.threadGroup.activeGroupCount(); - if (numSubGroups > 0) { - ThreadGroup [] subGroups = new ThreadGroup[numSubGroups]; - numSubGroups = this.threadGroup.enumerate(subGroups); - for (int subGroup = 0; subGroup < numSubGroups; subGroup++) { - threadGroup2appContext.remove(subGroups[subGroup]); - } - } - threadGroup2appContext.remove(this.threadGroup); - - threadAppContext.set(null); - - // Finally, we destroy the ThreadGroup entirely. - try { - this.threadGroup.destroy(); - } catch (IllegalThreadStateException e) { - // Fired if not all the Threads died, ignore it and proceed - } - - synchronized (table) { - this.table.clear(); // Clear out the Hashtable to ease garbage collection - } - - numAppContexts.decrementAndGet(); - - mostRecentKeyValue = null; - } - - static final class PostShutdownEventRunnable implements Runnable { - private final AppContext appContext; - - public PostShutdownEventRunnable(AppContext ac) { - appContext = ac; - } - - public void run() { - final EventQueue eq = (EventQueue)appContext.get(EVENT_QUEUE_KEY); - if (eq != null) { - eq.postEvent(AWTAutoShutdown.getShutdownEvent()); - } - } - } - - static final class CreateThreadAction implements PrivilegedAction { - private final AppContext appContext; - private final Runnable runnable; - - public CreateThreadAction(AppContext ac, Runnable r) { - appContext = ac; - runnable = r; - } - - public Object run() { - Thread t = new Thread(appContext.getThreadGroup(), runnable); - t.setContextClassLoader(appContext.getContextClassLoader()); - t.setPriority(Thread.NORM_PRIORITY + 1); - t.setDaemon(true); - return t; - } - } - - static void stopEventDispatchThreads() { - for (AppContext appContext: getAppContexts()) { - if (appContext.isDisposed()) { - continue; - } - Runnable r = new PostShutdownEventRunnable(appContext); - // For security reasons EventQueue.postEvent should only be called - // on a thread that belongs to the corresponding thread group. - if (appContext != AppContext.getAppContext()) { - // Create a thread that belongs to the thread group associated - // with the AppContext and invokes EventQueue.postEvent. - PrivilegedAction action = new CreateThreadAction(appContext, r); - Thread thread = (Thread)AccessController.doPrivileged(action); - thread.start(); - } else { - r.run(); - } - } - } - - private MostRecentKeyValue mostRecentKeyValue = null; - private MostRecentKeyValue shadowMostRecentKeyValue = null; - - /** - * Returns the value to which the specified key is mapped in this context. - * - * @param key a key in the AppContext. - * @return the value to which the key is mapped in this AppContext; - * <code>null</code> if the key is not mapped to any value. - * @see #put(Object, Object) - * @since 1.2 - */ - public Object get(Object key) { - /* - * The most recent reference should be updated inside a synchronized - * block to avoid a race when put() and get() are executed in - * parallel on different threads. - */ - synchronized (table) { - // Note: this most recent key/value caching is thread-hot. - // A simple test using SwingSet found that 72% of lookups - // were matched using the most recent key/value. By instantiating - // a simple MostRecentKeyValue object on cache misses, the - // cache hits can be processed without synchronization. - - MostRecentKeyValue recent = mostRecentKeyValue; - if ((recent != null) && (recent.key == key)) { - return recent.value; - } - - Object value = table.get(key); - if(mostRecentKeyValue == null) { - mostRecentKeyValue = new MostRecentKeyValue(key, value); - shadowMostRecentKeyValue = new MostRecentKeyValue(key, value); - } else { - MostRecentKeyValue auxKeyValue = mostRecentKeyValue; - shadowMostRecentKeyValue.setPair(key, value); - mostRecentKeyValue = shadowMostRecentKeyValue; - shadowMostRecentKeyValue = auxKeyValue; - } - return value; - } - } - - /** - * Maps the specified <code>key</code> to the specified - * <code>value</code> in this AppContext. Neither the key nor the - * value can be <code>null</code>. - * <p> - * The value can be retrieved by calling the <code>get</code> method - * with a key that is equal to the original key. - * - * @param key the AppContext key. - * @param value the value. - * @return the previous value of the specified key in this - * AppContext, or <code>null</code> if it did not have one. - * @exception NullPointerException if the key or value is - * <code>null</code>. - * @see #get(Object) - * @since 1.2 - */ - public Object put(Object key, Object value) { - synchronized (table) { - MostRecentKeyValue recent = mostRecentKeyValue; - if ((recent != null) && (recent.key == key)) - recent.value = value; - return table.put(key, value); - } - } - - /** - * Removes the key (and its corresponding value) from this - * AppContext. This method does nothing if the key is not in the - * AppContext. - * - * @param key the key that needs to be removed. - * @return the value to which the key had been mapped in this AppContext, - * or <code>null</code> if the key did not have a mapping. - * @since 1.2 - */ - public Object remove(Object key) { - synchronized (table) { - MostRecentKeyValue recent = mostRecentKeyValue; - if ((recent != null) && (recent.key == key)) - recent.value = null; - return table.remove(key); - } - } - - /** - * Returns the root ThreadGroup for all Threads contained within - * this AppContext. - * @since 1.2 - */ - public ThreadGroup getThreadGroup() { - return threadGroup; - } - - /** - * Returns the context ClassLoader that was used to create this - * AppContext. - * - * @see java.lang.Thread#getContextClassLoader - */ - public ClassLoader getContextClassLoader() { - return contextClassLoader; - } - - /** - * Returns a string representation of this AppContext. - * @since 1.2 - */ - @Override - public String toString() { - return getClass().getName() + "[threadGroup=" + threadGroup.getName() + "]"; - } - - /** - * Returns an array of all the property change listeners - * registered on this component. - * - * @return all of this component's <code>PropertyChangeListener</code>s - * or an empty array if no property change - * listeners are currently registered - * - * @see #addPropertyChangeListener - * @see #removePropertyChangeListener - * @see #getPropertyChangeListeners(java.lang.String) - * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners - * @since 1.4 - */ - public synchronized PropertyChangeListener[] getPropertyChangeListeners() { - if (changeSupport == null) { - return new PropertyChangeListener[0]; - } - return changeSupport.getPropertyChangeListeners(); - } - - /** - * Adds a PropertyChangeListener to the listener list for a specific - * property. The specified property may be one of the following: - * <ul> - * <li>if this AppContext is disposed ("disposed")</li> - * </ul> - * <ul> - * <li>if this AppContext's unowned Windows have been disposed - * ("guidisposed"). Code to cleanup after the GUI is disposed - * (such as LookAndFeel.uninitialize()) should execute in response to - * this property being fired. Notifications for the "guidisposed" - * property are sent on the event dispatch thread.</li> - * </ul> - * <p> - * If listener is null, no exception is thrown and no action is performed. - * - * @param propertyName one of the property names listed above - * @param listener the PropertyChangeListener to be added - * - * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) - * @see #getPropertyChangeListeners(java.lang.String) - * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) - */ - public synchronized void addPropertyChangeListener( - String propertyName, - PropertyChangeListener listener) { - if (listener == null) { - return; - } - if (changeSupport == null) { - changeSupport = new PropertyChangeSupport(this); - } - changeSupport.addPropertyChangeListener(propertyName, listener); - } - - /** - * Removes a PropertyChangeListener from the listener list for a specific - * property. This method should be used to remove PropertyChangeListeners - * that were registered for a specific bound property. - * <p> - * If listener is null, no exception is thrown and no action is performed. - * - * @param propertyName a valid property name - * @param listener the PropertyChangeListener to be removed - * - * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) - * @see #getPropertyChangeListeners(java.lang.String) - * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) - */ - public synchronized void removePropertyChangeListener( - String propertyName, - PropertyChangeListener listener) { - if (listener == null || changeSupport == null) { - return; - } - changeSupport.removePropertyChangeListener(propertyName, listener); - } - - /** - * Returns an array of all the listeners which have been associated - * with the named property. - * - * @return all of the <code>PropertyChangeListeners</code> associated with - * the named property or an empty array if no listeners have - * been added - * - * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) - * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) - * @see #getPropertyChangeListeners - * @since 1.4 - */ - public synchronized PropertyChangeListener[] getPropertyChangeListeners( - String propertyName) { - if (changeSupport == null) { - return new PropertyChangeListener[0]; - } - return changeSupport.getPropertyChangeListeners(propertyName); - } - - // Set up JavaAWTAccess in SharedSecrets - static { - sun.misc.SharedSecrets.setJavaAWTAccess(new sun.misc.JavaAWTAccess() { - public Object get(Object key) { - AppContext ac = getAppContext(); - return (ac == null) ? null : ac.get(key); - } - public void put(Object key, Object value) { - AppContext ac = getAppContext(); - if (ac != null) { - ac.put(key, value); - } - } - public void remove(Object key) { - AppContext ac = getAppContext(); - if (ac != null) { - ac.remove(key); - } - } - public boolean isDisposed() { - AppContext ac = getAppContext(); - return (ac == null) ? true : ac.isDisposed(); - } - public boolean isMainAppContext() { - return (numAppContexts.get() == 1 && mainAppContext != null); - } - public Object getContext() { - return getAppContext(); - } - public Object getExecutionContext() { - return getExecutionAppContext(); - } - public Object get(Object context, Object key) { - return ((AppContext)context).get(key); - } - public void put(Object context, Object key, Object value) { - ((AppContext)context).put(key, value); - } - public void remove(Object context, Object key) { - ((AppContext)context).remove(key); - } - }); - } -} - -final class MostRecentKeyValue { - Object key; - Object value; - MostRecentKeyValue(Object k, Object v) { - key = k; - value = v; - } - void setPair(Object k, Object v) { - key = k; - value = v; - } -} diff --git a/openjdk/sun/awt/EmbeddedFrame.java b/openjdk/sun/awt/EmbeddedFrame.java deleted file mode 100644 index ac350852..00000000 --- a/openjdk/sun/awt/EmbeddedFrame.java +++ /dev/null @@ -1,590 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt; - -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; -import java.awt.peer.*; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.lang.reflect.Field; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeEvent; -import java.util.Set; -import java.awt.AWTKeyStroke; -import java.applet.Applet; - -/** - * A generic container used for embedding Java components, usually applets. - * An EmbeddedFrame has two related uses: - * - * . Within a Java-based application, an EmbeddedFrame serves as a sort of - * firewall, preventing the contained components or applets from using - * getParent() to find parent components, such as menubars. - * - * . Within a C-based application, an EmbeddedFrame contains a window handle - * which was created by the application, which serves as the top-level - * Java window. EmbeddedFrames created for this purpose are passed-in a - * handle of an existing window created by the application. The window - * handle should be of the appropriate native type for a specific - * platform, as stored in the pData field of the ComponentPeer. - * - * @author Thomas Ball - */ -public abstract class EmbeddedFrame extends Frame - implements KeyEventDispatcher, PropertyChangeListener { - - private boolean isCursorAllowed = true; - private static Field fieldPeer; - private static Field currentCycleRoot; - private boolean supportsXEmbed = false; - private KeyboardFocusManager appletKFM; - // JDK 1.1 compatibility - private static final long serialVersionUID = 2967042741780317130L; - - // Use these in traverseOut method to determine directions - protected static final boolean FORWARD = true; - protected static final boolean BACKWARD = false; - - public boolean supportsXEmbed() { - return supportsXEmbed && SunToolkit.needsXEmbed(); - } - - protected EmbeddedFrame(boolean supportsXEmbed) { - this((long)0, supportsXEmbed); - } - - - protected EmbeddedFrame() { - this((long)0); - } - - /** - * @deprecated This constructor will be removed in 1.5 - */ - @Deprecated - protected EmbeddedFrame(int handle) { - this((long)handle); - } - - protected EmbeddedFrame(long handle) { - this(handle, false); - } - - protected EmbeddedFrame(long handle, boolean supportsXEmbed) { - this.supportsXEmbed = supportsXEmbed; - registerListeners(); - } - - /** - * Block introspection of a parent window by this child. - */ - public Container getParent() { - return null; - } - - /** - * Needed to track which KeyboardFocusManager is current. We want to avoid memory - * leaks, so when KFM stops being current, we remove ourselves as listeners. - */ - public void propertyChange(PropertyChangeEvent evt) { - // We don't handle any other properties. Skip it. - if (!evt.getPropertyName().equals("managingFocus")) { - return; - } - - // We only do it if it stops being current. Technically, we should - // never get an event about KFM starting being current. - if (evt.getNewValue() == Boolean.TRUE) { - return; - } - - // should be the same as appletKFM - removeTraversingOutListeners((KeyboardFocusManager)evt.getSource()); - - appletKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - if (isVisible()) { - addTraversingOutListeners(appletKFM); - } - } - - /** - * Register us as KeyEventDispatcher and property "managingFocus" listeners. - */ - private void addTraversingOutListeners(KeyboardFocusManager kfm) { - kfm.addKeyEventDispatcher(this); - kfm.addPropertyChangeListener("managingFocus", this); - } - - /** - * Deregister us as KeyEventDispatcher and property "managingFocus" listeners. - */ - private void removeTraversingOutListeners(KeyboardFocusManager kfm) { - kfm.removeKeyEventDispatcher(this); - kfm.removePropertyChangeListener("managingFocus", this); - } - - /** - * Because there may be many AppContexts, and we can't be sure where this - * EmbeddedFrame is first created or shown, we can't automatically determine - * the correct KeyboardFocusManager to attach to as KeyEventDispatcher. - * Those who want to use the functionality of traversing out of the EmbeddedFrame - * must call this method on the Applet's AppContext. After that, all the changes - * can be handled automatically, including possible replacement of - * KeyboardFocusManager. - */ - public void registerListeners() { - if (appletKFM != null) { - removeTraversingOutListeners(appletKFM); - } - appletKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - if (isVisible()) { - addTraversingOutListeners(appletKFM); - } - } - - /** - * Needed to avoid memory leak: we register this EmbeddedFrame as a listener with - * KeyboardFocusManager of applet's AppContext. We don't want the KFM to keep - * reference to our EmbeddedFrame forever if the Frame is no longer in use, so we - * add listeners in show() and remove them in hide(). - */ - public void show() { - if (appletKFM != null) { - addTraversingOutListeners(appletKFM); - } - super.show(); - } - - /** - * Needed to avoid memory leak: we register this EmbeddedFrame as a listener with - * KeyboardFocusManager of applet's AppContext. We don't want the KFM to keep - * reference to our EmbeddedFrame forever if the Frame is no longer in use, so we - * add listeners in show() and remove them in hide(). - */ - public void hide() { - if (appletKFM != null) { - removeTraversingOutListeners(appletKFM); - } - super.hide(); - } - - /** - * Need this method to detect when the focus may have chance to leave the - * focus cycle root which is EmbeddedFrame. Mostly, the code here is copied - * from DefaultKeyboardFocusManager.processKeyEvent with some minor - * modifications. - */ - public boolean dispatchKeyEvent(KeyEvent e) { - - // We can't guarantee that this is called on the same AppContext as EmbeddedFrame - // belongs to. That's why we can't use public methods to find current focus cycle - // root. Instead, we access KFM's private field directly. - if (currentCycleRoot == null) { - currentCycleRoot = (Field)AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - try { - Field unaccessibleRoot = KeyboardFocusManager.class. - getDeclaredField("currentFocusCycleRoot"); - if (unaccessibleRoot != null) { - unaccessibleRoot.setAccessible(true); - } - return unaccessibleRoot; - } catch (NoSuchFieldException e1) { - assert false; - } catch (SecurityException e2) { - assert false; - } - return null; - } - }); - } - - Container currentRoot = null; - if (currentCycleRoot != null) { - try { - // The field is static, so we can pass null to Field.get() as the argument. - currentRoot = (Container)currentCycleRoot.get(null); - } catch (IllegalAccessException e3) { - // This is impossible: currentCycleRoot would be null if setAccessible failed. - assert false; - } - } - - // if we are not in EmbeddedFrame's cycle, we should not try to leave. - if (this != currentRoot) { - return false; - } - - // KEY_TYPED events cannot be focus traversal keys - if (e.getID() == KeyEvent.KEY_TYPED) { - return false; - } - - if (!getFocusTraversalKeysEnabled() || e.isConsumed()) { - return false; - } - - AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e); - Set toTest; - Component currentFocused = e.getComponent(); - - Component last = getFocusTraversalPolicy().getLastComponent(this); - toTest = getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); - if (toTest.contains(stroke) && (currentFocused == last || last == null)) { - if (traverseOut(FORWARD)) { - e.consume(); - return true; - } - } - - Component first = getFocusTraversalPolicy().getFirstComponent(this); - toTest = getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); - if (toTest.contains(stroke) && (currentFocused == first || first == null)) { - if (traverseOut(BACKWARD)) { - e.consume(); - return true; - } - } - return false; - } - - /** - * This method is called from dispatchKeyEvent in the following two cases: - * 1. The focus is on the first Component of this EmbeddedFrame and we are - * about to transfer the focus backward. - * 2. The focus in on the last Component of this EmbeddedFrame and we are - * about to transfer the focus forward. - * This is needed to give the opportuity for keyboard focus to leave the - * EmbeddedFrame. Override this method, initiate focus transfer in it and - * return true if you want the focus to leave EmbeddedFrame's cycle. - * The direction parameter specifies which of the two mentioned cases is - * happening. Use FORWARD and BACKWARD constants defined in EmbeddedFrame - * to avoid confusing boolean values. - * - * @param direction FORWARD or BACKWARD - * @return true, if EmbeddedFrame wants the focus to leave it, - * false otherwise. - */ - protected boolean traverseOut(boolean direction) { - return false; - } - - /** - * Block modifying any frame attributes, since they aren't applicable - * for EmbeddedFrames. - */ - public void setTitle(String title) {} - public void setIconImage(Image image) {} - public void setIconImages(java.util.List<? extends Image> icons) {} - public void setMenuBar(MenuBar mb) {} - public void setResizable(boolean resizable) {} - public void remove(MenuComponent m) {} - - public boolean isResizable() { - return true; - } - - public void addNotify() { - synchronized (getTreeLock()) { - if (getPeer() == null) { - setPeer(new NullEmbeddedFramePeer()); - } - super.addNotify(); - } - } - - // These three functions consitute RFE 4100710. Do not remove. - public void setCursorAllowed(boolean isCursorAllowed) { - this.isCursorAllowed = isCursorAllowed; - getPeer().updateCursorImmediately(); - } - public boolean isCursorAllowed() { - return isCursorAllowed; - } - public Cursor getCursor() { - return (isCursorAllowed) - ? super.getCursor() - : Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); - } - - protected void setPeer(final ComponentPeer p){ - if (fieldPeer == null) { - fieldPeer = (Field)AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - try { - Field lnkPeer = Component.class.getDeclaredField("peer"); - if (lnkPeer != null) { - lnkPeer.setAccessible(true); - } - return lnkPeer; - } catch (NoSuchFieldException e) { - assert false; - } catch (SecurityException e) { - assert false; - } - return null; - }//run - }); - } - try{ - if (fieldPeer !=null){ - fieldPeer.set(EmbeddedFrame.this, p); - } - } catch (IllegalAccessException e) { - assert false; - } - }; //setPeer method ends - - /** - * Synthesize native message to activate or deactivate EmbeddedFrame window - * depending on the value of parameter <code>b</code>. - * Peers should override this method if they are to implement - * this functionality. - * @param doActivate if <code>true</code>, activates the window; - * otherwise, deactivates the window - */ - public void synthesizeWindowActivation(boolean doActivate) {} - - /** - * Moves this embedded frame to a new location. The top-left corner of - * the new location is specified by the <code>x</code> and <code>y</code> - * parameters relative to the native parent component. - * <p> - * setLocation() and setBounds() for EmbeddedFrame really don't move it - * within the native parent. These methods always put embedded frame to - * (0, 0) for backward compatibility. To allow moving embedded frame - * setLocationPrivate() and setBoundsPrivate() were introduced, and they - * work just the same way as setLocation() and setBounds() for usual, - * non-embedded components. - * </p> - * <p> - * Using usual get/setLocation() and get/setBounds() together with new - * get/setLocationPrivate() and get/setBoundsPrivate() is not recommended. - * For example, calling getBoundsPrivate() after setLocation() works fine, - * but getBounds() after setBoundsPrivate() may return unpredictable value. - * </p> - * @param x the new <i>x</i>-coordinate relative to the parent component - * @param y the new <i>y</i>-coordinate relative to the parent component - * @see java.awt.Component#setLocation - * @see #getLocationPrivate - * @see #setBoundsPrivate - * @see #getBoundsPrivate - * @since 1.5 - */ - protected void setLocationPrivate(int x, int y) { - Dimension size = getSize(); - setBoundsPrivate(x, y, size.width, size.height); - } - - /** - * Gets the location of this embedded frame as a point specifying the - * top-left corner relative to parent component. - * <p> - * setLocation() and setBounds() for EmbeddedFrame really don't move it - * within the native parent. These methods always put embedded frame to - * (0, 0) for backward compatibility. To allow getting location and size - * of embedded frame getLocationPrivate() and getBoundsPrivate() were - * introduced, and they work just the same way as getLocation() and getBounds() - * for ususal, non-embedded components. - * </p> - * <p> - * Using usual get/setLocation() and get/setBounds() together with new - * get/setLocationPrivate() and get/setBoundsPrivate() is not recommended. - * For example, calling getBoundsPrivate() after setLocation() works fine, - * but getBounds() after setBoundsPrivate() may return unpredictable value. - * </p> - * @return a point indicating this embedded frame's top-left corner - * @see java.awt.Component#getLocation - * @see #setLocationPrivate - * @see #setBoundsPrivate - * @see #getBoundsPrivate - * @since 1.6 - */ - protected Point getLocationPrivate() { - Rectangle bounds = getBoundsPrivate(); - return new Point(bounds.x, bounds.y); - } - - /** - * Moves and resizes this embedded frame. The new location of the top-left - * corner is specified by <code>x</code> and <code>y</code> parameters - * relative to the native parent component. The new size is specified by - * <code>width</code> and <code>height</code>. - * <p> - * setLocation() and setBounds() for EmbeddedFrame really don't move it - * within the native parent. These methods always put embedded frame to - * (0, 0) for backward compatibility. To allow moving embedded frames - * setLocationPrivate() and setBoundsPrivate() were introduced, and they - * work just the same way as setLocation() and setBounds() for usual, - * non-embedded components. - * </p> - * <p> - * Using usual get/setLocation() and get/setBounds() together with new - * get/setLocationPrivate() and get/setBoundsPrivate() is not recommended. - * For example, calling getBoundsPrivate() after setLocation() works fine, - * but getBounds() after setBoundsPrivate() may return unpredictable value. - * </p> - * @param x the new <i>x</i>-coordinate relative to the parent component - * @param y the new <i>y</i>-coordinate relative to the parent component - * @param width the new <code>width</code> of this embedded frame - * @param height the new <code>height</code> of this embedded frame - * @see java.awt.Component#setBounds - * @see #setLocationPrivate - * @see #getLocationPrivate - * @see #getBoundsPrivate - * @since 1.5 - */ - protected void setBoundsPrivate(int x, int y, int width, int height) { - final FramePeer peer = (FramePeer)getPeer(); - if (peer != null) { - peer.setBoundsPrivate(x, y, width, height); - } - } - - /** - * Gets the bounds of this embedded frame as a rectangle specifying the - * width, height and location relative to the native parent component. - * <p> - * setLocation() and setBounds() for EmbeddedFrame really don't move it - * within the native parent. These methods always put embedded frame to - * (0, 0) for backward compatibility. To allow getting location and size - * of embedded frames getLocationPrivate() and getBoundsPrivate() were - * introduced, and they work just the same way as getLocation() and getBounds() - * for ususal, non-embedded components. - * </p> - * <p> - * Using usual get/setLocation() and get/setBounds() together with new - * get/setLocationPrivate() and get/setBoundsPrivate() is not recommended. - * For example, calling getBoundsPrivate() after setLocation() works fine, - * but getBounds() after setBoundsPrivate() may return unpredictable value. - * </p> - * @return a rectangle indicating this embedded frame's bounds - * @see java.awt.Component#getBounds - * @see #setLocationPrivate - * @see #getLocationPrivate - * @see #setBoundsPrivate - * @since 1.6 - */ - protected Rectangle getBoundsPrivate() { - final FramePeer peer = (FramePeer)getPeer(); - if (peer != null) { - return peer.getBoundsPrivate(); - } - else { - return getBounds(); - } - } - - public void toFront() {} - public void toBack() {} - - public abstract void registerAccelerator(AWTKeyStroke stroke); - public abstract void unregisterAccelerator(AWTKeyStroke stroke); - - /** - * Checks if the component is in an EmbeddedFrame. If so, - * returns the applet found in the hierarchy or null if - * not found. - * @return the parent applet or {@ null} - * @since 1.6 - */ - public static Applet getAppletIfAncestorOf(Component comp) { - Container parent = comp.getParent(); - Applet applet = null; - while (parent != null && !(parent instanceof EmbeddedFrame)) { - if (parent instanceof Applet) { - applet = (Applet)parent; - } - parent = parent.getParent(); - } - return parent == null ? null : applet; - } - - /** - * This method should be overriden in subclasses. It is - * called when window this frame is within should be blocked - * by some modal dialog. - */ - public void notifyModalBlocked(Dialog blocker, boolean blocked) { - } - - private static class NullEmbeddedFramePeer - extends NullComponentPeer implements FramePeer { - public void setTitle(String title) {} - public void setIconImage(Image im) {} - public void updateIconImages() {} - public void setMenuBar(MenuBar mb) {} - public void setResizable(boolean resizeable) {} - public void setState(int state) {} - public int getState() { return Frame.NORMAL; } - public void setMaximizedBounds(Rectangle b) {} - public void toFront() {} - public void toBack() {} - public void updateFocusableWindowState() {} - public void updateAlwaysOnTop() {} - public void setAlwaysOnTop(boolean alwaysOnTop) {} - public Component getGlobalHeavyweightFocusOwner() { return null; } - public void setBoundsPrivate(int x, int y, int width, int height) { - setBounds(x, y, width, height, SET_BOUNDS); - } - public Rectangle getBoundsPrivate() { - return getBounds(); - } - public void setModalBlocked(Dialog blocker, boolean blocked) {} - - /** - * @see java.awt.peer.ContainerPeer#restack - */ - public void restack() { - throw new UnsupportedOperationException(); - } - - /** - * @see java.awt.peer.ContainerPeer#isRestackSupported - */ - public boolean isRestackSupported() { - return false; - } - public boolean requestWindowFocus() { - return false; - } - public void updateMinimumSize() { - } - public void setOpacity(float opacity) { - } - public void setOpaque(boolean isOpaque) { - } - public void updateWindow() { - } - public void repositionSecurityWarning() { - } - } -} // class EmbeddedFrame diff --git a/openjdk/sun/awt/IkvmDataTransferer.java b/openjdk/sun/awt/IkvmDataTransferer.java deleted file mode 100644 index 27040318..00000000 --- a/openjdk/sun/awt/IkvmDataTransferer.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - Copyright (C) 2009 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ - -package sun.awt; - -import java.awt.Image; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.FlavorTable; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedMap; - -import sun.awt.datatransfer.DataTransferer; -import cli.System.Runtime.InteropServices.DllImportAttribute; - -public abstract class IkvmDataTransferer extends DataTransferer { - public static final int CF_TEXT = 1; - public static final int CF_METAFILEPICT = 3; - public static final int CF_DIB = 8; - public static final int CF_ENHMETAFILE = 14; - public static final int CF_HDROP = 15; - public static final int CF_LOCALE = 16; - - public static final long CF_HTML = RegisterClipboardFormat("HTML Format"); - public static final long CFSTR_INETURL = RegisterClipboardFormat("UniformResourceLocator"); - public static final long CF_PNG = RegisterClipboardFormat("PNG"); - public static final long CF_JFIF = RegisterClipboardFormat("JFIF"); - - private static final String[] predefinedClipboardNames = { - "", - "TEXT", - "BITMAP", - "METAFILEPICT", - "SYLK", - "DIF", - "TIFF", - "OEM TEXT", - "DIB", - "PALETTE", - "PENDATA", - "RIFF", - "WAVE", - "UNICODE TEXT", - "ENHMETAFILE", - "HDROP", - "LOCALE", - "DIBV5" - }; - - private static final Map<String, Long> predefinedClipboardNameMap; - - static { - Map<String, Long> tempMap = new HashMap<String, Long>(predefinedClipboardNames.length, 1.0f); - for (int i = 1; i < predefinedClipboardNames.length; i++) { - tempMap.put(predefinedClipboardNames[i], Long.valueOf(i)); - } - predefinedClipboardNameMap = Collections.synchronizedMap(tempMap); - } - - private static final Long L_CF_LOCALE = (Long) predefinedClipboardNameMap.get(predefinedClipboardNames[CF_LOCALE]); - - @DllImportAttribute.Annotation(value = "user32.dll", EntryPoint = "RegisterClipboardFormat") - private native static int _RegisterClipboardFormat(String format); - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - private static int RegisterClipboardFormat(String format) - { - return _RegisterClipboardFormat(format); - } - - public SortedMap getFormatsForFlavors(DataFlavor[] flavors, FlavorTable map) { - SortedMap retval = super.getFormatsForFlavors(flavors, map); - - // The Win32 native code does not support exporting LOCALE data, nor - // should it. - retval.remove(L_CF_LOCALE); - - return retval; - } - - public String getDefaultUnicodeEncoding() { - return "utf-16le"; - } - - public byte[] translateTransferable(Transferable contents, - DataFlavor flavor, - long format) throws IOException - { - byte[] bytes = super.translateTransferable(contents, flavor, format); - - if (format == CF_HTML) { - bytes = HTMLCodec.convertToHTMLFormat(bytes); - } - return bytes; - } - - protected Object translateBytesOrStream(InputStream str, byte[] bytes, - DataFlavor flavor, long format, - Transferable localeTransferable) - throws IOException - { - if (format == CF_HTML && flavor.isFlavorTextType()) { - if (str == null) { - str = new ByteArrayInputStream(bytes); - bytes = null; - } - - str = new HTMLCodec(str, EHTMLReadMode.HTML_READ_SELECTION); - } - - if (format == CFSTR_INETURL && - URL.class.equals(flavor.getRepresentationClass())) - { - if (bytes == null) { - bytes = inputStreamToByteArray(str); - str = null; - } - String charset = getDefaultTextCharset(); - if (localeTransferable != null && localeTransferable. - isDataFlavorSupported(javaTextEncodingFlavor)) - { - try { - charset = new String((byte[])localeTransferable. - getTransferData(javaTextEncodingFlavor), - "UTF-8"); - } catch (UnsupportedFlavorException cannotHappen) { - } - } - return new URL(new String(bytes, charset)); - } - - return super.translateBytesOrStream(str, bytes, flavor, format, - localeTransferable); - } - - protected byte[] imageToPlatformBytes(Image image, long format) - throws IOException { - String mimeType = null; - if (format == CF_PNG) { - mimeType = "image/png"; - } else if (format == CF_JFIF) { - mimeType = "image/jpeg"; - } - if (mimeType != null) { - return imageToStandardBytes(image, mimeType); - } - throw new Error("Not implemented"); - } - - protected abstract byte[] imageToStandardBytes(Image image, String mimeType) - throws IOException; - - protected Image platformImageBytesOrStreamToImage(InputStream str, - byte[] bytes, long format) { - throw new Error("Not implemented"); - } - - protected String[] dragQueryFile(byte[] bytes) { - throw new Error("Not implemented"); - } - - protected String getNativeForFormat(long format) { - return (format < predefinedClipboardNames.length && format>=0) - ? predefinedClipboardNames[(int)format] - : getClipboardFormatName(format); - } - - protected Long getFormatForNativeAsLong(String str) { - Long format = (Long)predefinedClipboardNameMap.get(str); - if (format == null) { - format = Long.valueOf(RegisterClipboardFormat(str)); - } - return format; } - - protected abstract String getClipboardFormatName(long format); - - public boolean isImageFormat(long format) { - return format == CF_DIB || format == CF_ENHMETAFILE || - format == CF_METAFILEPICT || format == CF_PNG || - format == CF_JFIF; - } - - public boolean isLocaleDependentTextFormat(long format) { - return format == CF_TEXT || format == CFSTR_INETURL; - } - - public boolean isFileFormat(long format) { - return format == CF_HDROP; - } - -} - -enum EHTMLReadMode { - HTML_READ_ALL, - HTML_READ_FRAGMENT, - HTML_READ_SELECTION -} - -/** - * on decode: This stream takes an InputStream which provides data in CF_HTML format, - * strips off the description and context to extract the original HTML data. - * - * on encode: static convertToHTMLFormat is responsible for HTML clipboard header creation - */ -class HTMLCodec extends InputStream { - //static section - public static final String ENCODING = "UTF-8"; - - public static final String VERSION = "Version:"; - public static final String START_HTML = "StartHTML:"; - public static final String END_HTML = "EndHTML:"; - public static final String START_FRAGMENT = "StartFragment:"; - public static final String END_FRAGMENT = "EndFragment:"; - public static final String START_SELECTION = "StartSelection:"; //optional - public static final String END_SELECTION = "EndSelection:"; //optional - - public static final String START_FRAGMENT_CMT = "<!--StartFragment-->"; - public static final String END_FRAGMENT_CMT = "<!--EndFragment-->"; - public static final String SOURCE_URL = "SourceURL:"; - public static final String DEF_SOURCE_URL = "about:blank"; - - public static final String EOLN = "\r\n"; - - private static final String VERSION_NUM = "1.0"; - private static final int PADDED_WIDTH = 10; - - private static String toPaddedString(int n, int width) { - String string = "" + n; - int len = string.length(); - if (n >= 0 && len < width) { - char[] array = new char[width - len]; - Arrays.fill(array, '0'); - StringBuffer buffer = new StringBuffer(width); - buffer.append(array); - buffer.append(string); - string = buffer.toString(); - } - return string; - } - - /** - * convertToHTMLFormat adds the MS HTML clipboard header to byte array that - * contains the parameters pairs. - * - * The consequence of parameters is fixed, but some or all of them could be - * omitted. One parameter per one text line. - * It looks like that: - * - * Version:1.0\r\n -- current supported version - * StartHTML:000000192\r\n -- shift in array to the first byte after the header - * EndHTML:000000757\r\n -- shift in array of last byte for HTML syntax analysis - * StartFragment:000000396\r\n -- shift in array jast after <!--StartFragment--> - * EndFragment:000000694\r\n -- shift in array before start <!--EndFragment--> - * StartSelection:000000398\r\n -- shift in array of the first char in copied selection - * EndSelection:000000692\r\n -- shift in array of the last char in copied selection - * SourceURL:http://sun.com/\r\n -- base URL for related referenses - * <HTML>...<BODY>...<!--StartFragment-->.....................<!--EndFragment-->...</BODY><HTML> - * ^ ^ ^ ^^ ^ - * \ StartHTML | \-StartSelection | \EndFragment EndHTML/ - * \-StartFragment \EndSelection - * - *Combinations with tags sequence - *<!--StartFragment--><HTML>...<BODY>...</BODY><HTML><!--EndFragment--> - * or - *<HTML>...<!--StartFragment-->...<BODY>...</BODY><!--EndFragment--><HTML> - * are vailid too. - */ - public static byte[] convertToHTMLFormat(byte[] bytes) { - // Calculate section offsets - String htmlPrefix = ""; - String htmlSuffix = ""; - { - //we have extend the fragment to full HTML document correctly - //to avoid HTML and BODY tags doubling - String stContext = new String(bytes); - String stUpContext = stContext.toUpperCase(); - if( -1 == stUpContext.indexOf("<HTML") ) { - htmlPrefix = "<HTML>"; - htmlSuffix = "</HTML>"; - if( -1 == stUpContext.indexOf("<BODY") ) { - htmlPrefix = htmlPrefix +"<BODY>"; - htmlSuffix = "</BODY>" + htmlSuffix; - }; - }; - htmlPrefix = htmlPrefix + START_FRAGMENT_CMT; - htmlSuffix = END_FRAGMENT_CMT + htmlSuffix; - } - - String stBaseUrl = DEF_SOURCE_URL; - int nStartHTML = - VERSION.length() + VERSION_NUM.length() + EOLN.length() - + START_HTML.length() + PADDED_WIDTH + EOLN.length() - + END_HTML.length() + PADDED_WIDTH + EOLN.length() - + START_FRAGMENT.length() + PADDED_WIDTH + EOLN.length() - + END_FRAGMENT.length() + PADDED_WIDTH + EOLN.length() - + SOURCE_URL.length() + stBaseUrl.length() + EOLN.length() - ; - int nStartFragment = nStartHTML + htmlPrefix.length(); - int nEndFragment = nStartFragment + bytes.length - 1; - int nEndHTML = nEndFragment + htmlSuffix.length(); - - StringBuilder header = new StringBuilder( - nStartFragment - + START_FRAGMENT_CMT.length() - ); - //header - header.append(VERSION); - header.append(VERSION_NUM); - header.append(EOLN); - - header.append(START_HTML); - header.append(toPaddedString(nStartHTML, PADDED_WIDTH)); - header.append(EOLN); - - header.append(END_HTML); - header.append(toPaddedString(nEndHTML, PADDED_WIDTH)); - header.append(EOLN); - - header.append(START_FRAGMENT); - header.append(toPaddedString(nStartFragment, PADDED_WIDTH)); - header.append(EOLN); - - header.append(END_FRAGMENT); - header.append(toPaddedString(nEndFragment, PADDED_WIDTH)); - header.append(EOLN); - - header.append(SOURCE_URL); - header.append(stBaseUrl); - header.append(EOLN); - - //HTML - header.append(htmlPrefix); - - byte[] headerBytes = null, trailerBytes = null; - - try { - headerBytes = new String(header).getBytes(ENCODING); - trailerBytes = htmlSuffix.getBytes(ENCODING); - } catch (UnsupportedEncodingException cannotHappen) { - } - - byte[] retval = new byte[headerBytes.length + bytes.length + - trailerBytes.length]; - - System.arraycopy(headerBytes, 0, retval, 0, headerBytes.length); - System.arraycopy(bytes, 0, retval, headerBytes.length, - bytes.length - 1); - System.arraycopy(trailerBytes, 0, retval, - headerBytes.length + bytes.length - 1, - trailerBytes.length); - retval[retval.length-1] = 0; - - return retval; - } - - //////////////////////////////////// - //decoder instance data and methods: - - private final BufferedInputStream bufferedStream; - private boolean descriptionParsed = false; - private boolean closed = false; - - // InputStreamReader uses an 8K buffer. The size is not customizable. - public static final int BYTE_BUFFER_LEN = 8192; - - // CharToByteUTF8.getMaxBytesPerChar returns 3, so we should not buffer - // more chars than 3 times the number of bytes we can buffer. - public static final int CHAR_BUFFER_LEN = BYTE_BUFFER_LEN / 3; - - private static final String FAILURE_MSG = - "Unable to parse HTML description: "; - private static final String INVALID_MSG = - " invalid"; - - //HTML header mapping: - private long iHTMLStart,// StartHTML -- shift in array to the first byte after the header - iHTMLEnd, // EndHTML -- shift in array of last byte for HTML syntax analysis - iFragStart,// StartFragment -- shift in array jast after <!--StartFragment--> - iFragEnd, // EndFragment -- shift in array before start <!--EndFragment--> - iSelStart, // StartSelection -- shift in array of the first char in copied selection - iSelEnd; // EndSelection -- shift in array of the last char in copied selection - private String stBaseURL; // SourceURL -- base URL for related referenses - private String stVersion; // Version -- current supported version - - //Stream reader markers: - private long iStartOffset, - iEndOffset, - iReadCount; - - private EHTMLReadMode readMode; - - public HTMLCodec( - InputStream _bytestream, - EHTMLReadMode _readMode) throws IOException - { - bufferedStream = new BufferedInputStream(_bytestream, BYTE_BUFFER_LEN); - readMode = _readMode; - } - - public synchronized String getBaseURL() throws IOException - { - if( !descriptionParsed ) { - parseDescription(); - } - return stBaseURL; - } - public synchronized String getVersion() throws IOException - { - if( !descriptionParsed ) { - parseDescription(); - } - return stVersion; - } - - /** - * parseDescription parsing HTML clipboard header as it described in - * comment to convertToHTMLFormat - */ - private void parseDescription() throws IOException - { - stBaseURL = null; - stVersion = null; - - // initialization of array offset pointers - // to the same "uninitialized" state. - iHTMLEnd = - iHTMLStart = - iFragEnd = - iFragStart = - iSelEnd = - iSelStart = -1; - - bufferedStream.mark(BYTE_BUFFER_LEN); - String astEntries[] = new String[] { - //common - VERSION, - START_HTML, - END_HTML, - START_FRAGMENT, - END_FRAGMENT, - //ver 1.0 - START_SELECTION, - END_SELECTION, - SOURCE_URL - }; - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader( - bufferedStream, - ENCODING - ), - CHAR_BUFFER_LEN - ); - long iHeadSize = 0; - long iCRSize = EOLN.length(); - int iEntCount = astEntries.length; - boolean bContinue = true; - - for( int iEntry = 0; iEntry < iEntCount; ++iEntry ){ - String stLine = bufferedReader.readLine(); - if( null==stLine ) { - break; - } - //some header entries are optional, but the order is fixed. - for( ; iEntry < iEntCount; ++iEntry ){ - if( !stLine.startsWith(astEntries[iEntry]) ) { - continue; - } - iHeadSize += stLine.length() + iCRSize; - String stValue = stLine.substring(astEntries[iEntry].length()).trim(); - if( null!=stValue ) { - try{ - switch( iEntry ){ - case 0: - stVersion = stValue; - break; - case 1: - iHTMLStart = Integer.parseInt(stValue); - break; - case 2: - iHTMLEnd = Integer.parseInt(stValue); - break; - case 3: - iFragStart = Integer.parseInt(stValue); - break; - case 4: - iFragEnd = Integer.parseInt(stValue); - break; - case 5: - iSelStart = Integer.parseInt(stValue); - break; - case 6: - iSelEnd = Integer.parseInt(stValue); - break; - case 7: - stBaseURL = stValue; - break; - }; - } catch ( NumberFormatException e ) { - throw new IOException(FAILURE_MSG + astEntries[iEntry]+ " value " + e + INVALID_MSG); - } - } - break; - } - } - //some entries could absent in HTML header, - //so we have find they by another way. - if( -1 == iHTMLStart ) - iHTMLStart = iHeadSize; - if( -1 == iFragStart ) - iFragStart = iHTMLStart; - if( -1 == iFragEnd ) - iFragEnd = iHTMLEnd; - if( -1 == iSelStart ) - iSelStart = iFragStart; - if( -1 == iSelEnd ) - iSelEnd = iFragEnd; - - //one of possible modes - switch( readMode ){ - case HTML_READ_ALL: - iStartOffset = iHTMLStart; - iEndOffset = iHTMLEnd; - break; - case HTML_READ_FRAGMENT: - iStartOffset = iFragStart; - iEndOffset = iFragEnd; - break; - case HTML_READ_SELECTION: - default: - iStartOffset = iSelStart; - iEndOffset = iSelEnd; - break; - } - - bufferedStream.reset(); - if( -1 == iStartOffset ){ - throw new IOException(FAILURE_MSG + "invalid HTML format."); - } - iReadCount = bufferedStream.skip(iStartOffset); - if( iStartOffset != iReadCount ){ - throw new IOException(FAILURE_MSG + "Byte stream ends in description."); - } - descriptionParsed = true; - } - - public synchronized int read() throws IOException { - if( closed ){ - throw new IOException("Stream closed"); - } - - if( !descriptionParsed ){ - parseDescription(); - } - if( -1 != iEndOffset && iReadCount >= iEndOffset ) { - return -1; - } - - int retval = bufferedStream.read(); - if( retval == -1 ) { - return -1; - } - ++iReadCount; - return retval; - } - - public synchronized void close() throws IOException { - if( !closed ){ - closed = true; - bufferedStream.close(); - } - } -} diff --git a/openjdk/sun/awt/SunToolkit.java b/openjdk/sun/awt/SunToolkit.java deleted file mode 100644 index 11612ec1..00000000 --- a/openjdk/sun/awt/SunToolkit.java +++ /dev/null @@ -1,2010 +0,0 @@ -/* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt; - -import java.awt.*; -import static java.awt.RenderingHints.*; -import java.awt.dnd.*; -import java.awt.dnd.peer.DragSourceContextPeer; -import java.awt.peer.*; -import java.awt.event.WindowEvent; -import java.awt.event.KeyEvent; -import java.awt.image.*; -import java.awt.TrayIcon; -import java.awt.SystemTray; -import java.awt.event.InputEvent; -import java.net.URL; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import sun.security.util.SecurityConstants; -import sun.util.logging.PlatformLogger; -import sun.misc.SoftCache; -import sun.font.FontDesignMetrics; -import sun.awt.im.InputContext; -import sun.awt.image.*; -import sun.security.action.GetPropertyAction; -import sun.security.action.GetBooleanAction; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -public abstract class SunToolkit extends Toolkit - implements WindowClosingSupport, WindowClosingListener, - ComponentFactory, InputMethodSupport, KeyboardFocusManagerPeerProvider { - - // 8014736: logging has been removed from SunToolkit - - /** - * Special mask for the UngrabEvent events, in addition to the - * public masks defined in AWTEvent. Should be used as the mask - * value for Toolkit.addAWTEventListener. - */ - public static final int GRAB_EVENT_MASK = 0x80000000; - - private static Method wakeupMethod; - /* The key to put()/get() the PostEventQueue into/from the AppContext. - */ - private static final String POST_EVENT_QUEUE_KEY = "PostEventQueue"; - - /** - * Number of buttons. - * By default it's taken from the system. If system value does not - * fit into int type range, use our own MAX_BUTTONS_SUPPORT value. - */ - protected static int numberOfButtons = 0; - - - /* XFree standard mention 24 buttons as maximum: - * http://www.xfree86.org/current/mouse.4.html - * We workaround systems supporting more than 24 buttons. - * Otherwise, we have to use long type values as masks - * which leads to API change. - * InputEvent.BUTTON_DOWN_MASK may contain only 21 masks due to - * the 4-bytes limit for the int type. (CR 6799099) - * One more bit is reserved for FIRST_HIGH_BIT. - */ - public final static int MAX_BUTTONS_SUPPORTED = 20; - - /** - * Creates and initializes EventQueue instance for the specified - * AppContext. - * Note that event queue must be created from createNewAppContext() - * only in order to ensure that EventQueue constructor obtains - * the correct AppContext. - * @param appContext AppContext to associate with the event queue - */ - private static void initEQ(AppContext appContext) { - EventQueue eventQueue; - - String eqName = System.getProperty("AWT.EventQueueClass", - "java.awt.EventQueue"); - - try { - eventQueue = (EventQueue)Class.forName(eqName).newInstance(); - } catch (Exception e) { - e.printStackTrace(); - System.err.println("Failed loading " + eqName + ": " + e); - eventQueue = new EventQueue(); - } - appContext.put(AppContext.EVENT_QUEUE_KEY, eventQueue); - - PostEventQueue postEventQueue = new PostEventQueue(eventQueue); - appContext.put(POST_EVENT_QUEUE_KEY, postEventQueue); - } - - public SunToolkit() { - } - - public boolean useBufferPerWindow() { - return false; - } - - public abstract WindowPeer createWindow(Window target) - throws HeadlessException; - - public abstract FramePeer createFrame(Frame target) - throws HeadlessException; - - public abstract DialogPeer createDialog(Dialog target) - throws HeadlessException; - - public abstract ButtonPeer createButton(Button target) - throws HeadlessException; - - public abstract TextFieldPeer createTextField(TextField target) - throws HeadlessException; - - public abstract ChoicePeer createChoice(Choice target) - throws HeadlessException; - - public abstract LabelPeer createLabel(Label target) - throws HeadlessException; - - public abstract ListPeer createList(java.awt.List target) - throws HeadlessException; - - public abstract CheckboxPeer createCheckbox(Checkbox target) - throws HeadlessException; - - public abstract ScrollbarPeer createScrollbar(Scrollbar target) - throws HeadlessException; - - public abstract ScrollPanePeer createScrollPane(ScrollPane target) - throws HeadlessException; - - public abstract TextAreaPeer createTextArea(TextArea target) - throws HeadlessException; - - public abstract FileDialogPeer createFileDialog(FileDialog target) - throws HeadlessException; - - public abstract MenuBarPeer createMenuBar(MenuBar target) - throws HeadlessException; - - public abstract MenuPeer createMenu(Menu target) - throws HeadlessException; - - public abstract PopupMenuPeer createPopupMenu(PopupMenu target) - throws HeadlessException; - - public abstract MenuItemPeer createMenuItem(MenuItem target) - throws HeadlessException; - - public abstract CheckboxMenuItemPeer createCheckboxMenuItem( - CheckboxMenuItem target) - throws HeadlessException; - - public abstract DragSourceContextPeer createDragSourceContextPeer( - DragGestureEvent dge) - throws InvalidDnDOperationException; - - public abstract TrayIconPeer createTrayIcon(TrayIcon target) - throws HeadlessException, AWTException; - - public abstract SystemTrayPeer createSystemTray(SystemTray target); - - public abstract boolean isTraySupported(); - - public abstract FontPeer getFontPeer(String name, int style); - - public abstract RobotPeer createRobot(Robot target, GraphicsDevice screen) - throws AWTException; - - public abstract KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager) - throws HeadlessException; - - /** - * The AWT lock is typically only used on Unix platforms to synchronize - * access to Xlib, OpenGL, etc. However, these methods are implemented - * in SunToolkit so that they can be called from shared code (e.g. - * from the OGL pipeline) or from the X11 pipeline regardless of whether - * XToolkit or MToolkit is currently in use. There are native macros - * (such as AWT_LOCK) defined in awt.h, so if the implementation of these - * methods is changed, make sure it is compatible with the native macros. - * - * Note: The following methods (awtLock(), awtUnlock(), etc) should be - * used in place of: - * synchronized (getAWTLock()) { - * ... - * } - * - * By factoring these methods out specially, we are able to change the - * implementation of these methods (e.g. use more advanced locking - * mechanisms) without impacting calling code. - * - * Sample usage: - * private void doStuffWithXlib() { - * assert !SunToolkit.isAWTLockHeldByCurrentThread(); - * SunToolkit.awtLock(); - * try { - * ... - * XlibWrapper.XDoStuff(); - * } finally { - * SunToolkit.awtUnlock(); - * } - * } - */ - - private static final ReentrantLock AWT_LOCK = new ReentrantLock(); - private static final Condition AWT_LOCK_COND = AWT_LOCK.newCondition(); - - public static final void awtLock() { - AWT_LOCK.lock(); - } - - public static final boolean awtTryLock() { - return AWT_LOCK.tryLock(); - } - - public static final void awtUnlock() { - AWT_LOCK.unlock(); - } - - public static final void awtLockWait() - throws InterruptedException - { - AWT_LOCK_COND.await(); - } - - public static final void awtLockWait(long timeout) - throws InterruptedException - { - AWT_LOCK_COND.await(timeout, TimeUnit.MILLISECONDS); - } - - public static final void awtLockNotify() { - AWT_LOCK_COND.signal(); - } - - public static final void awtLockNotifyAll() { - AWT_LOCK_COND.signalAll(); - } - - public static final boolean isAWTLockHeldByCurrentThread() { - return AWT_LOCK.isHeldByCurrentThread(); - } - - /* - * Create a new AppContext, along with its EventQueue, for a - * new ThreadGroup. Browser code, for example, would use this - * method to create an AppContext & EventQueue for an Applet. - */ - public static AppContext createNewAppContext() { - ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); - return createNewAppContext(threadGroup); - } - - static final AppContext createNewAppContext(ThreadGroup threadGroup) { - // Create appContext before initialization of EventQueue, so all - // the calls to AppContext.getAppContext() from EventQueue ctor - // return correct values - AppContext appContext = new AppContext(threadGroup); - initEQ(appContext); - - return appContext; - } - - public static Field getField(final Class klass, final String fieldName) { - return AccessController.doPrivileged(new PrivilegedAction<Field>() { - public Field run() { - try { - Field field = klass.getDeclaredField(fieldName); - assert (field != null); - field.setAccessible(true); - return field; - } catch (SecurityException e) { - assert false; - } catch (NoSuchFieldException e) { - assert false; - } - return null; - }//run - }); - } - - static void wakeupEventQueue(EventQueue q, boolean isShutdown){ - if (wakeupMethod == null){ - wakeupMethod = (Method)AccessController.doPrivileged(new PrivilegedAction(){ - public Object run(){ - try { - Method method = EventQueue.class.getDeclaredMethod("wakeup",new Class [] {Boolean.TYPE} ); - if (method != null) { - method.setAccessible(true); - } - return method; - } catch (NoSuchMethodException e) { - assert false; - } catch (SecurityException e) { - assert false; - } - return null; - }//run - }); - } - try{ - if (wakeupMethod != null){ - wakeupMethod.invoke(q, new Object[]{Boolean.valueOf(isShutdown)}); - } - } catch (InvocationTargetException e){ - assert false; - } catch (IllegalAccessException e) { - assert false; - } - } - - /* - * Fetch the peer associated with the given target (as specified - * in the peer creation method). This can be used to determine - * things like what the parent peer is. If the target is null - * or the target can't be found (either because the a peer was - * never created for it or the peer was disposed), a null will - * be returned. - */ - protected static Object targetToPeer(Object target) { - if (target != null && !GraphicsEnvironment.isHeadless()) { - return AWTAutoShutdown.getInstance().getPeer(target); - } - return null; - } - - protected static void targetCreatedPeer(Object target, Object peer) { - if (target != null && peer != null && - !GraphicsEnvironment.isHeadless()) - { - AWTAutoShutdown.getInstance().registerPeer(target, peer); - } - } - - protected static void targetDisposedPeer(Object target, Object peer) { - if (target != null && peer != null && - !GraphicsEnvironment.isHeadless()) - { - AWTAutoShutdown.getInstance().unregisterPeer(target, peer); - } - } - - // Maps from non-Component/MenuComponent to AppContext. - // WeakHashMap<Component,AppContext> - private static final Map appContextMap = - Collections.synchronizedMap(new WeakHashMap()); - - /** - * Sets the appContext field of target. If target is not a Component or - * MenuComponent, this returns false. - */ - private static boolean setAppContext(Object target, - AppContext context) { - if (target instanceof Component) { - AWTAccessor.getComponentAccessor(). - setAppContext((Component)target, context); - } else if (target instanceof MenuComponent) { - AWTAccessor.getMenuComponentAccessor(). - setAppContext((MenuComponent)target, context); - } else { - return false; - } - return true; - } - - /** - * Returns the appContext field for target. If target is not a - * Component or MenuComponent this returns null. - */ - private static AppContext getAppContext(Object target) { - if (target instanceof Component) { - return AWTAccessor.getComponentAccessor(). - getAppContext((Component)target); - } else if (target instanceof MenuComponent) { - return AWTAccessor.getMenuComponentAccessor(). - getAppContext((MenuComponent)target); - } else { - return null; - } - } - - /* - * Fetch the AppContext associated with the given target. - * This can be used to determine things like which EventQueue - * to use for posting events to a Component. If the target is - * null or the target can't be found, a null with be returned. - */ - public static AppContext targetToAppContext(Object target) { - if (target == null || GraphicsEnvironment.isHeadless()) { - return null; - } - AppContext context = getAppContext(target); - if (context == null) { - // target is not a Component/MenuComponent, try the - // appContextMap. - context = (AppContext)appContextMap.get(target); - } - return context; - } - - /** - * Sets the synchronous status of focus requests on lightweight - * components in the specified window to the specified value. - * If the boolean parameter is <code>true</code> then the focus - * requests on lightweight components will be performed - * synchronously, if it is <code>false</code>, then asynchronously. - * By default, all windows have their lightweight request status - * set to asynchronous. - * <p> - * The application can only set the status of lightweight focus - * requests to synchronous for any of its windows if it doesn't - * perform focus transfers between different heavyweight containers. - * In this case the observable focus behaviour is the same as with - * asynchronous status. - * <p> - * If the application performs focus transfer between different - * heavyweight containers and sets the lightweight focus request - * status to synchronous for any of its windows, then further focus - * behaviour is unspecified. - * <p> - * @param w window for which the lightweight focus request status - * should be set - * @param status the value of lightweight focus request status - */ - - public static void setLWRequestStatus(Window changed,boolean status){ - AWTAccessor.getWindowAccessor().setLWRequestStatus(changed, status); - }; - - public static void checkAndSetPolicy(Container cont) { - FocusTraversalPolicy defaultPolicy = KeyboardFocusManager. - getCurrentKeyboardFocusManager(). - getDefaultFocusTraversalPolicy(); - - cont.setFocusTraversalPolicy(defaultPolicy); - } - - private static FocusTraversalPolicy createLayoutPolicy() { - FocusTraversalPolicy policy = null; - try { - Class layoutPolicyClass = - Class.forName("javax.swing.LayoutFocusTraversalPolicy"); - policy = (FocusTraversalPolicy) layoutPolicyClass.newInstance(); - } - catch (ClassNotFoundException e) { - assert false; - } - catch (InstantiationException e) { - assert false; - } - catch (IllegalAccessException e) { - assert false; - } - - return policy; - } - - /* - * Insert a mapping from target to AppContext, for later retrieval - * via targetToAppContext() above. - */ - public static void insertTargetMapping(Object target, AppContext appContext) { - if (!GraphicsEnvironment.isHeadless()) { - if (!setAppContext(target, appContext)) { - // Target is not a Component/MenuComponent, use the private Map - // instead. - appContextMap.put(target, appContext); - } - } - } - - /* - * Post an AWTEvent to the Java EventQueue, using the PostEventQueue - * to avoid possibly calling client code (EventQueueSubclass.postEvent()) - * on the toolkit (AWT-Windows/AWT-Motif) thread. This function should - * not be called under another lock since it locks the EventQueue. - * See bugids 4632918, 4526597. - */ - public static void postEvent(AppContext appContext, AWTEvent event) { - if (event == null) { - throw new NullPointerException(); - } - // All events posted via this method are system-generated. - // Placing the following call here reduces considerably the - // number of places throughout the toolkit that would - // otherwise have to be modified to precisely identify - // system-generated events. - setSystemGenerated(event); - PostEventQueue postEventQueue = - (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY); - if (postEventQueue != null) { - postEventQueue.postEvent(event); - } - } - - /* - * Post AWTEvent of high priority. - */ - public static void postPriorityEvent(final AWTEvent e) { - PeerEvent pe = new PeerEvent(Toolkit.getDefaultToolkit(), new Runnable() { - public void run() { - AWTAccessor.getAWTEventAccessor().setPosted(e); - ((Component)e.getSource()).dispatchEvent(e); - } - }, PeerEvent.ULTIMATE_PRIORITY_EVENT); - postEvent(targetToAppContext(e.getSource()), pe); - } - - protected static final Lock flushLock = new ReentrantLock(); - private static boolean isFlushingPendingEvents = false; - - /* - * Flush any pending events which haven't been posted to the AWT - * EventQueue yet. - */ - public static void flushPendingEvents() { - AppContext appContext = AppContext.getAppContext(); - flushPendingEvents(appContext); - } - - public static void flushPendingEvents(AppContext appContext) { - flushLock.lock(); - try { - // Don't call flushPendingEvents() recursively - if (!isFlushingPendingEvents) { - isFlushingPendingEvents = true; - try { - PostEventQueue postEventQueue = - (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY); - if (postEventQueue != null) { - postEventQueue.flush(); - } - } - finally { - isFlushingPendingEvents = false; - } - } - } finally { - flushLock.unlock(); - } - } - - public static boolean isPostEventQueueEmpty() { - AppContext appContext = AppContext.getAppContext(); - PostEventQueue postEventQueue = - (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY); - if (postEventQueue != null) { - return postEventQueue.noEvents(); - } else { - return true; - } - } - - /* - * Execute a chunk of code on the Java event handler thread for the - * given target. Does not wait for the execution to occur before - * returning to the caller. - */ - public static void executeOnEventHandlerThread(Object target, - Runnable runnable) { - executeOnEventHandlerThread(new PeerEvent(target, runnable, PeerEvent.PRIORITY_EVENT)); - } - - /* - * Fixed 5064013: the InvocationEvent time should be equals - * the time of the ActionEvent - */ - public static void executeOnEventHandlerThread(Object target, - Runnable runnable, - final long when) { - executeOnEventHandlerThread(new PeerEvent(target, runnable, PeerEvent.PRIORITY_EVENT){ - public long getWhen(){ - return when; - } - }); - } - - /* - * Execute a chunk of code on the Java event handler thread for the - * given target. Does not wait for the execution to occur before - * returning to the caller. - */ - public static void executeOnEventHandlerThread(PeerEvent peerEvent) { - postEvent(targetToAppContext(peerEvent.getSource()), peerEvent); - } - - /* - * Execute a chunk of code on the Java event handler thread. The - * method takes into account provided AppContext and sets - * <code>SunToolkit.getDefaultToolkit()</code> as a target of the - * event. See 6451487 for detailes. - * Does not wait for the execution to occur before returning to - * the caller. - */ - public static void invokeLaterOnAppContext( - AppContext appContext, Runnable dispatcher) - { - postEvent(appContext, - new PeerEvent(Toolkit.getDefaultToolkit(), dispatcher, - PeerEvent.PRIORITY_EVENT)); - } - - /* - * Execute a chunk of code on the Java event handler thread for the - * given target. Waits for the execution to occur before returning - * to the caller. - */ - public static void executeOnEDTAndWait(Object target, Runnable runnable) - throws InterruptedException, InvocationTargetException - { - if (EventQueue.isDispatchThread()) { - throw new Error("Cannot call executeOnEDTAndWait from any event dispatcher thread"); - } - - class AWTInvocationLock {} - Object lock = new AWTInvocationLock(); - - PeerEvent event = new PeerEvent(target, runnable, lock, true, PeerEvent.PRIORITY_EVENT); - - synchronized (lock) { - executeOnEventHandlerThread(event); - while(!event.isDispatched()) { - lock.wait(); - } - } - - Throwable eventThrowable = event.getThrowable(); - if (eventThrowable != null) { - throw new InvocationTargetException(eventThrowable); - } - } - - /* - * Returns true if the calling thread is the event dispatch thread - * contained within AppContext which associated with the given target. - * Use this call to ensure that a given task is being executed - * (or not being) on the event dispatch thread for the given target. - */ - public static boolean isDispatchThreadForAppContext(Object target) { - AppContext appContext = targetToAppContext(target); - EventQueue eq = (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); - - AWTAccessor.EventQueueAccessor accessor = AWTAccessor.getEventQueueAccessor(); - return accessor.isDispatchThreadImpl(eq); - } - - public Dimension getScreenSize() { - return new Dimension(getScreenWidth(), getScreenHeight()); - } - protected abstract int getScreenWidth(); - protected abstract int getScreenHeight(); - - public String[] getFontList() { - String[] hardwiredFontList = { - Font.DIALOG, Font.SANS_SERIF, Font.SERIF, Font.MONOSPACED, - Font.DIALOG_INPUT - - // -- Obsolete font names from 1.0.2. It was decided that - // -- getFontList should not return these old names: - // "Helvetica", "TimesRoman", "Courier", "ZapfDingbats" - }; - return hardwiredFontList; - } - - public PanelPeer createPanel(Panel target) { - return (PanelPeer)createComponent(target); - } - - public CanvasPeer createCanvas(Canvas target) { - return (CanvasPeer)createComponent(target); - } - - /** - * Disables erasing of background on the canvas before painting if - * this is supported by the current toolkit. It is recommended to - * call this method early, before the Canvas becomes displayable, - * because some Toolkit implementations do not support changing - * this property once the Canvas becomes displayable. - */ - public void disableBackgroundErase(Canvas canvas) { - disableBackgroundEraseImpl(canvas); - } - - /** - * Disables the native erasing of the background on the given - * component before painting if this is supported by the current - * toolkit. This only has an effect for certain components such as - * Canvas, Panel and Window. It is recommended to call this method - * early, before the Component becomes displayable, because some - * Toolkit implementations do not support changing this property - * once the Component becomes displayable. - */ - public void disableBackgroundErase(Component component) { - disableBackgroundEraseImpl(component); - } - - private void disableBackgroundEraseImpl(Component component) { - AWTAccessor.getComponentAccessor().setBackgroundEraseDisabled(component, true); - } - - /** - * Returns the value of "sun.awt.noerasebackground" property. Default - * value is {@code false}. - */ - public static boolean getSunAwtNoerasebackground() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.noerasebackground")); - } - - /** - * Returns the value of "sun.awt.erasebackgroundonresize" property. Default - * value is {@code false}. - */ - public static boolean getSunAwtErasebackgroundonresize() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.erasebackgroundonresize")); - } - - public Image createImage(ImageProducer producer) { - return new ToolkitImage(producer); - } - - public int checkImage(Image img, int w, int h, ImageObserver o) { - if (!(img instanceof ToolkitImage)) { - return ImageObserver.ALLBITS; - } - - ToolkitImage tkimg = (ToolkitImage)img; - int repbits; - if (w == 0 || h == 0) { - repbits = ImageObserver.ALLBITS; - } else { - repbits = tkimg.getImageRep().check(o); - } - return tkimg.check(o) | repbits; - } - - public boolean prepareImage(Image img, int w, int h, ImageObserver o) { - if (w == 0 || h == 0) { - return true; - } - - // Must be a ToolkitImage - if (!(img instanceof ToolkitImage)) { - return true; - } - - ToolkitImage tkimg = (ToolkitImage)img; - if (tkimg.hasError()) { - if (o != null) { - o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT, - -1, -1, -1, -1); - } - return false; - } - ImageRepresentation ir = tkimg.getImageRep(); - return ir.prepare(o); - } - - /** - * Scans {@code imageList} for best-looking image of specified dimensions. - * Image can be scaled and/or padded with transparency. - */ - public static BufferedImage getScaledIconImage(java.util.List<Image> imageList, int width, int height) { - if (width == 0 || height == 0) { - return null; - } - Image bestImage = null; - int bestWidth = 0; - int bestHeight = 0; - double bestSimilarity = 3; //Impossibly high value - double bestScaleFactor = 0; - for (Iterator<Image> i = imageList.iterator();i.hasNext();) { - //Iterate imageList looking for best matching image. - //'Similarity' measure is defined as good scale factor and small insets. - //best possible similarity is 0 (no scale, no insets). - //It's found while the experiments that good-looking result is achieved - //with scale factors x1, x3/4, x2/3, xN, x1/N. - Image im = i.next(); - if (im == null) { - continue; - } - if (im instanceof ToolkitImage) { - ImageRepresentation ir = ((ToolkitImage)im).getImageRep(); - ir.reconstruct(ImageObserver.ALLBITS); - } - int iw; - int ih; - try { - iw = im.getWidth(null); - ih = im.getHeight(null); - } catch (Exception e){ - continue; - } - if (iw > 0 && ih > 0) { - //Calc scale factor - double scaleFactor = Math.min((double)width / (double)iw, - (double)height / (double)ih); - //Calculate scaled image dimensions - //adjusting scale factor to nearest "good" value - int adjw = 0; - int adjh = 0; - double scaleMeasure = 1; //0 - best (no) scale, 1 - impossibly bad - if (scaleFactor >= 2) { - //Need to enlarge image more than twice - //Round down scale factor to multiply by integer value - scaleFactor = Math.floor(scaleFactor); - adjw = iw * (int)scaleFactor; - adjh = ih * (int)scaleFactor; - scaleMeasure = 1.0 - 0.5 / scaleFactor; - } else if (scaleFactor >= 1) { - //Don't scale - scaleFactor = 1.0; - adjw = iw; - adjh = ih; - scaleMeasure = 0; - } else if (scaleFactor >= 0.75) { - //Multiply by 3/4 - scaleFactor = 0.75; - adjw = iw * 3 / 4; - adjh = ih * 3 / 4; - scaleMeasure = 0.3; - } else if (scaleFactor >= 0.6666) { - //Multiply by 2/3 - scaleFactor = 0.6666; - adjw = iw * 2 / 3; - adjh = ih * 2 / 3; - scaleMeasure = 0.33; - } else { - //Multiply size by 1/scaleDivider - //where scaleDivider is minimum possible integer - //larger than 1/scaleFactor - double scaleDivider = Math.ceil(1.0 / scaleFactor); - scaleFactor = 1.0 / scaleDivider; - adjw = (int)Math.round((double)iw / scaleDivider); - adjh = (int)Math.round((double)ih / scaleDivider); - scaleMeasure = 1.0 - 1.0 / scaleDivider; - } - double similarity = ((double)width - (double)adjw) / (double)width + - ((double)height - (double)adjh) / (double)height + //Large padding is bad - scaleMeasure; //Large rescale is bad - if (similarity < bestSimilarity) { - bestSimilarity = similarity; - bestScaleFactor = scaleFactor; - bestImage = im; - bestWidth = adjw; - bestHeight = adjh; - } - if (similarity == 0) break; - } - } - if (bestImage == null) { - //No images were found, possibly all are broken - return null; - } - BufferedImage bimage = - new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = bimage.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - try { - int x = (width - bestWidth) / 2; - int y = (height - bestHeight) / 2; - g.drawImage(bestImage, x, y, bestWidth, bestHeight, null); - } finally { - g.dispose(); - } - return bimage; - } - - public static DataBufferInt getScaledIconData(java.util.List<Image> imageList, int width, int height) { - BufferedImage bimage = getScaledIconImage(imageList, width, height); - if (bimage == null) { - return null; - } - Raster raster = bimage.getRaster(); - DataBuffer buffer = raster.getDataBuffer(); - return (DataBufferInt)buffer; - } - - protected EventQueue getSystemEventQueueImpl() { - return getSystemEventQueueImplPP(); - } - - // Package private implementation - static EventQueue getSystemEventQueueImplPP() { - return getSystemEventQueueImplPP(AppContext.getAppContext()); - } - - public static EventQueue getSystemEventQueueImplPP(AppContext appContext) { - EventQueue theEventQueue = - (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); - return theEventQueue; - } - - /** - * Give native peers the ability to query the native container - * given a native component (eg the direct parent may be lightweight). - */ - public static Container getNativeContainer(Component c) { - return Toolkit.getNativeContainer(c); - } - - /** - * Gives native peers the ability to query the closest HW component. - * If the given component is heavyweight, then it returns this. Otherwise, - * it goes one level up in the hierarchy and tests next component. - */ - public static Component getHeavyweightComponent(Component c) { - while (c != null && AWTAccessor.getComponentAccessor().isLightweight(c)) { - c = AWTAccessor.getComponentAccessor().getParent(c); - } - return c; - } - - /** - * Returns key modifiers used by Swing to set up a focus accelerator key stroke. - */ - public int getFocusAcceleratorKeyMask() { - return InputEvent.ALT_MASK; - } - - /** - * Tests whether specified key modifiers mask can be used to enter a printable - * character. This is a default implementation of this method, which reflects - * the way things work on Windows: here, pressing ctrl + alt allows user to enter - * characters from the extended character set (like euro sign or math symbols) - */ - public boolean isPrintableCharacterModifiersMask(int mods) { - return ((mods & InputEvent.ALT_MASK) == (mods & InputEvent.CTRL_MASK)); - } - - /** - * Returns whether popup is allowed to be shown above the task bar. - * This is a default implementation of this method, which checks - * corresponding security permission. - */ - public boolean canPopupOverlapTaskBar() { - boolean result = true; - try { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission( - SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); - } - } catch (SecurityException se) { - // There is no permission to show popups over the task bar - result = false; - } - return result; - } - - /** - * Returns whether enableInputMethods should be set to true for peered - * TextComponent instances on this platform. False by default. - */ - public boolean enableInputMethodsForTextComponent() { - return false; - } - - private static Locale startupLocale = null; - - /** - * Returns the locale in which the runtime was started. - */ - public static Locale getStartupLocale() { - if (startupLocale == null) { - String language, region, country, variant; - language = (String) AccessController.doPrivileged( - new GetPropertyAction("user.language", "en")); - // for compatibility, check for old user.region property - region = (String) AccessController.doPrivileged( - new GetPropertyAction("user.region")); - if (region != null) { - // region can be of form country, country_variant, or _variant - int i = region.indexOf('_'); - if (i >= 0) { - country = region.substring(0, i); - variant = region.substring(i + 1); - } else { - country = region; - variant = ""; - } - } else { - country = (String) AccessController.doPrivileged( - new GetPropertyAction("user.country", "")); - variant = (String) AccessController.doPrivileged( - new GetPropertyAction("user.variant", "")); - } - startupLocale = new Locale(language, country, variant); - } - return startupLocale; - } - - /** - * Returns the default keyboard locale of the underlying operating system - */ - public Locale getDefaultKeyboardLocale() { - return getStartupLocale(); - } - - private static String dataTransfererClassName = null; - - protected static void setDataTransfererClassName(String className) { - dataTransfererClassName = className; - } - - public static String getDataTransfererClassName() { - if (dataTransfererClassName == null) { - Toolkit.getDefaultToolkit(); // transferer set during toolkit init - } - return dataTransfererClassName; - } - - // Support for window closing event notifications - private transient WindowClosingListener windowClosingListener = null; - /** - * @see sun.awt.WindowClosingSupport#getWindowClosingListener - */ - public WindowClosingListener getWindowClosingListener() { - return windowClosingListener; - } - /** - * @see sun.awt.WindowClosingSupport#setWindowClosingListener - */ - public void setWindowClosingListener(WindowClosingListener wcl) { - windowClosingListener = wcl; - } - - /** - * @see sun.awt.WindowClosingListener#windowClosingNotify - */ - public RuntimeException windowClosingNotify(WindowEvent event) { - if (windowClosingListener != null) { - return windowClosingListener.windowClosingNotify(event); - } else { - return null; - } - } - /** - * @see sun.awt.WindowClosingListener#windowClosingDelivered - */ - public RuntimeException windowClosingDelivered(WindowEvent event) { - if (windowClosingListener != null) { - return windowClosingListener.windowClosingDelivered(event); - } else { - return null; - } - } - - - - /** - * Returns whether default toolkit needs the support of the xembed - * from embedding host(if any). - * @return <code>true</code>, if XEmbed is needed, <code>false</code> otherwise - */ - public static boolean needsXEmbed() { - String noxembed = (String) AccessController. - doPrivileged(new GetPropertyAction("sun.awt.noxembed", "false")); - if ("true".equals(noxembed)) { - return false; - } - - Toolkit tk = Toolkit.getDefaultToolkit(); - if (tk instanceof SunToolkit) { - // SunToolkit descendants should override this method to specify - // concrete behavior - return ((SunToolkit)tk).needsXEmbedImpl(); - } else { - // Non-SunToolkit doubtly might support XEmbed - return false; - } - } - - /** - * Returns whether this toolkit needs the support of the xembed - * from embedding host(if any). - * @return <code>true</code>, if XEmbed is needed, <code>false</code> otherwise - */ - protected boolean needsXEmbedImpl() { - return false; - } - - private static Dialog.ModalExclusionType DEFAULT_MODAL_EXCLUSION_TYPE = null; - - /** - * Returns whether the XEmbed server feature is requested by - * developer. If true, Toolkit should return an - * XEmbed-server-enabled CanvasPeer instead of the ordinary CanvasPeer. - */ - protected final boolean isXEmbedServerRequested() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembedserver")); - } - - /** - * Returns whether the modal exclusion API is supported by the current toolkit. - * When it isn't supported, calling <code>setModalExcluded</code> has no - * effect, and <code>isModalExcluded</code> returns false for all windows. - * - * @return true if modal exclusion is supported by the toolkit, false otherwise - * - * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window) - * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window) - * - * @since 1.5 - */ - public static boolean isModalExcludedSupported() - { - Toolkit tk = Toolkit.getDefaultToolkit(); - return tk.isModalExclusionTypeSupported(DEFAULT_MODAL_EXCLUSION_TYPE); - } - /* - * Default implementation for isModalExcludedSupportedImpl(), returns false. - * - * @see sun.awt.windows.WToolkit#isModalExcludeSupportedImpl - * @see sun.awt.X11.XToolkit#isModalExcludeSupportedImpl - * - * @since 1.5 - */ - protected boolean isModalExcludedSupportedImpl() - { - return false; - } - - /* - * Sets this window to be excluded from being modally blocked. When the - * toolkit supports modal exclusion and this method is called, input - * events, focus transfer and z-order will continue to work for the - * window, it's owned windows and child components, even in the - * presence of a modal dialog. - * For details on which <code>Window</code>s are normally blocked - * by modal dialog, see {@link java.awt.Dialog}. - * Invoking this method when the modal exclusion API is not supported by - * the current toolkit has no effect. - * @param window Window to be marked as not modally blocked - * @see java.awt.Dialog - * @see java.awt.Dialog#setModal(boolean) - * @see sun.awt.SunToolkit#isModalExcludedSupported - * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window) - */ - public static void setModalExcluded(Window window) - { - if (DEFAULT_MODAL_EXCLUSION_TYPE == null) { - DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE; - } - window.setModalExclusionType(DEFAULT_MODAL_EXCLUSION_TYPE); - } - - /* - * Returns whether the specified window is blocked by modal dialogs. - * If the modal exclusion API isn't supported by the current toolkit, - * it returns false for all windows. - * - * @param window Window to test for modal exclusion - * - * @return true if the window is modal excluded, false otherwise. If - * the modal exclusion isn't supported by the current Toolkit, false - * is returned - * - * @see sun.awt.SunToolkit#isModalExcludedSupported - * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window) - * - * @since 1.5 - */ - public static boolean isModalExcluded(Window window) - { - if (DEFAULT_MODAL_EXCLUSION_TYPE == null) { - DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE; - } - return window.getModalExclusionType().compareTo(DEFAULT_MODAL_EXCLUSION_TYPE) >= 0; - } - - /** - * Overridden in XToolkit and WToolkit - */ - public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { - return (modalityType == Dialog.ModalityType.MODELESS) || - (modalityType == Dialog.ModalityType.APPLICATION_MODAL); - } - - /** - * Overridden in XToolkit and WToolkit - */ - public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) { - return (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE); - } - - /////////////////////////////////////////////////////////////////////////// - // - // The following is used by the Java Plug-in to coordinate dialog modality - // between containing applications (browsers, ActiveX containers etc) and - // the AWT. - // - /////////////////////////////////////////////////////////////////////////// - - private ModalityListenerList modalityListeners = new ModalityListenerList(); - - public void addModalityListener(ModalityListener listener) { - modalityListeners.add(listener); - } - - public void removeModalityListener(ModalityListener listener) { - modalityListeners.remove(listener); - } - - public void notifyModalityPushed(Dialog dialog) { - notifyModalityChange(ModalityEvent.MODALITY_PUSHED, dialog); - } - - public void notifyModalityPopped(Dialog dialog) { - notifyModalityChange(ModalityEvent.MODALITY_POPPED, dialog); - } - - final void notifyModalityChange(int id, Dialog source) { - ModalityEvent ev = new ModalityEvent(source, modalityListeners, id); - ev.dispatch(); - } - - static class ModalityListenerList implements ModalityListener { - - Vector<ModalityListener> listeners = new Vector<ModalityListener>(); - - void add(ModalityListener listener) { - listeners.addElement(listener); - } - - void remove(ModalityListener listener) { - listeners.removeElement(listener); - } - - public void modalityPushed(ModalityEvent ev) { - Iterator<ModalityListener> it = listeners.iterator(); - while (it.hasNext()) { - it.next().modalityPushed(ev); - } - } - - public void modalityPopped(ModalityEvent ev) { - Iterator<ModalityListener> it = listeners.iterator(); - while (it.hasNext()) { - it.next().modalityPopped(ev); - } - } - } // end of class ModalityListenerList - - /////////////////////////////////////////////////////////////////////////// - // End Plug-in code - /////////////////////////////////////////////////////////////////////////// - - public static boolean isLightweightOrUnknown(Component comp) { - if (comp.isLightweight() - || !(getDefaultToolkit() instanceof SunToolkit)) - { - return true; - } - return !(comp instanceof Button - || comp instanceof Canvas - || comp instanceof Checkbox - || comp instanceof Choice - || comp instanceof Label - || comp instanceof java.awt.List - || comp instanceof Panel - || comp instanceof Scrollbar - || comp instanceof ScrollPane - || comp instanceof TextArea - || comp instanceof TextField - || comp instanceof Window); - } - - public static Method getMethod(final Class clz, final String methodName, final Class[] params) { - Method res = null; - try { - res = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { - public Method run() throws Exception { - Method m = clz.getDeclaredMethod(methodName, params); - m.setAccessible(true); - return m; - } - }); - } catch (PrivilegedActionException ex) { - ex.printStackTrace(); - } - return res; - } - - public static class OperationTimedOut extends RuntimeException { - public OperationTimedOut(String msg) { - super(msg); - } - public OperationTimedOut() { - } - } - public static class InfiniteLoop extends RuntimeException { - } - - public static class IllegalThreadException extends RuntimeException { - public IllegalThreadException(String msg) { - super(msg); - } - public IllegalThreadException() { - } - } - - public static final int DEFAULT_WAIT_TIME = 10000; - private static final int MAX_ITERS = 20; - private static final int MIN_ITERS = 0; - private static final int MINIMAL_EDELAY = 0; - - /** - * Parameterless version of realsync which uses default timout (see DEFAUL_WAIT_TIME). - */ - public void realSync() throws OperationTimedOut, InfiniteLoop { - realSync(DEFAULT_WAIT_TIME); - } - - /** - * Forces toolkit to synchronize with the native windowing - * sub-system, flushing all pending work and waiting for all the - * events to be processed. This method guarantees that after - * return no additional Java events will be generated, unless - * cause by user. Obviously, the method cannot be used on the - * event dispatch thread (EDT). In case it nevertheless gets - * invoked on this thread, the method throws the - * IllegalThreadException runtime exception. - * - * <p> This method allows to write tests without explicit timeouts - * or wait for some event. Example: - * <code> - * Frame f = ...; - * f.setVisible(true); - * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); - * </code> - * - * <p> After realSync, <code>f</code> will be completely visible - * on the screen, its getLocationOnScreen will be returning the - * right result and it will be the focus owner. - * - * <p> Another example: - * <code> - * b.requestFocus(); - * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); - * </code> - * - * <p> After realSync, <code>b</code> will be focus owner. - * - * <p> Notice that realSync isn't guaranteed to work if recurring - * actions occur, such as if during processing of some event - * another request which may generate some events occurs. By - * default, sync tries to perform as much as {@value MAX_ITERS} - * cycles of event processing, allowing for roughly {@value - * MAX_ITERS} additional requests. - * - * <p> For example, requestFocus() generates native request, which - * generates one or two Java focus events, which then generate a - * serie of paint events, a serie of Java focus events, which then - * generate a serie of paint events which then are processed - - * three cycles, minimum. - * - * @param timeout the maximum time to wait in milliseconds, negative means "forever". - */ - public void realSync(final long timeout) throws OperationTimedOut, InfiniteLoop - { - if (EventQueue.isDispatchThread()) { - throw new IllegalThreadException("The SunToolkit.realSync() method cannot be used on the event dispatch thread (EDT)."); - } - int bigLoop = 0; - do { - // Let's do sync first - sync(); - - // During the wait process, when we were processing incoming - // events, we could have made some new request, which can - // generate new events. Example: MapNotify/XSetInputFocus. - // Therefore, we dispatch them as long as there is something - // to dispatch. - int iters = 0; - while (iters < MIN_ITERS) { - syncNativeQueue(timeout); - iters++; - } - while (syncNativeQueue(timeout) && iters < MAX_ITERS) { - iters++; - } - if (iters >= MAX_ITERS) { - throw new InfiniteLoop(); - } - - // native requests were dispatched by X/Window Manager or Windows - // Moreover, we processed them all on Toolkit thread - // Now wait while EDT processes them. - // - // During processing of some events (focus, for example), - // some other events could have been generated. So, after - // waitForIdle, we may end up with full EventQueue - iters = 0; - while (iters < MIN_ITERS) { - waitForIdle(timeout); - iters++; - } - while (waitForIdle(timeout) && iters < MAX_ITERS) { - iters++; - } - if (iters >= MAX_ITERS) { - throw new InfiniteLoop(); - } - - bigLoop++; - // Again, for Java events, it was simple to check for new Java - // events by checking event queue, but what if Java events - // resulted in native requests? Therefor, check native events again. - } while ((syncNativeQueue(timeout) || waitForIdle(timeout)) && bigLoop < MAX_ITERS); - } - - /** - * Platform toolkits need to implement this method to perform the - * sync of the native queue. The method should wait until native - * requests are processed, all native events are processed and - * corresponding Java events are generated. Should return - * <code>true</code> if some events were processed, - * <code>false</code> otherwise. - */ - protected abstract boolean syncNativeQueue(final long timeout); - - private boolean eventDispatched = false; - private boolean queueEmpty = false; - private final Object waitLock = "Wait Lock"; - - static Method eqNoEvents; - - private boolean isEQEmpty() { - EventQueue queue = getSystemEventQueueImpl(); - synchronized(SunToolkit.class) { - if (eqNoEvents == null) { - eqNoEvents = getMethod(java.awt.EventQueue.class, "noEvents", null); - } - } - try { - return (Boolean)eqNoEvents.invoke(queue); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * Waits for the Java event queue to empty. Ensures that all - * events are processed (including paint events), and that if - * recursive events were generated, they are also processed. - * Should return <code>true</code> if more processing is - * necessary, <code>false</code> otherwise. - */ - protected final boolean waitForIdle(final long timeout) { - flushPendingEvents(); - boolean queueWasEmpty = isEQEmpty(); - queueEmpty = false; - eventDispatched = false; - synchronized(waitLock) { - postEvent(AppContext.getAppContext(), - new PeerEvent(getSystemEventQueueImpl(), null, PeerEvent.LOW_PRIORITY_EVENT) { - public void dispatch() { - // Here we block EDT. It could have some - // events, it should have dispatched them by - // now. So native requests could have been - // generated. First, dispatch them. Then, - // flush Java events again. - int iters = 0; - while (iters < MIN_ITERS) { - syncNativeQueue(timeout); - iters++; - } - while (syncNativeQueue(timeout) && iters < MAX_ITERS) { - iters++; - } - flushPendingEvents(); - - synchronized(waitLock) { - queueEmpty = isEQEmpty(); - eventDispatched = true; - waitLock.notifyAll(); - } - } - }); - try { - while (!eventDispatched) { - waitLock.wait(); - } - } catch (InterruptedException ie) { - return false; - } - } - - try { - Thread.sleep(MINIMAL_EDELAY); - } catch (InterruptedException ie) { - throw new RuntimeException("Interrupted"); - } - - flushPendingEvents(); - - // Lock to force write-cache flush for queueEmpty. - synchronized (waitLock) { - return !(queueEmpty && isEQEmpty() && queueWasEmpty); - } - } - - /** - * Grabs the mouse input for the given window. The window must be - * visible. The window or its children do not receive any - * additional mouse events besides those targeted to them. All - * other events will be dispatched as before - to the respective - * targets. This Window will receive UngrabEvent when automatic - * ungrab is about to happen. The event can be listened to by - * installing AWTEventListener with WINDOW_EVENT_MASK. See - * UngrabEvent class for the list of conditions when ungrab is - * about to happen. - * @see UngrabEvent - */ - public abstract void grab(Window w); - - /** - * Forces ungrab. No event will be sent. - */ - public abstract void ungrab(Window w); - - - /** - * Locates the splash screen library in a platform dependent way and closes - * the splash screen. Should be invoked on first top-level frame display. - * @see java.awt.SplashScreen - * @since 1.6 - */ - public static native void closeSplashScreen(); - - /* The following methods and variables are to support retrieving - * desktop text anti-aliasing settings - */ - - /* Need an instance method because setDesktopProperty(..) is protected. */ - private void fireDesktopFontPropertyChanges() { - setDesktopProperty(SunToolkit.DESKTOPFONTHINTS, - SunToolkit.getDesktopFontHints()); - } - - private static boolean checkedSystemAAFontSettings; - private static boolean useSystemAAFontSettings; - private static boolean lastExtraCondition = true; - private static RenderingHints desktopFontHints; - - /* Since Swing is the reason for this "extra condition" logic its - * worth documenting it in some detail. - * First, a goal is for Swing and applications to both retrieve and - * use the same desktop property value so that there is complete - * consistency between the settings used by JDK's Swing implementation - * and 3rd party custom Swing components, custom L&Fs and any general - * text rendering that wants to be consistent with these. - * But by default on Solaris & Linux Swing will not use AA text over - * remote X11 display (unless Xrender can be used which is TBD and may not - * always be available anyway) as that is a noticeable performance hit. - * So there needs to be a way to express that extra condition so that - * it is seen by all clients of the desktop property API. - * If this were the only condition it could be handled here as it would - * be the same for any L&F and could reasonably be considered to be - * a static behaviour of those systems. - * But GTK currently has an additional test based on locale which is - * not applied by Metal. So mixing GTK in a few locales with Metal - * would mean the last one wins. - * This could be stored per-app context which would work - * for different applets, but wouldn't help for a single application - * using GTK and some other L&F concurrently. - * But it is expected this will be addressed within GTK and the font - * system so is a temporary and somewhat unlikely harmless corner case. - */ - public static void setAAFontSettingsCondition(boolean extraCondition) { - if (extraCondition != lastExtraCondition) { - lastExtraCondition = extraCondition; - if (checkedSystemAAFontSettings) { - /* Someone already asked for this info, under a different - * condition. - * We'll force re-evaluation instead of replicating the - * logic, then notify any listeners of any change. - */ - checkedSystemAAFontSettings = false; - Toolkit tk = Toolkit.getDefaultToolkit(); - if (tk instanceof SunToolkit) { - ((SunToolkit)tk).fireDesktopFontPropertyChanges(); - } - } - } - } - - /* "false", "off", ""default" aren't explicitly tested, they - * just fall through to produce a null return which all are equated to - * "false". - */ - private static RenderingHints getDesktopAAHintsByName(String hintname) { - Object aaHint = null; - hintname = hintname.toLowerCase(Locale.ENGLISH); - if (hintname.equals("on")) { - aaHint = VALUE_TEXT_ANTIALIAS_ON; - } else if (hintname.equals("gasp")) { - aaHint = VALUE_TEXT_ANTIALIAS_GASP; - } else if (hintname.equals("lcd") || hintname.equals("lcd_hrgb")) { - aaHint = VALUE_TEXT_ANTIALIAS_LCD_HRGB; - } else if (hintname.equals("lcd_hbgr")) { - aaHint = VALUE_TEXT_ANTIALIAS_LCD_HBGR; - } else if (hintname.equals("lcd_vrgb")) { - aaHint = VALUE_TEXT_ANTIALIAS_LCD_VRGB; - } else if (hintname.equals("lcd_vbgr")) { - aaHint = VALUE_TEXT_ANTIALIAS_LCD_VBGR; - } - if (aaHint != null) { - RenderingHints map = new RenderingHints(null); - map.put(KEY_TEXT_ANTIALIASING, aaHint); - return map; - } else { - return null; - } - } - - /* This method determines whether to use the system font settings, - * or ignore them if a L&F has specified they should be ignored, or - * to override both of these with a system property specified value. - * If the toolkit isn't a SunToolkit, (eg may be headless) then that - * system property isn't applied as desktop properties are considered - * to be inapplicable in that case. In that headless case although - * this method will return "true" the toolkit will return a null map. - */ - private static boolean useSystemAAFontSettings() { - if (!checkedSystemAAFontSettings) { - useSystemAAFontSettings = true; /* initially set this true */ - String systemAAFonts = null; - Toolkit tk = Toolkit.getDefaultToolkit(); - if (tk instanceof SunToolkit) { - systemAAFonts = - (String)AccessController.doPrivileged( - new GetPropertyAction("awt.useSystemAAFontSettings")); - } - if (systemAAFonts != null) { - useSystemAAFontSettings = - Boolean.valueOf(systemAAFonts).booleanValue(); - /* If it is anything other than "true", then it may be - * a hint name , or it may be "off, "default", etc. - */ - if (!useSystemAAFontSettings) { - desktopFontHints = getDesktopAAHintsByName(systemAAFonts); - } - } - /* If its still true, apply the extra condition */ - if (useSystemAAFontSettings) { - useSystemAAFontSettings = lastExtraCondition; - } - checkedSystemAAFontSettings = true; - } - return useSystemAAFontSettings; - } - - /* A variable defined for the convenience of JDK code */ - public static final String DESKTOPFONTHINTS = "awt.font.desktophints"; - - /* Overridden by subclasses to return platform/desktop specific values */ - protected RenderingHints getDesktopAAHints() { - return null; - } - - /* Subclass desktop property loading methods call this which - * in turn calls the appropriate subclass implementation of - * getDesktopAAHints() when system settings are being used. - * Its public rather than protected because subclasses may delegate - * to a helper class. - */ - public static RenderingHints getDesktopFontHints() { - if (useSystemAAFontSettings()) { - Toolkit tk = Toolkit.getDefaultToolkit(); - if (tk instanceof SunToolkit) { - Object map = ((SunToolkit)tk).getDesktopAAHints(); - return (RenderingHints)map; - } else { /* Headless Toolkit */ - return null; - } - } else if (desktopFontHints != null) { - /* cloning not necessary as the return value is cloned later, but - * its harmless. - */ - return (RenderingHints)(desktopFontHints.clone()); - } else { - return null; - } - } - - - public abstract boolean isDesktopSupported(); - - /* - * consumeNextKeyTyped() method is not currently used, - * however Swing could use it in the future. - */ - private static Method consumeNextKeyTypedMethod = null; - public static synchronized void consumeNextKeyTyped(KeyEvent keyEvent) { - if (consumeNextKeyTypedMethod == null) { - consumeNextKeyTypedMethod = getMethod(DefaultKeyboardFocusManager.class, - "consumeNextKeyTyped", - new Class[] {KeyEvent.class}); - } - try { - consumeNextKeyTypedMethod.invoke(KeyboardFocusManager.getCurrentKeyboardFocusManager(), - keyEvent); - } catch (IllegalAccessException iae) { - iae.printStackTrace(); - } catch (InvocationTargetException ite) { - ite.printStackTrace(); - } - } - - protected static void dumpPeers(final PlatformLogger aLog) { - AWTAutoShutdown.getInstance().dumpPeers(aLog); - } - - /** - * Returns the <code>Window</code> ancestor of the component <code>comp</code>. - * @return Window ancestor of the component or component by itself if it is Window; - * null, if component is not a part of window hierarchy - */ - public static Window getContainingWindow(Component comp) { - while (comp != null && !(comp instanceof Window)) { - comp = comp.getParent(); - } - return (Window)comp; - } - - private static Boolean sunAwtDisableMixing = null; - - /** - * Returns the value of "sun.awt.disableMixing" property. Default - * value is {@code false}. - */ - public synchronized static boolean getSunAwtDisableMixing() { - if (sunAwtDisableMixing == null) { - sunAwtDisableMixing = AccessController.doPrivileged( - new GetBooleanAction("sun.awt.disableMixing")); - } - return sunAwtDisableMixing.booleanValue(); - } - - /** - * Returns true if the native GTK libraries are available. The - * default implementation returns false, but UNIXToolkit overrides this - * method to provide a more specific answer. - */ - public boolean isNativeGTKAvailable() { - return false; - } - - private static final Object DEACTIVATION_TIMES_MAP_KEY = new Object(); - - public synchronized void setWindowDeactivationTime(Window w, long time) { - AppContext ctx = getAppContext(w); - WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY); - if (map == null) { - map = new WeakHashMap<Window, Long>(); - ctx.put(DEACTIVATION_TIMES_MAP_KEY, map); - } - map.put(w, time); - } - - public synchronized long getWindowDeactivationTime(Window w) { - AppContext ctx = getAppContext(w); - WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY); - if (map == null) { - return -1; - } - Long time = map.get(w); - return time == null ? -1 : time; - } - - // Cosntant alpha - public boolean isWindowOpacitySupported() { - return false; - } - - // Shaping - public boolean isWindowShapingSupported() { - return false; - } - - // Per-pixel alpha - public boolean isWindowTranslucencySupported() { - return false; - } - - public boolean isTranslucencyCapable(GraphicsConfiguration gc) { - return false; - } - - /** - * Returns true if swing backbuffer should be translucent. - */ - public boolean isSwingBackbufferTranslucencySupported() { - return false; - } - - /** - * Returns whether or not a containing top level window for the passed - * component is - * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}. - * - * @param c a Component which toplevel's to check - * @return {@code true} if the passed component is not null and has a - * containing toplevel window which is opaque (so per-pixel translucency - * is not enabled), {@code false} otherwise - * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT - */ - public static boolean isContainingTopLevelOpaque(Component c) { - Window w = getContainingWindow(c); - return w != null && w.isOpaque(); - } - - /** - * Returns whether or not a containing top level window for the passed - * component is - * {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}. - * - * @param c a Component which toplevel's to check - * @return {@code true} if the passed component is not null and has a - * containing toplevel window which has opacity less than - * 1.0f (which means that it is translucent), {@code false} otherwise - * @see GraphicsDevice.WindowTranslucency#TRANSLUCENT - */ - public static boolean isContainingTopLevelTranslucent(Component c) { - Window w = getContainingWindow(c); - return w != null && ((Window)w).getOpacity() < 1.0f; - } - - /** - * Returns whether the native system requires using the peer.updateWindow() - * method to update the contents of a non-opaque window, or if usual - * painting procedures are sufficient. The default return value covers - * the X11 systems. On MS Windows this method is overriden in WToolkit - * to return true. - */ - public boolean needUpdateWindow() { - return false; - } - - /** - * Descendants of the SunToolkit should override and put their own logic here. - */ - public int getNumberOfButtons(){ - return 3; - } - - /** - * Checks that the given object implements/extends the given - * interface/class. - * - * Note that using the instanceof operator causes a class to be loaded. - * Using this method doesn't load a class and it can be used instead of - * the instanceof operator for performance reasons. - * - * @param obj Object to be checked - * @param type The name of the interface/class. Must be - * fully-qualified interface/class name. - * @return true, if this object implements/extends the given - * interface/class, false, otherwise, or if obj or type is null - */ - public static boolean isInstanceOf(Object obj, String type) { - if (obj == null) return false; - if (type == null) return false; - - return isInstanceOf(obj.getClass(), type); - } - - private static boolean isInstanceOf(Class cls, String type) { - if (cls == null) return false; - - if (cls.getName().equals(type)) { - return true; - } - - for (Class c : cls.getInterfaces()) { - if (c.getName().equals(type)) { - return true; - } - } - return isInstanceOf(cls.getSuperclass(), type); - } - - /////////////////////////////////////////////////////////////////////////// - // - // The following methods help set and identify whether a particular - // AWTEvent object was produced by the system or by user code. As of this - // writing the only consumer is the Java Plug-In, although this information - // could be useful to more clients and probably should be formalized in - // the public API. - // - /////////////////////////////////////////////////////////////////////////// - - public static void setSystemGenerated(AWTEvent e) { - AWTAccessor.getAWTEventAccessor().setSystemGenerated(e); - } - - public static boolean isSystemGenerated(AWTEvent e) { - return AWTAccessor.getAWTEventAccessor().isSystemGenerated(e); - } - -} // class SunToolkit - - -/* - * PostEventQueue is a Thread that runs in the same AppContext as the - * Java EventQueue. It is a queue of AWTEvents to be posted to the - * Java EventQueue. The toolkit Thread (AWT-Windows/AWT-Motif) posts - * events to this queue, which then calls EventQueue.postEvent(). - * - * We do this because EventQueue.postEvent() may be overridden by client - * code, and we mustn't ever call client code from the toolkit thread. - */ -class PostEventQueue { - private EventQueueItem queueHead = null; - private EventQueueItem queueTail = null; - private final EventQueue eventQueue; - - // For the case when queue is cleared but events are not posted - private volatile boolean isFlushing = false; - - PostEventQueue(EventQueue eq) { - eventQueue = eq; - } - - public synchronized boolean noEvents() { - return queueHead == null && !isFlushing; - } - - /* - * Continually post pending AWTEvents to the Java EventQueue. The method - * is synchronized to ensure the flush is completed before a new event - * can be posted to this queue. - * - * 7177040: The method couldn't be wholly synchronized because of calls - * of EventQueue.postEvent() that uses pushPopLock, otherwise it could - * potentially lead to deadlock - */ - public void flush() { - EventQueueItem tempQueue; - synchronized (this) { - tempQueue = queueHead; - queueHead = queueTail = null; - isFlushing = (tempQueue != null); - } - try { - while (tempQueue != null) { - eventQueue.postEvent(tempQueue.event); - tempQueue = tempQueue.next; - } - } - finally { - isFlushing = false; - } - } - - /* - * Enqueue an AWTEvent to be posted to the Java EventQueue. - */ - void postEvent(AWTEvent event) { - EventQueueItem item = new EventQueueItem(event); - - synchronized (this) { - if (queueHead == null) { - queueHead = queueTail = item; - } else { - queueTail.next = item; - queueTail = item; - } - } - SunToolkit.wakeupEventQueue(eventQueue, event.getSource() == AWTAutoShutdown.getInstance()); - } -} // class PostEventQueue diff --git a/openjdk/sun/awt/Win32FontManager.java b/openjdk/sun/awt/Win32FontManager.java deleted file mode 100644 index 20dbe48e..00000000 --- a/openjdk/sun/awt/Win32FontManager.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (C) 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.awt; - -import sun.font.SunFontManager; - -public class Win32FontManager extends SunFontManager { - -} diff --git a/openjdk/sun/awt/X11FontManager.java b/openjdk/sun/awt/X11FontManager.java deleted file mode 100644 index 1f1ab313..00000000 --- a/openjdk/sun/awt/X11FontManager.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (C) 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.awt; - -import sun.font.SunFontManager; - -public class X11FontManager extends SunFontManager { - -} diff --git a/openjdk/sun/awt/image/GifImageDecoder.java b/openjdk/sun/awt/image/GifImageDecoder.java deleted file mode 100644 index 80f79e15..00000000 --- a/openjdk/sun/awt/image/GifImageDecoder.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright (C) 2010 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.awt.image; - -import java.io.InputStream; - -/** - * Replace the same class from Sun with native parts. - * @author Volker Berlin - */ -public class GifImageDecoder extends IkvmImageDecoder{ - - GifImageDecoder(InputStreamImageSource src, InputStream is){ - super(src, is); - } - -} diff --git a/openjdk/sun/awt/image/IkvmImageDecoder.java b/openjdk/sun/awt/image/IkvmImageDecoder.java deleted file mode 100644 index 17be22b9..00000000 --- a/openjdk/sun/awt/image/IkvmImageDecoder.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - Copyright (C) 2010 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.awt.image; - -import java.awt.image.*; -import java.io.IOException; -import java.io.InputStream; - -import cli.System.Drawing.Bitmap; -import cli.System.Drawing.Imaging.ImageLockMode; -import cli.System.Drawing.Imaging.PixelFormat; -import cli.System.IO.SeekOrigin; -import cli.System.IO.Stream; -import cli.System.NotSupportedException; -import ikvm.runtime.Util; - -abstract class IkvmImageDecoder extends ImageDecoder { - - IkvmImageDecoder(InputStreamImageSource src, InputStream is){ - super(src, is); - } - - @Override - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public void produceImage() throws IOException, ImageFormatException{ - Stream stream = new Stream(){ - - @Override - public void Flush(){ - Util.throwException(new NotSupportedException()); - } - - @Override - public int Read(byte[] bytes, int off, int len){ - try{ - int count = input.read(bytes, off, len); - if( count < 0 ){ - return 0; - } - return count; - }catch(IOException ex){ - throw new RuntimeException(ex); - } - } - - @Override - public long Seek(long arg0, SeekOrigin arg1){ - Util.throwException(new NotSupportedException()); - return 0; - } - - @Override - public void SetLength(long arg0){ - Util.throwException(new NotSupportedException()); - } - - @Override - public void Write(byte[] arg0, int arg1, int arg2){ - Util.throwException(new NotSupportedException()); - } - - @Override - public boolean get_CanRead(){ - return true; - } - - @Override - public boolean get_CanSeek(){ - return false; - } - - @Override - public boolean get_CanWrite(){ - return true; - } - - @Override - public long get_Length(){ - try{ - return input.available(); - }catch(IOException ex){ - throw new RuntimeException(ex); - } - } - - @Override - public long get_Position(){ - Util.throwException(new NotSupportedException()); - return 0; - } - - @Override - public void set_Position(long arg0){ - Util.throwException(new NotSupportedException()); - } - - }; - try{ - Bitmap bitmap = new Bitmap(stream); - int width = bitmap.get_Width(); - int height = bitmap.get_Height(); - int size = width * height; - int[] pixelData = new int[size]; - - cli.System.Drawing.Rectangle rect = new cli.System.Drawing.Rectangle(0, 0, width, height); - cli.System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, ImageLockMode.wrap(ImageLockMode.ReadOnly), PixelFormat.wrap(PixelFormat.Format32bppArgb)); - cli.System.IntPtr pixelPtr = data.get_Scan0(); - cli.System.Runtime.InteropServices.Marshal.Copy(pixelPtr, pixelData, 0, size); - bitmap.UnlockBits(data); - - //source. - - setDimensions(width, height); - ColorModel cm = ColorModel.getRGBdefault(); - setColorModel(cm); - //setHints(flags); - headerComplete(); - - setPixels(0,0,width,height, cm, pixelData,0,width); - imageComplete(ImageConsumer.STATICIMAGEDONE, true); - }catch(Throwable th){ - th.printStackTrace(); - imageComplete(ImageConsumer.IMAGEERROR|ImageConsumer.STATICIMAGEDONE, true); - throw new IOException(th); - } finally { - try { close(); } catch(Throwable e){e.printStackTrace();} - } - } -} diff --git a/openjdk/sun/awt/image/ImageRepresentation.java b/openjdk/sun/awt/image/ImageRepresentation.java deleted file mode 100644 index 962d46e0..00000000 --- a/openjdk/sun/awt/image/ImageRepresentation.java +++ /dev/null @@ -1,421 +0,0 @@ -/* - Copyright (C) 2009 Jeroen Frijters - Copyright (C) 2010 Volker Berlin (i-net software) - Copyright (C) 2011 Karsten Heinrich (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.awt.image; - -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.ImageConsumer; -import java.awt.image.ImageObserver; -import java.util.Hashtable; - -import cli.System.Drawing.Bitmap; -import cli.System.Drawing.Imaging.BitmapData; -import cli.System.Drawing.Imaging.ImageLockMode; -import cli.System.Drawing.Imaging.PixelFormat; - -public class ImageRepresentation extends ImageWatched implements ImageConsumer{ - - private static final int DEFAULT_PIXEL_FORMAT = PixelFormat.Format32bppArgb; - InputStreamImageSource src; - ToolkitImage image; - - private int width = -1; - private int height = -1; - - private int availinfo; - - private BufferedImage bimage; - private cli.System.Drawing.Bitmap bitmap; - private int pixelFormat = DEFAULT_PIXEL_FORMAT; - - ImageRepresentation(ToolkitImage im){ - image = im; - - if (image.getSource() instanceof InputStreamImageSource) { - src = (InputStreamImageSource) image.getSource(); - } - } - - /* REMIND: Only used for Frame.setIcon - should use ImageWatcher instead */ - public synchronized void reconstruct(int flags) { - if (src != null) { - src.checkSecurity(null, false); - } - int missinginfo = flags & ~availinfo; - if ((availinfo & ImageObserver.ERROR) == 0 && missinginfo != 0) { - numWaiters++; - try { - startProduction(); - missinginfo = flags & ~availinfo; - while ((availinfo & ImageObserver.ERROR) == 0 && - missinginfo != 0) - { - try { - wait(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - missinginfo = flags & ~availinfo; - } - } finally { - decrementWaiters(); - } - } - } - - @Override - public void setDimensions(int w, int h){ - if (src != null) { - src.checkSecurity(null, false); - } - - image.setDimensions(w, h); -// bitmap = new cli.System.Drawing.Bitmap(w, h); - - newInfo(image, (ImageObserver.WIDTH | ImageObserver.HEIGHT), - 0, 0, w, h); - - if (w <= 0 || h <= 0) { - imageComplete(ImageConsumer.IMAGEERROR); - return; - } - - width = w; - height = h; - - availinfo |= ImageObserver.WIDTH | ImageObserver.HEIGHT; - } - - private Bitmap getBitmapRef(){ - if( bitmap == null ){ - bitmap = new Bitmap(width, height, PixelFormat.wrap(pixelFormat) ); - } - return bitmap; - } - - public int getWidth(){ - return width; - } - - public int getHeight(){ - return height; - } - - public BufferedImage getBufferedImage(){ - return bimage; - } - - @Override - public void setProperties(Hashtable<?, ?> props){ - // ignore it - - } - - @Override - public synchronized void setColorModel(ColorModel model){ - int newPixelFormat = getPixelFormatForColorModel(model); - if( model.getPixelSize() <= 8 ){ - newPixelFormat = DEFAULT_PIXEL_FORMAT; - } - if( newPixelFormat != pixelFormat && bitmap != null ){ - // force reconstruct of the bitmap due to a color model change - bitmap.Dispose(); - bitmap = null; - } - pixelFormat = newPixelFormat; - } - - @Override - public void setHints(int hintflags){ - // ignore it - } - - @Override - public void setPixels(int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize){ - int[] pixeli = new int[pixels.length]; - for (int i = 0; i < pixels.length; i++) - { - pixeli[i] = model.getRGB(pixels[i] & 0xff); - } - setPixels(x, y, w, h, model, pixeli, off, scansize); - } - - @Override - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize){ - // FIXME this method will fail for scan lines - if( x < 0) { - w -= x; - x = 0; - } - if (y < 0) { - h -= y; - y = 0; - } - if (w <= 0 || h <= 0) { - // nothing to set - return; - } - if ( off < 0 ) { - throw new java.lang.ArrayIndexOutOfBoundsException( "Data offset out of bounds." ); - } - long length = w * h; - if (length > pixels.length - off) - { - throw new java.lang.ArrayIndexOutOfBoundsException("Data offset out of bounds."); - } - synchronized (this) - { - int pixelFormat = getPixelFormatForColorModel( model ); - int bpp = model.getPixelSize(); - if( bpp == 32 ){ // 32 can be copies 1:1 using an int array - copyInt(x, y, w, h, pixels, off, pixelFormat); - }else if( bpp <= 8 ){ - // transform all pixels using the color model (for indexed color models) - int[] newData = new int[pixels.length]; - for( int i=0; i < newData.length; i++ ){ - newData[i] = model.getRGB(pixels[i]); - } - copyInt(x, y, w, h, pixels, off, DEFAULT_PIXEL_FORMAT); - }else { - // byte per scanline, must be a multitude of 4 - // see http://stackoverflow.com/questions/2185944/why-must-stride-in-the-system-drawing-bitmap-constructor-be-a-multiple-of-4 - int bytesPerLine = (bpp * w) / 8; - int scanLine = ((bytesPerLine + 3) / 4) * 4; - int offset = scanLine - bytesPerLine; - byte[] newData = new byte[h * scanLine]; - int position = 0; - int pixel; - for( int i=0; i<pixels.length; i++ ){ - pixel = pixels[i]; - switch( bpp ){ - case 16: newData[position] = (byte)(pixel & 0xFF); - newData[position + 1] = (byte)((pixel >> 8) & 0xFF); break; - case 24: newData[position] = (byte)(pixel & 0xFF); - newData[position + 1] = (byte)((pixel >> 8) & 0xFF); - newData[position + 2] = (byte)((pixel >> 16) & 0xFF); break; - } - position += bpp / 8; - if( position % scanLine == bytesPerLine ){ - position += offset; - } - } - copyByte(x, y, w, h, newData, off, pixelFormat, bpp); - } - } - - availinfo |= ImageObserver.SOMEBITS; - - // Can't do this here since we might need to transform/clip - // the region - if (((availinfo & ImageObserver.FRAMEBITS) == 0)) { - newInfo(image, ImageObserver.SOMEBITS, x, y, w, h); - } - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - private void copyInt(int x, int y, int w, int h, int[] pixels, int off, int pixelFormat ) { - BitmapData data = getBitmapRef().LockBits(new cli.System.Drawing.Rectangle(x, y, w, h), ImageLockMode.wrap(ImageLockMode.WriteOnly), PixelFormat.wrap(pixelFormat)); - cli.System.Runtime.InteropServices.Marshal.Copy(pixels, off, data.get_Scan0(), data.get_Width() * data.get_Height()); - getBitmapRef().UnlockBits(data); - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - private void copyByte(int x, int y, int w, int h, byte[] pixels, int off, int pixelFormat, int bpp) { - BitmapData data = getBitmapRef().LockBits(new cli.System.Drawing.Rectangle(x, y, w, h), ImageLockMode.wrap(ImageLockMode.WriteOnly), PixelFormat.wrap(pixelFormat)); - cli.System.Runtime.InteropServices.Marshal.Copy(pixels, off, data.get_Scan0(), pixels.length); - getBitmapRef().UnlockBits(data); - } - - - private int getPixelFormatForColorModel( ColorModel cm ){ - if( cm == null ){ - return DEFAULT_PIXEL_FORMAT; // TODO is PixelFormat.Canonical better here? - } - int bpp = cm.getPixelSize(); - int[] sizes = cm.getComponentSize(); - switch( bpp ){ - case 1: return PixelFormat.Undefined; // Indexed is invalid and there is no 1bpp - case 4: return PixelFormat.Format4bppIndexed; - case 8: return PixelFormat.Format8bppIndexed; - case 16: - if( sizes.length <= 1) { - return PixelFormat.Format16bppGrayScale; - } - if( sizes.length == 3 ){ - if( sizes[0] == 5 && sizes[2] == 5 ){ - return sizes[1] == 5 ? PixelFormat.Format16bppRgb555 : PixelFormat.Format16bppRgb565; - } - } - if( sizes.length == 4 && cm.hasAlpha() ){ - return PixelFormat.Format16bppArgb1555; - } - break; - case 24: - return PixelFormat.Format24bppRgb; - case 32: - if(!cm.hasAlpha()){ - return PixelFormat.Format32bppRgb; - } else { - return cm.isAlphaPremultiplied() ? PixelFormat.Format32bppPArgb : PixelFormat.Format32bppArgb; - } - case 48: - return PixelFormat.Format48bppRgb; - case 64: - return cm.isAlphaPremultiplied() ? PixelFormat.Format64bppPArgb : PixelFormat.Format64bppArgb; - } - return PixelFormat.Undefined; - } - - private boolean consuming = false; - - public void imageComplete(int status) { - if (src != null) { - src.checkSecurity(null, false); - } - boolean done; - int info; - switch (status) { - default: - case ImageConsumer.IMAGEABORTED: - done = true; - info = ImageObserver.ABORT; - break; - case ImageConsumer.IMAGEERROR: - image.addInfo(ImageObserver.ERROR); - done = true; - info = ImageObserver.ERROR; - dispose(); - break; - case ImageConsumer.STATICIMAGEDONE: - done = true; - info = ImageObserver.ALLBITS; - break; - case ImageConsumer.SINGLEFRAMEDONE: - done = false; - info = ImageObserver.FRAMEBITS; - break; - } - synchronized (this) { - if (done) { - image.getSource().removeConsumer(this); - consuming = false; - } - if (bimage == null ) { - bimage = new BufferedImage(getBitmapRef()); - } - availinfo |= info; - notifyAll(); - } - - newInfo(image, info, 0, 0, width, height); - - image.infoDone(status); - } - - /*synchronized*/ void startProduction() { - if (!consuming) { - consuming = true; - image.getSource().startProduction(this); - } - } - - private int numWaiters; - - private synchronized void checkConsumption() { - if (isWatcherListEmpty() && numWaiters == 0 && - ((availinfo & ImageObserver.ALLBITS) == 0)) - { - dispose(); - } - } - - @Override - public synchronized void notifyWatcherListEmpty() { - checkConsumption(); - } - - private synchronized void decrementWaiters() { - --numWaiters; - checkConsumption(); - } - - public boolean prepare(ImageObserver iw) { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.ERROR) != 0) { - if (iw != null) { - iw.imageUpdate(image, ImageObserver.ERROR|ImageObserver.ABORT, - -1, -1, -1, -1); - } - return false; - } - boolean done = ((availinfo & ImageObserver.ALLBITS) != 0); - if (!done) { - addWatcher(iw); - startProduction(); - // Some producers deliver image data synchronously - done = ((availinfo & ImageObserver.ALLBITS) != 0); - } - return done; - } - - public int check(ImageObserver iw) { - - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & (ImageObserver.ERROR | ImageObserver.ALLBITS)) == 0) { - addWatcher(iw); - } - - return availinfo; - } - - synchronized void abort() { - image.getSource().removeConsumer(this); - consuming = false; - bimage = null; - bitmap = null; - - newInfo(image, ImageObserver.ABORT, -1, -1, -1, -1); - availinfo &= ~(ImageObserver.SOMEBITS - | ImageObserver.FRAMEBITS - | ImageObserver.ALLBITS - | ImageObserver.ERROR); - } - - synchronized void dispose() { - image.getSource().removeConsumer(this); - consuming = false; - availinfo &= ~(ImageObserver.SOMEBITS - | ImageObserver.FRAMEBITS - | ImageObserver.ALLBITS); - } -} diff --git a/openjdk/sun/awt/image/ImagingLib.java b/openjdk/sun/awt/image/ImagingLib.java deleted file mode 100644 index 104c3c46..00000000 --- a/openjdk/sun/awt/image/ImagingLib.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt.image; - -import java.awt.geom.AffineTransform; -import java.awt.image.AffineTransformOp; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ByteLookupTable; -import java.awt.image.ConvolveOp; -import java.awt.image.Kernel; -import java.awt.image.LookupOp; -import java.awt.image.LookupTable; -import java.awt.image.RasterOp; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.security.AccessController; -import java.security.PrivilegedAction; - -/** - * This class provides a hook to access platform-specific - * imaging code. - * - * If the implementing class cannot handle the op, tile format or - * image format, the method will return null; - * If there is an error when processing the - * data, the implementing class may either return null - * (in which case our java code will be executed) or may throw - * an exception. - */ -public class ImagingLib { - - public static WritableRaster filter(RasterOp op, Raster src, - WritableRaster dst) { - return null; - } - - - public static BufferedImage filter(BufferedImageOp op, BufferedImage src, - BufferedImage dst) - { - return null; - } -} diff --git a/openjdk/sun/awt/image/JPEGImageDecoder.java b/openjdk/sun/awt/image/JPEGImageDecoder.java deleted file mode 100644 index 8a406817..00000000 --- a/openjdk/sun/awt/image/JPEGImageDecoder.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright (C) 2010 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.awt.image; - -import java.io.InputStream; - -/** - * Replace the same class from Sun with native parts. - * @author Volker Berlin - */ -public class JPEGImageDecoder extends IkvmImageDecoder{ - - JPEGImageDecoder(InputStreamImageSource src, InputStream is){ - super(src, is); - } - -} diff --git a/openjdk/sun/awt/image/SunWritableRaster.java b/openjdk/sun/awt/image/SunWritableRaster.java deleted file mode 100644 index 6eb92086..00000000 --- a/openjdk/sun/awt/image/SunWritableRaster.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2001, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt.image; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Image; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.DataBufferUShort; -import java.awt.image.DataBufferInt; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; - -import sun.java2d.StateTrackable.State; -//import sun.java2d.SurfaceData; -import sun.java2d.StateTrackableDelegate; - -/** - * This class exists as a middle layer between WritableRaster and its - * implementation specific subclasses (ByteComponentRaster, ShortBandedRaster, - * etc). - * It provides utilities to steal the data arrays from the standard DataBuffer - * types and also steals the StateTrackableDelegate from the associated - * DataBuffer so that it can be updated when the data is changed. - */ -public class SunWritableRaster extends WritableRaster { - private static DataStealer stealer; - - public static interface DataStealer { - public byte[] getData(DataBufferByte dbb, int bank); - public short[] getData(DataBufferUShort dbus, int bank); - public int[] getData(DataBufferInt dbi, int bank); - public StateTrackableDelegate getTrackable(DataBuffer db); - public void setTrackable(DataBuffer db, StateTrackableDelegate trackable); - } - - public static void setDataStealer(DataStealer ds) { - if (stealer != null) { - throw new InternalError("Attempt to set DataStealer twice"); - } - stealer = ds; - } - - public static byte[] stealData(DataBufferByte dbb, int bank) { - return stealer.getData(dbb, bank); - } - - public static short[] stealData(DataBufferUShort dbus, int bank) { - return stealer.getData(dbus, bank); - } - - public static int[] stealData(DataBufferInt dbi, int bank) { - return stealer.getData(dbi, bank); - } - - public static StateTrackableDelegate stealTrackable(DataBuffer db) { - return stealer.getTrackable(db); - } - - public static void markDirty(DataBuffer db) { - stealer.getTrackable(db).markDirty(); - } - - public static void setTrackable(DataBuffer db, StateTrackableDelegate trackable) { - stealer.setTrackable(db, trackable); - } - - public static void makeTrackable(DataBuffer db) { - stealer.setTrackable(db, StateTrackableDelegate.createInstance(State.STABLE)); - } - - public static void markDirty(WritableRaster wr) { - if (wr instanceof SunWritableRaster) { - ((SunWritableRaster) wr).markDirty(); - } else { - markDirty(wr.getDataBuffer()); - } - } - - public static void markDirty(Image img) { -// SurfaceData.getPrimarySurfaceData(img).markDirty(); - } - - private StateTrackableDelegate theTrackable; - - public SunWritableRaster(SampleModel sampleModel, Point origin) { - super(sampleModel, origin); - theTrackable = stealTrackable(dataBuffer); - } - - public SunWritableRaster(SampleModel sampleModel, - DataBuffer dataBuffer, - Point origin) - { - super(sampleModel, dataBuffer, origin); - theTrackable = stealTrackable(dataBuffer); - } - - public SunWritableRaster(SampleModel sampleModel, - DataBuffer dataBuffer, - Rectangle aRegion, - Point sampleModelTranslate, - WritableRaster parent) - { - super(sampleModel, dataBuffer, aRegion, sampleModelTranslate, parent); - theTrackable = stealTrackable(dataBuffer); - } - - /** - * Mark the TrackableDelegate of the associated DataBuffer dirty. - */ - public final void markDirty() { - theTrackable.markDirty(); - } -} diff --git a/openjdk/sun/awt/image/ToolkitImage.java b/openjdk/sun/awt/image/ToolkitImage.java deleted file mode 100644 index 8f882f3e..00000000 --- a/openjdk/sun/awt/image/ToolkitImage.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt.image; - -import java.util.Hashtable; -import java.util.Enumeration; - -import java.awt.Component; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.ImageProducer; -import java.awt.image.ImageConsumer; -import java.awt.image.ImageObserver; -import sun.awt.image.ImageRepresentation; - -public class ToolkitImage extends Image { - - /** - * The object which is used to reconstruct the original image data - * as needed. - */ - ImageProducer source; - - InputStreamImageSource src; - - ImageRepresentation imagerep; - - - protected ToolkitImage() { - } - - /** - * Construct an image from an ImageProducer object. - */ - public ToolkitImage(ImageProducer is) { - source = is; - if (is instanceof InputStreamImageSource) { - src = (InputStreamImageSource) is; - } - } - - public ImageProducer getSource() { - if (src != null) { - src.checkSecurity(null, false); - } - return source; - } - - private int width = -1; - private int height = -1; - private Hashtable properties; - - private int availinfo; - - /** - * Return the width of the original image source. - * If the width isn't known, then the image is reconstructed. - */ - public int getWidth() { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.WIDTH) == 0) { - reconstruct(ImageObserver.WIDTH); - } - return width; - } - - /** - * Return the width of the original image source. - * If the width isn't known, then the ImageObserver object will be - * notified when the data is available. - */ - public synchronized int getWidth(ImageObserver iw) { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.WIDTH) == 0) { - addWatcher(iw, true); - if ((availinfo & ImageObserver.WIDTH) == 0) { - return -1; - } - } - return width; - } - - /** - * Return the height of the original image source. - * If the height isn't known, then the image is reconstructed. - */ - public int getHeight() { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.HEIGHT) == 0) { - reconstruct(ImageObserver.HEIGHT); - } - return height; - } - - /** - * Return the height of the original image source. - * If the height isn't known, then the ImageObserver object will be - * notified when the data is available. - */ - public synchronized int getHeight(ImageObserver iw) { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.HEIGHT) == 0) { - addWatcher(iw, true); - if ((availinfo & ImageObserver.HEIGHT) == 0) { - return -1; - } - } - return height; - } - - /** - * Return a property of the image by name. Individual property names - * are defined by the various image formats. If a property is not - * defined for a particular image, then this method will return the - * UndefinedProperty object. If the properties for this image are - * not yet known, then this method will return null and the ImageObserver - * object will be notified later. The property name "comment" should - * be used to store an optional comment which can be presented to - * the user as a description of the image, its source, or its author. - */ - public Object getProperty(String name, ImageObserver observer) { - if (name == null) { - throw new NullPointerException("null property name is not allowed"); - } - - if (src != null) { - src.checkSecurity(null, false); - } - if (properties == null) { - addWatcher(observer, true); - if (properties == null) { - return null; - } - } - Object o = properties.get(name); - if (o == null) { - o = Image.UndefinedProperty; - } - return o; - } - - public boolean hasError() { - if (src != null) { - src.checkSecurity(null, false); - } - return (availinfo & ImageObserver.ERROR) != 0; - } - - public int check(ImageObserver iw) { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.ERROR) == 0 && - ((~availinfo) & (ImageObserver.WIDTH | - ImageObserver.HEIGHT | - ImageObserver.PROPERTIES)) != 0) { - addWatcher(iw, false); - } - return availinfo; - } - - public void preload(ImageObserver iw) { - if (src != null) { - src.checkSecurity(null, false); - } - if ((availinfo & ImageObserver.ALLBITS) == 0) { - addWatcher(iw, true); - } - } - - private synchronized void addWatcher(ImageObserver iw, boolean load) { - if ((availinfo & ImageObserver.ERROR) != 0) { - if (iw != null) { - iw.imageUpdate(this, ImageObserver.ERROR|ImageObserver.ABORT, - -1, -1, -1, -1); - } - return; - } - ImageRepresentation ir = getImageRep(); - ir.addWatcher(iw); - if (load) { - ir.startProduction(); - } - } - - private synchronized void reconstruct(int flags) { - if ((flags & ~availinfo) != 0) { - if ((availinfo & ImageObserver.ERROR) != 0) { - return; - } - ImageRepresentation ir = getImageRep(); - ir.startProduction(); - while ((flags & ~availinfo) != 0) { - try { - wait(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - if ((availinfo & ImageObserver.ERROR) != 0) { - return; - } - } - } - } - - synchronized void addInfo(int newinfo) { - availinfo |= newinfo; - notifyAll(); - } - - void setDimensions(int w, int h) { - width = w; - height = h; - addInfo(ImageObserver.WIDTH | ImageObserver.HEIGHT); - } - - void setProperties(Hashtable props) { - if (props == null) { - props = new Hashtable(); - } - properties = props; - addInfo(ImageObserver.PROPERTIES); - } - - synchronized void infoDone(int status) { - if (status == ImageConsumer.IMAGEERROR || - ((~availinfo) & (ImageObserver.WIDTH | - ImageObserver.HEIGHT)) != 0) { - addInfo(ImageObserver.ERROR); - } else if ((availinfo & ImageObserver.PROPERTIES) == 0) { - setProperties(null); - } - } - - public void flush() { - if (src != null) { - src.checkSecurity(null, false); - } - - ImageRepresentation ir; - synchronized (this) { - availinfo &= ~ImageObserver.ERROR; - ir = imagerep; - imagerep = null; - } - if (ir != null) { - ir.abort(); - } - if (src != null) { - src.flush(); - } - } - - protected ImageRepresentation makeImageRep() { - return new ImageRepresentation(this); - } - - public synchronized ImageRepresentation getImageRep() { - if (src != null) { - src.checkSecurity(null, false); - } - if (imagerep == null) { - imagerep = makeImageRep(); - } - return imagerep; - } - - public Graphics getGraphics() { - throw new UnsupportedOperationException("getGraphics() not valid for images " + - "created with createImage(producer)"); - } - -// /* this method is needed by printing code */ -// public ColorModel getColorModel() { -// ImageRepresentation imageRep = getImageRep(); -// return imageRep.getColorModel(); -// } -// - /* this method is needed by printing code */ - public BufferedImage getBufferedImage() { - ImageRepresentation imageRep = getImageRep(); - return imageRep.getBufferedImage(); - } -// -// public void setAccelerationPriority(float priority) { -// super.setAccelerationPriority(priority); -// ImageRepresentation imageRep = getImageRep(); -// imageRep.setAccelerationPriority(accelerationPriority); -// } -} diff --git a/openjdk/sun/awt/shell/Win32ShellFolder2.java b/openjdk/sun/awt/shell/Win32ShellFolder2.java deleted file mode 100644 index 0f5f6816..00000000 --- a/openjdk/sun/awt/shell/Win32ShellFolder2.java +++ /dev/null @@ -1,1145 +0,0 @@ -/* - * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. - * Copyright (C) 2009 Volker Berlin (i-net software) - * Copyright (C) 2010 Karsten Heinrich (i-net software) - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt.shell; - -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.*; -import javax.swing.SwingConstants; - -import cli.System.IntPtr; -import cli.System.Drawing.Bitmap; - -// NOTE: This class basically a conversion of the OpenJDK Wen32ShellFolder2, but uses -// .NET pointers and objects instead of representing pointers as long - -/** - * Win32 Shell Folders - * <P> - * <BR> - * There are two fundamental types of shell folders : file system folders - * and non-file system folders. File system folders are relatively easy - * to deal with. Non-file system folders are items such as My Computer, - * Network Neighborhood, and the desktop. Some of these non-file system - * folders have special values and properties. - * <P> - * <BR> - * Win32 keeps two basic data structures for shell folders. The first - * of these is called an ITEMIDLIST. Usually a pointer, called an - * LPITEMIDLIST, or more frequently just "PIDL". This structure holds - * a series of identifiers and can be either relative to the desktop - * (an absolute PIDL), or relative to the shell folder that contains them. - * Some Win32 functions can take absolute or relative PIDL values, and - * others can only accept relative values. - * <BR> - * The second data structure is an IShellFolder COM interface. Using - * this interface, one can enumerate the relative PIDLs in a shell - * folder, get attributes, etc. - * <BR> - * All Win32ShellFolder2 objects which are folder types (even non-file - * system folders) contain an IShellFolder object. Files are named in - * directories via relative PIDLs. - * - * @author Michael Martak - * @author Leif Samuelsson - * @author Kenneth Russell - * @author Volker Berlin - * @author Karsten Heinrich - * @since 1.4 */ - -final class Win32ShellFolder2 extends ShellFolder { - - // Win32 Shell Folder Constants - public static final int DESKTOP = 0x0000; - public static final int INTERNET = 0x0001; - public static final int PROGRAMS = 0x0002; - public static final int CONTROLS = 0x0003; - public static final int PRINTERS = 0x0004; - public static final int PERSONAL = 0x0005; - public static final int FAVORITES = 0x0006; - public static final int STARTUP = 0x0007; - public static final int RECENT = 0x0008; - public static final int SENDTO = 0x0009; - public static final int BITBUCKET = 0x000a; - public static final int STARTMENU = 0x000b; - public static final int DESKTOPDIRECTORY = 0x0010; - public static final int DRIVES = 0x0011; - public static final int NETWORK = 0x0012; - public static final int NETHOOD = 0x0013; - public static final int FONTS = 0x0014; - public static final int TEMPLATES = 0x0015; - public static final int COMMON_STARTMENU = 0x0016; - public static final int COMMON_PROGRAMS = 0X0017; - public static final int COMMON_STARTUP = 0x0018; - public static final int COMMON_DESKTOPDIRECTORY = 0x0019; - public static final int APPDATA = 0x001a; - public static final int PRINTHOOD = 0x001b; - public static final int ALTSTARTUP = 0x001d; - public static final int COMMON_ALTSTARTUP = 0x001e; - public static final int COMMON_FAVORITES = 0x001f; - public static final int INTERNET_CACHE = 0x0020; - public static final int COOKIES = 0x0021; - public static final int HISTORY = 0x0022; - - // Win32 shell folder attributes - public static final int ATTRIB_CANCOPY = 0x00000001; - public static final int ATTRIB_CANMOVE = 0x00000002; - public static final int ATTRIB_CANLINK = 0x00000004; - public static final int ATTRIB_CANRENAME = 0x00000010; - public static final int ATTRIB_CANDELETE = 0x00000020; - public static final int ATTRIB_HASPROPSHEET = 0x00000040; - public static final int ATTRIB_DROPTARGET = 0x00000100; - public static final int ATTRIB_LINK = 0x00010000; - public static final int ATTRIB_SHARE = 0x00020000; - public static final int ATTRIB_READONLY = 0x00040000; - public static final int ATTRIB_GHOSTED = 0x00080000; - public static final int ATTRIB_HIDDEN = 0x00080000; - public static final int ATTRIB_FILESYSANCESTOR = 0x10000000; - public static final int ATTRIB_FOLDER = 0x20000000; - public static final int ATTRIB_FILESYSTEM = 0x40000000; - public static final int ATTRIB_HASSUBFOLDER = 0x80000000; - public static final int ATTRIB_VALIDATE = 0x01000000; - public static final int ATTRIB_REMOVABLE = 0x02000000; - public static final int ATTRIB_COMPRESSED = 0x04000000; - public static final int ATTRIB_BROWSABLE = 0x08000000; - public static final int ATTRIB_NONENUMERATED = 0x00100000; - public static final int ATTRIB_NEWCONTENT = 0x00200000; - - // IShellFolder::GetDisplayNameOf constants - public static final int SHGDN_NORMAL = 0; - public static final int SHGDN_INFOLDER = 1; - public static final int SHGDN_INCLUDE_NONFILESYS= 0x2000; - public static final int SHGDN_FORADDRESSBAR = 0x4000; - public static final int SHGDN_FORPARSING = 0x8000; - - // Values for system call LoadIcon() - public enum SystemIcon { - IDI_APPLICATION(32512), - IDI_HAND(32513), - IDI_ERROR(32513), - IDI_QUESTION(32514), - IDI_EXCLAMATION(32515), - IDI_WARNING(32515), - IDI_ASTERISK(32516), - IDI_INFORMATION(32516), - IDI_WINLOGO(32517); - - private final int iconID; - - SystemIcon(int iconID) { - this.iconID = iconID; - } - - public int getIconID() { - return iconID; - } - } - - static class FolderDisposer implements sun.java2d.DisposerRecord { - /* - * This is cached as a concession to getFolderType(), which needs - * an absolute PIDL. - */ - cli.System.IntPtr absolutePIDL; - /* - * We keep track of shell folders through the IShellFolder - * interface of their parents plus their relative PIDL. - */ - cli.System.Object pIShellFolder; - cli.System.IntPtr relativePIDL; - - boolean disposed; - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public void dispose() { - if (disposed) - return; - if ( relativePIDL != null && !cli.System.IntPtr.Zero.Equals( relativePIDL ) ) { - releasePIDL(relativePIDL); - } - if ( absolutePIDL != null && !cli.System.IntPtr.Zero.Equals( absolutePIDL ) ) { - releasePIDL(absolutePIDL); - } - if ( pIShellFolder != null ) { - releaseIShellFolder(pIShellFolder); - } - disposed = true; - } - } - - FolderDisposer disposer = new FolderDisposer(); - - private void setIShellFolder( cli.System.Object iShellFolder ) { - disposer.pIShellFolder = iShellFolder; - } - - private void setRelativePIDL(cli.System.IntPtr relativePIDL) { - disposer.relativePIDL = relativePIDL; - } - - /* - * The following are for caching various shell folder properties. - */ - private cli.System.Object pIShellIcon = null; - private String folderType = null; - private String displayName = null; - private Image smallIcon = null; - private Image largeIcon = null; - private Boolean isDir = null; - - /* - * The following is to identify the My Documents folder as being special - */ - private boolean isPersonal; - - /** - * Create a system special shell folder, such as the - * desktop or Network Neighborhood. - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - Win32ShellFolder2(final int csidl) throws IOException, InterruptedException { - // Desktop is parent of DRIVES and NETWORK, not necessarily - // other special shell folders. - super ( null, (getFileSystemPath(csidl) == null) ? ("ShellFolder: 0x" + Integer.toHexString(csidl)) : getFileSystemPath(csidl)); - if (csidl == DESKTOP) { - // compared to the Java implementation we require two steps here since - // we don't have a callback from the native methods in to this instance - setIShellFolder( initDesktopFolder() ); - setRelativePIDL( initDesktopPIDL() ); - } else { - cli.System.Object desktopFolder = getDesktop().getIShellFolder(); - cli.System.IntPtr pidl = initSpecialPIDL( desktopFolder, csidl ); - setRelativePIDL( pidl ); - setIShellFolder( initSpecialFolder(desktopFolder, pidl) ); - // At this point, the native method initSpecial() has set our relativePIDL - // relative to the Desktop, which may not be our immediate parent. We need - // to traverse this ID list and break it into a chain of shell folders from - // the top, with each one having an immediate parent and a relativePIDL - // relative to that parent. - bindToDesktop(); - } - - sun.java2d.Disposer.addRecord(this , disposer); - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - protected void bindToDesktop() { - cli.System.IntPtr pIDL = disposer.relativePIDL; - parent = getDesktop(); - while ( pIDL != null && !cli.System.IntPtr.Zero.Equals( pIDL ) ) { - // Get a child pidl relative to 'parent' - cli.System.IntPtr childPIDL = copyFirstPIDLEntry(pIDL); - if (childPIDL != null && !cli.System.IntPtr.Zero.Equals( childPIDL ) ) { - // Get a handle to the the rest of the ID list - // i,e, parent's grandchilren and down - pIDL = getNextPIDLEntry(pIDL); - if ( pIDL != null && !cli.System.IntPtr.Zero.Equals( pIDL ) ) { - // Now we know that parent isn't immediate to 'this' because it - // has a continued ID list. Create a shell folder for this child - // pidl and make it the new 'parent'. - parent = new Win32ShellFolder2( (Win32ShellFolder2) parent, childPIDL ); - } else { - // No grandchildren means we have arrived at the parent of 'this', - // and childPIDL is directly relative to parent. - disposer.relativePIDL = childPIDL; - } - } else { - break; - } - } - } - - /** - * Create a system shell folder - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - Win32ShellFolder2(Win32ShellFolder2 parent, cli.System.Object pIShellFolder, cli.System.IntPtr relativePIDL, String path) { - super(parent, (path != null) ? path : "ShellFolder: "); - this.disposer.pIShellFolder = pIShellFolder; - this.disposer.relativePIDL = relativePIDL; - sun.java2d.Disposer.addRecord(this, disposer); - } - - /** - * Creates a shell folder with a parent and relative PIDL - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - Win32ShellFolder2(Win32ShellFolder2 parent, cli.System.IntPtr relativePIDL) { - super (parent, getFileSystemPath(parent.getIShellFolder(), relativePIDL)); - this .disposer.relativePIDL = relativePIDL; - getAbsolutePath(); - sun.java2d.Disposer.addRecord(this , disposer); - } - - // Initializes the desktop shell folder - /** - * Returns the pIDL of the Desktop folder (pIDL root) - * @return the pIDL of the Desktop folder (pIDL root) - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.IntPtr initDesktopPIDL(); - /** - * Returns the IShellFolder pointer of the Desktop folder (pIDL root) - * @return the IShellFolder pointer of the Desktop folder (pIDL root) - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.Object initDesktopFolder(); - - // Initializes a special, non-file system shell folder - // from one of the above constants - /** - * initializes a special folder - * @param desktopIShellFolder the IShellFolder reference of the desktop folder - * @param csidl the CSIDL of the requested special folder - * @return the pIDL of the special folder relative to the desktop root - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.IntPtr initSpecialPIDL(cli.System.Object desktopIShellFolder, int csidl); - /** - * initializes a special folder - * @param desktopIShellFolder the IShellFolder reference of the desktop folder - * @param pidl the pIDL of the requested folder relative to the desktopIShellFolder - * @return the IShellFolder reference for the requested folder - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.Object initSpecialFolder(cli.System.Object desktopIShellFolder, cli.System.IntPtr pidl); - - /** Marks this folder as being the My Documents (Personal) folder */ - public void setIsPersonal() { - isPersonal = true; - } - - /** - * This method is implemented to make sure that no instances - * of <code>ShellFolder</code> are ever serialized. If <code>isFileSystem()</code> returns - * <code>true</code>, then the object is representable with an instance of - * <code>java.io.File</code> instead. If not, then the object depends - * on native PIDL state and should not be serialized. - * - * @returns a <code>java.io.File</code> replacement object. If the folder - * is a not a normal directory, then returns the first non-removable - * drive (normally "C:\"). - */ - protected Object writeReplace() - throws java.io.ObjectStreamException { - if (isFileSystem()) { - return new File(getPath()); - } else { - Win32ShellFolder2 drives = Win32ShellFolderManager2.getDrives(); - if (drives != null) { - File[] driveRoots = drives.listFiles(); - if (driveRoots != null) { - for (int i = 0; i < driveRoots.length; i++) { - if (driveRoots[i] instanceof Win32ShellFolder2) { - Win32ShellFolder2 sf = (Win32ShellFolder2) driveRoots[i]; - if (sf.isFileSystem() && !sf.hasAttribute(ATTRIB_REMOVABLE)) { - return new File(sf.getPath()); - } - } - } - } - } - // Ouch, we have no hard drives. Return something "valid" anyway. - return new File("C:\\"); - } - } - - /** - * Finalizer to clean up any COM objects or PIDLs used by this object. - */ - protected void dispose() { - disposer.dispose(); - } - - // Given a (possibly multi-level) relative PIDL (with respect to - // the desktop, at least in all of the usage cases in this code), - // return a pointer to the next entry. Does not mutate the PIDL in - // any way. Returns 0 if the null terminator is reached. - // Needs to be accessible to Win32ShellFolderManager2 - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native cli.System.IntPtr getNextPIDLEntry(cli.System.IntPtr pIDL); - - // Given a (possibly multi-level) relative PIDL (with respect to - // the desktop, at least in all of the usage cases in this code), - // copy the first entry into a newly-allocated PIDL. Returns 0 if - // the PIDL is at the end of the list. - // Needs to be accessible to Win32ShellFolderManager2 - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native cli.System.IntPtr copyFirstPIDLEntry(cli.System.IntPtr pIDL); - - // Given a parent's absolute PIDL and our relative PIDL, build an absolute PIDL - /** - * Combines a parent pIDL with a descendant pIDL. It doesn't matter whether the parent pIDL - * is relative or absolute since this is only a concatenation of the IDLs - * @param ppIDL the parent pIDL - * @param pIDL the pIDL relative to the ppIDL - * @return a pIDL for the item referenced by the original pIDL but relative to the parent of ppIDL - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.IntPtr combinePIDLs(cli.System.IntPtr ppIDL, cli.System.IntPtr pIDL); - - // Release a PIDL object - // Needs to be accessible to Win32ShellFolderManager2 - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native void releasePIDL(cli.System.IntPtr pIDL); - - // Release an IShellFolder object - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native void releaseIShellFolder( cli.System.Object iShellFolder ); - - /** - * Accessor for IShellFolder - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public cli.System.Object getIShellFolder() { - if (disposer.pIShellFolder == null ) { - assert (isDirectory()); - assert (parent != null); - cli.System.Object parentIShellFolder = getParentIShellFolder(); - if (parentIShellFolder == null) { - throw new InternalError( "Parent IShellFolder was null for " + getAbsolutePath() ); - } - // We are a directory with a parent and a relative PIDL. - // We want to bind to the parent so we get an IShellFolder instance associated with us. - disposer.pIShellFolder = bindToObject(parentIShellFolder, disposer.relativePIDL); - if (disposer.pIShellFolder == null ) { - throw new InternalError("Unable to bind " + getAbsolutePath() + " to parent"); - } - } - return disposer.pIShellFolder; - } - - /** - * Get the parent ShellFolder's IShellFolder interface - */ - public cli.System.Object getParentIShellFolder() { - Win32ShellFolder2 parent = (Win32ShellFolder2) getParentFile(); - cli.System.Object parentFolder; - if (parent == null) { - // Parent should only be null if this is the desktop, whose - // relativePIDL is relative to its own IShellFolder. - parentFolder = getIShellFolder(); - } else { - parentFolder = parent.getIShellFolder(); - } - return parentFolder; - } - - /** - * Accessor for relative PIDL - */ - public cli.System.IntPtr getRelativePIDL() { - if (disposer.relativePIDL == null) { - throw new InternalError( "Should always have a relative PIDL" ); - } - return disposer.relativePIDL; - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - private cli.System.IntPtr getAbsolutePIDL() { - if (parent == null) { - // This is the desktop - return getRelativePIDL(); - } else { - if (disposer.absolutePIDL == null || disposer.absolutePIDL.Equals( IntPtr.Zero )) { - disposer.absolutePIDL = combinePIDLs( ((Win32ShellFolder2) parent).getAbsolutePIDL(), getRelativePIDL()); - } - - return disposer.absolutePIDL; - } - } - - /** - * Helper function to return the desktop - */ - public Win32ShellFolder2 getDesktop() { - return Win32ShellFolderManager2.getDesktop(); - } - - /** - * Helper function to return the desktop IShellFolder interface - */ - public cli.System.Object getDesktopIShellFolder() { - return getDesktop().getIShellFolder(); - } - - private static boolean pathsEqual(String path1, String path2) { - // Same effective implementation as Win32FileSystem - return path1.equalsIgnoreCase(path2); - } - - /** - * Check to see if two ShellFolder objects are the same - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public boolean equals(Object o) { - if (o == null || !(o instanceof Win32ShellFolder2)) { - // Short-circuit circuitous delegation path - if (!(o instanceof File)) { - return super.equals(o); - } - return pathsEqual(getPath(), ((File) o).getPath()); - } - Win32ShellFolder2 rhs = (Win32ShellFolder2) o; - if ((parent == null && rhs.parent != null) || - (parent != null && rhs.parent == null)) { - return false; - } - - if (isFileSystem() && rhs.isFileSystem()) { - // Only folders with identical parents can be equal - return (pathsEqual(getPath(), rhs.getPath()) && - (parent == rhs.parent || parent.equals(rhs.parent))); - } - - if (parent == rhs.parent || parent.equals(rhs.parent)) { - try { - return pidlsEqual(getParentIShellFolder(), disposer.relativePIDL, rhs.disposer.relativePIDL); - } catch (InterruptedException e) { - return false; - } - } - - return false; - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - static boolean pidlsEqual(final cli.System.Object pIShellFolder, final cli.System.IntPtr pidl1, final cli.System.IntPtr pidl2) - throws InterruptedException { - return invoke(new Callable<Boolean>() { - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public Boolean call() { - return compareIDs(pIShellFolder, pidl1, pidl2) == 0; - } - }, RuntimeException.class); - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native int compareIDs(cli.System.Object pParentIShellFolder, cli.System.IntPtr pidl1, cli.System.IntPtr pidl2); - - private volatile Boolean cachedIsFileSystem; - - /** - * @return Whether this is a file system shell folder - */ - public boolean isFileSystem() { - if (cachedIsFileSystem == null) { - cachedIsFileSystem = hasAttribute(ATTRIB_FILESYSTEM); - } - - return cachedIsFileSystem; - } - - /** - * Return whether the given attribute flag is set for this object - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public boolean hasAttribute(int attribute) { - // Caching at this point doesn't seem to be cost efficient - return (getAttributes0(getParentIShellFolder(), getRelativePIDL(), attribute) & attribute) != 0; - } - - /** - * Returns the queried attributes specified in attrsMask. - * - * Could plausibly be used for attribute caching but have to be - * very careful not to touch network drives and file system roots - * with a full attrsMask - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native int getAttributes0(cli.System.Object pParentIShellFolder, cli.System.IntPtr pIDL, int attrsMask); - - // Return the path to the underlying file system object - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static String getFileSystemPath(cli.System.Object parentIShellFolder, cli.System.IntPtr relativePIDL) { - int linkedFolder = ATTRIB_LINK | ATTRIB_FOLDER; - if (parentIShellFolder == Win32ShellFolderManager2.getNetwork().getIShellFolder() && - getAttributes0(parentIShellFolder, relativePIDL, linkedFolder) == linkedFolder) { - - cli.System.Object desktopIShellFolder = Win32ShellFolderManager2.getDesktop().getIShellFolder(); - String path = getDisplayNameOf(parentIShellFolder, relativePIDL, SHGDN_FORPARSING ); - String s = getFileSystemPath(desktopIShellFolder, getLinkLocation( path, false)); - if (s != null && s.startsWith("\\\\")) { - return s; - } - } - return getDisplayNameOf(parentIShellFolder, relativePIDL, SHGDN_NORMAL | SHGDN_FORPARSING); - } - - // Needs to be accessible to Win32ShellFolderManager2 - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native String getFileSystemPath(int csidl) throws IOException, InterruptedException; - - // Return whether the path is a network root. - // Path is assumed to be non-null - private static boolean isNetworkRoot(String path) { - return (path.equals("\\\\") || path.equals("\\") || path.equals("//") || path.equals("/")); - } - - /** - * @return The parent shell folder of this shell folder, null if - * there is no parent - */ - public File getParentFile() { - return parent; - } - - public boolean isDirectory() { - if (isDir == null) { - // Folders with SFGAO_BROWSABLE have "shell extension" handlers and are - // not traversable in JFileChooser. - if (hasAttribute(ATTRIB_FOLDER) && !hasAttribute(ATTRIB_BROWSABLE)) { - isDir = Boolean.TRUE; - } else if (isLink()) { - ShellFolder linkLocation = getLinkLocation(false); - isDir = Boolean.valueOf(linkLocation != null && linkLocation.isDirectory()); - } else { - isDir = Boolean.FALSE; - } - } - return isDir.booleanValue(); - } - - /* - * Functions for enumerating an IShellFolder's children - */ - // Returns an IEnumIDList interface for an IShellFolder. The value - // returned must be released using releaseEnumObjects(). - /** - * Returns an IEnumIDList interface for an IShellFolder. The value - * returned must be released using releaseEnumObjects(). - * @param pIShellFolder the IShellFolder instance of the parent shell folder - * @param includeHiddenFiles if true, hidden files will be included in the enumeration - * @return an instance of IEnumIDList - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - cli.System.Object getEnumObjects(cli.System.Object pIShellFolder, boolean includeHiddenFiles) { - boolean isDesktop = (disposer.pIShellFolder == getDesktopIShellFolder()); - return getEnumObjects(disposer.pIShellFolder, isDesktop, includeHiddenFiles); - } - - /** - * Returns an IEnumIDList interface for an IShellFolder. The value - * returned must be released using releaseEnumObjects(). - * @param pIShellFolder the IShellFolder instance of the parent shell folder - * @param isDesktop must be set to true, if the pIShellFolder is the desktop shell folder - * @param includeHiddenFiles if true, hidden files will be included in the enumeration - * @return an instance of IEnumIDList - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.Object getEnumObjects(cli.System.Object pIShellFolder, boolean isDesktop, boolean includeHiddenFiles); - - /** - * Returns the next sequential child as a relative PIDL - * from an IEnumIDList interface. The value returned must - * be released using releasePIDL(). - * @param pEnumObjects the IEnumIDList instance to get the next child from - * @return the next child or {@link IntPtr#Zero} if the end of the enumeration is reached - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native cli.System.IntPtr getNextChild(cli.System.Object pEnumObjects); - - /** - * Releases the IEnumIDList interface - * @param pEnumObjects an IEnumIDList instance - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native void releaseEnumObjects(cli.System.Object pEnumObjects); - - /** - * Returns the IShellFolder of a child from a parent IShellFolder and a relative pIDL. The pIDL - * may as well be any other descendant of the shell folder - at least this is, what the windows API - * documentation says. - * The value returned must be released using releaseIShellFolder(). - * @param parentIShellFolder an IShellFolder instance as root for the pIDL - * @param pIDL a pIDL relative to the parent shell folder - * @return a NEW instance of an IShellFolder for the path given by the pIDL, may be null if the path is invalid - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.Object bindToObject(cli.System.Object parentIShellFolder, cli.System.IntPtr pIDL); - - /** - * @return An array of shell folders that are children of this shell folder - * object. The array will be empty if the folder is empty. Returns - * <code>null</code> if this shellfolder does not denote a directory. - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public File[] listFiles(final boolean includeHiddenFiles) { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(getPath()); - } - - try { - return invoke(new Callable<File[]>() { - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public File[] call() throws InterruptedException { - if (!isDirectory()) { - return null; - } - // Links to directories are not directories and cannot be parents. - // This does not apply to folders in My Network Places (NetHood) - // because they are both links and real directories! - if (isLink() && !hasAttribute(ATTRIB_FOLDER)) { - return new File[0]; - } - - Win32ShellFolder2 desktop = Win32ShellFolderManager2.getDesktop(); - Win32ShellFolder2 personal = Win32ShellFolderManager2.getPersonal(); - - // If we are a directory, we have a parent and (at least) a - // relative PIDL. We must first ensure we are bound to the - // parent so we have an IShellFolder to query. - cli.System.Object pIShellFolder = getIShellFolder(); - // Now we can enumerate the objects in this folder. - ArrayList<Win32ShellFolder2> list = new ArrayList<Win32ShellFolder2>(); - cli.System.Object pEnumObjects = getEnumObjects(pIShellFolder, includeHiddenFiles); - if (pEnumObjects != null) { - cli.System.IntPtr childPIDL = null; - int testedAttrs = ATTRIB_FILESYSTEM | ATTRIB_FILESYSANCESTOR; - do { - if (Thread.currentThread().isInterrupted()) { - return new File[0]; - } - childPIDL = getNextChild(pEnumObjects); - boolean releasePIDL = true; - if ( childPIDL != null && !cli.System.IntPtr.Zero.Equals( childPIDL ) && (getAttributes0(pIShellFolder, childPIDL, testedAttrs) & testedAttrs) != 0) { - Win32ShellFolder2 childFolder = null; - if (this .equals(desktop) && personal != null - && pidlsEqual(pIShellFolder, childPIDL, personal.disposer.relativePIDL) ) { - childFolder = personal; - } else { - childFolder = new Win32ShellFolder2(Win32ShellFolder2.this , childPIDL); - releasePIDL = false; - } - list.add(childFolder); - } - if (releasePIDL) { - releasePIDL(childPIDL); - } - } while (childPIDL != null && !childPIDL.Equals( cli.System.IntPtr.Zero )); - releaseEnumObjects(pEnumObjects); - } - return Thread.currentThread().isInterrupted() - ? new File[0] - : list.toArray(new ShellFolder[list.size()]); - } - }, InterruptedException.class); - } catch (InterruptedException e) { - return new File[0]; - } - } - - - /** - * Look for (possibly special) child folder by it's path. Note: this will not work an an ancestor(not child) - * of the current folder. - * @return The child shell folder, or null if not found. - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - Win32ShellFolder2 getChildByPath(String filePath) { - cli.System.Object pIShellFolder = getIShellFolder(); - cli.System.Object pEnumObjects = getEnumObjects(pIShellFolder, true); - Win32ShellFolder2 child = null; - cli.System.IntPtr childPIDL = null; - - childPIDL = getNextChild(pEnumObjects); - while ( childPIDL != null && !cli.System.IntPtr.Zero.Equals( childPIDL ) ) { - if (getAttributes0(pIShellFolder, childPIDL, ATTRIB_FILESYSTEM) != 0) { - String path = getFileSystemPath(pIShellFolder, childPIDL); - if (path != null && path.equalsIgnoreCase(filePath)) { - cli.System.Object childIShellFolder = bindToObject( pIShellFolder, childPIDL); - child = new Win32ShellFolder2(this, childIShellFolder, childPIDL, path); - break; - } - } - releasePIDL(childPIDL); - childPIDL = getNextChild(pEnumObjects); - } - releaseEnumObjects(pEnumObjects); - return child; - } - - private volatile Boolean cachedIsLink; - - /** - * @return Whether this shell folder is a link - */ - public boolean isLink() { - if (cachedIsLink == null) { - cachedIsLink = hasAttribute(ATTRIB_LINK); - } - - return cachedIsLink; - } - - /** - * @return Whether this shell folder is marked as hidden - */ - public boolean isHidden() { - return hasAttribute(ATTRIB_HIDDEN); - } - - // Return the link location of a shell folder - /** - * Resolves the link location of an item to an ABSOLUTE pIDL - * @param parentIShellFolder the pointer to the parent IShellFolder of the item - * @param relativePIDL a single-level pIDL to the item - * @param resolve - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native cli.System.IntPtr getLinkLocation( String path, boolean resolve); - - /** - * @return The shell folder linked to by this shell folder, or null - * if this shell folder is not a link or is a broken or invalid link - */ - public ShellFolder getLinkLocation() { - return getLinkLocation(true); - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - private ShellFolder getLinkLocation(final boolean resolve) { - return invoke(new Callable<ShellFolder>() { - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public ShellFolder call() { - if (!isLink()) { - return null; - } - - ShellFolder location = null; - cli.System.IntPtr linkLocationPIDL = getLinkLocation( getAbsolutePath(), resolve); - if (linkLocationPIDL != null && !cli.System.IntPtr.Zero.Equals( linkLocationPIDL ) ) { - try { - location = - Win32ShellFolderManager2.createShellFolderFromRelativePIDL(getDesktop(), - linkLocationPIDL); - } catch (InterruptedException e) { - // Return null - } catch (InternalError e) { - // Could be a link to a non-bindable object, such as a network connection - // TODO: getIShellFolder() should throw FileNotFoundException instead - } - } - return location; - } - }); - } - - /** - * Parse a display name into a PIDL relative to the current IShellFolder. - * @param name the name or relative path - * @return a pIDL for the path, may be {@link IntPtr#Zero} if not found - * @throws FileNotFoundException - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - cli.System.IntPtr parseDisplayName(String name) throws FileNotFoundException { - try { - return parseDisplayName0(getIShellFolder(), name); - } catch (IOException e) { - throw new FileNotFoundException("Could not find file " + name); - } - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.IntPtr parseDisplayName0(cli.System.Object pIShellFolder, String name) throws IOException; - - /** - * Returns the display name of an item in a folder - * @param parentIShellFolder the pointer to the IShellFolder interface of the parent folder - * @param relativePIDL single-level pIDL to the requested item within the parent folder - * @param attrs formatting attributes for the display name, refer to SHGDN in MSDN - * @return - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native String getDisplayNameOf( cli.System.Object parentIShellFolder, cli.System.IntPtr relativePIDL, int attrs); - - /** - * @return The name used to display this shell folder - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public String getDisplayName() { - if (displayName == null) { - displayName = getDisplayNameOf(getParentIShellFolder(), getRelativePIDL(), SHGDN_NORMAL); - } - return displayName; - } - - // Return the folder type of a shell folder - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native String getFolderType(cli.System.IntPtr pIDL); - - /** - * @return The type of shell folder as a string - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public String getFolderType() { - if (folderType == null) { - folderType = getFolderType(getAbsolutePIDL()); - } - return folderType; - } - - // Return the executable type of a file system shell folder - private static native String getExecutableType(String path); - - /** - * @return The executable type as a string - */ - public String getExecutableType() { - if (!isFileSystem()) { - return null; - } - return getExecutableType(getAbsolutePath()); - } - - // Icons - - private static Map smallSystemImages = new HashMap(); - private static Map largeSystemImages = new HashMap(); - private static Map smallLinkedSystemImages = new HashMap(); - private static Map largeLinkedSystemImages = new HashMap(); - - /** - * Returns the icon index in the system image list - * @param parentIShellIcon the the pointer to the IShellIcon instance of the parent folder - * @param relativePIDL the relative pIDL to the requested item - * @return the system image list index for the icon of the item or zero, if there is no entry - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native int getIconIndex(cli.System.Object parentIShellFolder, cli.System.IntPtr relativePIDL); - - // Return the icon of a file system shell folder in the form of an HICON - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.IntPtr getIcon(String absolutePath, boolean getLargeIcon); - - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.IntPtr extractIcon(cli.System.Object parentIShellFolder, cli.System.IntPtr relativePIDL, - boolean getLargeIcon); - - /** - * Returns the {@link Bitmap} for a HICON. - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native Bitmap getIconBits(cli.System.IntPtr hIcon, int size); - - /** - * Disposes a icon handle - * @param hIcon the handle to be disposed - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native void disposeIcon(cli.System.IntPtr hIcon); - - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native Bitmap getStandardViewButton0(int iconIndex); - - /** - * Creates a Java icon for a HICON pointer - * @param hIcon the handle for the icon - * @param getLargeIcon true for a large icon, false for a small icon - * @return the created image or null, if the handle is invalid - */ - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static Image makeIcon(cli.System.IntPtr hIcon, boolean getLargeIcon) { - if (hIcon != null ) { - // Get the bits. This has the side effect of setting the imageHash value for this object. - Bitmap bitmap = getIconBits(hIcon, getLargeIcon ? 32 : 16 ); - if (bitmap == null) { - return null; - } - return new BufferedImage(bitmap); - } - return null; - } - - - /** - * @return The icon image used to display this shell folder - */ - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public Image getIcon(boolean getLargeIcon) { - Image icon = getLargeIcon ? largeIcon : smallIcon; - if (icon == null) { - cli.System.IntPtr relativePIDL = getRelativePIDL(); - - if (isFileSystem() && parent != null) { - // These are cached per type (using the index in the system image list) - int index = getIconIndex( ((Win32ShellFolder2)parent).getIShellFolder(), relativePIDL); - if (index > 0) { - Map imageCache; - if (isLink()) { - imageCache = getLargeIcon ? largeLinkedSystemImages : smallLinkedSystemImages; - } else { - imageCache = getLargeIcon ? largeSystemImages : smallSystemImages; - } - icon = (Image) imageCache.get(Integer.valueOf(index)); - if (icon == null) { - cli.System.IntPtr hIcon = getIcon(getAbsolutePath(), getLargeIcon); - icon = makeIcon(hIcon, getLargeIcon); - disposeIcon(hIcon); - if (icon != null) { - imageCache.put(Integer.valueOf(index), icon); - } - } - } - } - - if (icon == null) { - // These are only cached per object - cli.System.IntPtr hIcon = extractIcon(getParentIShellFolder(), getRelativePIDL(), getLargeIcon); - icon = makeIcon(hIcon, getLargeIcon); - disposeIcon(hIcon); - } - - if (getLargeIcon) { - largeIcon = icon; - } else { - smallIcon = icon; - } - } - if (icon == null) { - icon = super .getIcon(getLargeIcon); - } - return icon; - } - - /** - * Gets an icon from the Windows system icon list as an <code>Image</code> - */ - static Image getShell32Icon(int iconID, boolean getLargeIcon) { - Bitmap bitmap = getShell32IconResourceAsBitmap(iconID, getLargeIcon); - if (bitmap == null) { - return null; - } - return new BufferedImage(bitmap); - } - - private static native Bitmap getShell32IconResourceAsBitmap(int iconID, boolean getLargeIcon); - - /** - * Returns the canonical form of this abstract pathname. Equivalent to - * <code>new Win32ShellFolder2(getParentFile(), this.{@link java.io.File#getCanonicalPath}())</code>. - * - * @see java.io.File#getCanonicalFile - */ - public File getCanonicalFile() throws IOException { - return this; - } - - /* - * Indicates whether this is a special folder (includes My Documents) - */ - public boolean isSpecial() { - return isPersonal || !isFileSystem() || (this == getDesktop()); - } - - /** - * Compares this object with the specified object for order. - * - * @see sun.awt.shell.ShellFolder#compareTo(File) - */ - public int compareTo(File file2) { - if (!(file2 instanceof Win32ShellFolder2)) { - if (isFileSystem() && !isSpecial()) { - return super.compareTo(file2); - } else { - return -1; // Non-file shellfolders sort before files - } - } - return Win32ShellFolderManager2.compareShellFolders(this, (Win32ShellFolder2) file2); - } - - // native constants from commctrl.h - private static final int LVCFMT_LEFT = 0; - private static final int LVCFMT_RIGHT = 1; - private static final int LVCFMT_CENTER = 2; - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public ShellFolderColumnInfo[] getFolderColumns() { - Object o = doGetColumnInfo(getIShellFolder()); - ShellFolderColumnInfo[] columns = (ShellFolderColumnInfo[]) o; - - if (columns != null) { - List<ShellFolderColumnInfo> notNullColumns = new ArrayList<ShellFolderColumnInfo>(); - for (int i = 0; i < columns.length; i++) { - ShellFolderColumnInfo column = columns[i]; - if (column != null) { - column.setAlignment(column.getAlignment() == LVCFMT_RIGHT ? SwingConstants.RIGHT - : column.getAlignment() == LVCFMT_CENTER ? SwingConstants.CENTER - : SwingConstants.LEADING); - - column.setComparator(new ColumnComparator(i)); - - notNullColumns.add(column); - } - } - columns = new ShellFolderColumnInfo[notNullColumns.size()]; - notNullColumns.toArray(columns); - } - return columns; - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public Object getFolderColumnValue(int column) { - return doGetColumnValue(getParentIShellFolder(), getRelativePIDL(), column); - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native cli.System.Object /*ShellFolderColumnInfo[]*/ doGetColumnInfo( cli.System.Object iShellFolder2 ); - - @cli.System.Security.SecurityCriticalAttribute.Annotation - private static native Object doGetColumnValue(cli.System.Object parentIShellFolder2, cli.System.IntPtr childPIDL, int columnIdx); - - @cli.System.Security.SecurityCriticalAttribute.Annotation - static native int compareIDsByColumn(cli.System.Object pParentIShellFolder, cli.System.IntPtr pidl1, cli.System.IntPtr pidl2, int columnIdx); - - private class ColumnComparator implements Comparator { - private final int columnIdx; - - public ColumnComparator(int columnIdx) { - this.columnIdx = columnIdx; - } - - // compares 2 objects within this folder by the specified column - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - public int compare(Object o, Object o1) { - if (o instanceof Win32ShellFolder2 && o1 instanceof Win32ShellFolder2) { - // delegates comparison to native method - return compareIDsByColumn(getIShellFolder(), - ((Win32ShellFolder2) o).getRelativePIDL(), - ((Win32ShellFolder2) o1).getRelativePIDL(), - columnIdx); - } - return 0; - } - } -}
\ No newline at end of file diff --git a/openjdk/sun/awt/shell/Win32ShellFolderManager2.java b/openjdk/sun/awt/shell/Win32ShellFolderManager2.java deleted file mode 100644 index d688b6a0..00000000 --- a/openjdk/sun/awt/shell/Win32ShellFolderManager2.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * 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 - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.awt.shell; - -import java.awt.*; -import java.awt.image.BufferedImage; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.*; -import java.util.List; -import java.util.concurrent.*; - -import cli.System.IntPtr; -import cli.System.Drawing.Bitmap; -import cli.System.Drawing.SystemIcons; -import sun.security.action.LoadLibraryAction; - -import static sun.awt.shell.Win32ShellFolder2.*; -import sun.awt.OSInfo; - -// NOTE: This class supersedes Win32ShellFolderManager, which was removed -// from distribution after version 1.4.2. - -/** - * @author Michael Martak - * @author Leif Samuelsson - * @author Kenneth Russell - * @since 1.4 - */ - -public class Win32ShellFolderManager2 extends ShellFolderManager { - - - public ShellFolder createShellFolder(File file) throws FileNotFoundException { - try { - return createShellFolder(getDesktop(), file); - } catch (InterruptedException e) { - throw new FileNotFoundException("Execution was interrupted"); - } - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - static Win32ShellFolder2 createShellFolder(Win32ShellFolder2 parent, File file) - throws FileNotFoundException, InterruptedException { - cli.System.IntPtr pIDL = null; - try { - pIDL = parent.parseDisplayName(file.getCanonicalPath()); - } catch (IOException ex) { - pIDL = null; - } - if (pIDL == null || cli.System.IntPtr.Zero.Equals(pIDL) ) { - // Shouldn't happen but watch for it anyway - throw new FileNotFoundException("File " + file.getAbsolutePath() + " not found"); - } - - try { - return createShellFolderFromRelativePIDL(parent, pIDL); - } finally { - Win32ShellFolder2.releasePIDL(pIDL); - } - } - - @cli.System.Security.SecurityCriticalAttribute.Annotation - static Win32ShellFolder2 createShellFolderFromRelativePIDL(Win32ShellFolder2 parent, cli.System.IntPtr pIDL) - throws InterruptedException { - // Walk down this relative pIDL, creating new nodes for each of the entries - while (pIDL != null && !cli.System.IntPtr.Zero.Equals( pIDL ) ) { - cli.System.IntPtr curPIDL = Win32ShellFolder2.copyFirstPIDLEntry(pIDL); - if (curPIDL != null && !cli.System.IntPtr.Zero.Equals( curPIDL )) { - parent = new Win32ShellFolder2(parent, curPIDL); - pIDL = Win32ShellFolder2.getNextPIDLEntry(pIDL); - } else { - // The list is empty if the parent is Desktop and pIDL is a shortcut to Desktop - break; - } - } - return parent; - } - - private static final int VIEW_LIST = 2; - private static final int VIEW_DETAILS = 3; - private static final int VIEW_PARENTFOLDER = 8; - private static final int VIEW_NEWFOLDER = 11; - - private static final Image[] STANDARD_VIEW_BUTTONS = new Image[12]; - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - private static Image getStandardViewButton(int iconIndex) { - Image result = STANDARD_VIEW_BUTTONS[iconIndex]; - - if (result != null) { - return result; - } - - Bitmap bitmap = Win32ShellFolder2.getStandardViewButton0(iconIndex); - if( bitmap != null ) { - result = new BufferedImage(bitmap); - STANDARD_VIEW_BUTTONS[iconIndex] = result; - } - - return result; - } - - // Special folders - private static Win32ShellFolder2 desktop; - private static Win32ShellFolder2 drives; - private static Win32ShellFolder2 recent; - private static Win32ShellFolder2 network; - private static Win32ShellFolder2 personal; - - static Win32ShellFolder2 getDesktop() { - if (desktop == null) { - try { - desktop = new Win32ShellFolder2(DESKTOP); - } catch (IOException e) { - // Ignore error - } catch (InterruptedException e) { - // Ignore error - } - } - return desktop; - } - - static Win32ShellFolder2 getDrives() { - if (drives == null) { - try { - drives = new Win32ShellFolder2(DRIVES); - } catch (IOException e) { - // Ignore error - } catch (InterruptedException e) { - // Ignore error - } - } - return drives; - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - static Win32ShellFolder2 getRecent() { - if (recent == null) { - try { - String path = Win32ShellFolder2.getFileSystemPath(RECENT); - if (path != null) { - recent = createShellFolder(getDesktop(), new File(path)); - } - } catch (InterruptedException e) { - // Ignore error - } catch (IOException e) { - // Ignore error - } - } - return recent; - } - - static Win32ShellFolder2 getNetwork() { - if (network == null) { - try { - network = new Win32ShellFolder2(NETWORK); - } catch (IOException e) { - // Ignore error - } catch (InterruptedException e) { - // Ignore error - } - } - return network; - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - static Win32ShellFolder2 getPersonal() { - if (personal == null) { - try { - String path = Win32ShellFolder2.getFileSystemPath(PERSONAL); - if (path != null) { - Win32ShellFolder2 desktop = getDesktop(); - personal = desktop.getChildByPath(path); - if (personal == null) { - personal = createShellFolder(getDesktop(), new File(path)); - } - if (personal != null) { - personal.setIsPersonal(); - } - } - } catch (InterruptedException e) { - // Ignore error - } catch (IOException e) { - // Ignore error - } - } - return personal; - } - - - private static File[] roots; - - /** - * @param key a <code>String</code> - * "fileChooserDefaultFolder": - * Returns a <code>File</code> - the default shellfolder for a new filechooser - * "roots": - * Returns a <code>File[]</code> - containing the root(s) of the displayable hierarchy - * "fileChooserComboBoxFolders": - * Returns a <code>File[]</code> - an array of shellfolders representing the list to - * show by default in the file chooser's combobox - * "fileChooserShortcutPanelFolders": - * Returns a <code>File[]</code> - an array of shellfolders representing well-known - * folders, such as Desktop, Documents, History, Network, Home, etc. - * This is used in the shortcut panel of the filechooser on Windows 2000 - * and Windows Me. - * "fileChooserIcon <icon>": - * Returns an <code>Image</code> - icon can be ListView, DetailsView, UpFolder, NewFolder or - * ViewMenu (Windows only). - * "optionPaneIcon iconName": - * Returns an <code>Image</code> - icon from the system icon list - * - * @return An Object matching the key string. - */ - public Object get(String key) { - if (key.equals("fileChooserDefaultFolder")) { - File file = getPersonal(); - if (file == null) { - file = getDesktop(); - } - return file; - } else if (key.equals("roots")) { - // Should be "History" and "Desktop" ? - if (roots == null) { - File desktop = getDesktop(); - if (desktop != null) { - roots = new File[] { desktop }; - } else { - roots = (File[])super.get(key); - } - } - return roots; - } else if (key.equals("fileChooserComboBoxFolders")) { - Win32ShellFolder2 desktop = getDesktop(); - - if (desktop != null) { - ArrayList<File> folders = new ArrayList<File>(); - Win32ShellFolder2 drives = getDrives(); - - Win32ShellFolder2 recentFolder = getRecent(); - if (recentFolder != null && OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_2000) >= 0) { - folders.add(recentFolder); - } - - folders.add(desktop); - // Add all second level folders - File[] secondLevelFolders = desktop.listFiles(); - Arrays.sort(secondLevelFolders); - for (File secondLevelFolder : secondLevelFolders) { - Win32ShellFolder2 folder = (Win32ShellFolder2) secondLevelFolder; - if (!folder.isFileSystem() || (folder.isDirectory() && !folder.isLink()) ) { - folders.add(folder); - // Add third level for "My Computer" - if (folder.equals(drives)) { - File[] thirdLevelFolders = folder.listFiles(); - if (thirdLevelFolders != null && thirdLevelFolders.length > 0) { - List<File> thirdLevelFoldersList = Arrays.asList(thirdLevelFolders); - - folder.sortChildren(thirdLevelFoldersList); - folders.addAll(thirdLevelFoldersList); - } - } - } - } - return folders.toArray(new File[folders.size()]); - } else { - return super.get(key); - } - } else if (key.equals("fileChooserShortcutPanelFolders")) { - Toolkit toolkit = Toolkit.getDefaultToolkit(); - ArrayList<File> folders = new ArrayList<File>(); - int i = 0; - Object value; - do { - value = toolkit.getDesktopProperty("win.comdlg.placesBarPlace" + i++); - try { - if (value instanceof Integer) { - // A CSIDL - folders.add(new Win32ShellFolder2((Integer)value)); - } else if (value instanceof String) { - // A path - folders.add(createShellFolder(new File((String)value))); - } - } catch (IOException e) { - // Skip this value - } catch (InterruptedException e) { - // Return empty result - return new File[0]; - } - } while (value != null); - - if (folders.size() == 0) { - // Use default list of places - for (File f : new File[] { - getRecent(), getDesktop(), getPersonal(), getDrives(), getNetwork() - }) { - if (f != null) { - folders.add(f); - } - } - } - return folders.toArray(new File[folders.size()]); - } else if (key.startsWith("fileChooserIcon ")) { - String name = key.substring(key.indexOf(" ") + 1); - - int iconIndex; - - if (name.equals("ListView") || name.equals("ViewMenu")) { - iconIndex = VIEW_LIST; - } else if (name.equals("DetailsView")) { - iconIndex = VIEW_DETAILS; - } else if (name.equals("UpFolder")) { - iconIndex = VIEW_PARENTFOLDER; - } else if (name.equals("NewFolder")) { - iconIndex = VIEW_NEWFOLDER; - } else { - return null; - } - - return getStandardViewButton(iconIndex); - } else if (key.startsWith("optionPaneIcon ")) { - cli.System.Drawing.Icon icon; - if (key == "optionPaneIcon Error") { - icon = SystemIcons.get_Error(); - } else if (key == "optionPaneIcon Information") { - icon = SystemIcons.get_Information(); - } else if (key == "optionPaneIcon Question") { - icon = SystemIcons.get_Question(); - } else if (key == "optionPaneIcon Warning") { - icon = SystemIcons.get_Warning(); - } else { - return null; - } - return new BufferedImage(icon.ToBitmap()); - } else if (key.startsWith("shell32Icon ") || key.startsWith("shell32LargeIcon ")) { - String name = key.substring(key.indexOf(" ") + 1); - try { - int i = Integer.parseInt(name); - if (i >= 0) { - return Win32ShellFolder2.getShell32Icon(i, key.startsWith("shell32LargeIcon ")); - } - } catch (NumberFormatException ex) { - } - } - return null; - } - - /** - * Does <code>dir</code> represent a "computer" such as a node on the network, or - * "My Computer" on the desktop. - */ - public boolean isComputerNode(final File dir) { - if (dir != null && dir == getDrives()) { - return true; - } else { - String path = AccessController.doPrivileged(new PrivilegedAction<String>() { - public String run() { - return dir.getAbsolutePath(); - } - }); - - return (path.startsWith("\\\\") && path.indexOf("\\", 2) < 0); //Network path - } - } - - public boolean isFileSystemRoot(File dir) { - //Note: Removable drives don't "exist" but are listed in "My Computer" - if (dir != null) { - Win32ShellFolder2 drives = getDrives(); - if (dir instanceof Win32ShellFolder2) { - Win32ShellFolder2 sf = (Win32ShellFolder2)dir; - if (sf.isFileSystem()) { - if (sf.parent != null) { - return sf.parent.equals(drives); - } - // else fall through ... - } else { - return false; - } - } - String path = dir.getPath(); - - if (path.length() != 3 || path.charAt(1) != ':') { - return false; - } - - File[] files = drives.listFiles(); - - return files != null && Arrays.asList(files).contains(dir); - } - return false; - } - - private static List topFolderList = null; - static int compareShellFolders(Win32ShellFolder2 sf1, Win32ShellFolder2 sf2) { - boolean special1 = sf1.isSpecial(); - boolean special2 = sf2.isSpecial(); - - if (special1 || special2) { - if (topFolderList == null) { - ArrayList tmpTopFolderList = new ArrayList(); - tmpTopFolderList.add(Win32ShellFolderManager2.getPersonal()); - tmpTopFolderList.add(Win32ShellFolderManager2.getDesktop()); - tmpTopFolderList.add(Win32ShellFolderManager2.getDrives()); - tmpTopFolderList.add(Win32ShellFolderManager2.getNetwork()); - topFolderList = tmpTopFolderList; - } - int i1 = topFolderList.indexOf(sf1); - int i2 = topFolderList.indexOf(sf2); - if (i1 >= 0 && i2 >= 0) { - return (i1 - i2); - } else if (i1 >= 0) { - return -1; - } else if (i2 >= 0) { - return 1; - } - } - - // Non-file shellfolders sort before files - if (special1 && !special2) { - return -1; - } else if (special2 && !special1) { - return 1; - } - - return compareNames(sf1.getAbsolutePath(), sf2.getAbsolutePath()); - } - - static int compareNames(String name1, String name2) { - // First ignore case when comparing - int diff = name1.compareToIgnoreCase(name2); - if (diff != 0) { - return diff; - } else { - // May differ in case (e.g. "mail" vs. "Mail") - // We need this test for consistent sorting - return name1.compareTo(name2); - } - } -} diff --git a/openjdk/sun/awt/windows/WPrinterJob.java b/openjdk/sun/awt/windows/WPrinterJob.java deleted file mode 100644 index 08756efd..00000000 --- a/openjdk/sun/awt/windows/WPrinterJob.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.awt.windows; - -import ikvm.awt.IkvmToolkit; - -import java.awt.Graphics; -import java.awt.HeadlessException; -import java.awt.Toolkit; -import java.awt.image.BufferedImage; -import java.awt.print.PageFormat; -import java.awt.print.Pageable; -import java.awt.print.Paper; -import java.awt.print.Printable; -import java.awt.print.PrinterException; -import java.awt.print.PrinterJob; - -import javax.print.PrintService; -import javax.print.attribute.PrintRequestAttributeSet; - -import cli.System.Drawing.Printing.*; - -import sun.print.PeekGraphics; -import sun.print.PrintPeer; -import sun.print.RasterPrinterJob; -import sun.print.Win32PrintService; - -import ikvm.internal.NotYetImplementedError; - -/** - * @author Volker Berlin - */ -public class WPrinterJob extends RasterPrinterJob{ - - @Override - protected void abortDoc(){ - throw new NotYetImplementedError(); - } - - @Override - protected void endDoc() throws PrinterException{ - throw new NotYetImplementedError(); - } - - @Override - protected void endPage(PageFormat format, Printable painter, int index) throws PrinterException{ - throw new NotYetImplementedError(); - } - - @Override - protected double getPhysicalPageHeight(Paper p){ - throw new NotYetImplementedError(); - } - - @Override - protected double getPhysicalPageWidth(Paper p){ - throw new NotYetImplementedError(); - } - - @Override - protected double getPhysicalPrintableHeight(Paper p){ - throw new NotYetImplementedError(); - } - - @Override - protected double getPhysicalPrintableWidth(Paper p){ - throw new NotYetImplementedError(); - } - - @Override - protected double getPhysicalPrintableX(Paper p){ - throw new NotYetImplementedError(); - } - - @Override - protected double getPhysicalPrintableY(Paper p){ - throw new NotYetImplementedError(); - } - - @Override - protected double getXRes(){ - throw new NotYetImplementedError(); - } - - @Override - protected double getYRes(){ - throw new NotYetImplementedError(); - } - - @Override - protected void printBand(byte[] data, int x, int y, int width, int height) throws PrinterException{ - throw new NotYetImplementedError(); - } - - @Override - protected void startDoc() throws PrinterException{ - throw new NotYetImplementedError(); - } - - @Override - protected void startPage(PageFormat format, Printable painter, int index, boolean paperChanged) - throws PrinterException{ - throw new NotYetImplementedError(); - } -} diff --git a/openjdk/sun/font/CompositeFont.java b/openjdk/sun/font/CompositeFont.java deleted file mode 100644 index ba4c59ff..00000000 --- a/openjdk/sun/font/CompositeFont.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import java.awt.font.FontRenderContext; -import java.awt.geom.AffineTransform; -import java.util.Locale; - -import cli.System.Drawing.Font; -import ikvm.internal.NotYetImplementedError; - - -/** - * - */ -public class CompositeFont extends Font2D{ - - private final PhysicalFont delegate; - - - public CompositeFont(PhysicalFont physicalFont, CompositeFont dialog2d) { - delegate = physicalFont; - } - - public CompositeFont(Font2D font2d){ - delegate = (PhysicalFont)font2d; - } - - public int getNumSlots() { - throw new NotYetImplementedError(); - } - - public PhysicalFont getSlotFont(int slot) { - if( slot == 0){ - return delegate; - } - throw new NotYetImplementedError(); - } - - public boolean isStdComposite() { - throw new NotYetImplementedError(); - } - - @Override - public int getStyle(){ - return delegate.getStyle(); - } - - @Override - public Font createNetFont(java.awt.Font font){ - return delegate.createNetFont(font); - } - - public FontStrike getStrike(java.awt.Font font, AffineTransform devTx, - int aa, int fm) { - return delegate.getStrike(font, devTx, aa, fm); - } - - public FontStrike getStrike(java.awt.Font font, FontRenderContext frc) { - return delegate.getStrike(font, frc); - } - - public void removeFromCache(FontStrikeDesc desc) { - delegate.removeFromCache(desc); - } - - public void getFontMetrics(java.awt.Font font, AffineTransform identityTx, - Object antiAliasingHint, Object fractionalMetricsHint, - float[] metrics) { - delegate.getFontMetrics(font, identityTx, antiAliasingHint, - fractionalMetricsHint, metrics); - } - - public void getStyleMetrics(float pointSize, float[] metrics, int offset) { - delegate.getStyleMetrics(pointSize, metrics, offset); - } - - public void getFontMetrics(java.awt.Font font, FontRenderContext frc, - float[] metrics) { - delegate.getFontMetrics(font, frc, metrics); - } - - public boolean useAAForPtSize(int ptsize) { - return delegate.useAAForPtSize(ptsize); - } - - public boolean hasSupplementaryChars() { - return delegate.hasSupplementaryChars(); - } - - public String getPostscriptName() { - return delegate.getPostscriptName(); - } - - public String getFontName(Locale l) { - return delegate.getFontName(l); - } - - public String getFamilyName(Locale l) { - return delegate.getFamilyName(l); - } - - public int getNumGlyphs() { - return delegate.getNumGlyphs(); - } - - public int charToGlyph(int wchar) { - return delegate.charToGlyph(wchar); - } - - public int getMissingGlyphCode() { - return delegate.getMissingGlyphCode(); - } - - public boolean canDisplay(char c) { - return delegate.canDisplay(c); - } - - public boolean canDisplay(int cp) { - return delegate.canDisplay(cp); - } - - public byte getBaselineFor(char c) { - return delegate.getBaselineFor(c); - } - - public float getItalicAngle(java.awt.Font font, AffineTransform at, - Object aaHint, Object fmHint) { - return delegate.getItalicAngle(font, at, aaHint, fmHint); - } -} diff --git a/openjdk/sun/font/Font2D.java b/openjdk/sun/font/Font2D.java deleted file mode 100644 index 7fc9eda0..00000000 --- a/openjdk/sun/font/Font2D.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import java.awt.Font; -import java.awt.font.FontRenderContext; -import java.awt.geom.AffineTransform; -import java.util.Locale; - -import sun.awt.SunHints; - - - -/** - * - */ -public abstract class Font2D{ - - public Font2DHandle handle = new Font2DHandle(this); - - /* SunGraphics2D has font, tx, aa and fm. From this info - * can get a Strike object from the cache, creating it if necessary. - * This code is designed for multi-threaded access. - * For that reason it creates a local FontStrikeDesc rather than filling - * in a shared one. Up to two AffineTransforms and one FontStrikeDesc will - * be created by every lookup. This appears to perform more than - * adequately. But it may make sense to expose FontStrikeDesc - * as a parameter so a caller can use its own. - * In such a case if a FontStrikeDesc is stored as a key then - * we would need to use a private copy. - * - * Note that this code doesn't prevent two threads from creating - * two different FontStrike instances and having one of the threads - * overwrite the other in the map. This is likely to be a rare - * occurrence and the only consequence is that these callers will have - * different instances of the strike, and there'd be some duplication of - * population of the strikes. However since users of these strikes are - * transient, then the one that was overwritten would soon be freed. - * If there is any problem then a small synchronized block would be - * required with its attendant consequences for MP scalability. - */ - public FontStrike getStrike(Font font, AffineTransform devTx, int aa, int fm){ - return getStrike(font, new FontRenderContext(devTx, aa == SunHints.INTVAL_TEXT_ANTIALIAS_ON, - fm == SunHints.INTVAL_FRACTIONALMETRICS_ON)); - } - - public FontStrike getStrike(Font font, FontRenderContext frc) { - // TODO Auto-generated method stub - return null; - } - - public void removeFromCache(FontStrikeDesc desc){ - // TODO Auto-generated method stub - - } - - /** - * The length of the metrics array must be >= 8. This method will - * store the following elements in that array before returning: - * metrics[0]: ascent - * metrics[1]: descent - * metrics[2]: leading - * metrics[3]: max advance - * metrics[4]: strikethrough offset - * metrics[5]: strikethrough thickness - * metrics[6]: underline offset - * metrics[7]: underline thickness - */ - public void getFontMetrics(Font font, AffineTransform identityTx, Object antiAliasingHint, - Object fractionalMetricsHint, float[] metrics){ - FontRenderContext frc = new FontRenderContext(identityTx, antiAliasingHint, fractionalMetricsHint); - StrikeMetrics strikeMetrics = getStrike(font, frc).getFontMetrics(); - metrics[0] = strikeMetrics.getAscent(); - metrics[1] = strikeMetrics.getDescent(); - metrics[2] = strikeMetrics.getLeading(); - metrics[3] = strikeMetrics.getMaxAdvance(); - - getStyleMetrics(font.getSize2D(), metrics, 4); - } - - /** - * The length of the metrics array must be >= offset+4, and offset must be - * >= 0. Typically offset is 4. This method will - * store the following elements in that array before returning: - * metrics[off+0]: strikethrough offset - * metrics[off+1]: strikethrough thickness - * metrics[off+2]: underline offset - * metrics[off+3]: underline thickness - * - * Note that this implementation simply returns default values; - * subclasses can override this method to provide more accurate values. - */ - public void getStyleMetrics(float pointSize, float[] metrics, int offset) { - metrics[offset] = -metrics[0] / 2.5f; - metrics[offset+1] = pointSize / 12; - metrics[offset+2] = metrics[offset+1] / 1.5f; - metrics[offset+3] = metrics[offset+1]; - } - - /** - * The length of the metrics array must be >= 4. This method will - * store the following elements in that array before returning: - * metrics[0]: ascent - * metrics[1]: descent - * metrics[2]: leading - * metrics[3]: max advance - */ - public void getFontMetrics(Font font, FontRenderContext frc, - float metrics[]) { - StrikeMetrics strikeMetrics = getStrike(font, frc).getFontMetrics(); - metrics[0] = strikeMetrics.getAscent(); - metrics[1] = strikeMetrics.getDescent(); - metrics[2] = strikeMetrics.getLeading(); - metrics[3] = strikeMetrics.getMaxAdvance(); - } - - /* - * All the important subclasses override this which is principally for - * the TrueType 'gasp' table. - */ - public boolean useAAForPtSize(int ptsize) { - return true; - } - - public boolean hasSupplementaryChars() { - return false; - } - - /* The following methods implement public methods on java.awt.Font */ - public String getPostscriptName(){ - // TODO Auto-generated method stub - return null; - } - - public String getFontName(Locale l){ - // TODO Auto-generated method stub - return null; - } - - public String getFamilyName(Locale l){ - // TODO Auto-generated method stub - return null; - } - - public int getNumGlyphs(){ - // TODO Auto-generated method stub - return 0; - } - - public int charToGlyph(int wchar) { - return wchar; - } - - public int getMissingGlyphCode(){ - // TODO Auto-generated method stub - return 0; - } - - public boolean canDisplay(char c){ - //HACK There is no equivalent in C# http://msdn2.microsoft.com/en-us/library/sf4dhbw8(VS.80).aspx - return true; - } - - public boolean canDisplay(int cp){ - //HACK There is no equivalent in C# http://msdn2.microsoft.com/en-us/library/sf4dhbw8(VS.80).aspx - return true; - } - - public byte getBaselineFor(char c) { - return Font.ROMAN_BASELINE; - } - - public float getItalicAngle(Font font, AffineTransform at, - Object aaHint, Object fmHint) { - /* hardwire psz=12 as that's typical and AA vs non-AA for 'gasp' mode - * isn't important for the caret slope of this rarely used API. - */ - int aa = FontStrikeDesc.getAAHintIntVal(aaHint, this, 12); - int fm = FontStrikeDesc.getFMHintIntVal(fmHint); - FontStrike strike = getStrike(font, at, aa, fm); - StrikeMetrics metrics = strike.getFontMetrics(); - if (metrics.ascentY == 0 || metrics.ascentX == 0) { - return 0f; - } else { - /* ascent is "up" from the baseline so its typically - * a negative value, so we need to compensate - */ - return metrics.ascentX/-metrics.ascentY; - } - } - - /** Returns the "real" style of this Font2D. Eg the font face - * Lucida Sans Bold" has a real style of Font.BOLD, even though - * it may be able to used to simulate bold italic - */ - public abstract int getStyle(); - - public abstract cli.System.Drawing.Font createNetFont(Font font); - -} diff --git a/openjdk/sun/font/FontManager.java b/openjdk/sun/font/FontManager.java deleted file mode 100644 index 3f02cf06..00000000 --- a/openjdk/sun/font/FontManager.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. - * Copyright (C) 2009 - 2011 Volker Berlin (i-net software) - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.font; - -import java.awt.Font; -import java.lang.reflect.Method; -import java.util.Locale; -import java.util.concurrent.ConcurrentHashMap; - -import javax.swing.plaf.FontUIResource; - -import cli.System.Drawing.FontFamily; -import ikvm.internal.NotYetImplementedError; - -/* - * Interface between Java Fonts (java.awt.Font) and the underlying - * font files/native font resources and the Java and native font scalers. - */ -public final class FontManager { - - public static final int NO_FALLBACK = 0; - public static final int PHYSICAL_FALLBACK = 1; - public static final int LOGICAL_FALLBACK = 2; - - /* deprecated, unsupported hack - actually invokes a bug! */ - private static boolean usePlatformFontMetrics = false; - - private static ConcurrentHashMap<String, Font2D> fontNameCache = new ConcurrentHashMap<String, Font2D>(); - - private static final Method getFont2D; - static{ - try{ - getFont2D = Font.class.getDeclaredMethod("getFont2D"); - getFont2D.setAccessible(true); - }catch(NoSuchMethodException ex){ - NoClassDefFoundError error = new NoClassDefFoundError(ex.toString()); - error.initCause(ex); - throw error; - } - } - - /* Revise the implementation to in fact mean "font is a composite font. - * This ensures that Swing components will always benefit from the - * fall back fonts - */ - public static boolean fontSupportsDefaultEncoding(Font font) { - // In Java the font must be a instanceof CompositeFont - // because .NET fonts are all already Composite Fonts (I think) that we can return true - // and does not need to implements CompositeFont - return true; - } - - /** - * This method is provided for internal and exclusive use by Swing. - * - * It may be used in conjunction with fontSupportsDefaultEncoding(Font) - * In the event that a desktop properties font doesn't directly - * support the default encoding, (ie because the host OS supports - * adding support for the current locale automatically for native apps), - * then Swing calls this method to get a font which uses the specified - * font for the code points it covers, but also supports this locale - * just as the standard composite fonts do. - * Note: this will over-ride any setting where an application - * specifies it prefers locale specific composite fonts. - * The logic for this, is that this method is used only where the user or - * application has specified that the native L&F be used, and that - * we should honour that request to use the same font as native apps use. - * - * The behaviour of this method is to construct a new composite - * Font object that uses the specified physical font as its first - * component, and adds all the components of "dialog" as fall back - * components. - * The method currently assumes that only the size and style attributes - * are set on the specified font. It doesn't copy the font transform or - * other attributes because they aren't set on a font created from - * the desktop. This will need to be fixed if use is broadened. - * - * Operations such as Font.deriveFont will work properly on the - * font returned by this method for deriving a different point size. - * Additionally it tries to support a different style by calling - * getNewComposite() below. That also supports replacing slot zero - * with a different physical font but that is expected to be "rare". - * Deriving with a different style is needed because its been shown - * that some applications try to do this for Swing FontUIResources. - * Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14); - * will NOT yield the same result, as the new underlying CompositeFont - * cannot be "looked up" in the font registry. - * This returns a FontUIResource as that is the Font sub-class needed - * by Swing. - * Suggested usage is something like : - * FontUIResource fuir; - * Font desktopFont = getDesktopFont(..); - * // NOTE even if fontSupportsDefaultEncoding returns true because - * // you get Tahoma and are running in an English locale, you may - * // still want to just call getCompositeFontUIResource() anyway - * // as only then will you get fallback fonts - eg for CJK. - * if (FontManager.fontSupportsDefaultEncoding(desktopFont)) { - * fuir = new FontUIResource(..); - * } else { - * fuir = FontManager.getCompositeFontUIResource(desktopFont); - * } - * return fuir; - */ - public static FontUIResource getCompositeFontUIResource(Font font) { - throw new NotYetImplementedError(); - } - - public static Font2D getNewComposite(String family, int style, Font2D handle) { - throw new NotYetImplementedError(); - } - - /* - * return String representation of style prepended with "." - * This is useful for performance to avoid unnecessary string operations. - */ - private static String dotStyleStr(int num) { - switch(num){ - case Font.BOLD: - return ".bold"; - case Font.ITALIC: - return ".italic"; - case Font.ITALIC | Font.BOLD: - return ".bolditalic"; - default: - return ".plain"; - } - } - - /* - * The client supplies a name and a style. - * The name could be a family name, or a full name. - * A font may exist with the specified style, or it may - * exist only in some other style. For non-native fonts the scaler - * may be able to emulate the required style. - */ - public static Font2D findFont2D(String name, int style, int fallback){ - String lowerCaseName = name.toLowerCase(Locale.ENGLISH); - String mapName = lowerCaseName + dotStyleStr(style); - Font2D font2D = fontNameCache.get(mapName); - - if(font2D != null){ - return font2D; - } - font2D = new PhysicalFont(name,style); - fontNameCache.put(mapName, font2D); - return font2D; - } - - /** - * Create a new Font2D without caching. This is used from createFont - * - * @param family - * .NET FontFamily - * @param style - * the style - * @return a Font2D - */ - public static Font2D createFont2D( FontFamily family, int style ) { - return new PhysicalFont( family, style ); - } - - /* This method can be more efficient as it will only need to - * do the lookup once, and subsequent calls on the java.awt.Font - * instance can utilise the cached Font2D on that object. - * Its unfortunate it needs to be a native method, but the font2D - * variable has to be private. - */ - public static Font2D getFont2D(Font font){ - try{ - return (Font2D)getFont2D.invoke(font); - }catch(Exception ex){ - throw new RuntimeException(ex); - } - } - - /* Stuff below was in NativeFontWrapper and needed a new home */ - - /* - * Workaround for apps which are dependent on a font metrics bug - * in JDK 1.1. This is an unsupported win32 private setting. - */ - public static boolean usePlatformFontMetrics() { - return usePlatformFontMetrics; - } - - /* This method doesn't check if alternates are selected in this app - * context. Its used by the FontMetrics caching code which in such - * a case cannot retrieve a cached metrics solely on the basis of - * the Font.equals() method since it needs to also check if the Font2D - * is the same. - * We also use non-standard composites for Swing native L&F fonts on - * Windows. In that case the policy is that the metrics reported are - * based solely on the physical font in the first slot which is the - * visible java.awt.Font. So in that case the metrics cache which tests - * the Font does what we want. In the near future when we expand the GTK - * logical font definitions we may need to revisit this if GTK reports - * combined metrics instead. For now though this test can be simple. - */ - static boolean maybeUsingAlternateCompositeFonts() { - // TODO Auto-generated method stub - return false; - } - - public static synchronized void preferLocaleFonts() { - // TODO Auto-generated method stub - - } - - public static synchronized void preferProportionalFonts() { - // TODO Auto-generated method stub - } - - public static boolean registerFont(Font font) { - /* This method should not be called with "null". - * It is the caller's responsibility to ensure that. - */ - // TODO Auto-generated method stub - return false; - } - - /* This is called by Swing passing in a fontconfig family name - * such as "sans". In return Swing gets a FontUIResource instance - * that has queried fontconfig to resolve the font(s) used for this. - * Fontconfig will if asked return a list of fonts to give the largest - * possible code point coverage. - * For now we use only the first font returned by fontconfig, and - * back it up with the most closely matching JDK logical font. - * Essentially this means pre-pending what we return now with fontconfig's - * preferred physical font. This could lead to some duplication in cases, - * if we already included that font later. We probably should remove such - * duplicates, but it is not a significant problem. It can be addressed - * later as part of creating a Composite which uses more of the - * same fonts as fontconfig. At that time we also should pay more - * attention to the special rendering instructions fontconfig returns, - * such as whether we should prefer embedded bitmaps over antialiasing. - * There's no way to express that via a Font at present. - */ - public static FontUIResource getFontConfigFUIR( String fcFamily, int style, int size ) { - return new FontUIResource( fcFamily, style, size ); - } - - /* The following fields and methods which relate to layout - * perhaps belong in some other class but FontManager is already - * widely used as an entry point for other JDK code that needs - * access to the font system internals. - */ - - /** - * Referenced by code in the JDK which wants to test for the - * minimum char code for which layout may be required. - * Note that even basic latin text can benefit from ligatures, - * eg "ffi" but we presently apply those only if explicitly - * requested with TextAttribute.LIGATURES_ON. - * The value here indicates the lowest char code for which failing - * to invoke layout would prevent acceptable rendering. - */ - public static final int MIN_LAYOUT_CHARCODE = 0x0300; - - /** - * Referenced by code in the JDK which wants to test for the - * maximum char code for which layout may be required. - * Note this does not account for supplementary characters - * where the caller interprets 'layout' to mean any case where - * one 'char' (ie the java type char) does not map to one glyph - */ - public static final int MAX_LAYOUT_CHARCODE = 0x206F; - - /* If the character code falls into any of a number of unicode ranges - * where we know that simple left->right layout mapping chars to glyphs - * 1:1 and accumulating advances is going to produce incorrect results, - * we want to know this so the caller can use a more intelligent layout - * approach. A caller who cares about optimum performance may want to - * check the first case and skip the method call if its in that range. - * Although there's a lot of tests in here, knowing you can skip - * CTL saves a great deal more. The rest of the checks are ordered - * so that rather than checking explicitly if (>= start & <= end) - * which would mean all ranges would need to be checked so be sure - * CTL is not needed, the method returns as soon as it recognises - * the code point is outside of a CTL ranges. - * NOTE: Since this method accepts an 'int' it is asssumed to properly - * represent a CHARACTER. ie it assumes the caller has already - * converted surrogate pairs into supplementary characters, and so - * can handle this case and doesn't need to be told such a case is - * 'complex'. - */ - static boolean isComplexCharCode(int code) { - - if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) { - return false; - } - else if (code <= 0x036f) { - // Trigger layout for combining diacriticals 0x0300->0x036f - return true; - } - else if (code < 0x0590) { - // No automatic layout for Greek, Cyrillic, Armenian. - return false; - } - else if (code <= 0x06ff) { - // Hebrew 0590 - 05ff - // Arabic 0600 - 06ff - return true; - } - else if (code < 0x0900) { - return false; // Syriac and Thaana - } - else if (code <= 0x0e7f) { - // if Indic, assume shaping for conjuncts, reordering: - // 0900 - 097F Devanagari - // 0980 - 09FF Bengali - // 0A00 - 0A7F Gurmukhi - // 0A80 - 0AFF Gujarati - // 0B00 - 0B7F Oriya - // 0B80 - 0BFF Tamil - // 0C00 - 0C7F Telugu - // 0C80 - 0CFF Kannada - // 0D00 - 0D7F Malayalam - // 0D80 - 0DFF Sinhala - // 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks - return true; - } - else if (code < 0x1780) { - return false; - } - else if (code <= 0x17ff) { // 1780 - 17FF Khmer - return true; - } - else if (code < 0x200c) { - return false; - } - else if (code <= 0x200d) { // zwj or zwnj - return true; - } - else if (code >= 0x202a && code <= 0x202e) { // directional control - return true; - } - else if (code >= 0x206a && code <= 0x206f) { // directional control - return true; - } - return false; - } - - /* This is almost the same as the method above, except it takes a - * char which means it may include undecoded surrogate pairs. - * The distinction is made so that code which needs to identify all - * cases in which we do not have a simple mapping from - * char->unicode character->glyph can be be identified. - * For example measurement cannot simply sum advances of 'chars', - * the caret in editable text cannot advance one 'char' at a time, etc. - * These callers really are asking for more than whether 'layout' - * needs to be run, they need to know if they can assume 1->1 - * char->glyph mapping. - */ - static boolean isNonSimpleChar(char ch) { - return - isComplexCharCode(ch) || - (ch >= CharToGlyphMapper.HI_SURROGATE_START && - ch <= CharToGlyphMapper.LO_SURROGATE_END); - } - - /** - * If there is anything in the text which triggers a case - * where char->glyph does not map 1:1 in straightforward - * left->right ordering, then this method returns true. - * Scripts which might require it but are not treated as such - * due to JDK implementations will not return true. - * ie a 'true' return is an indication of the treatment by - * the implementation. - * Whether supplementary characters should be considered is dependent - * on the needs of the caller. Since this method accepts the 'char' type - * then such chars are always represented by a pair. From a rendering - * perspective these will all (in the cases I know of) still be one - * unicode character -> one glyph. But if a caller is using this to - * discover any case where it cannot make naive assumptions about - * the number of chars, and how to index through them, then it may - * need the option to have a 'true' return in such a case. - */ - public static boolean isComplexText(char [] chs, int start, int limit) { - - for (int i = start; i < limit; i++) { - if (chs[i] < MIN_LAYOUT_CHARCODE) { - continue; - } - else if (isNonSimpleChar(chs[i])) { - return true; - } - } - return false; - } - -} diff --git a/openjdk/sun/font/GlyphLayout.java b/openjdk/sun/font/GlyphLayout.java deleted file mode 100644 index 3d6ed7a9..00000000 --- a/openjdk/sun/font/GlyphLayout.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import java.awt.Font; -import java.awt.font.FontRenderContext; - - - -/** - * - */ -public class GlyphLayout{ - - private static GlyphLayout glyphLayout = new GlyphLayout(); - - /** - * Return a new instance of GlyphLayout, using the provided layout engine factory. - * If null, the system layout engine factory will be used. - */ - public static GlyphLayout get(Object lef) { - return glyphLayout; //current this class has no state - } - - /** - * Return the old instance of GlyphLayout when you are done. This enables reuse - * of GlyphLayout objects. - */ - public static void done(GlyphLayout gl) { - } - - /** - * Create a glyph vector. - * @param font the font to use - * @param frc the font render context - * @param text the text, including optional context before start and after start + count - * @param offset the start of the text to lay out - * @param count the length of the text to lay out - * @param flags bidi and context flags {@see #java.awt.Font} - * @param result a StandardGlyphVector to modify, can be null - * @return the layed out glyphvector, if result was passed in, it is returned - */ - public StandardGlyphVector layout(Font font, FontRenderContext frc, - char[] text, int offset, int count, - int flags, StandardGlyphVector result) - { - if (text == null || offset < 0 || count < 0 || (count > text.length - offset)) { - throw new IllegalArgumentException(); - } - - return new StandardGlyphVector(font, text, offset, count, frc); - } - - -} diff --git a/openjdk/sun/font/PhysicalFont.java b/openjdk/sun/font/PhysicalFont.java deleted file mode 100644 index ad9499bd..00000000 --- a/openjdk/sun/font/PhysicalFont.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - Copyright (C) 2009, 2010 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import java.awt.Font; -import java.awt.font.FontRenderContext; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.Locale; - -import cli.System.Drawing.FontFamily; -import cli.System.Drawing.FontStyle; -import cli.System.Globalization.CultureInfo; - -/** - * A Font2D implementation that based on .NET fonts. It replace the equals naming Sun class. - * A Font2D is define with the font name and the font style but it is independent of the size; - */ -class PhysicalFont extends Font2D{ - - private final FontFamily family; - - private String familyName; // family name for logical fonts - - private final FontStyle style; - - private static final FontStyle REGULAR = FontStyle.wrap(FontStyle.Regular); - - private static final FontStyle BOLD = FontStyle.wrap(FontStyle.Bold); - - private static final FontStyle ITALIC = FontStyle.wrap(FontStyle.Italic); - - private static final FontStyle BOLD_ITALIC = FontStyle.wrap(FontStyle.Bold + FontStyle.Italic); - - private static final cli.System.Drawing.GraphicsUnit PIXEL = cli.System.Drawing.GraphicsUnit - .wrap(cli.System.Drawing.GraphicsUnit.Pixel); - - //for method getStyleMetrics - //for Reflection to the .NET 3.0 API in namespace System.Windows.Media of PresentationCore - //If we switch to .NET 3.0 then we can access it directly - private static boolean isMediaLoaded; - private static Class classMediaFontFamily; - private static Constructor ctorMediaFontFamily; - private static Method getFamilyTypefaces; - private static Method getItem; - private static Method getStrikethroughPosition; - private static Method getStrikethroughThickness; - private static Method getUnderlinePosition; - private static Method getUnderlineThickness; - private float strikethroughPosition; - private float strikethroughThickness; - private float underlinePosition; - private float underlineThickness; - - - PhysicalFont(String name, int style){ - this.family = createFontFamily(name); - this.style = createFontStyle(family, style); - } - - PhysicalFont(FontFamily family, int style){ - this.family = family; - this.style = createFontStyle(family, style); - } - - - - /** - * {@inheritDoc} - */ - @Override - public cli.System.Drawing.Font createNetFont(Font font){ - float size2D = font.getSize2D(); - if(size2D <= 0){ - size2D = 1; - } - return new cli.System.Drawing.Font(family, size2D, style, PIXEL); - } - - /** - * Search for .NET FamilyName. For logical fonts it set the variable familyName - * @param name the name of the font. - * @return ever a FontFamily - */ - private FontFamily createFontFamily(String name){ - if(Font.MONOSPACED.equalsIgnoreCase(name)){ - familyName = Font.MONOSPACED; - return FontFamily.get_GenericMonospace(); - } - if(Font.SERIF.equalsIgnoreCase(name)){ - familyName = Font.SERIF; - return FontFamily.get_GenericSerif(); - } - if(name == null || Font.SANS_SERIF.equalsIgnoreCase(name)){ - familyName = Font.SANS_SERIF; - return FontFamily.get_GenericSansSerif(); - } - if(Font.DIALOG.equalsIgnoreCase(name)){ - familyName = Font.DIALOG; - return FontFamily.get_GenericSansSerif(); - } - if(Font.DIALOG_INPUT.equalsIgnoreCase(name)){ - familyName = Font.DIALOG_INPUT; - return FontFamily.get_GenericSansSerif(); - } - try{ - if(false) throw new cli.System.ArgumentException(); - return new FontFamily(name); - }catch(cli.System.ArgumentException ex){ - // continue - } - - //now we want map specific Name to a shorter Family Name like "Arial Bold" --> "Arial" - String shortName = name; - int spaceIdx = shortName.lastIndexOf(' '); - while(spaceIdx > 0){ - shortName = shortName.substring(0, spaceIdx).trim(); - try{ - if(false) throw new cli.System.ArgumentException(); - return new FontFamily(shortName); - }catch(cli.System.ArgumentException ex){ - // continue - } - spaceIdx = shortName.lastIndexOf(' '); - } - - //now we want map generic names to specific families like "courier" --> "Courier New" - FontFamily[] fontFanilies = FontFamily.get_Families(); - name = name.toLowerCase(); - for (int i = 0; i < fontFanilies.length; i++) { - FontFamily fontFamily = fontFanilies[i]; - if(fontFamily.get_Name().toLowerCase().startsWith(name)){ - return fontFamily; - } - } - - //we have not find a valid font, we use the default font - familyName = Font.DIALOG; - return FontFamily.get_GenericSansSerif(); - } - - - private static FontStyle createFontStyle(FontFamily family, int style){ - int fs = FontStyle.Regular; - if((style & java.awt.Font.BOLD) != 0){ - fs |= FontStyle.Bold; - } - if((style & java.awt.Font.ITALIC) != 0){ - fs |= FontStyle.Italic; - } - FontStyle fontStyle = FontStyle.wrap(fs); - if(!family.IsStyleAvailable(fontStyle)){ - // Some Fonts (for example Aharoni) does not support Regular style. This throw an exception else it is not - // documented. - if(family.IsStyleAvailable(REGULAR)){ - fontStyle = REGULAR; - }else if(family.IsStyleAvailable(BOLD)){ - fontStyle = BOLD; - }else if(family.IsStyleAvailable(ITALIC)){ - fontStyle = ITALIC; - }else if(family.IsStyleAvailable(BOLD_ITALIC)){ - fontStyle = BOLD_ITALIC; - } - } - return fontStyle; - } - - - /** - * {@inheritDoc} - */ - @Override - public FontStrike getStrike(Font font, FontRenderContext frc){ - return new PhysicalStrike(font, family, style, frc); - } - - - /** - * {@inheritDoc} - */ - @Override - public int getStyle(){ - return style.Value; - } - - - /** - * {@inheritDoc} - */ - @Override - public String getPostscriptName(){ - return family.get_Name(); - } - - - /** - * {@inheritDoc} - */ - @Override - public String getFontName(Locale locale){ - return family.GetName(getLanguage(locale)); - } - - - /** - * {@inheritDoc} - */ - @Override - public String getFamilyName(Locale locale){ - if(familyName != null){ - return familyName; - } - return family.GetName(getLanguage(locale)); - } - - /** - * Convert the Java locale to a language ID - */ - private int getLanguage(Locale locale){ - int language = 0; - try{ - language = CultureInfo.GetCultureInfo(locale.toString().replace("_", "-")).get_LCID(); - }catch(Throwable th){ - try{ - language = CultureInfo.GetCultureInfo(locale.getLanguage()).get_LCID(); - }catch(Throwable th2){} - } - return language; - } - - - /** - * {@inheritDoc} - */ - @Override - public void getStyleMetrics(float pointSize, float[] metrics, int offset) { - try{ - try{ - if(!isMediaLoaded){ - classMediaFontFamily = Class.forName("System.Windows.Media.FontFamily, PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); - ctorMediaFontFamily = classMediaFontFamily.getConstructor(String.class); - getFamilyTypefaces = classMediaFontFamily.getMethod("get_FamilyTypefaces"); - } - if(classMediaFontFamily != null){ - if(strikethroughPosition == 0.0){ - Object mediaFontFamily = ctorMediaFontFamily.newInstance(family.get_Name()); - Object familyTypefaces = getFamilyTypefaces.invoke(mediaFontFamily); - if(getItem == null){ - getItem = familyTypefaces.getClass().getMethod("get_Item", Integer.TYPE); - } - Object familyTypeface = getItem.invoke(familyTypefaces, 0); - if(getStrikethroughPosition == null){ - getStrikethroughPosition = familyTypeface.getClass().getMethod("get_StrikethroughPosition"); - getStrikethroughThickness = familyTypeface.getClass().getMethod( - "get_StrikethroughThickness"); - getUnderlinePosition = familyTypeface.getClass().getMethod("get_UnderlinePosition"); - getUnderlineThickness = familyTypeface.getClass().getMethod("get_UnderlineThickness"); - } - strikethroughPosition = ((Number)getStrikethroughPosition.invoke(familyTypeface)).floatValue(); - strikethroughThickness = ((Number)getStrikethroughThickness.invoke(familyTypeface)) - .floatValue(); - underlinePosition = ((Number)getUnderlinePosition.invoke(familyTypeface)).floatValue(); - underlineThickness = ((Number)getUnderlineThickness.invoke(familyTypeface)).floatValue(); - } - } - metrics[offset++] = -strikethroughPosition * pointSize; - metrics[offset++] = strikethroughThickness * pointSize; - metrics[offset++] = -underlinePosition * pointSize; - metrics[offset] = underlineThickness * pointSize; - }catch(Throwable ex){ - // ignore it, NET 3.0 is not available, use the default implementation - super.getStyleMetrics(pointSize, metrics, offset); - } - }finally{ - isMediaLoaded = true; - } - } -} diff --git a/openjdk/sun/font/PhysicalStrike.java b/openjdk/sun/font/PhysicalStrike.java deleted file mode 100644 index cf22d94e..00000000 --- a/openjdk/sun/font/PhysicalStrike.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - Copyright (C) 2009 - 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import java.awt.Font; -import java.awt.Rectangle; -import java.awt.font.FontRenderContext; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D.Float; - -import cli.System.Drawing.Bitmap; -import cli.System.Drawing.CharacterRange; -import cli.System.Drawing.FontFamily; -import cli.System.Drawing.FontStyle; -import cli.System.Drawing.Graphics; -import cli.System.Drawing.RectangleF; -import cli.System.Drawing.Region; -import cli.System.Drawing.SizeF; -import cli.System.Drawing.StringFormat; -import cli.System.Drawing.StringFormatFlags; -import cli.System.Drawing.StringTrimming; -import cli.System.Drawing.Drawing2D.PixelOffsetMode; -import cli.System.Drawing.Drawing2D.SmoothingMode; -import cli.System.Drawing.Text.TextRenderingHint; - -import ikvm.internal.NotYetImplementedError; - -/** - * A FontStrike implementation that based on .NET fonts. - * It replace the equals naming Sun class - */ -public class PhysicalStrike extends FontStrike{ - - private static final Bitmap BITMAP = new Bitmap( 1, 1 ); - private static Graphics FRACT_GRAPHICS = createGraphics(true); - private static Graphics FIXED_GRAPHICS = createGraphics(false); - - private final Font font; - private final FontFamily family; - private final FontStyle style; - private final FontRenderContext frc; - private final float size2D; - private final float factor; - - private StrikeMetrics strike; - - public PhysicalStrike(Font font, FontFamily family, FontStyle style, FontRenderContext frc){ - this.font = font; - this.family = family; - this.style = style; - this.frc = frc; - this.size2D = font.getNetFont().get_Size(); - this.factor = size2D / family.GetEmHeight(style); - } - - /** - * {@inheritDoc} - */ - @Override - Float getCharMetrics(char ch){ - return new Float(getCodePointAdvance(ch), 0); - } - - - /** - * Create a Graphics with the settings for fractional or fixed FontRenderContext - * - * @return - */ - private static Graphics createGraphics(boolean fractional){ - Graphics g = Graphics.FromImage(BITMAP); - g.set_SmoothingMode(SmoothingMode.wrap(fractional ? SmoothingMode.None : SmoothingMode.AntiAlias)); - g.set_PixelOffsetMode(PixelOffsetMode.wrap(fractional ? PixelOffsetMode.None : PixelOffsetMode.HighQuality)); - g.set_TextRenderingHint(TextRenderingHint.wrap(fractional ? TextRenderingHint.SingleBitPerPixelGridFit : TextRenderingHint.AntiAliasGridFit)); - return g; - } - - /** - * {@inheritDoc} - */ - @Override - float getCodePointAdvance( int cp ) { - StringFormat format = new StringFormat(StringFormat.get_GenericTypographic()); - - format.set_FormatFlags( StringFormatFlags.wrap( StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap | - StringFormatFlags.FitBlackBox )); - format.set_Trimming( StringTrimming.wrap( StringTrimming.None ) ); - format.SetMeasurableCharacterRanges(new CharacterRange[] {new CharacterRange(0, 1)}); - boolean fractional = frc.usesFractionalMetrics(); - Graphics g = fractional ? FRACT_GRAPHICS : FIXED_GRAPHICS; - SizeF size; - synchronized (g) { - Region[] regions = g.MeasureCharacterRanges(String.valueOf((char)cp), font.getNetFont(), - new RectangleF(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE), format); - size = regions[0].GetBounds(g).get_Size(); - regions[0].Dispose(); - } - return frc.usesFractionalMetrics() ? size.get_Width() : Math.round(size.get_Width()); - } - - /** - * {@inheritDoc} - */ - @Override - StrikeMetrics getFontMetrics(){ - if(strike == null){ - float ascent = family.GetCellAscent(style) * factor; - float descent = family.GetCellDescent(style) * factor; - float height = family.GetLineSpacing(style) * factor; - float leading = height - ascent - descent; - strike = new StrikeMetrics( - 0, -ascent - leading/2, - 0, descent - leading/2, - 0.25f, 0, - 0, leading, - size2D * 2, 0); - } - return strike; - } - - - /** - * {@inheritDoc} - */ - @Override - float getGlyphAdvance(int glyphCode){ - return getCodePointAdvance( glyphCode ); - } - - - /** - * {@inheritDoc} - */ - @Override - void getGlyphImageBounds(int glyphcode, Float pt, Rectangle result){ - throw new NotYetImplementedError(); - } - - - /** - * {@inheritDoc} - */ - @Override - long getGlyphImagePtr(int glyphcode){ - throw new NotYetImplementedError(); - } - - - /** - * {@inheritDoc} - */ - @Override - void getGlyphImagePtrs(int[] glyphCodes, long[] images, int len){ - throw new NotYetImplementedError(); - } - - - /** - * {@inheritDoc} - */ - @Override - Float getGlyphMetrics(int glyphcode){ - return getCharMetrics((char)glyphcode); - } - - - /** - * {@inheritDoc} - */ - @Override - GeneralPath getGlyphOutline(int glyphCode, float x, float y){ - throw new NotYetImplementedError(); - } - - - /** - * {@inheritDoc} - */ - @Override - java.awt.geom.Rectangle2D.Float getGlyphOutlineBounds(int glyphCode){ - throw new NotYetImplementedError(); - } - - - /** - * {@inheritDoc} - */ - @Override - GeneralPath getGlyphVectorOutline(int[] glyphs, float x, float y){ - throw new NotYetImplementedError(); - } - - - /** - * {@inheritDoc} - */ - @Override - public int getNumGlyphs(){ - throw new NotYetImplementedError(); - } - -} diff --git a/openjdk/sun/font/StandardGlyphVector.java b/openjdk/sun/font/StandardGlyphVector.java deleted file mode 100644 index fb3de314..00000000 --- a/openjdk/sun/font/StandardGlyphVector.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - Copyright (C) 2009 - 2013 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import ikvm.awt.IkvmToolkit; - -import java.awt.Font; -import java.awt.Shape; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphMetrics; -import java.awt.font.GlyphJustificationInfo; -import java.awt.font.GlyphVector; -import java.awt.font.LineMetrics; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.text.CharacterIterator; - -import ikvm.internal.NotYetImplementedError; - -/** - * Standard implementation of GlyphVector used by Font, GlyphList, and SunGraphics2D. - * - */ -public class StandardGlyphVector extends GlyphVector{ - private Font font; - private FontRenderContext frc; - private final String glyphs; // always - private float[] positions; // only if not default advances - - - - private Font2D font2D; - private FontStrike strike; - - - ///////////////////////////// - // Constructors and Factory methods - ///////////////////////////// - - public StandardGlyphVector(Font font, String str, FontRenderContext frc) { - if(str == null){ - throw new NullPointerException("Glyphs are null"); - } - this.font = font; - if( frc == null ){ - frc = new FontRenderContext( null, false, false ); - } - this.frc = frc; - this.glyphs = str; - this.font2D = FontUtilities.getFont2D(font); - this.strike = font2D.getStrike(font, frc); - } - - public StandardGlyphVector(Font font, char[] text, FontRenderContext frc) { - this(font, text, 0, text.length, frc); - } - - public StandardGlyphVector(Font font, char[] text, int start, int count, - FontRenderContext frc) { - this(font, new String(text, start, count), frc); - } - - private float getTracking(Font font) { - if (font.hasLayoutAttributes()) { - AttributeValues values = ((AttributeMap)font.getAttributes()).getValues(); - return values.getTracking(); - } - return 0; - } - - public StandardGlyphVector(Font font, CharacterIterator iter, FontRenderContext frc) { - this(font, getString(iter), frc); - } - - public StandardGlyphVector( Font font, int[] glyphs, FontRenderContext frc ) { - this( font, glyphs2chars(glyphs), frc ); - } - - /** - * Symmetric to {@link #getGlyphCodes(int, int, int[])} - * Currently there is no real mapping possible between the chars and the glyph IDs in the TTF file - */ - private static char[] glyphs2chars( int[] glyphs ) { - int count = glyphs.length; - char[] text = new char[count]; - for( int i = 0; i < count; ++i ) { - text[i] = (char)glyphs[i]; - } - return text; - } - - ///////////////////////////// - // GlyphVector API - ///////////////////////////// - - @Override - public Font getFont() { - return this.font; - } - - @Override - public FontRenderContext getFontRenderContext() { - return this.frc; - } - - @Override - public void performDefaultLayout() { - positions = null; - } - - @Override - public int getNumGlyphs() { - return glyphs.length(); - } - - @Override - public int getGlyphCode(int glyphIndex) { - return glyphs.charAt(glyphIndex); - } - - @Override - public int[] getGlyphCodes(int start, int count, int[] result) { - if (count < 0) { - throw new IllegalArgumentException("count = " + count); - } - if (start < 0) { - throw new IndexOutOfBoundsException("start = " + start); - } - if (start > glyphs.length() - count) { // watch out for overflow if index + count overlarge - throw new IndexOutOfBoundsException("start + count = " + (start + count)); - } - - if (result == null) { - result = new int[count]; - } - for (int i = 0; i < count; ++i) { - result[i] = glyphs.charAt(i + start); - } - return result; - } - - // !!! not cached, assume TextLayout will cache if necessary - // !!! reexamine for per-glyph-transforms - // !!! revisit for text-on-a-path, vertical - @Override - public Rectangle2D getLogicalBounds() { - initPositions(); - - LineMetrics lm = font.getLineMetrics("", frc); - - float minX, minY, maxX, maxY; - // horiz only for now... - minX = 0; - minY = -lm.getAscent(); - maxX = 0; - maxY = lm.getDescent() + lm.getLeading(); - if (glyphs.length() > 0) { - maxX = positions[positions.length - 2]; - } - - return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY); - } - - // !!! not cached, assume TextLayout will cache if necessary - @Override - public Rectangle2D getVisualBounds() { - return getOutline().getBounds2D(); - } - - @Override - public Shape getOutline() { - return getOutline( 0, 0 ); - } - - @Override - public Shape getOutline(float x, float y) { - return IkvmToolkit.DefaultToolkit.get().outline( font, frc, glyphs, x, y ); - } - - @Override - public Shape getGlyphOutline( int glyphIndex ) { - return getGlyphOutline( glyphIndex, 0, 0 ); - } - - @Override - public Shape getGlyphOutline( int glyphIndex, float x, float y ) { - initPositions(); - - return IkvmToolkit.DefaultToolkit.get().outline( font, frc, glyphs.substring( glyphIndex, glyphIndex + 1 ), x + positions[glyphIndex * 2], y ); - } - - @Override - public Point2D getGlyphPosition(int ix) { - initPositions(); - - ix *= 2; - return new Point2D.Float(positions[ix], positions[ix + 1]); - } - - @Override - public void setGlyphPosition(int ix, Point2D pos) { - initPositions(); - - int ix2 = ix << 1; - positions[ix2] = (float)pos.getX(); - positions[ix2 + 1] = (float)pos.getY(); - } - - @Override - public AffineTransform getGlyphTransform(int ix) { - throw new NotYetImplementedError(); - } - - @Override - public float[] getGlyphPositions(int start, int count, float[] result) { - if (count < 0) { - throw new IllegalArgumentException("count = " + count); - } - if (start < 0) { - throw new IndexOutOfBoundsException("start = " + start); - } - if (start > this.glyphs.length() + 1 - count) { - throw new IndexOutOfBoundsException("start + count = " + (start + count)); - } - int count2 = count * 2; - if( result == null ) { - result = new float[count2]; - } - initPositions(); - System.arraycopy( positions, start * 2, result, 0, count2 ); - return result; - } - - @Override - public Shape getGlyphLogicalBounds(int ix) { - if (ix < 0 || ix >= glyphs.length()) { - throw new IndexOutOfBoundsException("ix = " + ix); - } - - initPositions(); - StrikeMetrics metrics = strike.getFontMetrics(); - float x = positions[ix * 2]; - return new Rectangle2D.Float( x, -metrics.getAscent(), positions[(ix + 1) * 2] - x, metrics.getAscent() - + metrics.getDescent() + metrics.getLeading() ); - } - - @Override - public Shape getGlyphVisualBounds(int ix) { - if (ix < 0 || ix >= glyphs.length()) { - throw new IndexOutOfBoundsException("ix = " + ix); - } - - initPositions(); - return IkvmToolkit.DefaultToolkit.get().outline( font, frc, glyphs.substring( ix, ix + 1 ), positions[ix * 2], 0 ); - } - - @Override - public GlyphMetrics getGlyphMetrics(int ix) { - if (ix < 0 || ix >= glyphs.length()) { - throw new IndexOutOfBoundsException("ix = " + ix); - } - - Rectangle2D vb = getGlyphVisualBounds(ix).getBounds2D(); - Point2D pt = getGlyphPosition(ix); - vb.setRect(vb.getMinX() - pt.getX(), - vb.getMinY() - pt.getY(), - vb.getWidth(), - vb.getHeight()); - Point2D.Float adv = - strike.getGlyphMetrics( glyphs.charAt( ix ) ); - GlyphMetrics gm = new GlyphMetrics(true, adv.x, adv.y, - vb, - (byte)0); - return gm; - } - - @Override - public GlyphJustificationInfo getGlyphJustificationInfo(int ix) { - if (ix < 0 || ix >= glyphs.length()) { - throw new IndexOutOfBoundsException("ix = " + ix); - } - - // currently we don't have enough information to do this right. should - // get info from the font and use real OT/GX justification. Right now - // sun/font/ExtendedTextSourceLabel assigns one of three infos - // based on whether the char is kanji, space, or other. - - return null; - } - - @Override - public boolean equals(GlyphVector rhs) { - if(!(rhs instanceof StandardGlyphVector)){ - return false; - } - StandardGlyphVector sgv = (StandardGlyphVector)rhs; - if(!glyphs.equals(sgv.glyphs)){ - return false; - } - if(equals(font, sgv.font)){ - return false; - } - if(equals(frc, sgv.frc)){ - return false; - } - return true; - } - - /** - * Compare 2 objects via equals where both can be null - */ - private static boolean equals(Object obj1, Object obj2){ - if(obj1 != null){ - if(!obj1.equals(obj2)){ - return false; - } - }else{ - if(obj2 != null){ - return false; - } - } - return true; - } - - /** - * As a concrete subclass of GlyphVector, this must implement clone. - */ - @Override - public Object clone() { - // positions, gti are mutable so we have to clone them - // font2d can be shared - // fsref is a cache and can be shared - try { - StandardGlyphVector result = (StandardGlyphVector)super.clone(); - - if (positions != null) { - result.positions = (float[])positions.clone(); - } - - return result; - } - catch (CloneNotSupportedException e) { - } - - return this; - } - - ////////////////////// - // StandardGlyphVector new public methods - ///////////////////// - - /** - * Set all the glyph positions, including the 'after last glyph' position. - * The srcPositions array must be of length (numGlyphs + 1) * 2. - */ - public void setGlyphPositions(float[] srcPositions) { - int requiredLength = glyphs.length() * 2 + 2; - if (srcPositions.length != requiredLength) { - throw new IllegalArgumentException("srcPositions.length != " + requiredLength); - } - - positions = (float[])srcPositions.clone(); - - } - - /** - * This is a convenience overload that gets all the glyph positions, which - * is what you usually want to do if you're getting more than one. - * !!! should I bother taking result parameter? - */ - public float[] getGlyphPositions(float[] result) { - initPositions(); - return positions; - } - - /** - * For each glyph return posx, posy, advx, advy, visx, visy, visw, vish. - */ - public float[] getGlyphInfo() { - initPositions(); - float[] result = new float[glyphs.length() * 8]; - for (int i = 0, n = 0; i < glyphs.length(); ++i, n += 8) { - float x = positions[i*2]; - float y = positions[i*2+1]; - result[n] = x; - result[n+1] = y; - - int glyphID = glyphs.charAt(i); - Point2D.Float adv = strike.getGlyphMetrics(glyphID); - result[n+2] = adv.x; - result[n+3] = adv.y; - - Rectangle2D vb = getGlyphVisualBounds(i).getBounds2D(); - result[n+4] = (float)(vb.getMinX()); - result[n+5] = (float)(vb.getMinY()); - result[n+6] = (float)(vb.getWidth()); - result[n+7] = (float)(vb.getHeight()); - } - return result; - } - - @Override - public void setGlyphTransform(int glyphIndex, AffineTransform newTX){ - throw new NotYetImplementedError(); - } - - - /** - * Convert a CharacterIterator to a string - * @param iterator the iterator - * @return the string - */ - private static String getString(java.text.CharacterIterator iterator){ - iterator.first(); - StringBuilder sb = new StringBuilder(); - - while(true){ - char c = iterator.current(); - if(c == CharacterIterator.DONE){ - break; - } - sb.append(c); - iterator.next(); - } - - return sb.toString(); - } - - /** - * Ensure that the positions array exists and holds position data. - * If the array is null, this allocates it and sets default positions. - */ - private void initPositions() { - if (positions == null) { - positions = new float[glyphs.length() * 2 + 2]; - - Point2D.Float trackPt = null; - float track = getTracking(font); - if (track != 0) { - track *= font.getSize2D(); - trackPt = new Point2D.Float(track, 0); // advance delta - } - - Point2D.Float pt = new Point2D.Float(0, 0); - if (font.isTransformed()) { - AffineTransform at = font.getTransform(); - at.transform(pt, pt); - positions[0] = pt.x; - positions[1] = pt.y; - - if (trackPt != null) { - at.deltaTransform(trackPt, trackPt); - } - } - for (int i = 0, n = 2; i < glyphs.length(); ++i, n += 2) { - addDefaultGlyphAdvance(glyphs.charAt(i), pt); - if (trackPt != null) { - pt.x += trackPt.x; - pt.y += trackPt.y; - } - positions[n] = pt.x; - positions[n+1] = pt.y; - } - } - } - - private void addDefaultGlyphAdvance(int glyphID, Point2D.Float result) { - Point2D.Float adv = strike.getGlyphMetrics(glyphID); - result.x += adv.x; - result.y += adv.y; - } - - /** - * If the text is a simple text and we can use FontDesignMetrics without a stackoverflow. - * @see FontDesignMetrics#stringWidth(String) - * @return true, if a simple text. false it is a complex text. - */ - public static boolean isSimpleString(Font font, String str) { - if (font.hasLayoutAttributes()) { - return false; - } - for (int i = 0; i < str.length(); ++i) { - if (FontUtilities.isNonSimpleChar(str.charAt(i))) { - return false; - } - } - return true; - } -} diff --git a/openjdk/sun/font/StrikeCache.java b/openjdk/sun/font/StrikeCache.java deleted file mode 100644 index 4bf2e75b..00000000 --- a/openjdk/sun/font/StrikeCache.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.font; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import java.awt.Font; -import java.awt.FontFormatException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import sun.java2d.Disposer; -import sun.misc.Unsafe; -import ikvm.internal.NotYetImplementedError; - -/** - -A FontStrike is the keeper of scaled glyph image data which is expensive -to compute so needs to be cached. -So long as that data may be being used it cannot be invalidated. -Yet we also need to limit the amount of native memory and number of -strike objects in use. -For scaleability and ease of use, a key goal is multi-threaded read -access to a strike, so that it may be shared by multiple client objects, -potentially executing on different threads, with no special reference -counting or "check-out/check-in" requirements which would pass on the -burden of keeping track of strike references to the SG2D and other clients. - -A cache of strikes is maintained via Reference objects. -This helps in two ways : -1. The VM will free references when memory is low or they have not been -used in a long time. -2. Reference queues provide a way to get notification of this so we can -free native memory resources. - - */ - -public final class StrikeCache { - - static final Unsafe unsafe = Unsafe.getUnsafe(); - - static ReferenceQueue refQueue = Disposer.getQueue(); - - /* Reference objects may have their referents cleared when GC chooses. - * During application client start-up there is typically at least one - * GC which causes the hotspot VM to clear soft (not just weak) references - * Thus not only is there a GC pause, but the work done do rasterise - * glyphs that are fairly certain to be needed again almost immediately - * is thrown away. So for performance reasons a simple optimisation is to - * keep up to 8 strong references to strikes to reduce the chance of - * GC'ing strikes that have been used recently. Note that this may not - * suffice in Solaris UTF-8 locales where a single composite strike may be - * composed of 15 individual strikes, plus the composite strike. - * And this assumes the new architecture doesn't maintain strikes for - * natively accessed bitmaps. It may be worth "tuning" the number of - * strikes kept around for the platform or locale. - * Since no attempt is made to ensure uniqueness or ensure synchronized - * access there is no guarantee that this cache will ensure that unique - * strikes are cached. Every time a strike is looked up it is added - * to the current index in this cache. All this cache has to do to be - * worthwhile is prevent excessive cache flushing of strikes that are - * referenced frequently. The logic that adds references here could be - * tweaked to keep only strikes that represent untransformed, screen - * sizes as that's the typical performance case. - */ - static int MINSTRIKES = 8; // can be overridden by property - static int recentStrikeIndex = 0; - static FontStrike[] recentStrikes; - static boolean cacheRefTypeWeak; - - /* - * Native sizes and offsets for glyph cache - * There are 10 values. - */ - static int nativeAddressSize; - static int glyphInfoSize; - static int xAdvanceOffset; - static int yAdvanceOffset; - static int boundsOffset; - static int widthOffset; - static int heightOffset; - static int rowBytesOffset; - static int topLeftXOffset; - static int topLeftYOffset; - static int pixelDataOffset; - static long invisibleGlyphPtr; - - /* Native method used to return information used for unsafe - * access to native data. - * return values as follows:- - * arr[0] = size of an address/pointer. - * arr[1] = size of a GlyphInfo - * arr[2] = offset of advanceX - * arr[3] = offset of advanceY - * arr[4] = offset of width - * arr[5] = offset of height - * arr[6] = offset of rowBytes - * arr[7] = offset of topLeftX - * arr[8] = offset of topLeftY - * arr[9] = offset of pixel data. - * arr[10] = address of a GlyphImageRef representing the invisible glyph - */ - static void getGlyphCacheDescription(long[] infoArray){ - throw new NotYetImplementedError(); - } - - static { - - long[] nativeInfo = new long[11]; - getGlyphCacheDescription(nativeInfo); - //Can also get address size from Unsafe class :- - //nativeAddressSize = unsafe.addressSize(); - nativeAddressSize = (int)nativeInfo[0]; - glyphInfoSize = (int)nativeInfo[1]; - xAdvanceOffset = (int)nativeInfo[2]; - yAdvanceOffset = (int)nativeInfo[3]; - widthOffset = (int)nativeInfo[4]; - heightOffset = (int)nativeInfo[5]; - rowBytesOffset = (int)nativeInfo[6]; - topLeftXOffset = (int)nativeInfo[7]; - topLeftYOffset = (int)nativeInfo[8]; - pixelDataOffset = (int)nativeInfo[9]; - invisibleGlyphPtr = nativeInfo[10]; - if (nativeAddressSize < 4) { - throw new InternalError("Unexpected address size for font data: " + - nativeAddressSize); - } - - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - - /* Allow a client to override the reference type used to - * cache strikes. The default is "soft" which hints to keep - * the strikes around. This property allows the client to - * override this to "weak" which hint to the GC to free - * memory more agressively. - */ - String refType = - System.getProperty("sun.java2d.font.reftype", "soft"); - cacheRefTypeWeak = refType.equals("weak"); - - String minStrikesStr = - System.getProperty("sun.java2d.font.minstrikes"); - if (minStrikesStr != null) { - try { - MINSTRIKES = Integer.parseInt(minStrikesStr); - if (MINSTRIKES <= 0) { - MINSTRIKES = 1; - } - } catch (NumberFormatException e) { - } - } - - recentStrikes = new FontStrike[MINSTRIKES]; - - return null; - } - }); - } - - - static void refStrike(FontStrike strike) { - int index = recentStrikeIndex; - recentStrikes[index] = strike; - index++; - if (index == MINSTRIKES) { - index = 0; - } - recentStrikeIndex = index; - } - - static void disposeStrike(FontStrikeDisposer disposer) { - if (disposer.intGlyphImages != null) { - freeIntMemory(disposer.intGlyphImages, - disposer.pScalerContext); - } else if (disposer.longGlyphImages != null) { - freeLongMemory(disposer.longGlyphImages, - disposer.pScalerContext); - } else if (disposer.segIntGlyphImages != null) { - /* NB Now making multiple JNI calls in this case. - * But assuming that there's a reasonable amount of locality - * rather than sparse references then it should be OK. - */ - for (int i=0; i<disposer.segIntGlyphImages.length; i++) { - if (disposer.segIntGlyphImages[i] != null) { - freeIntMemory(disposer.segIntGlyphImages[i], - disposer.pScalerContext); - /* native will only free the scaler context once */ - disposer.pScalerContext = 0L; - disposer.segIntGlyphImages[i] = null; - } - } - /* This may appear inefficient but it should only be invoked - * for a strike that never was asked to rasterise a glyph. - */ - if (disposer.pScalerContext != 0L) { - freeIntMemory(new int[0], disposer.pScalerContext); - } - } else if (disposer.segLongGlyphImages != null) { - for (int i=0; i<disposer.segLongGlyphImages.length; i++) { - if (disposer.segLongGlyphImages[i] != null) { - freeLongMemory(disposer.segLongGlyphImages[i], - disposer.pScalerContext); - disposer.pScalerContext = 0L; - disposer.segLongGlyphImages[i] = null; - } - } - if (disposer.pScalerContext != 0L) { - freeLongMemory(new long[0], disposer.pScalerContext); - } - } - } - - static void freeIntPointer(int ptr){ - throw new NotYetImplementedError(); - } - static void freeLongPointer(long ptr){ - throw new NotYetImplementedError(); - } - private static void freeIntMemory(int[] glyphPtrs, long pContext){ - throw new NotYetImplementedError(); - } - private static void freeLongMemory(long[] glyphPtrs, long pContext){ - throw new NotYetImplementedError(); - } - - - public static Reference getStrikeRef(FontStrike strike) { - return getStrikeRef(strike, cacheRefTypeWeak); - } - - public static Reference getStrikeRef(FontStrike strike, boolean weak) { - /* Some strikes may have no disposer as there's nothing - * for them to free, as they allocated no native resource - * eg, if they did not allocate resources because of a problem, - * or they never hold native resources. So they create no disposer. - * But any strike that reaches here that has a null disposer is - * a potential memory leak. - */ - if (strike.disposer == null) { - if (weak) { - return new WeakReference(strike); - } else { - return new SoftReference(strike); - } - } - - if (weak) { - return new WeakDisposerRef(strike); - } else { - return new SoftDisposerRef(strike); - } - } - - static interface DisposableStrike { - FontStrikeDisposer getDisposer(); - } - - static class SoftDisposerRef - extends SoftReference implements DisposableStrike { - - private FontStrikeDisposer disposer; - - public FontStrikeDisposer getDisposer() { - return disposer; - } - - SoftDisposerRef(FontStrike strike) { - super(strike, StrikeCache.refQueue); - disposer = strike.disposer; - Disposer.addReference(this, disposer); - } - } - - static class WeakDisposerRef - extends WeakReference implements DisposableStrike { - - private FontStrikeDisposer disposer; - - public FontStrikeDisposer getDisposer() { - return disposer; - } - - WeakDisposerRef(FontStrike strike) { - super(strike, StrikeCache.refQueue); - disposer = strike.disposer; - Disposer.addReference(this, disposer); - } - } - -} diff --git a/openjdk/sun/font/SunFontManager.java b/openjdk/sun/font/SunFontManager.java deleted file mode 100644 index 131784a8..00000000 --- a/openjdk/sun/font/SunFontManager.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - Copyright (C) 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import ikvm.internal.NotYetImplementedError; - -import java.awt.Font; -import java.awt.FontFormatException; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.StringTokenizer; -import java.util.TreeMap; -import java.util.Vector; -import java.util.concurrent.ConcurrentHashMap; - -import javax.swing.plaf.FontUIResource; -import sun.awt.AppContext; -import sun.awt.FontConfiguration; -import sun.awt.SunToolkit; -import sun.java2d.FontSupport; -import sun.util.logging.PlatformLogger; - -/** - * The base implementation of the {@link FontManager} interface. It implements - * the platform independent, shared parts of OpenJDK's FontManager - * implementations. The platform specific parts are declared as abstract - * methods that have to be implemented by specific implementations. - */ -public class SunFontManager implements FontManager { - - private static class TTFilter implements FilenameFilter { - public boolean accept(File dir,String name) { - /* all conveniently have the same suffix length */ - int offset = name.length()-4; - if (offset <= 0) { /* must be at least A.ttf */ - return false; - } else { - return(name.startsWith(".ttf", offset) || - name.startsWith(".TTF", offset) || - name.startsWith(".ttc", offset) || - name.startsWith(".TTC", offset) || - name.startsWith(".otf", offset) || - name.startsWith(".OTF", offset)); - } - } - } - - private static class T1Filter implements FilenameFilter { - public boolean accept(File dir,String name) { - if (noType1Font) { - return false; - } - /* all conveniently have the same suffix length */ - int offset = name.length()-4; - if (offset <= 0) { /* must be at least A.pfa */ - return false; - } else { - return(name.startsWith(".pfa", offset) || - name.startsWith(".pfb", offset) || - name.startsWith(".PFA", offset) || - name.startsWith(".PFB", offset)); - } - } - } - - /* No need to keep consing up new instances - reuse a singleton. - * The trade-off is that these objects don't get GC'd. - */ - private static final FilenameFilter ttFilter = new TTFilter(); - private static final FilenameFilter t1Filter = new T1Filter(); - - public static boolean noType1Font; - - /** - * Deprecated, unsupported hack - actually invokes a bug! - * Left in for a customer, don't remove. - */ - private boolean usePlatformFontMetrics = false; - - /** - * Returns the global SunFontManager instance. This is similar to - * {@link FontManagerFactory#getInstance()} but it returns a - * SunFontManager instance instead. This is only used in internal classes - * where we can safely assume that a SunFontManager is to be used. - * - * @return the global SunFontManager instance - */ - public static SunFontManager getInstance() { - FontManager fm = FontManagerFactory.getInstance(); - return (SunFontManager) fm; - } - - public FilenameFilter getTrueTypeFilter() { - return ttFilter; - } - - public FilenameFilter getType1Filter() { - return t1Filter; - } - - @Override - public boolean usingPerAppContextComposites() { - return _usingPerAppContextComposites; - } - - public Font2DHandle getNewComposite(String family, int style, - Font2DHandle handle) { - - if (!(handle.font2D instanceof CompositeFont)) { - return handle; - } - - CompositeFont oldComp = (CompositeFont)handle.font2D; - PhysicalFont oldFont = oldComp.getSlotFont(0); - - if (family == null) { - family = oldFont.getFamilyName(null); - } - if (style == -1) { - style = oldComp.getStyle(); - } - - Font2D newFont = findFont2D(family, style, NO_FALLBACK); - if (!(newFont instanceof PhysicalFont)) { - newFont = oldFont; - } - PhysicalFont physicalFont = (PhysicalFont)newFont; - CompositeFont dialog2D = - (CompositeFont)findFont2D("dialog", style, NO_FALLBACK); - if (dialog2D == null) { /* shouldn't happen */ - return handle; - } - CompositeFont compFont = new CompositeFont(physicalFont, dialog2D); - Font2DHandle newHandle = compFont.handle; - return newHandle; - } - - /* - * return String representation of style prepended with "." - * This is useful for performance to avoid unnecessary string operations. - */ - private static String dotStyleStr(int num) { - switch(num){ - case Font.BOLD: - return ".bold"; - case Font.ITALIC: - return ".italic"; - case Font.ITALIC | Font.BOLD: - return ".bolditalic"; - default: - return ".plain"; - } - } - - private ConcurrentHashMap<String, Font2D> fontNameCache = - new ConcurrentHashMap<String, Font2D>(); - /* - * The client supplies a name and a style. - * The name could be a family name, or a full name. - * A font may exist with the specified style, or it may - * exist only in some other style. For non-native fonts the scaler - * may be able to emulate the required style. - */ - public Font2D findFont2D(String name, int style, int fallback) { - String lowerCaseName = name.toLowerCase(Locale.ENGLISH); - String mapName = lowerCaseName + dotStyleStr(style); - Font2D font; - - /* If preferLocaleFonts() or preferProportionalFonts() has been - * called we may be using an alternate set of composite fonts in this - * app context. The presence of a pre-built name map indicates whether - * this is so, and gives access to the alternate composite for the - * name. - */ - if (_usingPerAppContextComposites) { - ConcurrentHashMap<String, Font2D> altNameCache = - (ConcurrentHashMap<String, Font2D>) - AppContext.getAppContext().get(CompositeFont.class); - if (altNameCache != null) { - font = (Font2D)altNameCache.get(mapName); - } else { - font = null; - } - } else { - font = fontNameCache.get(mapName); - } - if (font != null) { - return font; - } - - if (FontUtilities.isLogging()) { - FontUtilities.getLogger().info("Search for font: " + name); - } - - // The check below is just so that the bitmap fonts being set by - // AWT and Swing thru the desktop properties do not trigger the - // the load fonts case. The two bitmap fonts are now mapped to - // appropriate equivalents for serif and sansserif. - // Note that the cost of this comparison is only for the first - // call until the map is filled. - if (FontUtilities.isWindows) { - if (lowerCaseName.equals("ms sans serif")) { - name = "sansserif"; - } else if (lowerCaseName.equals("ms serif")) { - name = "serif"; - } - } - - /* This isn't intended to support a client passing in the - * string default, but if a client passes in null for the name - * the java.awt.Font class internally substitutes this name. - * So we need to recognise it here to prevent a loadFonts - * on the unrecognised name. The only potential problem with - * this is it would hide any real font called "default"! - * But that seems like a potential problem we can ignore for now. - */ - if (lowerCaseName.equals("default")) { - lowerCaseName = name = "dialog"; - } - - font = new PhysicalFont(name,style); - - switch (lowerCaseName){ - case "dialog": - font = new CompositeFont(font); //dialog must a CompositeFont, else there are ClassCastExceptions - break; - } - fontNameCache.put(mapName, font); - return font; - } - - /* - * Workaround for apps which are dependent on a font metrics bug - * in JDK 1.1. This is an unsupported win32 private setting. - * Left in for a customer - do not remove. - */ - public boolean usePlatformFontMetrics() { - return usePlatformFontMetrics; - } - - public Font2D createFont2D(File fontFile, int fontFormat, - boolean isCopy, CreatedFontTracker tracker) - throws FontFormatException { - throw new NotYetImplementedError(); - } - /* - * This is called when font is determined to be invalid/bad. - * It designed to be called (for example) by the font scaler - * when in processing a font file it is discovered to be incorrect. - * This is different than the case where fonts are discovered to - * be incorrect during initial verification, as such fonts are - * never registered. - * Handles to this font held are re-directed to a default font. - * This default may not be an ideal substitute buts it better than - * crashing This code assumes a PhysicalFont parameter as it doesn't - * make sense for a Composite to be "bad". - */ - public synchronized void deRegisterBadFont(Font2D font2D) { - if (!(font2D instanceof PhysicalFont)) { - /* We should never reach here, but just in case */ - return; - } else { - if (FontUtilities.isLogging()) { - FontUtilities.getLogger() - .severe("Deregister bad font: " + font2D); - } - throw new NotYetImplementedError(); - } - } - - /* Supporting "alternate" composite fonts on 2D graphics objects - * is accessed by the application by calling methods on the local - * GraphicsEnvironment. The overall implementation is described - * in one place, here, since otherwise the implementation is spread - * around it may be difficult to track. - * The methods below call into SunGraphicsEnvironment which creates a - * new FontConfiguration instance. The FontConfiguration class, - * and its platform sub-classes are updated to take parameters requesting - * these behaviours. This is then used to create new composite font - * instances. Since this calls the initCompositeFont method in - * SunGraphicsEnvironment it performs the same initialization as is - * performed normally. There may be some duplication of effort, but - * that code is already written to be able to perform properly if called - * to duplicate work. The main difference is that if we detect we are - * running in an applet/browser/Java plugin environment these new fonts - * are not placed in the "default" maps but into an AppContext instance. - * The font lookup mechanism in java.awt.Font.getFont2D() is also updated - * so that look-up for composite fonts will in that case always - * do a lookup rather than returning a cached result. - * This is inefficient but necessary else singleton java.awt.Font - * instances would not retrieve the correct Font2D for the appcontext. - * sun.font.FontManager.findFont2D is also updated to that it uses - * a name map cache specific to that appcontext. - * - * Getting an AppContext is expensive, so there is a global variable - * that records whether these methods have ever been called and can - * avoid the expense for almost all applications. Once the correct - * CompositeFont is associated with the Font, everything should work - * through existing mechanisms. - * A special case is that GraphicsEnvironment.getAllFonts() must - * return an AppContext specific list. - * - * Calling the methods below is "heavyweight" but it is expected that - * these methods will be called very rarely. - * - * If _usingPerAppContextComposites is true, we are in "applet" - * (eg browser) enviroment and at least one context has selected - * an alternate composite font behaviour. - * If _usingAlternateComposites is true, we are not in an "applet" - * environment and the (single) application has selected - * an alternate composite font behaviour. - * - * - Printing: The implementation delegates logical fonts to an AWT - * mechanism which cannot use these alternate configurations. - * We can detect that alternate fonts are in use and back-off to 2D, but - * that uses outlines. Much of this can be fixed with additional work - * but that may have to wait. The results should be correct, just not - * optimal. - */ - private boolean _usingPerAppContextComposites = false; - private boolean _usingAlternateComposites = false; - - /* This method doesn't check if alternates are selected in this app - * context. Its used by the FontMetrics caching code which in such - * a case cannot retrieve a cached metrics solely on the basis of - * the Font.equals() method since it needs to also check if the Font2D - * is the same. - * We also use non-standard composites for Swing native L&F fonts on - * Windows. In that case the policy is that the metrics reported are - * based solely on the physical font in the first slot which is the - * visible java.awt.Font. So in that case the metrics cache which tests - * the Font does what we want. In the near future when we expand the GTK - * logical font definitions we may need to revisit this if GTK reports - * combined metrics instead. For now though this test can be simple. - */ - public boolean maybeUsingAlternateCompositeFonts() { - return false; - } - - public boolean usingAlternateFontforJALocales() { - return false; - } - - public synchronized void preferLocaleFonts() { - if (FontUtilities.isLogging()) { - FontUtilities.getLogger().info("Entered preferLocaleFonts()."); - } - /* Test if re-ordering will have any effect */ - if (!FontConfiguration.willReorderForStartupLocale()) { - return; - } - - } - - public synchronized void preferProportionalFonts() { - throw new NotYetImplementedError(); - } - - public boolean registerFont(Font font) { - /* This method should not be called with "null". - * It is the caller's responsibility to ensure that. - */ - if (font == null) { - return false; - } - throw new NotYetImplementedError(); - } - - /* Called to register fall back fonts */ - public void registerFontsInDir(String fallbackDirName) { - } - - /** - * Returns file name for default font, either absolute - * or relative as needed by registerFontFile. - */ - public synchronized String getDefaultFontFile() { - return null; - } - - /** - * Returns face name for default font, or null if - * no face names are used for CompositeFontDescriptors - * for this platform. - */ - public synchronized String getDefaultFontFaceName() { - return null; - } - - protected FontUIResource getFontConfigFUIR(String family, int style, - int size) - { - return new FontUIResource(family, style, size); - } - - /** - * Create a new Font2D without caching. This is used from createFont - * - * @param family - * .NET FontFamily - * @param style - * the style - * @return a Font2D - */ - public static Font2D createFont2D( cli.System.Drawing.FontFamily family, int style ) { - return new PhysicalFont( family, style ); - } -} diff --git a/openjdk/sun/font/TrueTypeFont.java b/openjdk/sun/font/TrueTypeFont.java deleted file mode 100644 index 83000327..00000000 --- a/openjdk/sun/font/TrueTypeFont.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (C) 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.font; - -import cli.System.Drawing.FontFamily; - -public class TrueTypeFont extends PhysicalFont { - - public static final int GPOSTag = 0x47504F53; // 'GPOS' - public static final int GSUBTag = 0x47535542; // 'GSUB' - - public TrueTypeFont(String name, int style) { - super(name, style); - } - - public TrueTypeFont(FontFamily family, int style) { - super(family, style); - } - - Object getDirectoryEntry(int tag) { - return null; - } -} diff --git a/openjdk/sun/java2d/HeadlessGraphicsEnvironment.java b/openjdk/sun/java2d/HeadlessGraphicsEnvironment.java deleted file mode 100644 index 29c05387..00000000 --- a/openjdk/sun/java2d/HeadlessGraphicsEnvironment.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.java2d; - -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.GraphicsDevice; -import java.awt.GraphicsEnvironment; -import java.awt.HeadlessException; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.image.BufferedImage; -import java.util.Locale; - - -/** - * Placeholder for not supported headless environment - */ -public class HeadlessGraphicsEnvironment extends GraphicsEnvironment{ - - private final GraphicsEnvironment env; - - - public HeadlessGraphicsEnvironment(GraphicsEnvironment env){ - this.env = env; - } - - /** - * {@inheritDoc} - */ - @Override - public Graphics2D createGraphics(BufferedImage img){ - return env.createGraphics(img); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj){ - return env.equals(obj); - } - - /** - * {@inheritDoc} - */ - @Override - public Font[] getAllFonts(){ - return env.getAllFonts(); - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getAvailableFontFamilyNames(){ - return env.getAvailableFontFamilyNames(); - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getAvailableFontFamilyNames(Locale l){ - return env.getAvailableFontFamilyNames(l); - } - - /** - * {@inheritDoc} - */ - @Override - public Point getCenterPoint() throws HeadlessException{ - return env.getCenterPoint(); - } - - /** - * {@inheritDoc} - */ - @Override - public GraphicsDevice getDefaultScreenDevice() throws HeadlessException{ - return env.getDefaultScreenDevice(); - } - - /** - * {@inheritDoc} - */ - @Override - public Rectangle getMaximumWindowBounds() throws HeadlessException{ - return env.getMaximumWindowBounds(); - } - - /** - * {@inheritDoc} - */ - @Override - public GraphicsDevice[] getScreenDevices() throws HeadlessException{ - return env.getScreenDevices(); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode(){ - return env.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isHeadlessInstance(){ - return env.isHeadlessInstance(); - } - - /** - * {@inheritDoc} - */ - @Override - public void preferLocaleFonts(){ - env.preferLocaleFonts(); - } - - /** - * {@inheritDoc} - */ - @Override - public void preferProportionalFonts(){ - env.preferProportionalFonts(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean registerFont(Font font){ - return env.registerFont(font); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString(){ - return env.toString(); - } -} diff --git a/openjdk/sun/java2d/SunCompositeContext.java b/openjdk/sun/java2d/SunCompositeContext.java deleted file mode 100644 index 25291c2f..00000000 --- a/openjdk/sun/java2d/SunCompositeContext.java +++ /dev/null @@ -1,316 +0,0 @@ -/* AlphaCompositeContext.java -- CompositeContext impl for AlphaComposite - Copyright (C) 2006 Free Software Foundation, Inc. - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath 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 for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package sun.java2d; - -import java.awt.AWTError; -import java.awt.AlphaComposite; -import java.awt.CompositeContext; -import java.awt.image.ColorModel; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; - -/** - * A CompositeContext implementation for {@link AlphaComposite}. - * - * @author Roman Kennke (kennke@aicas.com) - */ -public class SunCompositeContext - implements CompositeContext -{ - - /** - * The Composite object for which we perform compositing. - */ - private AlphaComposite composite; - - /** - * The source color model. - */ - private ColorModel srcColorModel; - - /** - * The destination color model. - */ - private ColorModel dstColorModel; - - /** - * The blending factor for the source. - */ - private float fs; - - /** - * The blending factor for the destination. - */ - private float fd; - - /** - * Creates a new AlphaCompositeContext. - * - * @param aComp the AlphaComposite object - * @param srcCM the source color model - * @param dstCM the destination color model - */ - public SunCompositeContext(AlphaComposite aComp, ColorModel srcCM, - ColorModel dstCM) - { - composite = aComp; - srcColorModel = srcCM; - dstColorModel = dstCM; - - - // Determine the blending factors according to the rule in the - // AlphaComposite. For some rules the factors must be determined - // dynamically because they depend on the actual pixel value. - switch (composite.getRule()) - { - case AlphaComposite.CLEAR: - fs = 0.F; - fd= 0.F; - break; - case AlphaComposite.DST: - fs = 0.F; - fd= 1.F; - break; - case AlphaComposite.DST_ATOP: - fs = 1.F; // Determined later as 1 - alpha_dst; - fd = 1.F; // Determined later as alpha_src; - break; - case AlphaComposite.DST_IN: - fs = 0.F; - fd = 0.F; // Determined later as alpha_src; - break; - case AlphaComposite.DST_OUT: - fs = 0.F; - fd = 0.F; // Determined later as 1 - alpha_src; - break; - case AlphaComposite.DST_OVER: - fs = 1.F; // Determined later as 1 - alpha_dst. - fd= 1.F; - break; - case AlphaComposite.SRC: - fs = 1.F; - fd= 0.F; - break; - case AlphaComposite.SRC_ATOP: - fs = 1.F; // Determined later as alpha_dst; - fd = 1.F; // Determined later as 1 - alpha_src; - break; - case AlphaComposite.SRC_IN: - fs = 0.F; // Determined later as alpha_dst; - fd = 0.F; - break; - case AlphaComposite.SRC_OUT: - fs = 0.F; // Determined later as 1 - alpha_dst; - fd = 0.F; - break; - case AlphaComposite.SRC_OVER: - fs = 1.F; - fd= 1.F; // Determined later as 1 - alpha_src. - break; - case AlphaComposite.XOR: - fs = 1.F; // Determined later as 1 - alpha_dst. - fd= 1.F; // Determined later as 1 - alpha_src. - break; - default: - throw new AWTError("Illegal AlphaComposite rule"); - } - - } - - /** - * Releases all resources held by this composite object. - */ - public void dispose() - { - // Nothing to do here yet. - } - - /** - * Performs compositing according to the rules specified in the - * AlphaComposite from the constructor. - */ - public void compose(Raster src, Raster dstIn, WritableRaster dstOut) - { - - // TODO: This implementation is very general and highly inefficient. There - // are two possible ways to optimize this: - // 1. Special cased implementations for common ColorModels and transfer - // types. - // 2. Native implementation. - - int x0 = src.getMinX(); - int y0 = src.getMinY(); - int width = src.getWidth(); - int height = src.getHeight(); - int x1 = x0 + width; - int y1 = y0 + height; - - Object srcPixel = null; - Object dstPixel = null; - - // Prepare the array that holds the color and alpha components of the - // source pixels. - float[] srcComponents; - int srcComponentsLength = srcColorModel.getNumComponents(); - if (! srcColorModel.hasAlpha()) - srcComponentsLength += 1; - srcComponents = new float[srcComponentsLength]; - - // Prepare the array that holds the color and alpha components of the - // destination pixels. - float[] dstComponents; - int dstComponentsLength = dstColorModel.getNumComponents(); - if (! dstColorModel.hasAlpha()) - dstComponentsLength += 1; - dstComponents = new float[dstComponentsLength]; - - if (srcComponentsLength != dstComponentsLength) - throw new AWTError("The color models of the source and destination have" - + "incompatible number of color components"); - - int srcTransferType = srcColorModel.getTransferType(); - int dstTransferType = dstColorModel.getTransferType(); - - for (int y = y0; y < y1; y++) - { - for (int x = x0; x < x1; x++) - { - // Fetch source pixel. - srcPixel = src.getDataElements(x, y, (int[]) srcPixel); - // Fetch destination pixel. - dstPixel = dstIn.getDataElements(x, y, dstPixel); - // Get normalized components. This is the only type that is - // guaranteed to be supported by all ColorModels. - srcComponents = - srcColorModel.getNormalizedComponents(srcPixel, srcComponents, 0); - if (! srcColorModel.hasAlpha()) - srcComponents[srcComponentsLength - 1] = 1.0F; - dstComponents = - dstColorModel.getNormalizedComponents(dstPixel, dstComponents, 0); - if (! dstColorModel.hasAlpha()) - dstComponents[dstComponentsLength - 1] = 1.0F; - - // Prepare the input. - float compositeAlpha = composite.getAlpha(); - srcComponents[srcComponentsLength - 1] *= compositeAlpha; - if (srcColorModel.isAlphaPremultiplied()) - { - for (int i = srcComponentsLength - 2; i >= 0; i--) - srcComponents[i] *= compositeAlpha; - } - else - { - for (int i = srcComponentsLength - 2; i >= 0; i--) - srcComponents[i] *= srcComponents[srcComponentsLength - 1]; - } - if (! dstColorModel.isAlphaPremultiplied()) - { - for (int i = dstComponentsLength - 2; i >= 0; i--) - dstComponents[i] *= dstComponents[dstComponents.length - 1]; - } - - // Determine the blending factors according to the rule in the - // AlphaComposite. For some rules the factors must be determined - // dynamically because they depend on the actual pixel value. - float srcAlpha = srcComponents[srcComponentsLength - 1]; - float dstAlpha = dstComponents[dstComponentsLength - 1]; - switch (composite.getRule()) - { - case AlphaComposite.DST_ATOP: - fs = 1.F - dstAlpha; - fd = srcAlpha; - break; - case AlphaComposite.DST_IN: - fd = srcAlpha; - break; - case AlphaComposite.DST_OUT: - fd = 1.F - srcAlpha; - break; - case AlphaComposite.DST_OVER: - fs = 1.F - dstAlpha; - break; - case AlphaComposite.SRC_ATOP: - fs = srcAlpha; - fd = 1.F - srcAlpha; - break; - case AlphaComposite.SRC_IN: - fs = dstAlpha; - break; - case AlphaComposite.SRC_OUT: - fs = 1.F - dstAlpha; - break; - case AlphaComposite.SRC_OVER: - fd= 1.F - srcAlpha; - break; - case AlphaComposite.XOR: - fs = 1.F - dstAlpha; - fd= 1.F - srcAlpha; - break; - default: - // For the other cases the factors have already been determined - // in the constructor. - } - - // Apply the blending equation to the pixels. - for (int i = 0; i < srcComponentsLength; i++) - { - dstComponents[i] = srcComponents[i] * fs - + dstComponents[i] * fd; - } - - // Convert the result back when the destination is not - // alpha-premultiplied. - dstAlpha = dstComponents[dstComponentsLength - 1]; - if (!dstColorModel.isAlphaPremultiplied() && dstAlpha != 0.F) - { - for (int i = 0; i < dstComponentsLength - 1; i++) - { - dstComponents[i] = dstComponents[i] / dstAlpha; - } - } - - // Store the result in the destination raster. - dstPixel = dstColorModel.getDataElements(dstComponents, 0, - dstPixel); - dstOut.setDataElements(x, y, dstPixel); - } // End X loop. - } // End Y loop. - } - -} diff --git a/openjdk/sun/java2d/SunGraphics2D.java b/openjdk/sun/java2d/SunGraphics2D.java deleted file mode 100644 index ef7dc57a..00000000 --- a/openjdk/sun/java2d/SunGraphics2D.java +++ /dev/null @@ -1,844 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.java2d; - -import java.awt.*; -import java.awt.RenderingHints.Key; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -import sun.java2d.pipe.Region; -import ikvm.internal.NotYetImplementedError; - -/** - * A replacement of the Sun implementation that redirect to the NetGraphics - */ -public class SunGraphics2D extends Graphics2D{ - /* - * Attribute States - */ - /* Paint */ - public static final int PAINT_CUSTOM = 6; /* Any other Paint object */ - public static final int PAINT_TEXTURE = 5; /* Tiled Image */ - public static final int PAINT_RAD_GRADIENT = 4; /* Color RadialGradient */ - public static final int PAINT_LIN_GRADIENT = 3; /* Color LinearGradient */ - public static final int PAINT_GRADIENT = 2; /* Color Gradient */ - public static final int PAINT_ALPHACOLOR = 1; /* Non-opaque Color */ - public static final int PAINT_OPAQUECOLOR = 0; /* Opaque Color */ - - /* Composite*/ - public static final int COMP_CUSTOM = 3;/* Custom Composite */ - public static final int COMP_XOR = 2;/* XOR Mode Composite */ - public static final int COMP_ALPHA = 1;/* AlphaComposite */ - public static final int COMP_ISCOPY = 0;/* simple stores into destination, - * i.e. Src, SrcOverNoEa, and other - * alpha modes which replace - * the destination. - */ - - /* Stroke */ - public static final int STROKE_CUSTOM = 3; /* custom Stroke */ - public static final int STROKE_WIDE = 2; /* BasicStroke */ - public static final int STROKE_THINDASHED = 1; /* BasicStroke */ - public static final int STROKE_THIN = 0; /* BasicStroke */ - - /* Transform */ - public static final int TRANSFORM_GENERIC = 4; /* any 3x2 */ - public static final int TRANSFORM_TRANSLATESCALE = 3; /* scale XY */ - public static final int TRANSFORM_ANY_TRANSLATE = 2; /* non-int translate */ - public static final int TRANSFORM_INT_TRANSLATE = 1; /* int translate */ - public static final int TRANSFORM_ISIDENT = 0; /* Identity */ - - /* Clipping */ - public static final int CLIP_SHAPE = 2; /* arbitrary clip */ - public static final int CLIP_RECTANGULAR = 1; /* rectangular clip */ - public static final int CLIP_DEVICE = 0; /* no clipping set */ - - private static SurfaceData surfaceData = new SurfaceData(); - - public int strokeState; - - public Stroke stroke; - public int strokeHint; - - public Region clipRegion; - public int constrainX; - public int constrainY; - - public AffineTransform transform; - - /** a instance of cli.ikvm.awt.NetGraphics */ - private final Graphics2D graphics; - - /** - * TODO implement the real Constructor - */ - private SunGraphics2D(){ - graphics = null; - } - - /** - * {@inheritDoc} - */ - @Override - public void addRenderingHints(Map<?, ?> hints){ - graphics.addRenderingHints(hints); - } - - /** - * {@inheritDoc} - */ - @Override - public void clearRect(int x, int y, int width, int height){ - graphics.clearRect(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void clip(Shape s){ - graphics.clip(s); - } - - /** - * {@inheritDoc} - */ - @Override - public void clipRect(int x, int y, int width, int height){ - graphics.clipRect(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void copyArea(int x, int y, int width, int height, int dx, int dy){ - graphics.copyArea(x, y, width, height, dx, dy); - } - - /** - * {@inheritDoc} - */ - @Override - public Graphics create(){ - return graphics.create(); - } - - /** - * {@inheritDoc} - */ - @Override - public Graphics create(int x, int y, int width, int height){ - return graphics.create(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void dispose(){ - graphics.dispose(); - } - - /** - * {@inheritDoc} - */ - @Override - public void draw(Shape s){ - graphics.draw(s); - } - - /** - * {@inheritDoc} - */ - @Override - public void draw3DRect(int x, int y, int width, int height, boolean raised){ - graphics.draw3DRect(x, y, width, height, raised); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawArc(int x, int y, int width, int height, int arcStart, int arcAngle){ - graphics.drawArc(x, y, width, height, arcStart, arcAngle); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawBytes(byte[] data, int offset, int length, int x, int y){ - graphics.drawBytes(data, offset, length, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawChars(char[] data, int offset, int length, int x, int y){ - graphics.drawChars(data, offset, length, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawGlyphVector(GlyphVector g, float x, float y){ - graphics.drawGlyphVector(g, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y){ - graphics.drawImage(img, op, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs){ - return graphics.drawImage(img, xform, obs); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image image, int x, int y, Color bgcolor, ImageObserver observer){ - return graphics.drawImage(image, x, y, bgcolor, observer); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image image, int x, int y, ImageObserver observer){ - return graphics.drawImage(image, x, y, observer); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image image, int x, int y, int width, int height, Color bgcolor, ImageObserver observer){ - return graphics.drawImage(image, x, y, width, height, bgcolor, observer); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image image, int x, int y, int width, int height, ImageObserver observer){ - return graphics.drawImage(image, x, y, width, height, observer); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, - Color bgcolor, ImageObserver observer){ - return graphics.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, - ImageObserver observer){ - return graphics.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawLine(int x1, int y1, int x2, int y2){ - graphics.drawLine(x1, y1, x2, y2); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawOval(int x, int y, int width, int height){ - graphics.drawOval(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawPolygon(int[] points, int[] points2, int npoints){ - graphics.drawPolygon(points, points2, npoints); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawPolygon(Polygon polygon){ - graphics.drawPolygon(polygon); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawPolyline(int[] points, int[] points2, int npoints){ - graphics.drawPolyline(points, points2, npoints); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawRect(int x, int y, int width, int height){ - graphics.drawRect(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawRenderableImage(RenderableImage img, AffineTransform xform){ - graphics.drawRenderableImage(img, xform); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawRenderedImage(RenderedImage img, AffineTransform xform){ - graphics.drawRenderedImage(img, xform); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight){ - graphics.drawRoundRect(x, y, width, height, arcWidth, arcHeight); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawString(AttributedCharacterIterator iterator, float x, float y){ - graphics.drawString(iterator, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawString(AttributedCharacterIterator iterator, int x, int y){ - graphics.drawString(iterator, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawString(String str, float x, float y){ - graphics.drawString(str, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void drawString(String str, int x, int y){ - graphics.drawString(str, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj){ - return graphics.equals(obj); - } - - /** - * {@inheritDoc} - */ - @Override - public void fill(Shape s){ - graphics.fill(s); - } - - /** - * {@inheritDoc} - */ - @Override - public void fill3DRect(int x, int y, int width, int height, boolean raised){ - graphics.fill3DRect(x, y, width, height, raised); - } - - /** - * {@inheritDoc} - */ - @Override - public void fillArc(int x, int y, int width, int height, int arcStart, int arcAngle){ - graphics.fillArc(x, y, width, height, arcStart, arcAngle); - } - - /** - * {@inheritDoc} - */ - @Override - public void fillOval(int x, int y, int width, int height){ - graphics.fillOval(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void fillPolygon(int[] points, int[] points2, int npoints){ - graphics.fillPolygon(points, points2, npoints); - } - - /** - * {@inheritDoc} - */ - @Override - public void fillPolygon(Polygon polygon){ - graphics.fillPolygon(polygon); - } - - /** - * {@inheritDoc} - */ - @Override - public void fillRect(int x, int y, int width, int height){ - graphics.fillRect(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight){ - graphics.fillRoundRect(x, y, width, height, arcWidth, arcHeight); - } - - /** - * {@inheritDoc} - */ - @Override - public void finalize(){ - graphics.finalize(); - } - - /** - * {@inheritDoc} - */ - @Override - public Color getBackground(){ - return graphics.getBackground(); - } - - /** - * {@inheritDoc} - */ - @Override - public Shape getClip(){ - return graphics.getClip(); - } - - /** - * {@inheritDoc} - */ - @Override - public Rectangle getClipBounds(){ - return graphics.getClipBounds(); - } - - /** - * {@inheritDoc} - */ - @Override - public Rectangle getClipBounds(Rectangle r){ - return graphics.getClipBounds(r); - } - - /** - * {@inheritDoc} - */ - @Override - public Rectangle getClipRect(){ - return graphics.getClipRect(); - } - - /** - * {@inheritDoc} - */ - @Override - public Color getColor(){ - return graphics.getColor(); - } - - /** - * {@inheritDoc} - */ - @Override - public Composite getComposite(){ - return graphics.getComposite(); - } - - /** - * {@inheritDoc} - */ - @Override - public GraphicsConfiguration getDeviceConfiguration(){ - return graphics.getDeviceConfiguration(); - } - - /** - * {@inheritDoc} - */ - @Override - public Font getFont(){ - return graphics.getFont(); - } - - /** - * {@inheritDoc} - */ - @Override - public FontMetrics getFontMetrics(){ - return graphics.getFontMetrics(); - } - - /** - * {@inheritDoc} - */ - @Override - public FontMetrics getFontMetrics(Font font){ - return graphics.getFontMetrics(font); - } - - /** - * {@inheritDoc} - */ - @Override - public FontRenderContext getFontRenderContext(){ - return graphics.getFontRenderContext(); - } - - /** - * {@inheritDoc} - */ - @Override - public Paint getPaint(){ - return graphics.getPaint(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getRenderingHint(Key hintKey){ - return graphics.getRenderingHint(hintKey); - } - - /** - * {@inheritDoc} - */ - @Override - public RenderingHints getRenderingHints(){ - return graphics.getRenderingHints(); - } - - /** - * {@inheritDoc} - */ - @Override - public Stroke getStroke(){ - return graphics.getStroke(); - } - - /** - * {@inheritDoc} - */ - @Override - public AffineTransform getTransform(){ - return graphics.getTransform(); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode(){ - return graphics.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hit(Rectangle rect, Shape s, boolean onStroke){ - return graphics.hit(rect, s, onStroke); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hitClip(int x, int y, int width, int height){ - return graphics.hitClip(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void rotate(double theta, double x, double y){ - graphics.rotate(theta, x, y); - } - - /** - * {@inheritDoc} - */ - @Override - public void rotate(double theta){ - graphics.rotate(theta); - } - - /** - * {@inheritDoc} - */ - @Override - public void scale(double sx, double sy){ - graphics.scale(sx, sy); - } - - /** - * {@inheritDoc} - */ - @Override - public void setBackground(Color color){ - graphics.setBackground(color); - } - - /** - * {@inheritDoc} - */ - @Override - public void setClip(int x, int y, int width, int height){ - graphics.setClip(x, y, width, height); - } - - /** - * {@inheritDoc} - */ - @Override - public void setClip(Shape clip){ - graphics.setClip(clip); - } - - /** - * {@inheritDoc} - */ - @Override - public void setColor(Color color){ - graphics.setColor(color); - } - - /** - * {@inheritDoc} - */ - @Override - public void setComposite(Composite comp){ - graphics.setComposite(comp); - } - - /** - * {@inheritDoc} - */ - @Override - public void setFont(Font font){ - graphics.setFont(font); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPaint(Paint paint){ - graphics.setPaint(paint); - } - - /** - * {@inheritDoc} - */ - @Override - public void setPaintMode(){ - graphics.setPaintMode(); - } - - /** - * {@inheritDoc} - */ - @Override - public void setRenderingHint(Key hintKey, Object hintValue){ - graphics.setRenderingHint(hintKey, hintValue); - } - - /** - * {@inheritDoc} - */ - @Override - public void setRenderingHints(Map<?, ?> hints){ - graphics.setRenderingHints(hints); - } - - /** - * {@inheritDoc} - */ - @Override - public void setStroke(Stroke s){ - graphics.setStroke(s); - } - - /** - * {@inheritDoc} - */ - @Override - public void setTransform(AffineTransform Tx){ - graphics.setTransform(Tx); - } - - /** - * {@inheritDoc} - */ - @Override - public void setXORMode(Color color){ - graphics.setXORMode(color); - } - - /** - * {@inheritDoc} - */ - @Override - public void shear(double shx, double shy){ - graphics.shear(shx, shy); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString(){ - return graphics.toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public void transform(AffineTransform Tx){ - graphics.transform(Tx); - } - - /** - * {@inheritDoc} - */ - @Override - public void translate(double tx, double ty){ - graphics.translate(tx, ty); - } - - /** - * {@inheritDoc} - */ - @Override - public void translate(int x, int y){ - graphics.translate(x, y); - } - - /* - * Special functions of the original SunGraphics2D - * - */ - - /* - * Intersect usrClip bounds and device bounds to determine the composite - * rendering boundaries. - */ - public Region getCompClip() { - throw new NotYetImplementedError(); - } - - /** - * Constrain rendering for lightweight objects. - * - * REMIND: This method will back off to the "workaround" - * of using translate and clipRect if the Graphics - * to be constrained has a complex transform. The - * drawback of the workaround is that the resulting - * clip and device origin cannot be "enforced". - * - * @exception IllegalStateException If the Graphics - * to be constrained has a complex transform. - */ - public void constrain(int i, int j, int k, int l){ - throw new NotYetImplementedError(); - } - - /** - * Return the SurfaceData object assigned to manage the destination - * drawable surface of this Graphics2D. - */ - public final SurfaceData getSurfaceData() { - return surfaceData; - } - - /** - * Returns destination that this Graphics renders to. This could be - * either an Image or a Component; subclasses of SurfaceData are - * responsible for returning the appropriate object. - */ - public Object getDestination() { - throw new NotYetImplementedError(); - } -} diff --git a/openjdk/sun/java2d/SunGraphicsEnvironment.java b/openjdk/sun/java2d/SunGraphicsEnvironment.java deleted file mode 100644 index 8f746145..00000000 --- a/openjdk/sun/java2d/SunGraphicsEnvironment.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.java2d; - -import java.awt.GraphicsConfiguration; -import java.awt.GraphicsDevice; -import java.awt.GraphicsEnvironment; -import java.awt.Insets; -import java.awt.peer.ComponentPeer; -import java.awt.Rectangle; -import java.awt.Toolkit; - -import sun.awt.DisplayChangedListener; -import sun.awt.SunDisplayChanger; - - - -/** - * A replacement of the Sun implementation that will extends from from NetGraphicsEnvironment - */ -public abstract class SunGraphicsEnvironment extends GraphicsEnvironment{ - - /** - * Return the bounds of a GraphicsDevice, less its screen insets. - * See also java.awt.GraphicsEnvironment.getUsableBounds(); - */ - public static Rectangle getUsableBounds(GraphicsDevice gd) { - GraphicsConfiguration gc = gd.getDefaultConfiguration(); - Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc); - Rectangle usableBounds = gc.getBounds(); - - usableBounds.x += insets.left; - usableBounds.y += insets.top; - usableBounds.width -= (insets.left + insets.right); - usableBounds.height -= (insets.top + insets.bottom); - - return usableBounds; - } - - /** - * Returns true when the display is local, false for remote displays. - * - * @return true when the display is local, false for remote displays - */ - public abstract boolean isDisplayLocal(); - - /* - * ----DISPLAY CHANGE SUPPORT---- - */ - - protected SunDisplayChanger displayChanger = new SunDisplayChanger(); - - /** - * Add a DisplayChangeListener to be notified when the display settings - * are changed. - */ - public void addDisplayChangedListener(DisplayChangedListener client) { - displayChanger.add(client); - } - - /** - * Remove a DisplayChangeListener from Win32GraphicsEnvironment - */ - public void removeDisplayChangedListener(DisplayChangedListener client) { - displayChanger.remove(client); - } - - /* - * ----END DISPLAY CHANGE SUPPORT---- - */ - - /** - * Returns true if FlipBufferStrategy with COPIED buffer contents - * is preferred for this peer's GraphicsConfiguration over - * BlitBufferStrategy, false otherwise. - * - * The reason FlipBS could be preferred is that in some configurations - * an accelerated copy to the screen is supported (like Direct3D 9) - * - * @return true if flip strategy should be used, false otherwise - */ - public boolean isFlipStrategyPreferred(ComponentPeer peer) { - return false; - } -} diff --git a/openjdk/sun/java2d/SurfaceData.java b/openjdk/sun/java2d/SurfaceData.java deleted file mode 100644 index 6972b301..00000000 --- a/openjdk/sun/java2d/SurfaceData.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright (C) 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.java2d; - -public class SurfaceData { - - public boolean isSurfaceLost() { - return false; - } - -} diff --git a/openjdk/sun/java2d/cmm/lcms/LCMS.java b/openjdk/sun/java2d/cmm/lcms/LCMS.java deleted file mode 100644 index 06bff7bf..00000000 --- a/openjdk/sun/java2d/cmm/lcms/LCMS.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - Copyright (C) 2009 Jeroen Frijters - Copyright (C) 2010 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.java2d.cmm.lcms; - -import gnu.java.awt.color.TagEntry; - -import java.awt.color.CMMException; -import java.awt.color.ColorSpace; -import java.awt.color.ICC_Profile; -import java.awt.color.ICC_ProfileGray; -import java.awt.color.ICC_ProfileRGB; -import java.awt.image.BufferedImage; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Hashtable; - -import sun.java2d.cmm.ColorTransform; -import sun.java2d.cmm.PCMM; - -// dummy color management implementation -public class LCMS implements PCMM { - - private static final int HEADER_SIZE = 128; - - private final ArrayList<ProfileData> profiles = new ArrayList<ProfileData>(); - - public synchronized long loadProfile( byte[] data ) { - int free = profiles.indexOf( null ); - if( free != -1 ) { - profiles.set( free, new ProfileData( data.clone()) ); - return free; - } else { - long id = profiles.size(); - profiles.add( new ProfileData( data.clone()) ); - return id; - } - } - - public synchronized void freeProfile( long profileID ) { - profiles.set( (int)profileID, null ); - } - - public synchronized int getProfileSize( long profileID ) { - return profiles.get( (int)profileID ).data.length; - } - - public synchronized void getProfileData( long profileID, byte[] data ) { - byte[] src = profiles.get( (int)profileID ).data; - System.arraycopy( src, 0, data, 0, src.length ); - } - - public void getTagData( long profileID, int tagSignature, byte[] data ) { - ProfileData profile = profiles.get( (int)profileID ); - if( tagSignature == ICC_Profile.icSigHead ) { - byte[] src = profile.data; - System.arraycopy( src, 0, data, 0, HEADER_SIZE ); - } else { - TagEntry entry = profile.tags.get( tagSignature ); - if( entry == null ){ - throw new CMMException( "tag does not exist: " + tagSignature ); - } - byte[] src = entry.getData(); - System.arraycopy( src, 0, data, 0, src.length ); - } - - } - - public int getTagSize( long profileID, int tagSignature ) { - if( tagSignature == ICC_Profile.icSigHead ) { - return HEADER_SIZE; - } - ProfileData profile = profiles.get( (int)profileID ); - TagEntry entry = profile.tags.get( tagSignature ); - if( entry == null ){ - throw new CMMException( "tag does not exist: " + tagSignature ); - } - return entry.getData().length; - } - - public void setTagData(long profileID, int tagSignature, byte[] data) - { - throw new CMMException("Not implemented"); - } - - public ColorTransform createTransform(ICC_Profile profile, int renderType, int transformType) - { - return new DummyColorTransform(); - } - - public ColorTransform createTransform(ColorTransform[] transforms) - { - return new DummyColorTransform(); - } - - private static class ProfileData{ - - private final byte[] data; - private final Hashtable<Integer, TagEntry> tags; - - private ProfileData(byte[] data){ - this.data = data; - this.tags = createTagTable( data ); - } - - private static Hashtable<Integer, TagEntry> createTagTable( byte[] data ) throws IllegalArgumentException { - ByteBuffer buf = ByteBuffer.wrap( data ); - int nTags = buf.getInt( HEADER_SIZE ); - - Hashtable<Integer, TagEntry> tagTable = new Hashtable<Integer, TagEntry>(); - for( int i = 0; i < nTags; i++ ) { - int sig = buf.getInt( HEADER_SIZE + i * TagEntry.entrySize + 4 ); - int offset = buf.getInt( HEADER_SIZE + i * TagEntry.entrySize + 8 ); - int size = buf.getInt( HEADER_SIZE + i * TagEntry.entrySize + 12 ); - TagEntry te = new TagEntry( sig, offset, size, data ); - - if( tagTable.put( sig, te ) != null ) - throw new IllegalArgumentException( "Duplicate tag in profile:" + te ); - } - return tagTable; - } - - } - - static class DummyColorTransform implements ColorTransform - { - public int getNumInComponents() - { - throw new CMMException("Not implemented"); - } - - public int getNumOutComponents() - { - throw new CMMException("Not implemented"); - } - - public void colorConvert(BufferedImage src, BufferedImage dst) - { - throw new CMMException("Not implemented"); - } - - public void colorConvert(Raster src, WritableRaster dst, float[] srcMinVal, float[] srcMaxVal, float[] dstMinVal, float[]dstMaxVal) - { - throw new CMMException("Not implemented"); - } - - public void colorConvert(Raster src, WritableRaster dst) - { - throw new CMMException("Not implemented"); - } - - public short[] colorConvert(short[] src, short[] dest) - { - throw new CMMException("Not implemented"); - } - - public byte[] colorConvert(byte[] src, byte[] dest) - { - throw new CMMException("Not implemented"); - } - } -} diff --git a/openjdk/sun/java2d/pipe/ShapeSpanIterator.java b/openjdk/sun/java2d/pipe/ShapeSpanIterator.java deleted file mode 100644 index f320ad1d..00000000 --- a/openjdk/sun/java2d/pipe/ShapeSpanIterator.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.java2d.pipe; - -import java.awt.geom.PathIterator; -import ikvm.internal.NotYetImplementedError; - -/** - * Replacement for compiling only - */ -public class ShapeSpanIterator implements SpanIterator{ - - public ShapeSpanIterator(boolean normalize){ - throw new NotYetImplementedError(); - } - - public void setOutputArea(Region devBounds){ - // TODO Auto-generated method stub - - } - - public void appendPath(PathIterator pathIterator){ - // TODO Auto-generated method stub - - } - - public void getPathBox(int[] box){ - // TODO Auto-generated method stub - - } - - @Override - public long getNativeIterator(){ - // TODO Auto-generated method stub - return 0; - } - - @Override - public void intersectClipBox(int lox, int loy, int hix, int hiy){ - // TODO Auto-generated method stub - - } - - @Override - public boolean nextSpan(int[] spanbox){ - // TODO Auto-generated method stub - return false; - } - - @Override - public void skipDownTo(int y){ - // TODO Auto-generated method stub - - } - - public void dispose(){ - // TODO Auto-generated method stub - - } - -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcCallableStatement.java b/openjdk/sun/jdbc/odbc/JdbcOdbcCallableStatement.java deleted file mode 100644 index 12a15ff3..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcCallableStatement.java +++ /dev/null @@ -1,662 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.*; -import java.util.Calendar; -import java.util.Map; - -import cli.System.Data.*; -import cli.System.Data.Common.*; -import cli.System.Data.Odbc.*; - - - -/** - * @author Volker Berlin - */ -public class JdbcOdbcCallableStatement extends JdbcOdbcPreparedStatement implements CallableStatement{ - - private final Parameters parameters = new Parameters(); - - public JdbcOdbcCallableStatement(JdbcOdbcConnection jdbcConn, OdbcCommand command, String sql, int resultSetType, int resultSetConcurrency){ - super(jdbcConn, command, sql, resultSetType, resultSetConcurrency); - } - - - public final Array getArray(int parameterIndex){ - return parameters.getArray(parameterIndex); - } - - - public final Array getArray(String parameterName) throws SQLException{ - return parameters.getArray(parameterName); - } - - - public final BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException{ - return parameters.getBigDecimal(parameterIndex, scale); - } - - - public final BigDecimal getBigDecimal(int parameterIndex) throws SQLException{ - return parameters.getBigDecimal(parameterIndex); - } - - - public final BigDecimal getBigDecimal(String parameterName) throws SQLException{ - return parameters.getBigDecimal(parameterName); - } - - - public final Blob getBlob(int parameterIndex){ - return parameters.getBlob(parameterIndex); - } - - - public final Blob getBlob(String parameterName) throws SQLException{ - return parameters.getBlob(parameterName); - } - - - public final boolean getBoolean(int parameterIndex) throws SQLException{ - return parameters.getBoolean(parameterIndex); - } - - - public final boolean getBoolean(String parameterName) throws SQLException{ - return parameters.getBoolean(parameterName); - } - - - public final byte getByte(int parameterIndex) throws SQLException{ - return parameters.getByte(parameterIndex); - } - - - public final byte getByte(String parameterName) throws SQLException{ - return parameters.getByte(parameterName); - } - - - public final byte[] getBytes(int parameterIndex) throws SQLException{ - return parameters.getBytes(parameterIndex); - } - - - public final byte[] getBytes(String parameterName) throws SQLException{ - return parameters.getBytes(parameterName); - } - - - public final Reader getCharacterStream(int parameterIndex) throws SQLException{ - return parameters.getCharacterStream(parameterIndex); - } - - - public final Reader getCharacterStream(String parameterName) throws SQLException{ - return parameters.getCharacterStream(parameterName); - } - - - public final Clob getClob(int parameterIndex){ - return parameters.getClob(parameterIndex); - } - - - public final Clob getClob(String parameterName) throws SQLException{ - return parameters.getClob(parameterName); - } - - - public final Date getDate(int parameterIndex, Calendar cal) throws SQLException{ - return parameters.getDate(parameterIndex, cal); - } - - - public final Date getDate(int parameterIndex) throws SQLException{ - return parameters.getDate(parameterIndex); - } - - - public final Date getDate(String parameterName, Calendar cal) throws SQLException{ - return parameters.getDate(parameterName, cal); - } - - - public final Date getDate(String parameterName) throws SQLException{ - return parameters.getDate(parameterName); - } - - - public final double getDouble(int parameterIndex) throws SQLException{ - return parameters.getDouble(parameterIndex); - } - - - public final double getDouble(String parameterName) throws SQLException{ - return parameters.getDouble(parameterName); - } - - - public final float getFloat(int parameterIndex) throws SQLException{ - return parameters.getFloat(parameterIndex); - } - - - public final float getFloat(String parameterName) throws SQLException{ - return parameters.getFloat(parameterName); - } - - - public final int getInt(int parameterIndex) throws SQLException{ - return parameters.getInt(parameterIndex); - } - - - public final int getInt(String parameterName) throws SQLException{ - return parameters.getInt(parameterName); - } - - - public final long getLong(int parameterIndex) throws SQLException{ - return parameters.getLong(parameterIndex); - } - - - public final long getLong(String parameterName) throws SQLException{ - return parameters.getLong(parameterName); - } - - - public final Reader getNCharacterStream(int parameterIndex) throws SQLException{ - return parameters.getNCharacterStream(parameterIndex); - } - - - public final Reader getNCharacterStream(String parameterName) throws SQLException{ - return parameters.getNCharacterStream(parameterName); - } - - - public final NClob getNClob(int parameterIndex){ - return parameters.getNClob(parameterIndex); - } - - - public final NClob getNClob(String parameterName) throws SQLException{ - return parameters.getNClob(parameterName); - } - - - public final String getNString(int parameterIndex) throws SQLException{ - return parameters.getNString(parameterIndex); - } - - - public final String getNString(String parameterName) throws SQLException{ - return parameters.getNString(parameterName); - } - - - public final Object getObject(int parameterIndex, Map<String, Class<?>> map){ - return parameters.getObject(parameterIndex, map); - } - - - public final Object getObject(int parameterIndex) throws SQLException{ - return parameters.getObject(parameterIndex); - } - - - public final Object getObject(String parameterName, Map<String, Class<?>> map) throws SQLException{ - return parameters.getObject(parameterName, map); - } - - - public final Object getObject(String parameterName) throws SQLException{ - return parameters.getObject(parameterName); - } - - - public final Ref getRef(int parameterIndex){ - return parameters.getRef(parameterIndex); - } - - - public final Ref getRef(String parameterName) throws SQLException{ - return parameters.getRef(parameterName); - } - - - public final RowId getRowId(int parameterIndex){ - return parameters.getRowId(parameterIndex); - } - - - public final RowId getRowId(String parameterName) throws SQLException{ - return parameters.getRowId(parameterName); - } - - - public final short getShort(int parameterIndex) throws SQLException{ - return parameters.getShort(parameterIndex); - } - - - public final short getShort(String parameterName) throws SQLException{ - return parameters.getShort(parameterName); - } - - - public final SQLXML getSQLXML(int parameterIndex){ - return parameters.getSQLXML(parameterIndex); - } - - - public final SQLXML getSQLXML(String parameterName) throws SQLException{ - return parameters.getSQLXML(parameterName); - } - - - public final String getString(int parameterIndex) throws SQLException{ - return parameters.getString(parameterIndex); - } - - - public final String getString(String parameterName) throws SQLException{ - return parameters.getString(parameterName); - } - - - public final Time getTime(int parameterIndex, Calendar cal) throws SQLException{ - return parameters.getTime(parameterIndex, cal); - } - - - public final Time getTime(int parameterIndex) throws SQLException{ - return parameters.getTime(parameterIndex); - } - - - public final Time getTime(String parameterName, Calendar cal) throws SQLException{ - return parameters.getTime(parameterName, cal); - } - - - public final Time getTime(String parameterName) throws SQLException{ - return parameters.getTime(parameterName); - } - - - public final Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException{ - return parameters.getTimestamp(parameterIndex, cal); - } - - - public final Timestamp getTimestamp(int parameterIndex) throws SQLException{ - return parameters.getTimestamp(parameterIndex); - } - - - public final Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException{ - return parameters.getTimestamp(parameterName, cal); - } - - - public final Timestamp getTimestamp(String parameterName) throws SQLException{ - return parameters.getTimestamp(parameterName); - } - - - public final URL getURL(int parameterIndex) throws SQLException{ - return parameters.getURL(parameterIndex); - } - - - public final URL getURL(String parameterName) throws SQLException{ - return parameters.getURL(parameterName); - } - - - public final boolean wasNull(){ - return parameters.wasNull(); - } - - - public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException{ - registerOutParameter(parameterIndex, sqlType, -1); - } - - - public void registerOutParameter(String parameterName, int sqlType) throws SQLException{ - registerOutParameter(parameters.findColumn(parameterName), sqlType); - } - - - public void registerOutParameter(int parameterIndex, int sqlType, int scaleOrLength) throws SQLException{ - DbParameter para = getPara(parameterIndex); - int direction = para.get_Value() == null ? ParameterDirection.Output : ParameterDirection.InputOutput; - para.set_Direction(ParameterDirection.wrap(direction)); - - if(sqlType != Types.OTHER){ - para.set_DbType(DbType.wrap(JdbcOdbcUtils.convertJdbc2AdoNetType(sqlType))); - } - - if(scaleOrLength >= 0){ - switch(sqlType){ - case Types.DECIMAL: - case Types.NUMERIC: - para.set_Scale((byte)scaleOrLength); - } - } - } - - - public void registerOutParameter(int parameterIndex, int sqlType, String typeName){ - throw new UnsupportedOperationException(); - } - - - public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException{ - registerOutParameter(parameters.findColumn(parameterName), sqlType, scale); - } - - - public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException{ - registerOutParameter(parameters.findColumn(parameterName), sqlType, typeName); - } - - - public void setAsciiStream(String parameterName, InputStream x) throws SQLException{ - setAsciiStream(parameters.findColumn(parameterName), x); - } - - - public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException{ - setAsciiStream(parameters.findColumn(parameterName), x, length); - } - - - public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException{ - setAsciiStream(parameters.findColumn(parameterName), x, length); - } - - - public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException{ - setBigDecimal(parameters.findColumn(parameterName), x); - } - - - public void setBinaryStream(String parameterName, InputStream x) throws SQLException{ - setBinaryStream(parameters.findColumn(parameterName), x); - } - - - public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException{ - setBinaryStream(parameters.findColumn(parameterName), x, length); - } - - - public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException{ - setBinaryStream(parameters.findColumn(parameterName), x, length); - } - - - public void setBlob(String parameterName, Blob x) throws SQLException{ - setBlob(parameters.findColumn(parameterName), x); - } - - - public void setBlob(String parameterName, InputStream x) throws SQLException{ - setBlob(parameters.findColumn(parameterName), x); - } - - - public void setBlob(String parameterName, InputStream x, long length) throws SQLException{ - setBlob(parameters.findColumn(parameterName), x, length); - } - - - public void setBoolean(String parameterName, boolean x) throws SQLException{ - setBoolean(parameters.findColumn(parameterName), x); - } - - - public void setByte(String parameterName, byte x) throws SQLException{ - setByte(parameters.findColumn(parameterName), x); - } - - - public void setBytes(String parameterName, byte[] x) throws SQLException{ - setBytes(parameters.findColumn(parameterName), x); - } - - - public void setCharacterStream(String parameterName, Reader x) throws SQLException{ - setCharacterStream(parameters.findColumn(parameterName), x); - } - - - public void setCharacterStream(String parameterName, Reader x, int length) throws SQLException{ - setCharacterStream(parameters.findColumn(parameterName), x, length); - } - - - public void setCharacterStream(String parameterName, Reader x, long length) throws SQLException{ - setCharacterStream(parameters.findColumn(parameterName), x, length); - } - - - public void setClob(String parameterName, Clob x) throws SQLException{ - setClob(parameters.findColumn(parameterName), x); - } - - - public void setClob(String parameterName, Reader x) throws SQLException{ - setClob(parameters.findColumn(parameterName), x); - } - - - public void setClob(String parameterName, Reader x, long length) throws SQLException{ - setClob(parameters.findColumn(parameterName), x, length); - } - - - public void setDate(String parameterName, Date x) throws SQLException{ - setDate(parameters.findColumn(parameterName), x); - } - - - public void setDate(String parameterName, Date x, Calendar cal) throws SQLException{ - setDate(parameters.findColumn(parameterName), x, cal); - } - - - public void setDouble(String parameterName, double x) throws SQLException{ - setDouble(parameters.findColumn(parameterName), x); - } - - - public void setFloat(String parameterName, float x) throws SQLException{ - setFloat(parameters.findColumn(parameterName), x); - } - - - public void setInt(String parameterName, int x) throws SQLException{ - setInt(parameters.findColumn(parameterName), x); - } - - - public void setLong(String parameterName, long x) throws SQLException{ - setLong(parameters.findColumn(parameterName), x); - } - - - public void setNCharacterStream(String parameterName, Reader x) throws SQLException{ - setNCharacterStream(parameters.findColumn(parameterName), x); - } - - - public void setNCharacterStream(String parameterName, Reader x, long length) throws SQLException{ - setNCharacterStream(parameters.findColumn(parameterName), x, length); - } - - - public void setNClob(String parameterName, NClob x) throws SQLException{ - setNClob(parameters.findColumn(parameterName), x); - } - - - public void setNClob(String parameterName, Reader x) throws SQLException{ - setNClob(parameters.findColumn(parameterName), x); - } - - - public void setNClob(String parameterName, Reader x, long length) throws SQLException{ - setNClob(parameters.findColumn(parameterName), x, length); - } - - - public void setNString(String parameterName, String x) throws SQLException{ - setNString(parameters.findColumn(parameterName), x); - } - - - public void setNull(String parameterName, int sqlType) throws SQLException{ - setNull(parameters.findColumn(parameterName), sqlType); - } - - - public void setNull(String parameterName, int sqlType, String typeName) throws SQLException{ - setNull(parameters.findColumn(parameterName), sqlType, typeName); - } - - - public void setObject(String parameterName, Object x) throws SQLException{ - setObject(parameters.findColumn(parameterName), x); - } - - - public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException{ - setObject(parameters.findColumn(parameterName), x, targetSqlType); - } - - - public void setObject(String parameterName, Object x, int targetSqlType, int scaleOrLength) throws SQLException{ - setObject(parameters.findColumn(parameterName), x, targetSqlType, scaleOrLength); - } - - - public void setRowId(String parameterName, RowId x) throws SQLException{ - setRowId(parameters.findColumn(parameterName), x); - } - - - public void setSQLXML(String parameterName, SQLXML x) throws SQLException{ - setSQLXML(parameters.findColumn(parameterName), x); - } - - - public void setShort(String parameterName, short x) throws SQLException{ - setShort(parameters.findColumn(parameterName), x); - } - - - public void setString(String parameterName, String x) throws SQLException{ - setString(parameters.findColumn(parameterName), x); - } - - - public void setTime(String parameterName, Time x) throws SQLException{ - setTime(parameters.findColumn(parameterName), x); - } - - - public void setTime(String parameterName, Time x, Calendar cal) throws SQLException{ - setTime(parameters.findColumn(parameterName), x, cal); - } - - - public void setTimestamp(String parameterName, Timestamp x) throws SQLException{ - setTimestamp(parameters.findColumn(parameterName), x); - } - - - public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException{ - setTimestamp(parameters.findColumn(parameterName), x, cal); - } - - - public void setURL(String parameterName, URL x) throws SQLException{ - setURL(parameters.findColumn(parameterName), x); - } - - private class Parameters extends JdbcOdbcObject{ - - @Override - public int findColumn(String parameterName) throws SQLException{ - try{ - DbParameterCollection params = command.get_Parameters(); - for(int i=0; i<params.get_Count();i++){ - DbParameter param = params.get_Item(i); - if(parameterName.equalsIgnoreCase(param.get_ParameterName())){ - return i+1; - } - } - throw new SQLException( "Parameter '"+parameterName+"' not found.", "S0022"); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - @Override - protected Object getObjectImpl(int parameterIndex) throws SQLException{ - return getPara(parameterIndex).get_Value(); - } - - } - - - /** - * {@inheritDoc} - */ - public <T> T getObject(int parameterIndex, Class<T> type) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - - /** - * {@inheritDoc} - */ - public <T> T getObject(String parameterName, Class<T> type) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcConnection.java b/openjdk/sun/jdbc/odbc/JdbcOdbcConnection.java deleted file mode 100644 index 5e075b2a..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcConnection.java +++ /dev/null @@ -1,490 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import cli.System.Data.*; -import cli.System.Data.Common.*; -import cli.System.Data.Odbc.*; - -import java.sql.*; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider - */ -public class JdbcOdbcConnection implements Connection{ - - private final OdbcConnection netConn; - - private DbTransaction transaction; - - private int isolation = TRANSACTION_READ_COMMITTED; - - - JdbcOdbcConnection(String connectString, Properties info) throws SQLException{ - try{ - boolean isDSN = connectString.indexOf('=') < 0; - StringBuilder connStr = new StringBuilder(); - if(isDSN){ - connStr.append("DSN="); - } - connStr.append(connectString); - - String uid = info.getProperty("user"); - String pwd = info.getProperty("password"); - - if(uid != null){ - connStr.append(";UID=").append(uid); - } - if(pwd != null){ - connStr.append(";PWD=").append(pwd); - } - - netConn = new OdbcConnection(connStr.toString()); - - netConn.Open(); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - @Override - public void clearWarnings() throws SQLException{ - // TODO Auto-generated method stub - - } - - - @Override - public void close() throws SQLException{ - try{ - netConn.Close(); - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - @Override - public Array createArrayOf(String typeName, Object[] elements){ - throw new UnsupportedOperationException(); - } - - - @Override - public Blob createBlob(){ - throw new UnsupportedOperationException(); - } - - - @Override - public Clob createClob(){ - throw new UnsupportedOperationException(); - } - - - @Override - public NClob createNClob(){ - throw new UnsupportedOperationException(); - } - - - @Override - public SQLXML createSQLXML(){ - throw new UnsupportedOperationException(); - } - - - @Override - public Statement createStatement() throws SQLException{ - return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - } - - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException{ - try{ - return new JdbcOdbcStatement(this, netConn.CreateCommand(), resultSetType, resultSetConcurrency); - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability){ - throw new UnsupportedOperationException(); - } - - - @Override - public Struct createStruct(String typeName, Object[] attributes){ - throw new UnsupportedOperationException(); - } - - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException{ - try{ - if(autoCommit && transaction != null){ - return; // no change - } - if(!autoCommit && transaction == null){ - return; // no change - } - int level; - switch(isolation){ - case TRANSACTION_READ_COMMITTED: - level = IsolationLevel.ReadUncommitted; - break; - case TRANSACTION_READ_UNCOMMITTED: - level = IsolationLevel.ReadCommitted; - break; - case TRANSACTION_REPEATABLE_READ: - level = IsolationLevel.RepeatableRead; - break; - case TRANSACTION_SERIALIZABLE: - level = IsolationLevel.Serializable; - break; - default: - level = IsolationLevel.ReadCommitted; - } - if(autoCommit){ - transaction = netConn.BeginTransaction(IsolationLevel.wrap(level)); - }else{ - transaction.Commit(); - transaction = null; - } - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - @Override - public boolean getAutoCommit(){ - return transaction != null; - } - - - @Override - public void commit() throws SQLException{ - try{ - if(transaction == null){ - // auto commit == true - return; - } - transaction.Commit(); - transaction = netConn.BeginTransaction(transaction.get_IsolationLevel()); - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - @Override - public void rollback() throws SQLException{ - try{ - if(transaction == null){ - // auto commit == true - return; - } - transaction.Rollback(); - transaction = netConn.BeginTransaction(transaction.get_IsolationLevel()); - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - @Override - public void setTransactionIsolation(int level){ - isolation = level; - } - - - @Override - public int getTransactionIsolation(){ - return isolation; - } - - - @Override - public String getClientInfo(String name){ - throw new UnsupportedOperationException(); - } - - - @Override - public Properties getClientInfo(){ - throw new UnsupportedOperationException(); - } - - - @Override - public int getHoldability(){ - throw new UnsupportedOperationException(); - } - - - @Override - public DatabaseMetaData getMetaData(){ - return new JdbcOdbcDatabaseMetaData(this, netConn); - } - - - @Override - public Map<String, Class<?>> getTypeMap(){ - throw new UnsupportedOperationException(); - } - - - @Override - public SQLWarning getWarnings() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - @Override - public boolean isClosed() throws SQLException{ - return netConn.get_State().Value == ConnectionState.Closed; - } - - - @Override - public boolean isReadOnly() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - @Override - public boolean isValid(int timeout) throws SQLException{ - throw new UnsupportedOperationException(); - } - - - @Override - public String nativeSQL(String sql) throws SQLException{ - // TODO Auto-generated method stub - return sql; - } - - - @Override - public CallableStatement prepareCall(String sql) throws SQLException{ - return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - } - - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException{ - try{ - return new JdbcOdbcCallableStatement(this, netConn.CreateCommand(), sql, resultSetType, - resultSetConcurrency); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability){ - throw new UnsupportedOperationException(); - } - - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException{ - return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - } - - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) - throws SQLException{ - try{ - return new JdbcOdbcPreparedStatement(this, netConn.CreateCommand(), sql, resultSetType, - resultSetConcurrency); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability){ - throw new UnsupportedOperationException(); - } - - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys){ - throw new UnsupportedOperationException(); - } - - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes){ - throw new UnsupportedOperationException(); - } - - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames){ - throw new UnsupportedOperationException(); - } - - - @Override - public void releaseSavepoint(Savepoint savepoint){ - throw new UnsupportedOperationException(); - } - - - @Override - public void rollback(Savepoint savepoint){ - throw new UnsupportedOperationException(); - } - - - @Override - public void setCatalog(String catalog) throws SQLException{ - try{ - netConn.ChangeDatabase(catalog); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - @Override - public String getCatalog(){ - return netConn.get_Database(); - } - - - @Override - public void setClientInfo(String name, String value){ - throw new UnsupportedOperationException(); - } - - - @Override - public void setClientInfo(Properties properties){ - throw new UnsupportedOperationException(); - } - - - @Override - public void setHoldability(int holdability){ - throw new UnsupportedOperationException(); - } - - - @Override - public void setReadOnly(boolean readOnly) throws SQLException{ - // TODO Auto-generated method stub - - } - - - @Override - public Savepoint setSavepoint(){ - throw new UnsupportedOperationException(); - } - - - @Override - public Savepoint setSavepoint(String name){ - throw new UnsupportedOperationException(); - } - - - @Override - public void setTypeMap(Map<String, Class<?>> map){ - throw new UnsupportedOperationException(); - } - - - @Override - public boolean isWrapperFor(Class<?> iface){ - return iface.isAssignableFrom(this.getClass()); - } - - - @Override - public <T>T unwrap(Class<T> iface) throws SQLException{ - if(isWrapperFor(iface)){ - return (T)this; - } - throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); - } - - - /** - * {@inheritDoc} - */ - public void setSchema(String schema) throws SQLException { - } - - - /** - * {@inheritDoc} - */ - public String getSchema() throws SQLException { - return null; - } - - - /** - * {@inheritDoc} - */ - public void abort(Executor executor) throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - - /** - * {@inheritDoc} - */ - public void setNetworkTimeout(Executor executor, int milliseconds) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - - /** - * {@inheritDoc} - */ - public int getNetworkTimeout() throws SQLException { - throw new SQLFeatureNotSupportedException(); - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcDTResultSet.java b/openjdk/sun/jdbc/odbc/JdbcOdbcDTResultSet.java deleted file mode 100644 index 9de750a4..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcDTResultSet.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.sql.*; - -import cli.System.Data.*; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider. This ResultSet based on DataTable. It is read only and - * scrollable. - */ -public class JdbcOdbcDTResultSet extends JdbcOdbcResultSet{ - - private final DataTable data; - - private DataRowCollection rows; - - private int rowIndex; // row index starting with 0; -1 means beforeFirst - - private cli.System.Data.DataRow row; - - - public JdbcOdbcDTResultSet(DataTable data){ - this(data, CONCUR_READ_ONLY); - } - public JdbcOdbcDTResultSet(DataTable data, int concurrency){ - super(null, TYPE_SCROLL_INSENSITIVE, concurrency); - this.data = data; - this.rows = data.get_Rows(); - this.rowIndex = -1; - } - - - @Override - public boolean absolute(int rowPosition) throws SQLException{ - if(rowPosition == 0){ - return !isBeforeFirst() && !isAfterLast(); - } - DataRowCollection dataRows = getRows(); - int count = dataRows.get_Count(); - if(rowPosition > 0){ - if(rowPosition > count){ - rowIndex = count; - setDataRow(); - return false; - } - rowIndex = rowPosition - 1; - setDataRow(); - return true; - }else{ - if(-rowPosition > count){ - rowIndex = -1; - setDataRow(); - return false; - } - rowIndex = count + rowPosition; - setDataRow(); - return true; - } - } - - - @Override - public void afterLast() throws SQLException{ - rowIndex = getRows().get_Count(); - setDataRow(); - } - - - @Override - public void beforeFirst() throws SQLException{ - rowIndex = -1; - setDataRow(); - } - - - @Override - public void close(){ - rows = null; - } - - - @Override - public int findColumn(String columnLabel) throws SQLException{ - getRows(); // Check if ResultSet is closed - int idx = data.get_Columns().IndexOf(columnLabel); - if(idx < 0){ - throw new SQLException("Column '" + columnLabel + "' not found.", "S0022"); - } - return idx + 1; - } - - - @Override - public boolean first() throws SQLException{ - beforeFirst(); - return next(); - } - - - @Override - public ResultSetMetaData getMetaData(){ - return new JdbcOdbcDTResultSetMetaData(data); - } - - - @Override - public int getRow() throws SQLException{ - return rowIndex < getRows().get_Count() ? rowIndex + 1 : 0; - } - - - @Override - public boolean isAfterLast() throws SQLException{ - int count = getRows().get_Count(); - return rowIndex >= count || count == 0; - } - - - @Override - public boolean isBeforeFirst() throws SQLException{ - return rowIndex <= -1 || getRows().get_Count() == 0; - } - - - @Override - public boolean isClosed(){ - return rows == null; - } - - - @Override - public boolean isFirst() throws SQLException{ - return rowIndex == 0 && getRows().get_Count() > 0; - } - - - @Override - public boolean isLast() throws SQLException{ - return rowIndex >= 0 && rowIndex == getRows().get_Count() - 1; - } - - - @Override - public boolean last() throws SQLException{ - afterLast(); - return previous(); - } - - - @Override - public boolean next() throws SQLException{ - DataRowCollection dataRows = getRows(); - if(rowIndex + 1 < dataRows.get_Count()){ - ++rowIndex; - setDataRow(); - return true; - }else{ - rowIndex = dataRows.get_Count(); - setDataRow(); - return false; - } - } - - - @Override - public boolean previous() throws SQLException{ - if(rowIndex > 0){ - --rowIndex; - setDataRow(); - return true; - }else{ - rowIndex = -1; - setDataRow(); - return false; - } - } - - - @Override - public void refreshRow(){ - // ignore it - } - - - @Override - public boolean relative(int rowPositions) throws SQLException{ - DataRowCollection dataRows = getRows(); - int newRowIndex = rowIndex + rowPositions; - if(newRowIndex < 0){ - rowIndex = -1; - setDataRow(); - return false; - } - int count = dataRows.get_Count(); - if(newRowIndex >= dataRows.get_Count()){ - rowIndex = count; - setDataRow(); - return false; - } - rowIndex = newRowIndex; - setDataRow(); - return true; - } - - - /** - * {@inheritDoc} - */ - @Override - protected Object getObjectImpl(int columnIndex) throws SQLException{ - try{ - return getDataRow().get_Item(columnIndex - 1); - }catch(ArrayIndexOutOfBoundsException ex){ - throw new SQLException("Invalid column number (" + columnIndex + "). A number between 1 and " - + data.get_Columns().get_Count() + " is valid.", "S1002"); - } - } - - - /** - * Check if this ResultSet is closed before access to the DataRowCollection - * - * @return the local rows object - * @throws SQLException - * If the ResultSet is closed. - */ - protected DataRowCollection getRows() throws SQLException{ - if(rows == null){ - throw new SQLException("ResultSet is closed.", "24000"); - } - return rows; - } - - - /** - * Get the current DataRow - * - * @return the DataRow - * @throws SQLException - * if closed or no current Row - */ - protected DataRow getDataRow() throws SQLException{ - getRows(); // checks if ResultSet is closed - if(row == null){ - throw new SQLException("No current row", "S1109"); - } - return row; - } - - /** - * Set the current row from the current rowIndex. If the rowIndex was not change - * then the row variable will be new set. - * @throws SQLException If the ResultSet is closed. - */ - protected void setDataRow() throws SQLException{ - DataRowCollection dataRows = getRows(); - if(rowIndex < 0 || rowIndex >= dataRows.get_Count()){ - row = null; - }else{ - row = dataRows.get_Item(rowIndex); - } - } - -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcDTResultSetMetaData.java b/openjdk/sun/jdbc/odbc/JdbcOdbcDTResultSetMetaData.java deleted file mode 100644 index 25c15fb9..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcDTResultSetMetaData.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.sql.*; - -import cli.System.Data.*; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider - */ -public class JdbcOdbcDTResultSetMetaData implements ResultSetMetaData{ - - private final DataTable table; - - - public JdbcOdbcDTResultSetMetaData(DataTable table){ - this.table = table; - } - - - public String getCatalogName(int column){ - return ""; - } - - - public String getColumnClassName(int column){ - String type = getDataColumn(column).get_DataType().toString(); - return JdbcOdbcUtils.getJavaClassName(type); - } - - - public int getColumnCount(){ - return table.get_Columns().get_Count(); - } - - - public int getColumnDisplaySize(int column) throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public String getColumnLabel(int column) throws SQLException{ - return getDataColumn(column).get_Caption(); - } - - - public String getColumnName(int column) throws SQLException{ - return getDataColumn(column).get_ColumnName(); - } - - - public int getColumnType(int column) throws SQLException{ - cli.System.Type type = getDataColumn(column).get_DataType(); - // TODO Auto-generated method stub - return Types.OTHER; - } - - - public String getColumnTypeName(int column) throws SQLException{ - return ""; - } - - - public int getPrecision(int column) throws SQLException{ - return getDataColumn(column).get_MaxLength(); - } - - - public int getScale(int column) throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public String getSchemaName(int column) throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public String getTableName(int column) throws SQLException{ - return table.get_TableName(); - } - - - public boolean isAutoIncrement(int column) throws SQLException{ - return getDataColumn(column).get_AutoIncrement(); - } - - - public boolean isCaseSensitive(int column) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isCurrency(int column) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isDefinitelyWritable(int column) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public int isNullable(int column) throws SQLException{ - return getDataColumn(column).get_AllowDBNull() ? columnNullable : columnNoNulls; - } - - - public boolean isReadOnly(int column) throws SQLException{ - return getDataColumn(column).get_ReadOnly(); - } - - - public boolean isSearchable(int column) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isSigned(int column) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isWritable(int column) throws SQLException{ - return !getDataColumn(column).get_ReadOnly(); - } - - - public boolean isWrapperFor(Class<?> iface){ - return iface.isAssignableFrom(this.getClass()); - } - - - public <T>T unwrap(Class<T> iface) throws SQLException{ - if(isWrapperFor(iface)){ - return (T)this; - } - throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); - } - - - /** - * Get a DataColumn from the DataTable - * @param column the JDBC column index starting with 1 - * @return the DataColumn - */ - private DataColumn getDataColumn(int column){ - return table.get_Columns().get_Item(column - 1); - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcDatabaseMetaData.java b/openjdk/sun/jdbc/odbc/JdbcOdbcDatabaseMetaData.java deleted file mode 100644 index df631c5b..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcDatabaseMetaData.java +++ /dev/null @@ -1,1211 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import ikvm.lang.CIL; - -import java.sql.*; -import java.util.HashSet; - -import cli.System.Data.*; -import cli.System.Data.Common.*; -import cli.System.Data.Odbc.*; - -/** - * @author Volker Berlin - */ -public class JdbcOdbcDatabaseMetaData implements DatabaseMetaData{ - - private JdbcOdbcConnection jdbcConn; - - private final OdbcConnection netConn; - - private DataRow dataSourceInfo; - - public JdbcOdbcDatabaseMetaData(JdbcOdbcConnection jdbcConn, OdbcConnection netConn){ - this.jdbcConn = jdbcConn; - this.netConn = netConn; - } - - - public boolean allProceduresAreCallable() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean allTablesAreSelectable() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean autoCommitFailureClosesAllResultSets(){ - throw new UnsupportedOperationException(); - } - - - public boolean dataDefinitionCausesTransactionCommit() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean dataDefinitionIgnoredInTransactions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean deletesAreDetected(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean doesMaxRowSizeIncludeBlobs() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, - String attributeNamePattern){ - throw new UnsupportedOperationException(); - } - - - public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) - throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public String getCatalogSeparator() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public String getCatalogTerm() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getCatalogs() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getClientInfoProperties(){ - throw new UnsupportedOperationException(); - } - - - public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) - throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) - throws SQLException{ - try{ - // the description of the restrictions can you request with GetSchema("Restrictions") - String[] restrictions = new String[]{catalog, schemaPattern, tableNamePattern, columnNamePattern}; - DataTable data = netConn.GetSchema(OdbcMetaDataCollectionNames.Columns, restrictions); - return new JdbcOdbcDTResultSet(data); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public Connection getConnection(){ - return jdbcConn; - } - - - public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, - String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public int getDatabaseMajorVersion(){ - String version = netConn.get_ServerVersion().trim(); - for(int i = 0; i < version.length(); i++){ - char ch = version.charAt(i); - if(ch < '0' || ch > '9'){ - return Integer.parseInt(version.substring(0, i)); - } - } - return Integer.parseInt(version); - } - - - public int getDatabaseMinorVersion(){ - String version = netConn.get_ServerVersion().trim(); - int idx = version.indexOf('.'); - if(idx < 0){ - return 0; - } - version = version.substring(idx + 1); - for(int i = 0; i < version.length(); i++){ - char ch = version.charAt(i); - if(ch < '0' || ch > '9'){ - return Integer.parseInt(version.substring(0, i)); - } - } - return Integer.parseInt(version); - } - - - public String getDatabaseProductName() throws SQLException{ - return String.valueOf(getInfo(DbMetaDataColumnNames.DataSourceProductName)); - } - - - public String getDatabaseProductVersion(){ - return netConn.get_ServerVersion(); - } - - - public int getDefaultTransactionIsolation(){ - return Connection.TRANSACTION_READ_COMMITTED; - } - - - public int getDriverMajorVersion(){ - return 2; - } - - - public int getDriverMinorVersion(){ - return 1; - } - - - public String getDriverName(){ - return "JDBC-ODBC Bridge (" + netConn.get_Driver() + ")"; - } - - - public String getDriverVersion(){ - return "2.0001"; - } - - - public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public String getExtraNameCharacters(){ - return ""; - } - - - public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, - String columnNamePattern){ - throw new UnsupportedOperationException(); - } - - - public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern){ - throw new UnsupportedOperationException(); - } - - - public String getIdentifierQuoteString() throws SQLException{ - String quote = (String)getInfo(DbMetaDataColumnNames.QuotedIdentifierPattern); - if(quote.length()>=2){ - char ch1 = quote.charAt(0); - char ch2 = quote.charAt(quote.length()-1); - if(ch1 == ch2){ - return quote.substring(0,1); - } - } - return "\""; // ANSI SQL and should work with the most DBMS - } - - - public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) - throws SQLException{ - try{ - // the description of the restrictions can you request with GetSchema("Restrictions") - String[] restrictions = new String[]{catalog, schema, table}; - DataTable data = netConn.GetSchema(OdbcMetaDataCollectionNames.Indexes, restrictions); - return new JdbcOdbcDTResultSet(data); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public int getJDBCMajorVersion(){ - return 2; - } - - - public int getJDBCMinorVersion(){ - return 0; - } - - - public int getMaxBinaryLiteralLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxCatalogNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxCharLiteralLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxColumnNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxColumnsInGroupBy() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxColumnsInIndex() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxColumnsInOrderBy() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxColumnsInSelect() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxColumnsInTable() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxConnections() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxCursorNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxIndexLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxProcedureNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxRowSize() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxSchemaNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxStatementLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxStatements() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxTableNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxTablesInSelect() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxUserNameLength() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public String getNumericFunctions() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, - String columnNamePattern) throws SQLException{ - try{ - // the description of the restrictions can you request with GetSchema("Restrictions") - String[] restrictions = new String[]{catalog, schemaPattern, procedureNamePattern, columnNamePattern}; - DataTable dt1 = netConn.GetSchema(OdbcMetaDataCollectionNames.ProcedureColumns, restrictions); - DataTable dt2 = netConn.GetSchema(OdbcMetaDataCollectionNames.ProcedureParameters, restrictions); - // concatenate the both DataTable - DataRowCollection rows1 = dt1.get_Rows(); - DataRowCollection rows2 = dt2.get_Rows(); - for(int i = 0; i < rows2.get_Count(); i++){ - DataRow row = rows2.get_Item(i); - rows1.Add(row.get_ItemArray()); - } - return new JdbcOdbcDTResultSet(dt1); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public String getProcedureTerm() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) - throws SQLException{ - try{ - // the description of the restrictions can you request with GetSchema("Restrictions") - String[] restrictions = new String[]{catalog, schemaPattern, procedureNamePattern}; - DataTable data = netConn.GetSchema(OdbcMetaDataCollectionNames.Procedures, restrictions); - return new JdbcOdbcDTResultSet(data); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public int getResultSetHoldability(){ - throw new UnsupportedOperationException(); - } - - - public RowIdLifetime getRowIdLifetime(){ - throw new UnsupportedOperationException(); - } - - - public String getSQLKeywords() throws SQLException{ - try{ - DataTable dt = netConn.GetSchema(DbMetaDataCollectionNames.ReservedWords); - final DataRowCollection rows = dt.get_Rows(); - final int count = rows.get_Count(); - final StringBuilder builder = new StringBuilder(); - for(int i=0; i<count; i++){ - String word = (String)rows.get_Item(i).get_Item(0); - if(builder.length() > 0){ - builder.append(','); - } - builder.append(word); - } - return builder.toString(); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public int getSQLStateType() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public String getSchemaTerm() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getSchemas() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getSchemas(String catalog, String schemaPattern){ - throw new UnsupportedOperationException(); - } - - - public String getSearchStringEscape() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public String getStringFunctions() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern){ - throw new UnsupportedOperationException(); - } - - - public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern){ - throw new UnsupportedOperationException(); - } - - - public String getSystemFunctions() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) - throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getTableTypes() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) - throws SQLException{ - try{ - // the description of the restrictions can you request with GetSchema("Restrictions") - String[] restrictions = new String[]{catalog, schemaPattern, tableNamePattern}; - DataTable dt1 = netConn.GetSchema(OdbcMetaDataCollectionNames.Tables, restrictions); - DataTable dt2 = netConn.GetSchema(OdbcMetaDataCollectionNames.Views, restrictions); - // concatenate the both DataTable - DataRowCollection rows1 = dt1.get_Rows(); - DataRowCollection rows2 = dt2.get_Rows(); - for(int i = 0; i < rows2.get_Count(); i++){ - DataRow row = rows2.get_Item(i); - rows1.Add(row.get_ItemArray()); - } - if(types != null){ - RowLoop: - // Filter the types - for(int i = rows1.get_Count() - 1; i >= 0; i--){ - DataRow row = rows1.get_Item(i); - Object tableType = row.get_Item("TABLE_TYPE"); - for(String type : types){ - if(type.equals(tableType)){ - continue RowLoop; - } - } - rows1.RemoveAt(i); - } - } - return new JdbcOdbcDTResultSet(dt1); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public String getTimeDateFunctions() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getTypeInfo() throws SQLException{ - try{ - //TODO Column Names and order are wrong - DataTable data = netConn.GetSchema(DbMetaDataCollectionNames.DataTypes); - return new JdbcOdbcDTResultSet(data); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types){ - throw new UnsupportedOperationException(); - } - - - public String getURL() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public String getUserName() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public boolean insertsAreDetected(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isCatalogAtStart() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isReadOnly() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean locatorsUpdateCopy(){ - throw new UnsupportedOperationException(); - } - - - public boolean nullPlusNonNullIsNull() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean nullsAreSortedAtEnd() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean nullsAreSortedAtStart() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean nullsAreSortedHigh() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean nullsAreSortedLow() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean othersDeletesAreVisible(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean othersInsertsAreVisible(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean othersUpdatesAreVisible(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean ownDeletesAreVisible(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean ownInsertsAreVisible(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean ownUpdatesAreVisible(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean storesLowerCaseIdentifiers() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean storesLowerCaseQuotedIdentifiers() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean storesMixedCaseIdentifiers() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean storesMixedCaseQuotedIdentifiers() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean storesUpperCaseIdentifiers() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean storesUpperCaseQuotedIdentifiers() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsANSI92EntryLevelSQL() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsANSI92FullSQL() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsANSI92IntermediateSQL() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsAlterTableWithAddColumn() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsAlterTableWithDropColumn() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsBatchUpdates() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCatalogsInDataManipulation() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCatalogsInIndexDefinitions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCatalogsInProcedureCalls() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCatalogsInTableDefinitions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsColumnAliasing() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsConvert() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsConvert(int fromType, int toType) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCoreSQLGrammar() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsCorrelatedSubqueries() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsDataManipulationTransactionsOnly() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsDifferentTableCorrelationNames() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsExpressionsInOrderBy() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsExtendedSQLGrammar() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsFullOuterJoins() throws SQLException{ - int join = CIL.unbox_int(getInfo(DbMetaDataColumnNames.SupportedJoinOperators)); - return (join & SupportedJoinOperators.FullOuter) > 0; - } - - - public boolean supportsGetGeneratedKeys() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsGroupBy() throws SQLException{ - int behavior = CIL.unbox_int(getInfo(DbMetaDataColumnNames.GroupByBehavior)); - return behavior != GroupByBehavior.NotSupported; - } - - - public boolean supportsGroupByBeyondSelect() throws SQLException{ - int behavior = CIL.unbox_int(getInfo(DbMetaDataColumnNames.GroupByBehavior)); - return behavior == GroupByBehavior.MustContainAll; - } - - - public boolean supportsGroupByUnrelated() throws SQLException{ - int behavior = CIL.unbox_int(getInfo(DbMetaDataColumnNames.GroupByBehavior)); - return behavior == GroupByBehavior.Unrelated; - } - - - public boolean supportsIntegrityEnhancementFacility() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsLikeEscapeClause() throws SQLException{ - return getSQLKeywords().toUpperCase().indexOf(",LIKE,") > 0; - } - - - public boolean supportsLimitedOuterJoins() throws SQLException{ - int join = CIL.unbox_int(getInfo(DbMetaDataColumnNames.SupportedJoinOperators)); - return join > 0; - } - - - public boolean supportsMinimumSQLGrammar() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsMixedCaseIdentifiers() throws SQLException{ - int identifierCase = CIL.unbox_int(getInfo(DbMetaDataColumnNames.IdentifierCase)); - return identifierCase == IdentifierCase.Sensitive; - } - - - public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException{ - int identifierCase = CIL.unbox_int(getInfo(DbMetaDataColumnNames.QuotedIdentifierCase)); - return identifierCase == IdentifierCase.Sensitive; - } - - - public boolean supportsMultipleOpenResults() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsMultipleResultSets() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsMultipleTransactions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsNamedParameters() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsNonNullableColumns() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsOpenCursorsAcrossCommit() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsOpenCursorsAcrossRollback() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsOpenStatementsAcrossCommit() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsOpenStatementsAcrossRollback() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsOrderByUnrelated() throws SQLException{ - return CIL.unbox_boolean( getInfo(DbMetaDataColumnNames.OrderByColumnsInSelect)); - } - - - public boolean supportsOuterJoins() throws SQLException{ - int join = CIL.unbox_int(getInfo(DbMetaDataColumnNames.SupportedJoinOperators)); - return (join & SupportedJoinOperators.LeftOuter) > 0 || (join & SupportedJoinOperators.RightOuter) > 0; - } - - - public boolean supportsPositionedDelete() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsPositionedUpdate() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsResultSetHoldability(int holdability){ - throw new UnsupportedOperationException(); - } - - - public boolean supportsResultSetType(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSavepoints() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSchemasInDataManipulation() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSchemasInIndexDefinitions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSchemasInProcedureCalls() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSchemasInTableDefinitions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSelectForUpdate() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsStatementPooling(){ - throw new UnsupportedOperationException(); - } - - - public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException{ - throw new UnsupportedOperationException(); - } - - - public boolean supportsStoredProcedures() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSubqueriesInComparisons() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSubqueriesInExists() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSubqueriesInIns() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsSubqueriesInQuantifieds() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsTableCorrelationNames() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsTransactionIsolationLevel(int level) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsTransactions() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsUnion() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean supportsUnionAll() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean updatesAreDetected(int type) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean usesLocalFilePerTable() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean usesLocalFiles() throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public boolean isWrapperFor(Class<?> iface){ - return iface.isAssignableFrom(this.getClass()); - } - - - public <T>T unwrap(Class<T> iface) throws SQLException{ - if(isWrapperFor(iface)){ - return (T)this; - } - throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); - } - - private Object getInfo(String key) throws SQLException{ - try{ - if(dataSourceInfo == null){ - DataTable td = netConn.GetSchema(DbMetaDataCollectionNames.DataSourceInformation); - dataSourceInfo = td.get_Rows().get_Item(0); - } - return dataSourceInfo.get_Item(key); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - /** - * {@inheritDoc} - */ - public ResultSet getPseudoColumns(String catalog, String schemaPattern, - String tableNamePattern, String columnNamePattern) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - - /** - * {@inheritDoc} - */ - public boolean generatedKeyAlwaysReturned() throws SQLException { - return false; - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcDriver.java b/openjdk/sun/jdbc/odbc/JdbcOdbcDriver.java deleted file mode 100644 index 9eb1d9d4..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcDriver.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.sql.*; -import java.util.Properties; -import java.util.logging.Logger; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider - */ -public class JdbcOdbcDriver implements Driver{ - - private static final String URL_PREFIX = "jdbc:odbc:"; - - static{ - try{ - DriverManager.registerDriver(new JdbcOdbcDriver()); - }catch(SQLException ex){ - throw new ExceptionInInitializerError(ex); - } - } - - - /** - * {@inheritDoc} - */ - @Override - public boolean acceptsURL(String url){ - return url.startsWith(URL_PREFIX); - } - - - /** - * {@inheritDoc} - */ - @Override - public Connection connect(String url, Properties info) throws SQLException{ - if(!acceptsURL(url)){ - return null; - } - String connectString = url.substring(URL_PREFIX.length()); - return new JdbcOdbcConnection(connectString, info); - } - - - /** - * {@inheritDoc} - */ - @Override - public int getMajorVersion(){ - return 2; - } - - - /** - * {@inheritDoc} - */ - @Override - public int getMinorVersion(){ - return 1; - } - - - /** - * {@inheritDoc} - */ - @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException{ - return new DriverPropertyInfo[0]; - } - - - /** - * {@inheritDoc} - */ - @Override - public boolean jdbcCompliant(){ - return true; - } - - - /** - * {@inheritDoc} - */ - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - throw new SQLFeatureNotSupportedException(); - } - -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcObject.java b/openjdk/sun/jdbc/odbc/JdbcOdbcObject.java deleted file mode 100644 index 32e9a40f..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcObject.java +++ /dev/null @@ -1,650 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - Copyright (C) 2011 Karsten Heinrich (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.Ref; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLXML; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Map; - -import cli.System.Convert; -import cli.System.DBNull; -import cli.System.IConvertible; -import cli.System.Int16; -import cli.System.Int32; -import cli.System.Int64; -import cli.System.Single; - -/** - * @author Volker Berlin - */ -public abstract class JdbcOdbcObject{ - - private boolean wasNull; - - - /** - * Maps the given ResultSet column label to its ResultSet column index or the given CallableStatment parameter name - * to the parameter index. - * - * @param columnLabel - * the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, - * then the label is the name of the column - * @return the column index of the given column name - * @throws SQLException - * if the ResultSet object does not contain a column labeled columnLabel, a database access error occurs - * or this method is called on a closed result set - */ - public abstract int findColumn(String columnLabel) throws SQLException; - - - /** - * Read an Object from the current row store at the current row on the given column. - * - * @param columnIndex - * a JDBC column index starting with 1 - * @return a .NET Object, DBNull or null - * @throws SQLException - * if the result is closed or any other error occur. - */ - protected abstract Object getObjectImpl(int columnIndex) throws SQLException; - - - /** - * Read an Object from the current row store at the current row on the given column. Set the flag wasNull. - * - * @param columnIndex - * a JDBC column index starting with 1 - * @return a .NET Object or null - * @throws SQLException - * if the result is closed or any other error occur. - */ - private final Object getObjectSetWasNull(int columnIndex) throws SQLException{ - Object obj = getObjectImpl(columnIndex); - if(obj == null || obj == DBNull.Value){ - wasNull = true; - return null; - } - wasNull = false; - return obj; - } - - - public final Array getArray(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final Array getArray(String columnLabel) throws SQLException{ - return getArray(findColumn(columnLabel)); - } - - - public final InputStream getAsciiStream(int columnIndex) throws SQLException{ - try{ - String str = getString(columnIndex); - if(str == null){ - return null; - } - return new ByteArrayInputStream(str.getBytes("Ascii")); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final InputStream getAsciiStream(String columnLabel) throws SQLException{ - return getAsciiStream(findColumn(columnLabel)); - } - - - public final BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException{ - BigDecimal dec = getBigDecimal(columnIndex); - if(dec == null){ - return null; - } - if(dec.scale() != scale){ - return dec.setScale(scale, BigDecimal.ROUND_HALF_EVEN); - } - return dec; - } - - - public final BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException{ - return getBigDecimal(findColumn(columnLabel), scale); - } - - - public final BigDecimal getBigDecimal(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return null; - } - String str = obj.toString(); - return new BigDecimal(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final BigDecimal getBigDecimal(String columnLabel) throws SQLException{ - return getBigDecimal(findColumn(columnLabel)); - } - - - public final InputStream getBinaryStream(int columnIndex) throws SQLException{ - byte[] data = getBytes(columnIndex); - if(data == null){ - return null; - } - return new ByteArrayInputStream(data); - } - - - public final InputStream getBinaryStream(String columnLabel) throws SQLException{ - return getBinaryStream(findColumn(columnLabel)); - } - - - public final Blob getBlob(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final Blob getBlob(String columnLabel) throws SQLException{ - return getBlob(findColumn(columnLabel)); - } - - - public final boolean getBoolean(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return false; - } - if(obj instanceof IConvertible){ - return Convert.ToBoolean(obj); - } - String str = obj.toString(); - if(str.length() > 0){ - // special handling for boolean representation in old databases - char ch = str.charAt(0); - if(ch == 'T' || ch == 't'){ - return true; - } - if(ch == 'F' || ch == 'f'){ - return true; - } - } - return cli.System.Boolean.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final boolean getBoolean(String columnLabel) throws SQLException{ - return getBoolean(findColumn(columnLabel)); - } - - - public final byte getByte(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return 0; - } - if(obj instanceof IConvertible){ - return Convert.ToByte(obj); - } - String str = obj.toString(); - return cli.System.Byte.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final byte getByte(String columnLabel) throws SQLException{ - return getByte(findColumn(columnLabel)); - } - - - public final byte[] getBytes(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return null; - } - if(obj instanceof byte[]){ - return (byte[])obj; - } - String str = obj.toString(); - return str.getBytes(); // which encoding? - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final byte[] getBytes(String columnLabel) throws SQLException{ - return getBytes(findColumn(columnLabel)); - } - - - public final Reader getCharacterStream(int columnIndex) throws SQLException{ - String str = getString(columnIndex); - if(str == null){ - return null; - } - return new StringReader(str); - } - - - public final Reader getCharacterStream(String columnLabel) throws SQLException{ - return getCharacterStream(findColumn(columnLabel)); - } - - - public final Clob getClob(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final Clob getClob(String columnLabel) throws SQLException{ - return getClob(findColumn(columnLabel)); - } - - - public final Date getDate(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return null; - } - if(obj instanceof cli.System.DateTime){ - cli.System.DateTime dt = (cli.System.DateTime)obj; - return new Date(dt.get_Year() - 1900, dt.get_Month() - 1, dt.get_Day()); - } - String str = obj.toString(); - return Date.valueOf(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final Date getDate(String columnLabel) throws SQLException{ - return getDate(findColumn(columnLabel)); - } - - - public final Date getDate(int columnIndex, Calendar cal) throws SQLException{ - Date date = getDate(columnIndex); - JdbcOdbcUtils.convertLocalToCalendarDate(date, cal); - return date; - } - - - public final Date getDate(String columnLabel, Calendar cal) throws SQLException{ - return getDate(findColumn(columnLabel), cal); - } - - - public final double getDouble(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return 0; - } - if(obj instanceof IConvertible){ - return Convert.ToDouble(obj); - } - String str = obj.toString(); - return cli.System.Double.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final double getDouble(String columnLabel) throws SQLException{ - return getDouble(findColumn(columnLabel)); - } - - - public final float getFloat(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return 0; - } - if(obj instanceof IConvertible){ - return Convert.ToSingle(obj); - } - String str = obj.toString(); - return Single.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final float getFloat(String columnLabel) throws SQLException{ - return getFloat(findColumn(columnLabel)); - } - - - public final int getInt(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return 0; - } - if(obj instanceof IConvertible){ - return Convert.ToInt32(obj); - } - String str = obj.toString(); - return Int32.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final int getInt(String columnLabel) throws SQLException{ - return getInt(findColumn(columnLabel)); - } - - - public final long getLong(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return 0; - } - if(obj instanceof IConvertible){ - return Convert.ToInt64(obj); - } - String str = obj.toString(); - return Int64.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final long getLong(String columnLabel) throws SQLException{ - return getLong(findColumn(columnLabel)); - } - - - public final Reader getNCharacterStream(int columnIndex) throws SQLException{ - return getCharacterStream(columnIndex); - } - - - public final Reader getNCharacterStream(String columnLabel) throws SQLException{ - return getCharacterStream(columnLabel); - } - - - public final NClob getNClob(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final NClob getNClob(String columnLabel) throws SQLException{ - return getNClob(findColumn(columnLabel)); - } - - - public final String getNString(int columnIndex) throws SQLException{ - return getString(columnIndex); - } - - - public final String getNString(String columnLabel) throws SQLException{ - return getString(columnLabel); - } - - - public final Object getObject(int columnIndex) throws SQLException{ - return JdbcOdbcUtils.convertNet2Java(getObjectSetWasNull(columnIndex)); - } - - - public final Object getObject(String columnLabel) throws SQLException{ - return getObject(findColumn(columnLabel)); - } - - - public final Object getObject(int columnIndex, Map<String, Class<?>> map){ - throw new UnsupportedOperationException(); - } - - - public final Object getObject(String columnLabel, Map<String, Class<?>> map) throws SQLException{ - return getObject(findColumn(columnLabel), map); - } - - - public final Ref getRef(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final Ref getRef(String columnLabel) throws SQLException{ - return getRef(findColumn(columnLabel)); - } - - - public final RowId getRowId(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final RowId getRowId(String columnLabel) throws SQLException{ - return getRowId(findColumn(columnLabel)); - } - - - public final SQLXML getSQLXML(int columnIndex){ - throw new UnsupportedOperationException(); - } - - - public final SQLXML getSQLXML(String columnLabel) throws SQLException{ - return getSQLXML(findColumn(columnLabel)); - } - - - public final short getShort(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return 0; - } - if(obj instanceof IConvertible){ - return Convert.ToInt16(obj); - } - String str = obj.toString(); - return Int16.Parse(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final short getShort(String columnLabel) throws SQLException{ - return getShort(findColumn(columnLabel)); - } - - - public final String getString(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return null; - } - return obj.toString(); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final String getString(String columnLabel) throws SQLException{ - return getString(findColumn(columnLabel)); - } - - - public final Time getTime(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return null; - } - if(obj instanceof cli.System.DateTime){ - cli.System.DateTime dt = (cli.System.DateTime)obj; - return new Time(dt.get_Hour(), dt.get_Minute() - 1, dt.get_Second()); - } - if(obj instanceof cli.System.TimeSpan){ - cli.System.TimeSpan ts = (cli.System.TimeSpan)obj; - return new Time(ts.get_Hours(), ts.get_Minutes() - 1, ts.get_Seconds()); - } - String str = obj.toString(); - return Time.valueOf(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final Time getTime(String columnLabel) throws SQLException{ - return getTime(findColumn(columnLabel)); - } - - - public final Time getTime(int columnIndex, Calendar cal) throws SQLException{ - Time time = getTime(columnIndex); - JdbcOdbcUtils.convertLocalToCalendarDate(time, cal); - return time; - } - - - public final Time getTime(String columnLabel, Calendar cal) throws SQLException{ - return getTime(findColumn(columnLabel), cal); - } - - - public final Timestamp getTimestamp(int columnIndex) throws SQLException{ - try{ - Object obj = getObjectSetWasNull(columnIndex); - if(wasNull){ - return null; - } - if(obj instanceof cli.System.DateTime){ - return JdbcOdbcUtils.convertDateTimeToTimestamp((cli.System.DateTime)obj); - } - String str = obj.toString(); - return Timestamp.valueOf(str); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final Timestamp getTimestamp(String columnLabel) throws SQLException{ - return getTimestamp(findColumn(columnLabel)); - } - - - public final Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException{ - Timestamp ts = getTimestamp(columnIndex); - JdbcOdbcUtils.convertLocalToCalendarDate(ts, cal); - return ts; - } - - - public final Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException{ - return getTimestamp(findColumn(columnLabel), cal); - } - - - public final URL getURL(int columnIndex) throws SQLException{ - try{ - String url = getString(columnIndex); - if(wasNull){ - return null; - } - return new URL(url); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final URL getURL(String columnLabel) throws SQLException{ - return getURL(findColumn(columnLabel)); - } - - - public final InputStream getUnicodeStream(int columnIndex) throws SQLException{ - try{ - return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF16")); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public final InputStream getUnicodeStream(String columnLabel) throws SQLException{ - return getUnicodeStream(findColumn(columnLabel)); - } - - - public final boolean wasNull(){ - return wasNull; - } - -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcPreparedStatement.java b/openjdk/sun/jdbc/odbc/JdbcOdbcPreparedStatement.java deleted file mode 100644 index 93805fd6..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcPreparedStatement.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.ParameterMetaData; -import java.sql.PreparedStatement; -import java.sql.Ref; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLXML; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.Calendar; - -import cli.System.Data.*; -import cli.System.Data.Common.*; -import cli.System.Data.Odbc.*; - -/** - * @author Volker Berlin - */ -public class JdbcOdbcPreparedStatement extends JdbcOdbcStatement implements PreparedStatement{ - - public JdbcOdbcPreparedStatement(JdbcOdbcConnection jdbcConn, OdbcCommand command, String sql, int resultSetType, int resultSetConcurrency){ - super(jdbcConn, command, resultSetType, resultSetConcurrency); - command.set_CommandText(sql); - command.Prepare(); - } - - - public void addBatch() throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void clearParameters(){ - DbParameterCollection params = command.get_Parameters(); - params.Clear(); - } - - - public boolean execute() throws SQLException{ - return super.execute(null); - } - - - public ResultSet executeQuery() throws SQLException{ - return super.executeQuery(null); - } - - - public int executeUpdate() throws SQLException{ - return super.executeUpdate(null); - } - - - public ResultSetMetaData getMetaData() throws SQLException{ - ResultSet rs = getResultSet(); - if(rs != null){ - rs.getMetaData(); - } - DbDataReader reader = command.ExecuteReader(CommandBehavior.wrap(CommandBehavior.SchemaOnly)); - JdbcOdbcResultSetMetaData metadata = new JdbcOdbcResultSetMetaData(reader); - reader.Close(); - return metadata; - } - - - public ParameterMetaData getParameterMetaData(){ - throw new UnsupportedOperationException(); - } - - - public void setArray(int parameterIndex, Array x) throws SQLException{ - setObject(parameterIndex, x, Types.ARRAY); - } - - - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARCHAR); - } - - - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARCHAR, length); - } - - - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARCHAR, (int)length); - } - - - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException{ - setObject(parameterIndex, x, Types.DECIMAL); - } - - - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARBINARY); - } - - - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARBINARY, length); - } - - - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARBINARY, (int)length); - } - - - public void setBlob(int parameterIndex, Blob x) throws SQLException{ - setObject(parameterIndex, x, Types.BLOB); - } - - - public void setBlob(int parameterIndex, InputStream x) throws SQLException{ - setObject(parameterIndex, x, Types.BLOB); - } - - - public void setBlob(int parameterIndex, InputStream x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.BLOB, (int)length); - } - - - public void setBoolean(int parameterIndex, boolean x) throws SQLException{ - setObject(parameterIndex, Boolean.valueOf(x), Types.BOOLEAN); - } - - - public void setByte(int parameterIndex, byte x) throws SQLException{ - setObject(parameterIndex, Byte.valueOf(x), Types.TINYINT); - } - - - public void setBytes(int parameterIndex, byte[] x) throws SQLException{ - setObject(parameterIndex, x, Types.BINARY); - } - - - public void setCharacterStream(int parameterIndex, Reader x) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARCHAR); - } - - - public void setCharacterStream(int parameterIndex, Reader x, int length) throws SQLException{ - setObject(parameterIndex, x, Types.NCLOB, length); - } - - - public void setCharacterStream(int parameterIndex, Reader x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGVARCHAR, (int)length); - } - - - public void setClob(int parameterIndex, Clob x) throws SQLException{ - setObject(parameterIndex, x, Types.CLOB); - } - - - public void setClob(int parameterIndex, Reader x) throws SQLException{ - setObject(parameterIndex, x, Types.CLOB); - } - - - public void setClob(int parameterIndex, Reader x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.CLOB, (int)length); - } - - - public void setDate(int parameterIndex, Date x) throws SQLException{ - setObject(parameterIndex, x, Types.DATE); - } - - - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException{ - JdbcOdbcUtils.convertCalendarToLocalDate(x, cal); - setObject(parameterIndex, x, Types.DATE); - } - - - public void setDouble(int parameterIndex, double x) throws SQLException{ - setObject(parameterIndex, Double.valueOf(x), Types.DOUBLE); - } - - - public void setFloat(int parameterIndex, float x) throws SQLException{ - setObject(parameterIndex, Float.valueOf(x), Types.FLOAT); - } - - - public void setInt(int parameterIndex, int x) throws SQLException{ - setObject(parameterIndex, Integer.valueOf(x), Types.INTEGER); - } - - - public void setLong(int parameterIndex, long x) throws SQLException{ - setObject(parameterIndex, Long.valueOf(x), Types.BIGINT); - } - - - public void setNCharacterStream(int parameterIndex, Reader x) throws SQLException{ - setObject(parameterIndex, x, Types.LONGNVARCHAR); - } - - - public void setNCharacterStream(int parameterIndex, Reader x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGNVARCHAR, (int)length); - } - - - public void setNClob(int parameterIndex, NClob x) throws SQLException{ - setObject(parameterIndex, x, Types.NCLOB); - } - - - public void setNClob(int parameterIndex, Reader x) throws SQLException{ - setObject(parameterIndex, x, Types.NCLOB); - } - - - public void setNClob(int parameterIndex, Reader x, long length) throws SQLException{ - setObject(parameterIndex, x, Types.NCLOB, (int)length); - } - - - public void setNString(int parameterIndex, String x) throws SQLException{ - setObject(parameterIndex, x, Types.NVARCHAR); - } - - - public void setNull(int parameterIndex, int sqlType) throws SQLException{ - setObject(parameterIndex, null, sqlType); - } - - - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException{ - setObject(parameterIndex, null, sqlType); - } - - - public void setObject(int parameterIndex, Object x) throws SQLException{ - setObject(parameterIndex, x, Types.OTHER, -1); - } - - - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException{ - setObject(parameterIndex, x, targetSqlType, -1); - } - - - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException{ - DbParameter para = getPara(parameterIndex); - para.set_Value(JdbcOdbcUtils.convertJava2Net(x, scaleOrLength)); - if(para.get_Direction().Value == ParameterDirection.Output){ - para.set_Direction(ParameterDirection.wrap(ParameterDirection.InputOutput)); - } - - if(targetSqlType != Types.OTHER){ - para.set_DbType(DbType.wrap(JdbcOdbcUtils.convertJdbc2AdoNetType(targetSqlType))); - } - - if(scaleOrLength >= 0){ - switch(targetSqlType){ - case Types.DECIMAL: - case Types.NUMERIC: - para.set_Scale((byte)scaleOrLength); - } - } - } - - - public void setRef(int parameterIndex, Ref x) throws SQLException{ - setObject(parameterIndex, x, Types.REF); - } - - - public void setRowId(int parameterIndex, RowId x) throws SQLException{ - setObject(parameterIndex, x, Types.ROWID); - } - - - public void setSQLXML(int parameterIndex, SQLXML x) throws SQLException{ - setObject(parameterIndex, x, Types.SQLXML); - } - - - public void setShort(int parameterIndex, short x) throws SQLException{ - setObject(parameterIndex, Short.valueOf(x), Types.SMALLINT); - } - - - public void setString(int parameterIndex, String x) throws SQLException{ - setObject(parameterIndex, x, Types.VARCHAR); - } - - - public void setTime(int parameterIndex, Time x) throws SQLException{ - setObject(parameterIndex, x, Types.TIME); - } - - - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException{ - JdbcOdbcUtils.convertCalendarToLocalDate(x, cal); - setObject(parameterIndex, x, Types.TIME); - } - - - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException{ - setObject(parameterIndex, x, Types.TIMESTAMP); - } - - - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException{ - JdbcOdbcUtils.convertCalendarToLocalDate(x, cal); - setObject(parameterIndex, x, Types.TIMESTAMP); - } - - - public void setURL(int parameterIndex, URL x) throws SQLException{ - setObject(parameterIndex, x, Types.DATALINK); - } - - - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException{ - setObject(parameterIndex, x, Types.LONGNVARCHAR, length); - } - - - /** - * Get the DbParameter from the current command. If the parameter does not exits in the collection then add it. - * - * @param parameterIndex - * The JDBC parameter index starting with 1 - * @return the DbParameter for the index. - * @throws SQLException - * If any error occur. - */ - protected DbParameter getPara(int parameterIndex) throws SQLException{ - try{ - DbParameterCollection params = command.get_Parameters(); - while(params.get_Count() < parameterIndex){ - params.Add(command.CreateParameter()); - } - return params.get_Item(parameterIndex - 1); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcResultSet.java b/openjdk/sun/jdbc/odbc/JdbcOdbcResultSet.java deleted file mode 100644 index 398f368b..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcResultSet.java +++ /dev/null @@ -1,799 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.sql.*; - -import cli.System.Data.Common.*; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider. This ResultSet based on a DataReader. - */ -public class JdbcOdbcResultSet extends JdbcOdbcObject implements ResultSet{ - - private DbDataReader reader; - - private final JdbcOdbcStatement statement; - - private final int holdability; - - private final int concurrency; - - private int fetchSize; - - private int row; - - private final int resultSetType; - - private ResultSetMetaData metaData; - - - /** - * Create a ResultSet that based on a DbDataReader - * - * @param statement - * the statement for getStatement(), can be null - * @param reader - * the reader for the data access, if it null then the resultset is closed. - */ - public JdbcOdbcResultSet(JdbcOdbcStatement statement, DbDataReader reader){ - this.statement = statement; - this.reader = reader; - this.resultSetType = TYPE_FORWARD_ONLY; - this.concurrency = CONCUR_READ_ONLY; - this.holdability = HOLD_CURSORS_OVER_COMMIT; - } - - - /** - * A constructor for extended classes. All methods that use the reader must be overridden if you use this - * constructor. - * - * @param statement - * the statement for getStatement(), can be null - * @param resultSetType - * a result set type; one of ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or - * ResultSet.TYPE_SCROLL_SENSITIVE - * @param concurrency - * a concurrency type; one of ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE - */ - protected JdbcOdbcResultSet(JdbcOdbcStatement statement, int resultSetType, int concurrency){ - this.statement = statement; - this.reader = null; - this.resultSetType = resultSetType; - this.concurrency = concurrency; - this.holdability = HOLD_CURSORS_OVER_COMMIT; - } - - - public boolean absolute(int rowPosition) throws SQLException{ - throwForwardOnly(); - return false; // for Compiler - } - - - public void afterLast() throws SQLException{ - throwForwardOnly(); - } - - - public void beforeFirst() throws SQLException{ - throwForwardOnly(); - } - - - public void cancelRowUpdates() throws SQLException{ - throwReadOnly(); - } - - - public void clearWarnings() throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void close(){ - reader = null; - statement.closeReaderIfPossible(); - } - - - public void deleteRow() throws SQLException{ - throwReadOnly(); - } - - - @Override - public int findColumn(String columnLabel) throws SQLException{ - try{ - return getReader().GetOrdinal(columnLabel) + 1; - }catch(ArrayIndexOutOfBoundsException ex){ - throw new SQLException("Column '" + columnLabel + "' not found.", "S0022", ex); - } - } - - - public boolean first() throws SQLException{ - throwForwardOnly(); - return false; // for compiler - } - - - public int getConcurrency(){ - return concurrency; - } - - - public String getCursorName() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public int getFetchDirection(){ - return FETCH_UNKNOWN; - } - - - public int getFetchSize(){ - return fetchSize; - } - - - public int getHoldability(){ - return holdability; - } - - - public ResultSetMetaData getMetaData() throws SQLException{ - if(metaData == null){ - metaData = new JdbcOdbcResultSetMetaData(getReader()); - } - return metaData; - } - - - public int getRow() throws SQLException{ - getReader(); // checking for is closed - return row; - } - - - public Statement getStatement(){ - return statement; - } - - - public int getType(){ - return resultSetType; - } - - - public SQLWarning getWarnings() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public void insertRow() throws SQLException{ - throwReadOnly(); - } - - - public boolean isAfterLast() throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public boolean isBeforeFirst() throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public boolean isClosed(){ - return reader == null; - } - - - public boolean isFirst() throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public boolean isLast() throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public boolean last() throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public void moveToCurrentRow() throws SQLException{ - throwReadOnly(); - } - - - public void moveToInsertRow() throws SQLException{ - throwReadOnly(); - } - - - public boolean next() throws SQLException{ - DbDataReader dataReader = getReader(); - //if we after the last row then we close the reader - //to prevent an error on repeating call of next() after the end - //that we check also get_IsClosed() - if(!dataReader.get_IsClosed() && dataReader.Read()){ - row++; - return true; - } - row = 0; - statement.closeReaderIfPossible(); - return false; - } - - - public boolean previous() throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public void refreshRow() throws SQLException{ - throwForwardOnly(); - } - - - public boolean relative(int rowPositions) throws SQLException{ - throwForwardOnly(); - return false; // only for compiler - } - - - public boolean rowDeleted() throws SQLException{ - throwReadOnly(); - return false; // only for compiler - } - - - public boolean rowInserted() throws SQLException{ - throwReadOnly(); - return false; // only for compiler - } - - - public boolean rowUpdated() throws SQLException{ - throwReadOnly(); - return false; // only for compiler - } - - - public void setFetchDirection(int direction){ - // ignore it - } - - - public void setFetchSize(int rows){ - // ignore it - } - - - public void updateArray(int columnIndex, Array x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateArray(String columnLabel, Array x) throws SQLException{ - updateArray(findColumn(columnLabel), x); - } - - - public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException{ - updateObject(columnIndex, x, length); - } - - - public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException{ - updateObject(findColumn(columnLabel), x, length); - } - - - public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException{ - updateObject(columnIndex, x, length); - } - - - public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException{ - updateObject(findColumn(columnLabel), x, length); - } - - - public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateBlob(int columnIndex, Blob x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateBlob(String columnLabel, Blob x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateBlob(int columnIndex, InputStream x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateBlob(String columnLabel, InputStream x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateBlob(int columnIndex, InputStream x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateBlob(String columnLabel, InputStream x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateBoolean(int columnIndex, boolean x) throws SQLException{ - updateObject(columnIndex, Boolean.valueOf(x)); - } - - - public void updateBoolean(String columnLabel, boolean x) throws SQLException{ - updateObject(findColumn(columnLabel), Boolean.valueOf(x)); - } - - - public void updateByte(int columnIndex, byte x) throws SQLException{ - updateObject(columnIndex, Byte.valueOf(x)); - } - - - public void updateByte(String columnLabel, byte x) throws SQLException{ - updateObject(findColumn(columnLabel), Byte.valueOf(x)); - } - - - public void updateBytes(int columnIndex, byte[] x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateBytes(String columnLabel, byte[] x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException{ - updateObject(columnIndex, x, length); - } - - - public void updateCharacterStream(String columnLabel, Reader x, int length) throws SQLException{ - updateObject(findColumn(columnLabel), x, length); - } - - - public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateCharacterStream(String columnLabel, Reader x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateCharacterStream(int columnIndex, Reader x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateCharacterStream(String columnLabel, Reader x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateClob(int columnIndex, Clob x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateClob(String columnLabel, Clob x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateClob(int columnIndex, Reader x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateClob(String columnLabel, Reader x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateClob(int columnIndex, Reader x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateClob(String columnLabel, Reader x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateDate(int columnIndex, Date x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateDate(String columnLabel, Date x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateDouble(int columnIndex, double x) throws SQLException{ - updateObject(columnIndex, Double.valueOf(x)); - } - - - public void updateDouble(String columnLabel, double x) throws SQLException{ - updateObject(findColumn(columnLabel), Double.valueOf(x)); - } - - - public void updateFloat(int columnIndex, float x) throws SQLException{ - updateObject(columnIndex, Float.valueOf(x)); - } - - - public void updateFloat(String columnLabel, float x) throws SQLException{ - updateObject(findColumn(columnLabel), Float.valueOf(x)); - } - - - public void updateInt(int columnIndex, int x) throws SQLException{ - updateObject(columnIndex, Integer.valueOf(x)); - } - - - public void updateInt(String columnLabel, int x) throws SQLException{ - updateObject(findColumn(columnLabel), Integer.valueOf(x)); - } - - - public void updateLong(int columnIndex, long x) throws SQLException{ - updateObject(columnIndex, Long.valueOf(x)); - } - - - public void updateLong(String columnLabel, long x) throws SQLException{ - updateObject(findColumn(columnLabel), Long.valueOf(x)); - } - - - public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateNCharacterStream(String columnLabel, Reader x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateNCharacterStream(String columnLabel, Reader x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateNClob(int columnIndex, NClob x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateNClob(String columnLabel, NClob x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateNClob(int columnIndex, Reader x, long length) throws SQLException{ - updateObject(columnIndex, x, (int)length); - } - - - public void updateNClob(String columnLabel, Reader x, long length) throws SQLException{ - updateObject(findColumn(columnLabel), x, (int)length); - } - - - public void updateNClob(int columnIndex, Reader x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateNClob(String columnLabel, Reader x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateNString(int columnIndex, String x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateNString(String columnLabel, String x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateNull(int columnIndex) throws SQLException{ - updateObject(columnIndex, null); - } - - - public void updateNull(String columnLabel) throws SQLException{ - updateObject(findColumn(columnLabel), null); - } - - - public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException{ - throwReadOnly(); - } - - - public void updateObject(int columnIndex, Object x) throws SQLException{ - updateObject(columnIndex, x, -1); - } - - - public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException{ - updateObject(findColumn(columnLabel), x, scaleOrLength); - } - - - public void updateObject(String columnLabel, Object x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateRef(int columnIndex, Ref x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateRef(String columnLabel, Ref x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateRow() throws SQLException{ - throwReadOnly(); - } - - - public void updateRowId(int columnIndex, RowId x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateRowId(String columnLabel, RowId x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateSQLXML(int columnIndex, SQLXML x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateSQLXML(String columnLabel, SQLXML x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateShort(int columnIndex, short x) throws SQLException{ - updateObject(columnIndex, Short.valueOf(x)); - } - - - public void updateShort(String columnLabel, short x) throws SQLException{ - updateObject(findColumn(columnLabel), Short.valueOf(x)); - } - - - public void updateString(int columnIndex, String x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateString(String columnLabel, String x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateTime(int columnIndex, Time x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateTime(String columnLabel, Time x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException{ - updateObject(columnIndex, x); - } - - - public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException{ - updateObject(findColumn(columnLabel), x); - } - - - public boolean isWrapperFor(Class<?> iface){ - return iface.isAssignableFrom(this.getClass()); - } - - - public <T>T unwrap(Class<T> iface) throws SQLException{ - if(isWrapperFor(iface)){ - return (T)this; - } - throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); - } - - - private void throwForwardOnly() throws SQLException{ - throw new SQLException("ResultSet is forward only.", "24000"); - } - - - private void throwReadOnly() throws SQLException{ - throw new SQLException("ResultSet is read only.", "24000"); - } - - - /** - * Check if this ResultSet is closed before access to the DbDataReader - * - * @return - * @throws SQLException - */ - private DbDataReader getReader() throws SQLException{ - if(reader == null){ - throw new SQLException("ResultSet is closed.", "24000"); - } - return reader; - } - - - /** - * {@inheritDoc} - */ - @Override - protected Object getObjectImpl(int columnIndex) throws SQLException{ - try{ - DbDataReader datareader = getReader(); - try{ - return datareader.get_Item(columnIndex-1); - }catch(ArrayIndexOutOfBoundsException aioobe){ - throw new SQLException( "Invalid column number ("+columnIndex+"). A number between 1 and "+datareader.get_FieldCount()+" is valid.", "S1002", aioobe); - } - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - /** - * {@inheritDoc} - */ - public <T> T getObject(int columnIndex, Class<T> type) throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - - /** - * {@inheritDoc} - */ - public <T> T getObject(String columnLabel, Class<T> type) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcResultSetMetaData.java b/openjdk/sun/jdbc/odbc/JdbcOdbcResultSetMetaData.java deleted file mode 100644 index a92fdaf1..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcResultSetMetaData.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import ikvm.lang.CIL; - -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Types; - -import cli.System.Convert; -import cli.System.DBNull; -import cli.System.Data.*; -import cli.System.Data.Common.*; -import cli.System.Data.Odbc.OdbcType; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider. - */ -public class JdbcOdbcResultSetMetaData implements ResultSetMetaData{ - - private final DbDataReader reader; - - private final DataTable schema; - - JdbcOdbcResultSetMetaData(DbDataReader reader){ - this.reader = reader; - schema = reader.GetSchemaTable(); - } - - public String getCatalogName(int column) throws SQLException{ - Object obj = getColumnMeta(column, "BaseCatalogName"); - if(obj == null || obj == DBNull.Value){ - return ""; - } - return obj.toString(); - } - - - public String getColumnClassName(int column) throws SQLException{ - String type = getColumnMeta(column, "DataType").toString(); - return JdbcOdbcUtils.getJavaClassName(type); - } - - - public int getColumnCount(){ - return schema.get_Rows().get_Count(); - } - - - public int getColumnDisplaySize(int column) throws SQLException{ - int precision = getPrecision(column); - int type = CIL.unbox_int( getColumnMeta(column, "ProviderType") ); - switch(type){ - case OdbcType.Decimal: - case OdbcType.Numeric: - return precision + (getScale(column) > 0 ? 2 : 1); // + sign and comma - } - return precision; - } - - - public String getColumnLabel(int column) throws SQLException{ - return getColumnMeta(column, "ColumnName").toString(); - } - - - public String getColumnName(int column) throws SQLException{ - return getColumnMeta(column, "ColumnName").toString(); - } - - - public int getColumnType(int column) throws SQLException{ - int type = CIL.unbox_int( getColumnMeta(column, "ProviderType") ); - switch(type){ - case OdbcType.VarChar: - return Types.VARCHAR; - case OdbcType.Char: - return Types.CHAR; - case OdbcType.Binary: - case OdbcType.Timestamp: - return Types.BINARY; - case OdbcType.Bit: - return Types.BOOLEAN; - case OdbcType.TinyInt: - return Types.TINYINT; - case OdbcType.Date: - return Types.DATE; - case OdbcType.DateTime: - case OdbcType.SmallDateTime: - return Types.TIMESTAMP; - case OdbcType.Decimal: - return Types.DECIMAL; - case OdbcType.Double: - return Types.DOUBLE; - case OdbcType.UniqueIdentifier: - return Types.ROWID; - case OdbcType.SmallInt: - return Types.SMALLINT; - case OdbcType.Int: - return Types.INTEGER; - case OdbcType.BigInt: - return Types.BIGINT; - case OdbcType.Real: - return Types.FLOAT; - case OdbcType.NVarChar: - return Types.NVARCHAR; - case OdbcType.NChar: - return Types.NCHAR; - case OdbcType.NText: - return Types.LONGNVARCHAR; - case OdbcType.Text: - return Types.LONGVARCHAR; - case OdbcType.Image: - return Types.LONGVARBINARY; - case OdbcType.Time: - return Types.TIME; - case OdbcType.Numeric: - return Types.NUMERIC; - case OdbcType.VarBinary: - return Types.VARBINARY; - } - return Types.OTHER; - } - - - public String getColumnTypeName(int column) throws SQLException{ - try{ - return reader.GetDataTypeName(column - 1); - }catch(ArrayIndexOutOfBoundsException ex){ - throw new SQLException("Invalid column number ("+column+"). A number between 1 and "+schema.get_Rows().get_Count()+" is valid.", "S1002"); - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - public int getPrecision(int column) throws SQLException{ - Object obj = getColumnMeta(column, "NumericPrecision"); - return Convert.ToInt32(obj); - } - - - public int getScale(int column) throws SQLException{ - Object obj = getColumnMeta(column, "NumericScale"); - return Convert.ToInt32(obj); - } - - - public String getSchemaName(int column) throws SQLException{ - Object obj = getColumnMeta(column, "BaseSchemaName"); - if(obj == null || obj == DBNull.Value){ - return ""; - } - return obj.toString(); - } - - - public String getTableName(int column) throws SQLException{ - Object obj = getColumnMeta(column, "BaseTableName"); - if(obj == null || obj == DBNull.Value){ - return ""; - } - return obj.toString(); - } - - - public boolean isAutoIncrement(int column) throws SQLException{ - Object obj = getColumnMeta(column, "IsAutoIncrement"); - return Convert.ToBoolean(obj); - } - - - public boolean isCaseSensitive(int column){ - return false; - } - - - public boolean isCurrency(int column) throws SQLException{ - return CIL.unbox_int( getColumnMeta(column, "ProviderType") ) == OdbcType.Decimal && getScale(column) == 4; - } - - - public boolean isDefinitelyWritable(int column){ - return false; - } - - - public int isNullable(int column) throws SQLException{ - Object obj = getColumnMeta(column, "AllowDBNull"); - return Convert.ToBoolean(obj) ? columnNullable : columnNoNulls; - } - - - public boolean isReadOnly(int column) throws SQLException{ - Object obj = getColumnMeta(column, "IsReadOnly"); - return Convert.ToBoolean(obj); - } - - - public boolean isSearchable(int column) throws SQLException{ - return !CIL.unbox_boolean( getColumnMeta(column, "IsLong") ); - } - - - public boolean isSigned(int column) throws SQLException{ - int type = CIL.unbox_int( getColumnMeta(column, "ProviderType") ); - switch(type){ - case OdbcType.Numeric: - case OdbcType.Decimal: - case OdbcType.Double: - case OdbcType.SmallInt: - case OdbcType.Int: - case OdbcType.BigInt: - case OdbcType.Real: - return true; - } - return false; - } - - - public boolean isWritable(int column) throws SQLException{ - Object obj = getColumnMeta(column, "IsReadOnly"); - return !Convert.ToBoolean(obj); - } - - - public boolean isWrapperFor(Class<?> iface){ - return iface.isAssignableFrom(this.getClass()); - } - - - public <T>T unwrap(Class<T> iface) throws SQLException{ - if(isWrapperFor(iface)){ - return (T)this; - } - throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); - } - - private Object getColumnMeta(int column, String metaKey) throws SQLException{ - try{ - DataRow columnMeta = schema.get_Rows().get_Item(column-1); - return columnMeta.get_Item(metaKey); - }catch(ArrayIndexOutOfBoundsException ex){ - throw new SQLException("Invalid column number ("+column+"). A number between 1 and "+schema.get_Rows().get_Count()+" is valid.", "S1002"); - } - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcStatement.java b/openjdk/sun/jdbc/odbc/JdbcOdbcStatement.java deleted file mode 100644 index 358ae0e7..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcStatement.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - Copyright (C) 2009, 2011 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.sql.*; - -import cli.System.Data.*; -import cli.System.Data.Common.*; -import cli.System.Data.Odbc.*; - -/** - * This JDBC Driver is a wrapper to the ODBC.NET Data Provider. - */ -public class JdbcOdbcStatement implements Statement{ - - private final JdbcOdbcConnection jdbcConn; - - protected final OdbcCommand command; - - private final int resultSetType; - - private final int resultSetConcurrency; - - private DbDataReader reader; - - private ResultSet rs; - - private int updateCount; - - private boolean isClosed; - - private ResultSet moreResults; - - public JdbcOdbcStatement(JdbcOdbcConnection jdbcConn, OdbcCommand command, int resultSetType, int resultSetConcurrency){ - this.jdbcConn = jdbcConn; - this.command = command; - this.resultSetType = resultSetType; - this.resultSetConcurrency = resultSetConcurrency; - } - - - public void addBatch(String sql) throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void cancel() throws SQLException{ - try{ - command.Cancel(); - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - public void clearBatch() throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void clearWarnings() throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void close() throws SQLException{ - isClosed = true; - if(rs != null){ - rs.close(); - } - if(reader != null){ - reader.Close(); - } - command.Dispose(); - } - - - public boolean execute(String sql) throws SQLException{ - try{ - if(sql != null){ - command.set_CommandText(sql); - } - command.ExecuteNonQuery(); - return false; - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - public boolean execute(String sql, int autoGeneratedKeys){ - throw new UnsupportedOperationException(); - } - - - public boolean execute(String sql, int[] columnIndexes){ - throw new UnsupportedOperationException(); - } - - - public boolean execute(String sql, String[] columnNames){ - throw new UnsupportedOperationException(); - } - - - public int[] executeBatch() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public ResultSet executeQuery(String sql) throws SQLException{ - try{ - if(sql != null){ - command.set_CommandText(sql); - } - if(resultSetConcurrency == ResultSet.CONCUR_UPDATABLE){ - rs = new JdbcOdbcUpdateableResultSet(command); - }else{ - if(resultSetType == ResultSet.TYPE_FORWARD_ONLY){ - reader = command.ExecuteReader(); - rs = new JdbcOdbcResultSet(this, reader); - }else{ - OdbcDataAdapter da = new OdbcDataAdapter(command); - DataTable dt = new DataTable(); - da.Fill(dt); - rs = new JdbcOdbcDTResultSet(dt); - } - } - return rs; - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - public int executeUpdate(String sql) throws SQLException{ - try{ - if(sql != null){ - command.set_CommandText(sql); - } - updateCount = command.ExecuteNonQuery(); - return updateCount; - }catch(Throwable ex){ - throw JdbcOdbcUtils.createSQLException(ex); - } - } - - - public int executeUpdate(String sql, int autoGeneratedKeys){ - throw new UnsupportedOperationException(); - } - - - public int executeUpdate(String sql, int[] columnIndexes){ - throw new UnsupportedOperationException(); - } - - - public int executeUpdate(String sql, String[] columnNames){ - throw new UnsupportedOperationException(); - } - - - public Connection getConnection(){ - return jdbcConn; - } - - - public int getFetchDirection(){ - return ResultSet.FETCH_UNKNOWN; - } - - - public int getFetchSize(){ - return 0; - } - - - public ResultSet getGeneratedKeys(){ - throw new UnsupportedOperationException(); - } - - - public int getMaxFieldSize() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getMaxRows() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public boolean getMoreResults() throws SQLException{ - try{ - if(moreResults != null){ - rs = moreResults; - moreResults = null; - return true; - } - boolean isNext = reader.NextResult(); - if(isNext){ - rs = new JdbcOdbcResultSet(this, reader); - return true; - } - rs = null; - return false; - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - public boolean getMoreResults(int current) throws SQLException{ - // TODO Auto-generated method stub - return false; - } - - - public int getQueryTimeout(){ - return command.get_CommandTimeout(); - } - - - public ResultSet getResultSet(){ - return rs; - } - - - public int getResultSetConcurrency(){ - return resultSetConcurrency; - } - - - public int getResultSetHoldability() throws SQLException{ - // TODO Auto-generated method stub - return 0; - } - - - public int getResultSetType(){ - return resultSetType; - } - - - public int getUpdateCount(){ - return updateCount; - } - - - public SQLWarning getWarnings() throws SQLException{ - // TODO Auto-generated method stub - return null; - } - - - public boolean isClosed(){ - return isClosed; - } - - - public void setCursorName(String name) throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void setEscapeProcessing(boolean enable) throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void setFetchDirection(int direction){ - // ignore it - } - - - public void setFetchSize(int rows){ - // ignore it - } - - - public void setMaxFieldSize(int max) throws SQLException{ - // TODO Auto-generated method stub - - } - - - public void setMaxRows(int max) throws SQLException{ - // TODO Auto-generated method stub - - } - - - public boolean isPoolable(){ - return false; - } - - - public void setPoolable(boolean poolable) throws SQLException{ - // ignore it - } - - - public void setQueryTimeout(int seconds){ - command.set_CommandTimeout(seconds); - } - - - public boolean isWrapperFor(Class<?> iface){ - return iface.isAssignableFrom(this.getClass()); - } - - - public <T>T unwrap(Class<T> iface) throws SQLException{ - if(isWrapperFor(iface)){ - return (T)this; - } - throw new SQLException(this.getClass().getName() + " does not implements " + iface.getName() + ".", "01000"); - } - - /** - * Close the DbDataReader if there are no more results. - * This give some blocking free without calling close() explicit. - * If there are more results then we need to save it. - */ - void closeReaderIfPossible(){ - ResultSet currentRs = rs; - boolean isMoreResults; - try{ - isMoreResults = getMoreResults(); - }catch(SQLException ex){ - isMoreResults = false; - } - if(!isMoreResults){ - reader.Close(); //this give the ODBC cursor free - }else{ - moreResults = rs; - } - rs = currentRs; - } - - - /** - * {@inheritDoc} - */ - public void closeOnCompletion() throws SQLException { - } - - - /** - * {@inheritDoc} - */ - public boolean isCloseOnCompletion() throws SQLException { - return false; - } - -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcUpdateableResultSet.java b/openjdk/sun/jdbc/odbc/JdbcOdbcUpdateableResultSet.java deleted file mode 100644 index a3ce0ffe..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcUpdateableResultSet.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import java.sql.*; - -import cli.System.Data.*; -import cli.System.Data.Odbc.*; - -/** - * @author Volker Berlin - */ -public class JdbcOdbcUpdateableResultSet extends JdbcOdbcDTResultSet{ - - private final OdbcDataAdapter da; - - private final DataTable data; - - private DataRow insertRow; - - - public JdbcOdbcUpdateableResultSet(OdbcCommand cmd){ - this(new DataTable(), cmd); - } - - - private JdbcOdbcUpdateableResultSet(DataTable data, OdbcCommand cmd){ - super(data, CONCUR_UPDATABLE); - this.data = data; - da = new OdbcDataAdapter(cmd); - da.Fill(data); - OdbcCommandBuilder cmdBldr = new OdbcCommandBuilder(da); - cmdBldr.GetUpdateCommand(); // throw an exception if update is not possible, we want a very early exception - } - - - @Override - protected DataRow getDataRow() throws SQLException{ - if(insertRow != null){ - return insertRow; - } - return super.getDataRow(); - } - - - @Override - protected void setDataRow() throws SQLException{ - insertRow = null; - super.setDataRow(); - } - - - @Override - public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException{ - try{ - x = JdbcOdbcUtils.convertJava2Net(x, scaleOrLength); - getDataRow().set_Item(columnIndex - 1, x); - }catch(ArrayIndexOutOfBoundsException ex){ - throw new SQLException("Invalid column number (" + columnIndex + "). A number between 1 and " - + data.get_Columns().get_Count() + " is valid.", "S1002", ex); - } - } - - - @Override - public void updateRow() throws SQLException{ - if(insertRow != null){ - throw new SQLException("Cursor is on the insert row."); - } - try{ - da.Update(data); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - @Override - public void deleteRow() throws SQLException{ - if(insertRow != null){ - throw new SQLException("Cursor is on the insert row."); - } - try{ - getDataRow().Delete(); // Delete the current row - da.Update(data); - setDataRow(); // set a new Current Row - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - } - - - @Override - public void insertRow() throws SQLException{ - if(insertRow == null){ - throw new SQLException("Cursor is not on the insert row."); - } - try{ - getRows().Add(insertRow); - insertRow = null; - da.Update(data); - last(); - }catch(Throwable th){ - throw JdbcOdbcUtils.createSQLException(th); - } - - } - - - @Override - public void moveToInsertRow(){ - insertRow = data.NewRow(); - } - - - @Override - public void moveToCurrentRow(){ - insertRow = null; - } - - - @Override - public void cancelRowUpdates() throws SQLException{ - getDataRow().CancelEdit(); - } - - - @Override - public boolean rowDeleted(){ - return false; - } - - - @Override - public boolean rowInserted(){ - return false; - } - - - @Override - public boolean rowUpdated(){ - return false; - } -} diff --git a/openjdk/sun/jdbc/odbc/JdbcOdbcUtils.java b/openjdk/sun/jdbc/odbc/JdbcOdbcUtils.java deleted file mode 100644 index c5497e30..00000000 --- a/openjdk/sun/jdbc/odbc/JdbcOdbcUtils.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - Copyright (C) 2009, 2010 Volker Berlin (i-net software) - Copyright (C) 2011 Karsten Heinrich (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.jdbc.odbc; - -import ikvm.lang.CIL; - -import java.math.BigDecimal; -import java.sql.*; -import java.util.Calendar; -import java.util.HashMap; - -import cli.System.DBNull; -import cli.System.TimeSpan; -import cli.System.Data.DbType; -import cli.System.Data.Common.DbException; -import cli.System.Data.Odbc.*; -import cli.System.Globalization.CultureInfo; - -/** - * @author Volker Berlin - */ -public class JdbcOdbcUtils{ - - private static final HashMap<String, String> classNameMap = new HashMap<String, String>(); - static{ - classNameMap.put("System.String", "java.lang.String"); - classNameMap.put("System.Int16", "java.lang.Short"); - classNameMap.put("System.Int32", "java.lang.Integer"); - classNameMap.put("System.Int64", "java.lang.Long"); - classNameMap.put("System.Double", "java.lang.Double"); - classNameMap.put("System.Decimal", "java.math.BigDecimal"); - classNameMap.put("System.DateTime", "java.sql.Timestamp"); - classNameMap.put("System.TimeSpan", "java.sql.Time"); - } - - - /** - * Solve a mapping between .NET class names and the equivalent Java class names for - * ResultSetMetaData.getColumnClassName - * - * @param netClassName - * the .NET class name - * @return the Java class name - */ - public static String getJavaClassName(String netClassName){ - String javaClassName = classNameMap.get(netClassName); - if(javaClassName != null){ - return javaClassName; - } - return "java.lang.Object"; - } - - - /** - * Convert a .NET Object in the equals Java Object. - * - * @param obj - * the .NET Object - * @return a Java Object - */ - public static java.lang.Object convertNet2Java(java.lang.Object obj){ - if(obj instanceof cli.System.Int64){ - return Long.valueOf(CIL.unbox_long(obj)); - } - if(obj instanceof cli.System.Int32){ - return Integer.valueOf(CIL.unbox_int(obj)); - } - if(obj instanceof cli.System.Int16){ - return Short.valueOf(CIL.unbox_short(obj)); - } - if(obj instanceof cli.System.Byte){ - return Byte.valueOf(CIL.unbox_byte(obj)); - } - if(obj instanceof cli.System.Double){ - return Double.valueOf(CIL.unbox_double(obj)); - } - if(obj instanceof cli.System.Single){ - return Float.valueOf(CIL.unbox_float(obj)); - } - if(obj instanceof cli.System.Boolean){ - return Boolean.valueOf(CIL.unbox_boolean(obj)); - } - if(obj instanceof cli.System.Decimal){ - return new BigDecimal(((cli.System.Decimal)obj).ToString(CultureInfo.get_InvariantCulture())); - } - if(obj instanceof cli.System.DateTime){ - return convertDateTimeToTimestamp((cli.System.DateTime)obj); - } - if(obj instanceof cli.System.TimeSpan){ - cli.System.TimeSpan ts = (cli.System.TimeSpan)obj; - return new Time(ts.get_Hours(), ts.get_Minutes(), ts.get_Seconds()); - } - if(obj instanceof cli.System.DBNull){ - return null; - } - return obj; - } - - /** - * Converts a .NET DateTime to a Timestamp in the current Timezone - * @param obj the dateTime - * @return the conveted time stamp - */ - public static Timestamp convertDateTimeToTimestamp( cli.System.DateTime obj) { - long javaMillis = getJavaMillis(obj); - int seconds = (int)(javaMillis / 1000); - int nanos = (int)((javaMillis % 1000) * 1000000); - return new Timestamp( 70, 0, 1, 0, 0, seconds, nanos ); - } - - - /** - * Convert a Java Object in the equals .NET Object. - * - * @param obj - * Java Object - * @param length - * the length of data if obj is a stream - * @return .NET Object - */ - public static Object convertJava2Net(Object obj, int length){ - // TODO use the length with streams - return convertJava2Net(obj); - } - - - /** - * Convert a Java Object in the equals .NET Object. - * - * @param obj - * Java Object - * @return a .NET Object - */ - public static Object convertJava2Net(Object obj){ - if(obj == null){ - return DBNull.Value; - } - if(obj instanceof Double){ - return CIL.box_double(((Double)obj).doubleValue()); - } - if(obj instanceof Float){ - return CIL.box_float(((Float)obj).floatValue()); - } - if(obj instanceof Long){ - return CIL.box_long(((Long)obj).longValue()); - } - if(obj instanceof Integer){ - return CIL.box_int(((Integer)obj).intValue()); - } - if(obj instanceof Short){ - return CIL.box_short(((Short)obj).shortValue()); - } - if(obj instanceof Byte){ - return CIL.box_byte(((Byte)obj).byteValue()); - } - if(obj instanceof Boolean){ - return CIL.box_boolean(((Boolean)obj).booleanValue()); - } - if(obj instanceof Time){ - Time ts = (Time)obj; - return new TimeSpan(ts.getHours(), ts.getMinutes(), ts.getSeconds()); - } - if(obj instanceof java.util.Date){ - long ticks = getNetTicks((java.util.Date)obj); - return new cli.System.DateTime(ticks); - } - if(obj instanceof BigDecimal){ - return cli.System.Decimal.Parse(obj.toString(), CultureInfo.get_InvariantCulture()); - } - return obj; - } - - - /** - * Get the milliseconds in the Java range from a .NET DateTime object. - * - * @param dt - * the DateTime object - * @return the milliseconds since 1970-01-01 - */ - public static long getJavaMillis(cli.System.DateTime dt){ - // calculation copied from System.currentTimeMillis() - long january_1st_1970 = 62135596800000L; - return dt.get_Ticks() / 10000L - january_1st_1970; - } - - - /** - * Get the ticks for a System.DateTime from a java.util.Date - * - * @param date - * the java.util.Date - * @return ticks - */ - public static long getNetTicks(java.util.Date date){ - // inverse from getJavaMillis - long january_1st_1970 = 62135596800000L; - return (date.getTime() + january_1st_1970) * 10000L; - } - - - /** - * Convert a local (current default) Date to a Date in the time zone of the given calendar. Do nothing if date or - * calendar is null. - * - * @param date - * the converting Date - * @param cal - * the Calendar with the time zone - */ - public static void convertLocalToCalendarDate(java.util.Date date, Calendar cal){ - if(date == null || cal == null){ - return; - } - cal.set(date.getYear() + 1900, date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date - .getSeconds()); - long millis = cal.getTimeInMillis() / 1000 * 1000 + date.getTime() % 1000; - date.setTime(millis); - } - - - /** - * Convert a Date in the calendar time zone to a date in the local (current default) time zone. Do nothing if date - * or calendar is null. - * - * @param date - * @param cal - */ - public static void convertCalendarToLocalDate(java.util.Date date, Calendar cal){ - if(date == null || cal == null){ - return; - } - cal.setTimeInMillis(date.getTime()); - date.setYear(cal.get(Calendar.YEAR) - 1900); - date.setMonth(cal.get(Calendar.MONTH)); - date.setDate(cal.get(Calendar.DAY_OF_MONTH)); - date.setHours(cal.get(Calendar.HOUR_OF_DAY)); - date.setMinutes(cal.get(Calendar.MINUTE)); - date.setSeconds(cal.get(Calendar.SECOND)); - } - - - /** - * The only valid Exception for JDBC is a SQLException. Here we create one based on the real exception. - * - * @param th - * any Throwable that occur - * @return a SQLException, never null - */ - public static SQLException createSQLException(Throwable th){ - if(th instanceof SQLException){ - return (SQLException)th; - } - if(th instanceof OdbcException){ - SQLException sqlEx = null; - OdbcErrorCollection errors = ((OdbcException)th).get_Errors(); - for(int e = 0; e < errors.get_Count(); e++){ - OdbcError err = errors.get_Item(e); - SQLException newEx = new SQLException(err.get_Message(), err.get_SQLState(), err.get_NativeError()); - if(sqlEx == null){ - sqlEx = newEx; - }else{ - sqlEx.setNextException(newEx); - } - } - if(sqlEx != null){ - sqlEx.initCause(th); - return sqlEx; - } - } - if(th instanceof DbException){ - DbException dbEx = (DbException)th; - return new SQLException(dbEx.get_Message(), "S1000", dbEx.get_ErrorCode(), th); - } - return new SQLException(th); - } - - - /** - * Convert a value from java.sql.Types to a value from to a System.Data.DbType - * - * @param type - * a JDBC type - * @return a ADO.NET type - * @throws SQLException - * if the type can not be converted - */ - public static int convertJdbc2AdoNetType(int type) throws SQLException{ - switch(type){ - case Types.BIGINT: - return DbType.Int64; - case Types.BINARY: - case Types.BLOB: - case Types.LONGVARBINARY: - case Types.VARBINARY: - return DbType.Binary; - case Types.BIT: - case Types.BOOLEAN: - return DbType.Boolean; - case Types.CHAR: - return DbType.AnsiStringFixedLength; - case Types.CLOB: - case Types.DATALINK: - case Types.LONGVARCHAR: - case Types.NULL: // we hope that the DBMS can map any NULL values from VARCHAR - case Types.VARCHAR: - return DbType.AnsiString; - case Types.DATE: - return DbType.Date; - case Types.DECIMAL: - case Types.NUMERIC: - return DbType.Decimal; - case Types.DOUBLE: - return DbType.Double; - case Types.FLOAT: - case Types.REAL: - return DbType.Single; - case Types.INTEGER: - return DbType.Int32; - case Types.JAVA_OBJECT: - return DbType.Object; - case Types.LONGNVARCHAR: - case Types.NCLOB: - case Types.NVARCHAR: - return DbType.String; - case Types.NCHAR: - return DbType.StringFixedLength; - case Types.ROWID: - return DbType.Guid; - case Types.SMALLINT: - return DbType.Int16; - case Types.SQLXML: - return DbType.Xml; - case Types.TIME: - return DbType.Time; - case Types.TIMESTAMP: - return DbType.DateTime; - case Types.TINYINT: - return DbType.Byte; - case Types.ARRAY: - case Types.DISTINCT: - case Types.OTHER: - case Types.REF: - case Types.STRUCT: - break; - - } - throw new SQLException("Not supported JDBC type:" + type); - } -} diff --git a/openjdk/sun/management/ManagementFactoryHelper.java b/openjdk/sun/management/ManagementFactoryHelper.java deleted file mode 100644 index 0e54032d..00000000 --- a/openjdk/sun/management/ManagementFactoryHelper.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.management; - -import java.lang.management.*; - -import javax.management.InstanceAlreadyExistsException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanServer; -import javax.management.MBeanRegistrationException; -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; -import javax.management.RuntimeOperationsException; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import sun.security.action.LoadLibraryAction; - -import sun.util.logging.LoggingSupport; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import com.sun.management.OSMBeanFactory; - -import static java.lang.management.ManagementFactory.*; - -/** - * ManagementFactoryHelper provides static factory methods to create - * instances of the management interface. - */ -public class ManagementFactoryHelper { - private ManagementFactoryHelper() {}; - - private static VMManagement jvm; - - private static ClassLoadingImpl classMBean = null; - private static MemoryImpl memoryMBean = null; - private static ThreadImpl threadMBean = null; - private static RuntimeImpl runtimeMBean = null; - private static CompilationImpl compileMBean = null; - private static OperatingSystemImpl osMBean = null; - - public static synchronized ClassLoadingMXBean getClassLoadingMXBean() { - if (classMBean == null) { - classMBean = new ClassLoadingImpl(jvm); - } - return classMBean; - } - - public static synchronized MemoryMXBean getMemoryMXBean() { - if (memoryMBean == null) { - memoryMBean = new MemoryImpl(jvm); - } - return memoryMBean; - } - - public static synchronized ThreadMXBean getThreadMXBean() { - if (threadMBean == null) { - threadMBean = new ThreadImpl(jvm); - } - return threadMBean; - } - - public static synchronized RuntimeMXBean getRuntimeMXBean() { - if (runtimeMBean == null) { - runtimeMBean = new RuntimeImpl(jvm); - } - return runtimeMBean; - } - - public static synchronized CompilationMXBean getCompilationMXBean() { - if (compileMBean == null && jvm.getCompilerName() != null) { - compileMBean = new CompilationImpl(jvm); - } - return compileMBean; - } - - public static synchronized OperatingSystemMXBean getOperatingSystemMXBean() { - if (osMBean == null) { - osMBean = (OperatingSystemImpl) - OSMBeanFactory.getOperatingSystemMXBean(jvm); - } - return osMBean; - } - - public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() { - MemoryPoolMXBean[] pools = MemoryImpl.getMemoryPools(); - List<MemoryPoolMXBean> list = new ArrayList<MemoryPoolMXBean>(pools.length); - for (MemoryPoolMXBean p : pools) { - list.add(p); - } - return list; - } - - public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() { - MemoryManagerMXBean[] mgrs = MemoryImpl.getMemoryManagers(); - List<MemoryManagerMXBean> result = new ArrayList<MemoryManagerMXBean>(mgrs.length); - for (MemoryManagerMXBean m : mgrs) { - result.add(m); - } - return result; - } - - public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() { - MemoryManagerMXBean[] mgrs = MemoryImpl.getMemoryManagers(); - List<GarbageCollectorMXBean> result = new ArrayList<GarbageCollectorMXBean>(mgrs.length); - for (MemoryManagerMXBean m : mgrs) { - if (GarbageCollectorMXBean.class.isInstance(m)) { - result.add(GarbageCollectorMXBean.class.cast(m)); - } - } - return result; - } - - public static PlatformLoggingMXBean getPlatformLoggingMXBean() { - if (LoggingSupport.isAvailable()) { - return PlatformLoggingImpl.instance; - } else { - return null; - } - } - - // The logging MXBean object is an instance of - // PlatformLoggingMXBean and java.util.logging.LoggingMXBean - // but it can't directly implement two MXBean interfaces - // as a compliant MXBean implements exactly one MXBean interface, - // or if it implements one interface that is a subinterface of - // all the others; otherwise, it is a non-compliant MXBean - // and MBeanServer will throw NotCompliantMBeanException. - // See the Definition of an MXBean section in javax.management.MXBean spec. - // - // To create a compliant logging MXBean, define a LoggingMXBean interface - // that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean - interface LoggingMXBean - extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean { - } - - static class PlatformLoggingImpl implements LoggingMXBean - { - final static PlatformLoggingMXBean instance = new PlatformLoggingImpl(); - final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging"; - - private volatile ObjectName objname; // created lazily - @Override - public ObjectName getObjectName() { - ObjectName result = objname; - if (result == null) { - synchronized (this) { - result = objname; - if (result == null) { - result = Util.newObjectName(LOGGING_MXBEAN_NAME); - objname = result; - } - } - } - return result; - } - - @Override - public java.util.List<String> getLoggerNames() { - return LoggingSupport.getLoggerNames(); - } - - @Override - public String getLoggerLevel(String loggerName) { - return LoggingSupport.getLoggerLevel(loggerName); - } - - @Override - public void setLoggerLevel(String loggerName, String levelName) { - LoggingSupport.setLoggerLevel(loggerName, levelName); - } - - @Override - public String getParentLoggerName(String loggerName) { - return LoggingSupport.getParentLoggerName(loggerName); - } - } - - private static List<BufferPoolMXBean> bufferPools = null; - public static synchronized List<BufferPoolMXBean> getBufferPoolMXBeans() { - if (bufferPools == null) { - bufferPools = new ArrayList<>(2); - bufferPools.add(createBufferPoolMXBean(sun.misc.SharedSecrets.getJavaNioAccess() - .getDirectBufferPool())); - bufferPools.add(createBufferPoolMXBean(sun.nio.ch.FileChannelImpl - .getMappedBufferPool())); - } - return bufferPools; - } - - private final static String BUFFER_POOL_MXBEAN_NAME = "java.nio:type=BufferPool"; - - /** - * Creates management interface for the given buffer pool. - */ - private static BufferPoolMXBean - createBufferPoolMXBean(final sun.misc.JavaNioAccess.BufferPool pool) - { - return new BufferPoolMXBean() { - private volatile ObjectName objname; // created lazily - @Override - public ObjectName getObjectName() { - ObjectName result = objname; - if (result == null) { - synchronized (this) { - result = objname; - if (result == null) { - result = Util.newObjectName(BUFFER_POOL_MXBEAN_NAME + - ",name=" + pool.getName()); - objname = result; - } - } - } - return result; - } - @Override - public String getName() { - return pool.getName(); - } - @Override - public long getCount() { - return pool.getCount(); - } - @Override - public long getTotalCapacity() { - return pool.getTotalCapacity(); - } - @Override - public long getMemoryUsed() { - return pool.getMemoryUsed(); - } - }; - } - - /** - * Registers a given MBean if not registered in the MBeanServer; - * otherwise, just return. - */ - private static void addMBean(MBeanServer mbs, Object mbean, String mbeanName) { - try { - final ObjectName objName = Util.newObjectName(mbeanName); - - // inner class requires these fields to be final - final MBeanServer mbs0 = mbs; - final Object mbean0 = mbean; - AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { - public Void run() throws MBeanRegistrationException, - NotCompliantMBeanException { - try { - mbs0.registerMBean(mbean0, objName); - return null; - } catch (InstanceAlreadyExistsException e) { - // if an instance with the object name exists in - // the MBeanServer ignore the exception - } - return null; - } - }); - } catch (PrivilegedActionException e) { - throw Util.newException(e.getException()); - } - } - - static void registerInternalMBeans(MBeanServer mbs) { - } - - static void unregisterInternalMBeans(MBeanServer mbs) { - } - - static { - jvm = new VMManagementImpl(); - } - - public static boolean isThreadSuspended(int state) { - return ((state & JMM_THREAD_STATE_FLAG_SUSPENDED) != 0); - } - - public static boolean isThreadRunningNative(int state) { - return ((state & JMM_THREAD_STATE_FLAG_NATIVE) != 0); - } - - public static Thread.State toThreadState(int state) { - // suspended and native bits may be set in state - int threadStatus = state & ~JMM_THREAD_STATE_FLAG_MASK; - return sun.misc.VM.toThreadState(threadStatus); - } - - // These values are defined in jmm.h - private static final int JMM_THREAD_STATE_FLAG_MASK = 0xFFF00000; - private static final int JMM_THREAD_STATE_FLAG_SUSPENDED = 0x00100000; - private static final int JMM_THREAD_STATE_FLAG_NATIVE = 0x00400000; - -} diff --git a/openjdk/sun/management/VMManagementImpl.java b/openjdk/sun/management/VMManagementImpl.java deleted file mode 100644 index 351cf435..00000000 --- a/openjdk/sun/management/VMManagementImpl.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.management; - -import sun.misc.Perf; -import sun.management.counter.*; -import java.nio.ByteBuffer; -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.List; -import java.util.Arrays; -import java.util.Collections; -import java.security.AccessController; -import java.security.PrivilegedAction; -import sun.security.action.GetPropertyAction; - -/** - * Implementation of VMManagement interface that accesses the management - * attributes and operations locally within the same Java virtual - * machine. - */ -class VMManagementImpl implements VMManagement { - - private static String version = "1.2"; - - private static boolean compTimeMonitoringSupport; - private static boolean threadContentionMonitoringSupport; - private static boolean currentThreadCpuTimeSupport; - private static boolean otherThreadCpuTimeSupport; - private static boolean bootClassPathSupport; - private static boolean objectMonitorUsageSupport; - private static boolean synchronizerUsageSupport; - private static boolean threadAllocatedMemorySupport; - private static boolean gcNotificationSupport; - - // Optional supports - public boolean isCompilationTimeMonitoringSupported() { - return compTimeMonitoringSupport; - } - - public boolean isThreadContentionMonitoringSupported() { - return threadContentionMonitoringSupport; - } - - public boolean isCurrentThreadCpuTimeSupported() { - return currentThreadCpuTimeSupport; - } - - public boolean isOtherThreadCpuTimeSupported() { - return otherThreadCpuTimeSupport; - } - - public boolean isBootClassPathSupported() { - return bootClassPathSupport; - } - - public boolean isObjectMonitorUsageSupported() { - return objectMonitorUsageSupport; - } - - public boolean isSynchronizerUsageSupported() { - return synchronizerUsageSupport; - } - - public boolean isThreadAllocatedMemorySupported() { - return threadAllocatedMemorySupport; - } - - public boolean isGcNotificationSupported() { - return gcNotificationSupport; - } - - public boolean isThreadContentionMonitoringEnabled() { - return false; - } - - public boolean isThreadCpuTimeEnabled() { - return false; - } - - public boolean isThreadAllocatedMemoryEnabled() { - return false; - } - - // Class Loading Subsystem - public int getLoadedClassCount() { - long count = getTotalClassCount() - getUnloadedClassCount(); - return (int) count; - } - public long getTotalClassCount() { - throw new Error("Not implemented"); - } - public long getUnloadedClassCount() { - throw new Error("Not implemented"); - } - - public boolean getVerboseClass() { - return false; - } - - // Memory Subsystem - public boolean getVerboseGC() { - return false; - } - - // Runtime Subsystem - public String getManagementVersion() { - return version; - } - - public String getVmId() { - int pid = getProcessId(); - String hostname = "localhost"; - try { - hostname = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - // ignore - } - - return pid + "@" + hostname; - } - private int getProcessId() { - return cli.System.Diagnostics.Process.GetCurrentProcess().get_Id(); - } - - public String getVmName() { - return System.getProperty("java.vm.name"); - } - - public String getVmVendor() { - return System.getProperty("java.vm.vendor"); - } - public String getVmVersion() { - return System.getProperty("java.vm.version"); - } - public String getVmSpecName() { - return System.getProperty("java.vm.specification.name"); - } - public String getVmSpecVendor() { - return System.getProperty("java.vm.specification.vendor"); - } - public String getVmSpecVersion() { - return System.getProperty("java.vm.specification.version"); - } - public String getClassPath() { - return System.getProperty("java.class.path"); - } - public String getLibraryPath() { - return System.getProperty("java.library.path"); - } - - public String getBootClassPath( ) { - PrivilegedAction<String> pa - = new GetPropertyAction("sun.boot.class.path"); - String result = AccessController.doPrivileged(pa); - return result; - } - - private List<String> vmArgs = null; - public synchronized List<String> getVmArguments() { - if (vmArgs == null) { - String[] args = getVmArguments0(); - List<String> l = ((args != null && args.length != 0) ? Arrays.asList(args) : - Collections.<String>emptyList()); - vmArgs = Collections.unmodifiableList(l); - } - return vmArgs; - } - public String[] getVmArguments0() { - return new String[0]; - } - - public long getStartupTime() { - return (long)(cli.System.Diagnostics.Process.GetCurrentProcess().get_StartTime().ToUniversalTime().Subtract(new cli.System.DateTime(1970, 1, 1))).get_TotalMilliseconds(); - } - public int getAvailableProcessors() { - return cli.System.Environment.get_ProcessorCount(); - } - - // Compilation Subsystem - public String getCompilerName() { - String name = AccessController.doPrivileged( - new PrivilegedAction<String>() { - public String run() { - return System.getProperty("sun.management.compiler"); - } - }); - return name; - } - public long getTotalCompileTime() { - throw new Error("Not implemented"); - } - - // Thread Subsystem - public long getTotalThreadCount() { - throw new Error("Not implemented"); - } - public int getLiveThreadCount() { - throw new Error("Not implemented"); - } - public int getPeakThreadCount() { - throw new Error("Not implemented"); - } - public int getDaemonThreadCount() { - throw new Error("Not implemented"); - } - - // Operating System - public String getOsName() { - return System.getProperty("os.name"); - } - public String getOsArch() { - return System.getProperty("os.arch"); - } - public String getOsVersion() { - return System.getProperty("os.version"); - } - - // Hotspot-specific runtime support - public long getSafepointCount() { - throw new Error("Not implemented"); - } - public long getTotalSafepointTime() { - throw new Error("Not implemented"); - } - public long getSafepointSyncTime() { - throw new Error("Not implemented"); - } - public long getTotalApplicationNonStoppedTime() { - throw new Error("Not implemented"); - } - - public long getLoadedClassSize() { - throw new Error("Not implemented"); - } - public long getUnloadedClassSize() { - throw new Error("Not implemented"); - } - public long getClassLoadingTime() { - throw new Error("Not implemented"); - } - public long getMethodDataSize() { - throw new Error("Not implemented"); - } - public long getInitializedClassCount() { - throw new Error("Not implemented"); - } - public long getClassInitializationTime() { - throw new Error("Not implemented"); - } - public long getClassVerificationTime() { - throw new Error("Not implemented"); - } - - public List<Counter> getInternalCounters(String pattern) { - return Collections.emptyList(); - } -} diff --git a/openjdk/sun/misc/FileURLMapper.java b/openjdk/sun/misc/FileURLMapper.java deleted file mode 100644 index 3fd43e4f..00000000 --- a/openjdk/sun/misc/FileURLMapper.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2002, 2003, 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. - */ - -/*IKVM*/ -/* - * Modified for IKVM by Jeroen Frijters on May 22, 2007. - * - * This is a merged version of the Windows & Solaris platform specific versions. - * Since the IKVM class library binary can be used both on Windows and on *nix, - * I've merged the platform specific classes into a generic class that at - * runtime determines if it runs on Windows or not. - * -/*IKVM*/ - -package sun.misc; - -import java.net.URL; -import java.io.File; -import sun.net.www.ParseUtil; - -/** - * Platform specific handling for file: URLs . In particular deals - * with network paths mapping them to UNCs. - * - * @author Michael McMahon - * @version 1.10, 07/05/05 - */ - -public class FileURLMapper { - private static final boolean runningOnWindows = cli.System.Environment.get_OSVersion().ToString().indexOf("Unix") == -1; - URL url; - String file; - - public FileURLMapper (URL url) { - this.url = url; - } - - /** - * @returns the platform specific path corresponding to the URL, and in particular - * returns a UNC when the authority contains a hostname - */ - - public String getPath () { - if (file != null) { - return file; - } - if (runningOnWindows) { - String host = url.getHost(); - if (host != null && !host.equals("") && - !"localhost".equalsIgnoreCase(host)) { - String rest = url.getFile(); - String s = host + ParseUtil.decode (url.getFile()); - file = "\\\\"+ s.replace('/', '\\'); - return file; - } - String path = url.getFile().replace('/', '\\'); - file = ParseUtil.decode(path); - return file; - } else { - String host = url.getHost(); - if (host == null || "".equals(host) || "localhost".equalsIgnoreCase (host)) { - file = url.getFile(); - file = ParseUtil.decode (file); - } - return file; - } - } - - public boolean exists() { - String path = getPath(); - if (path == null) { - return false; - } - File f = new File (path); - return f.exists(); - } -} diff --git a/openjdk/sun/misc/IoTrace.java b/openjdk/sun/misc/IoTrace.java deleted file mode 100644 index ab15ed16..00000000 --- a/openjdk/sun/misc/IoTrace.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; - -import java.net.InetAddress; - -/** - * Utility class used to identify trace points for I/O calls. - * <p> - * To use this class, a diagnostic tool must redefine this class with a version - * that contains calls to the the diagnostic tool. This implementation will then - * receive callbacks when file and socket operations are performed. The reason - * for requiring a redefine of the class is to avoid any overhead caused by the - * instrumentation. - * <p> - * The xxBegin() methods return a "context". This can be any Object. This - * context will be passed to the corresponding xxEnd() method. This way, an - * implementation can correlate the beginning of an operation with the end. - * <p> - * It is possible for a xxEnd() method to be called with a null handle. This - * happens if tracing was started between the call to xxBegin() and xxEnd(), in - * which case xxBegin() would not have been called. It is the implementation's - * responsibility to not throw an exception in this case. - * <p> - * Only blocking I/O operations are identified with this facility. - * <p> - * <b>Warning</b> - * <p> - * These methods are called from sensitive points in the I/O subsystem. Great - * care must be taken to not interfere with ongoing operations or cause - * deadlocks. In particular: - * <ul> - * <li>Implementations must not throw exceptions since this will cause - * disruptions to the I/O operations. - * <li>Implementations must not do I/O operations since this will lead to an - * endless loop. - * <li>Since the hooks may be called while holding low-level locks in the I/O - * subsystem, implementations must be careful with synchronization or - * interaction with other threads to avoid deadlocks in the VM. - * </ul> - */ -public final class IoTrace { - private IoTrace() { - } - - /** - * Called before data is read from a socket. - * - * @return a context object - */ - public static Object socketReadBegin() { - return null; - } - - /** - * Called after data is read from the socket. - * - * @param context - * the context returned by the previous call to socketReadBegin() - * @param address - * the remote address the socket is bound to - * @param port - * the remote port the socket is bound to - * @param timeout - * the SO_TIMEOUT value of the socket (in milliseconds) or 0 if - * there is no timeout set - * @param bytesRead - * the number of bytes read from the socket, 0 if there was an - * error reading from the socket - */ - public static void socketReadEnd(Object context, InetAddress address, int port, - int timeout, long bytesRead) { - } - - /** - * Called before data is written to a socket. - * - * @return a context object - */ - public static Object socketWriteBegin() { - return null; - } - - /** - * Called after data is written to a socket. - * - * @param context - * the context returned by the previous call to - * socketWriteBegin() - * @param address - * the remote address the socket is bound to - * @param port - * the remote port the socket is bound to - * @param bytesWritten - * the number of bytes written to the socket, 0 if there was an - * error writing to the socket - */ - public static void socketWriteEnd(Object context, InetAddress address, int port, - long bytesWritten) { - } - - /** - * Called before data is read from a file. - * - * @param path - * the path of the file - * @return a context object - */ - public static Object fileReadBegin(String path) { - return null; - } - - /** - * Called after data is read from a file. - * - * @param context - * the context returned by the previous call to fileReadBegin() - * @param bytesRead - * the number of bytes written to the file, 0 if there was an - * error writing to the file - */ - public static void fileReadEnd(Object context, long bytesRead) { - } - - /** - * Called before data is written to a file. - * - * @param path - * the path of the file - * @return a context object - */ - public static Object fileWriteBegin(String path) { - return null; - } - - /** - * Called after data is written to a file. - * - * @param context - * the context returned by the previous call to fileReadBegin() - * @param bytesWritten - * the number of bytes written to the file, 0 if there was an - * error writing to the file - */ - public static void fileWriteEnd(Object context, long bytesWritten) { - } -} diff --git a/openjdk/sun/misc/JavaAWTAccess.java b/openjdk/sun/misc/JavaAWTAccess.java deleted file mode 100644 index 462eb9ab..00000000 --- a/openjdk/sun/misc/JavaAWTAccess.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; - -public interface JavaAWTAccess { - public Object getContext(); - public Object getExecutionContext(); - - public Object get(Object context, Object key); - public void put(Object context, Object key, Object value); - public void remove(Object context, Object key); - - // convenience methods whose context is the object returned by getContext() - public Object get(Object key); - public void put(Object key, Object value); - public void remove(Object key); - public boolean isDisposed(); - public boolean isMainAppContext(); -} diff --git a/openjdk/sun/misc/MiscHelper.java b/openjdk/sun/misc/MiscHelper.java deleted file mode 100644 index da8aae29..00000000 --- a/openjdk/sun/misc/MiscHelper.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.misc; - -import cli.System.Reflection.Assembly; -import java.io.IOException; - -class MiscHelper -{ - // map.xml replaces ExtClassLoader.getExtClassLoader() invocation in Launcher constructor with a call to this method - static Launcher.ExtClassLoader getExtClassLoader() throws IOException - { - if ("".equals(System.getProperty("java.ext.dirs")) && "".equals(System.getProperty("java.class.path"))) - { - return null; - } - return Launcher.ExtClassLoader.getExtClassLoader(); - } - - // map.xml replaces AppClassLoader.getAppClassLoader() invocation in Launcher constructor with a call to this method - static ClassLoader getAppClassLoader(ClassLoader extcl) throws IOException - { - Assembly entryAssembly = Assembly.GetEntryAssembly(); - if (entryAssembly != null) - { - ClassLoader acl = getAssemblyClassLoader(entryAssembly, extcl); - if (acl != null) - { - // assembly has a custom assembly class loader, - // that overrides the Launcher.AppClassLoader - return acl; - } - } - return Launcher.AppClassLoader.getAppClassLoader(extcl); - } - - private static native ClassLoader getAssemblyClassLoader(Assembly asm, ClassLoader extcl); -} diff --git a/openjdk/sun/misc/OSEnvironment.java b/openjdk/sun/misc/OSEnvironment.java deleted file mode 100644 index d51ac0f1..00000000 --- a/openjdk/sun/misc/OSEnvironment.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.misc; - -public class OSEnvironment -{ - public static void initialize() - { - } -} diff --git a/openjdk/sun/misc/SharedSecrets.java b/openjdk/sun/misc/SharedSecrets.java deleted file mode 100644 index 172c4c58..00000000 --- a/openjdk/sun/misc/SharedSecrets.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; - -import java.util.jar.JarFile; -import java.io.Console; -import java.security.ProtectionDomain; -import javax.security.auth.kerberos.KeyTab; - -import java.security.AccessController; - -/** A repository of "shared secrets", which are a mechanism for - calling implementation-private methods in another package without - using reflection. A package-private class implements a public - interface and provides the ability to call package-private methods - within that package; the object implementing that interface is - provided through a third package to which access is restricted. - This framework avoids the primary disadvantage of using reflection - for this purpose, namely the loss of compile-time checking. */ - -public class SharedSecrets { - private static final Unsafe unsafe = Unsafe.getUnsafe(); - private static JavaUtilJarAccess javaUtilJarAccess; - private static JavaLangAccess javaLangAccess = LangHelper.getJavaLangAccess(); - private static JavaIOAccess javaIOAccess; - private static JavaNetAccess javaNetAccess; - private static JavaNetHttpCookieAccess javaNetHttpCookieAccess; - private static JavaNioAccess javaNioAccess; - private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess; - private static JavaSecurityAccess javaSecurityAccess; - private static JavaxSecurityAuthKerberosAccess javaxSecurityAuthKerberosAccess; - private static JavaAWTAccess javaAWTAccess; - - public static JavaUtilJarAccess javaUtilJarAccess() { - if (javaUtilJarAccess == null) { - // Ensure JarFile is initialized; we know that that class - // provides the shared secret - unsafe.ensureClassInitialized(JarFile.class); - } - return javaUtilJarAccess; - } - - public static void setJavaUtilJarAccess(JavaUtilJarAccess access) { - javaUtilJarAccess = access; - } - - public static JavaLangAccess getJavaLangAccess() { - return javaLangAccess; - } - - public static void setJavaNetAccess(JavaNetAccess jna) { - javaNetAccess = jna; - } - - public static JavaNetAccess getJavaNetAccess() { - return javaNetAccess; - } - - public static void setJavaNetHttpCookieAccess(JavaNetHttpCookieAccess a) { - javaNetHttpCookieAccess = a; - } - - public static JavaNetHttpCookieAccess getJavaNetHttpCookieAccess() { - if (javaNetHttpCookieAccess == null) - unsafe.ensureClassInitialized(java.net.HttpCookie.class); - return javaNetHttpCookieAccess; - } - - public static void setJavaNioAccess(JavaNioAccess jna) { - javaNioAccess = jna; - } - - public static JavaNioAccess getJavaNioAccess() { - if (javaNioAccess == null) { - // [IKVM] OpenJDK initializes java.nio.ByteOrder here, but that doesn't work - java.nio.ByteOrder.nativeOrder(); - } - return javaNioAccess; - } - - public static void setJavaIOAccess(JavaIOAccess jia) { - javaIOAccess = jia; - } - - public static JavaIOAccess getJavaIOAccess() { - if (javaIOAccess == null) { - unsafe.ensureClassInitialized(Console.class); - } - return javaIOAccess; - } - - public static void setJavaSecurityProtectionDomainAccess - (JavaSecurityProtectionDomainAccess jspda) { - javaSecurityProtectionDomainAccess = jspda; - } - - public static JavaSecurityProtectionDomainAccess - getJavaSecurityProtectionDomainAccess() { - if (javaSecurityProtectionDomainAccess == null) - unsafe.ensureClassInitialized(ProtectionDomain.class); - return javaSecurityProtectionDomainAccess; - } - - public static void setJavaSecurityAccess(JavaSecurityAccess jsa) { - javaSecurityAccess = jsa; - } - - public static JavaSecurityAccess getJavaSecurityAccess() { - if (javaSecurityAccess == null) { - // [IKVM] OpenJDK initializes AccessController here, but that's a bug - unsafe.ensureClassInitialized(ProtectionDomain.class); - } - return javaSecurityAccess; - } - - public static void setJavaxSecurityAuthKerberosAccess - (JavaxSecurityAuthKerberosAccess jsaka) { - javaxSecurityAuthKerberosAccess = jsaka; - } - - public static JavaxSecurityAuthKerberosAccess - getJavaxSecurityAuthKerberosAccess() { - if (javaxSecurityAuthKerberosAccess == null) - unsafe.ensureClassInitialized(KeyTab.class); - return javaxSecurityAuthKerberosAccess; - } - - public static void setJavaAWTAccess(JavaAWTAccess jaa) { - javaAWTAccess = jaa; - } - - public static JavaAWTAccess getJavaAWTAccess() { - // this may return null in which case calling code needs to - // provision for. - if (javaAWTAccess == null || javaAWTAccess.getContext() == null) { - return null; - } - return javaAWTAccess; - } -} diff --git a/openjdk/sun/misc/Unsafe.java b/openjdk/sun/misc/Unsafe.java deleted file mode 100644 index df035e5c..00000000 --- a/openjdk/sun/misc/Unsafe.java +++ /dev/null @@ -1,1229 +0,0 @@ -/* - Copyright (C) 2006-2014 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.misc; - -import cli.System.Buffer; -import cli.System.IntPtr; -import cli.System.Runtime.InteropServices.Marshal; -import cli.System.Security.Permissions.SecurityAction; -import cli.System.Security.Permissions.SecurityPermissionAttribute; -import ikvm.lang.Internal; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.ReflectHelper; -import java.security.ProtectionDomain; -import java.util.ArrayList; - -public final class Unsafe -{ - public static final int INVALID_FIELD_OFFSET = -1; - public static final int ARRAY_BYTE_BASE_OFFSET = 0; - // NOTE sun.corba.Bridge actually access this field directly (via reflection), - // so the name must match the JDK name. - private static final Unsafe theUnsafe = new Unsafe(); - private static final ArrayList<Field> fields = new ArrayList<Field>(); - - private Unsafe() { } - - @sun.reflect.CallerSensitive - public static Unsafe getUnsafe() - { - if(!VM.isSystemDomainLoader(ikvm.internal.CallerID.getCallerID().getCallerClassLoader())) - { - throw new SecurityException("Unsafe"); - } - return theUnsafe; - } - - // this is the intrinsified version of objectFieldOffset(XXX.class.getDeclaredField("xxx")) - public long objectFieldOffset(Class c, String field) - { - return allocateUnsafeFieldId(ReflectHelper.createFieldAndMakeAccessible(c, field)); - } - - // NOTE we have a really lame (and slow) implementation! - public long objectFieldOffset(Field field) - { - if(Modifier.isStatic(field.getModifiers())) - { - throw new IllegalArgumentException(); - } - return allocateUnsafeFieldId(field); - } - - @Deprecated - public int fieldOffset(Field original) - { - return allocateUnsafeFieldId(original); - } - - static int allocateUnsafeFieldId(Field original) - { - Field copy = ReflectHelper.copyFieldAndMakeAccessible(original); - synchronized(fields) - { - int id = fields.size(); - fields.add(copy); - return id; - } - } - - public int arrayBaseOffset(Class c) - { - // don't change this, the Unsafe intrinsics depend on this value - return 0; - } - - public int arrayIndexScale(Class c) - { - if (c == byte[].class || c == boolean[].class) - { - return 1; - } - if (c == char[].class || c == short[].class) - { - return 2; - } - if (c == int[].class || c == float[].class) - { - return 4; - } - if (c == long[].class || c == double[].class) - { - return 8; - } - // don't change this, the Unsafe intrinsics depend on this value - return 1; - } - - static Field getField(long offset) - { - synchronized(fields) - { - return fields.get((int)offset); - } - } - - public final native boolean compareAndSwapObject(Object obj, long offset, Object expect, Object update); - - public void putObjectVolatile(Object obj, long offset, Object newValue) - { - if(obj instanceof Object[]) - { - synchronized(this) - { - ((Object[])obj)[(int)offset] = newValue; - } - } - else - { - Field field = getField(offset); - synchronized(field) - { - try - { - field.set(obj, newValue); - } - catch(IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - } - - public void putOrderedObject(Object obj, long offset, Object newValue) - { - putObjectVolatile(obj, offset, newValue); - } - - public Object getObjectVolatile(Object obj, long offset) - { - if(obj instanceof Object[]) - { - synchronized(this) - { - return ((Object[])obj)[(int)offset]; - } - } - else - { - Field field = getField(offset); - synchronized(field) - { - try - { - return field.get(obj); - } - catch(IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - } - - private static native short ReadInt16(Object obj, long offset); - private static native int ReadInt32(Object obj, long offset); - private static native long ReadInt64(Object obj, long offset); - private static native void WriteInt16(Object obj, long offset, short value); - private static native void WriteInt32(Object obj, long offset, int value); - private static native void WriteInt64(Object obj, long offset, long value); - - public final native boolean compareAndSwapInt(Object obj, long offset, int expect, int update); - - public void putIntVolatile(Object obj, long offset, int newValue) - { - if (obj instanceof cli.System.Array) - { - synchronized(this) - { - WriteInt32(obj, offset, newValue); - } - } - else - { - Field field = getField(offset); - synchronized(field) - { - try - { - field.setInt(obj, newValue); - } - catch(IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - } - - public void putOrderedInt(Object obj, long offset, int newValue) - { - putIntVolatile(obj, offset, newValue); - } - - public int getIntVolatile(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - synchronized(this) - { - return ReadInt32(obj, offset); - } - } - else - { - Field field = getField(offset); - synchronized(field) - { - try - { - return field.getInt(obj); - } - catch(IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - } - - public final native boolean compareAndSwapLong(Object obj, long offset, long expect, long update); - - public void putLongVolatile(Object obj, long offset, long newValue) - { - if (obj instanceof cli.System.Array) - { - synchronized(this) - { - WriteInt64(obj, offset, newValue); - } - } - else - { - Field field = getField(offset); - synchronized(field) - { - try - { - field.setLong(obj, newValue); - } - catch(IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - } - - public void putOrderedLong(Object obj, long offset, long newValue) - { - putLongVolatile(obj, offset, newValue); - } - - public long getLongVolatile(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - synchronized(this) - { - return ReadInt64(obj, offset); - } - } - else - { - Field field = getField(offset); - synchronized(field) - { - try - { - return field.getLong(obj); - } - catch(IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - } - - public void putBoolean(Object obj, long offset, boolean newValue) - { - if (obj instanceof cli.System.Array) - { - Buffer.SetByte((cli.System.Array)obj, (int)offset, newValue ? (byte)1 : (byte)0); - } - else - { - try - { - getField(offset).setBoolean(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putBooleanVolatile(Object obj, long offset, boolean newValue) - { - putBoolean(obj, offset, newValue); - } - - public boolean getBoolean(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return Buffer.GetByte((cli.System.Array)obj, (int)offset) != 0; - } - else - { - try - { - return getField(offset).getBoolean(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public boolean getBooleanVolatile(Object obj, long offset) - { - return getBoolean(obj, offset); - } - - public void putByte(Object obj, long offset, byte newValue) - { - if (obj instanceof cli.System.Array) - { - Buffer.SetByte((cli.System.Array)obj, (int)offset, newValue); - } - else - { - try - { - getField(offset).setByte(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putByteVolatile(Object obj, long offset, byte newValue) - { - putByte(obj, offset, newValue); - } - - public byte getByte(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return Buffer.GetByte((cli.System.Array)obj, (int)offset); - } - else - { - try - { - return getField(offset).getByte(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public byte getByteVolatile(Object obj, long offset) - { - return getByte(obj, offset); - } - - public void putChar(Object obj, long offset, char newValue) - { - if (obj instanceof cli.System.Array) - { - WriteInt16(obj, offset, (short)newValue); - } - else - { - try - { - getField(offset).setChar(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putCharVolatile(Object obj, long offset, char newValue) - { - putChar(obj, offset, newValue); - } - - public char getChar(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return (char)ReadInt16(obj, offset); - } - else - { - try - { - return getField(offset).getChar(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public char getCharVolatile(Object obj, long offset) - { - return getChar(obj, offset); - } - - public void putShort(Object obj, long offset, short newValue) - { - if (obj instanceof cli.System.Array) - { - WriteInt16(obj, offset, newValue); - } - else - { - try - { - getField(offset).setShort(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putShortVolatile(Object obj, long offset, short newValue) - { - putShort(obj, offset, newValue); - } - - public short getShort(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return ReadInt16(obj, offset); - } - else - { - try - { - return getField(offset).getShort(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public short getShortVolatile(Object obj, long offset) - { - return getShort(obj, offset); - } - - public void putInt(Object obj, long offset, int newValue) - { - if (obj instanceof cli.System.Array) - { - WriteInt32(obj, offset, newValue); - } - else - { - try - { - getField(offset).setInt(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public int getInt(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return ReadInt32(obj, offset); - } - else - { - try - { - return getField(offset).getInt(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putFloat(Object obj, long offset, float newValue) - { - if (obj instanceof cli.System.Array) - { - WriteInt32(obj, offset, Float.floatToRawIntBits(newValue)); - } - else - { - try - { - getField(offset).setFloat(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putFloatVolatile(Object obj, long offset, float newValue) - { - putFloat(obj, offset, newValue); - } - - public float getFloat(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return Float.intBitsToFloat(ReadInt32(obj, offset)); - } - else - { - try - { - return getField(offset).getFloat(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public float getFloatVolatile(Object obj, long offset) - { - return getFloat(obj, offset); - } - - public void putLong(Object obj, long offset, long newValue) - { - if (obj instanceof cli.System.Array) - { - WriteInt64(obj, offset, newValue); - } - else - { - try - { - getField(offset).setLong(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public long getLong(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return ReadInt64(obj, offset); - } - else - { - try - { - return getField(offset).getLong(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putDouble(Object obj, long offset, double newValue) - { - if (obj instanceof cli.System.Array) - { - WriteInt64(obj, offset, Double.doubleToRawLongBits(newValue)); - } - else - { - try - { - getField(offset).setDouble(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public void putDoubleVolatile(Object obj, long offset, double newValue) - { - synchronized (this) - { - putDouble(obj, offset, newValue); - } - } - - public double getDouble(Object obj, long offset) - { - if (obj instanceof cli.System.Array) - { - return Double.longBitsToDouble(ReadInt64(obj, offset)); - } - else - { - try - { - return getField(offset).getDouble(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public double getDoubleVolatile(Object obj, long offset) - { - synchronized (this) - { - return getDouble(obj, offset); - } - } - - public void putObject(Object obj, long offset, Object newValue) - { - if (obj instanceof Object[]) - { - ((Object[])obj)[(int)offset] = newValue; - } - else - { - try - { - getField(offset).set(obj, newValue); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - public Object getObject(Object obj, long offset) - { - if (obj instanceof Object[]) - { - return ((Object[])obj)[(int)offset]; - } - else - { - try - { - return getField(offset).get(obj); - } - catch (IllegalAccessException x) - { - throw (InternalError)new InternalError().initCause(x); - } - } - } - - @Deprecated - public int getInt(Object o, int offset) - { - return getInt(o, (long)offset); - } - - @Deprecated - public void putInt(Object o, int offset, int x) - { - putInt(o, (long)offset, x); - } - - @Deprecated - public Object getObject(Object o, int offset) - { - return getObject(o, (long)offset); - } - - @Deprecated - public void putObject(Object o, int offset, Object x) - { - putObject(o, (long)offset, x); - } - - @Deprecated - public boolean getBoolean(Object o, int offset) - { - return getBoolean(o, (long)offset); - } - - @Deprecated - public void putBoolean(Object o, int offset, boolean x) - { - putBoolean(o, (long)offset, x); - } - - @Deprecated - public byte getByte(Object o, int offset) - { - return getByte(o, (long)offset); - } - - @Deprecated - public void putByte(Object o, int offset, byte x) - { - putByte(o, (long)offset, x); - } - - @Deprecated - public short getShort(Object o, int offset) - { - return getShort(o, (long)offset); - } - - @Deprecated - public void putShort(Object o, int offset, short x) - { - putShort(o, (long)offset, x); - } - - @Deprecated - public char getChar(Object o, int offset) - { - return getChar(o, (long)offset); - } - - @Deprecated - public void putChar(Object o, int offset, char x) - { - putChar(o, (long)offset, x); - } - - @Deprecated - public long getLong(Object o, int offset) - { - return getLong(o, (long)offset); - } - - @Deprecated - public void putLong(Object o, int offset, long x) - { - putLong(o, (long)offset, x); - } - - @Deprecated - public float getFloat(Object o, int offset) - { - return getFloat(o, (long)offset); - } - - @Deprecated - public void putFloat(Object o, int offset, float x) - { - putFloat(o, (long)offset, x); - } - - @Deprecated - public double getDouble(Object o, int offset) - { - return getDouble(o, (long)offset); - } - - @Deprecated - public void putDouble(Object o, int offset, double x) - { - putDouble(o, (long)offset, x); - } - - public native void throwException(Throwable t); - - public native void ensureClassInitialized(Class clazz); - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, SerializationFormatter = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public native Object allocateInstance(Class clazz) throws InstantiationException; - - public int addressSize() - { - return IntPtr.get_Size(); - } - - public int pageSize() - { - return 4096; - } - - // The really unsafe methods start here. They are all have a LinkDemand for unmanaged code. - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public long allocateMemory(long bytes) - { - try - { - if (false) throw new cli.System.OutOfMemoryException(); - return Marshal.AllocHGlobal(IntPtr.op_Explicit(bytes)).ToInt64(); - } - catch (cli.System.OutOfMemoryException x) - { - throw new OutOfMemoryError(x.get_Message()); - } - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void freeMemory(long address) - { - Marshal.FreeHGlobal(IntPtr.op_Explicit(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void setMemory(long address, long bytes, byte value) - { - while (bytes-- > 0) - { - putByte(address++, value); - } - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void copyMemory(long srcAddress, long destAddress, long bytes) - { - while (bytes-- > 0) - { - putByte(destAddress++, getByte(srcAddress++)); - } - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes) - { - if (srcBase == null) - { - if (destBase instanceof byte[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (byte[])destBase, (int)destOffset, (int)bytes); - } - else if (destBase instanceof boolean[]) - { - byte[] tmp = new byte[(int)bytes]; - copyMemory(srcBase, srcOffset, tmp, 0, bytes); - copyMemory(tmp, 0, destBase, destOffset, bytes); - } - else if (destBase instanceof short[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (short[])destBase, (int)(destOffset >> 1), (int)(bytes >> 1)); - } - else if (destBase instanceof char[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (char[])destBase, (int)(destOffset >> 1), (int)(bytes >> 1)); - } - else if (destBase instanceof int[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (int[])destBase, (int)(destOffset >> 2), (int)(bytes >> 2)); - } - else if (destBase instanceof float[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (float[])destBase, (int)(destOffset >> 2), (int)(bytes >> 2)); - } - else if (destBase instanceof long[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (long[])destBase, (int)(destOffset >> 3), (int)(bytes >> 3)); - } - else if (destBase instanceof double[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy(IntPtr.op_Explicit(srcOffset), (double[])destBase, (int)(destOffset >> 3), (int)(bytes >> 3)); - } - else if (destBase == null) - { - copyMemory(srcOffset, destOffset, bytes); - } - else - { - throw new IllegalArgumentException(); - } - } - else if (srcBase instanceof cli.System.Array && destBase instanceof cli.System.Array) - { - cli.System.Buffer.BlockCopy((cli.System.Array)srcBase, (int)srcOffset, (cli.System.Array)destBase, (int)destOffset, (int)bytes); - } - else - { - if (srcBase instanceof byte[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((byte[])srcBase, (int)srcOffset, IntPtr.op_Explicit(destOffset), (int)bytes); - } - else if (srcBase instanceof boolean[]) - { - byte[] tmp = new byte[(int)bytes]; - copyMemory(srcBase, srcOffset, tmp, 0, bytes); - copyMemory(tmp, 0, destBase, destOffset, bytes); - } - else if (srcBase instanceof short[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((short[])srcBase, (int)(srcOffset >> 1), IntPtr.op_Explicit(destOffset), (int)(bytes >> 1)); - } - else if (srcBase instanceof char[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((char[])srcBase, (int)(srcOffset >> 1), IntPtr.op_Explicit(destOffset), (int)(bytes >> 1)); - } - else if (srcBase instanceof int[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((int[])srcBase, (int)(srcOffset >> 2), IntPtr.op_Explicit(destOffset), (int)(bytes >> 2)); - } - else if (srcBase instanceof float[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((float[])srcBase, (int)(srcOffset >> 2), IntPtr.op_Explicit(destOffset), (int)(bytes >> 2)); - } - else if (srcBase instanceof long[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((long[])srcBase, (int)(srcOffset >> 3), IntPtr.op_Explicit(destOffset), (int)(bytes >> 3)); - } - else if (srcBase instanceof double[]) - { - cli.System.Runtime.InteropServices.Marshal.Copy((double[])srcBase, (int)(srcOffset >> 3), IntPtr.op_Explicit(destOffset), (int)(bytes >> 3)); - } - else - { - throw new IllegalArgumentException(); - } - } - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public byte getByte(long address) - { - return cli.System.Runtime.InteropServices.Marshal.ReadByte(IntPtr.op_Explicit(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putByte(long address, byte x) - { - cli.System.Runtime.InteropServices.Marshal.WriteByte(IntPtr.op_Explicit(address), x); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public short getShort(long address) - { - return cli.System.Runtime.InteropServices.Marshal.ReadInt16(IntPtr.op_Explicit(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putShort(long address, short x) - { - cli.System.Runtime.InteropServices.Marshal.WriteInt16(IntPtr.op_Explicit(address), x); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public char getChar(long address) - { - return (char)cli.System.Runtime.InteropServices.Marshal.ReadInt16(IntPtr.op_Explicit(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putChar(long address, char x) - { - cli.System.Runtime.InteropServices.Marshal.WriteInt16(IntPtr.op_Explicit(address), (short)x); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public int getInt(long address) - { - return cli.System.Runtime.InteropServices.Marshal.ReadInt32(IntPtr.op_Explicit(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putInt(long address, int x) - { - cli.System.Runtime.InteropServices.Marshal.WriteInt32(IntPtr.op_Explicit(address), x); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public long getLong(long address) - { - return cli.System.Runtime.InteropServices.Marshal.ReadInt64(IntPtr.op_Explicit(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putLong(long address, long x) - { - cli.System.Runtime.InteropServices.Marshal.WriteInt64(IntPtr.op_Explicit(address), x); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public long getAddress(long address) - { - return cli.System.Runtime.InteropServices.Marshal.ReadIntPtr(IntPtr.op_Explicit(address)).ToInt64(); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putAddress(long address, long x) - { - cli.System.Runtime.InteropServices.Marshal.WriteIntPtr(IntPtr.op_Explicit(address), IntPtr.op_Explicit(x)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public float getFloat(long address) - { - return Float.intBitsToFloat(getInt(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putFloat(long address, float x) - { - putInt(address, Float.floatToIntBits(x)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public double getDouble(long address) - { - return Double.longBitsToDouble(getLong(address)); - } - - @SecurityPermissionAttribute.Annotation(value = SecurityAction.__Enum.LinkDemand, UnmanagedCode = true) - @cli.System.Security.SecurityCriticalAttribute.Annotation - public void putDouble(long address, double x) - { - putLong(address, Double.doubleToLongBits(x)); - } - - public int getLoadAverage(double[] loadavg, int nelems) - { - return -1; - } - - public void park(boolean isAbsolute, long time) - { - if (isAbsolute) - { - java.util.concurrent.locks.LockSupport.parkUntil(time); - } - else - { - if (time == 0) - { - time = Long.MAX_VALUE; - } - java.util.concurrent.locks.LockSupport.parkNanos(time); - } - } - - public void unpark(Object thread) - { - java.util.concurrent.locks.LockSupport.unpark((Thread)thread); - } - - public Object staticFieldBase(Field f) - { - return null; - } - - public native boolean shouldBeInitialized(Class<?> c); - - public native Class defineClass(String name, byte[] buf, int offset, int length, ClassLoader cl, ProtectionDomain pd); - - @Deprecated - @sun.reflect.CallerSensitive - public native Class defineClass(String name, byte[] b, int off, int len); - - public native Class defineAnonymousClass(Class hostClass, byte[] data, Object[] cpPatches); - - public void monitorEnter(Object o) - { - cli.System.Threading.Monitor.Enter(o); - } - - public void monitorExit(Object o) - { - cli.System.Threading.Monitor.Exit(o); - } - - public boolean tryMonitorEnter(Object o) - { - return cli.System.Threading.Monitor.TryEnter(o); - } - - public final int getAndAddInt(Object o, long offset, int delta) - { - for (;;) - { - int value = getIntVolatile(o, offset); - if (compareAndSwapInt(o, offset, value, value + delta)) - { - return value; - } - } - } - - public final long getAndAddLong(Object o, long offset, long delta) - { - for (;;) - { - long value = getLongVolatile(o, offset); - if (compareAndSwapLong(o, offset, value, value + delta)) - { - return value; - } - } - } - - public final int getAndSetInt(Object o, long offset, int newValue) - { - for (;;) - { - int value = getIntVolatile(o, offset); - if (compareAndSwapInt(o, offset, value, newValue)) - { - return value; - } - } - } - - public final long getAndSetLong(Object o, long offset, long newValue) - { - for (;;) - { - long value = getLongVolatile(o, offset); - if (compareAndSwapLong(o, offset, value, newValue)) - { - return value; - } - } - } - - public final Object getAndSetObject(Object o, long offset, Object newValue) - { - for (;;) - { - Object value = getObjectVolatile(o, offset); - if (compareAndSwapObject(o, offset, value, newValue)) - { - return value; - } - } - } - - public void loadFence() - { - cli.System.Threading.Thread.MemoryBarrier(); - } - - public void storeFence() - { - cli.System.Threading.Thread.MemoryBarrier(); - } - - public void fullFence() - { - cli.System.Threading.Thread.MemoryBarrier(); - } -} diff --git a/openjdk/sun/misc/VM.java b/openjdk/sun/misc/VM.java deleted file mode 100644 index 6cfa7fbe..00000000 --- a/openjdk/sun/misc/VM.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; - -import static java.lang.Thread.State.*; -import java.util.Properties; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class VM { - - /* The following methods used to be native methods that instruct - * the VM to selectively suspend certain threads in low-memory - * situations. They are inherently dangerous and not implementable - * on native threads. We removed them in JDK 1.2. The skeletons - * remain so that existing applications that use these methods - * will still work. - */ - private static boolean suspended = false; - - /** @deprecated */ - @Deprecated - public static boolean threadsSuspended() { - return suspended; - } - - public static boolean allowThreadSuspension(ThreadGroup g, boolean b) { - return g.allowThreadSuspension(b); - } - - /** @deprecated */ - @Deprecated - public static boolean suspendThreads() { - suspended = true; - return true; - } - - // Causes any suspended threadgroups to be resumed. - /** @deprecated */ - @Deprecated - public static void unsuspendThreads() { - suspended = false; - } - - // Causes threadgroups no longer marked suspendable to be resumed. - /** @deprecated */ - @Deprecated - public static void unsuspendSomeThreads() { - } - - /* Deprecated fields and methods -- Memory advice not supported in 1.2 */ - - /** @deprecated */ - @Deprecated - public static final int STATE_GREEN = 1; - - /** @deprecated */ - @Deprecated - public static final int STATE_YELLOW = 2; - - /** @deprecated */ - @Deprecated - public static final int STATE_RED = 3; - - /** @deprecated */ - @Deprecated - public static final int getState() { - return STATE_GREEN; - } - - /** @deprecated */ - @Deprecated - public static void registerVMNotification(VMNotification n) { } - - /** @deprecated */ - @Deprecated - public static void asChange(int as_old, int as_new) { } - - /** @deprecated */ - @Deprecated - public static void asChange_otherthread(int as_old, int as_new) { } - - /* - * Not supported in 1.2 because these will have to be exported as - * JVM functions, and we are not sure we want do that. Leaving - * here so it can be easily resurrected -- just remove the // - * comments. - */ - - /** - * Resume Java profiling. All profiling data is added to any - * earlier profiling, unless <code>resetJavaProfiler</code> is - * called in between. If profiling was not started from the - * command line, <code>resumeJavaProfiler</code> will start it. - * <p> - * - * NOTE: Profiling must be enabled from the command line for a - * java.prof report to be automatically generated on exit; if not, - * writeJavaProfilerReport must be invoked to write a report. - * - * @see resetJavaProfiler - * @see writeJavaProfilerReport - */ - - // public native static void resumeJavaProfiler(); - - /** - * Suspend Java profiling. - */ - // public native static void suspendJavaProfiler(); - - /** - * Initialize Java profiling. Any accumulated profiling - * information is discarded. - */ - // public native static void resetJavaProfiler(); - - /** - * Write the current profiling contents to the file "java.prof". - * If the file already exists, it will be overwritten. - */ - // public native static void writeJavaProfilerReport(); - - private static volatile boolean booted = false; - - static { - // [IKVM] force System properties initialization ("booting") - System.lineSeparator(); - } - - // Invoked by by System.initializeSystemClass just before returning. - // Subsystems that are invoked during initialization can check this - // property in order to avoid doing things that should wait until the - // application class loader has been set up. - // - // [IKVM] The above isn't applicable. We only use the booted flag - // for the system properties (this is required because the system properties - // use java.util.Hashtable (via java.util.Properties) and it relies on - // the booted flag to determine whether it is safe to query the system - // properties). - public static void booted() { - booted = true; - } - - public static boolean isBooted() { - return booted; - } - - // Returns the maximum amount of allocatable direct buffer memory. - // The directMemory variable is initialized during system initialization - // in the saveAndRemoveProperties method. - // - public static long maxDirectMemory() { - // we don't support -XX:MaxDirectMemorySize - return Long.MAX_VALUE; - } - - // User-controllable flag that determines if direct buffers should be page - // aligned. The "-XX:+PageAlignDirectMemory" option can be used to force - // buffers, allocated by ByteBuffer.allocateDirect, to be page aligned. - private static boolean pageAlignDirectMemory; - - // Returns {@code true} if the direct buffers should be page aligned. This - // variable is initialized by saveAndRemoveProperties. - public static boolean isDirectMemoryPageAligned() { - return pageAlignDirectMemory; - } - - // A user-settable boolean to determine whether ClassLoader.loadClass should - // accept array syntax. This value may be changed during VM initialization - // via the system property "sun.lang.ClassLoader.allowArraySyntax". - // - // The default for 1.5 is "true", array syntax is allowed. In 1.6, the - // default will be "false". The presence of this system property to - // control array syntax allows applications the ability to preview this new - // behaviour. - // - private static boolean defaultAllowArraySyntax = false; - private static boolean allowArraySyntax = defaultAllowArraySyntax; - - // The allowArraySyntax boolean is initialized during system initialization - // in the saveAndRemoveProperties method. - // - // It is initialized based on the value of the system property - // "sun.lang.ClassLoader.allowArraySyntax". If the system property is not - // provided, the default for 1.5 is "true". In 1.6, the default will be - // "false". If the system property is provided, then the value of - // allowArraySyntax will be equal to "true" if Boolean.parseBoolean() - // returns "true". Otherwise, the field will be set to "false". - // - public static boolean allowArraySyntax() { - return allowArraySyntax; - } - - /** - * Returns the system property of the specified key saved at - * system initialization time. This method should only be used - * for the system properties that are not changed during runtime. - * It accesses a private copy of the system properties so - * that user's locking of the system properties object will not - * cause the library to deadlock. - * - * Note that the saved system properties do not include - * the ones set by sun.misc.Version.init(). - * - */ - public static String getSavedProperty(String key) { - if (Lazy.savedProps.isEmpty()) - throw new IllegalStateException("Should be non-empty if initialized"); - - return Lazy.savedProps.getProperty(key); - } - - // TODO: the Property Management needs to be refactored and - // the appropriate prop keys need to be accessible to the - // calling classes to avoid duplication of keys. - static final class Lazy { - static final Properties savedProps = new Properties(); - } - - // Save a private copy of the system properties and remove - // the system properties that are not intended for public access. - // - // This method can only be invoked during system initialization. - public static void saveAndRemoveProperties(Properties props) { - if (booted) - throw new IllegalStateException("System initialization has completed"); - - Lazy.savedProps.putAll(props); - - // Set the maximum amount of direct memory. This value is controlled - // by the vm option -XX:MaxDirectMemorySize=<size>. - // The maximum amount of allocatable direct buffer memory (in bytes) - // from the system property sun.nio.MaxDirectMemorySize set by the VM. - // The system property will be removed. - String s = (String)props.remove("sun.nio.MaxDirectMemorySize"); - // [IKVM] we don't support the -XX:MaxDirectMemorySize=<size> option. - - // Check if direct buffers should be page aligned - s = (String)props.remove("sun.nio.PageAlignDirectMemory"); - if ("true".equals(s)) - pageAlignDirectMemory = true; - - // Set a boolean to determine whether ClassLoader.loadClass accepts - // array syntax. This value is controlled by the system property - // "sun.lang.ClassLoader.allowArraySyntax". - s = props.getProperty("sun.lang.ClassLoader.allowArraySyntax"); - allowArraySyntax = (s == null - ? defaultAllowArraySyntax - : Boolean.parseBoolean(s)); - - // Remove other private system properties - // used by java.lang.Integer.IntegerCache - props.remove("java.lang.Integer.IntegerCache.high"); - - // used by java.util.zip.ZipFile - props.remove("sun.zip.disableMemoryMapping"); - - // used by sun.launcher.LauncherHelper - props.remove("sun.java.launcher.diag"); - } - - // Initialize any miscellenous operating system settings that need to be - // set for the class libraries. - // - public static void initializeOSEnvironment() { - } - - /* Current count of objects pending for finalization */ - private static volatile int finalRefCount = 0; - - /* Peak count of objects pending for finalization */ - private static volatile int peakFinalRefCount = 0; - - /* - * Gets the number of objects pending for finalization. - * - * @return the number of objects pending for finalization. - */ - public static int getFinalRefCount() { - return finalRefCount; - } - - /* - * Gets the peak number of objects pending for finalization. - * - * @return the peak number of objects pending for finalization. - */ - public static int getPeakFinalRefCount() { - return peakFinalRefCount; - } - - /* - * Add <tt>n</tt> to the objects pending for finalization count. - * - * @param n an integer value to be added to the objects pending - * for finalization count - */ - public static void addFinalRefCount(int n) { - // The caller must hold lock to synchronize the update. - - finalRefCount += n; - if (finalRefCount > peakFinalRefCount) { - peakFinalRefCount = finalRefCount; - } - } - - /** - * Returns Thread.State for the given threadStatus - */ - public static Thread.State toThreadState(int threadStatus) { - if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) { - return RUNNABLE; - } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) { - return BLOCKED; - } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) { - return WAITING; - } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) { - return TIMED_WAITING; - } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) { - return TERMINATED; - } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) { - return NEW; - } else { - return RUNNABLE; - } - } - - /* The threadStatus field is set by the VM at state transition - * in the hotspot implementation. Its value is set according to - * the JVM TI specification GetThreadState function. - */ - private final static int JVMTI_THREAD_STATE_ALIVE = 0x0001; - private final static int JVMTI_THREAD_STATE_TERMINATED = 0x0002; - private final static int JVMTI_THREAD_STATE_RUNNABLE = 0x0004; - private final static int JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400; - private final static int JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010; - private final static int JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020; - - static { - initialize(); - } - private native static void initialize(); -} diff --git a/openjdk/sun/misc/Version.java b/openjdk/sun/misc/Version.java deleted file mode 100644 index 7e0f3724..00000000 --- a/openjdk/sun/misc/Version.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; -import java.io.PrintStream; - -public class Version { - - - private static final String launcher_name = - "openjdk"; - - private static final String java_version = - "1.7.0-internal"; - - private static final String java_runtime_name = - "OpenJDK Runtime Environment"; - - private static final String java_runtime_version = - "1.7.0-internal-jeroen_2012_05_22_06_05-b00"; - - static { - init(); - } - - public static void init() { - } - - private static boolean versionsInitialized = false; - private static int jvm_major_version = 0; - private static int jvm_minor_version = 0; - private static int jvm_micro_version = 0; - private static int jvm_update_version = 0; - private static int jvm_build_number = 0; - private static String jvm_special_version = null; - private static int jdk_major_version = 0; - private static int jdk_minor_version = 0; - private static int jdk_micro_version = 0; - private static int jdk_update_version = 0; - private static int jdk_build_number = 0; - private static String jdk_special_version = null; - - /** - * In case you were wondering this method is called by java -version. - * Sad that it prints to stderr; would be nicer if default printed on - * stdout. - */ - public static void print() { - print(System.err); - } - - /** - * This is the same as print except that it adds an extra line-feed - * at the end, typically used by the -showversion in the launcher - */ - public static void println() { - print(System.err); - System.err.println(); - } - - /** - * Give a stream, it will print version info on it. - */ - public static void print(PrintStream ps) { - boolean isHeadless = false; - - /* Report that we're running headless if the property is true */ - String headless = System.getProperty("java.awt.headless"); - if ( (headless != null) && (headless.equalsIgnoreCase("true")) ) { - isHeadless = true; - } - - /* First line: platform version. */ - ps.println(launcher_name + " version \"" + java_version + "\""); - - /* Second line: runtime version (ie, libraries). */ - - ps.print(java_runtime_name + " (build " + java_runtime_version); - - if (java_runtime_name.indexOf("Embedded") != -1 && isHeadless) { - // embedded builds report headless state - ps.print(", headless"); - } - ps.println(')'); - - /* Third line: JVM information. */ - String java_vm_name = System.getProperty("java.vm.name"); - String java_vm_version = System.getProperty("java.vm.version"); - String java_vm_info = System.getProperty("java.vm.info"); - ps.println(java_vm_name + " (build " + java_vm_version + ", " + - java_vm_info + ")"); - } - - - /** - * Returns the major version of the running JVM if it's 1.6 or newer - * or any RE VM build. It will return 0 if it's an internal 1.5 or - * 1.4.x build. - * - * @since 1.6 - */ - public static synchronized int jvmMajorVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jvm_major_version; - } - - /** - * Returns the minor version of the running JVM if it's 1.6 or newer - * or any RE VM build. It will return 0 if it's an internal 1.5 or - * 1.4.x build. - * @since 1.6 - */ - public static synchronized int jvmMinorVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jvm_minor_version; - } - - - /** - * Returns the micro version of the running JVM if it's 1.6 or newer - * or any RE VM build. It will return 0 if it's an internal 1.5 or - * 1.4.x build. - * @since 1.6 - */ - public static synchronized int jvmMicroVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jvm_micro_version; - } - - /** - * Returns the update release version of the running JVM if it's - * a RE build. It will return 0 if it's an internal build. - * @since 1.6 - */ - public static synchronized int jvmUpdateVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jvm_update_version; - } - - public static synchronized String jvmSpecialVersion() { - if (!versionsInitialized) { - initVersions(); - } - if (jvm_special_version == null) { - jvm_special_version = getJvmSpecialVersion(); - } - return jvm_special_version; - } - public static native String getJvmSpecialVersion(); - - /** - * Returns the build number of the running JVM if it's a RE build - * It will return 0 if it's an internal build. - * @since 1.6 - */ - public static synchronized int jvmBuildNumber() { - if (!versionsInitialized) { - initVersions(); - } - return jvm_build_number; - } - - /** - * Returns the major version of the running JDK. - * - * @since 1.6 - */ - public static synchronized int jdkMajorVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jdk_major_version; - } - - /** - * Returns the minor version of the running JDK. - * @since 1.6 - */ - public static synchronized int jdkMinorVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jdk_minor_version; - } - - /** - * Returns the micro version of the running JDK. - * @since 1.6 - */ - public static synchronized int jdkMicroVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jdk_micro_version; - } - - /** - * Returns the update release version of the running JDK if it's - * a RE build. It will return 0 if it's an internal build. - * @since 1.6 - */ - public static synchronized int jdkUpdateVersion() { - if (!versionsInitialized) { - initVersions(); - } - return jdk_update_version; - } - - public static synchronized String jdkSpecialVersion() { - if (!versionsInitialized) { - initVersions(); - } - if (jdk_special_version == null) { - jdk_special_version = getJdkSpecialVersion(); - } - return jdk_special_version; - } - public static native String getJdkSpecialVersion(); - - /** - * Returns the build number of the running JDK if it's a RE build - * It will return 0 if it's an internal build. - * @since 1.6 - */ - public static synchronized int jdkBuildNumber() { - if (!versionsInitialized) { - initVersions(); - } - return jdk_build_number; - } - - // true if JVM exports the version info including the capabilities - private static boolean jvmVersionInfoAvailable; - private static synchronized void initVersions() { - if (versionsInitialized) { - return; - } - jvmVersionInfoAvailable = getJvmVersionInfo(); - if (!jvmVersionInfoAvailable) { - // parse java.vm.version for older JVM before the - // new JVM_GetVersionInfo is added. - // valid format of the version string is: - // n.n.n[_uu[c]][-<identifer>]-bxx - CharSequence cs = System.getProperty("java.vm.version"); - if (cs.length() >= 5 && - Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' && - Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' && - Character.isDigit(cs.charAt(4))) { - jvm_major_version = Character.digit(cs.charAt(0), 10); - jvm_minor_version = Character.digit(cs.charAt(2), 10); - jvm_micro_version = Character.digit(cs.charAt(4), 10); - cs = cs.subSequence(5, cs.length()); - if (cs.charAt(0) == '_' && cs.length() >= 3 && - Character.isDigit(cs.charAt(1)) && - Character.isDigit(cs.charAt(2))) { - int nextChar = 3; - try { - String uu = cs.subSequence(1, 3).toString(); - jvm_update_version = Integer.valueOf(uu).intValue(); - if (cs.length() >= 4) { - char c = cs.charAt(3); - if (c >= 'a' && c <= 'z') { - jvm_special_version = Character.toString(c); - nextChar++; - } - } - } catch (NumberFormatException e) { - // not conforming to the naming convention - return; - } - cs = cs.subSequence(nextChar, cs.length()); - } - if (cs.charAt(0) == '-') { - // skip the first character - // valid format: <identifier>-bxx or bxx - // non-product VM will have -debug|-release appended - cs = cs.subSequence(1, cs.length()); - String[] res = cs.toString().split("-"); - for (String s : res) { - if (s.charAt(0) == 'b' && s.length() == 3 && - Character.isDigit(s.charAt(1)) && - Character.isDigit(s.charAt(2))) { - jvm_build_number = - Integer.valueOf(s.substring(1, 3)).intValue(); - break; - } - } - } - } - } - getJdkVersionInfo(); - versionsInitialized = true; - } - - // Gets the JVM version info if available and sets the jvm_*_version fields - // and its capabilities. - // - // Return false if not available which implies an old VM (Tiger or before). - private static native boolean getJvmVersionInfo(); - private static native void getJdkVersionInfo(); - -} - -// Help Emacs a little because this file doesn't end in .java. -// -// Local Variables: *** -// mode: java *** -// End: *** diff --git a/openjdk/sun/net/dns/ResolverConfigurationImpl.java b/openjdk/sun/net/dns/ResolverConfigurationImpl.java deleted file mode 100644 index 167faad9..00000000 --- a/openjdk/sun/net/dns/ResolverConfigurationImpl.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.net.dns; - -import java.util.List; -import java.util.LinkedList; -import java.util.StringTokenizer; -import java.io.IOException; -import cli.System.Net.NetworkInformation.IPAddressCollection; -import cli.System.Net.NetworkInformation.IPInterfaceProperties; -import cli.System.Net.NetworkInformation.NetworkInterface; - -/* - * An implementation of sun.net.ResolverConfiguration for Windows. - */ - -public class ResolverConfigurationImpl - extends ResolverConfiguration -{ - // Lock helds whilst loading configuration or checking - private static Object lock = new Object(); - - // Resolver options - private final Options opts; - - // Addreses have changed - private static boolean changed = false; - - // Time of last refresh. - private static long lastRefresh = -1; - - // Cache timeout (120 seconds) - should be converted into property - // or configured as preference in the future. - private static final int TIMEOUT = 120000; - - // DNS suffix list and name servers populated by native method - private static String os_searchlist; - private static String os_nameservers; - - // Cached lists - private static LinkedList searchlist; - private static LinkedList nameservers; - - // Parse string that consists of token delimited by space or commas - // and return LinkedHashMap - private LinkedList<String> stringToList(String str) { - LinkedList<String> ll = new LinkedList<>(); - - // comma and space are valid delimites - StringTokenizer st = new StringTokenizer(str, ", "); - while (st.hasMoreTokens()) { - String s = st.nextToken(); - if (!ll.contains(s)) { - ll.add(s); - } - } - return ll; - } - - // Load DNS configuration from OS - - private void loadConfig() { - assert Thread.holdsLock(lock); - - // if address have changed then DNS probably changed aswell; - // otherwise check if cached settings have expired. - // - if (changed) { - changed = false; - } else { - if (lastRefresh >= 0) { - long currTime = System.currentTimeMillis(); - if ((currTime - lastRefresh) < TIMEOUT) { - return; - } - } - } - - // load DNS configuration, update timestamp, create - // new HashMaps from the loaded configuration - // - loadDNSconfig0(); - - lastRefresh = System.currentTimeMillis(); - searchlist = stringToList(os_searchlist); - nameservers = stringToList(os_nameservers); - os_searchlist = null; // can be GC'ed - os_nameservers = null; - } - - ResolverConfigurationImpl() { - opts = new OptionsImpl(); - } - - public List<String> searchlist() { - synchronized (lock) { - loadConfig(); - - // List is mutable so return a shallow copy - return (List)searchlist.clone(); - } - } - - public List<String> nameservers() { - synchronized (lock) { - loadConfig(); - - // List is mutable so return a shallow copy - return (List)nameservers.clone(); - } - } - - public Options options() { - return opts; - } - - // --- Address Change Listener - - static class AddressChangeListener extends Thread { - public void run() { - for (;;) { - // wait for configuration to change - if (notifyAddrChange0() != 0) - return; - synchronized (lock) { - changed = true; - } - } - } - } - - - // --- Native methods -- - - static void init0() { - } - - static void loadDNSconfig0() { - String searchlist = ""; - String nameservers = ""; - for (NetworkInterface iface : NetworkInterface.GetAllNetworkInterfaces()) { - IPInterfaceProperties props = iface.GetIPProperties(); - IPAddressCollection addresses = props.get_DnsAddresses(); - for (int i = 0; i < addresses.get_Count(); i++) { - cli.System.Net.IPAddress addr = addresses.get_Item(i); - // no IPv6 support - if (addr.get_AddressFamily().Value == cli.System.Net.Sockets.AddressFamily.InterNetwork) { - nameservers = strAppend(nameservers, addr.toString()); - } - } - try { - if (false) throw new cli.System.PlatformNotSupportedException(); - searchlist = strAppend(searchlist, props.get_DnsSuffix()); - } - catch (cli.System.PlatformNotSupportedException _) { - } - } - os_searchlist = searchlist; - os_nameservers = nameservers; - } - - private static String strAppend(String s, String app) { - if (s.equals("")) { - return app; - } - if (app.equals("")) { - return s; - } - return s + " " + app; - } - - static int notifyAddrChange0() { - // TODO we could use System.Net.NetworkInformation.NetworkChange to detect changes - return -1; - } - - static { - java.security.AccessController.doPrivileged( - new sun.security.action.LoadLibraryAction("net")); - init0(); - - // start the address listener thread - AddressChangeListener thr = new AddressChangeListener(); - thr.setDaemon(true); - thr.start(); - } -} - -/** - * Implementation of {@link ResolverConfiguration.Options} - */ -class OptionsImpl extends ResolverConfiguration.Options { -} diff --git a/openjdk/sun/net/sdp/SdpSupport.java b/openjdk/sun/net/sdp/SdpSupport.java deleted file mode 100644 index 6784ab01..00000000 --- a/openjdk/sun/net/sdp/SdpSupport.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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. - */ - -package sun.net.sdp; - -import java.io.IOException; -import java.io.FileDescriptor; - - -/** - * This class defines methods for creating SDP sockets or "converting" existing - * file descriptors, referencing (unbound) TCP sockets, to SDP. - */ - -public final class SdpSupport { - - private SdpSupport() { } - - /** - * Creates a SDP socket, returning file descriptor referencing the socket. - */ - public static FileDescriptor createSocket() throws IOException { - throw new UnsupportedOperationException("SDP not supported on this platform"); - } - - /** - * Converts an existing file descriptor, that references an unbound TCP socket, - * to SDP. - */ - public static void convertSocket(FileDescriptor fd) throws IOException { - throw new UnsupportedOperationException("SDP not supported on this platform"); - } -} diff --git a/openjdk/sun/net/www/protocol/file/FileURLConnection.java b/openjdk/sun/net/www/protocol/file/FileURLConnection.java deleted file mode 100644 index 43c94b31..00000000 --- a/openjdk/sun/net/www/protocol/file/FileURLConnection.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 1995, 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. - */ - -/** - * Open an file input stream given a URL. - * @author James Gosling - * @author Steven B. Byrne - */ - -package sun.net.www.protocol.file; - -import java.net.URL; -import java.net.FileNameMap; -import java.io.*; -import java.text.Collator; -import java.security.Permission; -import sun.net.*; -import sun.net.www.*; -import java.util.*; -import java.text.SimpleDateFormat; - -import sun.security.action.GetPropertyAction; -import sun.security.action.GetIntegerAction; -import sun.security.action.GetBooleanAction; - -public class FileURLConnection extends URLConnection { - - static String CONTENT_LENGTH = "content-length"; - static String CONTENT_TYPE = "content-type"; - static String TEXT_PLAIN = "text/plain"; - static String LAST_MODIFIED = "last-modified"; - - String contentType; - InputStream is; - - File file; - String filename; - boolean isDirectory = false; - boolean exists = false; - List<String> files; - - long length = -1; - long lastModified = 0; - - protected FileURLConnection(URL u, File file) { - super(u); - this.file = file; - } - - /* - * Note: the semantics of FileURLConnection object is that the - * results of the various URLConnection calls, such as - * getContentType, getInputStream or getContentLength reflect - * whatever was true when connect was called. - */ - public void connect() throws IOException { - if (!connected) { - try { - filename = file.toString(); - isDirectory = file.isDirectory(); - if (isDirectory) { - String[] fileList = file.list(); - if (fileList == null) - throw new FileNotFoundException(filename + " exists, but is not accessible"); - files = Arrays.<String>asList(fileList); - } else { - - is = new BufferedInputStream(new FileInputStream(filename)); - - // Check if URL should be metered - boolean meteredInput = ProgressMonitor.getDefault().shouldMeterInput(url, "GET"); - if (meteredInput) { - ProgressSource pi = new ProgressSource(url, "GET", file.length()); - is = new MeteredStream(is, pi, file.length()); - } - } - } catch (IOException e) { - throw e; - } - connected = true; - } - } - - private boolean initializedHeaders = false; - - private void initializeHeaders() { - try { - connect(); - exists = file.exists(); - } catch (IOException e) { - } - if (!initializedHeaders || !exists) { - length = file.length(); - lastModified = file.lastModified(); - - if (!isDirectory) { - FileNameMap map = java.net.URLConnection.getFileNameMap(); - contentType = map.getContentTypeFor(filename); - if (contentType != null) { - properties.add(CONTENT_TYPE, contentType); - } - properties.add(CONTENT_LENGTH, String.valueOf(length)); - - /* - * Format the last-modified field into the preferred - * Internet standard - ie: fixed-length subset of that - * defined by RFC 1123 - */ - if (lastModified != 0) { - Date date = new Date(lastModified); - SimpleDateFormat fo = - new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); - fo.setTimeZone(TimeZone.getTimeZone("GMT")); - properties.add(LAST_MODIFIED, fo.format(date)); - } - } else { - properties.add(CONTENT_TYPE, TEXT_PLAIN); - } - initializedHeaders = true; - } - } - - public String getHeaderField(String name) { - initializeHeaders(); - return super.getHeaderField(name); - } - - public String getHeaderField(int n) { - initializeHeaders(); - return super.getHeaderField(n); - } - - public int getContentLength() { - initializeHeaders(); - if (length > Integer.MAX_VALUE) - return -1; - return (int) length; - } - - public long getContentLengthLong() { - initializeHeaders(); - return length; - } - - public String getHeaderFieldKey(int n) { - initializeHeaders(); - return super.getHeaderFieldKey(n); - } - - public MessageHeader getProperties() { - initializeHeaders(); - return super.getProperties(); - } - - public long getLastModified() { - initializeHeaders(); - return lastModified; - } - - public synchronized InputStream getInputStream() - throws IOException { - - int iconHeight; - int iconWidth; - - connect(); - - if (is == null) { - if (isDirectory) { - FileNameMap map = java.net.URLConnection.getFileNameMap(); - - StringBuffer buf = new StringBuffer(); - - if (files == null) { - throw new FileNotFoundException(filename); - } - - sort(files); - - for (int i = 0 ; i < files.size() ; i++) { - String fileName = files.get(i); - buf.append(fileName); - buf.append("\n"); - } - // Put it into a (default) locale-specific byte-stream. - is = new ByteArrayInputStream(buf.toString().getBytes()); - } else { - throw new FileNotFoundException(filename); - } - } - return is; - } - - // IKVM specific method (sorting moved here to delay java.text.Collator dependency) - private static void sort(List files) { - Collections.sort(files, Collator.getInstance()); - } - - Permission permission; - - /* since getOutputStream isn't supported, only read permission is - * relevant - */ - public Permission getPermission() throws IOException { - if (permission == null) { - String decodedPath = ParseUtil.decode(url.getPath()); - if (File.separatorChar == '/') { - permission = new FilePermission(decodedPath, "read"); - } else { - permission = new FilePermission( - decodedPath.replace('/',File.separatorChar), "read"); - } - } - return permission; - } -} diff --git a/openjdk/sun/net/www/protocol/file/Handler.java b/openjdk/sun/net/www/protocol/file/Handler.java deleted file mode 100644 index 88688c38..00000000 --- a/openjdk/sun/net/www/protocol/file/Handler.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.net.www.protocol.file; - -import java.net.InetAddress; -import java.net.URLConnection; -import java.net.URL; -import java.net.Proxy; -import java.net.MalformedURLException; -import java.net.URLStreamHandler; -import java.io.InputStream; -import java.io.IOException; -import sun.net.www.ParseUtil; -import java.io.File; - -/** - * Open an file input stream given a URL. - * @author James Gosling - */ -public class Handler extends URLStreamHandler { - - private String getHost(URL url) { - String host = url.getHost(); - if (host == null) - host = ""; - return host; - } - - - protected void parseURL(URL u, String spec, int start, int limit) { - /* - * Ugly backwards compatibility. Flip any file separator - * characters to be forward slashes. This is a nop on Unix - * and "fixes" win32 file paths. According to RFC 2396, - * only forward slashes may be used to represent hierarchy - * separation in a URL but previous releases unfortunately - * performed this "fixup" behavior in the file URL parsing code - * rather than forcing this to be fixed in the caller of the URL - * class where it belongs. Since backslash is an "unwise" - * character that would normally be encoded if literally intended - * as a non-seperator character the damage of veering away from the - * specification is presumably limited. - */ - super.parseURL(u, spec.replace(File.separatorChar, '/'), start, limit); - } - - public synchronized URLConnection openConnection(URL url) - throws IOException { - return openConnection(url, null); - } - - public synchronized URLConnection openConnection(URL url, Proxy p) - throws IOException { - - String path; - String file = url.getFile(); - String host = url.getHost(); - - if (ikvm.internal.Util.WINDOWS) { - path = ParseUtil.decode(file); - path = path.replace('/', '\\'); - path = path.replace('|', ':'); - } else { - path = ParseUtil.decode(url.getPath()); - } - - if ((host == null) || host.equals("") || - host.equalsIgnoreCase("localhost") || - host.equals("~")) { - return createFileURLConnection(url, new File(path)); - } - - /* - * attempt to treat this as a UNC path. See 4180841 - */ - if (ikvm.internal.Util.WINDOWS) { - path = "\\\\" + host + path; - File f = new File(path); - if (f.exists()) { - return createFileURLConnection(url, f); - } - } - - /* - * Now attempt an ftp connection. - */ - URLConnection uc; - URL newurl; - - try { - newurl = new URL("ftp", host, file + - (url.getRef() == null ? "": - "#" + url.getRef())); - if (p != null) { - uc = newurl.openConnection(p); - } else { - uc = newurl.openConnection(); - } - } catch (IOException e) { - uc = null; - } - if (uc == null) { - throw new IOException("Unable to connect to: " + - url.toExternalForm()); - } - return uc; - } - - /** - * Template method to be overriden by Java Plug-in. [stanleyh] - */ - protected URLConnection createFileURLConnection(URL url, File file) { - return new FileURLConnection(url, file); - } - - /** - * Compares the host components of two URLs. - * @param u1 the URL of the first host to compare - * @param u2 the URL of the second host to compare - * @return <tt>true</tt> if and only if they - * are equal, <tt>false</tt> otherwise. - */ - protected boolean hostsEqual(URL u1, URL u2) { - /* - * Special case for file: URLs - * per RFC 1738 no hostname is equivalent to 'localhost' - * i.e. file:///path is equal to file://localhost/path - */ - String s1 = u1.getHost(); - String s2 = u2.getHost(); - if ("localhost".equalsIgnoreCase(s1) && ( s2 == null || "".equals(s2))) - return true; - if ("localhost".equalsIgnoreCase(s2) && ( s1 == null || "".equals(s1))) - return true; - return super.hostsEqual(u1, u2); - } -} diff --git a/openjdk/sun/net/www/protocol/ikvmres/Handler.java b/openjdk/sun/net/www/protocol/ikvmres/Handler.java deleted file mode 100644 index 972ca315..00000000 --- a/openjdk/sun/net/www/protocol/ikvmres/Handler.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.net.www.protocol.ikvmres; - -public class Handler extends gnu.java.net.protocol.ikvmres.Handler -{ -} diff --git a/openjdk/sun/net/www/protocol/jar/JarFileFactory.java b/openjdk/sun/net/www/protocol/jar/JarFileFactory.java deleted file mode 100644 index af9f676f..00000000 --- a/openjdk/sun/net/www/protocol/jar/JarFileFactory.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 1999, 2006, 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. - */ - -/*IKVM*/ -/* - * Modified for IKVM by Jeroen Frijters on May 22, 2007. - * - * This is a merged version of the Windows & Solaris platform specific versions. - * Since the IKVM class library binary can be used both on Windows and on *nix, - * I've merged the platform specific classes into a generic class that at - * runtime determines if it runs on Windows or not. - * -/*IKVM*/ - -package sun.net.www.protocol.jar; - -import java.io.IOException; -import java.io.FileNotFoundException; -import java.net.URL; -import java.net.URLConnection; -import java.util.HashMap; -import java.util.jar.JarFile; -import java.security.Permission; -import sun.net.util.URLUtil; - -/* A factory for cached JAR file. This class is used to both retrieve - * and cache Jar files. - * - * @author Benjamin Renaud - * @since JDK1.2 - */ -class JarFileFactory implements URLJarFile.URLJarFileCloseController { - - /* the url to file cache */ - private static HashMap<String, JarFile> fileCache = new HashMap<String, JarFile>(); - - /* the file to url cache */ - private static HashMap<JarFile, URL> urlCache = new HashMap<JarFile, URL>(); - - URLConnection getConnection(JarFile jarFile) throws IOException { - URL u = urlCache.get(jarFile); - if (u != null) - return u.openConnection(); - - return null; - } - - public JarFile get(URL url) throws IOException { - return get(url, true); - } - - JarFile get(URL url, boolean useCaches) throws IOException { - if (ikvm.internal.Util.WINDOWS && url.getProtocol().equalsIgnoreCase("file")) { - // Deal with UNC pathnames specially. See 4180841 - - String host = url.getHost(); - if (host != null && !host.equals("") && - !host.equalsIgnoreCase("localhost")) { - - url = new URL("file", "", "//" + host + url.getPath()); - } - } - - JarFile result = null; - JarFile local_result = null; - - if (useCaches) { - synchronized (this) { - result = getCachedJarFile(url); - } - if (result == null) { - local_result = URLJarFile.getJarFile(url, this); - synchronized (this) { - result = getCachedJarFile(url); - if (result == null) { - fileCache.put(URLUtil.urlNoFragString(url), local_result); - urlCache.put(local_result, url); - result = local_result; - } else { - if (local_result != null) { - local_result.close(); - } - } - } - } - } else { - result = URLJarFile.getJarFile(url, this); - } - if (result == null) - throw new FileNotFoundException(url.toString()); - - return result; - } - - /** - * Callback method of the URLJarFileCloseController to - * indicate that the JarFile is close. This way we can - * remove the JarFile from the cache - */ - public void close(JarFile jarFile) { - URL urlRemoved = urlCache.remove(jarFile); - if( urlRemoved != null) { - fileCache.remove(URLUtil.urlNoFragString(urlRemoved)); - } - } - - private JarFile getCachedJarFile(URL url) { - JarFile result = fileCache.get(URLUtil.urlNoFragString(url)); - - /* if the JAR file is cached, the permission will always be there */ - if (result != null) { - Permission perm = getPermission(result); - if (perm != null) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - sm.checkPermission(perm); - } catch (SecurityException se) { - // fallback to checkRead/checkConnect for pre 1.2 - // security managers - if ((perm instanceof java.io.FilePermission) && - perm.getActions().indexOf("read") != -1) { - sm.checkRead(perm.getName()); - } else if ((perm instanceof - java.net.SocketPermission) && - perm.getActions().indexOf("connect") != -1) { - sm.checkConnect(url.getHost(), url.getPort()); - } else { - throw se; - } - } - } - } - } - return result; - } - - private Permission getPermission(JarFile jarFile) { - try { - URLConnection uc = (URLConnection)getConnection(jarFile); - if (uc != null) - return uc.getPermission(); - } catch (IOException ioe) { - // gulp - } - - return null; - } -} diff --git a/openjdk/sun/nio/ch/DatagramChannelImpl.java b/openjdk/sun/nio/ch/DatagramChannelImpl.java deleted file mode 100644 index 08cc5c95..00000000 --- a/openjdk/sun/nio/ch/DatagramChannelImpl.java +++ /dev/null @@ -1,1113 +0,0 @@ -/* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.*; -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.nio.channels.spi.*; -import java.util.*; -import sun.net.ResourceManager; - - -/** - * An implementation of DatagramChannels. - */ - -class DatagramChannelImpl - extends DatagramChannel - implements SelChImpl -{ - - // Used to make native read and write calls - private static NativeDispatcher nd = new SocketDispatcher(); - - // Our file descriptor - private final FileDescriptor fd; - - // fd value needed for dev/poll. This value will remain valid - // even after the value in the file descriptor object has been set to -1 - private final int fdVal; - - // The protocol family of the socket - private final ProtocolFamily family; - - // IDs of native threads doing reads and writes, for signalling - private volatile long readerThread = 0; - private volatile long writerThread = 0; - - // Cached InetAddress and port for unconnected DatagramChannels - // used by receive0 - private InetAddress cachedSenderInetAddress; - private int cachedSenderPort; - - // Lock held by current reading or connecting thread - private final Object readLock = new Object(); - - // Lock held by current writing or connecting thread - private final Object writeLock = new Object(); - - // Lock held by any thread that modifies the state fields declared below - // DO NOT invoke a blocking I/O operation while holding this lock! - private final Object stateLock = new Object(); - - // -- The following fields are protected by stateLock - - // State (does not necessarily increase monotonically) - private static final int ST_UNINITIALIZED = -1; - private static final int ST_UNCONNECTED = 0; - private static final int ST_CONNECTED = 1; - private static final int ST_KILLED = 2; - private int state = ST_UNINITIALIZED; - - // Binding - private InetSocketAddress localAddress; - private InetSocketAddress remoteAddress; - - // Our socket adaptor, if any - private DatagramSocket socket; - - // Multicast support - private MembershipRegistry registry; - - // set true when socket is bound and SO_REUSEADDRESS is emulated - private boolean reuseAddressEmulated; - - // set true/false when socket is already bound and SO_REUSEADDR is emulated - private boolean isReuseAddress; - - // -- End of fields protected by stateLock - - - public DatagramChannelImpl(SelectorProvider sp) - throws IOException - { - super(sp); - ResourceManager.beforeUdpCreate(); - try { - this.family = Net.isIPv6Available() ? - StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; - this.fd = Net.socket(family, false); - this.fdVal = IOUtil.fdVal(fd); - this.state = ST_UNCONNECTED; - } catch (IOException ioe) { - ResourceManager.afterUdpClose(); - throw ioe; - } - } - - public DatagramChannelImpl(SelectorProvider sp, ProtocolFamily family) - throws IOException - { - super(sp); - if ((family != StandardProtocolFamily.INET) && - (family != StandardProtocolFamily.INET6)) - { - if (family == null) - throw new NullPointerException("'family' is null"); - else - throw new UnsupportedOperationException("Protocol family not supported"); - } - if (family == StandardProtocolFamily.INET6) { - if (!Net.isIPv6Available()) { - throw new UnsupportedOperationException("IPv6 not available"); - } - } - this.family = family; - this.fd = Net.socket(family, false); - this.fdVal = IOUtil.fdVal(fd); - this.state = ST_UNCONNECTED; - } - - public DatagramChannelImpl(SelectorProvider sp, FileDescriptor fd) - throws IOException - { - super(sp); - this.family = Net.isIPv6Available() ? - StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; - this.fd = fd; - this.fdVal = IOUtil.fdVal(fd); - this.state = ST_UNCONNECTED; - this.localAddress = Net.localAddress(fd); - } - - public DatagramSocket socket() { - synchronized (stateLock) { - if (socket == null) - socket = DatagramSocketAdaptor.create(this); - return socket; - } - } - - @Override - public SocketAddress getLocalAddress() throws IOException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - return Net.getRevealedLocalAddress(localAddress); - } - } - - @Override - public SocketAddress getRemoteAddress() throws IOException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - return remoteAddress; - } - } - - @Override - public <T> DatagramChannel setOption(SocketOption<T> name, T value) - throws IOException - { - if (name == null) - throw new NullPointerException(); - if (!supportedOptions().contains(name)) - throw new UnsupportedOperationException("'" + name + "' not supported"); - - synchronized (stateLock) { - ensureOpen(); - - if (name == StandardSocketOptions.IP_TOS) { - // IPv4 only; no-op for IPv6 - if (family == StandardProtocolFamily.INET) { - Net.setSocketOption(fd, family, name, value); - } - return this; - } - - if (name == StandardSocketOptions.IP_MULTICAST_TTL || - name == StandardSocketOptions.IP_MULTICAST_LOOP) - { - // options are protocol dependent - Net.setSocketOption(fd, family, name, value); - return this; - } - - if (name == StandardSocketOptions.IP_MULTICAST_IF) { - if (value == null) - throw new IllegalArgumentException("Cannot set IP_MULTICAST_IF to 'null'"); - NetworkInterface interf = (NetworkInterface)value; - if (family == StandardProtocolFamily.INET6) { - int index = interf.getIndex(); - if (index == -1) - throw new IOException("Network interface cannot be identified"); - Net.setInterface6(fd, index); - } else { - // need IPv4 address to identify interface - Inet4Address target = Net.anyInet4Address(interf); - if (target == null) - throw new IOException("Network interface not configured for IPv4"); - int targetAddress = Net.inet4AsInt(target); - Net.setInterface4(fd, targetAddress); - } - return this; - } - if (name == StandardSocketOptions.SO_REUSEADDR && - Net.useExclusiveBind() && localAddress != null) - { - reuseAddressEmulated = true; - this.isReuseAddress = (Boolean)value; - } - - // remaining options don't need any special handling - Net.setSocketOption(fd, Net.UNSPEC, name, value); - return this; - } - } - - @Override - @SuppressWarnings("unchecked") - public <T> T getOption(SocketOption<T> name) - throws IOException - { - if (name == null) - throw new NullPointerException(); - if (!supportedOptions().contains(name)) - throw new UnsupportedOperationException("'" + name + "' not supported"); - - synchronized (stateLock) { - ensureOpen(); - - if (name == StandardSocketOptions.IP_TOS) { - // IPv4 only; always return 0 on IPv6 - if (family == StandardProtocolFamily.INET) { - return (T) Net.getSocketOption(fd, family, name); - } else { - return (T) Integer.valueOf(0); - } - } - - if (name == StandardSocketOptions.IP_MULTICAST_TTL || - name == StandardSocketOptions.IP_MULTICAST_LOOP) - { - return (T) Net.getSocketOption(fd, family, name); - } - - if (name == StandardSocketOptions.IP_MULTICAST_IF) { - if (family == StandardProtocolFamily.INET) { - int address = Net.getInterface4(fd); - if (address == 0) - return null; // default interface - - InetAddress ia = Net.inet4FromInt(address); - NetworkInterface ni = NetworkInterface.getByInetAddress(ia); - if (ni == null) - throw new IOException("Unable to map address to interface"); - return (T) ni; - } else { - int index = Net.getInterface6(fd); - if (index == 0) - return null; // default interface - - NetworkInterface ni = NetworkInterface.getByIndex(index); - if (ni == null) - throw new IOException("Unable to map index to interface"); - return (T) ni; - } - } - - if (name == StandardSocketOptions.SO_REUSEADDR && - reuseAddressEmulated) - { - return (T)Boolean.valueOf(isReuseAddress); - } - - // no special handling - return (T) Net.getSocketOption(fd, Net.UNSPEC, name); - } - } - - private static class DefaultOptionsHolder { - static final Set<SocketOption<?>> defaultOptions = defaultOptions(); - - private static Set<SocketOption<?>> defaultOptions() { - HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(8); - set.add(StandardSocketOptions.SO_SNDBUF); - set.add(StandardSocketOptions.SO_RCVBUF); - set.add(StandardSocketOptions.SO_REUSEADDR); - set.add(StandardSocketOptions.SO_BROADCAST); - set.add(StandardSocketOptions.IP_TOS); - set.add(StandardSocketOptions.IP_MULTICAST_IF); - set.add(StandardSocketOptions.IP_MULTICAST_TTL); - set.add(StandardSocketOptions.IP_MULTICAST_LOOP); - return Collections.unmodifiableSet(set); - } - } - - @Override - public final Set<SocketOption<?>> supportedOptions() { - return DefaultOptionsHolder.defaultOptions; - } - - private void ensureOpen() throws ClosedChannelException { - if (!isOpen()) - throw new ClosedChannelException(); - } - - SocketAddress sender; // Set by receive0 (## ugh) - - public SocketAddress receive(ByteBuffer dst) throws IOException { - if (dst.isReadOnly()) - throw new IllegalArgumentException("Read-only buffer"); - if (dst == null) - throw new NullPointerException(); - synchronized (readLock) { - ensureOpen(); - // Socket was not bound before attempting receive - if (localAddress() == null) - bind(null); - int n = 0; - ByteBuffer bb = null; - try { - begin(); - if (!isOpen()) - return null; - SecurityManager security = System.getSecurityManager(); - readerThread = NativeThread.current(); - if (isConnected() || (security == null)) { - do { - n = receive(fd, dst); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - if (n == IOStatus.UNAVAILABLE) - return null; - } else { - bb = ByteBuffer.allocate(dst.remaining()); - for (;;) { - do { - n = receive(fd, bb); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - if (n == IOStatus.UNAVAILABLE) - return null; - InetSocketAddress isa = (InetSocketAddress)sender; - try { - security.checkAccept( - isa.getAddress().getHostAddress(), - isa.getPort()); - } catch (SecurityException se) { - // Ignore packet - bb.clear(); - n = 0; - continue; - } - bb.flip(); - dst.put(bb); - break; - } - } - return sender; - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - private int receive(FileDescriptor fd, ByteBuffer dst) - throws IOException - { - int pos = dst.position(); - int lim = dst.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - if (dst.hasArray() && rem > 0) - return receiveIntoManagedBuffer(fd, dst, rem, pos); - - // Substitute a managed buffer. If the supplied buffer is empty - // we must instead use a nonempty buffer, otherwise the call - // will not block waiting for a datagram on some platforms. - int newSize = Math.max(rem, 1); - ByteBuffer bb = ByteBuffer.allocate(newSize); - try { - int n = receiveIntoManagedBuffer(fd, bb, newSize, 0); - bb.flip(); - if (n > 0 && rem > 0) - dst.put(bb); - return n; - } finally { - } - } - - private int receiveIntoManagedBuffer(FileDescriptor fd, ByteBuffer bb, - int rem, int pos) - throws IOException - { - int n = receive0(fd, bb.array(), bb.arrayOffset() + pos, rem, - isConnected()); - if (n > 0) - bb.position(pos + n); - return n; - } - - public int send(ByteBuffer src, SocketAddress target) - throws IOException - { - if (src == null) - throw new NullPointerException(); - - synchronized (writeLock) { - ensureOpen(); - InetSocketAddress isa = Net.checkAddress(target); - InetAddress ia = isa.getAddress(); - if (ia == null) - throw new IOException("Target address not resolved"); - synchronized (stateLock) { - if (!isConnected()) { - if (target == null) - throw new NullPointerException(); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - if (ia.isMulticastAddress()) { - sm.checkMulticast(ia); - } else { - sm.checkConnect(ia.getHostAddress(), - isa.getPort()); - } - } - } else { // Connected case; Check address then write - if (!target.equals(remoteAddress)) { - throw new IllegalArgumentException( - "Connected address not equal to target address"); - } - return write(src); - } - } - - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = send(fd, src, isa); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - - synchronized (stateLock) { - if (isOpen() && (localAddress == null)) { - localAddress = Net.localAddress(fd); - } - } - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - private int send(FileDescriptor fd, ByteBuffer src, InetSocketAddress target) - throws IOException - { - if (src.hasArray()) - return sendFromManagedBuffer(fd, src, target); - - // Substitute a managed buffer - int pos = src.position(); - int lim = src.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - ByteBuffer bb = ByteBuffer.allocate(rem); - try { - bb.put(src); - bb.flip(); - // Do not update src until we see how many bytes were written - src.position(pos); - - int n = sendFromManagedBuffer(fd, bb, target); - if (n > 0) { - // now update src - src.position(pos + n); - } - return n; - } finally { - } - } - - private int sendFromManagedBuffer(FileDescriptor fd, ByteBuffer bb, - InetSocketAddress target) - throws IOException - { - int pos = bb.position(); - int lim = bb.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - boolean preferIPv6 = (family != StandardProtocolFamily.INET); - int written; - try { - written = send0(preferIPv6, fd, bb.array(), bb.arrayOffset() + pos, - rem, target.getAddress(), target.getPort()); - } catch (PortUnreachableException pue) { - if (isConnected()) - throw pue; - written = rem; - } - if (written > 0) - bb.position(pos + written); - return written; - } - - public int read(ByteBuffer buf) throws IOException { - if (buf == null) - throw new NullPointerException(); - synchronized (readLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - readerThread = NativeThread.current(); - do { - n = IOUtil.read(fd, buf, -1, nd, readLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException - { - if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) - throw new IndexOutOfBoundsException(); - synchronized (readLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - readerThread = NativeThread.current(); - do { - n = IOUtil.read(fd, dsts, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - public int write(ByteBuffer buf) throws IOException { - if (buf == null) - throw new NullPointerException(); - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = IOUtil.write(fd, buf, -1, nd, writeLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException - { - if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) - throw new IndexOutOfBoundsException(); - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = IOUtil.write(fd, srcs, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - protected void implConfigureBlocking(boolean block) throws IOException { - IOUtil.configureBlocking(fd, block); - } - - public SocketAddress localAddress() { - synchronized (stateLock) { - return localAddress; - } - } - - public SocketAddress remoteAddress() { - synchronized (stateLock) { - return remoteAddress; - } - } - - @Override - public DatagramChannel bind(SocketAddress local) throws IOException { - synchronized (readLock) { - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (localAddress != null) - throw new AlreadyBoundException(); - InetSocketAddress isa; - if (local == null) { - // only Inet4Address allowed with IPv4 socket - if (family == StandardProtocolFamily.INET) { - isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0); - } else { - isa = new InetSocketAddress(0); - } - } else { - isa = Net.checkAddress(local); - - // only Inet4Address allowed with IPv4 socket - if (family == StandardProtocolFamily.INET) { - InetAddress addr = isa.getAddress(); - if (!(addr instanceof Inet4Address)) - throw new UnsupportedAddressTypeException(); - } - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkListen(isa.getPort()); - } - Net.bind(family, fd, isa.getAddress(), isa.getPort()); - localAddress = Net.localAddress(fd); - } - } - } - return this; - } - - public boolean isConnected() { - synchronized (stateLock) { - return (state == ST_CONNECTED); - } - } - - void ensureOpenAndUnconnected() throws IOException { // package-private - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (state != ST_UNCONNECTED) - throw new IllegalStateException("Connect already invoked"); - } - } - - @Override - public DatagramChannel connect(SocketAddress sa) throws IOException { - int localPort = 0; - - synchronized(readLock) { - synchronized(writeLock) { - synchronized (stateLock) { - ensureOpenAndUnconnected(); - InetSocketAddress isa = Net.checkAddress(sa); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); - int n = Net.connect(family, - fd, - isa.getAddress(), - isa.getPort()); - if (n <= 0) - throw new Error(); // Can't happen - - // Connection succeeded; disallow further invocation - state = ST_CONNECTED; - remoteAddress = isa; - sender = isa; - cachedSenderInetAddress = isa.getAddress(); - cachedSenderPort = isa.getPort(); - - // set or refresh local address - localAddress = Net.localAddress(fd); - } - } - } - return this; - } - - public DatagramChannel disconnect() throws IOException { - synchronized(readLock) { - synchronized(writeLock) { - synchronized (stateLock) { - if (!isConnected() || !isOpen()) - return this; - InetSocketAddress isa = remoteAddress; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); - boolean isIPv6 = (family == StandardProtocolFamily.INET6); - disconnect0(fd, isIPv6); - remoteAddress = null; - state = ST_UNCONNECTED; - - // refresh local address - localAddress = Net.localAddress(fd); - } - } - } - return this; - } - - /** - * Joins channel's socket to the given group/interface and - * optional source address. - */ - private MembershipKey innerJoin(InetAddress group, - NetworkInterface interf, - InetAddress source) - throws IOException - { - if (!group.isMulticastAddress()) - throw new IllegalArgumentException("Group not a multicast address"); - - // check multicast address is compatible with this socket - if (group instanceof Inet4Address) { - if (family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group()) - throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group"); - } else if (group instanceof Inet6Address) { - if (family != StandardProtocolFamily.INET6) - throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group"); - } else { - throw new IllegalArgumentException("Address type not supported"); - } - - // check source address - if (source != null) { - if (source.isAnyLocalAddress()) - throw new IllegalArgumentException("Source address is a wildcard address"); - if (source.isMulticastAddress()) - throw new IllegalArgumentException("Source address is multicast address"); - if (source.getClass() != group.getClass()) - throw new IllegalArgumentException("Source address is different type to group"); - } - - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkMulticast(group); - - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - - // check the registry to see if we are already a member of the group - if (registry == null) { - registry = new MembershipRegistry(); - } else { - // return existing membership key - MembershipKey key = registry.checkMembership(group, interf, source); - if (key != null) - return key; - } - - MembershipKeyImpl key; - if ((family == StandardProtocolFamily.INET6) && - ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group())) - { - int index = interf.getIndex(); - if (index == -1) - throw new IOException("Network interface cannot be identified"); - - // need multicast and source address as byte arrays - byte[] groupAddress = Net.inet6AsByteArray(group); - byte[] sourceAddress = (source == null) ? null : - Net.inet6AsByteArray(source); - - // join the group - int n = Net.join6(fd, groupAddress, index, sourceAddress); - if (n == IOStatus.UNAVAILABLE) - throw new UnsupportedOperationException(); - - key = new MembershipKeyImpl.Type6(this, group, interf, source, - groupAddress, index, sourceAddress); - - } else { - // need IPv4 address to identify interface - Inet4Address target = Net.anyInet4Address(interf); - if (target == null) - throw new IOException("Network interface not configured for IPv4"); - - int groupAddress = Net.inet4AsInt(group); - int targetAddress = Net.inet4AsInt(target); - int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source); - - // join the group - int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress); - if (n == IOStatus.UNAVAILABLE) - throw new UnsupportedOperationException(); - - key = new MembershipKeyImpl.Type4(this, group, interf, source, - groupAddress, targetAddress, sourceAddress); - } - - registry.add(key); - return key; - } - } - - @Override - public MembershipKey join(InetAddress group, - NetworkInterface interf) - throws IOException - { - return innerJoin(group, interf, null); - } - - @Override - public MembershipKey join(InetAddress group, - NetworkInterface interf, - InetAddress source) - throws IOException - { - if (source == null) - throw new NullPointerException("source address is null"); - return innerJoin(group, interf, source); - } - - // package-private - void drop(MembershipKeyImpl key) { - assert key.channel() == this; - - synchronized (stateLock) { - if (!key.isValid()) - return; - - try { - if (key instanceof MembershipKeyImpl.Type6) { - MembershipKeyImpl.Type6 key6 = - (MembershipKeyImpl.Type6)key; - Net.drop6(fd, key6.groupAddress(), key6.index(), key6.source()); - } else { - MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4)key; - Net.drop4(fd, key4.groupAddress(), key4.interfaceAddress(), - key4.source()); - } - } catch (IOException ioe) { - // should not happen - throw new AssertionError(ioe); - } - - key.invalidate(); - registry.remove(key); - } - } - - /** - * Block datagrams from given source if a memory to receive all - * datagrams. - */ - void block(MembershipKeyImpl key, InetAddress source) - throws IOException - { - assert key.channel() == this; - assert key.sourceAddress() == null; - - synchronized (stateLock) { - if (!key.isValid()) - throw new IllegalStateException("key is no longer valid"); - if (source.isAnyLocalAddress()) - throw new IllegalArgumentException("Source address is a wildcard address"); - if (source.isMulticastAddress()) - throw new IllegalArgumentException("Source address is multicast address"); - if (source.getClass() != key.group().getClass()) - throw new IllegalArgumentException("Source address is different type to group"); - - int n; - if (key instanceof MembershipKeyImpl.Type6) { - MembershipKeyImpl.Type6 key6 = - (MembershipKeyImpl.Type6)key; - n = Net.block6(fd, key6.groupAddress(), key6.index(), - Net.inet6AsByteArray(source)); - } else { - MembershipKeyImpl.Type4 key4 = - (MembershipKeyImpl.Type4)key; - n = Net.block4(fd, key4.groupAddress(), key4.interfaceAddress(), - Net.inet4AsInt(source)); - } - if (n == IOStatus.UNAVAILABLE) { - // ancient kernel - throw new UnsupportedOperationException(); - } - } - } - - /** - * Unblock given source. - */ - void unblock(MembershipKeyImpl key, InetAddress source) { - assert key.channel() == this; - assert key.sourceAddress() == null; - - synchronized (stateLock) { - if (!key.isValid()) - throw new IllegalStateException("key is no longer valid"); - - try { - if (key instanceof MembershipKeyImpl.Type6) { - MembershipKeyImpl.Type6 key6 = - (MembershipKeyImpl.Type6)key; - Net.unblock6(fd, key6.groupAddress(), key6.index(), - Net.inet6AsByteArray(source)); - } else { - MembershipKeyImpl.Type4 key4 = - (MembershipKeyImpl.Type4)key; - Net.unblock4(fd, key4.groupAddress(), key4.interfaceAddress(), - Net.inet4AsInt(source)); - } - } catch (IOException ioe) { - // should not happen - throw new AssertionError(ioe); - } - } - } - - protected void implCloseSelectableChannel() throws IOException { - synchronized (stateLock) { - if (state != ST_KILLED) - nd.preClose(fd); - ResourceManager.afterUdpClose(); - - // if member of mulitcast group then invalidate all keys - if (registry != null) - registry.invalidateAll(); - - long th; - if ((th = readerThread) != 0) - NativeThread.signal(th); - if ((th = writerThread) != 0) - NativeThread.signal(th); - if (!isRegistered()) - kill(); - } - } - - public void kill() throws IOException { - synchronized (stateLock) { - if (state == ST_KILLED) - return; - if (state == ST_UNINITIALIZED) { - state = ST_KILLED; - return; - } - assert !isOpen() && !isRegistered(); - nd.close(fd); - state = ST_KILLED; - } - } - - /** - * Translates native poll revent set into a ready operation set - */ - public boolean translateReadyOps(int ops, int initialOps, - SelectionKeyImpl sk) { - int intOps = sk.nioInterestOps(); // Do this just once, it synchronizes - int oldOps = sk.nioReadyOps(); - int newOps = initialOps; - - if ((ops & PollArrayWrapper.POLLNVAL) != 0) { - // This should only happen if this channel is pre-closed while a - // selection operation is in progress - // ## Throw an error if this channel has not been pre-closed - return false; - } - - if ((ops & (PollArrayWrapper.POLLERR - | PollArrayWrapper.POLLHUP)) != 0) { - newOps = intOps; - sk.nioReadyOps(newOps); - return (newOps & ~oldOps) != 0; - } - - if (((ops & PollArrayWrapper.POLLIN) != 0) && - ((intOps & SelectionKey.OP_READ) != 0)) - newOps |= SelectionKey.OP_READ; - - if (((ops & PollArrayWrapper.POLLOUT) != 0) && - ((intOps & SelectionKey.OP_WRITE) != 0)) - newOps |= SelectionKey.OP_WRITE; - - sk.nioReadyOps(newOps); - return (newOps & ~oldOps) != 0; - } - - public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk) { - return translateReadyOps(ops, sk.nioReadyOps(), sk); - } - - public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk) { - return translateReadyOps(ops, 0, sk); - } - - /** - * Translates an interest operation set into a native poll event set - */ - public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) { - int newOps = 0; - - if ((ops & SelectionKey.OP_READ) != 0) - newOps |= PollArrayWrapper.POLLIN; - if ((ops & SelectionKey.OP_WRITE) != 0) - newOps |= PollArrayWrapper.POLLOUT; - if ((ops & SelectionKey.OP_CONNECT) != 0) - newOps |= PollArrayWrapper.POLLIN; - sk.selector.putEventOps(sk, newOps); - } - - public FileDescriptor getFD() { - return fd; - } - - public int getFDVal() { - return fdVal; - } - - - // -- Native methods -- - - private static native void initIDs(); - - private static native void disconnect0(FileDescriptor fd, boolean isIPv6) - throws IOException; - - private native int receive0(FileDescriptor fd, byte[] buf, int pos, int len, - boolean connected) - throws IOException; - - private native int send0(boolean preferIPv6, FileDescriptor fd, byte[] buf, int pos, - int len, InetAddress addr, int port) - throws IOException; - - static { - Util.load(); - initIDs(); - } - -} diff --git a/openjdk/sun/nio/ch/DefaultSelectorProvider.java b/openjdk/sun/nio/ch/DefaultSelectorProvider.java deleted file mode 100644 index 8c5cf037..00000000 --- a/openjdk/sun/nio/ch/DefaultSelectorProvider.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.IOException; -import java.nio.channels.spi.AbstractSelector; -import java.nio.channels.spi.SelectorProvider; - - -/** - * Creates this platform's default SelectorProvider - */ - -public class DefaultSelectorProvider { - - /** - * Prevent instantiation. - */ - private DefaultSelectorProvider() { } - - /** - * Returns the default SelectorProvider. - */ - public static SelectorProvider create() { - return new SelectorProviderImpl() { - public AbstractSelector openSelector() throws IOException { - return new DotNetSelectorImpl(this); - } - }; - } - -} diff --git a/openjdk/sun/nio/ch/DotNetSelectorImpl.java b/openjdk/sun/nio/ch/DotNetSelectorImpl.java deleted file mode 100644 index 897cf9a1..00000000 --- a/openjdk/sun/nio/ch/DotNetSelectorImpl.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2002, 2007, 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. - */ - -// Parts Copyright (C) 2002-2007 Jeroen Frijters - -package sun.nio.ch; - -import cli.System.Net.Sockets.Socket; -import cli.System.Net.Sockets.SocketException; -import cli.System.Net.Sockets.AddressFamily; -import cli.System.Net.Sockets.SocketType; -import cli.System.Net.Sockets.ProtocolType; -import cli.System.Net.Sockets.SelectMode; -import cli.System.Collections.ArrayList; -import java.io.IOException; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.Pipe; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.AbstractSelectableChannel; -import java.nio.channels.spi.AbstractSelector; -import java.nio.channels.spi.SelectorProvider; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -final class DotNetSelectorImpl extends SelectorImpl -{ - private ArrayList channelArray = new ArrayList(); - private long updateCount = 0; - - //Pipe used as a wakeup object. - private final Pipe wakeupPipe; - - // File descriptors corresponding to source and sink - private final Socket wakeupSourceFd, wakeupSinkFd; - - // Lock for interrupt triggering and clearing - private final Object interruptLock = new Object(); - private volatile boolean interruptTriggered = false; - - // class for fdMap entries - private final static class MapEntry - { - SelectionKeyImpl ski; - long updateCount = 0; - long clearedCount = 0; - MapEntry(SelectionKeyImpl ski) - { - this.ski = ski; - } - } - private final HashMap<Socket, MapEntry> fdMap = new HashMap<Socket, MapEntry>(); - - DotNetSelectorImpl(SelectorProvider sp) throws IOException - { - super(sp); - wakeupPipe = Pipe.open(); - wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFD().getSocket(); - - // Disable the Nagle algorithm so that the wakeup is more immediate - SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink(); - (sink.sc).socket().setTcpNoDelay(true); - wakeupSinkFd = ((SelChImpl)sink).getFD().getSocket(); - } - - protected int doSelect(long timeout) throws IOException - { - if (channelArray == null) - throw new ClosedSelectorException(); - processDeregisterQueue(); - if (interruptTriggered) - { - resetWakeupSocket(); - return 0; - } - - ArrayList read = new ArrayList(); - ArrayList write = new ArrayList(); - ArrayList error = new ArrayList(); - for (int i = 0; i < channelArray.get_Count(); i++) - { - SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); - int ops = ski.interestOps(); - if (ski.channel() instanceof SocketChannelImpl) - { - // TODO there's a race condition here... - if (((SocketChannelImpl)ski.channel()).isConnected()) - { - ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE; - } - else - { - ops &= SelectionKey.OP_CONNECT; - } - } - if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) - { - read.Add(ski.getSocket()); - } - if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) - { - write.Add(ski.getSocket()); - } - if ((ops & SelectionKey.OP_CONNECT) != 0) - { - error.Add(ski.getSocket()); - } - } - read.Add(wakeupSourceFd); - try - { - begin(); - int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout); - try - { - if (false) throw new SocketException(); - // FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work - Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds); - } - catch (SocketException _) - { - read.Clear(); - write.Clear(); - error.Clear(); - } - } - finally - { - end(); - } - processDeregisterQueue(); - int updated = updateSelectedKeys(read, write, error); - // Done with poll(). Set wakeupSocket to nonsignaled for the next run. - resetWakeupSocket(); - return updated; - } - - private int updateSelectedKeys(ArrayList read, ArrayList write, ArrayList error) - { - updateCount++; - int keys = processFDSet(updateCount, read, PollArrayWrapper.POLLIN); - keys += processFDSet(updateCount, write, PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); - keys += processFDSet(updateCount, error, PollArrayWrapper.POLLIN | PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); - return keys; - } - - private int processFDSet(long updateCount, ArrayList sockets, int rOps) - { - int numKeysUpdated = 0; - for (int i = 0; i < sockets.get_Count(); i++) - { - Socket desc = (Socket)sockets.get_Item(i); - if (desc == wakeupSourceFd) - { - synchronized (interruptLock) - { - interruptTriggered = true; - } - continue; - } - MapEntry me = fdMap.get(desc); - // If me is null, the key was deregistered in the previous - // processDeregisterQueue. - if (me == null) - continue; - SelectionKeyImpl sk = me.ski; - if (selectedKeys.contains(sk)) - { // Key in selected set - if (me.clearedCount != updateCount) - { - if (sk.channel.translateAndSetReadyOps(rOps, sk) && - (me.updateCount != updateCount)) - { - me.updateCount = updateCount; - numKeysUpdated++; - } - } - else - { // The readyOps have been set; now add - if (sk.channel.translateAndUpdateReadyOps(rOps, sk) && - (me.updateCount != updateCount)) - { - me.updateCount = updateCount; - numKeysUpdated++; - } - } - me.clearedCount = updateCount; - } - else - { // Key is not in selected set yet - if (me.clearedCount != updateCount) - { - sk.channel.translateAndSetReadyOps(rOps, sk); - if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) - { - selectedKeys.add(sk); - me.updateCount = updateCount; - numKeysUpdated++; - } - } - else - { // The readyOps have been set; now add - sk.channel.translateAndUpdateReadyOps(rOps, sk); - if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) - { - selectedKeys.add(sk); - me.updateCount = updateCount; - numKeysUpdated++; - } - } - me.clearedCount = updateCount; - } - } - return numKeysUpdated; - } - - protected void implClose() throws IOException - { - if (channelArray != null) - { - // prevent further wakeup - synchronized (interruptLock) { - interruptTriggered = true; - } - wakeupPipe.sink().close(); - wakeupPipe.source().close(); - for (int i = 0; i < channelArray.get_Count(); i++) - { // Deregister channels - SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); - deregister(ski); - SelectableChannel selch = ski.channel(); - if (!selch.isOpen() && !selch.isRegistered()) - ((SelChImpl)selch).kill(); - } - selectedKeys = null; - channelArray = null; - } - } - - protected void implRegister(SelectionKeyImpl ski) - { - channelArray.Add(ski); - fdMap.put(ski.getSocket(), new MapEntry(ski)); - keys.add(ski); - } - - protected void implDereg(SelectionKeyImpl ski) throws IOException - { - channelArray.Remove(ski); - fdMap.remove(ski.getSocket()); - keys.remove(ski); - selectedKeys.remove(ski); - deregister(ski); - SelectableChannel selch = ski.channel(); - if (!selch.isOpen() && !selch.isRegistered()) - { - ((SelChImpl)selch).kill(); - } - } - - public Selector wakeup() - { - synchronized (interruptLock) - { - if (!interruptTriggered) - { - setWakeupSocket(); - interruptTriggered = true; - } - } - return this; - } - - // Sets Windows wakeup socket to a signaled state. - private void setWakeupSocket() { - wakeupSinkFd.Send(new byte[1]); - } - - // Sets Windows wakeup socket to a non-signaled state. - private void resetWakeupSocket() { - synchronized (interruptLock) - { - if (interruptTriggered == false) - return; - resetWakeupSocket0(wakeupSourceFd); - interruptTriggered = false; - } - } - - private static void resetWakeupSocket0(Socket wakeupSourceFd) - { - while (wakeupSourceFd.get_Available() > 0) - { - wakeupSourceFd.Receive(new byte[1]); - } - } -} diff --git a/openjdk/sun/nio/ch/FileChannelImpl.java b/openjdk/sun/nio/ch/FileChannelImpl.java deleted file mode 100644 index 902509bd..00000000 --- a/openjdk/sun/nio/ch/FileChannelImpl.java +++ /dev/null @@ -1,1104 +0,0 @@ -/* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import cli.Microsoft.Win32.SafeHandles.SafeFileHandle; -import cli.System.IntPtr; -import cli.System.IO.FileStream; -import cli.System.Runtime.InteropServices.DllImportAttribute; -import java.io.FileDescriptor; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.*; -import java.util.ArrayList; -import java.util.List; -import java.security.AccessController; -import sun.misc.Cleaner; -import sun.misc.IoTrace; -import sun.security.action.GetPropertyAction; - -public class FileChannelImpl - extends FileChannel -{ - private static final boolean win32 = ikvm.internal.Util.WINDOWS; - - // Memory allocation size for mapping buffers - private static final long allocationGranularity = 64 * 1024; // HACK we're using a hard coded value here that works on all mainstream platforms - - // Used to make native read and write calls - private final FileDispatcher nd; - - // File descriptor - private final FileDescriptor fd; - - // File access mode (immutable) - private final boolean writable; - private final boolean readable; - private final boolean append; - - // Required to prevent finalization of creating stream (immutable) - private final Object parent; - - // The path of the referenced file (null if the parent stream is created with a file descriptor) - private final String path; - - // Thread-safe set of IDs of native threads, for signalling - private final NativeThreadSet threads = new NativeThreadSet(2); - - // Lock for operations involving position and size - private final Object positionLock = new Object(); - - private FileChannelImpl(FileDescriptor fd, String path, boolean readable, - boolean writable, boolean append, Object parent) - { - this.fd = fd; - this.readable = readable; - this.writable = writable; - this.append = append; - this.parent = parent; - this.path = path; - this.nd = new FileDispatcherImpl(append); - } - - // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel() - public static FileChannel open(FileDescriptor fd, String path, - boolean readable, boolean writable, - Object parent) - { - return new FileChannelImpl(fd, path, readable, writable, false, parent); - } - - // Used by FileOutputStream.getChannel - public static FileChannel open(FileDescriptor fd, String path, - boolean readable, boolean writable, - boolean append, Object parent) - { - return new FileChannelImpl(fd, path, readable, writable, append, parent); - } - - private void ensureOpen() throws IOException { - if (!isOpen()) - throw new ClosedChannelException(); - } - - - // -- Standard channel operations -- - - protected void implCloseChannel() throws IOException { - // Release and invalidate any locks that we still hold - if (fileLockTable != null) { - for (FileLock fl: fileLockTable.removeAll()) { - synchronized (fl) { - if (fl.isValid()) { - nd.release(fd, fl.position(), fl.size()); - ((FileLockImpl)fl).invalidate(); - } - } - } - } - - nd.preClose(fd); - threads.signalAndWait(); - - if (parent != null) { - - // Close the fd via the parent stream's close method. The parent - // will reinvoke our close method, which is defined in the - // superclass AbstractInterruptibleChannel, but the isOpen logic in - // that method will prevent this method from being reinvoked. - // - ((java.io.Closeable)parent).close(); - } else { - nd.close(fd); - } - - } - - public int read(ByteBuffer dst) throws IOException { - ensureOpen(); - if (!readable) - throw new NonReadableChannelException(); - synchronized (positionLock) { - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileReadBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.read(fd, dst, -1, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - } - - public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException - { - if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) - throw new IndexOutOfBoundsException(); - ensureOpen(); - if (!readable) - throw new NonReadableChannelException(); - synchronized (positionLock) { - long n = 0; - int ti = -1; - Object traceContext = IoTrace.fileReadBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.read(fd, dsts, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - } - - public int write(ByteBuffer src) throws IOException { - ensureOpen(); - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileWriteBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.write(fd, src, -1, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - end(n > 0); - IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0); - assert IOStatus.check(n); - } - } - } - - public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException - { - if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) - throw new IndexOutOfBoundsException(); - ensureOpen(); - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { - long n = 0; - int ti = -1; - Object traceContext = IoTrace.fileWriteBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.write(fd, srcs, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - } - - // -- Other operations -- - - public long position() throws IOException { - ensureOpen(); - synchronized (positionLock) { - long p = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - // in append-mode then position is advanced to end before writing - p = (append) ? nd.size(fd) : position0(fd, -1); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(p); - } finally { - threads.remove(ti); - end(p > -1); - assert IOStatus.check(p); - } - } - } - - public FileChannel position(long newPosition) throws IOException { - ensureOpen(); - if (newPosition < 0) - throw new IllegalArgumentException(); - synchronized (positionLock) { - long p = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - do { - p = position0(fd, newPosition); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - return this; - } finally { - threads.remove(ti); - end(p > -1); - assert IOStatus.check(p); - } - } - } - - public long size() throws IOException { - ensureOpen(); - synchronized (positionLock) { - long s = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return -1; - do { - s = nd.size(fd); - } while ((s == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(s); - } finally { - threads.remove(ti); - end(s > -1); - assert IOStatus.check(s); - } - } - } - - public FileChannel truncate(long size) throws IOException { - ensureOpen(); - if (size < 0) - throw new IllegalArgumentException(); - if (size > size()) - return this; - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { - int rv = -1; - long p = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - - // get current position - do { - p = position0(fd, -1); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - if (!isOpen()) - return null; - assert p >= 0; - - // truncate file - do { - rv = nd.truncate(fd, size); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - if (!isOpen()) - return null; - - // [IKVM] in append mode we're not allowed to seek backwards, but the atomic append will honor the new file size - if (append) - return this; - - // set position to size if greater than size - if (p > size) - p = size; - do { - rv = (int)position0(fd, p); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - return this; - } finally { - threads.remove(ti); - end(rv > -1); - assert IOStatus.check(rv); - } - } - } - - public void force(boolean metaData) throws IOException { - ensureOpen(); - int rv = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return; - do { - rv = nd.force(fd, metaData); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - } finally { - threads.remove(ti); - end(rv > -1); - assert IOStatus.check(rv); - } - } - - private long transferToArbitraryChannel(long position, int icount, - WritableByteChannel target) - throws IOException - { - // Untrusted target: Use a newly-erased buffer - int c = Math.min(icount, TRANSFER_SIZE); - ByteBuffer bb = ByteBuffer.allocate(c); - long tw = 0; // Total bytes written - long pos = position; - try { - while (tw < icount) { - bb.limit(Math.min((int)(icount - tw), TRANSFER_SIZE)); - int nr = read(bb, pos); - if (nr <= 0) - break; - bb.flip(); - // ## Bug: Will block writing target if this channel - // ## is asynchronously closed - int nw = target.write(bb); - tw += nw; - if (nw != nr) - break; - pos += nw; - bb.clear(); - } - return tw; - } catch (IOException x) { - if (tw > 0) - return tw; - throw x; - } - } - - public long transferTo(long position, long count, - WritableByteChannel target) - throws IOException - { - ensureOpen(); - if (!target.isOpen()) - throw new ClosedChannelException(); - if (!readable) - throw new NonReadableChannelException(); - if (target instanceof FileChannelImpl && - !((FileChannelImpl)target).writable) - throw new NonWritableChannelException(); - if ((position < 0) || (count < 0)) - throw new IllegalArgumentException(); - long sz = size(); - if (position > sz) - return 0; - int icount = (int)Math.min(count, Integer.MAX_VALUE); - if ((sz - position) < icount) - icount = (int)(sz - position); - - // Slow path for untrusted targets - return transferToArbitraryChannel(position, icount, target); - } - - private long transferFromFileChannel(FileChannelImpl src, - long position, long count) - throws IOException - { - if (!src.readable) - throw new NonReadableChannelException(); - return transferFromArbitraryChannel(src, position, count); - } - - private static final int TRANSFER_SIZE = 8192; - - private long transferFromArbitraryChannel(ReadableByteChannel src, - long position, long count) - throws IOException - { - // Untrusted target: Use a newly-erased buffer - int c = (int)Math.min(count, TRANSFER_SIZE); - ByteBuffer bb = ByteBuffer.allocate(c); - long tw = 0; // Total bytes written - long pos = position; - try { - while (tw < count) { - bb.limit((int)Math.min((count - tw), (long)TRANSFER_SIZE)); - // ## Bug: Will block reading src if this channel - // ## is asynchronously closed - int nr = src.read(bb); - if (nr <= 0) - break; - bb.flip(); - int nw = write(bb, pos); - tw += nw; - if (nw != nr) - break; - pos += nw; - bb.clear(); - } - return tw; - } catch (IOException x) { - if (tw > 0) - return tw; - throw x; - } - } - - public long transferFrom(ReadableByteChannel src, - long position, long count) - throws IOException - { - ensureOpen(); - if (!src.isOpen()) - throw new ClosedChannelException(); - if (!writable) - throw new NonWritableChannelException(); - if ((position < 0) || (count < 0)) - throw new IllegalArgumentException(); - if (position > size()) - return 0; - if (src instanceof FileChannelImpl) - return transferFromFileChannel((FileChannelImpl)src, - position, count); - - return transferFromArbitraryChannel(src, position, count); - } - - public int read(ByteBuffer dst, long position) throws IOException { - if (dst == null) - throw new NullPointerException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (!readable) - throw new NonReadableChannelException(); - ensureOpen(); - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileReadBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return -1; - do { - n = IOUtil.read(fd, dst, position, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - - public int write(ByteBuffer src, long position) throws IOException { - if (src == null) - throw new NullPointerException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (!writable) - throw new NonWritableChannelException(); - ensureOpen(); - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileWriteBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return -1; - do { - n = IOUtil.write(fd, src, position, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - end(n > 0); - IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0); - assert IOStatus.check(n); - } - } - - - // -- Memory-mapped buffers -- - - 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; - static volatile long totalCapacity; - - private volatile long address; - private final long size; - private final int cap; - private final FileDescriptor fd; - - private Unmapper(long address, long size, int cap, - FileDescriptor fd) - { - assert (address != 0); - this.address = address; - this.size = size; - this.cap = cap; - this.fd = fd; - - synchronized (Unmapper.class) { - count++; - totalSize += size; - totalCapacity += cap; - } - } - - public void run() { - if (address == 0) - return; - unmap0(address, size); - address = 0; - - // if this mapping has a valid file descriptor then we close it - if (fd.valid()) { - try { - nd.close(fd); - } catch (IOException ignore) { - // nothing we can do - } - } - - synchronized (Unmapper.class) { - count--; - totalSize -= size; - totalCapacity -= cap; - } - } - } - - private static void unmap(MappedByteBuffer bb) { - Cleaner cl = ((DirectBuffer)bb).cleaner(); - if (cl != null) - cl.clean(); - } - - private static final int MAP_RO = 0; - private static final int MAP_RW = 1; - private static final int MAP_PV = 2; - - public MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException - { - ensureOpen(); - if (position < 0L) - throw new IllegalArgumentException("Negative position"); - if (size < 0L) - throw new IllegalArgumentException("Negative size"); - if (position + size < 0) - throw new IllegalArgumentException("Position + size overflow"); - if (size > Integer.MAX_VALUE) - throw new IllegalArgumentException("Size exceeds Integer.MAX_VALUE"); - int imode = -1; - if (mode == MapMode.READ_ONLY) - imode = MAP_RO; - else if (mode == MapMode.READ_WRITE) - imode = MAP_RW; - else if (mode == MapMode.PRIVATE) - imode = MAP_PV; - assert (imode >= 0); - if ((mode != MapMode.READ_ONLY) && !writable) - throw new NonWritableChannelException(); - if (!readable) - throw new NonReadableChannelException(); - - long addr = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - if (size() < position + size) { // Extend file size - if (!writable) { - throw new IOException("Channel not open for writing " + - "- cannot extend file to required size"); - } - int rv; - do { - rv = nd.truncate(fd, position + size); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - } - if (size == 0) { - addr = 0; - // a valid file descriptor is not required - FileDescriptor dummy = new FileDescriptor(); - if ((!writable) || (imode == MAP_RO)) - return Util.newMappedByteBufferR(0, 0, dummy, null); - else - return Util.newMappedByteBuffer(0, 0, dummy, null); - } - - int pagePosition = (int)(position % allocationGranularity); - long mapPosition = position - pagePosition; - long mapSize = size + pagePosition; - try { - // If no exception was thrown from map0, the address is valid - addr = map0(imode, mapPosition, mapSize); - } catch (OutOfMemoryError x) { - // An OutOfMemoryError may indicate that we've exhausted memory - // so force gc and re-attempt map - System.gc(); - try { - Thread.sleep(100); - } catch (InterruptedException y) { - Thread.currentThread().interrupt(); - } - try { - addr = map0(imode, mapPosition, mapSize); - } catch (OutOfMemoryError y) { - // After a second OOME, fail - throw new IOException("Map failed", y); - } - } - - // On Windows, and potentially other platforms, we need an open - // file descriptor for some mapping operations. - FileDescriptor mfd; - try { - mfd = nd.duplicateForMapping(fd); - } catch (IOException ioe) { - unmap0(addr, mapSize); - throw ioe; - } - - assert (IOStatus.checkAll(addr)); - assert (addr % allocationGranularity == 0); - int isize = (int)size; - Unmapper um = new Unmapper(addr, mapSize, isize, mfd); - if ((!writable) || (imode == MAP_RO)) { - return Util.newMappedByteBufferR(isize, - addr + pagePosition, - mfd, - um); - } else { - return Util.newMappedByteBuffer(isize, - addr + pagePosition, - mfd, - um); - } - } finally { - threads.remove(ti); - end(IOStatus.checkAll(addr)); - } - } - - /** - * Invoked by sun.management.ManagementFactoryHelper to create the management - * interface for mapped buffers. - */ - public static sun.misc.JavaNioAccess.BufferPool getMappedBufferPool() { - return new sun.misc.JavaNioAccess.BufferPool() { - @Override - public String getName() { - return "mapped"; - } - @Override - public long getCount() { - return Unmapper.count; - } - @Override - public long getTotalCapacity() { - return Unmapper.totalCapacity; - } - @Override - public long getMemoryUsed() { - return Unmapper.totalSize; - } - }; - } - - // -- Locks -- - - - - // keeps track of locks on this file - private volatile FileLockTable fileLockTable; - - // indicates if file locks are maintained system-wide (as per spec) - private static boolean isSharedFileLockTable; - - // indicates if the disableSystemWideOverlappingFileLockCheck property - // has been checked - private static volatile boolean propertyChecked; - - // The lock list in J2SE 1.4/5.0 was local to each FileChannel instance so - // the overlap check wasn't system wide when there were multiple channels to - // the same file. This property is used to get 1.4/5.0 behavior if desired. - private static boolean isSharedFileLockTable() { - if (!propertyChecked) { - synchronized (FileChannelImpl.class) { - if (!propertyChecked) { - String value = AccessController.doPrivileged( - new GetPropertyAction( - "sun.nio.ch.disableSystemWideOverlappingFileLockCheck")); - isSharedFileLockTable = ((value == null) || value.equals("false")); - propertyChecked = true; - } - } - } - return isSharedFileLockTable; - } - - private FileLockTable fileLockTable() throws IOException { - if (fileLockTable == null) { - synchronized (this) { - if (fileLockTable == null) { - if (isSharedFileLockTable()) { - int ti = threads.add(); - try { - ensureOpen(); - fileLockTable = FileLockTable.newSharedFileLockTable(this, fd); - } finally { - threads.remove(ti); - } - } else { - fileLockTable = new SimpleFileLockTable(); - } - } - } - } - return fileLockTable; - } - - public FileLock lock(long position, long size, boolean shared) - throws IOException - { - ensureOpen(); - if (shared && !readable) - throw new NonReadableChannelException(); - if (!shared && !writable) - throw new NonWritableChannelException(); - FileLockImpl fli = new FileLockImpl(this, position, size, shared); - FileLockTable flt = fileLockTable(); - flt.add(fli); - boolean completed = false; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - int n; - do { - n = nd.lock(fd, true, position, size, shared); - } while ((n == FileDispatcher.INTERRUPTED) && isOpen()); - if (isOpen()) { - if (n == FileDispatcher.RET_EX_LOCK) { - assert shared; - FileLockImpl fli2 = new FileLockImpl(this, position, size, - false); - flt.replace(fli, fli2); - fli = fli2; - } - completed = true; - } - } finally { - if (!completed) - flt.remove(fli); - threads.remove(ti); - try { - end(completed); - } catch (ClosedByInterruptException e) { - throw new FileLockInterruptionException(); - } - } - return fli; - } - - public FileLock tryLock(long position, long size, boolean shared) - throws IOException - { - ensureOpen(); - if (shared && !readable) - throw new NonReadableChannelException(); - if (!shared && !writable) - throw new NonWritableChannelException(); - FileLockImpl fli = new FileLockImpl(this, position, size, shared); - FileLockTable flt = fileLockTable(); - flt.add(fli); - int result; - - int ti = threads.add(); - try { - try { - ensureOpen(); - result = nd.lock(fd, false, position, size, shared); - } catch (IOException e) { - flt.remove(fli); - throw e; - } - if (result == FileDispatcher.NO_LOCK) { - flt.remove(fli); - return null; - } - if (result == FileDispatcher.RET_EX_LOCK) { - assert shared; - FileLockImpl fli2 = new FileLockImpl(this, position, size, - false); - flt.replace(fli, fli2); - return fli2; - } - return fli; - } finally { - threads.remove(ti); - } - } - - void release(FileLockImpl fli) throws IOException { - int ti = threads.add(); - try { - ensureOpen(); - nd.release(fd, fli.position(), fli.size()); - } finally { - threads.remove(ti); - } - assert fileLockTable != null; - fileLockTable.remove(fli); - } - - // -- File lock support -- - - /** - * A simple file lock table that maintains a list of FileLocks obtained by a - * FileChannel. Use to get 1.4/5.0 behaviour. - */ - private static class SimpleFileLockTable extends FileLockTable { - // synchronize on list for access - private final List<FileLock> lockList = new ArrayList<FileLock>(2); - - public SimpleFileLockTable() { - } - - private void checkList(long position, long size) - throws OverlappingFileLockException - { - assert Thread.holdsLock(lockList); - for (FileLock fl: lockList) { - if (fl.overlaps(position, size)) { - throw new OverlappingFileLockException(); - } - } - } - - public void add(FileLock fl) throws OverlappingFileLockException { - synchronized (lockList) { - checkList(fl.position(), fl.size()); - lockList.add(fl); - } - } - - public void remove(FileLock fl) { - synchronized (lockList) { - lockList.remove(fl); - } - } - - public List<FileLock> removeAll() { - synchronized(lockList) { - List<FileLock> result = new ArrayList<FileLock>(lockList); - lockList.clear(); - return result; - } - } - - public void replace(FileLock fl1, FileLock fl2) { - synchronized (lockList) { - lockList.remove(fl1); - lockList.add(fl2); - } - } - } - - // -- Native methods -- - - // Creates a new mapping - private long map0(int prot, long position, long length) throws IOException - { - FileStream fs = (FileStream)fd.getStream(); - if (win32) - return mapViewOfFileWin32(fs, prot, position, length); - else - return mapViewOfFilePosix(fs, prot, position, length); - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - private static long mapViewOfFileWin32(FileStream fs, int prot, long position, long length) throws IOException - { - try - { - int PAGE_READONLY = 2; - int PAGE_READWRITE = 4; - int PAGE_WRITECOPY = 8; - - int FILE_MAP_WRITE = 2; - int FILE_MAP_READ = 4; - int FILE_MAP_COPY = 1; - - int fileProtect; - int mapAccess; - - switch (prot) - { - case MAP_RO: - fileProtect = PAGE_READONLY; - mapAccess = FILE_MAP_READ; - break; - case MAP_RW: - fileProtect = PAGE_READWRITE; - mapAccess = FILE_MAP_WRITE; - break; - case MAP_PV: - fileProtect = PAGE_WRITECOPY; - mapAccess = FILE_MAP_COPY; - break; - default: - throw new Error(); - } - - long maxSize = length + position; - SafeFileHandle hFileMapping = CreateFileMapping(fs.get_SafeFileHandle(), IntPtr.Zero, fileProtect, (int)(maxSize >> 32), (int)maxSize, null); - int err = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); - if (hFileMapping.get_IsInvalid()) - { - throw new IOException("Win32 error " + err); - } - IntPtr p = MapViewOfFile(hFileMapping, mapAccess, (int)(position >> 32), (int)position, IntPtr.op_Explicit(length)); - err = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); - hFileMapping.Close(); - if (p.Equals(IntPtr.Zero)) - { - if (err == 8 /*ERROR_NOT_ENOUGH_MEMORY*/) - { - throw new OutOfMemoryError("Map failed"); - } - throw new IOException("Win32 error " + err); - } - cli.System.GC.AddMemoryPressure(length); - return p.ToInt64(); - } - finally - { - cli.System.GC.KeepAlive(fs); - } - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - private static long mapViewOfFilePosix(FileStream fs, int prot, long position, long length) throws IOException - { - byte writeable = prot != MAP_RO ? (byte)1 : (byte)0; - byte copy_on_write = prot == MAP_PV ? (byte)1 : (byte)0; - IntPtr p = ikvm_mmap(fs.get_SafeFileHandle(), writeable, copy_on_write, position, (int)length); - cli.System.GC.KeepAlive(fs); - // HACK ikvm_mmap should really be changed to return a null pointer on failure, - // instead of whatever MAP_FAILED is defined to on the particular system we're running on, - // common values for MAP_FAILED are 0 and -1, so we test for these. - if (p.Equals(IntPtr.Zero) || p.Equals(new IntPtr(-1))) - { - throw new IOException("file mapping failed"); - } - cli.System.GC.AddMemoryPressure(length); - return p.ToInt64(); - } - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native SafeFileHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, int flProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, String lpName); - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native IntPtr MapViewOfFile(SafeFileHandle hFileMapping, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, IntPtr dwNumberOfBytesToMap); - - @DllImportAttribute.Annotation("kernel32") - private static native int UnmapViewOfFile(IntPtr lpBaseAddress); - - @DllImportAttribute.Annotation("ikvm-native") - private static native int ikvm_munmap(IntPtr address, int size); - - @DllImportAttribute.Annotation("ikvm-native") - private static native IntPtr ikvm_mmap(SafeFileHandle handle, byte writeable, byte copy_on_write, long position, int size); - - // Removes an existing mapping - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - static int unmap0(long address, long length) - { - if (win32) - UnmapViewOfFile(IntPtr.op_Explicit(address)); - else - ikvm_munmap(IntPtr.op_Explicit(address), (int)length); - cli.System.GC.RemoveMemoryPressure(length); - return 0; - } - - // Sets or reports this file's position - // If offset is -1, the current position is returned - // otherwise the position is set to offset - private static long position0(FileDescriptor fd, long offset) throws IOException - { - if (offset == -1) - { - return fd.getFilePointer(); - } - fd.seek(offset); - return offset; - } -} diff --git a/openjdk/sun/nio/ch/FileDispatcherImpl.java b/openjdk/sun/nio/ch/FileDispatcherImpl.java deleted file mode 100644 index 971df81b..00000000 --- a/openjdk/sun/nio/ch/FileDispatcherImpl.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.nio.ByteBuffer; -import cli.Microsoft.Win32.SafeHandles.SafeFileHandle; -import cli.System.IntPtr; -import cli.System.IO.FileStream; -import cli.System.Runtime.InteropServices.DllImportAttribute; -import cli.System.Runtime.InteropServices.StructLayoutAttribute; -import cli.System.Runtime.InteropServices.LayoutKind; -import cli.System.Runtime.InteropServices.Marshal; -import static ikvm.internal.Util.WINDOWS; - -class FileDispatcherImpl extends FileDispatcher -{ - /** - * 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, byte[] buf, int offset, int length) throws IOException { - return fd.readBytes(buf, offset, length); - } - - int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - fd.writeBytes(buf, offset, length); - return length; - } - - long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException { - long totalRead = 0; - try - { - for (int i = offset; i < offset + length; i++) - { - int size = bufs[i].remaining(); - if (size > 0) - { - int read = IOUtil.read(fd, bufs[i], -1, this, this); - if (read < 0) - { - break; - } - totalRead += read; - if (read < size || fd.available() == 0) - { - break; - } - } - } - } - catch (IOException x) - { - if (totalRead == 0) - { - throw x; - } - } - return totalRead; - } - - long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException { - long totalWritten = 0; - try - { - for (int i = offset; i < offset + length; i++) - { - int size = bufs[i].remaining(); - if (size > 0) - { - int written = IOUtil.write(fd, bufs[i], -1, this, this); - totalWritten += written; - if (written < size) - { - break; - } - } - } - } - catch (IOException x) - { - if (totalWritten == 0) - { - throw x; - } - } - return totalWritten; - } - - int force(FileDescriptor fd, boolean metaData) throws IOException { - fd.sync(); - return 0; - } - - int truncate(FileDescriptor fd, long size) throws IOException { - if (append) { - // HACK in append mode we're not allowed to truncate, so we try to reopen the file and truncate that - try (FileOutputStream fos = new FileOutputStream(((FileStream)fd.getStream()).get_Name())) { - fos.getFD().setLength(size); - } - } else { - fd.setLength(size); - } - return 0; - } - - long size(FileDescriptor fd) throws IOException { - return fd.length(); - } - - @StructLayoutAttribute.Annotation(LayoutKind.__Enum.Sequential) - private static final class OVERLAPPED extends cli.System.Object - { - IntPtr Internal; - IntPtr InternalHigh; - int OffsetLow; - int OffsetHigh; - IntPtr hEvent; - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - int lock(FileDescriptor fd, boolean blocking, long pos, long size, - boolean shared) throws IOException - { - FileStream fs = (FileStream)fd.getStream(); - if (WINDOWS) - { - int LOCKFILE_FAIL_IMMEDIATELY = 1; - int LOCKFILE_EXCLUSIVE_LOCK = 2; - int ERROR_LOCK_VIOLATION = 33; - int flags = 0; - OVERLAPPED o = new OVERLAPPED(); - o.OffsetLow = (int)pos; - o.OffsetHigh = (int)(pos >> 32); - if (!blocking) - { - flags |= LOCKFILE_FAIL_IMMEDIATELY; - } - if (!shared) - { - flags |= LOCKFILE_EXCLUSIVE_LOCK; - } - int result = LockFileEx(fs.get_SafeFileHandle(), flags, 0, (int)size, (int)(size >> 32), o); - if (result == 0) - { - int error = Marshal.GetLastWin32Error(); - if (!blocking && error == ERROR_LOCK_VIOLATION) - { - return NO_LOCK; - } - throw new IOException("Lock failed"); - } - return LOCKED; - } - else - { - try - { - if (false) throw new cli.System.ArgumentOutOfRangeException(); - for (;;) - { - try - { - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fs.Lock(pos, size); - return shared ? RET_EX_LOCK : LOCKED; - } - catch (cli.System.IO.IOException x) - { - if (!blocking) - { - return NO_LOCK; - } - cli.System.Threading.Thread.Sleep(100); - } - catch (cli.System.ObjectDisposedException x) - { - throw new IOException(x.getMessage()); - } - } - } - catch (cli.System.ArgumentOutOfRangeException x) - { - throw new IOException(x.getMessage()); - } - } - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - void release(FileDescriptor fd, long pos, long size) throws IOException { - FileStream fs = (FileStream)fd.getStream(); - if (WINDOWS) - { - int ERROR_NOT_LOCKED = 158; - OVERLAPPED o = new OVERLAPPED(); - o.OffsetLow = (int)pos; - o.OffsetHigh = (int)(pos >> 32); - int result = UnlockFileEx(fs.get_SafeFileHandle(), 0, (int)size, (int)(size >> 32), o); - if (result == 0 && Marshal.GetLastWin32Error() != ERROR_NOT_LOCKED) - { - throw new IOException("Release failed"); - } - } - else - { - try - { - if (false) throw new cli.System.ArgumentOutOfRangeException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fs.Unlock(pos, size); - } - catch (cli.System.IO.IOException x) - { - if (!NotLockedHack.isErrorNotLocked(x)) - { - throw new IOException(x.getMessage()); - } - } - catch (cli.System.ArgumentOutOfRangeException - | cli.System.ObjectDisposedException x) - { - throw new IOException(x.getMessage()); - } - } - } - - static class NotLockedHack { - private static String msg; - static { - try { - File tmp = File.createTempFile("lock", null); - try (FileStream fs = new FileStream(tmp.getPath(), cli.System.IO.FileMode.wrap(cli.System.IO.FileMode.Create))) { - try { - if (false) throw new cli.System.IO.IOException(); - fs.Unlock(0, 1); - } catch (cli.System.IO.IOException x) { - msg = x.get_Message(); - } - } - tmp.delete(); - } catch (Throwable _) { - } - } - static boolean isErrorNotLocked(cli.System.IO.IOException x) { - return x.get_Message().equals(msg); - } - } - - - void close(FileDescriptor fd) throws IOException { - fd.close(); - } - - FileDescriptor duplicateForMapping(FileDescriptor fd) throws IOException { - // we return a dummy FileDescriptor, because we don't need it for mapping operations - // and we don't want the original to be closed - return new FileDescriptor(); - } - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native int LockFileEx(SafeFileHandle hFile, int dwFlags, int dwReserved, int nNumberOfBytesToLockLow, int nNumberOfBytesToLockHigh, OVERLAPPED lpOverlapped); - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native int UnlockFileEx(SafeFileHandle hFile, int dwReserved, int nNumberOfBytesToUnlockLow, int nNumberOfBytesToUnlockHigh, OVERLAPPED lpOverlapped); -} diff --git a/openjdk/sun/nio/ch/FileKey.java b/openjdk/sun/nio/ch/FileKey.java deleted file mode 100644 index 4feec5d3..00000000 --- a/openjdk/sun/nio/ch/FileKey.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.nio.ch; - -import java.io.File; -import java.io.FileDescriptor; -import java.io.IOException; - -public class FileKey -{ - private String path; - - public static FileKey create(FileDescriptor fd) - { - FileKey fk = new FileKey(); - fk.path = ((cli.System.IO.FileStream)fd.getStream()).get_Name(); - try - { - fk.path = new File(fk.path).getCanonicalPath(); - } - catch (IOException x) - { - } - return fk; - } - - public int hashCode() - { - return path.hashCode(); - } - - public boolean equals(Object obj) - { - return obj == this || (obj instanceof FileKey && ((FileKey)obj).path.equals(path)); - } -} diff --git a/openjdk/sun/nio/ch/IOUtil.java b/openjdk/sun/nio/ch/IOUtil.java deleted file mode 100644 index 38325371..00000000 --- a/openjdk/sun/nio/ch/IOUtil.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.*; -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.nio.channels.spi.*; - - -/** - * File-descriptor based I/O utilities that are shared by NIO classes. - */ - -class IOUtil { - - private IOUtil() { } // No instantiation - - static boolean randomBytes(byte[] someBytes) - { - try - { - if (false) throw new cli.System.Security.Cryptography.CryptographicException(); - cli.System.Security.Cryptography.RNGCryptoServiceProvider csp = new cli.System.Security.Cryptography.RNGCryptoServiceProvider(); - csp.GetBytes(someBytes); - return true; - } - catch (cli.System.Security.Cryptography.CryptographicException _) - { - return false; - } - } - - static void configureBlocking(FileDescriptor fd, boolean blocking) throws IOException - { - fd.setSocketBlocking(blocking); - } - - // this is a dummy method to allow us to use unmodified socket channel impls - static int fdVal(FileDescriptor fd) - { - return 0xbadc0de; - } - - static int read(FileDescriptor fd, ByteBuffer dst, long position, - NativeDispatcher nd, Object lock) - throws IOException - { - if (dst.isReadOnly()) - throw new IllegalArgumentException("Read-only buffer"); - - if (position != -1) - { - synchronized (lock) - { - long prevpos = fd.getFilePointer(); - try - { - fd.seek(position); - return read(fd, dst, -1, nd, null); - } - finally - { - fd.seek(prevpos); - } - } - } - - if (dst.hasArray()) - { - byte[] buf = dst.array(); - int len = nd.read(fd, buf, dst.arrayOffset() + dst.position(), dst.remaining()); - if (len > 0) - { - dst.position(dst.position() + len); - } - return len; - } - else - { - byte[] buf = new byte[dst.remaining()]; - int len = nd.read(fd, buf, 0, buf.length); - if (len > 0) - { - dst.put(buf, 0, len); - } - return len; - } - } - - static long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length, NativeDispatcher nd) - throws IOException - { - return nd.read(fd, bufs, offset, length); - } - - static int write(FileDescriptor fd, ByteBuffer src, long position, - NativeDispatcher nd, Object lock) - throws IOException - { - if (position != -1) - { - synchronized (lock) - { - long prevpos = fd.getFilePointer(); - try - { - fd.seek(position); - return write(fd, src, -1, nd, null); - } - finally - { - fd.seek(prevpos); - } - } - } - - if (src.hasArray()) - { - byte[] buf = src.array(); - int len = nd.write(fd, buf, src.arrayOffset() + src.position(), src.remaining()); - if (len > 0) - { - src.position(src.position() + len); - } - return len; - } - else - { - int pos = src.position(); - byte[] buf = new byte[src.remaining()]; - src.get(buf); - src.position(pos); - int len = nd.write(fd, buf, 0, buf.length); - if (len > 0) - { - src.position(pos + len); - } - return len; - } - } - - static long write(FileDescriptor fd, ByteBuffer[] bufs, NativeDispatcher nd) - throws IOException - { - return nd.write(fd, bufs, 0, bufs.length); - } - - static long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length, NativeDispatcher nd) - throws IOException - { - return nd.write(fd, bufs, offset, length); - } -} diff --git a/openjdk/sun/nio/ch/Iocp.java b/openjdk/sun/nio/ch/Iocp.java deleted file mode 100644 index b74b0a8f..00000000 --- a/openjdk/sun/nio/ch/Iocp.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.nio.channels.spi.AsynchronousChannelProvider; -import java.io.Closeable; -import java.io.IOException; -import java.io.FileDescriptor; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import ikvm.internal.NotYetImplementedError; - -/** - * Windows implementation of AsynchronousChannelGroup encapsulating an I/O - * completion port. - */ - -class Iocp extends AsynchronousChannelGroupImpl { - private static final boolean supportsThreadAgnosticIo; - - // true if port has been closed - private boolean closed; - - // the set of "stale" OVERLAPPED structures. These OVERLAPPED structures - // relate to I/O operations where the completion notification was not - // received in a timely manner after the channel is closed. - private final Set<Long> staleIoSet = new HashSet<Long>(); - - Iocp(AsynchronousChannelProvider provider, ThreadPool pool) - throws IOException - { - super(provider, pool); - } - - Iocp start() { - return this; - } - - /* - * Channels implements this interface support overlapped I/O and can be - * associated with a completion port. - */ - static interface OverlappedChannel extends Closeable { - /** - * Returns a reference to the pending I/O result. - */ - <V,A> PendingFuture<V,A> getByOverlapped(long overlapped); - } - - /** - * Indicates if this operating system supports thread agnostic I/O. - */ - static boolean supportsThreadAgnosticIo() { - return supportsThreadAgnosticIo; - } - - // release all resources - void implClose() { - synchronized (this) { - if (closed) - return; - closed = true; - } - } - - @Override - boolean isEmpty() { - return true; - } - - @Override - final Object attachForeignChannel(final Channel channel, FileDescriptor fdObj) - throws IOException - { - throw new NotYetImplementedError(); - } - - @Override - final void detachForeignChannel(Object key) { - throw new NotYetImplementedError(); - } - - @Override - void closeAllChannels() { - } - - @Override - void executeOnHandlerTask(Runnable task) { - throw new NotYetImplementedError(); - } - - @Override - void shutdownHandlerTasks() { - } - - /** - * The handler for consuming the result of an asynchronous I/O operation. - */ - static interface ResultHandler { - /** - * Invoked if the I/O operation completes successfully. - */ - public void completed(int bytesTransferred, boolean canInvokeDirect); - - /** - * Invoked if the I/O operation fails. - */ - public void failed(int error, IOException ioe); - } - - static { - supportsThreadAgnosticIo = true; - } -} diff --git a/openjdk/sun/nio/ch/NativeDispatcher.java b/openjdk/sun/nio/ch/NativeDispatcher.java deleted file mode 100644 index 7f523265..00000000 --- a/openjdk/sun/nio/ch/NativeDispatcher.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.nio.ByteBuffer; - -/** - * Allows different platforms to call different native methods - * for read and write operations. - */ - -abstract class NativeDispatcher -{ - abstract int read(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException; - - abstract int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException; - - abstract long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - abstract long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - abstract void close(FileDescriptor fd) throws IOException; - - // Prepare the given fd for closing by duping it to a known internal fd - // that's already closed. This is necessary on some operating systems - // (Solaris and Linux) to prevent fd recycling. - // - void preClose(FileDescriptor fd) throws IOException { - // Do nothing by default; this is only needed on Unix - } - -} diff --git a/openjdk/sun/nio/ch/Net.java b/openjdk/sun/nio/ch/Net.java deleted file mode 100644 index d9ab0f0f..00000000 --- a/openjdk/sun/nio/ch/Net.java +++ /dev/null @@ -1,609 +0,0 @@ -/* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.net.*; -import java.nio.channels.*; -import java.util.*; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; - - -class Net { // package-private - - private Net() { } - - // unspecified protocol family - static final ProtocolFamily UNSPEC = new ProtocolFamily() { - public String name() { - return "UNSPEC"; - } - }; - - // Value of jdk.net.revealLocalAddress - private static boolean revealLocalAddress; - - // True if jdk.net.revealLocalAddress had been read - private static volatile boolean propRevealLocalAddress; - - // set to true if exclusive binding is on for Windows - private static final boolean exclusiveBind; - - static { - int availLevel = isExclusiveBindAvailable(); - if (availLevel >= 0) { - String exclBindProp = - java.security.AccessController.doPrivileged( - new PrivilegedAction<String>() { - @Override - public String run() { - return System.getProperty( - "sun.net.useExclusiveBind"); - } - }); - if (exclBindProp != null) { - exclusiveBind = exclBindProp.length() == 0 ? - true : Boolean.parseBoolean(exclBindProp); - } else if (availLevel == 1) { - exclusiveBind = true; - } else { - exclusiveBind = false; - } - } else { - exclusiveBind = false; - } - } - - // -- Miscellaneous utilities -- - - private static volatile boolean checkedIPv6 = false; - private static volatile boolean isIPv6Available; - - /** - * Tells whether dual-IPv4/IPv6 sockets should be used. - */ - static boolean isIPv6Available() { - if (!checkedIPv6) { - isIPv6Available = isIPv6Available0(); - checkedIPv6 = true; - } - return isIPv6Available; - } - - /** - * Returns true if exclusive binding is on - */ - static boolean useExclusiveBind() { - return exclusiveBind; - } - - /** - * Tells whether IPv6 sockets can join IPv4 multicast groups - */ - static boolean canIPv6SocketJoinIPv4Group() { - return canIPv6SocketJoinIPv4Group0(); - } - - /** - * Tells whether {@link #join6} can be used to join an IPv4 - * multicast group (IPv4 group as IPv4-mapped IPv6 address) - */ - static boolean canJoin6WithIPv4Group() { - return canJoin6WithIPv4Group0(); - } - - static InetSocketAddress checkAddress(SocketAddress sa) { - if (sa == null) - throw new NullPointerException(); - if (!(sa instanceof InetSocketAddress)) - throw new UnsupportedAddressTypeException(); // ## needs arg - InetSocketAddress isa = (InetSocketAddress)sa; - if (isa.isUnresolved()) - throw new UnresolvedAddressException(); // ## needs arg - InetAddress addr = isa.getAddress(); - if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) - throw new IllegalArgumentException("Invalid address type"); - return isa; - } - - static InetSocketAddress asInetSocketAddress(SocketAddress sa) { - if (!(sa instanceof InetSocketAddress)) - throw new UnsupportedAddressTypeException(); - return (InetSocketAddress)sa; - } - - static void translateToSocketException(Exception x) - throws SocketException - { - if (x instanceof SocketException) - throw (SocketException)x; - Exception nx = x; - if (x instanceof ClosedChannelException) - nx = new SocketException("Socket is closed"); - else if (x instanceof NotYetConnectedException) - nx = new SocketException("Socket is not connected"); - else if (x instanceof AlreadyBoundException) - nx = new SocketException("Already bound"); - else if (x instanceof NotYetBoundException) - nx = new SocketException("Socket is not bound yet"); - else if (x instanceof UnsupportedAddressTypeException) - nx = new SocketException("Unsupported address type"); - else if (x instanceof UnresolvedAddressException) { - nx = new SocketException("Unresolved address"); - } - if (nx != x) - nx.initCause(x); - - if (nx instanceof SocketException) - throw (SocketException)nx; - else if (nx instanceof RuntimeException) - throw (RuntimeException)nx; - else - throw new Error("Untranslated exception", nx); - } - - static void translateException(Exception x, - boolean unknownHostForUnresolved) - throws IOException - { - if (x instanceof IOException) - throw (IOException)x; - // Throw UnknownHostException from here since it cannot - // be thrown as a SocketException - if (unknownHostForUnresolved && - (x instanceof UnresolvedAddressException)) - { - throw new UnknownHostException(); - } - translateToSocketException(x); - } - - static void translateException(Exception x) - throws IOException - { - translateException(x, false); - } - - /** - * Returns the local address after performing a SecurityManager#checkConnect. - */ - static InetSocketAddress getRevealedLocalAddress(InetSocketAddress addr) { - SecurityManager sm = System.getSecurityManager(); - if (addr == null || sm == null) - return addr; - - if (!getRevealLocalAddress()) { - // Return loopback address only if security check fails - try{ - sm.checkConnect(addr.getAddress().getHostAddress(), -1); - //Security check passed - } catch (SecurityException e) { - //Return loopback address - addr = getLoopbackAddress(addr.getPort()); - } - } - return addr; - } - - static String getRevealedLocalAddressAsString(InetSocketAddress addr) { - if (!getRevealLocalAddress() && System.getSecurityManager() != null) - addr = getLoopbackAddress(addr.getPort()); - return addr.toString(); - } - - private static boolean getRevealLocalAddress() { - if (!propRevealLocalAddress) { - try { - revealLocalAddress = Boolean.parseBoolean( - AccessController.doPrivileged( - new PrivilegedExceptionAction<String>() { - public String run() { - return System.getProperty( - "jdk.net.revealLocalAddress"); - } - })); - - } catch (Exception e) { - // revealLocalAddress is false - } - propRevealLocalAddress = true; - } - return revealLocalAddress; - } - - private static InetSocketAddress getLoopbackAddress(int port) { - return new InetSocketAddress(InetAddress.getLoopbackAddress(), - port); - } - - /** - * Returns any IPv4 address of the given network interface, or - * null if the interface does not have any IPv4 addresses. - */ - static Inet4Address anyInet4Address(final NetworkInterface interf) { - return AccessController.doPrivileged(new PrivilegedAction<Inet4Address>() { - public Inet4Address run() { - Enumeration<InetAddress> addrs = interf.getInetAddresses(); - while (addrs.hasMoreElements()) { - InetAddress addr = addrs.nextElement(); - if (addr instanceof Inet4Address) { - return (Inet4Address)addr; - } - } - return null; - } - }); - } - - /** - * Returns an IPv4 address as an int. - */ - static int inet4AsInt(InetAddress ia) { - if (ia instanceof Inet4Address) { - byte[] addr = ia.getAddress(); - int address = addr[3] & 0xFF; - address |= ((addr[2] << 8) & 0xFF00); - address |= ((addr[1] << 16) & 0xFF0000); - address |= ((addr[0] << 24) & 0xFF000000); - return address; - } - throw new AssertionError("Should not reach here"); - } - - /** - * Returns an InetAddress from the given IPv4 address - * represented as an int. - */ - static InetAddress inet4FromInt(int address) { - byte[] addr = new byte[4]; - addr[0] = (byte) ((address >>> 24) & 0xFF); - addr[1] = (byte) ((address >>> 16) & 0xFF); - addr[2] = (byte) ((address >>> 8) & 0xFF); - addr[3] = (byte) (address & 0xFF); - try { - return InetAddress.getByAddress(addr); - } catch (UnknownHostException uhe) { - throw new AssertionError("Should not reach here"); - } - } - - /** - * Returns an IPv6 address as a byte array - */ - static byte[] inet6AsByteArray(InetAddress ia) { - if (ia instanceof Inet6Address) { - return ia.getAddress(); - } - - // need to construct IPv4-mapped address - if (ia instanceof Inet4Address) { - byte[] ip4address = ia.getAddress(); - byte[] address = new byte[16]; - address[10] = (byte)0xff; - address[11] = (byte)0xff; - address[12] = ip4address[0]; - address[13] = ip4address[1]; - address[14] = ip4address[2]; - address[15] = ip4address[3]; - return address; - } - - throw new AssertionError("Should not reach here"); - } - - // -- Socket options - - static void setSocketOption(FileDescriptor fd, ProtocolFamily family, - SocketOption<?> name, Object value) - throws IOException - { - if (value == null) - throw new IllegalArgumentException("Invalid option value"); - - // only simple values supported by this method - Class<?> type = name.type(); - if (type != Integer.class && type != Boolean.class) - throw new AssertionError("Should not reach here"); - - // special handling - if (name == StandardSocketOptions.SO_RCVBUF || - name == StandardSocketOptions.SO_SNDBUF) - { - int i = ((Integer)value).intValue(); - if (i < 0) - throw new IllegalArgumentException("Invalid send/receive buffer size"); - } - if (name == StandardSocketOptions.SO_LINGER) { - int i = ((Integer)value).intValue(); - if (i < 0) - value = Integer.valueOf(-1); - if (i > 65535) - value = Integer.valueOf(65535); - } - if (name == StandardSocketOptions.IP_TOS) { - int i = ((Integer)value).intValue(); - if (i < 0 || i > 255) - throw new IllegalArgumentException("Invalid IP_TOS value"); - } - if (name == StandardSocketOptions.IP_MULTICAST_TTL) { - int i = ((Integer)value).intValue(); - if (i < 0 || i > 255) - throw new IllegalArgumentException("Invalid TTL/hop value"); - } - - // map option name to platform level/name - OptionKey key = SocketOptionRegistry.findOption(name, family); - if (key == null) - throw new AssertionError("Option not found"); - - int arg; - if (type == Integer.class) { - arg = ((Integer)value).intValue(); - } else { - boolean b = ((Boolean)value).booleanValue(); - arg = (b) ? 1 : 0; - } - - boolean mayNeedConversion = (family == UNSPEC); - setIntOption0(fd, mayNeedConversion, key.level(), key.name(), arg); - } - - static Object getSocketOption(FileDescriptor fd, ProtocolFamily family, - SocketOption<?> name) - throws IOException - { - Class<?> type = name.type(); - - // only simple values supported by this method - if (type != Integer.class && type != Boolean.class) - throw new AssertionError("Should not reach here"); - - // map option name to platform level/name - OptionKey key = SocketOptionRegistry.findOption(name, family); - if (key == null) - throw new AssertionError("Option not found"); - - boolean mayNeedConversion = (family == UNSPEC); - int value = getIntOption0(fd, mayNeedConversion, key.level(), key.name()); - - if (type == Integer.class) { - return Integer.valueOf(value); - } else { - return (value == 0) ? Boolean.FALSE : Boolean.TRUE; - } - } - - // -- Socket operations -- - - private static native boolean isIPv6Available0(); - - /* - * Returns 1 for Windows versions that support exclusive binding by default, 0 - * for those that do not, and -1 for Solaris/Linux/Mac OS - */ - private static native int isExclusiveBindAvailable(); - - private static native boolean canIPv6SocketJoinIPv4Group0(); - - private static native boolean canJoin6WithIPv4Group0(); - - static FileDescriptor socket(boolean stream) throws IOException { - return socket(UNSPEC, stream); - } - - static FileDescriptor socket(ProtocolFamily family, boolean stream) - throws IOException { - boolean preferIPv6 = isIPv6Available() && - (family != StandardProtocolFamily.INET); - return socket0(preferIPv6, stream, false); - } - - static FileDescriptor serverSocket(boolean stream) { - return socket0(isIPv6Available(), stream, true); - } - - // Due to oddities SO_REUSEADDR on windows reuse is ignored - private static native FileDescriptor socket0(boolean preferIPv6, boolean stream, boolean reuse); - - static void bind(FileDescriptor fd, InetAddress addr, int port) - throws IOException - { - bind(UNSPEC, fd, addr, port); - } - - static void bind(ProtocolFamily family, FileDescriptor fd, - InetAddress addr, int port) throws IOException - { - boolean preferIPv6 = isIPv6Available() && - (family != StandardProtocolFamily.INET); - bind0(fd, preferIPv6, exclusiveBind, addr, port); - } - - private static native void bind0(FileDescriptor fd, boolean preferIPv6, - boolean useExclBind, InetAddress addr, - int port) - throws IOException; - - static native void listen(FileDescriptor fd, int backlog) throws IOException; - - static int connect(FileDescriptor fd, InetAddress remote, int remotePort) - throws IOException - { - return connect(UNSPEC, fd, remote, remotePort); - } - - static int connect(ProtocolFamily family, FileDescriptor fd, InetAddress remote, int remotePort) - throws IOException - { - boolean preferIPv6 = isIPv6Available() && - (family != StandardProtocolFamily.INET); - return connect0(preferIPv6, fd, remote, remotePort); - } - - private static native int connect0(boolean preferIPv6, - FileDescriptor fd, - InetAddress remote, - int remotePort) - throws IOException; - - - public final static int SHUT_RD = 0; - public final static int SHUT_WR = 1; - public final static int SHUT_RDWR = 2; - - static native void shutdown(FileDescriptor fd, int how) throws IOException; - - private static native int localPort(FileDescriptor fd) - throws IOException; - - private static native InetAddress localInetAddress(FileDescriptor fd) - throws IOException; - - static InetSocketAddress localAddress(FileDescriptor fd) - throws IOException - { - return new InetSocketAddress(localInetAddress(fd), localPort(fd)); - } - - private static native int remotePort(FileDescriptor fd) - throws IOException; - - private static native InetAddress remoteInetAddress(FileDescriptor fd) - throws IOException; - - static InetSocketAddress remoteAddress(FileDescriptor fd) - throws IOException - { - return new InetSocketAddress(remoteInetAddress(fd), remotePort(fd)); - } - - private static native int getIntOption0(FileDescriptor fd, boolean mayNeedConversion, - int level, int opt) - throws IOException; - - private static native void setIntOption0(FileDescriptor fd, boolean mayNeedConversion, - int level, int opt, int arg) - throws IOException; - - // -- Multicast support -- - - - /** - * Join IPv4 multicast group - */ - static int join4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - return joinOrDrop4(true, fd, group, interf, source); - } - - /** - * Drop membership of IPv4 multicast group - */ - static void drop4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - joinOrDrop4(false, fd, group, interf, source); - } - - private static native int joinOrDrop4(boolean join, FileDescriptor fd, int group, int interf, int source) - throws IOException; - - /** - * Block IPv4 source - */ - static int block4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - return blockOrUnblock4(true, fd, group, interf, source); - } - - /** - * Unblock IPv6 source - */ - static void unblock4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - blockOrUnblock4(false, fd, group, interf, source); - } - - private static native int blockOrUnblock4(boolean block, FileDescriptor fd, int group, - int interf, int source) - throws IOException; - - /** - * Join IPv6 multicast group - */ - static int join6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - return joinOrDrop6(true, fd, group, index, source); - } - - /** - * Drop membership of IPv6 multicast group - */ - static void drop6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - joinOrDrop6(false, fd, group, index, source); - } - - private static native int joinOrDrop6(boolean join, FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException; - - /** - * Block IPv6 source - */ - static int block6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - return blockOrUnblock6(true, fd, group, index, source); - } - - /** - * Unblock IPv6 source - */ - static void unblock6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - blockOrUnblock6(false, fd, group, index, source); - } - - static native int blockOrUnblock6(boolean block, FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException; - - static native void setInterface4(FileDescriptor fd, int interf) throws IOException; - - static native int getInterface4(FileDescriptor fd) throws IOException; - - static native void setInterface6(FileDescriptor fd, int index) throws IOException; - - static native int getInterface6(FileDescriptor fd) throws IOException; - -} diff --git a/openjdk/sun/nio/ch/PollArrayWrapper.java b/openjdk/sun/nio/ch/PollArrayWrapper.java deleted file mode 100644 index 72ed9adc..00000000 --- a/openjdk/sun/nio/ch/PollArrayWrapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -class PollArrayWrapper -{ - static final short POLLIN = 0x0001; - static final short POLLCONN = 0x0002; - static final short POLLOUT = 0x0004; - static final short POLLERR = 0x0008; - static final short POLLHUP = 0x0010; - static final short POLLNVAL = 0x0020; - static final short POLLREMOVE = 0x0800; -} diff --git a/openjdk/sun/nio/ch/SelectionKeyImpl.java b/openjdk/sun/nio/ch/SelectionKeyImpl.java deleted file mode 100644 index 5edc3005..00000000 --- a/openjdk/sun/nio/ch/SelectionKeyImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright (C) 2002, 2003, 2004, 2005, 2006 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.nio.ch; - -import java.nio.channels.CancelledKeyException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.AbstractSelectionKey; - -final class SelectionKeyImpl extends AbstractSelectionKey -{ - final SelChImpl channel; - final SelectorImpl selector; - private final cli.System.Net.Sockets.Socket socket; - private int readyOps; - private volatile int interestOps; - - SelectionKeyImpl(SelChImpl ch, SelectorImpl sel) - { - this.channel = ch; - this.selector = sel; - socket = ch.getFD().getSocket(); - } - - public SelectableChannel channel() - { - return (SelectableChannel)channel; - } - - public int readyOps() - { - if (!isValid()) - throw new CancelledKeyException(); - - return readyOps; - } - - void readyOps(int ops) - { - readyOps = ops; - } - - public synchronized int interestOps() - { - if (!isValid()) - throw new CancelledKeyException(); - - return interestOps; - } - - public synchronized SelectionKey interestOps(int ops) - { - if (!isValid()) - throw new CancelledKeyException(); - - if ((ops & ~channel.validOps()) != 0) - throw new IllegalArgumentException(); - - interestOps = ops; - return this; - } - - public Selector selector() - { - return selector; - } - - cli.System.Net.Sockets.Socket getSocket() - { - return socket; - } - - void nioReadyOps(int ops) - { - readyOps = ops; - } - - int nioReadyOps() - { - return readyOps; - } - - int nioInterestOps() - { - return interestOps; - } - - SelectionKey nioInterestOps(int ops) - { - if ((ops & ~channel().validOps()) != 0) - throw new IllegalArgumentException(); - channel.translateAndSetInterestOps(ops, this); - interestOps = ops; - return this; - } -} diff --git a/openjdk/sun/nio/ch/SocketDispatcher.java b/openjdk/sun/nio/ch/SocketDispatcher.java deleted file mode 100644 index 7d408326..00000000 --- a/openjdk/sun/nio/ch/SocketDispatcher.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.net.SocketException; -import java.net.SocketUtil; -import java.nio.ByteBuffer; -import cli.System.Net.Sockets.SocketFlags; - -/** - * Allows different platforms to call different native methods - * for read and write operations. - */ - -class SocketDispatcher extends NativeDispatcher -{ - int read(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - if (length == 0) - { - return 0; - } - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - int read = fd.getSocket().Receive(buf, offset, length, SocketFlags.wrap(SocketFlags.None)); - return read == 0 ? IOStatus.EOF : read; - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == SocketUtil.WSAESHUTDOWN) - { - // the socket was shutdown, so we have to return EOF - return IOStatus.EOF; - } - else if (x.get_ErrorCode() == SocketUtil.WSAEWOULDBLOCK) - { - // nothing to read and would block - return IOStatus.UNAVAILABLE; - } - throw SocketUtil.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } - } - - int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - return fd.getSocket().Send(buf, offset, length, SocketFlags.wrap(SocketFlags.None)); - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == SocketUtil.WSAEWOULDBLOCK) - { - return IOStatus.UNAVAILABLE; - } - throw SocketUtil.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } - } - - native long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - native long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - void close(FileDescriptor fd) throws IOException { - } - - void preClose(FileDescriptor fd) throws IOException { - closeImpl(fd); - } - - static void closeImpl(FileDescriptor fd) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Close(); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw java.net.SocketUtil.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new java.net.SocketException("Socket is closed"); - } - } -} diff --git a/openjdk/sun/nio/ch/SocketOptionRegistry.java b/openjdk/sun/nio/ch/SocketOptionRegistry.java deleted file mode 100644 index 83887fbc..00000000 --- a/openjdk/sun/nio/ch/SocketOptionRegistry.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - */ - -package sun.nio.ch; -import java.net.SocketOption; -import java.net.StandardSocketOptions; -import java.net.ProtocolFamily; -import java.net.StandardProtocolFamily; -import java.util.Map; -import java.util.HashMap; -import cli.System.Net.Sockets.SocketOptionLevel; -import cli.System.Net.Sockets.SocketOptionName; - -class SocketOptionRegistry { - private SocketOptionRegistry() { } - private static class RegistryKey { - private final SocketOption<?> name; - private final ProtocolFamily family; - RegistryKey(SocketOption<?> name, ProtocolFamily family) { - this.name = name; - this.family = family; - } - public int hashCode() { - return name.hashCode() + family.hashCode(); - } - public boolean equals(Object ob) { - if (ob == null) return false; - if (!(ob instanceof RegistryKey)) return false; - RegistryKey other = (RegistryKey)ob; - if (this.name != other.name) return false; - if (this.family != other.family) return false; - return true; - } - } - private static class LazyInitialization { - static final Map<RegistryKey,OptionKey> options = options(); - private static Map<RegistryKey,OptionKey> options() { - Map<RegistryKey,OptionKey> map = - new HashMap<RegistryKey,OptionKey>(); - map.put(new RegistryKey(StandardSocketOptions.SO_BROADCAST, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.Broadcast)); - map.put(new RegistryKey(StandardSocketOptions.SO_KEEPALIVE, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.KeepAlive)); - map.put(new RegistryKey(StandardSocketOptions.SO_LINGER, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.Linger)); - map.put(new RegistryKey(StandardSocketOptions.SO_SNDBUF, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)); - map.put(new RegistryKey(StandardSocketOptions.SO_RCVBUF, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)); - map.put(new RegistryKey(StandardSocketOptions.SO_REUSEADDR, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress)); - map.put(new RegistryKey(StandardSocketOptions.TCP_NODELAY, Net.UNSPEC), new OptionKey(SocketOptionLevel.Tcp, SocketOptionName.NoDelay)); - map.put(new RegistryKey(StandardSocketOptions.IP_TOS, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.TypeOfService)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_IF, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.MulticastInterface)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_TTL, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_LOOP, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_IF, StandardProtocolFamily.INET6), new OptionKey(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_TTL, StandardProtocolFamily.INET6), new OptionKey(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_LOOP, StandardProtocolFamily.INET6), new OptionKey(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)); - map.put(new RegistryKey(ExtendedSocketOption.SO_OOBINLINE, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline)); - return map; - } - } - public static OptionKey findOption(SocketOption<?> name, ProtocolFamily family) { - RegistryKey key = new RegistryKey(name, family); - return LazyInitialization.options.get(key); - } -} diff --git a/openjdk/sun/nio/ch/Util.java b/openjdk/sun/nio/ch/Util.java deleted file mode 100644 index 475c1b9b..00000000 --- a/openjdk/sun/nio/ch/Util.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.lang.ref.SoftReference; -import java.lang.reflect.*; -import java.io.IOException; -import java.io.FileDescriptor; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.*; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.*; -import sun.misc.Unsafe; -import sun.misc.Cleaner; -import sun.security.action.GetPropertyAction; - - -class Util { - - private static class SelectorWrapper { - private Selector sel; - private SelectorWrapper (Selector sel) { - this.sel = sel; - Cleaner.create(this, new Closer(sel)); - } - private static class Closer implements Runnable { - private Selector sel; - private Closer (Selector sel) { - this.sel = sel; - } - public void run () { - try { - sel.close(); - } catch (Throwable th) { - throw new Error(th); - } - } - } - public Selector get() { return sel;} - } - - // Per-thread cached selector - private static ThreadLocal<SoftReference<SelectorWrapper>> localSelector - = new ThreadLocal<SoftReference<SelectorWrapper>>(); - // Hold a reference to the selWrapper object to prevent it from - // being cleaned when the temporary selector wrapped is on lease. - private static ThreadLocal<SelectorWrapper> localSelectorWrapper - = new ThreadLocal<SelectorWrapper>(); - - // When finished, invoker must ensure that selector is empty - // by cancelling any related keys and explicitly releasing - // the selector by invoking releaseTemporarySelector() - static Selector getTemporarySelector(SelectableChannel sc) - throws IOException - { - SoftReference<SelectorWrapper> ref = localSelector.get(); - SelectorWrapper selWrapper = null; - Selector sel = null; - if (ref == null - || ((selWrapper = ref.get()) == null) - || ((sel = selWrapper.get()) == null) - || (sel.provider() != sc.provider())) { - sel = sc.provider().openSelector(); - selWrapper = new SelectorWrapper(sel); - localSelector.set(new SoftReference<SelectorWrapper>(selWrapper)); - } - localSelectorWrapper.set(selWrapper); - return sel; - } - - static void releaseTemporarySelector(Selector sel) - throws IOException - { - // Selector should be empty - sel.selectNow(); // Flush cancelled keys - assert sel.keys().isEmpty() : "Temporary selector not empty"; - localSelectorWrapper.set(null); - } - - - // -- Random stuff -- - - static ByteBuffer[] subsequence(ByteBuffer[] bs, int offset, int length) { - if ((offset == 0) && (length == bs.length)) - return bs; - int n = length; - ByteBuffer[] bs2 = new ByteBuffer[n]; - for (int i = 0; i < n; i++) - bs2[i] = bs[offset + i]; - return bs2; - } - - static <E> Set<E> ungrowableSet(final Set<E> s) { - return new Set<E>() { - - public int size() { return s.size(); } - public boolean isEmpty() { return s.isEmpty(); } - public boolean contains(Object o) { return s.contains(o); } - public Object[] toArray() { return s.toArray(); } - public <T> T[] toArray(T[] a) { return s.toArray(a); } - public String toString() { return s.toString(); } - public Iterator<E> iterator() { return s.iterator(); } - public boolean equals(Object o) { return s.equals(o); } - public int hashCode() { return s.hashCode(); } - public void clear() { s.clear(); } - public boolean remove(Object o) { return s.remove(o); } - - public boolean containsAll(Collection<?> coll) { - return s.containsAll(coll); - } - public boolean removeAll(Collection<?> coll) { - return s.removeAll(coll); - } - public boolean retainAll(Collection<?> coll) { - return s.retainAll(coll); - } - - public boolean add(E o){ - throw new UnsupportedOperationException(); - } - public boolean addAll(Collection<? extends E> coll) { - throw new UnsupportedOperationException(); - } - - }; - } - - - private static volatile Constructor directByteBufferConstructor = null; - - private static void initDBBConstructor() { - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - try { - Class<?> cl = Class.forName("java.nio.DirectByteBuffer"); - Constructor ctor = cl.getDeclaredConstructor( - new Class[] { int.class, - long.class, - FileDescriptor.class, - Runnable.class }); - ctor.setAccessible(true); - directByteBufferConstructor = ctor; - } catch (ClassNotFoundException x) { - throw new InternalError(); - } catch (NoSuchMethodException x) { - throw new InternalError(); - } catch (IllegalArgumentException x) { - throw new InternalError(); - } catch (ClassCastException x) { - throw new InternalError(); - } - return null; - }}); - } - - static MappedByteBuffer newMappedByteBuffer(int size, long addr, - FileDescriptor fd, - Runnable unmapper) - { - MappedByteBuffer dbb; - if (directByteBufferConstructor == null) - initDBBConstructor(); - try { - dbb = (MappedByteBuffer)directByteBufferConstructor.newInstance( - new Object[] { new Integer(size), - new Long(addr), - fd, - unmapper }); - } catch (InstantiationException e) { - throw new InternalError(); - } catch (IllegalAccessException e) { - throw new InternalError(); - } catch (InvocationTargetException e) { - throw new InternalError(); - } - return dbb; - } - - private static volatile Constructor directByteBufferRConstructor = null; - - private static void initDBBRConstructor() { - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - try { - Class<?> cl = Class.forName("java.nio.DirectByteBufferR"); - Constructor ctor = cl.getDeclaredConstructor( - new Class[] { int.class, - long.class, - FileDescriptor.class, - Runnable.class }); - ctor.setAccessible(true); - directByteBufferRConstructor = ctor; - } catch (ClassNotFoundException x) { - throw new InternalError(); - } catch (NoSuchMethodException x) { - throw new InternalError(); - } catch (IllegalArgumentException x) { - throw new InternalError(); - } catch (ClassCastException x) { - throw new InternalError(); - } - return null; - }}); - } - - static MappedByteBuffer newMappedByteBufferR(int size, long addr, - FileDescriptor fd, - Runnable unmapper) - { - MappedByteBuffer dbb; - if (directByteBufferRConstructor == null) - initDBBRConstructor(); - try { - dbb = (MappedByteBuffer)directByteBufferRConstructor.newInstance( - new Object[] { new Integer(size), - new Long(addr), - fd, - unmapper }); - } catch (InstantiationException e) { - throw new InternalError(); - } catch (IllegalAccessException e) { - throw new InternalError(); - } catch (InvocationTargetException e) { - throw new InternalError(); - } - return dbb; - } - - - // -- Bug compatibility -- - - private static volatile String bugLevel = null; - - static boolean atBugLevel(String bl) { // package-private - if (bugLevel == null) { - if (!sun.misc.VM.isBooted()) - return false; - String value = AccessController.doPrivileged( - new GetPropertyAction("sun.nio.ch.bugLevel")); - bugLevel = (value != null) ? value : ""; - } - return bugLevel.equals(bl); - } - - - - // -- Initialization -- - - - static void load() { - } - -} diff --git a/openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java b/openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java deleted file mode 100644 index 4b96dfac..00000000 --- a/openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java +++ /dev/null @@ -1,689 +0,0 @@ -/* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.util.concurrent.*; -import java.nio.ByteBuffer; -import java.nio.BufferOverflowException; -import java.io.IOException; -import java.io.FileDescriptor; -import cli.System.AsyncCallback; -import cli.System.IAsyncResult; -import cli.System.IO.FileStream; -import cli.System.IO.SeekOrigin; - -/** - * Windows implementation of AsynchronousFileChannel using overlapped I/O. - */ - -public class WindowsAsynchronousFileChannelImpl - extends AsynchronousFileChannelImpl - implements Groupable -{ - // error when EOF is detected asynchronously. - private static final int ERROR_HANDLE_EOF = 38; - - // Lazy initialization of default I/O completion port - private static class DefaultIocpHolder { - static final Iocp defaultIocp = defaultIocp(); - private static Iocp defaultIocp() { - try { - return new Iocp(null, ThreadPool.createDefault()).start(); - } catch (IOException ioe) { - InternalError e = new InternalError(); - e.initCause(ioe); - throw e; - } - } - } - - // Used for force/truncate/size methods - private static final FileDispatcher nd = new FileDispatcherImpl(); - - // I/O completion port (group) - private final Iocp iocp; - - private final boolean isDefaultIocp; - - - private WindowsAsynchronousFileChannelImpl(FileDescriptor fdObj, - boolean reading, - boolean writing, - Iocp iocp, - boolean isDefaultIocp) - throws IOException - { - super(fdObj, reading, writing, iocp.executor()); - this.iocp = iocp; - this.isDefaultIocp = isDefaultIocp; - } - - public static AsynchronousFileChannel open(FileDescriptor fdo, - boolean reading, - boolean writing, - ThreadPool pool) - throws IOException - { - Iocp iocp; - boolean isDefaultIocp; - if (pool == null) { - iocp = DefaultIocpHolder.defaultIocp; - isDefaultIocp = true; - } else { - iocp = new Iocp(null, pool).start(); - isDefaultIocp = false; - } - try { - return new - WindowsAsynchronousFileChannelImpl(fdo, reading, writing, iocp, isDefaultIocp); - } catch (IOException x) { - // error binding to port so need to close it (if created for this channel) - if (!isDefaultIocp) - iocp.implClose(); - throw x; - } - } - - @Override - public void close() throws IOException { - closeLock.writeLock().lock(); - try { - if (closed) - return; // already closed - closed = true; - } finally { - closeLock.writeLock().unlock(); - } - - // invalidate all locks held for this channel - invalidateAllLocks(); - - // close the file - fdObj.close(); - - // for the non-default group close the port - if (!isDefaultIocp) - iocp.detachFromThreadPool(); - } - - @Override - public AsynchronousChannelGroupImpl group() { - return iocp; - } - - /** - * Translates Throwable to IOException - */ - private static IOException toIOException(Throwable x) { - if (x instanceof cli.System.ArgumentException) { - return new IOException(x.getMessage()); - } - if (x instanceof cli.System.IO.IOException) { - return new IOException(x.getMessage()); - } - if (x instanceof IOException) { - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - return (IOException)x; - } - return new IOException(x); - } - - @Override - public long size() throws IOException { - try { - begin(); - return nd.size(fdObj); - } finally { - end(); - } - } - - @Override - public AsynchronousFileChannel truncate(long size) throws IOException { - if (size < 0) - throw new IllegalArgumentException("Negative size"); - if (!writing) - throw new NonWritableChannelException(); - try { - begin(); - if (size > nd.size(fdObj)) - return this; - nd.truncate(fdObj, size); - } finally { - end(); - } - return this; - } - - @Override - public void force(boolean metaData) throws IOException { - try { - begin(); - nd.force(fdObj, metaData); - } finally { - end(); - } - } - - // -- file locking -- - - /** - * Task that initiates locking operation and handles completion result. - */ - private class LockTask<A> implements Runnable, Iocp.ResultHandler { - private final long position; - private final FileLockImpl fli; - private final PendingFuture<FileLock,A> result; - - LockTask(long position, - FileLockImpl fli, - PendingFuture<FileLock,A> result) - { - this.position = position; - this.fli = fli; - this.result = result; - } - - @Override - public void run() { - FileStream fs = (FileStream)fdObj.getStream(); - for (;;) { - try { - begin(); - - try { - if (false) throw new cli.System.IO.IOException(); - fs.Lock(position, fli.size()); - result.setResult(fli); - break; - } catch (cli.System.IO.IOException _) { - // we failed to acquire the lock, try again next iteration - } - } catch (Throwable x) { - // lock failed or channel closed - removeFromFileLockTable(fli); - result.setFailure(toIOException(x)); - } finally { - end(); - } - cli.System.Threading.Thread.Sleep(100); - } - - // invoke completion handler - Invoker.invoke(result); - } - - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - // release waiters and invoke completion handler - result.setResult(fli); - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // lock not acquired so remove from lock table - removeFromFileLockTable(fli); - - // release waiters - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - - @Override - <A> Future<FileLock> implLock(final long position, - final long size, - final boolean shared, - A attachment, - final CompletionHandler<FileLock,? super A> handler) - { - if (shared && !reading) - throw new NonReadableChannelException(); - if (!shared && !writing) - throw new NonWritableChannelException(); - - // add to lock table - FileLockImpl fli = addToFileLockTable(position, size, shared); - if (fli == null) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - // create Future and task that will be invoked to acquire lock - PendingFuture<FileLock,A> result = - new PendingFuture<FileLock,A>(this, handler, attachment); - LockTask lockTask = new LockTask<A>(position, fli, result); - result.setContext(lockTask); - - // initiate I/O - if (false) { - lockTask.run(); - } else { - boolean executed = false; - try { - Invoker.invokeOnThreadInThreadPool(this, lockTask); - executed = true; - } finally { - if (!executed) { - // rollback - removeFromFileLockTable(fli); - } - } - } - return result; - } - - static final int NO_LOCK = -1; // Failed to lock - static final int LOCKED = 0; // Obtained requested lock - - @Override - public FileLock tryLock(long position, long size, boolean shared) - throws IOException - { - if (shared && !reading) - throw new NonReadableChannelException(); - if (!shared && !writing) - throw new NonWritableChannelException(); - - // add to lock table - final FileLockImpl fli = addToFileLockTable(position, size, shared); - if (fli == null) - throw new ClosedChannelException(); - - boolean gotLock = false; - try { - begin(); - // try to acquire the lock - int res; - try { - if (false) throw new cli.System.IO.IOException(); - FileStream fs = (FileStream)fdObj.getStream(); - fs.Lock(position, size); - res = LOCKED; - } catch (cli.System.IO.IOException _) { - res = NO_LOCK; - } - if (res == NO_LOCK) - return null; - gotLock = true; - return fli; - } finally { - if (!gotLock) - removeFromFileLockTable(fli); - end(); - } - } - - @Override - protected void implRelease(FileLockImpl fli) throws IOException { - try { - if (false) throw new cli.System.IO.IOException(); - FileStream fs = (FileStream)fdObj.getStream(); - fs.Unlock(fli.position(), fli.size()); - } catch (cli.System.IO.IOException x) { - if (!FileDispatcherImpl.NotLockedHack.isErrorNotLocked(x)) { - throw new IOException(x.getMessage()); - } - } - } - - /** - * Task that initiates read operation and handles completion result. - */ - private class ReadTask<A> implements Runnable, Iocp.ResultHandler, AsyncCallback.Method { - private final ByteBuffer dst; - private final int pos, rem; // buffer position/remaining - private final long position; // file position - private final PendingFuture<Integer,A> result; - - // set to dst if direct; otherwise set to substituted direct buffer - private volatile ByteBuffer buf; - - ReadTask(ByteBuffer dst, - int pos, - int rem, - long position, - PendingFuture<Integer,A> result) - { - this.dst = dst; - this.pos = pos; - this.rem = rem; - this.position = position; - this.result = result; - } - - void updatePosition(int bytesTransferred) { - // if the I/O succeeded then adjust buffer position - if (bytesTransferred > 0) { - if (buf == dst) { - try { - dst.position(pos + bytesTransferred); - } catch (IllegalArgumentException x) { - // someone has changed the position; ignore - } - } else { - // had to substitute direct buffer - buf.position(bytesTransferred).flip(); - try { - dst.put(buf); - } catch (BufferOverflowException x) { - // someone has changed the position; ignore - } - } - } - } - - @Override - public void run() { - // Substitute an array backed buffer if not - if (dst.hasArray()) { - buf = dst; - } else { - buf = ByteBuffer.allocate(rem); - } - - try { - begin(); - - // initiate read - FileStream fs = (FileStream)fdObj.getStream(); - fs.Seek(position, SeekOrigin.wrap(SeekOrigin.Begin)); - fs.BeginRead(buf.array(), buf.arrayOffset() + pos, rem, new AsyncCallback(this), null); - return; - - } catch (Throwable x) { - // failed to initiate read - result.setFailure(toIOException(x)); - } finally { - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - public void Invoke(IAsyncResult ar) { - try { - FileStream fs = (FileStream)fdObj.getStream(); - completed(fs.EndRead(ar), false); - } catch (Throwable x) { - failed(0, toIOException(x)); - } - } - - /** - * Executed when the I/O has completed - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - updatePosition(bytesTransferred); - - // release waiters and invoke completion handler - result.setResult(bytesTransferred); - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // if EOF detected asynchronously then it is reported as error - if (error == ERROR_HANDLE_EOF) { - completed(-1, false); - } else { - // release waiters - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - } - - @Override - <A> Future<Integer> implRead(ByteBuffer dst, - long position, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - if (!reading) - throw new NonReadableChannelException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (dst.isReadOnly()) - throw new IllegalArgumentException("Read-only buffer"); - - // check if channel is closed - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - int pos = dst.position(); - int lim = dst.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - // no space remaining - if (rem == 0) { - if (handler == null) - return CompletedFuture.withResult(0); - Invoker.invoke(this, handler, attachment, 0, null); - return null; - } - - // create Future and task that initiates read - PendingFuture<Integer,A> result = - new PendingFuture<Integer,A>(this, handler, attachment); - ReadTask readTask = new ReadTask<A>(dst, pos, rem, position, result); - result.setContext(readTask); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - readTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, readTask); - } - return result; - } - - /** - * Task that initiates write operation and handles completion result. - */ - private class WriteTask<A> implements Runnable, Iocp.ResultHandler, AsyncCallback.Method { - private final ByteBuffer src; - private final int pos, rem; // buffer position/remaining - private final long position; // file position - private final PendingFuture<Integer,A> result; - - // set to src if direct; otherwise set to substituted direct buffer - private volatile ByteBuffer buf; - - WriteTask(ByteBuffer src, - int pos, - int rem, - long position, - PendingFuture<Integer,A> result) - { - this.src = src; - this.pos = pos; - this.rem = rem; - this.position = position; - this.result = result; - } - - void updatePosition(int bytesTransferred) { - // if the I/O succeeded then adjust buffer position - if (bytesTransferred > 0) { - try { - src.position(pos + bytesTransferred); - } catch (IllegalArgumentException x) { - // someone has changed the position - } - } - } - - @Override - public void run() { - // Substitute an array backed buffer if not - if (src.hasArray()) { - buf = src; - } else { - buf = ByteBuffer.allocate(rem); - buf.put(src); - buf.flip(); - // temporarily restore position as we don't know how many bytes - // will be written - src.position(pos); - } - - try { - begin(); - - // initiate the write - FileStream fs = (FileStream)fdObj.getStream(); - fs.Seek(position, SeekOrigin.wrap(SeekOrigin.Begin)); - fs.BeginWrite(buf.array(), buf.arrayOffset() + pos, rem, new AsyncCallback(this), null); - return; - - } catch (Throwable x) { - // failed to initiate read: - result.setFailure(toIOException(x)); - - } finally { - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - public void Invoke(IAsyncResult ar) { - try { - FileStream fs = (FileStream)fdObj.getStream(); - fs.EndWrite(ar); - completed(rem, false); - } catch (Throwable x) { - failed(0, toIOException(x)); - } - } - - /** - * Executed when the I/O has completed - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - updatePosition(bytesTransferred); - - // release waiters and invoke completion handler - result.setResult(bytesTransferred); - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // release waiters and invoker completion handler - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - - <A> Future<Integer> implWrite(ByteBuffer src, - long position, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - if (!writing) - throw new NonWritableChannelException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - - // check if channel is closed - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - int pos = src.position(); - int lim = src.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - // nothing to write - if (rem == 0) { - if (handler == null) - return CompletedFuture.withResult(0); - Invoker.invoke(this, handler, attachment, 0, null); - return null; - } - - // create Future and task to initiate write - PendingFuture<Integer,A> result = - new PendingFuture<Integer,A>(this, handler, attachment); - WriteTask writeTask = new WriteTask<A>(src, pos, rem, position, result); - result.setContext(writeTask); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - writeTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, writeTask); - } - return result; - } -} diff --git a/openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java b/openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java deleted file mode 100644 index b95f4279..00000000 --- a/openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.net.InetSocketAddress; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; -import java.io.FileDescriptor; -import java.io.IOException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; - -/** - * Windows implementation of AsynchronousServerSocketChannel using overlapped I/O. - */ - -class WindowsAsynchronousServerSocketChannelImpl - extends AsynchronousServerSocketChannelImpl -{ - private final Iocp iocp; - - // flag to indicate that an accept operation is outstanding - private AtomicBoolean accepting = new AtomicBoolean(); - - - WindowsAsynchronousServerSocketChannelImpl(Iocp iocp) throws IOException { - super(iocp); - - this.iocp = iocp; - } - - @Override - void implClose() throws IOException { - // close socket (which may cause outstanding accept to be aborted). - SocketDispatcher.closeImpl(fd); - } - - @Override - public AsynchronousChannelGroupImpl group() { - return iocp; - } - - /** - * Task to initiate accept operation and to handle result. - */ - private class AcceptTask implements Runnable, Iocp.ResultHandler { - private final WindowsAsynchronousSocketChannelImpl channel; - private final AccessControlContext acc; - private final PendingFuture<AsynchronousSocketChannel,Object> result; - - AcceptTask(WindowsAsynchronousSocketChannelImpl channel, - AccessControlContext acc, - PendingFuture<AsynchronousSocketChannel,Object> result) - { - this.channel = channel; - this.acc = acc; - this.result = result; - } - - void enableAccept() { - accepting.set(false); - } - - void closeChildChannel() { - try { - channel.close(); - } catch (IOException ignore) { } - } - - // caller must have acquired read lock for the listener and child channel. - void finishAccept() throws IOException { - /** - * Set local/remote addresses. This is currently very inefficient - * in that it requires 2 calls to getsockname and 2 calls to getpeername. - * (should change this to use GetAcceptExSockaddrs) - */ - updateAcceptContext(fd, channel.fd); - - InetSocketAddress local = Net.localAddress(channel.fd); - final InetSocketAddress remote = Net.remoteAddress(channel.fd); - channel.setConnected(local, remote); - - // permission check (in context of initiating thread) - if (acc != null) { - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - SecurityManager sm = System.getSecurityManager(); - sm.checkAccept(remote.getAddress().getHostAddress(), - remote.getPort()); - return null; - } - }, acc); - } - } - - /** - * Initiates the accept operation. - */ - @Override - public void run() { - - try { - // begin usage of listener socket - begin(); - try { - // begin usage of child socket (as it is registered with - // completion port and so may be closed in the event that - // the group is forcefully closed). - channel.begin(); - - synchronized (result) { - - int n = accept0(fd, channel.fd, this); - if (n == IOStatus.UNAVAILABLE) { - return; - } - - // connection accepted immediately - finishAccept(); - - // allow another accept before the result is set - enableAccept(); - result.setResult(channel); - } - } finally { - // end usage on child socket - channel.end(); - } - } catch (Throwable x) { - // failed to initiate accept so release resources - closeChildChannel(); - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException) && !(x instanceof SecurityException)) - x = new IOException(x); - enableAccept(); - result.setFailure(x); - } finally { - // end of usage of listener socket - end(); - } - - // accept completed immediately but may not have executed on - // initiating thread in which case the operation may have been - // cancelled. - if (result.isCancelled()) { - closeChildChannel(); - } - - // invoke completion handler - Invoker.invokeIndirectly(result); - } - - /** - * Executed when the I/O has completed - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - try { - // connection accept after group has shutdown - if (iocp.isShutdown()) { - throw new IOException(new ShutdownChannelGroupException()); - } - - // finish the accept - try { - begin(); - try { - channel.begin(); - finishAccept(); - } finally { - channel.end(); - } - } finally { - end(); - } - - // allow another accept before the result is set - enableAccept(); - result.setResult(channel); - } catch (Throwable x) { - enableAccept(); - closeChildChannel(); - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException) && !(x instanceof SecurityException)) - x = new IOException(x); - result.setFailure(x); - } - - // if an async cancel has already cancelled the operation then - // close the new channel so as to free resources - if (result.isCancelled()) { - closeChildChannel(); - } - - // invoke handler (but not directly) - Invoker.invokeIndirectly(result); - } - - @Override - public void failed(int error, IOException x) { - enableAccept(); - closeChildChannel(); - - // release waiters - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invokeIndirectly(result); - } - } - - @Override - Future<AsynchronousSocketChannel> implAccept(Object attachment, - final CompletionHandler<AsynchronousSocketChannel,Object> handler) - { - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invokeIndirectly(this, handler, attachment, null, exc); - return null; - } - if (isAcceptKilled()) - throw new RuntimeException("Accept not allowed due to cancellation"); - - // ensure channel is bound to local address - if (localAddress == null) - throw new NotYetBoundException(); - - // create the socket that will be accepted. The creation of the socket - // is enclosed by a begin/end for the listener socket to ensure that - // we check that the listener is open and also to prevent the I/O - // port from being closed as the new socket is registered. - WindowsAsynchronousSocketChannelImpl ch = null; - IOException ioe = null; - try { - begin(); - ch = new WindowsAsynchronousSocketChannelImpl(iocp, false); - } catch (IOException x) { - ioe = x; - } finally { - end(); - } - if (ioe != null) { - if (handler == null) - return CompletedFuture.withFailure(ioe); - Invoker.invokeIndirectly(this, handler, attachment, null, ioe); - return null; - } - - // need calling context when there is security manager as - // permission check may be done in a different thread without - // any application call frames on the stack - AccessControlContext acc = (System.getSecurityManager() == null) ? - null : AccessController.getContext(); - - PendingFuture<AsynchronousSocketChannel,Object> result = - new PendingFuture<AsynchronousSocketChannel,Object>(this, handler, attachment); - AcceptTask task = new AcceptTask(ch, acc, result); - result.setContext(task); - - // check and set flag to prevent concurrent accepting - if (!accepting.compareAndSet(false, true)) - throw new AcceptPendingException(); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - task.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, task); - } - return result; - } - - // -- Native methods -- - - private static native void initIDs(); - - private static native int accept0(FileDescriptor listenSocket, FileDescriptor acceptSocket, - Iocp.ResultHandler handler) throws IOException; - - private static native void updateAcceptContext(FileDescriptor listenSocket, - FileDescriptor acceptSocket) throws IOException; - - private static native void closesocket0(long socket) throws IOException; - - static { - Util.load(); - initIDs(); - } -} diff --git a/openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java b/openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java deleted file mode 100644 index e82c1d9b..00000000 --- a/openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java +++ /dev/null @@ -1,817 +0,0 @@ -/* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.nio.ByteBuffer; -import java.nio.BufferOverflowException; -import java.net.*; -import java.util.concurrent.*; -import java.io.FileDescriptor; -import java.io.IOException; - -/** - * Windows implementation of AsynchronousSocketChannel using overlapped I/O. - */ - -class WindowsAsynchronousSocketChannelImpl - extends AsynchronousSocketChannelImpl -{ - // maximum vector size for scatter/gather I/O - private static final int MAX_WSABUF = 16; - - // I/O completion port that the socket is associated with - private final Iocp iocp; - - - WindowsAsynchronousSocketChannelImpl(Iocp iocp, boolean failIfGroupShutdown) - throws IOException - { - super(iocp); - - this.iocp = iocp; - } - - WindowsAsynchronousSocketChannelImpl(Iocp iocp) throws IOException { - this(iocp, true); - } - - @Override - public AsynchronousChannelGroupImpl group() { - return iocp; - } - - // invoked by WindowsAsynchronousServerSocketChannelImpl when new connection - // accept - void setConnected(SocketAddress localAddress, SocketAddress remoteAddress) { - synchronized (stateLock) { - state = ST_CONNECTED; - this.localAddress = localAddress; - this.remoteAddress = remoteAddress; - } - } - - @Override - void implClose() throws IOException { - // close socket (may cause outstanding async I/O operations to fail). - SocketDispatcher.closeImpl(fd); - } - - @Override - public void onCancel(PendingFuture<?,?> task) { - if (task.getContext() instanceof ConnectTask) - killConnect(); - if (task.getContext() instanceof ReadTask) - killReading(); - if (task.getContext() instanceof WriteTask) - killWriting(); - } - - /** - * Implements the task to initiate a connection and the handler to - * consume the result when the connection is established (or fails). - */ - private class ConnectTask<A> implements Runnable, Iocp.ResultHandler { - private final InetSocketAddress remote; - private final PendingFuture<Void,A> result; - - ConnectTask(InetSocketAddress remote, PendingFuture<Void,A> result) { - this.remote = remote; - this.result = result; - } - - private void closeChannel() { - try { - close(); - } catch (IOException ignore) { } - } - - private IOException toIOException(Throwable x) { - if (x instanceof IOException) { - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - return (IOException)x; - } - return new IOException(x); - } - - /** - * Invoke after a connection is successfully established. - */ - private void afterConnect() throws IOException { - updateConnectContext(fd); - synchronized (stateLock) { - state = ST_CONNECTED; - remoteAddress = remote; - } - } - - /** - * Task to initiate a connection. - */ - @Override - public void run() { - Throwable exc = null; - try { - begin(); - - // synchronize on result to allow this thread handle the case - // where the connection is established immediately. - synchronized (result) { - // initiate the connection - int n = connect0(fd, Net.isIPv6Available(), remote.getAddress(), - remote.getPort(), this); - if (n == IOStatus.UNAVAILABLE) { - // connection is pending - return; - } - - // connection established immediately - afterConnect(); - result.setResult(null); - } - } catch (Throwable x) { - exc = x; - } finally { - end(); - } - - if (exc != null) { - closeChannel(); - result.setFailure(toIOException(exc)); - } - Invoker.invoke(result); - } - - /** - * Invoked by handler thread when connection established. - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - Throwable exc = null; - try { - begin(); - afterConnect(); - result.setResult(null); - } catch (Throwable x) { - // channel is closed or unable to finish connect - exc = x; - } finally { - end(); - } - - // can't close channel while in begin/end block - if (exc != null) { - closeChannel(); - result.setFailure(toIOException(exc)); - } - - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - /** - * Invoked by handler thread when failed to establish connection. - */ - @Override - public void failed(int error, IOException x) { - if (isOpen()) { - closeChannel(); - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - - @Override - <A> Future<Void> implConnect(SocketAddress remote, - A attachment, - CompletionHandler<Void,? super A> handler) - { - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - InetSocketAddress isa = Net.checkAddress(remote); - - // permission check - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); - - // check and update state - // ConnectEx requires the socket to be bound to a local address - IOException bindException = null; - synchronized (stateLock) { - if (state == ST_CONNECTED) - throw new AlreadyConnectedException(); - if (state == ST_PENDING) - throw new ConnectionPendingException(); - if (localAddress == null) { - try { - bind(new InetSocketAddress(0)); - } catch (IOException x) { - bindException = x; - } - } - if (bindException == null) - state = ST_PENDING; - } - - // handle bind failure - if (bindException != null) { - try { - close(); - } catch (IOException ignore) { } - if (handler == null) - return CompletedFuture.withFailure(bindException); - Invoker.invoke(this, handler, attachment, null, bindException); - return null; - } - - // setup task - PendingFuture<Void,A> result = - new PendingFuture<Void,A>(this, handler, attachment); - ConnectTask task = new ConnectTask<A>(isa, result); - result.setContext(task); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - task.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, task); - } - return result; - } - - /** - * Implements the task to initiate a read and the handler to consume the - * result when the read completes. - */ - private class ReadTask<V,A> implements Runnable, Iocp.ResultHandler { - private final ByteBuffer[] bufs; - private final int numBufs; - private final boolean scatteringRead; - private final PendingFuture<V,A> result; - - // set by run method - private ByteBuffer[] shadow; - - ReadTask(ByteBuffer[] bufs, - boolean scatteringRead, - PendingFuture<V,A> result) - { - this.bufs = bufs; - this.numBufs = (bufs.length > MAX_WSABUF) ? MAX_WSABUF : bufs.length; - this.scatteringRead = scatteringRead; - this.result = result; - } - - /** - * Invoked prior to read to prepare the WSABUF array. Where necessary, - * it substitutes direct buffers with managed buffers. - */ - void prepareBuffers() { - shadow = new ByteBuffer[numBufs]; - for (int i=0; i<numBufs; i++) { - ByteBuffer dst = bufs[i]; - int pos = dst.position(); - int lim = dst.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - if (!dst.hasArray()) { - // substitute with direct buffer - ByteBuffer bb = ByteBuffer.allocate(rem); - shadow[i] = bb; - } else { - shadow[i] = dst; - } - } - } - - /** - * Invoked after a read has completed to update the buffer positions - * and release any substituted buffers. - */ - void updateBuffers(int bytesRead) { - for (int i=0; i<numBufs; i++) { - ByteBuffer nextBuffer = shadow[i]; - int pos = nextBuffer.position(); - int len = nextBuffer.remaining(); - if (bytesRead >= len) { - bytesRead -= len; - int newPosition = pos + len; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by another - } - } else { // Buffers not completely filled - if (bytesRead > 0) { - assert(pos + bytesRead < (long)Integer.MAX_VALUE); - int newPosition = pos + bytesRead; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by another - } - } - break; - } - } - - // Put results from shadow into the slow buffers - for (int i=0; i<numBufs; i++) { - if (!bufs[i].hasArray()) { - shadow[i].flip(); - try { - bufs[i].put(shadow[i]); - } catch (BufferOverflowException x) { - // position changed by another - } - } - } - } - - void releaseBuffers() { - } - - @Override - @SuppressWarnings("unchecked") - public void run() { - boolean prepared = false; - boolean pending = false; - - try { - begin(); - - // substitute direct buffers - prepareBuffers(); - prepared = true; - - // initiate read - int n = read0(fd, shadow, this); - if (n == IOStatus.UNAVAILABLE) { - // I/O is pending - pending = true; - return; - } - if (n == IOStatus.EOF) { - // input shutdown - enableReading(); - if (scatteringRead) { - result.setResult((V)Long.valueOf(-1L)); - } else { - result.setResult((V)Integer.valueOf(-1)); - } - } - // read completed immediately - if (n == 0) { - n = -1; // EOF - } else { - updateBuffers(n); - } - releaseBuffers(); - enableReading(); - if (scatteringRead) { - result.setResult((V)Long.valueOf(n)); - } else { - result.setResult((V)Integer.valueOf(n)); - } - } catch (Throwable x) { - // failed to initiate read - // reset read flag before releasing waiters - enableReading(); - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException)) - x = new IOException(x); - result.setFailure(x); - } finally { - // release resources if I/O not pending - if (!pending) { - if (prepared) - releaseBuffers(); - } - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - /** - * Executed when the I/O has completed - */ - @Override - @SuppressWarnings("unchecked") - public void completed(int bytesTransferred, boolean canInvokeDirect) { - if (bytesTransferred == 0) { - bytesTransferred = -1; // EOF - } else { - updateBuffers(bytesTransferred); - } - - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - synchronized (result) { - if (result.isDone()) - return; - enableReading(); - if (scatteringRead) { - result.setResult((V)Long.valueOf(bytesTransferred)); - } else { - result.setResult((V)Integer.valueOf(bytesTransferred)); - } - } - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - if (!isOpen()) - x = new AsynchronousCloseException(); - - synchronized (result) { - if (result.isDone()) - return; - enableReading(); - result.setFailure(x); - } - Invoker.invoke(result); - } - - /** - * Invoked if timeout expires before it is cancelled - */ - void timeout() { - // synchronize on result as the I/O could complete/fail - synchronized (result) { - if (result.isDone()) - return; - - // kill further reading before releasing waiters - enableReading(true); - result.setFailure(new InterruptedByTimeoutException()); - } - - // invoke handler without any locks - Invoker.invoke(result); - } - } - - @Override - <V extends Number,A> Future<V> implRead(boolean isScatteringRead, - ByteBuffer dst, - ByteBuffer[] dsts, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<V,? super A> handler) - { - // setup task - PendingFuture<V,A> result = - new PendingFuture<V,A>(this, handler, attachment); - ByteBuffer[] bufs; - if (isScatteringRead) { - bufs = dsts; - } else { - bufs = new ByteBuffer[1]; - bufs[0] = dst; - } - final ReadTask readTask = new ReadTask<V,A>(bufs, isScatteringRead, result); - result.setContext(readTask); - - // schedule timeout - if (timeout > 0L) { - Future<?> timeoutTask = iocp.schedule(new Runnable() { - public void run() { - readTask.timeout(); - } - }, timeout, unit); - result.setTimeoutTask(timeoutTask); - } - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - readTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, readTask); - } - return result; - } - - /** - * Implements the task to initiate a write and the handler to consume the - * result when the write completes. - */ - private class WriteTask<V,A> implements Runnable, Iocp.ResultHandler { - private final ByteBuffer[] bufs; - private final int numBufs; - private final boolean gatheringWrite; - private final PendingFuture<V,A> result; - - // set by run method - private ByteBuffer[] shadow; - - WriteTask(ByteBuffer[] bufs, - boolean gatheringWrite, - PendingFuture<V,A> result) - { - this.bufs = bufs; - this.numBufs = (bufs.length > MAX_WSABUF) ? MAX_WSABUF : bufs.length; - this.gatheringWrite = gatheringWrite; - this.result = result; - } - - /** - * Invoked prior to write to prepare the WSABUF array. Where necessary, - * it substitutes direct buffers with managed buffers. - */ - void prepareBuffers() { - shadow = new ByteBuffer[numBufs]; - for (int i=0; i<numBufs; i++) { - ByteBuffer src = bufs[i]; - int pos = src.position(); - int lim = src.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - if (!src.hasArray()) { - // substitute with direct buffer - ByteBuffer bb = ByteBuffer.allocate(rem); - bb.put(src); - bb.flip(); - src.position(pos); // leave heap buffer untouched for now - shadow[i] = bb; - } else { - shadow[i] = src; - } - } - } - - /** - * Invoked after a write has completed to update the buffer positions - * and release any substituted buffers. - */ - void updateBuffers(int bytesWritten) { - // Notify the buffers how many bytes were taken - for (int i=0; i<numBufs; i++) { - ByteBuffer nextBuffer = bufs[i]; - int pos = nextBuffer.position(); - int lim = nextBuffer.limit(); - int len = (pos <= lim ? lim - pos : lim); - if (bytesWritten >= len) { - bytesWritten -= len; - int newPosition = pos + len; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by someone else - } - } else { // Buffers not completely filled - if (bytesWritten > 0) { - assert(pos + bytesWritten < (long)Integer.MAX_VALUE); - int newPosition = pos + bytesWritten; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by someone else - } - } - break; - } - } - } - - void releaseBuffers() { - } - - @Override - //@SuppressWarnings("unchecked") - public void run() { - boolean prepared = false; - boolean pending = false; - boolean shutdown = false; - - try { - begin(); - - // substitute direct buffers - prepareBuffers(); - prepared = true; - - int n = write0(fd, shadow, this); - if (n == IOStatus.UNAVAILABLE) { - // I/O is pending - pending = true; - return; - } - if (n == IOStatus.EOF) { - // special case for shutdown output - shutdown = true; - throw new ClosedChannelException(); - } - // write completed immediately - updateBuffers(n); - releaseBuffers(); - enableWriting(); - if (gatheringWrite) { - result.setResult((V)Long.valueOf(n)); - } else { - result.setResult((V)Integer.valueOf(n)); - } - } catch (Throwable x) { - // write failed. Enable writing before releasing waiters. - enableWriting(); - if (!shutdown && (x instanceof ClosedChannelException)) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException)) - x = new IOException(x); - result.setFailure(x); - } finally { - // release resources if I/O not pending - if (!pending) { - if (prepared) - releaseBuffers(); - } - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - /** - * Executed when the I/O has completed - */ - @Override - @SuppressWarnings("unchecked") - public void completed(int bytesTransferred, boolean canInvokeDirect) { - updateBuffers(bytesTransferred); - - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - synchronized (result) { - if (result.isDone()) - return; - enableWriting(); - if (gatheringWrite) { - result.setResult((V)Long.valueOf(bytesTransferred)); - } else { - result.setResult((V)Integer.valueOf(bytesTransferred)); - } - } - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - if (!isOpen()) - x = new AsynchronousCloseException(); - - synchronized (result) { - if (result.isDone()) - return; - enableWriting(); - result.setFailure(x); - } - Invoker.invoke(result); - } - - /** - * Invoked if timeout expires before it is cancelled - */ - void timeout() { - // synchronize on result as the I/O could complete/fail - synchronized (result) { - if (result.isDone()) - return; - - // kill further writing before releasing waiters - enableWriting(true); - result.setFailure(new InterruptedByTimeoutException()); - } - - // invoke handler without any locks - Invoker.invoke(result); - } - } - - @Override - <V extends Number,A> Future<V> implWrite(boolean gatheringWrite, - ByteBuffer src, - ByteBuffer[] srcs, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<V,? super A> handler) - { - // setup task - PendingFuture<V,A> result = - new PendingFuture<V,A>(this, handler, attachment); - ByteBuffer[] bufs; - if (gatheringWrite) { - bufs = srcs; - } else { - bufs = new ByteBuffer[1]; - bufs[0] = src; - } - final WriteTask writeTask = new WriteTask<V,A>(bufs, gatheringWrite, result); - result.setContext(writeTask); - - // schedule timeout - if (timeout > 0L) { - Future<?> timeoutTask = iocp.schedule(new Runnable() { - public void run() { - writeTask.timeout(); - } - }, timeout, unit); - result.setTimeoutTask(timeoutTask); - } - - // initiate I/O (can only be done from thread in thread pool) - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - writeTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, writeTask); - } - return result; - } - - // -- Native methods -- - - private static native void initIDs(); - - private static native int connect0(FileDescriptor fd, boolean preferIPv6, - InetAddress remote, int remotePort, Iocp.ResultHandler handler) throws IOException; - - private static native void updateConnectContext(FileDescriptor fd) throws IOException; - - private static native int read0(FileDescriptor fd, ByteBuffer[] bufs, Iocp.ResultHandler handler) - throws IOException; - - private static native int write0(FileDescriptor fd, ByteBuffer[] bufs, Iocp.ResultHandler handler) - throws IOException; - - private static native void shutdown0(long socket, int how) throws IOException; - - private static native void closesocket0(long socket) throws IOException; - - static { - Util.load(); - initIDs(); - } -} diff --git a/openjdk/sun/nio/cs/StandardCharsets.java b/openjdk/sun/nio/cs/StandardCharsets.java deleted file mode 100644 index af09bd63..00000000 --- a/openjdk/sun/nio/cs/StandardCharsets.java +++ /dev/null @@ -1,706 +0,0 @@ -/* - * Copyright (c) 2000, 2007, 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. - * - */ - -// -- This file was mechanically generated: Do not edit! -- // - -package sun.nio.cs; - -import java.nio.charset.*; - - -public class StandardCharsets - extends FastCharsetProvider -{ - - static final String[] aliases_US_ASCII = new String[] { - "iso-ir-6", - "ANSI_X3.4-1986", - "ISO_646.irv:1991", - "ASCII", - "ISO646-US", - "us", - "IBM367", - "cp367", - "csASCII", - "default", - "646", - "iso_646.irv:1983", - "ANSI_X3.4-1968", - "ascii7", - }; - - static final String[] aliases_UTF_8 = new String[] { - "UTF8", - "unicode-1-1-utf-8", - }; - - static final String[] aliases_UTF_16 = new String[] { - "UTF_16", - "utf16", - "unicode", - "UnicodeBig", - }; - - static final String[] aliases_UTF_16BE = new String[] { - "UTF_16BE", - "ISO-10646-UCS-2", - "X-UTF-16BE", - "UnicodeBigUnmarked", - }; - - static final String[] aliases_UTF_16LE = new String[] { - "UTF_16LE", - "X-UTF-16LE", - "UnicodeLittleUnmarked", - }; - - static final String[] aliases_UTF_16LE_BOM = new String[] { - "UnicodeLittle", - }; - - static final String[] aliases_UTF_32 = new String[] { - "UTF_32", - "UTF32", - }; - - static final String[] aliases_UTF_32LE = new String[] { - "UTF_32LE", - "X-UTF-32LE", - }; - - static final String[] aliases_UTF_32BE = new String[] { - "UTF_32BE", - "X-UTF-32BE", - }; - - static final String[] aliases_UTF_32LE_BOM = new String[] { - "UTF_32LE_BOM", - "UTF-32LE-BOM", - }; - - static final String[] aliases_UTF_32BE_BOM = new String[] { - "UTF_32BE_BOM", - "UTF-32BE-BOM", - }; - - static final String[] aliases_ISO_8859_1 = new String[] { - "iso-ir-100", - "ISO_8859-1", - "latin1", - "l1", - "IBM819", - "cp819", - "csISOLatin1", - "819", - "IBM-819", - "ISO8859_1", - "ISO_8859-1:1987", - "ISO_8859_1", - "8859_1", - "ISO8859-1", - }; - - static final String[] aliases_ISO_8859_2 = new String[] { - "iso8859_2", - "8859_2", - "iso-ir-101", - "ISO_8859-2", - "ISO_8859-2:1987", - "ISO8859-2", - "latin2", - "l2", - "ibm912", - "ibm-912", - "cp912", - "912", - "csISOLatin2", - }; - - static final String[] aliases_ISO_8859_4 = new String[] { - "iso8859_4", - "iso8859-4", - "8859_4", - "iso-ir-110", - "ISO_8859-4", - "ISO_8859-4:1988", - "latin4", - "l4", - "ibm914", - "ibm-914", - "cp914", - "914", - "csISOLatin4", - }; - - static final String[] aliases_ISO_8859_5 = new String[] { - "iso8859_5", - "8859_5", - "iso-ir-144", - "ISO_8859-5", - "ISO_8859-5:1988", - "ISO8859-5", - "cyrillic", - "ibm915", - "ibm-915", - "cp915", - "915", - "csISOLatinCyrillic", - }; - - static final String[] aliases_ISO_8859_7 = new String[] { - "iso8859_7", - "8859_7", - "iso-ir-126", - "ISO_8859-7", - "ISO_8859-7:1987", - "ELOT_928", - "ECMA-118", - "greek", - "greek8", - "csISOLatinGreek", - "sun_eu_greek", - "ibm813", - "ibm-813", - "813", - "cp813", - "iso8859-7", - }; - - static final String[] aliases_ISO_8859_9 = new String[] { - "iso8859_9", - "8859_9", - "iso-ir-148", - "ISO_8859-9", - "ISO_8859-9:1989", - "ISO8859-9", - "latin5", - "l5", - "ibm920", - "ibm-920", - "920", - "cp920", - "csISOLatin5", - }; - - static final String[] aliases_ISO_8859_13 = new String[] { - "iso8859_13", - "8859_13", - "iso_8859-13", - "ISO8859-13", - }; - - static final String[] aliases_ISO_8859_15 = new String[] { - "ISO_8859-15", - "8859_15", - "ISO-8859-15", - "ISO8859_15", - "ISO8859-15", - "IBM923", - "IBM-923", - "cp923", - "923", - "LATIN0", - "LATIN9", - "L9", - "csISOlatin0", - "csISOlatin9", - "ISO8859_15_FDIS", - }; - - static final String[] aliases_KOI8_R = new String[] { - "koi8_r", - "koi8", - "cskoi8r", - }; - - static final String[] aliases_KOI8_U = new String[] { - "koi8_u", - }; - - static final String[] aliases_MS1250 = new String[] { - "cp1250", - "cp5346", - }; - - static final String[] aliases_MS1251 = new String[] { - "cp1251", - "cp5347", - "ansi-1251", - }; - - static final String[] aliases_MS1252 = new String[] { - "cp1252", - "cp5348", - }; - - static final String[] aliases_MS1253 = new String[] { - "cp1253", - "cp5349", - }; - - static final String[] aliases_MS1254 = new String[] { - "cp1254", - "cp5350", - }; - - static final String[] aliases_MS1257 = new String[] { - "cp1257", - "cp5353", - }; - - static final String[] aliases_IBM437 = new String[] { - "cp437", - "ibm437", - "ibm-437", - "437", - "cspc8codepage437", - "windows-437", - }; - - static final String[] aliases_IBM737 = new String[] { - "cp737", - "ibm737", - "ibm-737", - "737", - }; - - static final String[] aliases_IBM775 = new String[] { - "cp775", - "ibm775", - "ibm-775", - "775", - }; - - static final String[] aliases_IBM850 = new String[] { - "cp850", - "ibm-850", - "ibm850", - "850", - "cspc850multilingual", - }; - - static final String[] aliases_IBM852 = new String[] { - "cp852", - "ibm852", - "ibm-852", - "852", - "csPCp852", - }; - - static final String[] aliases_IBM855 = new String[] { - "cp855", - "ibm-855", - "ibm855", - "855", - "cspcp855", - }; - - static final String[] aliases_IBM857 = new String[] { - "cp857", - "ibm857", - "ibm-857", - "857", - "csIBM857", - }; - - static final String[] aliases_IBM858 = new String[] { - "cp858", - "ccsid00858", - "cp00858", - "858", - "PC-Multilingual-850+euro", - }; - - static final String[] aliases_IBM862 = new String[] { - "cp862", - "ibm862", - "ibm-862", - "862", - "csIBM862", - "cspc862latinhebrew", - }; - - static final String[] aliases_IBM866 = new String[] { - "cp866", - "ibm866", - "ibm-866", - "866", - "csIBM866", - }; - - static final String[] aliases_IBM874 = new String[] { - "cp874", - "ibm874", - "ibm-874", - "874", - }; - - private static final class Aliases - extends sun.util.PreHashedMap<String> - { - - private static final int ROWS = 1024; - private static final int SIZE = 209; - private static final int SHIFT = 0; - private static final int MASK = 0x3ff; - - private Aliases() { - super(ROWS, SIZE, SHIFT, MASK); - } - - protected void init(Object[] ht) { - ht[1] = new Object[] { "csisolatin0", "iso-8859-15" }; - ht[2] = new Object[] { "csisolatin1", "iso-8859-1" }; - ht[3] = new Object[] { "csisolatin2", "iso-8859-2" }; - ht[5] = new Object[] { "csisolatin4", "iso-8859-4" }; - ht[6] = new Object[] { "csisolatin5", "iso-8859-9" }; - ht[10] = new Object[] { "csisolatin9", "iso-8859-15" }; - ht[19] = new Object[] { "unicodelittle", "x-utf-16le-bom" }; - ht[24] = new Object[] { "iso646-us", "us-ascii" }; - ht[25] = new Object[] { "iso_8859-7:1987", "iso-8859-7" }; - ht[26] = new Object[] { "912", "iso-8859-2" }; - ht[28] = new Object[] { "914", "iso-8859-4" }; - ht[29] = new Object[] { "915", "iso-8859-5" }; - ht[55] = new Object[] { "920", "iso-8859-9" }; - ht[58] = new Object[] { "923", "iso-8859-15" }; - ht[86] = new Object[] { "csisolatincyrillic", "iso-8859-5", - new Object[] { "8859_1", "iso-8859-1" } }; - ht[87] = new Object[] { "8859_2", "iso-8859-2" }; - ht[89] = new Object[] { "8859_4", "iso-8859-4" }; - ht[90] = new Object[] { "813", "iso-8859-7", - new Object[] { "8859_5", "iso-8859-5" } }; - ht[92] = new Object[] { "8859_7", "iso-8859-7" }; - ht[94] = new Object[] { "8859_9", "iso-8859-9" }; - ht[95] = new Object[] { "iso_8859-1:1987", "iso-8859-1" }; - ht[96] = new Object[] { "819", "iso-8859-1" }; - ht[106] = new Object[] { "unicode-1-1-utf-8", "utf-8" }; - ht[121] = new Object[] { "x-utf-16le", "utf-16le" }; - ht[125] = new Object[] { "ecma-118", "iso-8859-7" }; - ht[134] = new Object[] { "koi8_r", "koi8-r" }; - ht[137] = new Object[] { "koi8_u", "koi8-u" }; - ht[141] = new Object[] { "cp912", "iso-8859-2" }; - ht[143] = new Object[] { "cp914", "iso-8859-4" }; - ht[144] = new Object[] { "cp915", "iso-8859-5" }; - ht[170] = new Object[] { "cp920", "iso-8859-9" }; - ht[173] = new Object[] { "cp923", "iso-8859-15" }; - ht[177] = new Object[] { "utf_32le_bom", "x-utf-32le-bom" }; - ht[192] = new Object[] { "utf_16be", "utf-16be" }; - ht[199] = new Object[] { "cspc8codepage437", "ibm437", - new Object[] { "ansi-1251", "windows-1251" } }; - ht[205] = new Object[] { "cp813", "iso-8859-7" }; - ht[211] = new Object[] { "850", "ibm850", - new Object[] { "cp819", "iso-8859-1" } }; - ht[213] = new Object[] { "852", "ibm852" }; - ht[216] = new Object[] { "855", "ibm855" }; - ht[218] = new Object[] { "857", "ibm857", - new Object[] { "iso-ir-6", "us-ascii" } }; - ht[219] = new Object[] { "858", "ibm00858", - new Object[] { "737", "x-ibm737" } }; - ht[225] = new Object[] { "csascii", "us-ascii" }; - ht[244] = new Object[] { "862", "ibm862" }; - ht[248] = new Object[] { "866", "ibm866" }; - ht[253] = new Object[] { "x-utf-32be", "utf-32be" }; - ht[254] = new Object[] { "iso_8859-2:1987", "iso-8859-2" }; - ht[259] = new Object[] { "unicodebig", "utf-16" }; - ht[269] = new Object[] { "iso8859_15_fdis", "iso-8859-15" }; - ht[277] = new Object[] { "874", "x-ibm874" }; - ht[280] = new Object[] { "unicodelittleunmarked", "utf-16le" }; - ht[283] = new Object[] { "iso8859_1", "iso-8859-1" }; - ht[284] = new Object[] { "iso8859_2", "iso-8859-2" }; - ht[286] = new Object[] { "iso8859_4", "iso-8859-4" }; - ht[287] = new Object[] { "iso8859_5", "iso-8859-5" }; - ht[289] = new Object[] { "iso8859_7", "iso-8859-7" }; - ht[291] = new Object[] { "iso8859_9", "iso-8859-9" }; - ht[294] = new Object[] { "ibm912", "iso-8859-2" }; - ht[296] = new Object[] { "ibm914", "iso-8859-4" }; - ht[297] = new Object[] { "ibm915", "iso-8859-5" }; - ht[305] = new Object[] { "iso_8859-13", "iso-8859-13" }; - ht[307] = new Object[] { "iso_8859-15", "iso-8859-15" }; - ht[312] = new Object[] { "greek8", "iso-8859-7", - new Object[] { "646", "us-ascii" } }; - ht[321] = new Object[] { "ibm-912", "iso-8859-2" }; - ht[323] = new Object[] { "ibm920", "iso-8859-9", - new Object[] { "ibm-914", "iso-8859-4" } }; - ht[324] = new Object[] { "ibm-915", "iso-8859-5" }; - ht[325] = new Object[] { "l1", "iso-8859-1" }; - ht[326] = new Object[] { "cp850", "ibm850", - new Object[] { "ibm923", "iso-8859-15", - new Object[] { "l2", "iso-8859-2" } } }; - ht[327] = new Object[] { "cyrillic", "iso-8859-5" }; - ht[328] = new Object[] { "cp852", "ibm852", - new Object[] { "l4", "iso-8859-4" } }; - ht[329] = new Object[] { "l5", "iso-8859-9" }; - ht[331] = new Object[] { "cp855", "ibm855" }; - ht[333] = new Object[] { "cp857", "ibm857", - new Object[] { "l9", "iso-8859-15" } }; - ht[334] = new Object[] { "cp858", "ibm00858", - new Object[] { "cp737", "x-ibm737" } }; - ht[336] = new Object[] { "iso_8859_1", "iso-8859-1" }; - ht[339] = new Object[] { "koi8", "koi8-r" }; - ht[341] = new Object[] { "775", "ibm775" }; - ht[345] = new Object[] { "iso_8859-9:1989", "iso-8859-9" }; - ht[350] = new Object[] { "ibm-920", "iso-8859-9" }; - ht[353] = new Object[] { "ibm-923", "iso-8859-15" }; - ht[358] = new Object[] { "ibm813", "iso-8859-7" }; - ht[359] = new Object[] { "cp862", "ibm862" }; - ht[363] = new Object[] { "cp866", "ibm866" }; - ht[364] = new Object[] { "ibm819", "iso-8859-1" }; - ht[378] = new Object[] { "ansi_x3.4-1968", "us-ascii" }; - ht[385] = new Object[] { "ibm-813", "iso-8859-7" }; - ht[391] = new Object[] { "ibm-819", "iso-8859-1" }; - ht[392] = new Object[] { "cp874", "x-ibm874" }; - ht[405] = new Object[] { "iso-ir-100", "iso-8859-1" }; - ht[406] = new Object[] { "iso-ir-101", "iso-8859-2" }; - ht[408] = new Object[] { "437", "ibm437" }; - ht[421] = new Object[] { "iso-8859-15", "iso-8859-15" }; - ht[428] = new Object[] { "latin0", "iso-8859-15" }; - ht[429] = new Object[] { "latin1", "iso-8859-1" }; - ht[430] = new Object[] { "latin2", "iso-8859-2" }; - ht[432] = new Object[] { "latin4", "iso-8859-4" }; - ht[433] = new Object[] { "latin5", "iso-8859-9" }; - ht[436] = new Object[] { "iso-ir-110", "iso-8859-4" }; - ht[437] = new Object[] { "latin9", "iso-8859-15" }; - ht[438] = new Object[] { "ansi_x3.4-1986", "us-ascii" }; - ht[443] = new Object[] { "utf-32be-bom", "x-utf-32be-bom" }; - ht[456] = new Object[] { "cp775", "ibm775" }; - ht[473] = new Object[] { "iso-ir-126", "iso-8859-7" }; - ht[479] = new Object[] { "ibm850", "ibm850" }; - ht[481] = new Object[] { "ibm852", "ibm852" }; - ht[484] = new Object[] { "ibm855", "ibm855" }; - ht[486] = new Object[] { "ibm857", "ibm857" }; - ht[487] = new Object[] { "ibm737", "x-ibm737" }; - ht[502] = new Object[] { "utf_16le", "utf-16le" }; - ht[506] = new Object[] { "ibm-850", "ibm850" }; - ht[508] = new Object[] { "ibm-852", "ibm852" }; - ht[511] = new Object[] { "ibm-855", "ibm855" }; - ht[512] = new Object[] { "ibm862", "ibm862" }; - ht[513] = new Object[] { "ibm-857", "ibm857" }; - ht[514] = new Object[] { "ibm-737", "x-ibm737" }; - ht[516] = new Object[] { "ibm866", "ibm866" }; - ht[520] = new Object[] { "unicodebigunmarked", "utf-16be" }; - ht[523] = new Object[] { "cp437", "ibm437" }; - ht[524] = new Object[] { "utf16", "utf-16" }; - ht[533] = new Object[] { "iso-ir-144", "iso-8859-5" }; - ht[537] = new Object[] { "iso-ir-148", "iso-8859-9" }; - ht[539] = new Object[] { "ibm-862", "ibm862" }; - ht[543] = new Object[] { "ibm-866", "ibm866" }; - ht[545] = new Object[] { "ibm874", "x-ibm874" }; - ht[563] = new Object[] { "x-utf-32le", "utf-32le" }; - ht[572] = new Object[] { "ibm-874", "x-ibm874" }; - ht[573] = new Object[] { "iso_8859-4:1988", "iso-8859-4" }; - ht[577] = new Object[] { "default", "us-ascii" }; - ht[582] = new Object[] { "utf32", "utf-32" }; - ht[583] = new Object[] { "pc-multilingual-850+euro", "ibm00858" }; - ht[588] = new Object[] { "elot_928", "iso-8859-7" }; - ht[593] = new Object[] { "csisolatingreek", "iso-8859-7" }; - ht[598] = new Object[] { "csibm857", "ibm857" }; - ht[609] = new Object[] { "ibm775", "ibm775" }; - ht[617] = new Object[] { "cp1250", "windows-1250" }; - ht[618] = new Object[] { "cp1251", "windows-1251" }; - ht[619] = new Object[] { "cp1252", "windows-1252" }; - ht[620] = new Object[] { "cp1253", "windows-1253" }; - ht[621] = new Object[] { "cp1254", "windows-1254" }; - ht[624] = new Object[] { "csibm862", "ibm862", - new Object[] { "cp1257", "windows-1257" } }; - ht[628] = new Object[] { "csibm866", "ibm866" }; - ht[632] = new Object[] { "iso8859_13", "iso-8859-13" }; - ht[634] = new Object[] { "iso8859_15", "iso-8859-15", - new Object[] { "utf_32be", "utf-32be" } }; - ht[635] = new Object[] { "utf_32be_bom", "x-utf-32be-bom" }; - ht[636] = new Object[] { "ibm-775", "ibm775" }; - ht[654] = new Object[] { "cp00858", "ibm00858" }; - ht[669] = new Object[] { "8859_13", "iso-8859-13" }; - ht[670] = new Object[] { "us", "us-ascii" }; - ht[671] = new Object[] { "8859_15", "iso-8859-15" }; - ht[676] = new Object[] { "ibm437", "ibm437" }; - ht[679] = new Object[] { "cp367", "us-ascii" }; - ht[686] = new Object[] { "iso-10646-ucs-2", "utf-16be" }; - ht[703] = new Object[] { "ibm-437", "ibm437" }; - ht[710] = new Object[] { "iso8859-13", "iso-8859-13" }; - ht[712] = new Object[] { "iso8859-15", "iso-8859-15" }; - ht[732] = new Object[] { "iso_8859-5:1988", "iso-8859-5" }; - ht[733] = new Object[] { "unicode", "utf-16" }; - ht[768] = new Object[] { "greek", "iso-8859-7" }; - ht[774] = new Object[] { "ascii7", "us-ascii" }; - ht[781] = new Object[] { "iso8859-1", "iso-8859-1" }; - ht[782] = new Object[] { "iso8859-2", "iso-8859-2" }; - ht[783] = new Object[] { "cskoi8r", "koi8-r" }; - ht[784] = new Object[] { "iso8859-4", "iso-8859-4" }; - ht[785] = new Object[] { "iso8859-5", "iso-8859-5" }; - ht[787] = new Object[] { "iso8859-7", "iso-8859-7" }; - ht[789] = new Object[] { "iso8859-9", "iso-8859-9" }; - ht[813] = new Object[] { "ccsid00858", "ibm00858" }; - ht[818] = new Object[] { "cspc862latinhebrew", "ibm862" }; - ht[832] = new Object[] { "ibm367", "us-ascii" }; - ht[834] = new Object[] { "iso_8859-1", "iso-8859-1" }; - ht[835] = new Object[] { "iso_8859-2", "iso-8859-2", - new Object[] { "x-utf-16be", "utf-16be" } }; - ht[836] = new Object[] { "sun_eu_greek", "iso-8859-7" }; - ht[837] = new Object[] { "iso_8859-4", "iso-8859-4" }; - ht[838] = new Object[] { "iso_8859-5", "iso-8859-5" }; - ht[840] = new Object[] { "cspcp852", "ibm852", - new Object[] { "iso_8859-7", "iso-8859-7" } }; - ht[842] = new Object[] { "iso_8859-9", "iso-8859-9" }; - ht[843] = new Object[] { "cspcp855", "ibm855" }; - ht[846] = new Object[] { "windows-437", "ibm437" }; - ht[849] = new Object[] { "ascii", "us-ascii" }; - ht[881] = new Object[] { "utf8", "utf-8" }; - ht[896] = new Object[] { "iso_646.irv:1983", "us-ascii" }; - ht[909] = new Object[] { "cp5346", "windows-1250" }; - ht[910] = new Object[] { "cp5347", "windows-1251" }; - ht[911] = new Object[] { "cp5348", "windows-1252" }; - ht[912] = new Object[] { "cp5349", "windows-1253" }; - ht[925] = new Object[] { "iso_646.irv:1991", "us-ascii" }; - ht[934] = new Object[] { "cp5350", "windows-1254" }; - ht[937] = new Object[] { "cp5353", "windows-1257" }; - ht[944] = new Object[] { "utf_32le", "utf-32le" }; - ht[957] = new Object[] { "utf_16", "utf-16" }; - ht[993] = new Object[] { "cspc850multilingual", "ibm850" }; - ht[1009] = new Object[] { "utf-32le-bom", "x-utf-32le-bom" }; - ht[1015] = new Object[] { "utf_32", "utf-32" }; - } - - } - - private static final class Classes - extends sun.util.PreHashedMap<String> - { - - private static final int ROWS = 32; - private static final int SIZE = 38; - private static final int SHIFT = 1; - private static final int MASK = 0x1f; - - private Classes() { - super(ROWS, SIZE, SHIFT, MASK); - } - - protected void init(Object[] ht) { - ht[0] = new Object[] { "ibm862", "IBM862" }; - ht[2] = new Object[] { "ibm866", "IBM866", - new Object[] { "utf-32", "UTF_32", - new Object[] { "utf-16le", "UTF_16LE" } } }; - ht[3] = new Object[] { "windows-1251", "MS1251", - new Object[] { "windows-1250", "MS1250" } }; - ht[4] = new Object[] { "windows-1253", "MS1253", - new Object[] { "windows-1252", "MS1252", - new Object[] { "utf-32be", "UTF_32BE" } } }; - ht[5] = new Object[] { "windows-1254", "MS1254", - new Object[] { "utf-16", "UTF_16" } }; - ht[6] = new Object[] { "windows-1257", "MS1257" }; - ht[7] = new Object[] { "utf-16be", "UTF_16BE" }; - ht[8] = new Object[] { "iso-8859-2", "ISO_8859_2", - new Object[] { "iso-8859-1", "ISO_8859_1" } }; - ht[9] = new Object[] { "iso-8859-4", "ISO_8859_4", - new Object[] { "utf-8", "UTF_8" } }; - ht[10] = new Object[] { "iso-8859-5", "ISO_8859_5" }; - ht[11] = new Object[] { "x-ibm874", "IBM874", - new Object[] { "iso-8859-7", "ISO_8859_7" } }; - ht[12] = new Object[] { "iso-8859-9", "ISO_8859_9" }; - ht[14] = new Object[] { "x-ibm737", "IBM737" }; - ht[15] = new Object[] { "ibm850", "IBM850" }; - ht[16] = new Object[] { "ibm852", "IBM852", - new Object[] { "ibm775", "IBM775" } }; - ht[17] = new Object[] { "iso-8859-13", "ISO_8859_13", - new Object[] { "us-ascii", "US_ASCII" } }; - ht[18] = new Object[] { "ibm855", "IBM855", - new Object[] { "ibm437", "IBM437", - new Object[] { "iso-8859-15", "ISO_8859_15" } } }; - ht[19] = new Object[] { "ibm00858", "IBM858", - new Object[] { "ibm857", "IBM857", - new Object[] { "x-utf-32le-bom", "UTF_32LE_BOM" } } }; - ht[22] = new Object[] { "x-utf-16le-bom", "UTF_16LE_BOM" }; - ht[24] = new Object[] { "x-utf-32be-bom", "UTF_32BE_BOM" }; - ht[28] = new Object[] { "koi8-r", "KOI8_R" }; - ht[29] = new Object[] { "koi8-u", "KOI8_U" }; - ht[31] = new Object[] { "utf-32le", "UTF_32LE" }; - } - - } - - private static final class Cache - extends sun.util.PreHashedMap<Charset> - { - - private static final int ROWS = 32; - private static final int SIZE = 38; - private static final int SHIFT = 1; - private static final int MASK = 0x1f; - - private Cache() { - super(ROWS, SIZE, SHIFT, MASK); - } - - protected void init(Object[] ht) { - // [IKVM] we pre-populate some cache entries to avoid reflection when instantiating the common charsets - ht[0] = new Object[] { "ibm862", null }; - ht[2] = new Object[] { "ibm866", null, - new Object[] { "utf-32", null, - new Object[] { "utf-16le", null } } }; - ht[3] = new Object[] { "windows-1251", null, - new Object[] { "windows-1250", null } }; - ht[4] = new Object[] { "windows-1253", null, - new Object[] { "windows-1252", new MS1252(), - new Object[] { "utf-32be", null } } }; - ht[5] = new Object[] { "windows-1254", null, - new Object[] { "utf-16", null } }; - ht[6] = new Object[] { "windows-1257", null }; - ht[7] = new Object[] { "utf-16be", null }; - ht[8] = new Object[] { "iso-8859-2", null, - new Object[] { "iso-8859-1", null } }; - ht[9] = new Object[] { "iso-8859-4", null, - new Object[] { "utf-8", new UTF_8() } }; - ht[10] = new Object[] { "iso-8859-5", null }; - ht[11] = new Object[] { "x-ibm874", null, - new Object[] { "iso-8859-7", null } }; - ht[12] = new Object[] { "iso-8859-9", null }; - ht[14] = new Object[] { "x-ibm737", null }; - ht[15] = new Object[] { "ibm850", null }; - ht[16] = new Object[] { "ibm852", null, - new Object[] { "ibm775", null } }; - ht[17] = new Object[] { "iso-8859-13", null, - new Object[] { "us-ascii", null } }; - ht[18] = new Object[] { "ibm855", null, - new Object[] { "ibm437", null, - new Object[] { "iso-8859-15", null } } }; - ht[19] = new Object[] { "ibm00858", null, - new Object[] { "ibm857", null, - new Object[] { "x-utf-32le-bom", null } } }; - ht[22] = new Object[] { "x-utf-16le-bom", null }; - ht[24] = new Object[] { "x-utf-32be-bom", null }; - ht[28] = new Object[] { "koi8-r", null }; - ht[29] = new Object[] { "koi8-u", null }; - ht[31] = new Object[] { "utf-32le", null }; - } - - } - - public StandardCharsets() { - super("sun.nio.cs", new Aliases(), new Classes(), new Cache()); - } - -} diff --git a/openjdk/sun/nio/fs/DefaultFileSystemProvider.java b/openjdk/sun/nio/fs/DefaultFileSystemProvider.java deleted file mode 100644 index 6ef8d07d..00000000 --- a/openjdk/sun/nio/fs/DefaultFileSystemProvider.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright (C) 2011 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.nio.fs; - -import java.nio.file.spi.FileSystemProvider; - -public class DefaultFileSystemProvider -{ - public static FileSystemProvider create() - { - return new NetFileSystemProvider(); - } -} diff --git a/openjdk/sun/nio/fs/DefaultFileTypeDetector.java b/openjdk/sun/nio/fs/DefaultFileTypeDetector.java deleted file mode 100644 index 5da08123..00000000 --- a/openjdk/sun/nio/fs/DefaultFileTypeDetector.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (C) 2011 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.nio.fs; - -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.spi.FileTypeDetector; - -public class DefaultFileTypeDetector -{ - public static FileTypeDetector create() - { - return new AbstractFileTypeDetector() { - public String implProbeContentType(Path obj) throws IOException { - return null; - } - }; - } -} diff --git a/openjdk/sun/nio/fs/NetFileSystem.java b/openjdk/sun/nio/fs/NetFileSystem.java deleted file mode 100644 index 9c07f605..00000000 --- a/openjdk/sun/nio/fs/NetFileSystem.java +++ /dev/null @@ -1,498 +0,0 @@ -/* - Copyright (C) 2011 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.nio.fs; - -import cli.System.IO.DriveInfo; -import cli.System.IO.ErrorEventArgs; -import cli.System.IO.ErrorEventHandler; -import cli.System.IO.FileSystemEventArgs; -import cli.System.IO.FileSystemEventHandler; -import cli.System.IO.FileSystemWatcher; -import cli.System.IO.WatcherChangeTypes; -import java.io.IOException; -import java.nio.file.*; -import java.nio.file.attribute.*; -import java.nio.file.spi.FileSystemProvider; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; -import static ikvm.internal.Util.WINDOWS; - -final class NetFileSystem extends FileSystem -{ - private static final Set<String> attributes = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("basic"))); - private final NetFileSystemProvider provider; - private final String separator = Character.toString(cli.System.IO.Path.DirectorySeparatorChar); - - NetFileSystem(NetFileSystemProvider provider) - { - this.provider = provider; - } - - public FileSystemProvider provider() - { - return provider; - } - - public void close() throws IOException - { - throw new UnsupportedOperationException(); - } - - public boolean isOpen() - { - return true; - } - - public boolean isReadOnly() - { - return false; - } - - public String getSeparator() - { - return separator; - } - - public Iterable<Path> getRootDirectories() - { - SecurityManager sm = System.getSecurityManager(); - ArrayList<Path> list = new ArrayList<>(); - for (DriveInfo info : DriveInfo.GetDrives()) - { - try - { - if (sm != null) - { - sm.checkRead(info.get_Name()); - } - } - catch (SecurityException _) - { - continue; - } - list.add(getPath(info.get_Name())); - } - return list; - } - - public Iterable<FileStore> getFileStores() - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - try - { - sm.checkPermission(new RuntimePermission("getFileStoreAttributes")); - } - catch (SecurityException _) - { - return Collections.emptyList(); - } - } - ArrayList<FileStore> list = new ArrayList<>(); - for (DriveInfo info : DriveInfo.GetDrives()) - { - try - { - if (sm != null) - { - sm.checkRead(info.get_Name()); - } - } - catch (SecurityException _) - { - continue; - } - try - { - list.add(provider.getFileStore(info)); - } - catch (IOException _) - { - } - } - return list; - } - - public Set<String> supportedFileAttributeViews() - { - return attributes; - } - - public Path getPath(String first, String... more) - { - if (more.length == 0) - { - return new NetPath(this, first); - } - else - { - StringBuilder sb = new StringBuilder(first); - String sep = sb.length() == 0 ? "" : separator; - for (String s : more) - { - if (s.length() != 0) - { - sb.append(sep); - sb.append(s); - sep = separator; - } - } - return new NetPath(this, sb.toString()); - } - } - - public PathMatcher getPathMatcher(String syntaxAndPattern) - { - String regex; - if (syntaxAndPattern.startsWith("glob:")) - { - String pattern = syntaxAndPattern.substring(5); - if (WINDOWS) - { - regex = Globs.toWindowsRegexPattern(pattern); - } - else - { - regex = Globs.toUnixRegexPattern(pattern); - } - } - else if (syntaxAndPattern.startsWith("regex:")) - { - regex = syntaxAndPattern.substring(6); - } - else if (syntaxAndPattern.indexOf(':') <= 0) - { - throw new IllegalArgumentException(); - } - else - { - throw new UnsupportedOperationException(); - } - final Pattern pattern = Pattern.compile(regex, WINDOWS ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE : 0); - return new PathMatcher() { - @Override - public boolean matches(Path path) { - return pattern.matcher(path.toString()).matches(); - } - }; - } - - public UserPrincipalLookupService getUserPrincipalLookupService() - { - throw new UnsupportedOperationException(); - } - - static final class NetWatchService implements WatchService - { - static final WatchEvent<?> overflowEvent = new WatchEvent<Object>() { - public Object context() { - return null; - } - public int count() { - return 1; - } - public WatchEvent.Kind<Object> kind() { - return StandardWatchEventKinds.OVERFLOW; - } - }; - private static final WatchKey CLOSED = new WatchKey() { - public boolean isValid() { return false; } - public List<WatchEvent<?>> pollEvents() { return null; } - public boolean reset() { return false; } - public void cancel() { } - public Watchable watchable() { return null; } - }; - private boolean closed; - private final ArrayList<NetWatchKey> keys = new ArrayList<>(); - private final LinkedBlockingQueue<WatchKey> queue = new LinkedBlockingQueue<>(); - - public synchronized void close() - { - if (!closed) - { - closed = true; - for (NetWatchKey key : keys) - { - key.close(); - } - enqueue(CLOSED); - } - } - - private WatchKey checkClosed(WatchKey key) - { - if (key == CLOSED) - { - enqueue(CLOSED); - throw new ClosedWatchServiceException(); - } - return key; - } - - public WatchKey poll() - { - return checkClosed(queue.poll()); - } - - public WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException - { - return checkClosed(queue.poll(timeout, unit)); - } - - public WatchKey take() throws InterruptedException - { - return checkClosed(queue.take()); - } - - void enqueue(WatchKey key) - { - for (;;) - { - try - { - queue.put(key); - return; - } - catch (InterruptedException _) - { - } - } - } - - private final class NetWatchKey implements WatchKey - { - private final NetPath path; - private FileSystemWatcher fsw; - private ArrayList<WatchEvent<?>> list = new ArrayList<>(); - private HashSet<String> modified = new HashSet<>(); - private boolean signaled; - - NetWatchKey(NetPath path) - { - this.path = path; - } - - synchronized void init(final boolean create, final boolean delete, final boolean modify, final boolean overflow, final boolean subtree) - { - if (fsw != null) - { - // we could reuse the FileSystemWatcher, but for now we just recreate it - // (and we run the risk of missing some events while we're doing that) - fsw.Dispose(); - fsw = null; - } - fsw = new FileSystemWatcher(path.path); - if (create) - { - fsw.add_Created(new FileSystemEventHandler(new FileSystemEventHandler.Method() { - public void Invoke(Object sender, FileSystemEventArgs e) { - addEvent(createEvent(e), null); - } - })); - } - if (delete) - { - fsw.add_Deleted(new FileSystemEventHandler(new FileSystemEventHandler.Method() { - public void Invoke(Object sender, FileSystemEventArgs e) { - addEvent(createEvent(e), null); - } - })); - } - if (modify) - { - fsw.add_Changed(new FileSystemEventHandler(new FileSystemEventHandler.Method() { - public void Invoke(Object sender, FileSystemEventArgs e) { - synchronized (NetWatchKey.this) { - if (modified.contains(e.get_Name())) { - // we already have an ENTRY_MODIFY event pending - return; - } - } - addEvent(createEvent(e), e.get_Name()); - } - })); - } - fsw.add_Error(new ErrorEventHandler(new ErrorEventHandler.Method() { - public void Invoke(Object sender, ErrorEventArgs e) { - if (e.GetException() instanceof cli.System.ComponentModel.Win32Exception - && ((cli.System.ComponentModel.Win32Exception)e.GetException()).get_ErrorCode() == -2147467259) { - // the directory we were watching was deleted - cancelledByError(); - } else if (overflow) { - addEvent(overflowEvent, null); - } - } - })); - if (subtree) - { - fsw.set_IncludeSubdirectories(true); - } - fsw.set_EnableRaisingEvents(true); - } - - WatchEvent<?> createEvent(final FileSystemEventArgs e) - { - return new WatchEvent<Path>() { - public Path context() { - return new NetPath((NetFileSystem)path.getFileSystem(), e.get_Name()); - } - public int count() { - return 1; - } - public WatchEvent.Kind<Path> kind() { - switch (e.get_ChangeType().Value) { - case WatcherChangeTypes.Created: - return StandardWatchEventKinds.ENTRY_CREATE; - case WatcherChangeTypes.Deleted: - return StandardWatchEventKinds.ENTRY_DELETE; - default: - return StandardWatchEventKinds.ENTRY_MODIFY; - } - } - }; - } - - void cancelledByError() - { - cancel(); - synchronized (this) - { - if (!signaled) - { - signaled = true; - enqueue(this); - } - } - } - - synchronized void addEvent(WatchEvent<?> event, String modified) - { - list.add(event); - if (modified != null) - { - this.modified.add(modified); - } - if (!signaled) - { - signaled = true; - enqueue(this); - } - } - - public synchronized boolean isValid() - { - return fsw != null; - } - - public synchronized List<WatchEvent<?>> pollEvents() - { - ArrayList<WatchEvent<?>> r = list; - list = new ArrayList<>(); - modified.clear(); - return r; - } - - public synchronized boolean reset() - { - if (fsw == null) - { - return false; - } - if (signaled) - { - if (list.size() == 0) - { - signaled = false; - } - else - { - enqueue(this); - } - } - return true; - } - - void close() - { - if (fsw != null) - { - fsw.Dispose(); - fsw = null; - } - } - - public void cancel() - { - synchronized (NetWatchService.this) - { - keys.remove(this); - close(); - } - } - - public Watchable watchable() - { - return path; - } - } - - synchronized WatchKey register(NetPath path, boolean create, boolean delete, boolean modify, boolean overflow, boolean subtree) - { - if (closed) - { - throw new ClosedWatchServiceException(); - } - NetWatchKey existing = null; - for (NetWatchKey key : keys) - { - if (key.watchable().equals(path)) - { - existing = key; - break; - } - } - if (existing == null) - { - existing = new NetWatchKey(path); - keys.add(existing); - } - existing.init(create, delete, modify, overflow, subtree); - return existing; - } - } - - public WatchService newWatchService() throws IOException - { - return new NetWatchService(); - } -} diff --git a/openjdk/sun/nio/fs/NetFileSystemProvider.java b/openjdk/sun/nio/fs/NetFileSystemProvider.java deleted file mode 100644 index 1f112199..00000000 --- a/openjdk/sun/nio/fs/NetFileSystemProvider.java +++ /dev/null @@ -1,1424 +0,0 @@ -/* - Copyright (C) 2011 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.nio.fs; - -import ikvm.internal.NotYetImplementedError; -import static ikvm.internal.Util.WINDOWS; -import cli.System.IO.Directory; -import cli.System.IO.DirectoryInfo; -import cli.System.IO.DriveInfo; -import cli.System.IO.File; -import cli.System.IO.FileAttributes; -import cli.System.IO.FileInfo; -import cli.System.IO.FileMode; -import cli.System.IO.FileShare; -import cli.System.IO.FileStream; -import cli.System.IO.FileOptions; -import cli.System.Security.AccessControl.FileSystemRights; -import com.sun.nio.file.ExtendedOpenOption; -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.URI; -import java.nio.channels.*; -import java.nio.file.*; -import java.nio.file.attribute.*; -import java.nio.file.spi.FileSystemProvider; -import java.util.concurrent.ExecutorService; -import java.util.Iterator; -import java.util.HashMap; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import sun.nio.ch.WindowsAsynchronousFileChannelImpl; -import sun.nio.ch.FileChannelImpl; -import sun.nio.ch.ThreadPool; - -final class NetFileSystemProvider extends AbstractFileSystemProvider -{ - private final NetFileSystem fs = new NetFileSystem(this); - private final HashMap<String, FileStore> stores = new HashMap<String, FileStore>(); - - final synchronized FileStore getFileStore(DriveInfo drive) throws IOException - { - String name = drive.get_Name().toLowerCase(); - FileStore fs = stores.get(name); - if (fs == null) - { - fs = new NetFileStore(drive); - stores.put(name, fs); - } - return fs; - } - - public String getScheme() - { - return "file"; - } - - public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException - { - throw new FileSystemAlreadyExistsException(); - } - - public FileSystem getFileSystem(URI uri) - { - return fs; - } - - public Path getPath(URI uri) - { - if (WINDOWS) - { - return WindowsUriSupport.fromUri(fs, uri); - } - else - { - return UnixUriUtils.fromUri(fs, uri); - } - } - - public AsynchronousFileChannel newAsynchronousFileChannel(Path path, Set<? extends OpenOption> opts, ExecutorService executor, FileAttribute<?>... attrs) throws IOException - { - NetPath npath = NetPath.from(path); - for (FileAttribute<?> attr : attrs) - { - // null check - attr.getClass(); - throw new NotYetImplementedError(); - } - int mode = FileMode.Open; - int share = FileShare.ReadWrite | FileShare.Delete; - int options = FileOptions.Asynchronous; - boolean read = false; - boolean write = false; - boolean truncate = false; - for (OpenOption opt : opts) - { - if (opt instanceof StandardOpenOption) - { - switch ((StandardOpenOption)opt) - { - case CREATE: - mode = FileMode.Create; - break; - case CREATE_NEW: - mode = FileMode.CreateNew; - break; - case DELETE_ON_CLOSE: - options |= FileOptions.DeleteOnClose; - break; - case DSYNC: - options |= FileOptions.WriteThrough; - break; - case READ: - read = true; - break; - case SPARSE: - break; - case SYNC: - options |= FileOptions.WriteThrough; - break; - case TRUNCATE_EXISTING: - truncate = true; - break; - case WRITE: - write = true; - break; - default: - throw new UnsupportedOperationException(); - } - } - else if (opt instanceof ExtendedOpenOption) - { - switch ((ExtendedOpenOption)opt) - { - case NOSHARE_READ: - share &= ~FileShare.Read; - break; - case NOSHARE_WRITE: - share &= ~FileShare.Write; - break; - case NOSHARE_DELETE: - share &= ~FileShare.Delete; - break; - default: - throw new UnsupportedOperationException(); - } - } - else - { - // null check - opt.getClass(); - throw new UnsupportedOperationException(); - } - } - - if (!read && !write) - { - read = true; - } - - if (truncate) - { - if (mode == FileMode.Open) - { - mode = FileMode.Truncate; - } - } - - int rights = 0; - if (read) - { - rights |= FileSystemRights.Read; - } - if (write) - { - rights |= FileSystemRights.Write; - } - - ThreadPool pool; - if (executor == null) - { - pool = null; - } - else - { - pool = ThreadPool.wrap(executor, 0); - } - - return WindowsAsynchronousFileChannelImpl.open(open(npath.path, mode, rights, share, options), read, write, pool); - } - - public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> opts, FileAttribute<?>... attrs) throws IOException - { - return newFileChannel(path, opts, attrs); - } - - public FileChannel newFileChannel(Path path, Set<? extends OpenOption> opts, FileAttribute<?>... attrs) throws IOException - { - NetPath npath = NetPath.from(path); - for (FileAttribute<?> attr : attrs) - { - // null check - attr.getClass(); - throw new NotYetImplementedError(); - } - int mode = FileMode.Open; - int share = FileShare.ReadWrite | FileShare.Delete; - int options = FileOptions.None; - boolean read = false; - boolean write = false; - boolean append = false; - boolean truncate = false; - for (OpenOption opt : opts) - { - if (opt instanceof StandardOpenOption) - { - switch ((StandardOpenOption)opt) - { - case APPEND: - append = true; - write = true; - mode = FileMode.Append; - break; - case CREATE: - mode = FileMode.Create; - break; - case CREATE_NEW: - mode = FileMode.CreateNew; - break; - case DELETE_ON_CLOSE: - options |= FileOptions.DeleteOnClose; - break; - case DSYNC: - options |= FileOptions.WriteThrough; - break; - case READ: - read = true; - break; - case SPARSE: - break; - case SYNC: - options |= FileOptions.WriteThrough; - break; - case TRUNCATE_EXISTING: - truncate = true; - break; - case WRITE: - write = true; - break; - default: - throw new UnsupportedOperationException(); - } - } - else if (opt instanceof ExtendedOpenOption) - { - switch ((ExtendedOpenOption)opt) - { - case NOSHARE_READ: - share &= ~FileShare.Read; - break; - case NOSHARE_WRITE: - share &= ~FileShare.Write; - break; - case NOSHARE_DELETE: - share &= ~FileShare.Delete; - break; - default: - throw new UnsupportedOperationException(); - } - } - else - { - // null check - opt.getClass(); - throw new UnsupportedOperationException(); - } - } - - if (!read && !write) - { - read = true; - } - - if (read && append) - { - throw new IllegalArgumentException("READ + APPEND not allowed"); - } - - if (truncate) - { - if (append) - { - throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed"); - } - if (mode == FileMode.Open) - { - mode = FileMode.Truncate; - } - } - - int rights = 0; - if (append) - { - // for atomic append to work, we can't set FileSystemRights.Write - rights |= FileSystemRights.AppendData; - } - else - { - if (read) - { - rights |= FileSystemRights.Read; - } - if (write) - { - rights |= FileSystemRights.Write; - } - } - - return FileChannelImpl.open(open(npath.path, mode, rights, share, options), read, write, append, null); - } - - private static FileDescriptor open(String path, int mode, int rights, int share, int options) throws IOException - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - if ((rights & FileSystemRights.Read) != 0) - { - sm.checkRead(path); - } - if ((rights & (FileSystemRights.Write | FileSystemRights.AppendData)) != 0) - { - sm.checkWrite(path); - } - if ((options & FileOptions.DeleteOnClose) != 0) - { - sm.checkDelete(path); - } - } - - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.DirectoryNotFoundException(); - if (false) throw new cli.System.PlatformNotSupportedException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - return FileDescriptor.fromStream(new FileStream(path, FileMode.wrap(mode), FileSystemRights.wrap(rights), FileShare.wrap(share), 8, FileOptions.wrap(options))); - } - catch (cli.System.ArgumentException x) - { - throw new FileSystemException(path, null, x.getMessage()); - } - catch (cli.System.IO.FileNotFoundException _) - { - throw new NoSuchFileException(path); - } - catch (cli.System.IO.DirectoryNotFoundException _) - { - throw new NoSuchFileException(path); - } - catch (cli.System.PlatformNotSupportedException x) - { - throw new UnsupportedOperationException(x.getMessage()); - } - catch (cli.System.IO.IOException x) - { - if (mode == FileMode.CreateNew && File.Exists(path)) - { - throw new FileAlreadyExistsException(path); - } - throw new FileSystemException(path, null, x.getMessage()); - } - catch (cli.System.Security.SecurityException _) - { - throw new AccessDeniedException(path); - } - catch (cli.System.UnauthorizedAccessException _) - { - throw new AccessDeniedException(path); - } - } - - public DirectoryStream<Path> newDirectoryStream(Path dir, final DirectoryStream.Filter<? super Path> filter) throws IOException - { - final String ndir = NetPath.from(dir).path; - // null check - filter.getClass(); - - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(ndir); - } - - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.DirectoryNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - final String[] files = Directory.GetFileSystemEntries(ndir); - return new DirectoryStream<Path>() { - private boolean closed; - public Iterator<Path> iterator() { - if (closed) { - throw new IllegalStateException(); - } - closed = true; - return new Iterator<Path>() { - private int pos; - private Path filtered; - public boolean hasNext() { - if (filtered == null) { - while (pos != files.length) { - Path p = new NetPath(fs, cli.System.IO.Path.Combine(ndir, files[pos++])); - try { - if (filter.accept(p)) { - filtered = p; - break; - } - } catch (IOException x) { - throw new DirectoryIteratorException(x); - } - } - } - return filtered != null; - } - public Path next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - Path p = filtered; - filtered = null; - return p; - } - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - public void close() { - closed = true; - } - }; - } - catch (cli.System.ArgumentException - | cli.System.IO.IOException - | cli.System.Security.SecurityException - | cli.System.UnauthorizedAccessException x) - { - if (File.Exists(ndir)) - { - throw new NotDirectoryException(ndir); - } - throw new IOException(x.getMessage()); - } - } - - public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException - { - NetPath ndir = NetPath.from(dir); - for (FileAttribute<?> attr : attrs) - { - // null check - attr.getClass(); - throw new NotYetImplementedError(); - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkWrite(ndir.path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - Directory.CreateDirectory(ndir.path); - } - catch (cli.System.ArgumentException - | cli.System.IO.IOException - | cli.System.Security.SecurityException - | cli.System.UnauthorizedAccessException x) - { - if (File.Exists(ndir.path)) - { - throw new FileAlreadyExistsException(ndir.path); - } - throw new IOException(x.getMessage()); - } - } - - public void copy(Path source, Path target, CopyOption... options) throws IOException - { - NetPath nsource = NetPath.from(source); - NetPath ntarget = NetPath.from(target); - boolean overwrite = false; - boolean copyAttribs = false; - for (CopyOption opt : options) - { - if (opt == StandardCopyOption.REPLACE_EXISTING) - { - overwrite = true; - } - else if (opt == StandardCopyOption.COPY_ATTRIBUTES) - { - copyAttribs = true; - } - else - { - // null check - opt.getClass(); - throw new UnsupportedOperationException("Unsupported copy option"); - } - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(nsource.path); - sm.checkWrite(ntarget.path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.DirectoryNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - if (File.Exists(ntarget.path)) - { - if (!overwrite) - { - throw new FileAlreadyExistsException(ntarget.path); - } - File.Delete(ntarget.path); - } - if (Directory.Exists(ntarget.path)) - { - if (!overwrite) - { - throw new FileAlreadyExistsException(ntarget.path); - } - try - { - if (false) throw new cli.System.IO.IOException(); - Directory.Delete(ntarget.path); - } - catch (cli.System.IO.IOException _) - { - // HACK we assume that the IOException is caused by the directory not being empty - throw new DirectoryNotEmptyException(ntarget.path); - } - } - if (Directory.Exists(nsource.path)) - { - Directory.CreateDirectory(ntarget.path); - } - else - { - File.Copy(nsource.path, ntarget.path, overwrite); - } - if (copyAttribs) - { - if (Directory.Exists(ntarget.path)) - { - File.SetAttributes(ntarget.path, File.GetAttributes(nsource.path)); - Directory.SetCreationTimeUtc(ntarget.path, File.GetCreationTimeUtc(nsource.path)); - Directory.SetLastAccessTimeUtc(ntarget.path, File.GetLastAccessTimeUtc(nsource.path)); - Directory.SetLastWriteTimeUtc(ntarget.path, File.GetLastWriteTimeUtc(nsource.path)); - } - else - { - File.SetAttributes(ntarget.path, File.GetAttributes(nsource.path)); - File.SetCreationTimeUtc(ntarget.path, File.GetCreationTimeUtc(nsource.path)); - File.SetLastAccessTimeUtc(ntarget.path, File.GetLastAccessTimeUtc(nsource.path)); - File.SetLastWriteTimeUtc(ntarget.path, File.GetLastWriteTimeUtc(nsource.path)); - } - } - } - catch (cli.System.IO.FileNotFoundException x) - { - throw new NoSuchFileException(x.get_FileName()); - } - catch (cli.System.IO.DirectoryNotFoundException x) - { - throw new NoSuchFileException(nsource.path, ntarget.path, x.getMessage()); - } - catch (cli.System.IO.IOException | cli.System.ArgumentException x) - { - throw new FileSystemException(nsource.path, ntarget.path, x.getMessage()); - } - catch (cli.System.Security.SecurityException | cli.System.UnauthorizedAccessException x) - { - throw new AccessDeniedException(nsource.path, ntarget.path, x.getMessage()); - } - } - - public void move(Path source, Path target, CopyOption... options) throws IOException - { - NetPath nsource = NetPath.from(source); - NetPath ntarget = NetPath.from(target); - boolean overwrite = false; - for (CopyOption opt : options) - { - if (opt == StandardCopyOption.REPLACE_EXISTING) - { - overwrite = true; - } - else if (opt == StandardCopyOption.ATOMIC_MOVE) - { - throw new AtomicMoveNotSupportedException(nsource.path, ntarget.path, "Unsupported copy option"); - } - else - { - // null check - opt.getClass(); - throw new UnsupportedOperationException("Unsupported copy option"); - } - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(nsource.path); - sm.checkWrite(ntarget.path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.DirectoryNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - if (File.Exists(ntarget.path)) - { - if (!overwrite) - { - throw new FileAlreadyExistsException(ntarget.path); - } - File.Delete(ntarget.path); - } - if (Directory.Exists(ntarget.path)) - { - if (!overwrite) - { - throw new FileAlreadyExistsException(ntarget.path); - } - try - { - if (false) throw new cli.System.IO.IOException(); - Directory.Delete(ntarget.path); - } - catch (cli.System.IO.IOException _) - { - // HACK we assume that the IOException is caused by the directory not being empty - throw new DirectoryNotEmptyException(ntarget.path); - } - } - if (Directory.Exists(nsource.path)) - { - Directory.Move(nsource.path, ntarget.path); - } - else - { - File.Move(nsource.path, ntarget.path); - } - } - catch (cli.System.IO.FileNotFoundException x) - { - throw new NoSuchFileException(x.get_FileName()); - } - catch (cli.System.IO.DirectoryNotFoundException x) - { - throw new NoSuchFileException(nsource.path, ntarget.path, x.getMessage()); - } - catch (cli.System.IO.IOException | cli.System.ArgumentException x) - { - throw new FileSystemException(nsource.path, ntarget.path, x.getMessage()); - } - catch (cli.System.Security.SecurityException | cli.System.UnauthorizedAccessException x) - { - throw new AccessDeniedException(nsource.path, ntarget.path, x.getMessage()); - } - } - - public boolean isSameFile(Path path, Path path2) throws IOException - { - if (path.equals(path2)) - { - return true; - } - if (!(path instanceof NetPath && path2 instanceof NetPath)) - { - // null check - path2.getClass(); - return false; - } - return path.toRealPath().equals(path2.toRealPath()); - } - - public boolean isHidden(Path path) throws IOException - { - String npath = NetPath.from(path).path; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(npath); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - return (File.GetAttributes(npath).Value & (cli.System.IO.FileAttributes.Hidden | cli.System.IO.FileAttributes.Directory)) == cli.System.IO.FileAttributes.Hidden; - } - catch (cli.System.IO.FileNotFoundException x) - { - throw new NoSuchFileException(npath); - } - catch (cli.System.IO.IOException | cli.System.ArgumentException x) - { - throw new IOException(x.getMessage()); - } - } - - private static class NetFileStore extends FileStore - { - private final DriveInfo info; - private final String name; - private final String type; - - NetFileStore(DriveInfo info) throws IOException - { - this.info = info; - try - { - if (false) throw new cli.System.IO.IOException(); - name = info.get_VolumeLabel(); - type = info.get_DriveFormat(); - } - catch (cli.System.IO.IOException x) - { - throw new IOException(x.getMessage()); - } - } - - public Object getAttribute(String attribute) throws IOException - { - switch (attribute) - { - case "totalSpace": - return getTotalSpace(); - case "unallocatedSpace": - return getUnallocatedSpace(); - case "usableSpace": - return getUsableSpace(); - default: - throw new UnsupportedOperationException(); - } - } - - public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) - { - return null; - } - - public long getTotalSpace() throws IOException - { - try - { - if (false) throw new cli.System.IO.IOException(); - return info.get_TotalSize(); - } - catch (cli.System.IO.IOException x) - { - throw new IOException(x.getMessage()); - } - } - - public long getUnallocatedSpace() throws IOException - { - try - { - if (false) throw new cli.System.IO.IOException(); - return info.get_TotalFreeSpace(); - } - catch (cli.System.IO.IOException x) - { - throw new IOException(x.getMessage()); - } - } - - public long getUsableSpace() throws IOException - { - try - { - if (false) throw new cli.System.IO.IOException(); - return info.get_AvailableFreeSpace(); - } - catch (cli.System.IO.IOException x) - { - throw new IOException(x.getMessage()); - } - } - - public boolean isReadOnly() - { - return false; - } - - public String name() - { - return name; - } - - public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) - { - // null check - type.getClass(); - return type == BasicFileAttributeView.class || type == DosFileAttributeView.class; - } - - public boolean supportsFileAttributeView(String name) - { - return name.equals("basic") || name.equals("dos"); - } - - public String type() - { - return type; - } - - public String toString() - { - return name + " (" + info.get_Name().charAt(0) + ":)"; - } - } - - public FileStore getFileStore(Path path) throws IOException - { - NetPath npath = NetPath.from(path.toAbsolutePath()); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(npath.path); - } - return getFileStore(new DriveInfo(npath.path)); - } - - public void checkAccess(Path path, AccessMode... modes) throws IOException - { - String npath = NetPath.from(path).path; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - if (modes.length == 0) - { - sm.checkRead(npath); - } - for (AccessMode m : modes) - { - switch (m) - { - case READ: - sm.checkRead(npath); - break; - case WRITE: - sm.checkWrite(npath); - break; - case EXECUTE: - sm.checkExec(npath); - break; - default: - throw new UnsupportedOperationException(); - } - } - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.DirectoryNotFoundException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.NotSupportedException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - // note that File.GetAttributes() works for directories as well - int attr = File.GetAttributes(npath).Value; - for (AccessMode m : modes) - { - switch (m) - { - case READ: - case EXECUTE: - break; - case WRITE: - if ((attr & (cli.System.IO.FileAttributes.ReadOnly | cli.System.IO.FileAttributes.Directory)) == cli.System.IO.FileAttributes.ReadOnly) - { - throw new AccessDeniedException(npath, null, "file has read-only attribute set"); - } - if (getFileStore(path).isReadOnly()) - { - throw new AccessDeniedException(npath, null, "volume is read-only"); - } - break; - default: - throw new UnsupportedOperationException(); - } - } - } - catch (cli.System.IO.FileNotFoundException | cli.System.IO.DirectoryNotFoundException _) - { - throw new NoSuchFileException(npath); - } - catch (cli.System.Security.SecurityException | cli.System.UnauthorizedAccessException x) - { - throw new AccessDeniedException(npath, null, x.getMessage()); - } - catch (cli.System.ArgumentException | cli.System.IO.IOException | cli.System.NotSupportedException x) - { - throw new IOException(x.getMessage()); - } - } - - private static class BasicFileAttributesViewImpl extends AbstractBasicFileAttributeView - { - protected final String path; - - BasicFileAttributesViewImpl(String path) - { - this.path = path; - } - - public BasicFileAttributes readAttributes() throws IOException - { - return DosFileAttributesViewImpl.readAttributesImpl(path); - } - - public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkWrite(path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.NotSupportedException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - if (File.Exists(path)) - { - if (lastModifiedTime != null) - { - File.SetLastWriteTimeUtc(path, toDateTime(lastModifiedTime)); - } - if (lastAccessTime != null) - { - File.SetLastAccessTimeUtc(path, toDateTime(lastAccessTime)); - } - if (createTime != null) - { - File.SetCreationTimeUtc(path, toDateTime(createTime)); - } - } - else if (Directory.Exists(path)) - { - if (lastModifiedTime != null) - { - Directory.SetLastWriteTimeUtc(path, toDateTime(lastModifiedTime)); - } - if (lastAccessTime != null) - { - Directory.SetLastAccessTimeUtc(path, toDateTime(lastAccessTime)); - } - if (createTime != null) - { - Directory.SetCreationTimeUtc(path, toDateTime(createTime)); - } - } - else - { - throw new NoSuchFileException(path); - } - } - catch (cli.System.ArgumentException - | cli.System.IO.IOException - | cli.System.NotSupportedException - | cli.System.Security.SecurityException - | cli.System.UnauthorizedAccessException x) - { - throw new IOException(x.getMessage()); - } - } - } - - private static class DosFileAttributesViewImpl extends BasicFileAttributesViewImpl implements DosFileAttributeView - { - private static final String READONLY_NAME = "readonly"; - private static final String ARCHIVE_NAME = "archive"; - private static final String SYSTEM_NAME = "system"; - private static final String HIDDEN_NAME = "hidden"; - private static final String ATTRIBUTES_NAME = "attributes"; - private static final Set<String> dosAttributeNames = Util.newSet(basicAttributeNames, READONLY_NAME, ARCHIVE_NAME, SYSTEM_NAME, HIDDEN_NAME, ATTRIBUTES_NAME); - - DosFileAttributesViewImpl(String path) - { - super(path); - } - - public String name() - { - return "dos"; - } - - public DosFileAttributes readAttributes() throws IOException - { - return readAttributesImpl(path); - } - - private static class DosFileAttributesImpl implements DosFileAttributes - { - private final FileInfo info; - - DosFileAttributesImpl(FileInfo info) - { - this.info = info; - } - - int attributes() - { - return info.get_Attributes().Value; - } - - public FileTime creationTime() - { - return toFileTime(info.get_CreationTimeUtc()); - } - - public Object fileKey() - { - return null; - } - - public boolean isDirectory() - { - return (info.get_Attributes().Value & cli.System.IO.FileAttributes.Directory) != 0; - } - - public boolean isOther() - { - return false; - } - - public boolean isRegularFile() - { - return (info.get_Attributes().Value & cli.System.IO.FileAttributes.Directory) == 0; - } - - public boolean isSymbolicLink() - { - return false; - } - - public FileTime lastAccessTime() - { - return toFileTime(info.get_LastAccessTimeUtc()); - } - - public FileTime lastModifiedTime() - { - return toFileTime(info.get_LastWriteTimeUtc()); - } - - public long size() - { - return info.get_Exists() ? info.get_Length() : 0; - } - - public boolean isArchive() - { - return (info.get_Attributes().Value & cli.System.IO.FileAttributes.Archive) != 0; - } - - public boolean isHidden() - { - return (info.get_Attributes().Value & cli.System.IO.FileAttributes.Hidden) != 0; - } - - public boolean isReadOnly() - { - return (info.get_Attributes().Value & cli.System.IO.FileAttributes.ReadOnly) != 0; - } - - public boolean isSystem() - { - return (info.get_Attributes().Value & cli.System.IO.FileAttributes.System) != 0; - } - } - - static DosFileAttributesImpl readAttributesImpl(String path) throws IOException - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - FileInfo info = new FileInfo(path); - // We have to rely on the (undocumented) fact that FileInfo.Attributes returns -1 - // when the path does not exist. We need this to work for both files and directories - // and this is the only efficient way to do that. - if (info.get_Attributes().Value == -1) - { - throw new NoSuchFileException(path); - } - return new DosFileAttributesImpl(info); - } - catch (cli.System.IO.FileNotFoundException _) - { - throw new NoSuchFileException(path); - } - catch (cli.System.IO.IOException | cli.System.ArgumentException x) - { - throw new IOException(x.getMessage()); - } - } - - public void setArchive(boolean value) throws IOException - { - setAttribute(cli.System.IO.FileAttributes.Archive, value); - } - - public void setHidden(boolean value) throws IOException - { - setAttribute(cli.System.IO.FileAttributes.Hidden, value); - } - - public void setReadOnly(boolean value) throws IOException - { - setAttribute(cli.System.IO.FileAttributes.ReadOnly, value); - } - - public void setSystem(boolean value) throws IOException - { - setAttribute(cli.System.IO.FileAttributes.System, value); - } - - private void setAttribute(int attr, boolean value) throws IOException - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkWrite(path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.IOException(); - FileInfo info = new FileInfo(path); - if (value) - { - info.set_Attributes(cli.System.IO.FileAttributes.wrap(info.get_Attributes().Value | attr)); - } - else - { - info.set_Attributes(cli.System.IO.FileAttributes.wrap(info.get_Attributes().Value & ~attr)); - } - } - catch (cli.System.IO.FileNotFoundException _) - { - throw new NoSuchFileException(path); - } - catch (cli.System.ArgumentException - | cli.System.IO.IOException x) - { - throw new IOException(x.getMessage()); - } - } - - public Map<String,Object> readAttributes(String[] attributes) throws IOException - { - AttributesBuilder builder = AttributesBuilder.create(dosAttributeNames, attributes); - DosFileAttributesImpl attrs = readAttributesImpl(path); - addRequestedBasicAttributes(attrs, builder); - if (builder.match(READONLY_NAME)) - { - builder.add(READONLY_NAME, attrs.isReadOnly()); - } - if (builder.match(ARCHIVE_NAME)) - { - builder.add(ARCHIVE_NAME, attrs.isArchive()); - } - if (builder.match(SYSTEM_NAME)) - { - builder.add(SYSTEM_NAME, attrs.isSystem()); - } - if (builder.match(HIDDEN_NAME)) - { - builder.add(HIDDEN_NAME, attrs.isHidden()); - } - if (builder.match(ATTRIBUTES_NAME)) - { - builder.add(ATTRIBUTES_NAME, attrs.attributes()); - } - return builder.unmodifiableMap(); - } - - public void setAttribute(String attribute, Object value) throws IOException - { - switch (attribute) - { - case READONLY_NAME: - setReadOnly((Boolean)value); - break; - case ARCHIVE_NAME: - setArchive((Boolean)value); - break; - case SYSTEM_NAME: - setSystem((Boolean)value); - break; - case HIDDEN_NAME: - setHidden((Boolean)value); - break; - default: - super.setAttribute(attribute, value); - break; - } - } - } - - private static void validateLinkOption(LinkOption... options) - { - for (LinkOption option : options) - { - if (option == LinkOption.NOFOLLOW_LINKS) - { - // ignored - } - else - { - // null check - option.getClass(); - throw new UnsupportedOperationException(); - } - } - } - - public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) - { - String npath = NetPath.from(path).path; - validateLinkOption(options); - if (type == BasicFileAttributeView.class) - { - return (V)new BasicFileAttributesViewImpl(npath); - } - else if (type == DosFileAttributeView.class) - { - return (V)new DosFileAttributesViewImpl(npath); - } - else - { - // null check - type.getClass(); - return null; - } - } - - public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException - { - String npath = NetPath.from(path).path; - // null check - type.getClass(); - validateLinkOption(options); - if (type != BasicFileAttributes.class && type != DosFileAttributes.class) - { - throw new UnsupportedOperationException(); - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(npath); - } - return (A)DosFileAttributesViewImpl.readAttributesImpl(npath); - } - - DynamicFileAttributeView getFileAttributeView(Path file, String name, LinkOption... options) - { - validateLinkOption(options); - if (name.equals("basic")) - { - return new BasicFileAttributesViewImpl(NetPath.from(file).path); - } - else if (name.equals("dos")) - { - return new DosFileAttributesViewImpl(NetPath.from(file).path); - } - else - { - return null; - } - } - - boolean implDelete(Path file, boolean failIfNotExists) throws IOException - { - String path = NetPath.from(file).path; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkDelete(path); - } - try - { - if (false) throw new cli.System.ArgumentException(); - if (false) throw new cli.System.IO.FileNotFoundException(); - if (false) throw new cli.System.IO.DirectoryNotFoundException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.Security.SecurityException(); - if (false) throw new cli.System.UnauthorizedAccessException(); - int attr = cli.System.IO.File.GetAttributes(path).Value; - if ((attr & cli.System.IO.FileAttributes.Directory) != 0) - { - try - { - if (false) throw new cli.System.IO.IOException(); - cli.System.IO.Directory.Delete(path); - } - catch (cli.System.IO.IOException _) - { - // HACK we assume that the IOException is caused by the directory not being empty - throw new DirectoryNotEmptyException(path); - } - return true; - } - else - { - cli.System.IO.File.Delete(path); - return true; - } - } - catch (cli.System.ArgumentException x) - { - throw new FileSystemException(path, null, x.getMessage()); - } - catch (cli.System.IO.FileNotFoundException _) - { - if (failIfNotExists) - { - throw new NoSuchFileException(path); - } - else - { - return false; - } - } - catch (cli.System.IO.DirectoryNotFoundException _) - { - if (failIfNotExists) - { - throw new NoSuchFileException(path); - } - else - { - return false; - } - } - catch (cli.System.IO.IOException x) - { - throw new FileSystemException(path, null, x.getMessage()); - } - catch (cli.System.Security.SecurityException _) - { - throw new AccessDeniedException(path); - } - catch (cli.System.UnauthorizedAccessException _) - { - throw new AccessDeniedException(path); - } - } - - static FileTime toFileTime(cli.System.DateTime dateTime) - { - return FileTime.from((dateTime.get_Ticks() - 621355968000000000L) / 10, java.util.concurrent.TimeUnit.MICROSECONDS); - } - - static cli.System.DateTime toDateTime(FileTime fileTime) - { - return new cli.System.DateTime(fileTime.to(java.util.concurrent.TimeUnit.MICROSECONDS) * 10 + 621355968000000000L); - } -} diff --git a/openjdk/sun/nio/fs/NetPath.java b/openjdk/sun/nio/fs/NetPath.java deleted file mode 100644 index 6861a1e2..00000000 --- a/openjdk/sun/nio/fs/NetPath.java +++ /dev/null @@ -1,569 +0,0 @@ -/* - Copyright (C) 2011 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.nio.fs; - -import com.sun.nio.file.ExtendedWatchEventModifier; -import com.sun.nio.file.SensitivityWatchEventModifier; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.nio.file.*; -import java.util.ArrayList; -import java.util.Iterator; -import static ikvm.internal.Util.MACOSX; -import static ikvm.internal.Util.WINDOWS; - -final class NetPath extends AbstractPath -{ - private static final char[] invalid = cli.System.IO.Path.GetInvalidFileNameChars(); - private final NetFileSystem fs; - final String path; - - NetPath(NetFileSystem fs, String path) - { - if (WINDOWS) - { - path = WindowsPathParser.parse(path).path(); - } - else - { - StringBuilder sb = null; - int separatorCount = 0; - boolean prevWasSeparator = false; - for (int i = 0; i < path.length(); i++) - { - char c = path.charAt(i); - if (c == 0) - { - throw new InvalidPathException(path, "Nul character not allowed"); - } - else if (c == '/') - { - if (prevWasSeparator) - { - if (sb == null) - { - sb = new StringBuilder(); - sb.append(path, 0, i); - } - continue; - } - separatorCount++; - prevWasSeparator = true; - } - else - { - prevWasSeparator = false; - } - if (sb != null) - { - sb.append(c); - } - } - if (sb != null) - { - path = sb.toString(); - } - if (path.length() > 1 && path.charAt(path.length() - 1) == '/') - { - path = path.substring(0, path.length() - 1); - } - } - this.fs = fs; - this.path = path; - } - - public FileSystem getFileSystem() - { - return fs; - } - - public boolean isAbsolute() - { - return cli.System.IO.Path.IsPathRooted(path) - && (!WINDOWS || path.startsWith("\\\\") || (path.length() >= 3 && path.charAt(1) == ':' && path.charAt(2) == '\\')); - } - - public Path getRoot() - { - int len = getRootLength(); - return len == 0 ? null : new NetPath(fs, path.substring(0, len)); - } - - private int getRootLength() - { - if (WINDOWS) - { - if (path.length() >= 2 && path.charAt(1) == ':') - { - if (path.length() >= 3 && path.charAt(2) == '\\') - { - return 3; - } - else - { - return 2; - } - } - else if (path.startsWith("\\\\")) - { - return path.indexOf('\\', path.indexOf('\\', 2) + 1) + 1; - } - } - - if (path.length() >= 1 && path.charAt(0) == cli.System.IO.Path.DirectorySeparatorChar) - { - return 1; - } - else - { - return 0; - } - } - - public Path getFileName() - { - if (path.length() == 0) - { - return this; - } - if (path.length() == getRootLength()) - { - return null; - } - String name = cli.System.IO.Path.GetFileName(path); - if (name == null || name.length() == 0) - { - return null; - } - return new NetPath(fs, name); - } - - public Path getParent() - { - if (path.length() == getRootLength()) - { - return null; - } - String parent = cli.System.IO.Path.GetDirectoryName(path); - if (parent == null || parent.length() == 0) - { - return null; - } - return new NetPath(fs, parent); - } - - public int getNameCount() - { - int len = getRootLength(); - if (path.length() == len) - { - return len == 0 ? 1 : 0; - } - int count = 1; - for (int i = len; i < path.length(); i++) - { - if (path.charAt(i) == cli.System.IO.Path.DirectorySeparatorChar) - { - count++; - } - } - return count; - } - - public Path getName(int index) - { - return new NetPath(fs, getNameImpl(index)); - } - - private String getNameImpl(int index) - { - for (int pos = getRootLength(); pos < path.length(); index--) - { - int next = path.indexOf(cli.System.IO.Path.DirectorySeparatorChar, pos); - if (index == 0) - { - return next == -1 ? path.substring(pos) : path.substring(pos, next); - } - if (next == -1) - { - break; - } - pos = next + 1; - } - if (path.length() == 0 && index == 0) - { - return ""; - } - throw new IllegalArgumentException(); - } - - public Path subpath(int beginIndex, int endIndex) - { - StringBuilder sb = new StringBuilder(); - for (int i = beginIndex; i < endIndex; i++) - { - if (i != beginIndex) - { - sb.append(cli.System.IO.Path.DirectorySeparatorChar); - } - sb.append(getNameImpl(i)); - } - return new NetPath(fs, sb.toString()); - } - - public boolean startsWith(Path other) - { - String npath = NetPath.from(other).path; - if (npath.length() == 0) - { - return path.length() == 0; - } - return path.regionMatches(WINDOWS, 0, npath, 0, npath.length()) - && (npath.length() == getRootLength() - || (npath.length() > getRootLength() - && (path.length() == npath.length() - || (path.length() > npath.length() && path.charAt(npath.length()) == cli.System.IO.Path.DirectorySeparatorChar)))); - } - - public boolean endsWith(Path other) - { - NetPath nother = NetPath.from(other); - String npath = nother.path; - if (npath.length() > path.length()) - { - return false; - } - if (npath.length() == 0) - { - return path.length() == 0; - } - int nameCount = getNameCount(); - int otherNameCount = nother.getNameCount(); - if (otherNameCount > nameCount) - { - return false; - } - int otherRootLength = nother.getRootLength(); - if (otherRootLength > 0) - { - if (otherNameCount != nameCount - || getRootLength() != otherRootLength - || !path.regionMatches(WINDOWS, 0, npath, 0, otherRootLength)) - { - return false; - } - } - int skip = nameCount - otherNameCount; - for (int i = 0; i < otherNameCount; i++) - { - String s1 = getNameImpl(i + skip); - String s2 = nother.getNameImpl(i); - if (s1.length() != s2.length() || !s1.regionMatches(WINDOWS, 0, s2, 0, s1.length())) - { - return false; - } - } - return true; - } - - public Path normalize() - { - int rootLength = getRootLength(); - ArrayList<String> list = new ArrayList<>(); - for (int i = 0, count = getNameCount(); i < count; i++) - { - String s = getNameImpl(i); - if (s.equals("..")) - { - if (list.size() == 0) - { - if (rootLength == 0 || (WINDOWS && rootLength == 2)) - { - list.add(".."); - } - } - else if (list.get(list.size() - 1).equals("..")) - { - list.add(".."); - } - else - { - list.remove(list.size() - 1); - } - } - else if (!s.equals(".")) - { - list.add(s); - } - } - StringBuilder sb = new StringBuilder(); - sb.append(path.substring(0, getRootLength())); - for (int i = 0; i < list.size(); i++) - { - if (i != 0) - { - sb.append(cli.System.IO.Path.DirectorySeparatorChar); - } - sb.append(list.get(i)); - } - return new NetPath(fs, sb.toString()); - } - - public Path resolve(Path other) - { - NetPath nother = NetPath.from(other); - String npath = nother.path; - if (nother.isAbsolute()) - { - return other; - } - if (npath.length() == 0) - { - return this; - } - if (WINDOWS) - { - if (nother.getRootLength() == 2 && getRootLength() == 3 && (path.charAt(0) | 0x20) == (npath.charAt(0) | 0x20)) - { - // we're in the case where we have a root "x:\" and other "x:", so we have to chop off "x:" from other because - // otherwise Path.Combine will just return other - npath = npath.substring(2); - } - else if (nother.getRootLength() == 1 && getRootLength() > 3) - { - // we're in the case where we have a root "\\host\share\" and other "\", - // we have to manually handle this because Path.Combine doesn't do the right thing - return new NetPath(fs, path.substring(0, getRootLength()) + npath); - } - } - return new NetPath(fs, cli.System.IO.Path.Combine(path, npath)); - } - - public Path relativize(Path other) - { - NetPath nother = NetPath.from(other); - if (equals(nother)) - { - return new NetPath(fs, ""); - } - int rootLength = getRootLength(); - if (nother.getRootLength() != rootLength || !path.regionMatches(true, 0, nother.path, 0, rootLength)) - { - throw new IllegalArgumentException("'other' has different root"); - } - int nameCount = getNameCount(); - int otherNameCount = nother.getNameCount(); - int count = Math.min(nameCount, otherNameCount); - int i = 0; - // skip the common parts - for (; i < count && getNameImpl(i).equals(nother.getNameImpl(i)); i++) - { - } - // remove the unused parts of our path - StringBuilder sb = new StringBuilder(); - for (int j = i; j < nameCount; j++) - { - sb.append("..\\"); - } - // append the new parts of other - for (int j = i; j < otherNameCount; j++) - { - if (j != i) - { - sb.append("\\"); - } - sb.append(nother.getNameImpl(j)); - } - return new NetPath(fs, sb.toString()); - } - - public URI toUri() - { - if (WINDOWS) - { - return WindowsUriSupport.toUri(this); - } - else - { - return UnixUriUtils.toUri(this); - } - } - - public NetPath toAbsolutePath() - { - if (isAbsolute()) - { - return this; - } - // System.getProperty("user.dir") will trigger the specified security check - return new NetPath(fs, cli.System.IO.Path.GetFullPath(cli.System.IO.Path.Combine(System.getProperty("user.dir"), path))); - } - - public Path toRealPath(LinkOption... options) throws IOException - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(path); - if (!isAbsolute()) - { - sm.checkPropertyAccess("user.dir"); - } - } - return new NetPath(fs, toRealPathImpl(path)); - } - - private static native String toRealPathImpl(String path); - - public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException - { - if (!(watcher instanceof NetFileSystem.NetWatchService)) - { - // null check - watcher.getClass(); - throw new ProviderMismatchException(); - } - boolean create = false; - boolean delete = false; - boolean modify = false; - boolean overflow = false; - boolean subtree = false; - for (WatchEvent.Kind<?> kind : events) - { - if (kind == StandardWatchEventKinds.ENTRY_CREATE) - { - create = true; - } - else if (kind == StandardWatchEventKinds.ENTRY_DELETE) - { - delete = true; - } - else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) - { - modify = true; - } - else if (kind == StandardWatchEventKinds.OVERFLOW) - { - overflow = true; - } - else - { - // null check - kind.getClass(); - throw new UnsupportedOperationException(); - } - } - if (!create && !delete && !modify) - { - throw new IllegalArgumentException(); - } - for (WatchEvent.Modifier modifier : modifiers) - { - if (modifier == ExtendedWatchEventModifier.FILE_TREE) - { - subtree = true; - } - else if (modifier instanceof SensitivityWatchEventModifier) - { - // ignore - } - else - { - // null check - modifier.getClass(); - throw new UnsupportedOperationException(); - } - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkRead(path); - if (subtree) - { - sm.checkRead(path + cli.System.IO.Path.DirectorySeparatorChar + '-'); - } - } - return ((NetFileSystem.NetWatchService)watcher).register(this, create, delete, modify, overflow, subtree); - } - - public int compareTo(Path other) - { - String path2 = ((NetPath)other).path; - int len1 = path.length(); - int len2 = path2.length(); - int min = Math.min(len1, len2); - for (int i = 0; i < min; i++) - { - char c1 = path.charAt(i); - char c2 = path2.charAt(i); - if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) - { - return c1 - c2; - } - } - return len1 - len2; - } - - public boolean equals(Object other) - { - if (!(other instanceof NetPath)) - { - return false; - } - return compareTo((NetPath)other) == 0; - } - - public int hashCode() - { - int hash = 0; - for (int i = 0; i < path.length(); i++) - { - hash = 97 * hash + Character.toUpperCase(path.charAt(i)); - } - return hash; - } - - public String toString() - { - return path; - } - - boolean isUnc() - { - return WINDOWS && getRootLength() > 3; - } - - static NetPath from(Path path) - { - if (!(path instanceof NetPath)) - { - // null check - path.getClass(); - throw new ProviderMismatchException(); - } - return (NetPath)path; - } -} diff --git a/openjdk/sun/nio/fs/UnixUriUtils.java b/openjdk/sun/nio/fs/UnixUriUtils.java deleted file mode 100644 index 0c1135fc..00000000 --- a/openjdk/sun/nio/fs/UnixUriUtils.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.fs; - -import java.nio.file.Path; -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.util.Arrays; - -/** - * Unix specific Path <--> URI conversion - */ - -class UnixUriUtils { - private UnixUriUtils() { } - - /** - * Converts URI to Path - */ - static Path fromUri(NetFileSystem fs, URI uri) { - if (!uri.isAbsolute()) - throw new IllegalArgumentException("URI is not absolute"); - if (uri.isOpaque()) - throw new IllegalArgumentException("URI is not hierarchical"); - String scheme = uri.getScheme(); - if ((scheme == null) || !scheme.equalsIgnoreCase("file")) - throw new IllegalArgumentException("URI scheme is not \"file\""); - if (uri.getAuthority() != null) - throw new IllegalArgumentException("URI has an authority component"); - if (uri.getFragment() != null) - throw new IllegalArgumentException("URI has a fragment component"); - if (uri.getQuery() != null) - throw new IllegalArgumentException("URI has a query component"); - - // compatability with java.io.File - if (!uri.toString().startsWith("file:///")) - return new File(uri).toPath(); - - // transformation use raw path - String p = uri.getRawPath(); - int len = p.length(); - if (len == 0) - throw new IllegalArgumentException("URI path component is empty"); - - // transform escaped octets and unescaped characters to bytes - if (p.endsWith("/") && len > 1) - p = p.substring(0, len - 1); - - return new NetPath(fs, p); - } - - /** - * Converts Path to URI - */ - static URI toUri(NetPath up) { - byte[] path = up.toAbsolutePath().toString().getBytes(); - StringBuilder sb = new StringBuilder("file:///"); - assert path[0] == '/'; - for (int i=1; i<path.length; i++) { - char c = (char)(path[i] & 0xff); - if (match(c, L_PATH, H_PATH)) { - sb.append(c); - } else { - sb.append('%'); - sb.append(hexDigits[(c >> 4) & 0x0f]); - sb.append(hexDigits[(c) & 0x0f]); - } - } - - // trailing slash if directory - if (sb.charAt(sb.length()-1) != '/') { - try { - if (cli.System.IO.Directory.Exists(up.path)) - sb.append('/'); - } catch (Throwable x) { - // ignore - } - } - - try { - return new URI(sb.toString()); - } catch (URISyntaxException x) { - throw new AssertionError(x); // should not happen - } - } - - // The following is copied from java.net.URI - - // Compute the low-order mask for the characters in the given string - private static long lowMask(String chars) { - int n = chars.length(); - long m = 0; - for (int i = 0; i < n; i++) { - char c = chars.charAt(i); - if (c < 64) - m |= (1L << c); - } - return m; - } - - // Compute the high-order mask for the characters in the given string - private static long highMask(String chars) { - int n = chars.length(); - long m = 0; - for (int i = 0; i < n; i++) { - char c = chars.charAt(i); - if ((c >= 64) && (c < 128)) - m |= (1L << (c - 64)); - } - return m; - } - - // Compute a low-order mask for the characters - // between first and last, inclusive - private static long lowMask(char first, char last) { - long m = 0; - int f = Math.max(Math.min(first, 63), 0); - int l = Math.max(Math.min(last, 63), 0); - for (int i = f; i <= l; i++) - m |= 1L << i; - return m; - } - - // Compute a high-order mask for the characters - // between first and last, inclusive - private static long highMask(char first, char last) { - long m = 0; - int f = Math.max(Math.min(first, 127), 64) - 64; - int l = Math.max(Math.min(last, 127), 64) - 64; - for (int i = f; i <= l; i++) - m |= 1L << i; - return m; - } - - // Tell whether the given character is permitted by the given mask pair - private static boolean match(char c, long lowMask, long highMask) { - if (c < 64) - return ((1L << c) & lowMask) != 0; - if (c < 128) - return ((1L << (c - 64)) & highMask) != 0; - return false; - } - - // decode - private static int decode(char c) { - if ((c >= '0') && (c <= '9')) - return c - '0'; - if ((c >= 'a') && (c <= 'f')) - return c - 'a' + 10; - if ((c >= 'A') && (c <= 'F')) - return c - 'A' + 10; - throw new AssertionError(); - } - - // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | - // "8" | "9" - private static final long L_DIGIT = lowMask('0', '9'); - private static final long H_DIGIT = 0L; - - // upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | - // "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | - // "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" - private static final long L_UPALPHA = 0L; - private static final long H_UPALPHA = highMask('A', 'Z'); - - // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | - // "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | - // "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" - private static final long L_LOWALPHA = 0L; - private static final long H_LOWALPHA = highMask('a', 'z'); - - // alpha = lowalpha | upalpha - private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA; - private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA; - - // alphanum = alpha | digit - private static final long L_ALPHANUM = L_DIGIT | L_ALPHA; - private static final long H_ALPHANUM = H_DIGIT | H_ALPHA; - - // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | - // "(" | ")" - private static final long L_MARK = lowMask("-_.!~*'()"); - private static final long H_MARK = highMask("-_.!~*'()"); - - // unreserved = alphanum | mark - private static final long L_UNRESERVED = L_ALPHANUM | L_MARK; - private static final long H_UNRESERVED = H_ALPHANUM | H_MARK; - - // pchar = unreserved | escaped | - // ":" | "@" | "&" | "=" | "+" | "$" | "," - private static final long L_PCHAR - = L_UNRESERVED | lowMask(":@&=+$,"); - private static final long H_PCHAR - = H_UNRESERVED | highMask(":@&=+$,"); - - // All valid path characters - private static final long L_PATH = L_PCHAR | lowMask(";/"); - private static final long H_PATH = H_PCHAR | highMask(";/"); - - private final static char[] hexDigits = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' - }; -} diff --git a/openjdk/sun/nio/fs/WindowsUriSupport.java b/openjdk/sun/nio/fs/WindowsUriSupport.java deleted file mode 100644 index 0301bf90..00000000 --- a/openjdk/sun/nio/fs/WindowsUriSupport.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.fs; - -import java.net.URI; -import java.net.URISyntaxException; - -/** - * Utility methods to convert between Path and URIs. - */ - -class WindowsUriSupport { - private WindowsUriSupport() { - } - - // suffix for IPv6 literal address - private static final String IPV6_LITERAL_SUFFIX = ".ipv6-literal.net"; - - /** - * Returns URI to represent the given (absolute) path - */ - private static URI toUri(String path, boolean isUnc, boolean addSlash) { - String uriHost; - String uriPath; - - if (isUnc) { - int slash = path.indexOf('\\', 2); - uriHost = path.substring(2, slash); - uriPath = path.substring(slash).replace('\\', '/'); - - // handle IPv6 literal addresses - // 1. drop .ivp6-literal.net - // 2. replace "-" with ":" - // 3. replace "s" with "%" (zone/scopeID delimiter) - if (uriHost.endsWith(IPV6_LITERAL_SUFFIX)) { - uriHost = uriHost - .substring(0, uriHost.length() - IPV6_LITERAL_SUFFIX.length()) - .replace('-', ':') - .replace('s', '%'); - } - } else { - uriHost = ""; - uriPath = "/" + path.replace('\\', '/'); - } - - // append slash if known to be directory - if (addSlash) - uriPath += "/"; - - // return file:///C:/My%20Documents or file://server/share/foo - try { - return new URI("file", uriHost, uriPath, null); - } catch (URISyntaxException x) { - if (!isUnc) - throw new AssertionError(x); - } - - // if we get here it means we've got a UNC with reserved characters - // in the server name. The authority component cannot contain escaped - // octets so fallback to encoding the server name into the URI path - // component. - uriPath = "//" + path.replace('\\', '/'); - if (addSlash) - uriPath += "/"; - try { - return new URI("file", null, uriPath, null); - } catch (URISyntaxException x) { - throw new AssertionError(x); - } - } - - /** - * Converts given Path to a URI - */ - static URI toUri(NetPath path) { - path = path.toAbsolutePath(); - String s = path.toString(); - - // trailing slash will be added if file is a directory. Skip check if - // already have trailing space - boolean addSlash = false; - if (!s.endsWith("\\")) { - try { - addSlash = cli.System.IO.Directory.Exists(s); - } catch (Throwable x) { - } - } - - return toUri(s, path.isUnc(), addSlash); - } - - /** - * Converts given URI to a Path - */ - static NetPath fromUri(NetFileSystem fs, URI uri) { - if (!uri.isAbsolute()) - throw new IllegalArgumentException("URI is not absolute"); - if (uri.isOpaque()) - throw new IllegalArgumentException("URI is not hierarchical"); - String scheme = uri.getScheme(); - if ((scheme == null) || !scheme.equalsIgnoreCase("file")) - throw new IllegalArgumentException("URI scheme is not \"file\""); - if (uri.getFragment() != null) - throw new IllegalArgumentException("URI has a fragment component"); - if (uri.getQuery() != null) - throw new IllegalArgumentException("URI has a query component"); - String path = uri.getPath(); - if (path.equals("")) - throw new IllegalArgumentException("URI path component is empty"); - - // UNC - String auth = uri.getAuthority(); - if (auth != null && !auth.equals("")) { - String host = uri.getHost(); - if (host == null) - throw new IllegalArgumentException("URI authority component has undefined host"); - if (uri.getUserInfo() != null) - throw new IllegalArgumentException("URI authority component has user-info"); - if (uri.getPort() != -1) - throw new IllegalArgumentException("URI authority component has port number"); - - // IPv6 literal - // 1. drop enclosing brackets - // 2. replace ":" with "-" - // 3. replace "%" with "s" (zone/scopeID delimiter) - // 4. Append .ivp6-literal.net - if (host.startsWith("[")) { - host = host.substring(1, host.length()-1) - .replace(':', '-') - .replace('%', 's'); - host += IPV6_LITERAL_SUFFIX; - } - - // reconstitute the UNC - path = "\\\\" + host + path; - } else { - if ((path.length() > 2) && (path.charAt(2) == ':')) { - // "/c:/foo" --> "c:/foo" - path = path.substring(1); - } - } - return new NetPath(fs, path); - } -} diff --git a/openjdk/sun/print/PrintPeer.java b/openjdk/sun/print/PrintPeer.java deleted file mode 100644 index 892d591d..00000000 --- a/openjdk/sun/print/PrintPeer.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.print; - -import java.awt.Graphics2D; - - - -/** - * A helper interface for implementing the print API for IKVM - */ -public interface PrintPeer{ - - public Object getPrinterStatus(String PrinterName, Class category); - - public String getDefaultPrinterName(); - - public String[] getAllPrinterNames(); - - public Graphics2D createGraphics(cli.System.Drawing.Graphics g); -} diff --git a/openjdk/sun/print/UnixPrintServiceLookup.java b/openjdk/sun/print/UnixPrintServiceLookup.java deleted file mode 100644 index 8c18f4e6..00000000 --- a/openjdk/sun/print/UnixPrintServiceLookup.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.print; - - - -/** - * Currently this class is called via Reflection. - */ -public class UnixPrintServiceLookup extends Win32PrintServiceLookup{ - -} diff --git a/openjdk/sun/print/Win32PrintJob.java b/openjdk/sun/print/Win32PrintJob.java deleted file mode 100644 index 654f742b..00000000 --- a/openjdk/sun/print/Win32PrintJob.java +++ /dev/null @@ -1,1119 +0,0 @@ -/* - Copyright (C) 2009, 2012 Volker Berlin (i-net software) - Copyright (C) 2010, 2011 Karsten Heinrich (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.print; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.awt.print.PageFormat; -import java.awt.print.Pageable; -import java.awt.print.Paper; -import java.awt.print.Printable; -import java.awt.print.PrinterException; -import java.awt.print.PrinterJob; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.TreeSet; - -import javax.print.CancelablePrintJob; -import javax.print.Doc; -import javax.print.DocFlavor; -import javax.print.PrintException; -import javax.print.PrintService; -import javax.print.attribute.Attribute; -import javax.print.attribute.AttributeSetUtilities; -import javax.print.attribute.DocAttributeSet; -import javax.print.attribute.HashPrintJobAttributeSet; -import javax.print.attribute.HashPrintRequestAttributeSet; -import javax.print.attribute.PrintJobAttribute; -import javax.print.attribute.PrintJobAttributeSet; -import javax.print.attribute.PrintRequestAttribute; -import javax.print.attribute.PrintRequestAttributeSet; -import javax.print.attribute.standard.Chromaticity; -import javax.print.attribute.standard.Copies; -import javax.print.attribute.standard.Destination; -import javax.print.attribute.standard.DocumentName; -import javax.print.attribute.standard.Fidelity; -import javax.print.attribute.standard.JobName; -import javax.print.attribute.standard.JobOriginatingUserName; -import javax.print.attribute.standard.Media; -import javax.print.attribute.standard.MediaPrintableArea; -import javax.print.attribute.standard.MediaSize; -import javax.print.attribute.standard.MediaSizeName; -import javax.print.attribute.standard.MediaTray; -import javax.print.attribute.standard.OrientationRequested; -import javax.print.attribute.standard.PageRanges; -import javax.print.attribute.standard.PrinterIsAcceptingJobs; -import javax.print.attribute.standard.PrinterState; -import javax.print.attribute.standard.PrinterStateReason; -import javax.print.attribute.standard.PrinterStateReasons; -import javax.print.attribute.standard.RequestingUserName; -import javax.print.attribute.standard.SheetCollate; -import javax.print.event.PrintJobAttributeListener; -import javax.print.event.PrintJobEvent; -import javax.print.event.PrintJobListener; - -import sun.awt.windows.WPrinterJob; -import sun.print.Win32PrintService.NetMediaTray; - -import cli.System.Drawing.Printing.*; - -/** - * @author Volker Berlin - */ -public class Win32PrintJob implements CancelablePrintJob{ - - private ArrayList<PrintJobListener> jobListeners; - - private ArrayList<PrintJobAttributeListener> attrListeners; - - private ArrayList<PrintJobAttributeSet> listenedAttributeSets; - - private final Win32PrintService service; - - - private boolean printing; - private boolean printReturned; - - private PrintRequestAttributeSet reqAttrSet; - - private PrintJobAttributeSet jobAttrSet; - - private PrinterJob job = new WPrinterJob(); - private Doc doc; - private String mDestination; - - /* these variables used globally to store reference to the print - * data retrieved as a stream. On completion these are always closed - * if non-null. - */ - private InputStream instream; - - /* default values overridden by those extracted from the attributes */ - private boolean fidelity; - private boolean printColor; - private String jobName = "Java Printing"; - private int copies; - private MediaSizeName mediaName; - private MediaSize mediaSize; - private OrientationRequested orient; - - private final PrintPeer peer; - private PrinterException printerException; - - private PageNumberConverter pageRanges; - - private MediaTray mediaTray; - - - Win32PrintJob(Win32PrintService service, PrintPeer peer){ - this.service = service; - this.peer = peer; - } - - - @Override - public PrintService getPrintService(){ - return service; - } - - - @Override - public PrintJobAttributeSet getAttributes(){ - synchronized(this){ - if(jobAttrSet == null){ - /* just return an empty set until the job is submitted */ - PrintJobAttributeSet jobSet = new HashPrintJobAttributeSet(); - return AttributeSetUtilities.unmodifiableView(jobSet); - }else{ - return jobAttrSet; - } - } - } - - - @Override - public void addPrintJobListener(PrintJobListener listener){ - synchronized(this){ - if(listener == null){ - return; - } - if(jobListeners == null){ - jobListeners = new ArrayList<PrintJobListener>(); - } - jobListeners.add(listener); - } - } - - - @Override - public void removePrintJobListener(PrintJobListener listener){ - synchronized(this){ - if(listener == null || jobListeners == null){ - return; - } - jobListeners.remove(listener); - if(jobListeners.isEmpty()){ - jobListeners = null; - } - } - } - - - /* Closes any stream already retrieved for the data. - * We want to avoid unnecessarily asking the Doc to create a stream only - * to get a reference in order to close it because the job failed. - * If the representation class is itself a "stream", this - * closes that stream too. - */ - private void closeDataStreams() { - // TODO - } - - private void notifyEvent(int reason) { - - /* since this method should always get called, here's where - * we will perform the clean up of any data stream supplied. - */ - switch (reason) { - case PrintJobEvent.DATA_TRANSFER_COMPLETE: - case PrintJobEvent.JOB_CANCELED : - case PrintJobEvent.JOB_FAILED : - case PrintJobEvent.NO_MORE_EVENTS : - case PrintJobEvent.JOB_COMPLETE : - closeDataStreams(); - } - - synchronized (this) { - if (jobListeners != null) { - PrintJobListener listener; - PrintJobEvent event = new PrintJobEvent(this, reason); - for (int i = 0; i < jobListeners.size(); i++) { - listener = jobListeners.get(i); - switch (reason) { - - case PrintJobEvent.JOB_COMPLETE : - listener.printJobCompleted(event); - break; - - case PrintJobEvent.JOB_CANCELED : - listener.printJobCanceled(event); - break; - - case PrintJobEvent.JOB_FAILED : - listener.printJobFailed(event); - break; - - case PrintJobEvent.DATA_TRANSFER_COMPLETE : - listener.printDataTransferCompleted(event); - break; - - case PrintJobEvent.NO_MORE_EVENTS : - listener.printJobNoMoreEvents(event); - break; - - default: - break; - } - } - } - } - } - - @Override - public void addPrintJobAttributeListener(PrintJobAttributeListener listener, PrintJobAttributeSet attributes){ - synchronized(this){ - if(listener == null){ - return; - } - if(attrListeners == null){ - attrListeners = new ArrayList<PrintJobAttributeListener>(); - listenedAttributeSets = new ArrayList<PrintJobAttributeSet>(); - } - attrListeners.add(listener); - if(attributes == null){ - attributes = new HashPrintJobAttributeSet(); - } - listenedAttributeSets.add(attributes); - } - } - - - @Override - public void removePrintJobAttributeListener(PrintJobAttributeListener listener){ - synchronized(this){ - if(listener == null || attrListeners == null){ - return; - } - int index = attrListeners.indexOf(listener); - if(index == -1){ - return; - }else{ - attrListeners.remove(index); - listenedAttributeSets.remove(index); - if(attrListeners.isEmpty()){ - attrListeners = null; - listenedAttributeSets = null; - } - } - } - } - - - @Override - public void print(Doc doc, PrintRequestAttributeSet attributes) throws PrintException{ - - synchronized(this){ - if(printing){ - throw new PrintException("already printing"); - }else{ - printing = true; - } - } - - PrinterState prnState = (PrinterState)service.getAttribute(PrinterState.class); - if(prnState == PrinterState.STOPPED){ - PrinterStateReasons prnStateReasons = (PrinterStateReasons)service.getAttribute(PrinterStateReasons.class); - if((prnStateReasons != null) && (prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN))){ - throw new PrintException("PrintService is no longer available."); - } - } - - if((PrinterIsAcceptingJobs)(service.getAttribute(PrinterIsAcceptingJobs.class)) == PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS){ - throw new PrintException("Printer is not accepting job."); - } - - this.doc = doc; - /* check if the parameters are valid before doing much processing */ - DocFlavor flavor = doc.getDocFlavor(); - Object data; - - try{ - data = doc.getPrintData(); - }catch(IOException e){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException("can't get print data: " + e.toString()); - } - - if(flavor == null || (!service.isDocFlavorSupported(flavor))){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintJobFlavorException("invalid flavor", flavor); - } - - initializeAttributeSets(doc, attributes); - - getAttributeValues(flavor); - - String repClassName = flavor.getRepresentationClassName(); - - if(flavor.equals(DocFlavor.INPUT_STREAM.GIF) || flavor.equals(DocFlavor.INPUT_STREAM.JPEG) - || flavor.equals(DocFlavor.INPUT_STREAM.PNG) || flavor.equals(DocFlavor.BYTE_ARRAY.GIF) - || flavor.equals(DocFlavor.BYTE_ARRAY.JPEG) || flavor.equals(DocFlavor.BYTE_ARRAY.PNG)){ - try{ - instream = doc.getStreamForBytes(); - if(instream == null){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException("No stream for data"); - } - printableJob(new ImagePrinter(instream)); - service.wakeNotifier(); - return; - }catch(ClassCastException cce){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(cce); - }catch(IOException ioe){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(ioe); - } - }else if(flavor.equals(DocFlavor.URL.GIF) || flavor.equals(DocFlavor.URL.JPEG) - || flavor.equals(DocFlavor.URL.PNG)){ - try{ - printableJob(new ImagePrinter((URL)data)); - service.wakeNotifier(); - return; - }catch(ClassCastException cce){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(cce); - } - }else if(repClassName.equals("java.awt.print.Pageable")){ - try{ - pageableJob((Pageable)doc.getPrintData()); - service.wakeNotifier(); - return; - }catch(ClassCastException cce){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(cce); - }catch(IOException ioe){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(ioe); - } - }else if(repClassName.equals("java.awt.print.Printable")){ - try{ - printableJob((Printable)doc.getPrintData()); - service.wakeNotifier(); - return; - }catch(ClassCastException cce){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(cce); - }catch(IOException ioe){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(ioe); - } - }else if(repClassName.equals("[B") || repClassName.equals("java.io.InputStream") - || repClassName.equals("java.net.URL")){ - - if(repClassName.equals("java.net.URL")){ - URL url = (URL)data; - try{ - instream = url.openStream(); - }catch(IOException e){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(e.toString()); - } - }else{ - try{ - instream = doc.getStreamForBytes(); - }catch(IOException ioe){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(ioe.toString()); - } - } - - if(instream == null){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException("No stream for data"); - } - - if(mDestination != null){ // if destination attribute is set - try{ - FileOutputStream fos = new FileOutputStream(mDestination); - byte[] buffer = new byte[1024]; - int cread; - - while((cread = instream.read(buffer, 0, buffer.length)) >= 0){ - fos.write(buffer, 0, cread); - } - fos.flush(); - fos.close(); - }catch(FileNotFoundException fnfe){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(fnfe.toString()); - }catch(IOException ioe){ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(ioe.toString()); - } - notifyEvent(PrintJobEvent.DATA_TRANSFER_COMPLETE); - notifyEvent(PrintJobEvent.JOB_COMPLETE); - service.wakeNotifier(); - return; - } - - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException("Print job failed. IKVM does not support raw data currently."); - }else{ - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException("unrecognized class: " + repClassName); - } - } - - - public void printableJob(Printable printable) throws PrintException { - throw new PrintException("Win32PrintJob.printableJob() not implemented:"); - } - - public void pageableJob(Pageable pageable) throws PrintException { - // a general hint for this code here: The PrintJob implementation (WPrinterJob) in the Oracle - // JRE implements SunPrinterJobService - which we don't here. Unfortunately this is used as a hint - // to distinguish between the build-in printer service and custom printer services. So for the RasterPrinterJob - // this implementation of the Win32PrintJob is a custom print job! That's why several methods of - // RasterPrintJob(which only apply to the SunPrinterJobService otherwise) had to be moved here. - // This includes the attribute resolving and the media patch for instance. - try { - PrintDocument printDocument = createPrintDocument( ); - pageable = patchMedia( pageable ); - - printDocument.add_QueryPageSettings(new QueryPageSettingsEventHandler(new QueryPage( pageable, printColor, mediaTray ) ) ); - printDocument.add_PrintPage(new PrintPageEventHandler(new PrintPage(pageable))); - printDocument.Print(); - if(printerException != null){ - throw printerException; - } - //TODO throw exception on Cancel - notifyEvent(PrintJobEvent.DATA_TRANSFER_COMPLETE); - return; - } catch (PrinterException pe) { - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(pe); - } finally { - printReturned = true; - notifyEvent(PrintJobEvent.NO_MORE_EVENTS); - } - } - - - private PrintDocument createPrintDocument() throws PrintException{ - PrintDocument printDocument = new PrintDocument(); - PrinterSettings settings = printDocument.get_PrinterSettings(); - settings.set_PrinterName( service.getName() ); - if( !settings.get_IsValid() ){ - throw new PrintException("Printer name ''" + service.getName() + "' is invalid."); - } - - if( jobName != null ){ - printDocument.set_DocumentName( jobName ); - } - printDocument.get_DefaultPageSettings().set_Color(printColor); - - Attribute destination = reqAttrSet.get(Destination.class); - if(destination instanceof Destination){ - File destFile = new File(((Destination)destination).getURI()); - settings.set_PrintFileName(destFile.getAbsolutePath()); - settings.set_PrintToFile(true); - } - - settings.set_Copies((short)copies); - boolean collated = false; - if(copies > 1){ - Object collate = reqAttrSet.get(SheetCollate.class); - if( collate == null ){ - collate = service.getDefaultAttributeValue(SheetCollate.class); - } - collated = collate == SheetCollate.COLLATED; - settings.set_Collate( collated ); - } - Attribute pageRangeObj = reqAttrSet.get(PageRanges.class); - if( pageRangeObj != null ){ - int[][] ranges = ((PageRanges)pageRangeObj).getMembers(); - if( ranges.length > 1 ){ - settings.set_PrintRange( PrintRange.wrap( PrintRange.Selection ) ); - } else { - if( ranges.length > 0 ){ - settings.set_FromPage(ranges[0][0]); - settings.set_ToPage(ranges[0][1]); - settings.set_PrintRange( PrintRange.wrap( PrintRange.SomePages ) ); - } // else allPages??? - } - } else { - settings.set_PrintRange( PrintRange.wrap( PrintRange.AllPages ) ); - } - pageRanges = new PageNumberConverter( (PageRanges)pageRangeObj, copies, collated ); - return printDocument; - } - - // copied from RasterPrintJob - // Since we don't implement SunPrinterJobService the hack in RasterPrintService which applies - // the media format to the auto-generated OpenBook doesn't work here. So we have to modify - // the page format of the OpenBook here - equal to the code in RasterPrintJob - private Pageable patchMedia( Pageable pageable ){ - /* OpenBook is used internally only when app uses Printable. - * This is the case when we use the values from the attribute set. - */ - Media media = (Media)reqAttrSet.get(Media.class); - OrientationRequested orientReq = (OrientationRequested)reqAttrSet.get(OrientationRequested.class); - MediaPrintableArea mpa = (MediaPrintableArea)reqAttrSet.get(MediaPrintableArea.class); - - if ((orientReq != null || media != null || mpa != null) && pageable instanceof OpenBook) { - - /* We could almost(!) use PrinterJob.getPageFormat() except - * here we need to start with the PageFormat from the OpenBook : - */ - Printable printable = pageable.getPrintable(0); - PageFormat pf = (PageFormat)pageable.getPageFormat(0).clone(); - Paper paper = pf.getPaper(); - - /* If there's a media but no media printable area, we can try - * to retrieve the default value for mpa and use that. - */ - if (mpa == null && media != null && service.isAttributeCategorySupported(MediaPrintableArea.class)) { - Object mpaVals = service. getSupportedAttributeValues(MediaPrintableArea.class, null, reqAttrSet); - if (mpaVals instanceof MediaPrintableArea[] && ((MediaPrintableArea[])mpaVals).length > 0) { - mpa = ((MediaPrintableArea[])mpaVals)[0]; - } - } - - if (isSupportedValue(orientReq, reqAttrSet) || (!fidelity && orientReq != null)) { - int orient; - if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) { - orient = PageFormat.REVERSE_LANDSCAPE; - } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) { - orient = PageFormat.LANDSCAPE; - } else { - orient = PageFormat.PORTRAIT; - } - pf.setOrientation(orient); - } - - if (isSupportedValue(media, reqAttrSet) || (!fidelity && media != null)) { - if (media instanceof MediaSizeName) { - MediaSizeName msn = (MediaSizeName)media; - MediaSize msz = MediaSize.getMediaSizeForName(msn); - if (msz != null) { - float paperWid = msz.getX(MediaSize.INCH) * 72.0f; - float paperHgt = msz.getY(MediaSize.INCH) * 72.0f; - paper.setSize(paperWid, paperHgt); - if (mpa == null) { - paper.setImageableArea(72.0, 72.0, paperWid-144.0, paperHgt-144.0); - } - } - } - } - - if (isSupportedValue(mpa, reqAttrSet) || (!fidelity && mpa != null)) { - float [] printableArea = mpa.getPrintableArea(MediaPrintableArea.INCH); - for (int i=0; i < printableArea.length; i++) { - printableArea[i] = printableArea[i]*72.0f; - } - paper.setImageableArea(printableArea[0], printableArea[1], printableArea[2], printableArea[3]); - } - - pf.setPaper(paper); - pf = validatePage(pf); - return new OpenBook(pf, printable); - } - return pageable; - } - - // copied from RasterPrintJob to since we don't implement SunPrinterJobService - /** - * The passed in PageFormat is cloned and altered to be usable on - * the PrinterJob's current printer. - */ - private PageFormat validatePage(PageFormat page) { - PageFormat newPage = (PageFormat)page.clone(); - Paper newPaper = new Paper(); - validatePaper(newPage.getPaper(), newPaper); - newPage.setPaper(newPaper); - - return newPage; - } - - // copied from RasterPrintJob to since we don't implement SunPrinterJobService - /** - * updates a Paper object to reflect the current printer's selected - * paper size and imageable area for that paper size. - * Default implementation copies settings from the original, applies - * applies some validity checks, changes them only if they are - * clearly unreasonable, then sets them into the new Paper. - * Subclasses are expected to override this method to make more - * informed decisons. - */ - protected void validatePaper(Paper origPaper, Paper newPaper) { - if (origPaper == null || newPaper == null) { - return; - } else { - double wid = origPaper.getWidth(); - double hgt = origPaper.getHeight(); - double ix = origPaper.getImageableX(); - double iy = origPaper.getImageableY(); - double iw = origPaper.getImageableWidth(); - double ih = origPaper.getImageableHeight(); - - /* Assume any +ve values are legal. Overall paper dimensions - * take precedence. Make sure imageable area fits on the paper. - */ - Paper defaultPaper = new Paper(); - wid = ((wid > 0.0) ? wid : defaultPaper.getWidth()); - hgt = ((hgt > 0.0) ? hgt : defaultPaper.getHeight()); - ix = ((ix > 0.0) ? ix : defaultPaper.getImageableX()); - iy = ((iy > 0.0) ? iy : defaultPaper.getImageableY()); - iw = ((iw > 0.0) ? iw : defaultPaper.getImageableWidth()); - ih = ((ih > 0.0) ? ih : defaultPaper.getImageableHeight()); - /* full width/height is not likely to be imageable, but since we - * don't know the limits we have to allow it - */ - if (iw > wid) { - iw = wid; - } - if (ih > hgt) { - ih = hgt; - } - if ((ix + iw) > wid) { - ix = wid - iw; - } - if ((iy + ih) > hgt) { - iy = hgt - ih; - } - newPaper.setSize(wid, hgt); - newPaper.setImageableArea(ix, iy, iw, ih); - } - } - - // copied from RasterPrintJob - /** - * Checks whether a certain attribute value is valid for the current print service - * @param attrval the attribute value - * @param attrset Set of printing attributes for a supposed job (both job-level attributes and document-level attributes), or null. - * @return true if valid - */ - protected boolean isSupportedValue(Attribute attrval, PrintRequestAttributeSet attrset) { - return (attrval != null && service != null && service.isAttributeValueSupported(attrval, DocFlavor.SERVICE_FORMATTED.PAGEABLE, attrset)); - } - - - /* - * There's some inefficiency here as the job set is created even though it may never be requested. - */ - private synchronized void initializeAttributeSets(Doc doc, PrintRequestAttributeSet reqSet){ - - reqAttrSet = new HashPrintRequestAttributeSet(); - jobAttrSet = new HashPrintJobAttributeSet(); - - Attribute[] attrs; - if(reqSet != null){ - reqAttrSet.addAll(reqSet); - attrs = reqSet.toArray(); - for(int i = 0; i < attrs.length; i++){ - if(attrs[i] instanceof PrintJobAttribute){ - jobAttrSet.add(attrs[i]); - } - } - } - - DocAttributeSet docSet = doc.getAttributes(); - if(docSet != null){ - attrs = docSet.toArray(); - for(int i = 0; i < attrs.length; i++){ - if(attrs[i] instanceof PrintRequestAttribute){ - reqAttrSet.add(attrs[i]); - } - if(attrs[i] instanceof PrintJobAttribute){ - jobAttrSet.add(attrs[i]); - } - } - } - - /* add the user name to the job */ - String userName = ""; - try{ - userName = System.getProperty("user.name"); - }catch(SecurityException se){ - } - - if(userName == null || userName.equals("")){ - RequestingUserName ruName = (RequestingUserName)reqSet.get(RequestingUserName.class); - if(ruName != null){ - jobAttrSet.add(new JobOriginatingUserName(ruName.getValue(), ruName.getLocale())); - }else{ - jobAttrSet.add(new JobOriginatingUserName("", null)); - } - }else{ - jobAttrSet.add(new JobOriginatingUserName(userName, null)); - } - - /* - * if no job name supplied use doc name (if supplied), if none and its a URL use that, else finally anything .. - */ - if(jobAttrSet.get(JobName.class) == null){ - JobName jobName; - if(docSet != null && docSet.get(DocumentName.class) != null){ - DocumentName docName = (DocumentName)docSet.get(DocumentName.class); - jobName = new JobName(docName.getValue(), docName.getLocale()); - jobAttrSet.add(jobName); - }else{ - String str = "JPS Job:" + doc; - try{ - Object printData = doc.getPrintData(); - if(printData instanceof URL){ - str = ((URL)(doc.getPrintData())).toString(); - } - }catch(IOException e){ - } - jobName = new JobName(str, null); - jobAttrSet.add(jobName); - } - } - - jobAttrSet = AttributeSetUtilities.unmodifiableView(jobAttrSet); - } - - private void getAttributeValues(DocFlavor flavor) throws PrintException { - - if (reqAttrSet.get(Fidelity.class) == Fidelity.FIDELITY_TRUE) { - fidelity = true; - } else { - fidelity = false; - } - - Attribute chroma = reqAttrSet.get( Chromaticity.class ); - // TODO check whether supported by the print service - printColor = chroma == Chromaticity.COLOR; - - Attribute newTray = reqAttrSet.get( Media.class ); - if( newTray instanceof MediaTray ){ - mediaTray = (MediaTray)newTray; - } - // TODO check whether supported by the print service - - Class category; - Attribute [] attrs = reqAttrSet.toArray(); - for (int i=0; i<attrs.length; i++) { - Attribute attr = attrs[i]; - category = attr.getCategory(); - if (fidelity == true) { - if (!service.isAttributeCategorySupported(category)) { - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintJobAttributeException( - "unsupported category: " + category, category, null); - } else if - (!service.isAttributeValueSupported(attr, flavor, null)) { - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintJobAttributeException( - "unsupported attribute: " + attr, null, attr); - } - } - if (category == Destination.class) { - URI uri = ((Destination)attr).getURI(); - if (!"file".equals(uri.getScheme())) { - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException("Not a file: URI"); - } else { - try { - mDestination = (new File(uri)).getPath(); - } catch (Exception e) { - throw new PrintException(e); - } - // check write access - SecurityManager security = System.getSecurityManager(); - if (security != null) { - try { - security.checkWrite(mDestination); - } catch (SecurityException se) { - notifyEvent(PrintJobEvent.JOB_FAILED); - throw new PrintException(se); - } - } - } - } else if (category == JobName.class) { - jobName = ((JobName)attr).getValue(); - } else if (category == Copies.class) { - copies = ((Copies)attr).getValue(); - } else if (category == Media.class) { - if (attr instanceof MediaSizeName) { - mediaName = (MediaSizeName)attr; - // If requested MediaSizeName is not supported, - // get the corresponding media size - this will - // be used to create a new PageFormat. - if (!service.isAttributeValueSupported(attr, flavor, null)) { - mediaSize = MediaSize.getMediaSizeForName(mediaName); - } - } - } else if (category == OrientationRequested.class) { - orient = (OrientationRequested)attr; - } - } - } - - - @Override - public void cancel() throws PrintException{ - synchronized(this){ - if(!printing){ - throw new PrintException("Job is not yet submitted."); - }else if(job != null && !printReturned){ - job.cancel(); - notifyEvent(PrintJobEvent.JOB_CANCELED); - return; - }else{ - throw new PrintException("Job could not be cancelled."); - } - } - } - - /** - * Converts the Java 1/72 inch to .NET 1/100 inch - * @param javaLength the java length in 1/72 inch - * @return the .NET length in 1/100 inch - */ - private static int java2netLength( int javaLength ){ - return (int) Math.round( (double)(javaLength * 100) / 72d ); - } - - /** - * Converts the Java 1/72 inch to .NET 1/100 inch - * @param javaLength the java length in 1/72 inch - * @return the .NET length in 1/100 inch - */ - private static int java2netLength( double javaLength ){ - return (int) Math.round( (javaLength * 100) / 72d ); - } - - - private class PrintPage implements PrintPageEventHandler.Method{ - - private final Pageable pageable; - private int pageIndex; - - - PrintPage(Pageable pageable){ - this.pageable = pageable; - } - - - @Override - public void Invoke(Object paramObject, PrintPageEventArgs ev){ - - try{ - int realPage = pageRanges.getPageForIndex(pageIndex); - - Printable printable = pageable.getPrintable(realPage); - PageFormat pageFormat = pageable.getPageFormat(realPage); - - - BufferedImage pBand = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR); - Graphics2D imageGraphics = pBand.createGraphics(); - ((RasterPrinterJob)job).setGraphicsConfigInfo(imageGraphics.getTransform(), pageFormat.getImageableWidth(), pageFormat.getImageableHeight()); - PeekGraphics peekGraphics = new PeekGraphics(imageGraphics, job ); - - /* - * Because Sun is calling first with a PeekGraphics that we do it else for compatibility - */ - if(realPage == 0){ - int pageResult = printable.print(peekGraphics, pageFormat, realPage); - if(pageResult != Printable.PAGE_EXISTS){ - ev.set_HasMorePages(false); - ev.set_Cancel(true); - return; - } - } - Graphics2D printGraphics = peer.createGraphics(ev.get_Graphics()); - Graphics2D g2d = ((Graphics2D)printGraphics); - int tX = (int) pageFormat.getWidth(); - int tY = (int) pageFormat.getHeight(); - // apply Java to .NET scaling (1/72 inch to 1/100 inch) - g2d.scale(100d/72d, 100d/72d); - // NOTE on Landscape printing: - // Setting landscape to true on the printer settings - // of a page already rotates the page! The orig. java code rotates the page itself, - // for .NET this is not required. - if( orient == OrientationRequested.REVERSE_LANDSCAPE){ - g2d.translate( tX, tY ); - g2d.rotate( Math.PI ); - } - - printable.print(printGraphics, pageFormat, realPage); - - realPage = pageRanges.getPageForIndex(++pageIndex); - if( realPage >= 0 ){ - printable = pageable.getPrintable(realPage); - pageFormat = pageable.getPageFormat(realPage); - int pageResult = printable.print(peekGraphics, pageFormat, realPage); - ev.set_HasMorePages( pageResult == Printable.PAGE_EXISTS ); - } else { - ev.set_HasMorePages( false ); - } - }catch(PrinterException ex){ - printerException = ex; - ex.printStackTrace(); - ev.set_HasMorePages(false); - } - - } - - } - - private class QueryPage implements QueryPageSettingsEventHandler.Method{ - - private final Pageable pageable; - private int pageIndex; - private final boolean printColor; - private final MediaTray tray; - - - QueryPage(Pageable pageable, boolean printColor, MediaTray tray ){ - this.printColor = printColor; - this.pageable = pageable; - this.tray = tray; - } - - @Override - public void Invoke(Object source, QueryPageSettingsEventArgs e) { - int realPage = pageRanges.getPageForIndex(pageIndex); - // apply page settings to the current page - PageFormat format = pageable.getPageFormat(realPage); - PageSettings pageSettings = e.get_PageSettings(); - pageSettings.set_Color( printColor ); - PaperSource paperSource = service.getPaperSourceForTray( tray ); - if( paperSource != null ){ - pageSettings.set_PaperSource( paperSource ); - } - - PaperSize ps = new PaperSize(); - ps.set_Height( java2netLength( format.getHeight() ) ); - ps.set_Width( java2netLength( format.getWidth() ) ); - pageSettings.set_PaperSize( ps ); - - Margins margins = new Margins(); - margins.set_Left( java2netLength( format.getImageableX() ) ); - margins.set_Top( java2netLength( format.getImageableY() ) ); - margins.set_Right( java2netLength(format.getWidth() - format.getImageableX() - format.getImageableWidth() ) ); - margins.set_Bottom( java2netLength(format.getHeight() - format.getImageableY() - format.getImageableHeight() ) ); - pageSettings.set_Margins( margins ); - pageIndex++; - } - } - - /** - * Determines which logical page to print for a certain physical page - */ - public static class PageNumberConverter{ - - private List<Range> ranges; - private int totalPages = -1; - private final int copies; - - public PageNumberConverter( PageRanges pages, int copies, boolean collated ) { - // NOTE: uncollated is handled by the printer driver! If we would handle that here, - // we would get copies^2 copies! - this.copies = collated ? copies : 1; - if( pages != null && pages.getMembers() != null && pages.getMembers().length > 0 ){ - TreeSet<Range> rangesSort = new TreeSet<Range>(); - OUTER: - for( int[] range : pages.getMembers() ){ - Range r = new Range( range[0], range[1] + 1 ); // +1 to inlucde the uppre end - for( Range recent : rangesSort ){ - if( recent.canMerge(r) ){ - recent.merge(r); - continue OUTER; - } - } - rangesSort.add( r ); - } - // finally merge - Range recent = null; - ranges = new ArrayList<Range>(); - for( Range r : rangesSort ){ - if( recent != null && recent.canMerge( r ) ){ - recent.merge( r ); - } else { - ranges.add( r ); - recent = r; - } - } - // calculate total pages, required for collated copies - totalPages = 0; - for( Range r : rangesSort ){ - int diff = r.end - r.start; - totalPages += diff; - } - } - } - - /** - * Must be called in case the printable returns no-more-pages. Will return whether the print job - * will continue due to pending copies - * @param index the current page index - * @return if false, the print job will continue with copies, if true terminate the job - */ - public boolean checkJobComplete( int index ){ - if( ranges != null ){ - return true; - } - if( totalPages < 0 ){ - // this is the first time, this was called for 'all-pages' so it's the total number - totalPages = index; - } - return index > copies * totalPages; - } - - /** - * Returns which page to be printed for a certain page index - * @param index the inex to be printed - * @return the page number or -1, if there is no page for this index - */ - public int getPageForIndex( int index ){ - if( index < 0 || ( totalPages >=0 && index >= copies * totalPages ) ){ - return -1; - } - if( ranges == null ){ - return totalPages >=0 ? index % totalPages : index; - } - int counter = 0; - if( copies > 1 ){ - counter += (index / totalPages) * totalPages; - } - for( Range r : ranges ){ - int upper = counter + (r.end - r.start); - if( index < upper ){ - // so we're in the correct range - return r.start + ( index - counter ) - 1; - } else { - counter = upper; - } - } - return -1; - } - - /** - * A singular page range - */ - private static class Range implements Comparable<Range> { - - public int start; - public int end; - - public Range(int start, int end) { - this.start = start; - this.end = end; - } - - /** - * Checks whether the ranges intersect of have no gap in between - * @param otherRange the range to be checked - * @return true, if the ranges can be merged - */ - public boolean canMerge( Range otherRange ){ - if( otherRange.end >= start && otherRange.end <= end ){ - return true; - } - if( otherRange.start >= start && otherRange.start <= end ){ - return true; - } - return false; - } - - /** - * Merges the other range into this range. Ignores the gap between the ranges if there is any - * @param otherRange the range to be merged - */ - public void merge( Range otherRange ){ - start = Math.min(start, otherRange.start); - end = Math.max(end, otherRange.end); - } - - public int compareTo(Range o) { - return start - o.start; - } - } - } -} diff --git a/openjdk/sun/print/Win32PrintService.java b/openjdk/sun/print/Win32PrintService.java deleted file mode 100644 index 134c7a94..00000000 --- a/openjdk/sun/print/Win32PrintService.java +++ /dev/null @@ -1,920 +0,0 @@ -/* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. - * Copyright (C) 2009, 2012 Volker Berlin (i-net software) - * Copyright (C) 2010, 2011 Karsten Heinrich (i-net software) - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package sun.print; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.print.DocFlavor; -import javax.print.DocPrintJob; -import javax.print.PrintService; -import javax.print.ServiceUIFactory; -import javax.print.attribute.Attribute; -import javax.print.attribute.AttributeSet; -import javax.print.attribute.AttributeSetUtilities; -import javax.print.attribute.HashPrintServiceAttributeSet; -import javax.print.attribute.PrintServiceAttribute; -import javax.print.attribute.PrintServiceAttributeSet; -import javax.print.attribute.standard.Chromaticity; -import javax.print.attribute.standard.ColorSupported; -import javax.print.attribute.standard.Copies; -import javax.print.attribute.standard.CopiesSupported; -import javax.print.attribute.standard.Destination; -import javax.print.attribute.standard.Fidelity; -import javax.print.attribute.standard.JobName; -import javax.print.attribute.standard.Media; -import javax.print.attribute.standard.MediaPrintableArea; -import javax.print.attribute.standard.MediaSize; -import javax.print.attribute.standard.MediaSizeName; -import javax.print.attribute.standard.MediaTray; -import javax.print.attribute.standard.OrientationRequested; -import javax.print.attribute.standard.PageRanges; -import javax.print.attribute.standard.PrintQuality; -import javax.print.attribute.standard.PrinterIsAcceptingJobs; -import javax.print.attribute.standard.PrinterName; -import javax.print.attribute.standard.PrinterResolution; -import javax.print.attribute.standard.PrinterState; -import javax.print.attribute.standard.PrinterStateReasons; -import javax.print.attribute.standard.QueuedJobCount; -import javax.print.attribute.standard.RequestingUserName; -import javax.print.attribute.standard.SheetCollate; -import javax.print.attribute.standard.Sides; -import javax.print.event.PrintServiceAttributeListener; - -import cli.System.NewsStyleUriParser; -import cli.System.Type; -import cli.System.Collections.IEnumerator; -import cli.System.Drawing.RectangleF; -import cli.System.Drawing.Printing.Duplex; -import cli.System.Drawing.Printing.PaperKind; -import cli.System.Drawing.Printing.PaperSize; -import cli.System.Drawing.Printing.PaperSource; -import cli.System.Drawing.Printing.PrintDocument; -import cli.System.Drawing.Printing.PrinterSettings; -import cli.System.Drawing.Printing.PrinterSettings.PaperSizeCollection; -import cli.System.Drawing.Printing.PrinterSettings.PaperSourceCollection; -import cli.System.Drawing.Printing.PrinterSettings.PrinterResolutionCollection; -import cli.System.Net.Mime.MediaTypeNames; - -/** - * @author Volker Berlin - */ -public class Win32PrintService implements PrintService { - // note: the Win32PrintService is implemented as foreign service (doesn't implement SunPrinterJobService) - // to avoid implementing the WPrinterJob - - private static final DocFlavor[] supportedFlavors = { - DocFlavor.SERVICE_FORMATTED.PAGEABLE, - DocFlavor.SERVICE_FORMATTED.PRINTABLE, - }; - - /** Mapping for PageSize.RawKind to predefined MediaSizeName */ - private static final MediaSizeName[] MEDIA_NAMES = new MediaSizeName[70]; - - private static final Hashtable<String, MediaSizeName> CUSTOM_MEDIA_NAME = new Hashtable<>(); - - /* it turns out to be inconvenient to store the other categories - * separately because many attributes are in multiple categories. - */ - private static Class[] otherAttrCats = { - JobName.class, - RequestingUserName.class, - Copies.class, - Destination.class, - OrientationRequested.class, - PageRanges.class, - Media.class, - MediaPrintableArea.class, - Fidelity.class, - // We support collation on 2D printer jobs, even if the driver can't. - SheetCollate.class, - SunAlternateMedia.class, - Chromaticity.class - }; - - // conversion from 1/100 Inch (.NET) to um (Java) - private static final int INCH100_TO_MYM = 254; - private static final int MATCH_DIFF = 500; // 0.5 mm - - static { - MEDIA_NAMES[0] = MediaSizeName.NA_LETTER; - MEDIA_NAMES[1] = MediaSizeName.NA_LETTER ; - MEDIA_NAMES[2] = MediaSizeName.TABLOID ; - MEDIA_NAMES[3] = MediaSizeName.LEDGER ; - MEDIA_NAMES[4] = MediaSizeName.NA_LEGAL ; - MEDIA_NAMES[5] = MediaSizeName.INVOICE ; // Statement - MEDIA_NAMES[6] = MediaSizeName.EXECUTIVE ; - MEDIA_NAMES[7] = MediaSizeName.ISO_A3 ; - MEDIA_NAMES[8] = MediaSizeName.ISO_A4 ; - MEDIA_NAMES[9] = MediaSizeName.ISO_A4 ; // A4Small, 10 - MEDIA_NAMES[10] = MediaSizeName.ISO_A5 ; - MEDIA_NAMES[11] = MediaSizeName.JIS_B4 ; - MEDIA_NAMES[12] = MediaSizeName.JIS_B5 ; - MEDIA_NAMES[13] = MediaSizeName.FOLIO ; - MEDIA_NAMES[14] = MediaSizeName.QUARTO ; - MEDIA_NAMES[15] = MediaSizeName.NA_10X14_ENVELOPE ; - MEDIA_NAMES[16] = MediaSizeName.B ; // 10x17 Envelope - MEDIA_NAMES[17] = MediaSizeName.NA_LETTER ; // Note - MEDIA_NAMES[18] = MediaSizeName.NA_NUMBER_9_ENVELOPE ; - MEDIA_NAMES[19] = MediaSizeName.NA_NUMBER_10_ENVELOPE ; // 20 - MEDIA_NAMES[20] = MediaSizeName.NA_NUMBER_11_ENVELOPE ; - MEDIA_NAMES[21] = MediaSizeName.NA_NUMBER_12_ENVELOPE ; - MEDIA_NAMES[22] = MediaSizeName.NA_NUMBER_14_ENVELOPE ; - MEDIA_NAMES[23] = MediaSizeName.C ; - MEDIA_NAMES[24] = MediaSizeName.D ; - MEDIA_NAMES[25] = MediaSizeName.E ; - MEDIA_NAMES[26] = MediaSizeName.ISO_DESIGNATED_LONG ; - MEDIA_NAMES[27] = MediaSizeName.ISO_C5 ; - MEDIA_NAMES[28] = MediaSizeName.ISO_C3 ; - MEDIA_NAMES[29] = MediaSizeName.ISO_C4 ; // 30 - MEDIA_NAMES[30] = MediaSizeName.ISO_C6 ; - MEDIA_NAMES[31] = MediaSizeName.ITALY_ENVELOPE ; - MEDIA_NAMES[32] = MediaSizeName.ISO_B4 ; - MEDIA_NAMES[33] = MediaSizeName.ISO_B5 ; - MEDIA_NAMES[34] = MediaSizeName.ISO_B6 ; - MEDIA_NAMES[35] = MediaSizeName.ITALY_ENVELOPE ; - MEDIA_NAMES[36] = MediaSizeName.MONARCH_ENVELOPE ; - MEDIA_NAMES[37] = MediaSizeName.PERSONAL_ENVELOPE ; - MEDIA_NAMES[38] = MediaSizeName.NA_10X15_ENVELOPE ; // USStandardFanfold - MEDIA_NAMES[39] = MediaSizeName.NA_9X12_ENVELOPE ; // GermanStandardFanfold, 40 - MEDIA_NAMES[40] = MediaSizeName.FOLIO ; // GermanLegalFanfold - MEDIA_NAMES[41] = MediaSizeName.ISO_B4 ; - MEDIA_NAMES[42] = MediaSizeName.JAPANESE_POSTCARD ; - MEDIA_NAMES[43] = MediaSizeName.NA_9X11_ENVELOPE ; - - MEDIA_NAMES[65] = MediaSizeName.ISO_A2 ; - - MEDIA_NAMES[69] = MediaSizeName.ISO_A6 ; - -// // augment the media size with the .NET default sizes available on the printer -// PrinterSettings ps = new PrinterSettings(); -// IEnumerator printers = PrinterSettings.get_InstalledPrinters().GetEnumerator(); -// printers.Reset(); -// while( printers.MoveNext() ){ -// ps.set_PrinterName( (String) printers.get_Current() ); -// IEnumerator sizes = ps.get_PaperSizes().GetEnumerator(); -// sizes.Reset(); -// while( sizes.MoveNext() ){ -// PaperSize size = (PaperSize) sizes.get_Current(); -// int kind = size.get_RawKind(); -// if( kind >= 0 && kind < MEDIA_NAMES.length && MEDIA_NAMES[kind] == null ){ -// MEDIA_NAMES[kind] = new CustomMediaSizeName( size.get_PaperName() ); -// int x = size.get_Width(); -// int y = size.get_Height(); -// if( x > y ){ // not allowed by MediaSize -// int tmp = x; -// x = y; -// y = tmp; -// } -// new MediaSize(x, y, INCH100_TO_MYM, MEDIA_NAMES[kind]); // cache entry in map -// } -// } -// } - } - - private final PrintPeer peer; - - private final String printer; - private final PrinterSettings settings; - private PrinterName name; - - private MediaTray[] mediaTrays; - - transient private ServiceNotifier notifier = null; - - public Win32PrintService(String name, PrintPeer peer){ - if(name == null){ - throw new IllegalArgumentException("null printer name"); - } - this.peer = peer; - printer = name; - settings = new PrintDocument().get_PrinterSettings(); - settings.set_PrinterName(printer); - } - - - @Override - public String getName(){ - return printer; - } - - - private PrinterName getPrinterName(){ - if(name == null){ - name = new PrinterName(printer, null); - } - return name; - } - - - public void wakeNotifier() { - synchronized (this) { - if (notifier != null) { - notifier.wake(); - } - } - } - - - @Override - public void addPrintServiceAttributeListener(PrintServiceAttributeListener listener){ - synchronized (this) { - if (listener == null) { - return; - } - if (notifier == null) { - notifier = new ServiceNotifier(this); - } - notifier.addListener(listener); - } - } - - - @Override - public void removePrintServiceAttributeListener(PrintServiceAttributeListener listener){ - synchronized (this) { - if (listener == null || notifier == null ) { - return; - } - notifier.removeListener(listener); - if (notifier.isEmpty()) { - notifier.stopNotifier(); - notifier = null; - } - } - } - - - @Override - public DocPrintJob createPrintJob(){ - SecurityManager security = System.getSecurityManager(); - if(security != null){ - security.checkPrintJobAccess(); - } - return new Win32PrintJob(this, peer); - } - - - @Override - public <T extends PrintServiceAttribute>T getAttribute(Class<T> category){ - if(category == null){ - throw new NullPointerException("category"); - } - if(!(PrintServiceAttribute.class.isAssignableFrom(category))){ - throw new IllegalArgumentException("The categhory '" + category + "' is not a valid PrintServiceAttribute"); - } - if(category == ColorSupported.class){ - // works better than settings.get_SupportsColor(); - if(settings.get_DefaultPageSettings().get_Color()){ - return (T)ColorSupported.SUPPORTED; - }else{ - return (T)ColorSupported.NOT_SUPPORTED; - } - }else if(category == PrinterName.class){ - return (T)getPrinterName(); - } else { - // QueuedJobCount and PrinterIsAcceptingJobs - return (T)peer.getPrinterStatus(printer, category); - } - } - - - @Override - public PrintServiceAttributeSet getAttributes(){ - PrintServiceAttributeSet attrs = new HashPrintServiceAttributeSet(); - attrs.add(getPrinterName()); - PrinterIsAcceptingJobs acptJobs = getAttribute(PrinterIsAcceptingJobs.class); - if(acptJobs != null){ - attrs.add(acptJobs); - } - PrinterState prnState = getAttribute(PrinterState.class); - if(prnState != null){ - attrs.add(prnState); - } - PrinterStateReasons prnStateReasons = getAttribute(PrinterStateReasons.class); - if(prnStateReasons != null){ - attrs.add(prnStateReasons); - } - QueuedJobCount jobCount = getAttribute(QueuedJobCount.class); - if(jobCount != null){ - attrs.add(jobCount); - } - // TODO: Seems to be more accurate than settings.get_SupportsColor(), which doesn't work for CutePDF - if(settings.get_DefaultPageSettings().get_Color()){ - attrs.add(ColorSupported.SUPPORTED); - }else{ - attrs.add(ColorSupported.NOT_SUPPORTED); - } - - return AttributeSetUtilities.unmodifiableView(attrs); - } - - - @Override - public Object getDefaultAttributeValue(Class<? extends Attribute> category){ - if (category == null) { - throw new NullPointerException("category must not be null"); - } - if ( !Attribute.class.isAssignableFrom( category ) ) { - throw new IllegalArgumentException( category +" has to be an " + Attribute.class.getName() ); - } - if ( !isAttributeCategorySupported( category ) ) { - return null; - } - if (category == Copies.class) { - short copies = settings.get_Copies(); - return new Copies( copies > 0 ? copies : 1 ); - } else if (category == Chromaticity.class) { - // NOTE: this works for CutePDF, settings.get_SupportsColor() does not - return settings.get_DefaultPageSettings().get_Color() ? Chromaticity.COLOR : Chromaticity.MONOCHROME; - } else if (category == JobName.class) { - return new JobName( "Java Printing", null ); // TODO this is Java-Default, use another one for IKVM? - } else if (category == OrientationRequested.class) { - return settings.get_DefaultPageSettings().get_Landscape() ? OrientationRequested.LANDSCAPE : OrientationRequested.PORTRAIT; - } else if (category == PageRanges.class) { - return new PageRanges(1, Integer.MAX_VALUE ); - } else if (category == Media.class) { - int rawKind = settings.get_DefaultPageSettings().get_PaperSize().get_RawKind(); - if( rawKind > MEDIA_NAMES.length || rawKind < 1 || MEDIA_NAMES[ rawKind - 1 ] == null ){ // custom page format - return findMatchingMedia( settings.get_DefaultPageSettings().get_PaperSize() ); - } else { - return MEDIA_NAMES[ rawKind - 1 ]; - } - } else if (category == MediaPrintableArea.class) { - RectangleF area = settings.get_DefaultPageSettings().get_PrintableArea(); - // get_PrintableArea is in 1/100 inch, see http://msdn.microsoft.com/de-de/library/system.drawing.printing.pagesettings.printablearea(v=VS.90).aspx - return new MediaPrintableArea(area.get_X()/100, area.get_Y()/100, area.get_Width()/100, area.get_Height()/100, MediaPrintableArea.INCH); - } else if (category == Destination.class) { - String path = "out.prn"; - try { - return new Destination( ( new File( path ) ).toURI() ); - } catch (SecurityException se) { - try { - return new Destination( new URI( "file:" + path) ); - } catch (URISyntaxException e) { - return null; - } - } - } else if (category == Sides.class) { - switch( settings.get_Duplex().Value ){ - case cli.System.Drawing.Printing.Duplex.Default: // MSDN: 'The printer's default duplex setting.' - what ever that might be - case cli.System.Drawing.Printing.Duplex.Simplex: - return Sides.ONE_SIDED; - case cli.System.Drawing.Printing.Duplex.Horizontal: - return Sides.TWO_SIDED_LONG_EDGE; - case cli.System.Drawing.Printing.Duplex.Vertical: - return Sides.TWO_SIDED_SHORT_EDGE; - } - } else if (category == PrinterResolution.class) { - cli.System.Drawing.Printing.PrinterResolution pRes = settings.get_DefaultPageSettings().get_PrinterResolution(); - int xRes = pRes.get_X(); - int yRes = pRes.get_Y(); - if ((xRes <= 0) || (yRes <= 0)) { - int res = (yRes > xRes) ? yRes : xRes; - if (res > 0) { - return new PrinterResolution(res, res, PrinterResolution.DPI); - } - } - else { - return new PrinterResolution(xRes, yRes, PrinterResolution.DPI); - } - } else if (category == ColorSupported.class) { - if ( settings.get_SupportsColor() ) { - return ColorSupported.SUPPORTED; - } else { - return ColorSupported.NOT_SUPPORTED; - } - } else if( category == PrintQuality.class ){ - cli.System.Drawing.Printing.PrinterResolutionKind kind = settings.get_DefaultPageSettings().get_PrinterResolution().get_Kind(); - switch (kind.Value) { - case cli.System.Drawing.Printing.PrinterResolutionKind.High: - return PrintQuality.HIGH; - case cli.System.Drawing.Printing.PrinterResolutionKind.Medium: - case cli.System.Drawing.Printing.PrinterResolutionKind.Low: - return PrintQuality.NORMAL; - case cli.System.Drawing.Printing.PrinterResolutionKind.Draft: - return PrintQuality.DRAFT; - } - } else if (category == RequestingUserName.class) { - try{ - return new RequestingUserName( System.getProperty("user.name", ""), null); - } catch( SecurityException e ){ - return new RequestingUserName( "", null); - } - } else if (category == SheetCollate.class){ - return settings.get_Collate() ? SheetCollate.COLLATED : SheetCollate.UNCOLLATED; - } else if (category == Fidelity.class) { - return Fidelity.FIDELITY_FALSE; - } - return null; - } - - - @Override - public ServiceUIFactory getServiceUIFactory(){ - return null; - } - - - @Override - public Class<?>[] getSupportedAttributeCategories(){ - ArrayList<Class> categList = new ArrayList<Class>(otherAttrCats.length+3); - for (int i=0; i < otherAttrCats.length; i++) { - categList.add(otherAttrCats[i]); - } - - if (settings.get_CanDuplex()) { - categList.add(Sides.class); - } - - if (settings.get_PrinterResolutions().get_Count() > 0) { - categList.add(PrinterResolution.class); - } - - return categList.toArray(new Class[categList.size()]); - } - - - @Override - public Object getSupportedAttributeValues(Class<? extends Attribute> category, DocFlavor flavor, AttributeSet attributes){ - if ( category == null || !Attribute.class.isAssignableFrom( category ) ) { - throw new IllegalArgumentException( "The category '" + category + "' is not an Attribute" ); - } - if( !isAttributeCategorySupported(category) ){ - return null; - } - if (category == JobName.class || category == RequestingUserName.class || category == ColorSupported.class - || category == Destination.class ) { - return getDefaultAttributeValue(category); - } - if( category == Copies.class ){ - return new CopiesSupported(1, settings.get_MaximumCopies() ); - } - if( category == Media.class ){ - PaperSizeCollection sizes = settings.get_PaperSizes(); - List<Media> medias = new ArrayList<Media>(); - for( int i = 0; i < sizes.get_Count(); i++ ){ - PaperSize media = sizes.get_Item(i); - MediaSizeName mediaName = findMatchingMedia( sizes.get_Item(i) ); - if( mediaName != null - && !medias.contains( mediaName )){ // slow but better than creating a HashSet here - medias.add( mediaName); - } - } - // add media trays - MediaTray[] trays = getMediaTrays(); - for( MediaTray tray : trays ){ - medias.add( tray ); - } - return medias.size() > 0 ? medias.toArray( new Media[medias.size() ] ) : null; - } - if (category == PageRanges.class) { - if (flavor == null|| flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) - || flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE)) { - PageRanges[] arr = new PageRanges[1]; - arr[0] = new PageRanges(1, Integer.MAX_VALUE); - return arr; - } else { - return null; - } - } - if (category == Fidelity.class) { - return new Fidelity[]{ Fidelity.FIDELITY_FALSE, Fidelity.FIDELITY_TRUE}; - } - if (category == PrintQuality.class) { - return new PrintQuality[]{ PrintQuality.DRAFT, PrintQuality.HIGH, PrintQuality.NORMAL }; - } - - boolean printPageAble = flavor == null|| flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) - || flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE); - if (category == Sides.class) { - if ( printPageAble ) { - return new Sides[]{ Sides.ONE_SIDED, Sides.TWO_SIDED_LONG_EDGE, Sides.TWO_SIDED_SHORT_EDGE}; - } else { - return null; - } - } - if (category == SheetCollate.class) { - if ( printPageAble ) { - return new SheetCollate[]{ SheetCollate.COLLATED, SheetCollate.UNCOLLATED} ; - } else { - return null; - } - } - boolean imageBased = printPageAble || flavor.equals(DocFlavor.INPUT_STREAM.GIF) - || flavor.equals(DocFlavor.INPUT_STREAM.JPEG) - || flavor.equals(DocFlavor.INPUT_STREAM.PNG) - || flavor.equals(DocFlavor.BYTE_ARRAY.GIF) - || flavor.equals(DocFlavor.BYTE_ARRAY.JPEG) - || flavor.equals(DocFlavor.BYTE_ARRAY.PNG) - || flavor.equals(DocFlavor.URL.GIF) - || flavor.equals(DocFlavor.URL.JPEG) - || flavor.equals(DocFlavor.URL.PNG); - if (category == OrientationRequested.class) { - if( imageBased ){ - return new OrientationRequested[]{ OrientationRequested.PORTRAIT, OrientationRequested.LANDSCAPE, OrientationRequested.REVERSE_LANDSCAPE }; - } else { - return null; - } - } - if (category == Chromaticity.class) { - if( imageBased ){ - if( settings.get_DefaultPageSettings().get_Color() ){ - return new Chromaticity[]{ Chromaticity.MONOCHROME, Chromaticity.COLOR }; - } else { - return new Chromaticity[]{ Chromaticity.MONOCHROME }; - } - } else { - return null; - } - } - return null; - } - - private MediaTray[] getMediaTrays(){ - if( mediaTrays != null ){ - // the print service is a singleton per printer so we only do this once - return mediaTrays; - } - PaperSourceCollection trays = settings.get_PaperSources(); - int count = trays.get_Count(); - List<MediaTray> trayList = new ArrayList<MediaTray>(); - for( int i=0; i < count; i++ ){ - PaperSource tray = trays.get_Item(i); - MediaTray javaTray = getDefaultTray(tray); - if( javaTray != null ){ - trayList.add( javaTray ); - } else { - trayList.add( new NetMediaTray( tray ) ); - } - } - mediaTrays = trayList.toArray( new MediaTray[trayList.size()]); - return mediaTrays; - } - - - @Override - public DocFlavor[] getSupportedDocFlavors(){ - int len = supportedFlavors.length; - DocFlavor[] result = new DocFlavor[len]; - System.arraycopy(supportedFlavors, 0, result, 0, len); - return result; - } - - - @Override - public AttributeSet getUnsupportedAttributes(DocFlavor flavor, AttributeSet attributes){ - // TODO Auto-generated method stub - return null; - } - - - @Override - public boolean isAttributeCategorySupported(Class<? extends Attribute> category){ - if ( category == null || !Attribute.class.isAssignableFrom( category ) ) { - throw new IllegalArgumentException( "The category '" + category + "' is not an Attribute" ); - } - Class<?>[] supported = getSupportedAttributeCategories(); - for( int i=0; i < supported.length; i++ ){ - if( category == supported[i] ){ - return true; - } - } - return false; - } - - - private boolean isPostScriptFlavor(DocFlavor flavor) { - if (flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT) || - flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) || - flavor.equals(DocFlavor.URL.POSTSCRIPT)) { - return true; - } - else { - return false; - } - } - - private boolean isPSDocAttr(Class category) { - if (category == OrientationRequested.class || category == Copies.class) { - return true; - } - else { - return false; - } - } - - private boolean isAutoSense(DocFlavor flavor) { - if (flavor.equals(DocFlavor.BYTE_ARRAY.AUTOSENSE) || - flavor.equals(DocFlavor.INPUT_STREAM.AUTOSENSE) || - flavor.equals(DocFlavor.URL.AUTOSENSE)) { - return true; - } - else { - return false; - } - } - - @Override - public boolean isAttributeValueSupported(Attribute attr, DocFlavor flavor, AttributeSet attributes){ - if (attr == null) { - throw new NullPointerException("null attribute"); - } - Class category = attr.getCategory(); - if (flavor != null) { - if (!isDocFlavorSupported(flavor)) { - throw new IllegalArgumentException(flavor + - " is an unsupported flavor"); - // if postscript & category is already specified within the PostScript data - // we return false - } else if (isAutoSense(flavor) || (isPostScriptFlavor(flavor) && - (isPSDocAttr(category)))) { - return false; - } - } - - if (!isAttributeCategorySupported(category)) { - return false; - } - else if (category == Chromaticity.class) { - if ((flavor == null) || - flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) || - flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE) || - flavor.equals(DocFlavor.BYTE_ARRAY.GIF) || - flavor.equals(DocFlavor.INPUT_STREAM.GIF) || - flavor.equals(DocFlavor.URL.GIF) || - flavor.equals(DocFlavor.BYTE_ARRAY.JPEG) || - flavor.equals(DocFlavor.INPUT_STREAM.JPEG) || - flavor.equals(DocFlavor.URL.JPEG) || - flavor.equals(DocFlavor.BYTE_ARRAY.PNG) || - flavor.equals(DocFlavor.INPUT_STREAM.PNG) || - flavor.equals(DocFlavor.URL.PNG)) { - if (settings.get_DefaultPageSettings().get_Color()) { - return true; - } else { - return attr == Chromaticity.MONOCHROME; - } - } else { - return false; - } - } else if (category == Copies.class) { - return ((Copies)attr).getValue() >= 1 && ((Copies)attr).getValue() <= settings.get_MaximumCopies(); - - } else if (category == Destination.class) { - URI uri = ((Destination)attr).getURI(); - if ("file".equals(uri.getScheme()) && - !(uri.getSchemeSpecificPart().equals(""))) { - return true; - } else { - return false; - } - - } else if (category == Media.class) { - Media[] medias = (Media[])getSupportedAttributeValues( Media.class, flavor, attributes ); - if( medias != null ) { - return Arrays.asList( medias ).contains( attr ); - } - - } else if (category == MediaPrintableArea.class) { - //TODO - return true; - - } else if (category == SunAlternateMedia.class) { - Media media = ((SunAlternateMedia)attr).getMedia(); - return isAttributeValueSupported(media, flavor, attributes); - - } else if (category == PageRanges.class || - category == SheetCollate.class || - category == Sides.class) { - if (flavor != null && - !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) || - flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE))) { - return false; - } - } else if (category == PrinterResolution.class) { - if (attr instanceof PrinterResolution) { - int[] jRes = ((PrinterResolution)attr).getResolution( PrinterResolution.DPI ); - PrinterResolutionCollection resolutions = settings.get_PrinterResolutions(); - for( int i=0; i< resolutions.get_Count(); i++ ) { - cli.System.Drawing.Printing.PrinterResolution nRes = resolutions.get_Item( i ); - if( nRes.get_X() == jRes[0] && nRes.get_Y() == jRes[1] ) { - return true; - } - } - return false; - } - } else if (category == OrientationRequested.class) { - if (attr == OrientationRequested.REVERSE_PORTRAIT || - (flavor != null) && - !(flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE) || - flavor.equals(DocFlavor.SERVICE_FORMATTED.PRINTABLE) || - flavor.equals(DocFlavor.INPUT_STREAM.GIF) || - flavor.equals(DocFlavor.INPUT_STREAM.JPEG) || - flavor.equals(DocFlavor.INPUT_STREAM.PNG) || - flavor.equals(DocFlavor.BYTE_ARRAY.GIF) || - flavor.equals(DocFlavor.BYTE_ARRAY.JPEG) || - flavor.equals(DocFlavor.BYTE_ARRAY.PNG) || - flavor.equals(DocFlavor.URL.GIF) || - flavor.equals(DocFlavor.URL.JPEG) || - flavor.equals(DocFlavor.URL.PNG))) { - return false; - } - - } else if (category == ColorSupported.class) { - boolean isColorSup = settings.get_DefaultPageSettings().get_Color(); - if ((!isColorSup && (attr == ColorSupported.SUPPORTED)) || - (isColorSup && (attr == ColorSupported.NOT_SUPPORTED))) { - return false; - } - } - return true; - } - - - @Override - public boolean isDocFlavorSupported(DocFlavor flavor){ - for (int f=0; f<supportedFlavors.length; f++) { - if (flavor.equals(supportedFlavors[f])) { - return true; - } - } - return false; - } - - - @Override - public String toString(){ - return "Win32 Printer : " + getName(); - } - - - @Override - public boolean equals(Object obj){ - return (obj == this || (obj instanceof Win32PrintService && ((Win32PrintService)obj).getName() - .equals(getName()))); - } - - - @Override - public int hashCode(){ - return this.getClass().hashCode() + getName().hashCode(); - } - - /** - * Tries to find a matching {@link MediaSizeName} for a paper by it's size - * @param paper - * @return - */ - private MediaSizeName findMatchingMedia( PaperSize paper ){ - int rawKind = paper.get_RawKind(); - if( rawKind > 0 && rawKind <= MEDIA_NAMES.length ){ - // match to predefined size - MediaSizeName media = MEDIA_NAMES[ rawKind - 1 ]; - if( media != null ) { - return media; - } - } - int x = paper.get_Width() * INCH100_TO_MYM; - int y = paper.get_Height() * INCH100_TO_MYM; - if( x > y ){ // MediaSizes are always portrait! - int tmp = x; - x = y; - y = tmp; - } - for( MediaSizeName name : MEDIA_NAMES ){ - MediaSize media = MediaSize.getMediaSizeForName(name); - if( media != null ){ - if( Math.abs( x - media.getX(1) ) < MATCH_DIFF && Math.abs( y - media.getY(1) ) < MATCH_DIFF ){ - return name; - } - } - } - MediaSizeName media = CUSTOM_MEDIA_NAME.get(paper.get_PaperName()); - if (media == null) { - media = new CustomMediaSizeName(paper.get_PaperName()); - CUSTOM_MEDIA_NAME.put(paper.get_PaperName(), media); - new MediaSize( x, y, MediaSize.INCH/100, media); - } - return media; - } - - /** - * Returns the Java-default {@link MediaTray} for a paper source. This is required since these default - * trays are public constants which can be used without checking for the actually present media trays - * @param source the .NET paper source to get the predefined source for - * @return the media tray or null, in case there is no mapping for the paper source - */ - private MediaTray getDefaultTray( PaperSource source ){ - // convert from .NET kind to java's pre defined MediaTrays - switch( source.get_RawKind() ){ - case 1 : return MediaTray.TOP; - case 2 : return MediaTray.BOTTOM; - case 3 : return MediaTray.MIDDLE; - case 4 : return MediaTray.MANUAL; - case 5 : return MediaTray.ENVELOPE; - case 6 : return Win32MediaTray.ENVELOPE_MANUAL; - case 7 : return Win32MediaTray.AUTO; - case 8 : return Win32MediaTray.TRACTOR; - case 9 : return Win32MediaTray.SMALL_FORMAT; - case 10 : return Win32MediaTray.LARGE_FORMAT; - case 11 : return MediaTray.LARGE_CAPACITY; - case 14 : return MediaTray.MAIN; - case 15 : return Win32MediaTray.FORMSOURCE; - // FIXME which PaperSourceKind is MediaTray.SIDE ??? - } - return null; - } - - /** - * Returns the .NET {@link PaperSource} for a media tray. This will be done either by mapping or - * directly in case the tray is a {@link NetMediaTray} - * @param tray the tray to get the paper source for, must not be null - * @return the selected {@link PaperSource} or null, in case there is no matching {@link PaperSource} - */ - public PaperSource getPaperSourceForTray( MediaTray tray ){ - if( tray instanceof NetMediaTray ){ - return ((NetMediaTray)tray).getPaperSource( this ); - } - // try to find the appropriate paper source for the Java-Defined tray - PaperSourceCollection trays = settings.get_PaperSources(); - int count = trays.get_Count(); - for( int i=0; i < count; i++ ){ - PaperSource paperSource = trays.get_Item(i); - if( getDefaultTray( paperSource ) == tray ){ - return paperSource; - } - } - return null; - } - - public static class NetMediaTray extends MediaTray{ - - private static final long serialVersionUID = 1L; - - /** Not really used but required by the EnumSyntax super class */ - private static AtomicInteger idCounter = new AtomicInteger(8); - - private int rawKind; - private String name; - private transient PaperSource netSource; - - public NetMediaTray( PaperSource netSource ) { - super( idCounter.getAndIncrement() ); - this.rawKind = netSource.get_RawKind(); - this.name = netSource.get_SourceName(); - this.netSource = netSource; - } - - public PaperSource getPaperSource( Win32PrintService service ){ - if( netSource == null ){ - PaperSourceCollection sources = service.settings.get_PaperSources(); - int count = sources.get_Count(); - for( int i=0; i < count; i++ ){ - PaperSource source = sources.get_Item(i); - if( source.get_RawKind() == rawKind ){ - netSource = source; - break; - } - } - } - return netSource; - } - - @Override - public String toString() { - return netSource != null ? netSource.get_SourceName() : name; - } - } -} diff --git a/openjdk/sun/print/Win32PrintServiceLookup.java b/openjdk/sun/print/Win32PrintServiceLookup.java deleted file mode 100644 index f230c852..00000000 --- a/openjdk/sun/print/Win32PrintServiceLookup.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - Copyright (C) 2009 Volker Berlin (i-net software) - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - - */ -package sun.print; - -import ikvm.awt.IkvmToolkit; - -import java.awt.Toolkit; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.IOException; -import java.util.ArrayList; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import javax.print.DocFlavor; -import javax.print.MultiDocPrintService; -import javax.print.PrintService; -import javax.print.PrintServiceLookup; -import javax.print.attribute.Attribute; -import javax.print.attribute.AttributeSet; -import javax.print.attribute.HashPrintRequestAttributeSet; -import javax.print.attribute.HashPrintServiceAttributeSet; -import javax.print.attribute.PrintRequestAttribute; -import javax.print.attribute.PrintRequestAttributeSet; -import javax.print.attribute.PrintServiceAttribute; -import javax.print.attribute.PrintServiceAttributeSet; -import javax.print.attribute.standard.PrinterName; - -public class Win32PrintServiceLookup extends PrintServiceLookup { - - private final PrintPeer peer = IkvmToolkit.DefaultToolkit.get().getPrintPeer(); - - private String defaultPrinter; - private PrintService defaultPrintService; - private String[] printers; /* excludes the default printer */ - private PrintService[] printServices; /* includes the default printer */ - - - /* Want the PrintService which is default print service to have - * equality of reference with the equivalent in list of print services - * This isn't required by the API and there's a risk doing this will - * lead people to assume its guaranteed. - */ - public synchronized PrintService[] getPrintServices() { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPrintJobAccess(); - } - if (printServices == null) { - refreshServices(); - } - return printServices; - } - - private synchronized void refreshServices() { - printers = peer.getAllPrinterNames(); - if (printers == null) { - // In Windows it is safe to assume no default if printers == null so we - // don't get the default. - printServices = new PrintService[0]; - return; - } - - PrintService[] newServices = new PrintService[printers.length]; - PrintService defService = getDefaultPrintService(); - for (int p = 0; p < printers.length; p++) { - if (defService != null && - printers[p].equals(defService.getName())) { - newServices[p] = defService; - } else { - if (printServices == null) { - newServices[p] = new Win32PrintService(printers[p], peer); - } else { - int j; - for (j = 0; j < printServices.length; j++) { - if ((printServices[j]!= null) && - (printers[p].equals(printServices[j].getName()))) { - newServices[p] = printServices[j]; - printServices[j] = null; - break; - } - } - if (j == printServices.length) { - newServices[p] = new Win32PrintService(printers[p], peer); - } - } - } - } - - printServices = newServices; - } - - - public synchronized PrintService getPrintServiceByName(String name) { - - if (name == null || name.equals("")) { - return null; - } else { - /* getPrintServices() is now very fast. */ - PrintService[] printServices = getPrintServices(); - for (int i=0; i<printServices.length; i++) { - if (printServices[i].getName().equals(name)) { - return printServices[i]; - } - } - return null; - } - } - - boolean matchingService(PrintService service, - PrintServiceAttributeSet serviceSet) { - if (serviceSet != null) { - Attribute [] attrs = serviceSet.toArray(); - Attribute serviceAttr; - for (int i=0; i<attrs.length; i++) { - serviceAttr - = service.getAttribute((Class<PrintServiceAttribute>)attrs[i].getCategory()); - if (serviceAttr == null || !serviceAttr.equals(attrs[i])) { - return false; - } - } - } - return true; - } - - public PrintService[] getPrintServices(DocFlavor flavor, - AttributeSet attributes) { - - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPrintJobAccess(); - } - PrintRequestAttributeSet requestSet = null; - PrintServiceAttributeSet serviceSet = null; - - if (attributes != null && !attributes.isEmpty()) { - - requestSet = new HashPrintRequestAttributeSet(); - serviceSet = new HashPrintServiceAttributeSet(); - - Attribute[] attrs = attributes.toArray(); - for (int i=0; i<attrs.length; i++) { - if (attrs[i] instanceof PrintRequestAttribute) { - requestSet.add(attrs[i]); - } else if (attrs[i] instanceof PrintServiceAttribute) { - serviceSet.add(attrs[i]); - } - } - } - - /* - * Special case: If client is asking for a particular printer - * (by name) then we can save time by getting just that service - * to check against the rest of the specified attributes. - */ - PrintService[] services = null; - if (serviceSet != null && serviceSet.get(PrinterName.class) != null) { - PrinterName name = (PrinterName)serviceSet.get(PrinterName.class); - PrintService service = getPrintServiceByName(name.getValue()); - if (service == null || !matchingService(service, serviceSet)) { - services = new PrintService[0]; - } else { - services = new PrintService[1]; - services[0] = service; - } - } else { - services = getPrintServices(); - } - - if (services.length == 0) { - return services; - } else { - ArrayList matchingServices = new ArrayList(); - for (int i=0; i<services.length; i++) { - try { - if (services[i]. - getUnsupportedAttributes(flavor, requestSet) == null) { - matchingServices.add(services[i]); - } - } catch (IllegalArgumentException e) { - } - } - services = new PrintService[matchingServices.size()]; - return (PrintService[])matchingServices.toArray(services); - } - } - - /* - * return empty array as don't support multi docs - */ - public MultiDocPrintService[] - getMultiDocPrintServices(DocFlavor[] flavors, - AttributeSet attributes) { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPrintJobAccess(); - } - return new MultiDocPrintService[0]; - } - - - public synchronized PrintService getDefaultPrintService() { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPrintJobAccess(); - } - - - // Windows does not have notification for a change in default - // so we always get the latest. - defaultPrinter = peer.getDefaultPrinterName(); - if (defaultPrinter == null) { - return null; - } - - if ((defaultPrintService != null) && - defaultPrintService.getName().equals(defaultPrinter)) { - - return defaultPrintService; - } - - // Not the same as default so proceed to get new PrintService. - - // clear defaultPrintService - defaultPrintService = null; - - if (printServices != null) { - for (int j=0; j<printServices.length; j++) { - if (defaultPrinter.equals(printServices[j].getName())) { - defaultPrintService = printServices[j]; - break; - } - } - } - - if (defaultPrintService == null) { - defaultPrintService = new Win32PrintService(defaultPrinter, peer); - } - return defaultPrintService; - } -} diff --git a/openjdk/sun/reflect/CallerSensitive.java b/openjdk/sun/reflect/CallerSensitive.java deleted file mode 100644 index b238baaf..00000000 --- a/openjdk/sun/reflect/CallerSensitive.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.reflect; - -import java.lang.annotation.*; -import static java.lang.annotation.ElementType.*; - -/** - * A method annotated @CallerSensitive is sensitive to its calling class, - * via {@link sun.reflect.Reflection#getCallerClass Reflection.getCallerClass}, - * or via some equivalent. - * - * @author John R. Rose - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({METHOD}) -public @interface CallerSensitive { -} diff --git a/openjdk/sun/reflect/MethodAccessor.java b/openjdk/sun/reflect/MethodAccessor.java deleted file mode 100644 index 1115f191..00000000 --- a/openjdk/sun/reflect/MethodAccessor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.reflect; - -import java.lang.reflect.InvocationTargetException; - -/** This interface provides the declaration for - java.lang.reflect.Method.invoke(). Each Method object is - configured with a (possibly dynamically-generated) class which - implements this interface. -*/ - -public interface MethodAccessor { - /** Matches specification in {@link java.lang.reflect.Method} */ - public Object invoke(Object obj, Object[] args, ikvm.internal.CallerID callerID) - throws IllegalArgumentException, InvocationTargetException; -} diff --git a/openjdk/sun/reflect/Reflection.java b/openjdk/sun/reflect/Reflection.java deleted file mode 100644 index 6cff5746..00000000 --- a/openjdk/sun/reflect/Reflection.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * Copyright (c) 2001, 2006, 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. - */ - -/*IKVM*/ -/* Modified for IKVM by Jeroen Frijters - * - * May 27, 2007 Added support for @ikvm.lang.Internal access modifier - * - */ -/*IKVM*/ - -package sun.reflect; - -import java.lang.reflect.*; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** Common utility routines used by both java.lang and - java.lang.reflect */ - -public class Reflection { - - /** Used to filter out fields and methods from certain classes from public - view, where they are sensitive or they may contain VM-internal objects. - These Maps are updated very rarely. Rather than synchronize on - each access, we use copy-on-write */ - private static volatile Map<Class,String[]> fieldFilterMap; - private static volatile Map<Class,String[]> methodFilterMap; - - static { - Map<Class,String[]> map = new HashMap<Class,String[]>(); - map.put(Reflection.class, - new String[] {"fieldFilterMap", "methodFilterMap"}); - map.put(System.class, new String[] {"security"}); - fieldFilterMap = map; - - methodFilterMap = new HashMap<Class,String[]>(); - // [IKVM] to avoid initialization order issues, we actually add - // Unsafe.getUnsafe() here, instead of in Unsafe's class initializer - methodFilterMap.put(sun.misc.Unsafe.class, new String[] {"getUnsafe"}); - } - - /** Returns the class of the caller of the method calling this method, - ignoring frames associated with java.lang.reflect.Method.invoke() - and its implementation. */ - @CallerSensitive - public static Class getCallerClass() { - return getCallerClass(2); - } - - /** Returns the class of the method <code>realFramesToSkip</code> - frames up the stack (zero-based), ignoring frames associated - with java.lang.reflect.Method.invoke() and its implementation. - The first frame is that associated with this method, so - <code>getCallerClass(0)</code> returns the Class object for - sun.reflect.Reflection. Frames associated with - java.lang.reflect.Method.invoke() and its implementation are - completely ignored and do not count toward the number of "real" - frames skipped. */ - @CallerSensitive - public static native Class getCallerClass(int realFramesToSkip); - - /** Retrieves the access flags written to the class file. For - inner classes these flags may differ from those returned by - Class.getModifiers(), which searches the InnerClasses - attribute to find the source-level access flags. This is used - instead of Class.getModifiers() for run-time access checks due - to compatibility reasons; see 4471811. Only the values of the - low 13 bits (i.e., a mask of 0x1FFF) are guaranteed to be - valid. */ - private static native int getClassAccessFlags(Class c); - - /** A quick "fast-path" check to try to avoid getCallerClass() - calls. */ - public static boolean quickCheckMemberAccess(Class memberClass, - int modifiers) - { - return Modifier.isPublic(getClassAccessFlags(memberClass) & modifiers); - } - - public static void ensureMemberAccess(Class currentClass, - Class memberClass, - Object target, - int modifiers) - throws IllegalAccessException - { - if (currentClass == null || memberClass == null) { - throw new InternalError(); - } - - if (!verifyMemberAccess(currentClass, memberClass, target, modifiers)) { - throw new IllegalAccessException("Class " + currentClass.getName() + - " can not access a member of class " + - memberClass.getName() + - " with modifiers \"" + - Modifier.toString(modifiers) + - "\""); - } - } - - /*IKVM*/ - private static native boolean checkInternalAccess(Class currentClass, Class memberClass); - - public static boolean verifyMemberAccess(Class currentClass, - // Declaring class of field - // or method - Class memberClass, - // May be NULL in case of statics - Object target, - int modifiers) - { - // Verify that currentClass can access a field, method, or - // constructor of memberClass, where that member's access bits are - // "modifiers". - - boolean gotIsSameClassPackage = false; - boolean isSameClassPackage = false; - - if (currentClass == memberClass) { - // Always succeeds - return true; - } - - if (!Modifier.isPublic(getClassAccessFlags(memberClass))) { - isSameClassPackage = isSameClassPackage(currentClass, memberClass); - gotIsSameClassPackage = true; - /*IKVM*/ - if (!isSameClassPackage && !checkInternalAccess(currentClass, memberClass)) { - return false; - } - } - - // At this point we know that currentClass can access memberClass. - - if (Modifier.isPublic(modifiers)) { - return true; - } - - /*IKVM*/ - // Is the member @ikvm.lang.Internal accessible? - if ((modifiers & 0x40000000) != 0) { - return currentClass.getClassLoader() == memberClass.getClassLoader(); - } - - boolean successSoFar = false; - - if (Modifier.isProtected(modifiers)) { - // See if currentClass is a subclass of memberClass - if (isSubclassOf(currentClass, memberClass)) { - successSoFar = true; - } - } - - if (!successSoFar && !Modifier.isPrivate(modifiers)) { - if (!gotIsSameClassPackage) { - isSameClassPackage = isSameClassPackage(currentClass, - memberClass); - gotIsSameClassPackage = true; - } - - if (isSameClassPackage) { - successSoFar = true; - } - } - - if (!successSoFar) { - return false; - } - - if (Modifier.isProtected(modifiers)) { - // Additional test for protected members: JLS 6.6.2 - Class targetClass = (target == null ? memberClass : target.getClass()); - if (targetClass != currentClass) { - if (!gotIsSameClassPackage) { - isSameClassPackage = isSameClassPackage(currentClass, memberClass); - gotIsSameClassPackage = true; - } - if (!isSameClassPackage) { - if (!isSubclassOf(targetClass, currentClass)) { - return false; - } - } - } - } - - return true; - } - - private static boolean isSameClassPackage(Class c1, Class c2) { - return isSameClassPackage(c1.getClassLoader(), c1.getName(), - c2.getClassLoader(), c2.getName()); - } - - /** Returns true if two classes are in the same package; classloader - and classname information is enough to determine a class's package */ - private static boolean isSameClassPackage(ClassLoader loader1, String name1, - ClassLoader loader2, String name2) - { - if (loader1 != loader2) { - return false; - } else { - int lastDot1 = name1.lastIndexOf('.'); - int lastDot2 = name2.lastIndexOf('.'); - if ((lastDot1 == -1) || (lastDot2 == -1)) { - // One of the two doesn't have a package. Only return true - // if the other one also doesn't have a package. - return (lastDot1 == lastDot2); - } else { - int idx1 = 0; - int idx2 = 0; - - // Skip over '['s - if (name1.charAt(idx1) == '[') { - do { - idx1++; - } while (name1.charAt(idx1) == '['); - if (name1.charAt(idx1) != 'L') { - // Something is terribly wrong. Shouldn't be here. - throw new InternalError("Illegal class name " + name1); - } - } - if (name2.charAt(idx2) == '[') { - do { - idx2++; - } while (name2.charAt(idx2) == '['); - if (name2.charAt(idx2) != 'L') { - // Something is terribly wrong. Shouldn't be here. - throw new InternalError("Illegal class name " + name2); - } - } - - // Check that package part is identical - int length1 = lastDot1 - idx1; - int length2 = lastDot2 - idx2; - - if (length1 != length2) { - return false; - } - return name1.regionMatches(false, idx1, name2, idx2, length1); - } - } - } - - static boolean isSubclassOf(Class queryClass, - Class ofClass) - { - while (queryClass != null) { - if (queryClass == ofClass) { - return true; - } - queryClass = queryClass.getSuperclass(); - } - return false; - } - - // fieldNames must contain only interned Strings - public static synchronized void registerFieldsToFilter(Class containingClass, - String ... fieldNames) { - fieldFilterMap = - registerFilter(fieldFilterMap, containingClass, fieldNames); - } - - // methodNames must contain only interned Strings - public static synchronized void registerMethodsToFilter(Class containingClass, - String ... methodNames) { - methodFilterMap = - registerFilter(methodFilterMap, containingClass, methodNames); - } - - private static Map<Class,String[]> registerFilter(Map<Class,String[]> map, - Class containingClass, String ... names) { - if (map.get(containingClass) != null) { - throw new IllegalArgumentException - ("Filter already registered: " + containingClass); - } - map = new HashMap<Class,String[]>(map); - map.put(containingClass, names); - return map; - } - - public static Field[] filterFields(Class containingClass, - Field[] fields) { - if (fieldFilterMap == null) { - // Bootstrapping - return fields; - } - return (Field[])filter(fields, fieldFilterMap.get(containingClass)); - } - - public static Method[] filterMethods(Class containingClass, Method[] methods) { - if (methodFilterMap == null) { - // Bootstrapping - return methods; - } - return (Method[])filter(methods, methodFilterMap.get(containingClass)); - } - - private static Member[] filter(Member[] members, String[] filteredNames) { - if ((filteredNames == null) || (members.length == 0)) { - return members; - } - int numNewMembers = 0; - for (Member member : members) { - boolean shouldSkip = false; - for (String filteredName : filteredNames) { - if (member.getName() == filteredName) { - shouldSkip = true; - break; - } - } - if (!shouldSkip) { - ++numNewMembers; - } - } - Member[] newMembers = - (Member[])Array.newInstance(members[0].getClass(), numNewMembers); - int destIdx = 0; - for (Member member : members) { - boolean shouldSkip = false; - for (String filteredName : filteredNames) { - if (member.getName() == filteredName) { - shouldSkip = true; - break; - } - } - if (!shouldSkip) { - newMembers[destIdx++] = member; - } - } - return newMembers; - } -} diff --git a/openjdk/sun/reflect/ReflectionFactory.java b/openjdk/sun/reflect/ReflectionFactory.java deleted file mode 100644 index 5a3a848e..00000000 --- a/openjdk/sun/reflect/ReflectionFactory.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2001, 2008, 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. - */ - -/*IKVM*/ -/* - * May 29, 2007 Modified for IKVM.NET by Jeroen Frijters - * - */ - -package sun.reflect; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; - -/** <P> The master factory for all reflective objects, both those in - java.lang.reflect (Fields, Methods, Constructors) as well as their - delegates (FieldAccessors, MethodAccessors, ConstructorAccessors). - </P> - - <P> The methods in this class are extremely unsafe and can cause - subversion of both the language and the verifier. For this reason, - they are all instance methods, and access to the constructor of - this factory is guarded by a security check, in similar style to - {@link sun.misc.Unsafe}. </P> -*/ - -public class ReflectionFactory { - - private static Permission reflectionFactoryAccessPerm - = new RuntimePermission("reflectionFactoryAccess"); - private static ReflectionFactory soleInstance = new ReflectionFactory(); - // Provides access to package-private mechanisms in java.lang.reflect - private static volatile LangReflectAccess langReflectAccess; - - private ReflectionFactory() { - } - - /** - * A convenience class for acquiring the capability to instantiate - * reflective objects. Use this instead of a raw call to {@link - * #getReflectionFactory} in order to avoid being limited by the - * permissions of your callers. - * - * <p>An instance of this class can be used as the argument of - * <code>AccessController.doPrivileged</code>. - */ - public static final class GetReflectionFactoryAction - implements PrivilegedAction<ReflectionFactory> { - public ReflectionFactory run() { - return getReflectionFactory(); - } - } - - /** - * Provides the caller with the capability to instantiate reflective - * objects. - * - * <p> First, if there is a security manager, its - * <code>checkPermission</code> method is called with a {@link - * java.lang.RuntimePermission} with target - * <code>"reflectionFactoryAccess"</code>. This may result in a - * security exception. - * - * <p> The returned <code>ReflectionFactory</code> object should be - * carefully guarded by the caller, since it can be used to read and - * write private data and invoke private methods, as well as to load - * unverified bytecodes. It must never be passed to untrusted code. - * - * @exception SecurityException if a security manager exists and its - * <code>checkPermission</code> method doesn't allow - * access to the RuntimePermission "reflectionFactoryAccess". */ - public static ReflectionFactory getReflectionFactory() { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - // TO DO: security.checkReflectionFactoryAccess(); - security.checkPermission(reflectionFactoryAccessPerm); - } - return soleInstance; - } - - //-------------------------------------------------------------------------- - // - // Routines used by java.lang.reflect - // - // - - /** Called only by java.lang.reflect.Modifier's static initializer */ - public void setLangReflectAccess(LangReflectAccess access) { - langReflectAccess = access; - } - - /** - * Note: this routine can cause the declaring class for the field - * be initialized and therefore must not be called until the - * first get/set of this field. - * @param field the field - * @param override true if caller has overridden aaccessibility - */ - public native FieldAccessor newFieldAccessor(Field field, boolean override); - - public native MethodAccessor newMethodAccessor(Method method); - - private native ConstructorAccessor newConstructorAccessor0(Constructor c); - - public ConstructorAccessor newConstructorAccessor(Constructor c) { - Class<?> declaringClass = c.getDeclaringClass(); - if (Modifier.isAbstract(declaringClass.getModifiers())) { - return new InstantiationExceptionConstructorAccessorImpl(null); - } - if (declaringClass == Class.class) { - return new InstantiationExceptionConstructorAccessorImpl - ("Can not instantiate java.lang.Class"); - } - return newConstructorAccessor0(c); - } - - //-------------------------------------------------------------------------- - // - // Routines used by java.lang - // - // - - /** Creates a new java.lang.reflect.Field. Access checks as per - java.lang.reflect.AccessibleObject are not overridden. */ - public Field newField(Class<?> declaringClass, - String name, - Class<?> type, - int modifiers, - int slot, - String signature, - byte[] annotations) - { - return langReflectAccess().newField(declaringClass, - name, - type, - modifiers, - slot, - signature, - annotations); - } - - /** Creates a new java.lang.reflect.Method. Access checks as per - java.lang.reflect.AccessibleObject are not overridden. */ - public Method newMethod(Class<?> declaringClass, - String name, - Class<?>[] parameterTypes, - Class<?> returnType, - Class<?>[] checkedExceptions, - int modifiers, - int slot, - String signature, - byte[] annotations, - byte[] parameterAnnotations, - byte[] annotationDefault) - { - return langReflectAccess().newMethod(declaringClass, - name, - parameterTypes, - returnType, - checkedExceptions, - modifiers, - slot, - signature, - annotations, - parameterAnnotations, - annotationDefault); - } - - /** Creates a new java.lang.reflect.Constructor. Access checks as - per java.lang.reflect.AccessibleObject are not overridden. */ - public Constructor newConstructor(Class<?> declaringClass, - Class<?>[] parameterTypes, - Class<?>[] checkedExceptions, - int modifiers, - int slot, - String signature, - byte[] annotations, - byte[] parameterAnnotations) - { - return langReflectAccess().newConstructor(declaringClass, - parameterTypes, - checkedExceptions, - modifiers, - slot, - signature, - annotations, - parameterAnnotations); - } - - /** Gets the MethodAccessor object for a java.lang.reflect.Method */ - public MethodAccessor getMethodAccessor(Method m) { - return langReflectAccess().getMethodAccessor(m); - } - - /** Sets the MethodAccessor object for a java.lang.reflect.Method */ - public void setMethodAccessor(Method m, MethodAccessor accessor) { - langReflectAccess().setMethodAccessor(m, accessor); - } - - /** Gets the ConstructorAccessor object for a - java.lang.reflect.Constructor */ - public ConstructorAccessor getConstructorAccessor(Constructor c) { - return langReflectAccess().getConstructorAccessor(c); - } - - /** Sets the ConstructorAccessor object for a - java.lang.reflect.Constructor */ - public void setConstructorAccessor(Constructor c, - ConstructorAccessor accessor) - { - langReflectAccess().setConstructorAccessor(c, accessor); - } - - /** Makes a copy of the passed method. The returned method is a - "child" of the passed one; see the comments in Method.java for - details. */ - public Method copyMethod(Method arg) { - return langReflectAccess().copyMethod(arg); - } - - /** Makes a copy of the passed field. The returned field is a - "child" of the passed one; see the comments in Field.java for - details. */ - public Field copyField(Field arg) { - return langReflectAccess().copyField(arg); - } - - /** Makes a copy of the passed constructor. The returned - constructor is a "child" of the passed one; see the comments - in Constructor.java for details. */ - public <T> Constructor<T> copyConstructor(Constructor<T> arg) { - return langReflectAccess().copyConstructor(arg); - } - - //-------------------------------------------------------------------------- - // - // Routines used by serialization - // - // - - private static native ConstructorAccessor newConstructorAccessorForSerialization(Class classToInstantiate, Constructor constructorToCall); - - public Constructor newConstructorForSerialization - (Class<?> classToInstantiate, Constructor constructorToCall) - { - // Fast path - if (constructorToCall.getDeclaringClass() == classToInstantiate) { - return constructorToCall; - } - - ConstructorAccessor acc = newConstructorAccessorForSerialization(classToInstantiate, constructorToCall); - Constructor c = newConstructor(constructorToCall.getDeclaringClass(), - constructorToCall.getParameterTypes(), - constructorToCall.getExceptionTypes(), - constructorToCall.getModifiers(), - langReflectAccess(). - getConstructorSlot(constructorToCall), - langReflectAccess(). - getConstructorSignature(constructorToCall), - langReflectAccess(). - getConstructorAnnotations(constructorToCall), - langReflectAccess(). - getConstructorParameterAnnotations(constructorToCall)); - setConstructorAccessor(c, acc); - return c; - } - - //-------------------------------------------------------------------------- - // - // Internals only below this point - // - - private static LangReflectAccess langReflectAccess() { - if (langReflectAccess == null) { - // Call a static method to get class java.lang.reflect.Modifier - // initialized. Its static initializer will cause - // setLangReflectAccess() to be called from the context of the - // java.lang.reflect package. - Modifier.isPublic(Modifier.PUBLIC); - } - return langReflectAccess; - } -} diff --git a/openjdk/sun/reflect/annotation/AnnotationType.java b/openjdk/sun/reflect/annotation/AnnotationType.java deleted file mode 100644 index 80280018..00000000 --- a/openjdk/sun/reflect/annotation/AnnotationType.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.reflect.annotation; - -import sun.misc.JavaLangAccess; - -import java.lang.annotation.*; -import java.lang.reflect.*; -import java.util.*; -import java.security.AccessController; -import java.security.PrivilegedAction; - -/** - * Represents an annotation type at run time. Used to type-check annotations - * and apply member defaults. - * - * @author Josh Bloch - * @since 1.5 - */ -public class AnnotationType { - /** - * Member name -> type mapping. Note that primitive types - * are represented by the class objects for the corresponding wrapper - * types. This matches the return value that must be used for a - * dynamic proxy, allowing for a simple isInstance test. - */ - private final Map<String, Class<?>> memberTypes; - - /** - * Member name -> default value mapping. - */ - private final Map<String, Object> memberDefaults; - - /** - * Member name -> Method object mapping. This (and its assoicated - * accessor) are used only to generate AnnotationTypeMismatchExceptions. - */ - private final Map<String, Method> members; - - /** - * The retention policy for this annotation type. - */ - private final RetentionPolicy retention; - - /** - * Whether this annotation type is inherited. - */ - private final boolean inherited; - - /** - * Returns an AnnotationType instance for the specified annotation type. - * - * @throw IllegalArgumentException if the specified class object for - * does not represent a valid annotation type - */ - public static AnnotationType getInstance( - Class<? extends Annotation> annotationClass) - { - JavaLangAccess jla = sun.misc.SharedSecrets.getJavaLangAccess(); - AnnotationType result = jla.getAnnotationType(annotationClass); // volatile read - if (result == null) { - result = new AnnotationType(annotationClass); - // try to CAS the AnnotationType: null -> result - if (!jla.casAnnotationType(annotationClass, null, result)) { - // somebody was quicker -> read it's result - result = jla.getAnnotationType(annotationClass); - assert result != null; - } - } - - return result; - } - - /** - * Sole constructor. - * - * @param annotationClass the class object for the annotation type - * @throw IllegalArgumentException if the specified class object for - * does not represent a valid annotation type - */ - private AnnotationType(final Class<? extends Annotation> annotationClass) { - if (!annotationClass.isAnnotation()) - throw new IllegalArgumentException("Not an annotation type"); - - Method[] methods = - AccessController.doPrivileged(new PrivilegedAction<Method[]>() { - public Method[] run() { - // Initialize memberTypes and defaultValues - return annotationClass.getDeclaredMethods(); - } - }); - - memberTypes = new HashMap<String,Class<?>>(methods.length+1, 1.0f); - memberDefaults = new HashMap<String, Object>(0); - members = new HashMap<String, Method>(methods.length+1, 1.0f); - - for (Method method : methods) { - if (method.getParameterTypes().length != 0) - throw new IllegalArgumentException(method + " has params"); - String name = method.getName(); - Class<?> type = method.getReturnType(); - memberTypes.put(name, invocationHandlerReturnType(type)); - members.put(name, method); - - Object defaultValue = method.getDefaultValue(); - if (defaultValue != null) - memberDefaults.put(name, defaultValue); - } - - // Initialize retention, & inherited fields. Special treatment - // of the corresponding annotation types breaks infinite recursion. - if (annotationClass != Retention.class && - annotationClass != Inherited.class) { - Retention ret = (Retention) annotationClass.getDeclaredAnnotation(Retention.class); - retention = (ret == null ? RetentionPolicy.CLASS : ret.value()); - inherited = annotationClass.isAnnotationPresent(Inherited.class); - } - else { - retention = RetentionPolicy.RUNTIME; - inherited = false; - } - } - - /** - * Returns the type that must be returned by the invocation handler - * of a dynamic proxy in order to have the dynamic proxy return - * the specified type (which is assumed to be a legal member type - * for an annotation). - */ - public static Class<?> invocationHandlerReturnType(Class<?> type) { - // Translate primitives to wrappers - if (type == byte.class) - return Byte.class; - if (type == char.class) - return Character.class; - if (type == double.class) - return Double.class; - if (type == float.class) - return Float.class; - if (type == int.class) - return Integer.class; - if (type == long.class) - return Long.class; - if (type == short.class) - return Short.class; - if (type == boolean.class) - return Boolean.class; - - // Otherwise, just return declared type - return type; - } - - /** - * Returns member types for this annotation type - * (member name -> type mapping). - */ - public Map<String, Class<?>> memberTypes() { - return memberTypes; - } - - /** - * Returns members of this annotation type - * (member name -> associated Method object mapping). - */ - public Map<String, Method> members() { - return members; - } - - /** - * Returns the default values for this annotation type - * (Member name -> default value mapping). - */ - public Map<String, Object> memberDefaults() { - return memberDefaults; - } - - /** - * Returns the retention policy for this annotation type. - */ - public RetentionPolicy retention() { - return retention; - } - - /** - * Returns true if this this annotation type is inherited. - */ - public boolean isInherited() { - return inherited; - } - - /** - * For debugging. - */ - public String toString() { - return "Annotation Type:\n" + - " Member types: " + memberTypes + "\n" + - " Member defaults: " + memberDefaults + "\n" + - " Retention policy: " + retention + "\n" + - " Inherited: " + inherited; - } -} diff --git a/openjdk/sun/reflect/misc/ReflectUtil.java b/openjdk/sun/reflect/misc/ReflectUtil.java deleted file mode 100644 index 81468c20..00000000 --- a/openjdk/sun/reflect/misc/ReflectUtil.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -package sun.reflect.misc; - -import java.lang.reflect.Modifier; -import java.lang.reflect.Proxy; -import sun.reflect.Reflection; - -public final class ReflectUtil { - - private ReflectUtil() { - } - - public static Class forName(String name) - throws ClassNotFoundException { - checkPackageAccess(name); - return Class.forName(name); - } - - public static Object newInstance(Class cls) - throws InstantiationException, IllegalAccessException { - checkPackageAccess(cls); - return cls.newInstance(); - } - - /* - * Reflection.ensureMemberAccess is overly-restrictive - * due to a bug. We awkwardly work around it for now. - */ - public static void ensureMemberAccess(Class currentClass, - Class memberClass, - Object target, - int modifiers) - throws IllegalAccessException - { - if (target == null && Modifier.isProtected(modifiers)) { - int mods = modifiers; - mods = mods & (~Modifier.PROTECTED); - mods = mods | Modifier.PUBLIC; - - /* - * See if we fail because of class modifiers - */ - Reflection.ensureMemberAccess(currentClass, - memberClass, - target, - mods); - try { - /* - * We're still here so class access was ok. - * Now try with default field access. - */ - mods = mods & (~Modifier.PUBLIC); - Reflection.ensureMemberAccess(currentClass, - memberClass, - target, - mods); - /* - * We're still here so access is ok without - * checking for protected. - */ - return; - } catch (IllegalAccessException e) { - /* - * Access failed but we're 'protected' so - * if the test below succeeds then we're ok. - */ - if (isSubclassOf(currentClass, memberClass)) { - return; - } else { - throw e; - } - } - } else { - Reflection.ensureMemberAccess(currentClass, - memberClass, - target, - modifiers); - } - } - - private static boolean isSubclassOf(Class queryClass, - Class ofClass) - { - while (queryClass != null) { - if (queryClass == ofClass) { - return true; - } - queryClass = queryClass.getSuperclass(); - } - return false; - } - - - /** - * Checks package access on the given class. - * - * If it is a {@link Proxy#isProxyClass(java.lang.Class)} that implements - * a non-public interface (i.e. may be in a non-restricted package), - * also check the package access on the proxy interfaces. - */ - public static void checkPackageAccess(Class<?> clazz) { - checkPackageAccess(clazz.getName()); - if (isNonPublicProxyClass(clazz)) { - checkProxyPackageAccess(clazz); - } - } - - /** - * Checks package access on the given classname. - * This method is typically called when the Class instance is not - * available and the caller attempts to load a class on behalf - * the true caller (application). - */ - public static void checkPackageAccess(String name) { - SecurityManager s = System.getSecurityManager(); - if (s != null) { - String cname = name.replace('/', '.'); - if (cname.startsWith("[")) { - int b = cname.lastIndexOf('[') + 2; - if (b > 1 && b < cname.length()) { - cname = cname.substring(b); - } - } - int i = cname.lastIndexOf('.'); - if (i != -1) { - s.checkPackageAccess(cname.substring(0, i)); - } - } - } - - public static boolean isPackageAccessible(Class clazz) { - try { - checkPackageAccess(clazz); - } catch (SecurityException e) { - return false; - } - return true; - } - - // Returns true if p is an ancestor of cl i.e. class loader 'p' can - // be found in the cl's delegation chain - private static boolean isAncestor(ClassLoader p, ClassLoader cl) { - ClassLoader acl = cl; - do { - acl = acl.getParent(); - if (p == acl) { - return true; - } - } while (acl != null); - return false; - } - - /** - * Returns true if package access check is needed for reflective - * access from a class loader 'from' to classes or members in - * a class defined by class loader 'to'. This method returns true - * if 'from' is not the same as or an ancestor of 'to'. All code - * in a system domain are granted with all permission and so this - * method returns false if 'from' class loader is a class loader - * loading system classes. On the other hand, if a class loader - * attempts to access system domain classes, it requires package - * access check and this method will return true. - */ - public static boolean needsPackageAccessCheck(ClassLoader from, ClassLoader to) { - if (from == null || from == to) - return false; - - if (to == null) - return true; - - return !isAncestor(from, to); - } - - /** - * Check package access on the proxy interfaces that the given proxy class - * implements. - * - * @param clazz Proxy class object - */ - public static void checkProxyPackageAccess(Class<?> clazz) { - SecurityManager s = System.getSecurityManager(); - if (s != null) { - // check proxy interfaces if the given class is a proxy class - if (Proxy.isProxyClass(clazz)) { - for (Class<?> intf : clazz.getInterfaces()) { - checkPackageAccess(intf); - } - } - } - } - - /** - * Access check on the interfaces that a proxy class implements and throw - * {@code SecurityException} if it accesses a restricted package from - * the caller's class loader. - * - * @param ccl the caller's class loader - * @param interfaces the list of interfaces that a proxy class implements - */ - public static void checkProxyPackageAccess(ClassLoader ccl, - Class<?>... interfaces) - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - for (Class<?> intf : interfaces) { - ClassLoader cl = intf.getClassLoader(); - if (needsPackageAccessCheck(ccl, cl)) { - checkPackageAccess(intf); - } - } - } - } - - public static final String PROXY_PACKAGE = "com.sun.proxy"; - - /** - * Test if the given class is a proxy class that implements - * non-public interface. Such proxy class may be in a non-restricted - * package that bypasses checkPackageAccess. - */ - public static boolean isNonPublicProxyClass(Class<?> cls) { - String name = cls.getName(); - int i = name.lastIndexOf('.'); - String pkg = (i != -1) ? name.substring(0, i) : ""; - return Proxy.isProxyClass(cls) && !pkg.equals(PROXY_PACKAGE); - } -} diff --git a/openjdk/sun/security/jgss/wrapper/NativeGSSFactory.java b/openjdk/sun/security/jgss/wrapper/NativeGSSFactory.java deleted file mode 100644 index 08ac04d2..00000000 --- a/openjdk/sun/security/jgss/wrapper/NativeGSSFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.security.jgss.wrapper; - -// this is a compilation stub only -public abstract class NativeGSSFactory implements sun.security.jgss.spi.MechanismFactory -{ - private NativeGSSFactory() { } - /* - public Oid getMechanismOid() - { - throw new UnsupportedOperationException(); - } - - public Provider getProvider() - { - throw new UnsupportedOperationException(); - } - - public Oid[] getNameTypes() - { - throw new UnsupportedOperationException(); - } - - public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) - { - throw new UnsupportedOperationException(); - } - - public GSSNameSpi getNameElement(String nameStr, Oid nameType) - { - throw new UnsupportedOperationException(); - } - - public GSSNameSpi getNameElement(byte[] name, Oid nameType) - { - throw new UnsupportedOperationException(); - } - - public GSSContextSpi getMechanismContext(GSSNameSpi peer, GSSCredentialSpi myInitiatorCred, int lifetime) - { - } - - public GSSContextSpi getMechanismContext(GSSCredentialSpi myAcceptorCred) - { - } - - public GSSContextSpi getMechanismContext(byte[] exportedContext) - { - } -*/ - public abstract void setMech(org.ietf.jgss.Oid mech); -} diff --git a/openjdk/sun/security/jgss/wrapper/SunNativeProvider.java b/openjdk/sun/security/jgss/wrapper/SunNativeProvider.java deleted file mode 100644 index 42e027df..00000000 --- a/openjdk/sun/security/jgss/wrapper/SunNativeProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ - -package sun.security.jgss.wrapper; - -// this is a compilation stub only -public final class SunNativeProvider extends java.security.Provider -{ - public static final SunNativeProvider INSTANCE = new SunNativeProvider(); - - public SunNativeProvider() - { - super(null, 0.0, null); - } - - static void debug(String message) - { - } -} |