Imported GNU Classpath 0.19 + gcj-import-20051115.

* sources.am: Regenerated.
       * Makefile.in: Likewise.
       * scripts/makemake.tcl: Use glob -nocomplain.

From-SVN: r107049
This commit is contained in:
Mark Wielaard
2005-11-15 23:20:01 +00:00
parent 02e549bfaa
commit 8f523f3a10
1241 changed files with 97711 additions and 25284 deletions
+72 -4
View File
@@ -54,6 +54,10 @@ import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleState;
import javax.accessibility.AccessibleStateSet;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* This is the base applet class. An applet is a Java program that
@@ -257,8 +261,6 @@ public class Applet extends Panel
* Returns an audio clip from the specified URL. This clip is not tied to
* any particular applet.
*
* XXX Classpath does not yet implement this.
*
* @param url the URL of the audio clip
* @return the retrieved audio clip
* @throws NullPointerException if url is null
@@ -267,8 +269,7 @@ public class Applet extends Panel
*/
public static final AudioClip newAudioClip(URL url)
{
// This requires an implementation of AudioClip in gnu.java.applet.
throw new Error("Not implemented");
return new URLAudioClip(url);
}
/**
@@ -521,4 +522,71 @@ public class Applet extends Panel
return s;
}
} // class AccessibleApplet
private static class URLAudioClip implements AudioClip
{
// The URL we will try to play.
// This is null if we have already tried to create an
// audio input stream from this URL.
private URL url;
// The real audio clip. This is null before the URL is read,
// and might be null afterward if we were unable to read the URL
// for some reason.
private Clip clip;
public URLAudioClip(URL url)
{
this.url = url;
}
private synchronized Clip getClip()
{
if (url == null)
return clip;
try
{
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(url));
}
catch (LineUnavailableException _)
{
// Ignore.
}
catch (IOException _)
{
// Ignore.
}
catch (UnsupportedAudioFileException _)
{
// Ignore.
}
url = null;
return clip;
}
public void loop()
{
Clip myclip = getClip();
if (myclip != null)
myclip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void play()
{
Clip myclip = getClip();
if (myclip != null)
myclip.start();
}
public void stop()
{
Clip myclip = getClip();
if (myclip != null)
{
myclip.stop();
myclip.setFramePosition(0);
}
}
}
} // class Applet
+120 -10
View File
@@ -38,6 +38,7 @@ exception statement from your version. */
package java.awt;
/**
* This class implements a layout manager that positions components
* in certain sectors of the parent container.
@@ -229,6 +230,12 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
private int vgap;
// Some constants for use with calcSize().
private static final int MIN = 0;
private static final int MAX = 1;
private static final int PREF = 2;
/**
* Initializes a new instance of <code>BorderLayout</code> with no
* horiztonal or vertical gaps between components.
@@ -423,7 +430,7 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
*/
public float getLayoutAlignmentX(Container parent)
{
return(parent.getAlignmentX());
return 0.5F;
}
/**
@@ -438,7 +445,7 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
*/
public float getLayoutAlignmentY(Container parent)
{
return(parent.getAlignmentY());
return 0.5F;
}
/**
@@ -449,7 +456,7 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
*/
public void invalidateLayout(Container parent)
{
// FIXME: Implement this properly!
// Nothing to do here.
}
/**
@@ -560,7 +567,8 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
}
/**
* FIXME: Document me!
* This is a convenience method to set the bounds on a component.
* If the indicated component is null, nothing is done.
*/
private void setBounds(Component comp, int x, int y, int w, int h)
{
@@ -569,12 +577,6 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
comp.setBounds(x, y, w, h);
}
// FIXME: Maybe move to top of file.
// Some constants for use with calcSize().
private static final int MIN = 0;
private static final int MAX = 1;
private static final int PREF = 2;
private Dimension calcCompSize(Component comp, int what)
{
if (comp == null || !comp.isVisible())
@@ -660,4 +662,112 @@ public class BorderLayout implements LayoutManager2, java.io.Serializable
return(new Dimension(width, height));
}
}
/**
* Return the component at the indicated location, or null if no component
* is at that location. The constraints argument must be one of the
* location constants specified by this class.
* @param constraints the location
* @return the component at that location, or null
* @throws IllegalArgumentException if the constraints argument is not
* recognized
* @since 1.5
*/
public Component getLayoutComponent(Object constraints)
{
if (constraints == CENTER)
return center;
if (constraints == NORTH)
return north;
if (constraints == EAST)
return east;
if (constraints == SOUTH)
return south;
if (constraints == WEST)
return west;
if (constraints == PAGE_START)
return firstLine;
if (constraints == PAGE_END)
return lastLine;
if (constraints == LINE_START)
return firstItem;
if (constraints == LINE_END)
return lastItem;
throw new IllegalArgumentException("constraint " + constraints
+ " is not recognized");
}
/**
* Return the component at the specified location, which must be one
* of the absolute constants such as CENTER or SOUTH. The container's
* orientation is used to map this location to the correct corresponding
* component, so for instance in a right-to-left container, a request
* for the EAST component could return the LINE_END component. This will
* return null if no component is available at the given location.
* @param container the container whose orientation is used
* @param constraints the absolute location of the component
* @return the component at the location, or null
* @throws IllegalArgumentException if the constraint is not recognized
*/
public Component getLayoutComponent(Container container, Object constraints)
{
ComponentOrientation orient = container.getComponentOrientation();
if (constraints == CENTER)
return center;
// Note that we don't support vertical layouts.
if (constraints == NORTH)
return north;
if (constraints == SOUTH)
return south;
if (constraints == WEST)
{
// Note that relative layout takes precedence.
if (orient.isLeftToRight())
return firstItem == null ? west : firstItem;
return lastItem == null ? west : lastItem;
}
if (constraints == EAST)
{
// Note that relative layout takes precedence.
if (orient.isLeftToRight())
return lastItem == null ? east : lastItem;
return firstItem == null ? east : firstItem;
}
throw new IllegalArgumentException("constraint " + constraints
+ " is not recognized");
}
/**
* Return the constraint corresponding to a component in this layout.
* If the component is null, or is not in this layout, returns null.
* Otherwise, this will return one of the constraint constants defined
* in this class.
* @param c the component
* @return the constraint, or null
* @since 1.5
*/
public Object getConstraints(Component c)
{
if (c == null)
return null;
if (c == center)
return CENTER;
if (c == north)
return NORTH;
if (c == east)
return EAST;
if (c == south)
return SOUTH;
if (c == west)
return WEST;
if (c == firstLine)
return PAGE_START;
if (c == lastLine)
return PAGE_END;
if (c == firstItem)
return LINE_START;
if (c == lastItem)
return LINE_END;
return null;
}
}
+2
View File
@@ -98,6 +98,8 @@ private transient ActionListener action_listeners;
protected class AccessibleAWTButton extends AccessibleAWTComponent
implements AccessibleAction, AccessibleValue
{
public static final long serialVersionUID = -5932203980244017102L;
protected AccessibleAWTButton()
{
// Do nothing here.
+3 -11
View File
@@ -292,8 +292,8 @@ public class Canvas
*
* @since 1.4
*/
public void createBufferStrategy(int numBuffers,
BufferCapabilities caps)
public void createBufferStrategy(int numBuffers, BufferCapabilities caps)
throws AWTException
{
if (numBuffers < 1)
throw new IllegalArgumentException("Canvas.createBufferStrategy: number"
@@ -305,15 +305,7 @@ public class Canvas
// a flipping strategy was requested
if (caps.isPageFlipping())
{
try
{
bufferStrategy = new CanvasFlipBufferStrategy(numBuffers);
}
catch (AWTException e)
{
}
}
bufferStrategy = new CanvasFlipBufferStrategy(numBuffers);
else
bufferStrategy = new CanvasBltBufferStrategy(numBuffers, true);
}
+9 -2
View File
@@ -392,6 +392,11 @@ Checkbox(String label, boolean state, CheckboxGroup group)
this.label = label;
this.state = state;
this.group = group;
if ( state && group != null )
{
group.setSelectedCheckbox(this);
}
}
/*************************************************************************/
@@ -610,8 +615,10 @@ dispatchEventImpl(AWTEvent e)
protected String
paramString()
{
return ("label=" + label + ",state=" + state + ",group=" + group
+ "," + super.paramString());
// Note: We cannot add the checkbox group information here because this
// would trigger infinite recursion when CheckboxGroup.toString() is
// called and the box is in its selected state.
return ("label=" + label + ",state=" + state + "," + super.paramString());
}
/**
@@ -335,6 +335,8 @@ paramString()
implements AccessibleAction, AccessibleValue
{
// I think the base class provides the necessary implementation
private static final long serialVersionUID = -1122642964303476L;
}
/**
+4
View File
@@ -565,6 +565,10 @@ processEvent(AWTEvent event)
protected void
processItemEvent(ItemEvent event)
{
int index = pItems.indexOf((String) event.getItem());
// Don't call back into the peers when selecting index here
if (event.getStateChange() == ItemEvent.SELECTED)
this.selectedIndex = index;
if (item_listeners != null)
item_listeners.itemStateChanged(event);
}
+1 -1
View File
@@ -762,7 +762,7 @@ public class Color implements Paint, Serializable
if (max == 0)
array[1] = 0;
else
array[1] = (max - min) / max;
array[1] = ((float) (max - min)) / ((float) max);
// Calculate hue.
if (array[1] == 0)
array[0] = 0;
@@ -63,7 +63,7 @@ class ColorPaintContext implements PaintContext
/**
* Create the context for a given color.
*
* @param c The solid color to use.
* @param colorRGB The solid color to use.
*/
ColorPaintContext(int colorRGB)
{
@@ -74,7 +74,7 @@ class ColorPaintContext implements PaintContext
* Create the context for a given color.
*
* @param cm The color model of this context.
* @param c The solid color to use.
* @param colorRGB The solid color to use.
*/
ColorPaintContext(ColorModel cm,int colorRGB)
{
+49 -40
View File
@@ -587,6 +587,7 @@ public abstract class Component
*/
protected Component()
{
// Nothing to do here.
}
/**
@@ -720,8 +721,9 @@ public abstract class Component
/**
* Tests if the component is displayable. It must be connected to a native
* screen resource, and all its ancestors must be displayable. A containment
* hierarchy is made displayable when a window is packed or made visible.
* screen resource. This reduces to checking that peer is not null. A
* containment hierarchy is made displayable when a window is packed or
* made visible.
*
* @return true if the component is displayable
* @see Container#add(Component)
@@ -733,9 +735,7 @@ public abstract class Component
*/
public boolean isDisplayable()
{
if (parent != null)
return parent.isDisplayable();
return false;
return peer != null;
}
/**
@@ -763,7 +763,7 @@ public abstract class Component
if (! visible || peer == null)
return false;
return parent == null ? true : parent.isShowing();
return parent == null ? false : parent.isShowing();
}
/**
@@ -902,15 +902,16 @@ public abstract class Component
if (currentPeer != null)
currentPeer.setVisible(true);
// The JDK repaints the component before invalidating the parent.
// So do we.
if (isShowing())
repaint();
// Invalidate the parent if we have one. The component itself must
// not be invalidated. We also avoid NullPointerException with
// a local reference here.
Container currentParent = parent;
if (currentParent != null)
{
currentParent.invalidate();
currentParent.repaint();
}
currentParent.invalidate();
ComponentEvent ce =
new ComponentEvent(this,ComponentEvent.COMPONENT_SHOWN);
@@ -946,18 +947,19 @@ public abstract class Component
ComponentPeer currentPeer=peer;
if (currentPeer != null)
currentPeer.setVisible(false);
boolean wasShowing = isShowing();
this.visible = false;
// The JDK repaints the component before invalidating the parent.
// So do we.
if (wasShowing)
repaint();
// Invalidate the parent if we have one. The component itself must
// not be invalidated. We also avoid NullPointerException with
// a local reference here.
Container currentParent = parent;
if (currentParent != null)
{
currentParent.invalidate();
currentParent.repaint();
}
currentParent.invalidate();
ComponentEvent ce =
new ComponentEvent(this,ComponentEvent.COMPONENT_HIDDEN);
@@ -976,7 +978,7 @@ public abstract class Component
{
if (foreground != null)
return foreground;
return parent == null ? SystemColor.windowText : parent.getForeground();
return parent == null ? null : parent.getForeground();
}
/**
@@ -1075,8 +1077,9 @@ public abstract class Component
Component p = parent;
if (p != null)
return p.getFont();
else
return new Font("Dialog", Font.PLAIN, 12);
if (peer != null)
return peer.getGraphics().getFont();
return null;
}
/**
@@ -1402,17 +1405,14 @@ public abstract class Component
peer.setBounds (x, y, width, height);
// Erase old bounds and repaint new bounds for lightweights.
if (isLightweight() && isShowing ())
if (isLightweight() && isShowing())
{
if (parent != null)
{
Rectangle parentBounds = parent.getBounds();
Rectangle oldBounds = new Rectangle(parent.getX() + oldx,
parent.getY() + oldy,
oldwidth, oldheight);
Rectangle newBounds = new Rectangle(parent.getX() + x,
parent.getY() + y,
width, height);
Rectangle oldBounds = new Rectangle(oldx, oldy, oldwidth,
oldheight);
Rectangle newBounds = new Rectangle(x, y, width, height);
Rectangle destroyed = oldBounds.union(newBounds);
if (!destroyed.isEmpty())
parent.repaint(0, destroyed.x, destroyed.y, destroyed.width,
@@ -1646,7 +1646,7 @@ public abstract class Component
*/
public Dimension getMaximumSize()
{
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
}
/**
@@ -1720,7 +1720,7 @@ public abstract class Component
valid = false;
prefSize = null;
minSize = null;
if (parent != null && parent.valid)
if (parent != null && parent.isValid())
parent.invalidate();
}
@@ -1736,11 +1736,8 @@ public abstract class Component
if (peer != null)
{
Graphics gfx = peer.getGraphics();
if (gfx != null)
return gfx;
// create graphics for lightweight:
Container parent = getParent();
if (parent != null)
// Create peer for lightweights.
if (gfx == null && parent != null)
{
gfx = parent.getGraphics();
Rectangle bounds = getBounds();
@@ -1748,6 +1745,8 @@ public abstract class Component
gfx.translate(bounds.x, bounds.y);
return gfx;
}
gfx.setFont(font);
return gfx;
}
return null;
}
@@ -1887,7 +1886,7 @@ public abstract class Component
* @see #repaint(long, int, int, int, int)
*/
public void repaint()
{
{
if(!isShowing())
{
Component p = parent;
@@ -3481,7 +3480,10 @@ public abstract class Component
ComponentPeer tmp = peer;
peer = null;
if (tmp != null)
tmp.dispose();
{
tmp.hide();
tmp.dispose();
}
}
/**
@@ -3807,13 +3809,16 @@ public abstract class Component
{
synchronized (getTreeLock ())
{
// Find this Component's top-level ancestor.
Container parent = getParent ();
// Find this Component's top-level ancestor.
Container parent = (this instanceof Container) ? (Container) this
: getParent();
while (parent != null
&& !(parent instanceof Window))
parent = parent.getParent ();
if (parent == null)
return;
Window toplevel = (Window) parent;
if (toplevel.isFocusableWindow ())
{
@@ -4241,9 +4246,9 @@ public abstract class Component
if (isDoubleBuffered())
param.append(",doublebuffered");
if (parent == null)
param.append(",parent==null");
param.append(",parent=null");
else
param.append(",parent==").append(parent.getName());
param.append(",parent=").append(parent.getName());
return param.toString();
}
@@ -5567,6 +5572,7 @@ p * <li>the set of backward traversal keys
*/
protected AccessibleAWTComponentHandler()
{
// Nothing to do here.
}
/**
@@ -5598,6 +5604,7 @@ p * <li>the set of backward traversal keys
*/
public void componentMoved(ComponentEvent e)
{
// Nothing to do here.
}
/**
@@ -5607,6 +5614,7 @@ p * <li>the set of backward traversal keys
*/
public void componentResized(ComponentEvent e)
{
// Nothing to do here.
}
} // class AccessibleAWTComponentHandler
@@ -5624,6 +5632,7 @@ p * <li>the set of backward traversal keys
*/
protected AccessibleAWTFocusHandler()
{
// Nothing to do here.
}
/**
+115 -15
View File
@@ -38,6 +38,7 @@ exception statement from your version. */
package java.awt;
import java.awt.event.ComponentListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.KeyEvent;
@@ -394,17 +395,20 @@ public class Container extends Component
layoutMgr.addLayoutComponent(null, comp);
}
if (isShowing ())
{
// Post event to notify of adding the component.
ContainerEvent ce = new ContainerEvent(this,
ContainerEvent.COMPONENT_ADDED,
comp);
getToolkit().getSystemEventQueue().postEvent(ce);
// We previously only sent an event when this container is showing.
// Also, the event was posted to the event queue. A Mauve test shows
// that this event is not delivered using the event queue and it is
// also sent when the container is not showing.
ContainerEvent ce = new ContainerEvent(this,
ContainerEvent.COMPONENT_ADDED,
comp);
ContainerListener[] listeners = getContainerListeners();
for (int i = 0; i < listeners.length; i++)
listeners[i].componentAdded(ce);
// Repaint this container.
repaint();
}
// Repaint this container.
repaint(comp.getX(), comp.getY(), comp.getWidth(),
comp.getHeight());
}
}
@@ -419,6 +423,10 @@ public class Container extends Component
{
Component r = component[index];
ComponentListener[] list = r.getComponentListeners();
for (int j = 0; j < list.length; j++)
r.removeComponentListener(list[j]);
r.removeNotify();
System.arraycopy(component, index + 1, component, index,
@@ -730,7 +738,16 @@ public class Container extends Component
*/
public float getAlignmentX()
{
return super.getAlignmentX();
LayoutManager layout = getLayout();
float alignmentX = 0.0F;
if (layout != null && layout instanceof LayoutManager2)
{
LayoutManager2 lm2 = (LayoutManager2) layout;
alignmentX = lm2.getLayoutAlignmentX(this);
}
else
alignmentX = super.getAlignmentX();
return alignmentX;
}
/**
@@ -742,7 +759,16 @@ public class Container extends Component
*/
public float getAlignmentY()
{
return super.getAlignmentY();
LayoutManager layout = getLayout();
float alignmentY = 0.0F;
if (layout != null && layout instanceof LayoutManager2)
{
LayoutManager2 lm2 = (LayoutManager2) layout;
alignmentY = lm2.getLayoutAlignmentY(this);
}
else
alignmentY = super.getAlignmentY();
return alignmentY;
}
/**
@@ -1047,6 +1073,53 @@ public class Container extends Component
return this;
}
}
/**
* Finds the visible child component that contains the specified position.
* The top-most child is returned in the case where there is overlap.
* If the top-most child is transparent and has no MouseListeners attached,
* we discard it and return the next top-most component containing the
* specified position.
* @param x the x coordinate
* @param y the y coordinate
* @return null if the <code>this</code> does not contain the position,
* otherwise the top-most component (out of this container itself and
* its descendants) meeting the criteria above.
*/
Component findComponentForMouseEventAt(int x, int y)
{
synchronized (getTreeLock())
{
if (!contains(x, y))
return null;
for (int i = 0; i < ncomponents; ++i)
{
// Ignore invisible children...
if (!component[i].isVisible())
continue;
int x2 = x - component[i].x;
int y2 = y - component[i].y;
// We don't do the contains() check right away because
// findComponentAt would redundantly do it first thing.
if (component[i] instanceof Container)
{
Container k = (Container) component[i];
Component r = k.findComponentForMouseEventAt(x2, y2);
if (r != null)
return r;
}
else if (component[i].contains(x2, y2))
return component[i];
}
//don't return transparent components with no MouseListeners
if (this.getMouseListeners().length == 0)
return null;
return this;
}
}
public Component findComponentAt(Point p)
{
@@ -1955,6 +2028,30 @@ class LightweightDispatcher implements Serializable
eventMask |= l;
}
/**
* Returns the deepest visible descendent of parent that contains the
* specified location and that is not transparent and MouseListener-less.
* @param parent the root component to begin the search
* @param x the x coordinate
* @param y the y coordinate
* @return null if <code>parent</code> doesn't contain the location,
* parent if parent is not a container or has no child that contains the
* location, otherwise the appropriate component from the conditions
* above.
*/
Component getDeepestComponentForMouseEventAt (
Component parent, int x, int y)
{
if (parent == null || (! parent.contains(x, y)))
return null;
if (! (parent instanceof Container))
return parent;
Container c = (Container) parent;
return c.findComponentForMouseEventAt(x, y);
}
Component acquireComponentForMouseEvent(MouseEvent me)
{
int x = me.getX ();
@@ -1968,7 +2065,7 @@ class LightweightDispatcher implements Serializable
while (candidate == null && parent != null)
{
candidate =
AWTUtilities.getDeepestComponentAt(parent, p.x, p.y);
getDeepestComponentForMouseEventAt(parent, p.x, p.y);
if (candidate == null || (candidate.eventMask & me.getID()) == 0)
{
candidate = null;
@@ -2069,7 +2166,10 @@ class LightweightDispatcher implements Serializable
// Don't dispatch CLICKED events whose target is not the same as the
// target for the original PRESSED event.
if (candidate != pressedComponent)
mouseEventTarget = null;
{
mouseEventTarget = null;
pressCount = 0;
}
else if (pressCount == 0)
pressedComponent = null;
}
@@ -2107,7 +2207,7 @@ class LightweightDispatcher implements Serializable
pressedComponent = null;
break;
}
MouseEvent newEvt =
AWTUtilities.convertMouseEvent(nativeContainer, me,
mouseEventTarget);
@@ -146,8 +146,8 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager
*/
private AWTKeyStroke waitForKeyStroke = null;
/** The {@link java.util.SortedSet} of current {@link
#EventDelayRequest}s. */
/** The {@link java.util.SortedSet} of current
* {@link EventDelayRequest}s. */
private SortedSet delayRequests = new TreeSet ();
public DefaultKeyboardFocusManager ()
+2
View File
@@ -519,6 +519,8 @@ paramString()
protected class AccessibleAWTDialog extends AccessibleAWTWindow
{
private static final long serialVersionUID = 4837230331833941201L;
public AccessibleRole getAccessibleRole()
{
return AccessibleRole.DIALOG;
@@ -42,7 +42,6 @@ import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.InputMethodEvent;
import java.awt.event.InvocationEvent;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.EmptyStackException;
File diff suppressed because it is too large Load Diff
@@ -362,6 +362,18 @@ public abstract class FontMetrics implements java.io.Serializable
rc = gRC;
return font.getLineMetrics(chars, begin, limit, rc);
}
/**
* Returns the bounds of the largest character in a Graphics context.
* @param context the Graphics context object.
* @return a <code>Rectangle2D</code> representing the bounds
*/
public Rectangle2D getMaxCharBounds(Graphics context)
{
if( context instanceof Graphics2D )
return font.getMaxCharBounds(((Graphics2D)context).getFontRenderContext());
return font.getMaxCharBounds( gRC );
}
/**
* Returns a {@link LineMetrics} object constructed with the
@@ -424,4 +436,13 @@ public abstract class FontMetrics implements java.io.Serializable
return gRC;
}
/**
* Returns if the font has uniform line metrics.
* @see Font#hasUniformLineMetrics()
*/
public boolean hasUniformLineMetrics()
{
return font.hasUniformLineMetrics();
}
}
+2
View File
@@ -591,6 +591,8 @@ public static Frame[] getFrames()
protected class AccessibleAWTFrame extends AccessibleAWTWindow
{
private static final long serialVersionUID = -6172960752956030250L;
public AccessibleRole getAccessibleRole()
{
return AccessibleRole.FRAME;
File diff suppressed because it is too large Load Diff
@@ -130,11 +130,10 @@ public abstract class GraphicsConfiguration
* with the given transparency. Because the buffer is volatile, it
* can be optimized by native graphics accelerators.
*
* @param w the width of the buffer
* @param h the height of the buffer
* @param width the width of the buffer
* @param height the height of the buffer
* @param transparency the transparency value for the buffer
* @return the buffered image, or null if none is supported
* @throws AWTException if the capabilities cannot be met
* @since 1.5
*/
public abstract VolatileImage createCompatibleVolatileImage(int width,
+13 -10
View File
@@ -705,17 +705,20 @@ public class GridBagLayout
if (lastInCol.containsKey(new Integer(x)))
{
Component lastComponent = (Component) lastInRow.get(new Integer(x));
GridBagConstraints lastConstraints = lookupInternalConstraints(lastComponent);
if (lastConstraints.gridheight == GridBagConstraints.RELATIVE)
if (lastComponent != null)
{
constraints.gridy = max_y - 1;
break;
}
else
{
constraints.gridy = Math.max (constraints.gridy,
lastConstraints.gridy + Math.max (1, lastConstraints.gridheight));
GridBagConstraints lastConstraints = lookupInternalConstraints(lastComponent);
if (lastConstraints.gridheight == GridBagConstraints.RELATIVE)
{
constraints.gridy = max_y - 1;
break;
}
else
{
constraints.gridy = Math.max (constraints.gridy,
lastConstraints.gridy + Math.max (1, lastConstraints.gridheight));
}
}
}
}
+13 -7
View File
@@ -38,7 +38,9 @@ exception statement from your version. */
package java.awt;
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.ReplicateScaleFilter;
@@ -141,7 +143,6 @@ public abstract class Image
* This method is only valid for off-screen objects.
*
* @return a graphics context object for an off-screen object
* @see Graphics#getcreateImage(int, int)
*/
public abstract Graphics getGraphics();
@@ -179,20 +180,25 @@ public abstract class Image
*/
public Image getScaledInstance(int width, int height, int flags)
{
ImageFilter filter;
switch (flags)
{
case SCALE_DEFAULT:
case SCALE_FAST:
case SCALE_REPLICATE:
ImageProducer producer =
new FilteredImageSource(this.getSource(),
new ReplicateScaleFilter(width, height));
return Toolkit.getDefaultToolkit().createImage(producer);
case SCALE_SMOOTH:
filter = new ReplicateScaleFilter(width, height);
break;
case SCALE_AREA_AVERAGING:
filter = new AreaAveragingScaleFilter(width, height);
break;
case SCALE_SMOOTH:
throw new Error("SCALE_SMOOTH: not implemented");
default:
throw new Error("not implemented");
throw new Error("Unknown flag or not implemented: " + flags);
}
ImageProducer producer = new FilteredImageSource(getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(producer);
}
/**
@@ -39,6 +39,7 @@ exception statement from your version. */
package java.awt;
import java.applet.Applet;
import java.awt.FocusTraversalPolicy;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
@@ -213,7 +214,7 @@ public abstract class KeyboardFocusManager
currentFocusOwners */
private static Map currentFocusCycleRoots = new HashMap ();
/** The default {@link FocusTraveralPolicy} that focus-managing
/** The default {@link FocusTraversalPolicy} that focus-managing
{@link Container}s will use to define their initial focus
traversal policy. */
private FocusTraversalPolicy defaultPolicy;
@@ -287,53 +288,13 @@ public abstract class KeyboardFocusManager
KeyboardFocusManager manager;
if (m == null)
manager = createFocusManager();
manager = new DefaultKeyboardFocusManager();
else
manager = m;
currentKeyboardFocusManagers.put (currentGroup, manager);
}
/**
* Creates a KeyboardFocusManager. The exact class is determined by the
* system property 'gnu.java.awt.FocusManager'. If this is not set,
* we default to DefaultKeyboardFocusManager.
*/
private static KeyboardFocusManager createFocusManager()
{
String fmClassName = System.getProperty("gnu.java.awt.FocusManager",
"java.awt.DefaultKeyboardFocusManager");
try
{
Class fmClass = Class.forName(fmClassName);
KeyboardFocusManager fm = (KeyboardFocusManager) fmClass.newInstance();
return fm;
}
catch (ClassNotFoundException ex)
{
System.err.println("The class " + fmClassName + " cannot be found.");
System.err.println("Check the setting of the system property");
System.err.println("gnu.java.awt.FocusManager");
return null;
}
catch (InstantiationException ex)
{
System.err.println("The class " + fmClassName + " cannot be");
System.err.println("instantiated.");
System.err.println("Check the setting of the system property");
System.err.println("gnu.java.awt.FocusManager");
return null;
}
catch (IllegalAccessException ex)
{
System.err.println("The class " + fmClassName + " cannot be");
System.err.println("accessed.");
System.err.println("Check the setting of the system property");
System.err.println("gnu.java.awt.FocusManager");
return null;
}
}
/**
* Retrieve the {@link Component} that has the keyboard focus, or
* null if the focus owner was not set by a thread in the current
@@ -1364,11 +1325,11 @@ public abstract class KeyboardFocusManager
*
* @return a global object set by the current ThreadGroup, or null
*
* @see getFocusOwner
* @see getPermanentFocusOwner
* @see getFocusedWindow
* @see getActiveWindow
* @see getCurrentFocusCycleRoot
* @see #getFocusOwner()
* @see #getPermanentFocusOwner()
* @see #getFocusedWindow()
* @see #getActiveWindow()
* @see #getCurrentFocusCycleRoot()
*/
private Object getObject (Map globalMap)
{
@@ -1388,11 +1349,11 @@ public abstract class KeyboardFocusManager
* @throws SecurityException if this is not the keyboard focus
* manager associated with the current {@link java.lang.ThreadGroup}
*
* @see getGlobalFocusOwner
* @see getGlobalPermanentFocusOwner
* @see getGlobalFocusedWindow
* @see getGlobalActiveWindow
* @see getGlobalCurrentFocusCycleRoot
* @see #getGlobalFocusOwner()
* @see #getGlobalPermanentFocusOwner()
* @see #getGlobalFocusedWindow()
* @see #getGlobalActiveWindow()
* @see #getGlobalCurrentFocusCycleRoot()
*/
private Object getGlobalObject (Map globalMap)
{
@@ -1432,11 +1393,11 @@ public abstract class KeyboardFocusManager
* @param newObject the object to set
* @param property the property that will change
*
* @see setGlobalFocusOwner
* @see setGlobalPermanentFocusOwner
* @see setGlobalFocusedWindow
* @see setGlobalActiveWindow
* @see setGlobalCurrentFocusCycleRoot
* @see #setGlobalFocusOwner(Component)
* @see #setGlobalPermanentFocusOwner(Component)
* @see #setGlobalFocusedWindow(Window)
* @see #setGlobalActiveWindow(Window)
* @see #setGlobalCurrentFocusCycleRoot(Container)
*/
private void setGlobalObject (Map globalMap,
Object newObject,
+10 -5
View File
@@ -1088,18 +1088,23 @@ paramString()
protected class AccessibleAWTList extends AccessibleAWTComponent
implements AccessibleSelection, ItemListener, ActionListener
{
private static final long serialVersionUID = 7924617370136012829L;
protected class AccessibleAWTListChild extends AccessibleAWTComponent
implements Accessible
{
private int index;
private static final long serialVersionUID = 4412022926028300317L;
// Field names are fixed by serialization spec.
private List parent;
private int indexInParent;
public AccessibleAWTListChild(List parent, int indexInParent)
{
this.parent = parent;
index = indexInParent;
this.indexInParent = indexInParent;
if (parent == null)
index = -1;
this.indexInParent = -1;
}
/* (non-Javadoc)
@@ -1118,14 +1123,14 @@ paramString()
public AccessibleStateSet getAccessibleStateSet()
{
AccessibleStateSet states = super.getAccessibleStateSet();
if (parent.isIndexSelected(index))
if (parent.isIndexSelected(indexInParent))
states.add(AccessibleState.SELECTED);
return states;
}
public int getAccessibleIndexInParent()
{
return index;
return indexInParent;
}
}
+2
View File
@@ -441,6 +441,8 @@ paramString()
*/
protected class AccessibleAWTMenu extends AccessibleAWTMenuItem
{
private static final long serialVersionUID = 5228160894980069094L;
protected AccessibleAWTMenu()
{
}
@@ -1157,7 +1157,7 @@ protected abstract class AccessibleAWTMenuComponent
* the appropriate information.
*
* @param color the new color to use for the background.
* @see getBackground()
* @see #getBackground()
*/
public void setBackground(Color color)
{
@@ -1217,7 +1217,7 @@ protected abstract class AccessibleAWTMenuComponent
*
* @param enabled true if the component should be enabled,
* false otherwise.
* @see #getEnabled()
* @see #isEnabled()
*/
public void setEnabled(boolean enabled)
{
+2
View File
@@ -108,6 +108,8 @@ private transient ActionListener action_listeners;
extends MenuComponent.AccessibleAWTMenuComponent
implements AccessibleAction, AccessibleValue
{
private static final long serialVersionUID = -217847831945965825L;
/** Constructor */
public AccessibleAWTMenuItem()
{
+4
View File
@@ -226,6 +226,10 @@ public class Point extends Point2D implements Serializable
*/
public boolean equals(Object obj)
{
// NOTE: No special hashCode() method is required for this class,
// as this equals() implementation is functionally equivalent to
// super.equals(), which does define a proper hashCode().
if (! (obj instanceof Point2D))
return false;
Point2D p = (Point2D) obj;
-1
View File
@@ -544,7 +544,6 @@ public class Polygon implements Shape, Serializable
* the positive X, or Y axis, within a given interval.
*
* @return the winding number.
* @see #condensed
* @see #contains(double, double)
*/
private int evaluateCrossings(double x, double y, boolean useYaxis,
@@ -140,6 +140,8 @@ show(Component component, int x, int y)
protected class AccessibleAWTPopupMenu extends AccessibleAWTMenu
{
private static final long serialVersionUID = -4282044795947239955L;
protected AccessibleAWTPopupMenu()
{
}
@@ -727,6 +727,10 @@ public class Rectangle extends Rectangle2D implements Shape, Serializable
*/
public boolean equals(Object obj)
{
// NOTE: No special hashCode() method is required for this class,
// as this equals() implementation is functionally equivalent to
// super.equals(), which does define a proper hashCode().
if (! (obj instanceof Rectangle2D))
return false;
Rectangle2D r = (Rectangle2D) obj;
+3 -1
View File
@@ -401,7 +401,7 @@ setScrollPosition(int x, int y)
public void
addNotify()
{
if (!isDisplayable ())
if (peer != null)
return;
setPeer((ComponentPeer)getToolkit().createScrollPane(this));
@@ -592,6 +592,8 @@ paramString()
protected class AccessibleAWTScrollPane extends AccessibleAWTContainer
{
private static final long serialVersionUID = 6100703663886637L;
public AccessibleRole getAccessibleRole()
{
return AccessibleRole.SCROLL_PANE;
@@ -87,12 +87,16 @@ public class ScrollPaneAdjustable
public void addAdjustmentListener (AdjustmentListener listener)
{
AWTEventMulticaster.add (adjustmentListener, listener);
if (listener == null)
return;
adjustmentListener = AWTEventMulticaster.add (adjustmentListener, listener);
}
public void removeAdjustmentListener (AdjustmentListener listener)
{
AWTEventMulticaster.remove (adjustmentListener, listener);
if (listener == null)
return;
adjustmentListener = AWTEventMulticaster.remove (adjustmentListener, listener);
}
public AdjustmentListener[] getAdjustmentListeners ()
+2
View File
@@ -603,6 +603,8 @@ public class TextArea extends TextComponent implements java.io.Serializable
protected class AccessibleAWTTextArea extends AccessibleAWTTextComponent
{
private static final long serialVersionUID = 3472827823632144419L;
protected AccessibleAWTTextArea()
{
}
@@ -107,6 +107,8 @@ protected transient TextListener textListener;
extends AccessibleAWTComponent
implements AccessibleText, TextListener
{
private static final long serialVersionUID = 3631432373506317811L;
// Constructor
// Adds a listener for tracking caret changes
public AccessibleAWTTextComponent()
@@ -523,6 +523,8 @@ paramString()
protected class AccessibleAWTTextField extends AccessibleAWTTextComponent
{
private static final long serialVersionUID = 6219164359235943158L;
protected AccessibleAWTTextField()
{
}
+79 -31
View File
@@ -101,6 +101,8 @@ public class Window extends Container implements Accessible
protected class AccessibleAWTWindow extends AccessibleAWTContainer
{
private static final long serialVersionUID = 4215068635060671780L;
public AccessibleRole getAccessibleRole()
{
return AccessibleRole.WINDOW;
@@ -278,14 +280,14 @@ public class Window extends Container implements Accessible
*/
public void show()
{
synchronized (getTreeLock())
{
if (parent != null && !parent.isDisplayable())
parent.addNotify();
if (peer == null)
addNotify();
// Show visible owned windows.
synchronized (getTreeLock())
{
Iterator e = ownedWindows.iterator();
while(e.hasNext())
{
@@ -302,14 +304,13 @@ public class Window extends Container implements Accessible
// synchronous access to ownedWindows there.
e.remove();
}
}
validate();
super.show();
toFront();
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager ();
manager.setGlobalFocusedWindow (this);
if (!shown)
{
FocusTraversalPolicy policy = getFocusTraversalPolicy ();
@@ -323,6 +324,7 @@ public class Window extends Container implements Accessible
shown = true;
}
}
}
public void hide()
@@ -346,13 +348,6 @@ public class Window extends Container implements Accessible
super.hide();
}
public boolean isDisplayable()
{
if (super.isDisplayable())
return true;
return peer != null;
}
/**
* Destroys any resources associated with this window. This includes
* all components in the window and all owned top-level windows.
@@ -808,20 +803,81 @@ public class Window extends Container implements Accessible
return isVisible();
}
public void setLocationRelativeTo (Component c)
public void setLocationRelativeTo(Component c)
{
if (c == null || !c.isShowing ())
int x = 0;
int y = 0;
if (c == null || !c.isShowing())
{
int x = 0;
int y = 0;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment ();
Point center = ge.getCenterPoint ();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Point center = ge.getCenterPoint();
x = center.x - (width / 2);
y = center.y - (height / 2);
setLocation (x, y);
}
// FIXME: handle case where component is non-null.
else
{
int cWidth = c.getWidth();
int cHeight = c.getHeight();
Dimension screenSize = getToolkit().getScreenSize();
x = c.getLocationOnScreen().x;
y = c.getLocationOnScreen().y;
// If bottom of component is cut off, window placed
// on the left or the right side of component
if ((y + cHeight) > screenSize.height)
{
// If the right side of the component is closer to the center
if ((screenSize.width / 2 - x) <= 0)
{
if ((x - width) >= 0)
x -= width;
else
x = 0;
}
else
{
if ((x + cWidth + width) <= screenSize.width)
x += cWidth;
else
x = screenSize.width - width;
}
y = screenSize.height - height;
}
else if (cWidth > width || cHeight > height)
{
// If right side of component is cut off
if ((x + width) > screenSize.width)
x = screenSize.width - width;
// If left side of component is cut off
else if (x < 0)
x = 0;
else
x += (cWidth - width) / 2;
y += (cHeight - height) / 2;
}
else
{
// If right side of component is cut off
if ((x + width) > screenSize.width)
x = screenSize.width - width;
// If left side of component is cut off
else if (x < 0 || (x - (width - cWidth) / 2) < 0)
x = 0;
else
x -= (width - cWidth) / 2;
if ((y - (height - cHeight) / 2) > 0)
y -= (height - cHeight) / 2;
else
y = 0;
}
}
setLocation(x, y);
}
/**
@@ -938,8 +994,8 @@ public class Window extends Container implements Accessible
*
* @since 1.4
*/
public void createBufferStrategy(int numBuffers,
BufferCapabilities caps)
public void createBufferStrategy(int numBuffers, BufferCapabilities caps)
throws AWTException
{
if (numBuffers < 1)
throw new IllegalArgumentException("Window.createBufferStrategy: number"
@@ -951,15 +1007,7 @@ public class Window extends Container implements Accessible
// a flipping strategy was requested
if (caps.isPageFlipping())
{
try
{
bufferStrategy = new WindowFlipBufferStrategy(numBuffers);
}
catch (AWTException e)
{
}
}
bufferStrategy = new WindowFlipBufferStrategy(numBuffers);
else
bufferStrategy = new WindowBltBufferStrategy(numBuffers, true);
}
@@ -324,11 +324,11 @@ public class ICC_Profile implements Serializable
* An instance of the specialized classes ICC_ProfileRGB or ICC_ProfileGray
* may be returned if appropriate.
*
* @throws IllegalArgumentException if the profile data is an invalid
* v2 profile.
*
* @param data - the profile data
* @return An ICC_Profile object
*
* @throws IllegalArgumentException if the profile data is an invalid
* v2 profile.
*/
public static ICC_Profile getInstance(byte[] data)
{
@@ -373,12 +373,12 @@ public class ICC_Profile implements Serializable
* An instance of the specialized classes ICC_ProfileRGB or ICC_ProfileGray
* may be returned if appropriate.
*
* @param filename - the file name of the profile file.
* @return An ICC_Profile object
*
* @throws IllegalArgumentException if the profile data is an invalid
* v2 profile.
* @throws IOException if the file could not be read.
*
* @param filename - the file name of the profile file.
* @return An ICC_Profile object
*/
public static ICC_Profile getInstance(String filename)
throws IOException
@@ -400,12 +400,12 @@ public class ICC_Profile implements Serializable
* An instance of the specialized classes ICC_ProfileRGB or ICC_ProfileGray
* may be returned if appropriate.
*
* @param in - the input stream to read the profile from.
* @return An ICC_Profile object
*
* @throws IllegalArgumentException if the profile data is an invalid
* v2 profile.
* @throws IOException if the stream could not be read.
*
* @param in - the input stream to read the profile from.
* @return An ICC_Profile object
*/
public static ICC_Profile getInstance(InputStream in)
throws IOException
@@ -197,16 +197,27 @@ public abstract class InputEvent extends ComponentEvent
private final long when;
/**
* The modifiers in effect for this event. Package visible for use by
* subclasses. The old style (bitmask 0x3f) should not be mixed with the
* new style (bitmasks 0xffffffc0).
* The old-style modifiers in effect for this event. Package visible
* for use by subclasses. The old style (bitmask 0x3f) should not be
* mixed with the new style (bitmasks 0xffffffc0).
*
* @see #getModifiers()
* @see MouseEvent
* @serial the modifier state, stored in the new style
* @serial the modifier state, stored in the old style
*/
int modifiers;
/**
* The new-style modifiers in effect for this event. Package visible
* for use by subclasses. The old style (bitmask 0x3f) should not be
* mixed with the new style (bitmasks 0xffffffc0).
*
* @see #getModifiersEx()
* @see MouseEvent
* @serial the modifier state, stored in the new style
*/
int modifiersEx;
/**
* Initializes a new instance of <code>InputEvent</code> with the specified
* source, id, timestamp, and modifiers. Note that an invalid id leads to
@@ -222,7 +233,8 @@ public abstract class InputEvent extends ComponentEvent
{
super(source, id);
this.when = when;
this.modifiers = EventModifier.extend(modifiers);
this.modifiers = modifiers & EventModifier.OLD_MASK;
this.modifiersEx = modifiers & EventModifier.NEW_MASK;
}
/**
@@ -232,7 +244,8 @@ public abstract class InputEvent extends ComponentEvent
*/
public boolean isShiftDown()
{
return (modifiers & SHIFT_DOWN_MASK) != 0;
return ((modifiers & SHIFT_MASK) != 0)
|| ((modifiersEx & SHIFT_DOWN_MASK) != 0);
}
/**
@@ -243,7 +256,8 @@ public abstract class InputEvent extends ComponentEvent
*/
public boolean isControlDown()
{
return (modifiers & CTRL_DOWN_MASK) != 0;
return ((modifiers & CTRL_MASK) != 0)
|| ((modifiersEx & CTRL_DOWN_MASK) != 0);
}
/**
@@ -253,7 +267,8 @@ public abstract class InputEvent extends ComponentEvent
*/
public boolean isMetaDown()
{
return (modifiers & META_DOWN_MASK) != 0;
return ((modifiers & META_MASK) != 0)
|| ((modifiersEx & META_DOWN_MASK) != 0);
}
/**
@@ -263,7 +278,8 @@ public abstract class InputEvent extends ComponentEvent
*/
public boolean isAltDown()
{
return (modifiers & ALT_DOWN_MASK) != 0;
return ((modifiers & ALT_MASK) != 0)
|| ((modifiersEx & ALT_DOWN_MASK) != 0);
}
/**
@@ -274,7 +290,8 @@ public abstract class InputEvent extends ComponentEvent
*/
public boolean isAltGraphDown()
{
return (modifiers & ALT_GRAPH_DOWN_MASK) != 0;
return ((modifiers & ALT_GRAPH_MASK) != 0)
|| ((modifiersEx & ALT_GRAPH_DOWN_MASK) != 0);
}
/**
@@ -300,7 +317,7 @@ public abstract class InputEvent extends ComponentEvent
*/
public int getModifiers()
{
return EventModifier.revert(modifiers);
return modifiers;
}
/**
@@ -321,7 +338,7 @@ public abstract class InputEvent extends ComponentEvent
*/
public int getModifiersEx()
{
return modifiers;
return modifiersEx;
}
/**
@@ -106,6 +106,13 @@ public class InvocationEvent extends AWTEvent implements ActiveEvent
*/
private Exception exception;
/**
* This is the caught Throwable thrown in the <code>run()</code> method.
* It is null if throwables are ignored, the run method hasn't completed,
* or there were no throwables thrown.
*/
private Throwable throwable;
/**
* The timestamp when this event was created.
*
@@ -183,9 +190,11 @@ public class InvocationEvent extends AWTEvent implements ActiveEvent
{
runnable.run();
}
catch (Exception e)
catch (Throwable t)
{
exception = e;
throwable = t;
if (t instanceof Exception)
exception = (Exception)t;
}
else
runnable.run();
@@ -210,6 +219,18 @@ public class InvocationEvent extends AWTEvent implements ActiveEvent
return exception;
}
/**
* Returns a throwable caught while executing the Runnable's run() method.
* Null if none was thrown or if this InvocationEvent doesn't catch
* throwables.
* @return the caught Throwable
* @since 1.5
*/
public Throwable getThrowable()
{
return throwable;
}
/**
* Gets the timestamp of when this event was created.
*
@@ -1735,6 +1735,6 @@ public class KeyEvent extends InputEvent
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
modifiers = EventModifier.extend(modifiers);
modifiersEx = EventModifier.extend(modifiers) & EventModifier.NEW_MASK;
}
} // class KeyEvent
@@ -42,6 +42,7 @@ import gnu.java.awt.EventModifier;
import java.awt.Component;
import java.awt.Point;
import java.awt.PopupMenu;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -227,6 +228,12 @@ public class MouseEvent extends InputEvent
else if ((modifiers & BUTTON3_MASK) != 0)
this.button = BUTTON3;
}
// clear the mouse button modifier masks if this is a button
// release event.
if (id == MOUSE_RELEASED)
this.modifiersEx &= ~(BUTTON1_DOWN_MASK
| BUTTON2_DOWN_MASK
| BUTTON3_DOWN_MASK);
}
/**
@@ -392,17 +399,9 @@ public class MouseEvent extends InputEvent
s.append("unknown type,(");
}
s.append(x).append(',').append(y).append("),button=").append(button);
if ((modifiers & EventModifier.NEW_MASK) != 0)
{
int mod = modifiers;
if ((mod & (ALT_DOWN_MASK | BUTTON2_DOWN_MASK)) != 0)
mod |= ALT_DOWN_MASK | BUTTON2_DOWN_MASK;
if ((mod & (META_DOWN_MASK | BUTTON3_DOWN_MASK)) != 0)
mod |= META_DOWN_MASK | BUTTON3_DOWN_MASK;
s.append(",modifiers=").append(getModifiersExText(mod));
}
if (modifiers != 0)
s.append(",extModifiers=").append(getModifiersExText(modifiers));
// FIXME: need a mauve test for this method
if (modifiersEx != 0)
s.append(",extModifiers=").append(getModifiersExText(modifiersEx));
return s.append(",clickCount=").append(clickCount).toString();
}
@@ -426,7 +425,7 @@ public class MouseEvent extends InputEvent
button = BUTTON2;
else if ((modifiers & BUTTON3_MASK) != 0)
button = BUTTON3;
modifiers = EventModifier.extend(modifiers);
modifiersEx = EventModifier.extend(modifiers) & EventModifier.NEW_MASK;
}
}
} // class MouseEvent
+1 -1
View File
@@ -1215,7 +1215,7 @@ public class Area implements Shape, Cloneable
* @param t1 - global parametric value of the first curve's starting point
* @param t2 - global parametric value of the second curve's starting point
* @param w1 - global parametric length of curve 1
* @param c1 - global parametric length of curve 2
* @param w2 - global parametric length of curve 2
*
* The final four parameters are for keeping track of the parametric
* value of the curve. For a full curve t = 0, w = 1, w is halved with
@@ -558,7 +558,8 @@ public final class GeneralPath implements Shape, Cloneable
* Constructs a new iterator for enumerating the segments of a
* GeneralPath.
*
* @param at an affine transformation for projecting the returned
* @param path the path to enumerate
* @param transform an affine transformation for projecting the returned
* points, or <code>null</code> to return the original points
* without any mapping.
*/
@@ -49,6 +49,7 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
@@ -334,7 +335,7 @@ public class InputContext
/**
* Starts a reconversion operation in the current input method. The input
* method gets theh text to reconvert from the client component, using
* method gets the text to reconvert from the client component, using
* {@link InputMethodRequests#getSelectedText(Attribute[])}. Then the
* composed and committed text produced by the operation is sent back to
* the client using a sequence of InputMethodRequests.
@@ -37,6 +37,9 @@ exception statement from your version. */
package java.awt.im;
import java.awt.Toolkit;
import java.text.Annotation;
import java.text.AttributedCharacterIterator;
import java.util.Map;
/**
@@ -53,7 +56,7 @@ import java.util.Map;
* text segments.
*
* @author Eric Blake (ebb9@email.byu.edu)
* @see AttributedCharacterIterators
* @see AttributedCharacterIterator
* @see Annotation
* @since 1.2
* @status updated to 1.4
@@ -37,8 +37,10 @@ exception statement from your version. */
package java.awt.im;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.font.TextHitInfo;
import java.awt.event.InputMethodListener;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
@@ -38,7 +38,11 @@ exception statement from your version. */
package java.awt.im.spi;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.im.InputContext;
import java.awt.im.InputMethodRequests;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.Locale;
/**
@@ -152,8 +156,8 @@ public interface InputMethod
* Notify this input method of changes in the client window. This is called
* when notifications are enabled (see {@link
* InputMethodContext#enableClientWindowNotification(InputMethod, boolean)},
* if {@link #removeNotify(Component)} has not been called. The following
* situations trigger a notification:<ul>
* if {@link InputContext#removeNotify(Component)} has not been called.
* The following situations trigger a notification:<ul>
* <li>The client window changes in location, size, visibility,
* iconification, or is closed.</li>
* <li>When enabling client notification (or on the first activation after
@@ -202,7 +206,7 @@ public interface InputMethod
/**
* Notify the input method that a client component has been removed from its
* hierarchy, or that input method support has been disabled. This is
* called by {@link InputContext#removeNotify()}, and only when the input
* called by {@link InputContext#removeNotify(Component)}, and only when the input
* method is inactive.
*/
void removeNotify();
@@ -38,6 +38,8 @@ exception statement from your version. */
package java.awt.im.spi;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodRequests;
@@ -113,7 +115,7 @@ public interface InputMethodContext extends InputMethodRequests
/**
* Sets whether notification of the client window's location and state should
* be enabled for the input method. When enabled, the input method's
* {@link #notifyClientWindowChange(Rectangle)} method is called.
* {@link InputMethod#notifyClientWindowChange(Rectangle)} method is called.
* Notification is automatically disabled when the input method is disposed.
*
* @param inputMethod the method to change status of
@@ -39,6 +39,7 @@ package java.awt.im.spi;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.im.InputContext;
import java.util.Locale;
/**
@@ -57,7 +58,7 @@ public interface InputMethodDescriptor
* also by country and variant), via
* {@link InputContext#selectInputMethod(Locale)}. The returned list should
* ignore pass-through locales, so it is usually a subset of locales for
* which {@link InputMethod#setContext(Locale)} returns true. If
* which {@link InputMethod#setLocale(Locale)} returns true. If
* {@link #hasDynamicLocaleList()} returns true, this is called each time
* information is needed, allowing dynamic addition or removal of supported
* locales.
@@ -45,7 +45,7 @@ package java.awt.image;
* points should give the desired results although Sun does not
* specify what the exact algorithm should be.
* <br>
* Currently this filter does nothing and needs to be implemented.
* FIXME: Currently this filter does nothing and needs to be implemented.
*
* @author C. Brian Jones (cbj@gnu.org)
*/
@@ -1,5 +1,5 @@
/* BufferedImage.java --
Copyright (C) 2000, 2002, 2003, 2004 Free Software Foundation
Copyright (C) 2000, 2002, 2003, 2004, 2005 Free Software Foundation
This file is part of GNU Classpath.
@@ -48,9 +48,7 @@ import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
/**
@@ -64,7 +62,7 @@ import java.util.Vector;
* @author Rolf W. Rasmussen (rolfwr@ii.uib.no)
*/
public class BufferedImage extends Image
implements WritableRenderedImage
implements WritableRenderedImage, Transparency
{
public static final int TYPE_CUSTOM = 0,
TYPE_INT_RGB = 1,
@@ -690,4 +688,16 @@ public class BufferedImage extends Image
observers.remove (to);
}
/**
* Return the transparency type.
*
* @return One of {@link #OPAQUE}, {@link #BITMASK}, or {@link #TRANSLUCENT}.
* @see Transparency#getTransparency()
* @since 1.5
*/
public int getTransparency()
{
return colorModel.getTransparency();
}
}
@@ -609,7 +609,7 @@ public abstract class ColorModel implements Transparency
* @param obj Array of TransferType or null.
*
* @return pixel value encoded according to the color model.
* @throws ArrayIndexOutOfBounds
* @throws ArrayIndexOutOfBoundsException
* @throws ClassCastException
* @since 1.4
*/
@@ -63,8 +63,11 @@ public class ComponentSampleModel extends SampleModel
protected int[] bandOffsets;
protected int[] bankIndices;
// FIXME: Should we really shadow the numBands in the superclass?
//protected int numBands;
/**
* Number of bands in the image described.
* @specnote This field shadows the protected numBands in SampleModel.
*/
protected int numBands;
/** Used when creating data buffers. */
protected int numBanks;
@@ -100,6 +103,7 @@ public class ComponentSampleModel extends SampleModel
this.bandOffsets = bandOffsets;
this.bankIndices = bankIndices;
this.numBands = bandOffsets.length;
this.numBanks = 0;
for (int b=0; b<bankIndices.length; b++)
@@ -75,7 +75,7 @@ public interface ImageConsumer
* most one call to <code>setPixels</code> for any single pixel.
*
* @see #setHints
* @see #setPixels
* @see #setPixels(int, int, int, int, ColorModel, int[], int, int)
*/
int SINGLEPASS = 8;
@@ -90,11 +90,7 @@ public abstract class PackedColorModel extends ColorModel
return bitsPerComponent;
}
/** Initializes the masks.
*
* @return an array containing the number of bits per color
* component.
*/
/** Initializes the masks. */
private void initMasks(int[] colorMaskArray, int alphaMask)
{
int numComponents = colorMaskArray.length;
@@ -47,7 +47,8 @@ public abstract class SampleModel
/** Height of image described. */
protected int height;
/** Number of bands in the image described. */
/** Number of bands in the image described. Package-private here,
shadowed by ComponentSampleModel. */
protected int numBands;
/**
@@ -169,8 +169,11 @@ public abstract class PrinterJob
/**
* Prints the page with given attributes.
*/
public abstract void print (PrintRequestAttributeSet attributes)
throws PrinterException;
public void print (PrintRequestAttributeSet attributes)
throws PrinterException
{
print ();
}
/**
* Displays a dialog box to the user which allows the print job
@@ -1,4 +1,4 @@
/* java.beans.IndexedPropertyDescriptor
/* IndexedPropertyDescriptor.java --
Copyright (C) 1998, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -42,266 +42,380 @@ import java.lang.reflect.Array;
import java.lang.reflect.Method;
/**
** IndexedPropertyDescriptor describes information about a JavaBean
** indexed property, by which we mean an array-like property that
** has been exposed via a pair of get and set methods and another
** pair that allows you to get to the property by an index.<P>
**
** An example property would have four methods like this:<P>
** <CODE>FooBar[] getFoo()</CODE><BR>
** <CODE>void setFoo(FooBar[])</CODE><BR>
** <CODE>FooBar getFoo(int)</CODE><BR>
** <CODE>void setFoo(int,FooBar)</CODE><P>
**
** The constraints put on get and set methods are:<P>
** <OL>
** <LI>There must be at least a get(int) or a set(int,...) method.
** Nothing else is required. <B>Spec note:</B>One nice restriction
** would be that if there is a get() there must be a get(int), same
** with set, but that is not in the spec and is fairly harmless.)</LI>
** <LI>A get array method must have signature
** <CODE>&lt;propertyType&gt;[] &lt;getMethodName&gt;()</CODE></LI>
** <LI>A set array method must have signature
** <CODE>void &lt;setMethodName&gt;(&lt;propertyType&gt;[])</CODE></LI>
** <LI>A get index method must have signature
** <CODE>&lt;propertyType&gt; &lt;getMethodName&gt;(int)</CODE></LI>
** <LI>A set index method must have signature
** <CODE>void &lt;setMethodName&gt;(int,&lt;propertyType&gt;)</CODE></LI>
** <LI>All these methods may throw any exception.</LI>
** <LI>All these methods must be public.</LI>
** </OL>
**
** @author John Keiser
** @since JDK1.1
** @version 1.1.0, 26 Jul 1998
**/
* IndexedPropertyDescriptor describes information about a JavaBean
* indexed property, by which we mean an array-like property that
* has been exposed via a pair of get and set methods and another
* pair that allows you to get to the property by an index.<P>
*
* An example property would have four methods like this:<P>
* <CODE>FooBar[] getFoo()</CODE><BR>
* <CODE>void setFoo(FooBar[])</CODE><BR>
* <CODE>FooBar getFoo(int)</CODE><BR>
* <CODE>void setFoo(int,FooBar)</CODE><P>
*
* The constraints put on get and set methods are:<P>
* <OL>
* <LI>There must be at least a get(int) or a set(int,...) method.
* Nothing else is required. <B>Spec note:</B>One nice restriction
* would be that if there is a get() there must be a get(int), same
* with set, but that is not in the spec and is fairly harmless.)</LI>
* <LI>A get array method must have signature
* <CODE>&lt;propertyType&gt;[] &lt;getMethodName&gt;()</CODE></LI>
* <LI>A set array method must have signature
* <CODE>void &lt;setMethodName&gt;(&lt;propertyType&gt;[])</CODE></LI>
* <LI>A get index method must have signature
* <CODE>&lt;propertyType&gt; &lt;getMethodName&gt;(int)</CODE></LI>
* <LI>A set index method must have signature
* <CODE>void &lt;setMethodName&gt;(int,&lt;propertyType&gt;)</CODE></LI>
* <LI>All these methods may throw any exception.</LI>
* <LI>All these methods must be public.</LI>
* </OL>
*
* @author John Keiser
* @since JDK1.1
*/
public class IndexedPropertyDescriptor extends PropertyDescriptor
{
private Class indexedPropertyType;
private Method setIndex;
private Method getIndex;
public class IndexedPropertyDescriptor extends PropertyDescriptor {
private Class indexedPropertyType;
private Method setIndex;
private Method getIndex;
/**
* Create a new IndexedPropertyDescriptor by introspection.
* This form of constructor creates the PropertyDescriptor by
* looking for getter methods named <CODE>get&lt;name&gt;()</CODE>
* and setter methods named
* <CODE>set&lt;name&gt;()</CODE> in class
* <CODE>&lt;beanClass&gt;</CODE>, where &lt;name&gt; has its
* first letter capitalized by the constructor.<P>
*
* <B>Implementation note:</B> If there is a get(int) method,
* then the return type of that method is used to find the
* remaining methods. If there is no get method, then the
* set(int) method is searched for exhaustively and that type
* is used to find the others.<P>
*
* <B>Spec note:</B>
* If there is no get(int) method and multiple set(int) methods with
* the same name and the correct parameters (different type of course),
* then an IntrospectionException is thrown. While Sun's spec
* does not state this, it can make Bean behavior different on
* different systems (since method order is not guaranteed) and as
* such, can be treated as a bug in the spec. I am not aware of
* whether Sun's implementation catches this.
*
* @param name the programmatic name of the property, usually
* starting with a lowercase letter (e.g. fooManChu
* instead of FooManChu).
* @param beanClass the class the get and set methods live in.
*
* @exception IntrospectionException if the methods are not found or
* invalid.
*/
public IndexedPropertyDescriptor(String name, Class beanClass)
throws IntrospectionException
{
super(name);
String capitalized;
try
{
capitalized = Character.toUpperCase(name.charAt(0))
+ name.substring(1);
}
catch(StringIndexOutOfBoundsException e)
{
capitalized = "";
}
findMethods(beanClass, "get" + capitalized, "set" + capitalized,
"get" + capitalized, "set" + capitalized);
}
/** Create a new IndexedPropertyDescriptor by introspection.
** This form of constructor creates the PropertyDescriptor by
** looking for getter methods named <CODE>get&lt;name&gt;()</CODE>
** and setter methods named
** <CODE>set&lt;name&gt;()</CODE> in class
** <CODE>&lt;beanClass&gt;</CODE>, where &lt;name&gt; has its
** first letter capitalized by the constructor.<P>
**
** <B>Implementation note:</B> If there is a get(int) method,
** then the return type of that method is used to find the
** remaining methods. If there is no get method, then the
** set(int) method is searched for exhaustively and that type
** is used to find the others.<P>
**
** <B>Spec note:</B>
** If there is no get(int) method and multiple set(int) methods with
** the same name and the correct parameters (different type of course),
** then an IntrospectionException is thrown. While Sun's spec
** does not state this, it can make Bean behavior different on
** different systems (since method order is not guaranteed) and as
** such, can be treated as a bug in the spec. I am not aware of
** whether Sun's implementation catches this.
**
** @param name the programmatic name of the property, usually
** starting with a lowercase letter (e.g. fooManChu
** instead of FooManChu).
** @param beanClass the class the get and set methods live in.
** @exception IntrospectionException if the methods are not found or invalid.
**/
public IndexedPropertyDescriptor(String name, Class beanClass) throws IntrospectionException {
super(name);
String capitalized;
try {
capitalized = Character.toUpperCase(name.charAt(0)) + name.substring(1);
} catch(StringIndexOutOfBoundsException e) {
capitalized = "";
}
findMethods(beanClass, "get" + capitalized, "set" + capitalized, "get" + capitalized, "set" + capitalized);
}
/**
* Create a new IndexedPropertyDescriptor by introspection.
* This form of constructor allows you to specify the
* names of the get and set methods to search for.<P>
*
* <B>Implementation note:</B> If there is a get(int) method,
* then the return type of that method is used to find the
* remaining methods. If there is no get method, then the
* set(int) method is searched for exhaustively and that type
* is used to find the others.<P>
*
* <B>Spec note:</B>
* If there is no get(int) method and multiple set(int) methods with
* the same name and the correct parameters (different type of course),
* then an IntrospectionException is thrown. While Sun's spec
* does not state this, it can make Bean behavior different on
* different systems (since method order is not guaranteed) and as
* such, can be treated as a bug in the spec. I am not aware of
* whether Sun's implementation catches this.
*
* @param name the programmatic name of the property, usually
* starting with a lowercase letter (e.g. fooManChu
* instead of FooManChu).
* @param beanClass the class the get and set methods live in.
* @param getMethodName the name of the get array method.
* @param setMethodName the name of the set array method.
* @param getIndexName the name of the get index method.
* @param setIndexName the name of the set index method.
*
* @exception IntrospectionException if the methods are not found or invalid.
*/
public IndexedPropertyDescriptor(String name, Class beanClass,
String getMethodName, String setMethodName,
String getIndexName, String setIndexName)
throws IntrospectionException
{
super(name);
findMethods(beanClass, getMethodName, setMethodName, getIndexName,
setIndexName);
}
/** Create a new IndexedPropertyDescriptor by introspection.
** This form of constructor allows you to specify the
** names of the get and set methods to search for.<P>
**
** <B>Implementation note:</B> If there is a get(int) method,
** then the return type of that method is used to find the
** remaining methods. If there is no get method, then the
** set(int) method is searched for exhaustively and that type
** is used to find the others.<P>
**
** <B>Spec note:</B>
** If there is no get(int) method and multiple set(int) methods with
** the same name and the correct parameters (different type of course),
** then an IntrospectionException is thrown. While Sun's spec
** does not state this, it can make Bean behavior different on
** different systems (since method order is not guaranteed) and as
** such, can be treated as a bug in the spec. I am not aware of
** whether Sun's implementation catches this.
**
** @param name the programmatic name of the property, usually
** starting with a lowercase letter (e.g. fooManChu
** instead of FooManChu).
** @param beanClass the class the get and set methods live in.
** @param getMethodName the name of the get array method.
** @param setMethodName the name of the set array method.
** @param getIndexName the name of the get index method.
** @param setIndexName the name of the set index method.
** @exception IntrospectionException if the methods are not found or invalid.
**/
public IndexedPropertyDescriptor(String name, Class beanClass, String getMethodName, String setMethodName, String getIndexName, String setIndexName) throws IntrospectionException {
super(name);
findMethods(beanClass, getMethodName, setMethodName, getIndexName, setIndexName);
}
/**
* Create a new PropertyDescriptor using explicit Methods.
* Note that the methods will be checked for conformance to standard
* Property method rules, as described above at the top of this class.
*
* @param name the programmatic name of the property, usually
* starting with a lowercase letter (e.g. fooManChu
* instead of FooManChu).
* @param getMethod the get array method.
* @param setMethod the set array method.
* @param getIndex the get index method.
* @param setIndex the set index method.
*
* @exception IntrospectionException if the methods are not found or invalid.
*/
public IndexedPropertyDescriptor(String name, Method getMethod,
Method setMethod, Method getIndex,
Method setIndex)
throws IntrospectionException
{
super(name);
if(getMethod != null && getMethod.getParameterTypes().length > 0)
throw new IntrospectionException("get method has parameters");
if(getMethod != null && setMethod.getParameterTypes().length != 1)
throw new IntrospectionException("set method does not have exactly one parameter");
if(getMethod != null && setMethod != null)
{
if(!getMethod.getReturnType().equals(setMethod.getParameterTypes()[0]))
{
throw new IntrospectionException("set and get methods do not "
+ "share the same type");
}
if(!getMethod.getDeclaringClass().isAssignableFrom
(setMethod.getDeclaringClass())
&& !setMethod.getDeclaringClass().isAssignableFrom
(getMethod.getDeclaringClass()))
{
throw new IntrospectionException("set and get methods are not in "
+ "the same class.");
}
}
/** Create a new PropertyDescriptor using explicit Methods.
** Note that the methods will be checked for conformance to standard
** Property method rules, as described above at the top of this class.
**
** @param name the programmatic name of the property, usually
** starting with a lowercase letter (e.g. fooManChu
** instead of FooManChu).
** @param getMethod the get array method.
** @param setMethod the set array method.
** @param getIndex the get index method.
** @param setIndex the set index method.
** @exception IntrospectionException if the methods are not found or invalid.
**/
public IndexedPropertyDescriptor(String name, Method getMethod, Method setMethod, Method getIndex, Method setIndex) throws IntrospectionException {
super(name);
if(getMethod != null && getMethod.getParameterTypes().length > 0) {
throw new IntrospectionException("get method has parameters");
}
if(getMethod != null && setMethod.getParameterTypes().length != 1) {
throw new IntrospectionException("set method does not have exactly one parameter");
}
if(getMethod != null && setMethod != null) {
if(!getMethod.getReturnType().equals(setMethod.getParameterTypes()[0])) {
throw new IntrospectionException("set and get methods do not share the same type");
}
if(!getMethod.getDeclaringClass().isAssignableFrom(setMethod.getDeclaringClass())
&& !setMethod.getDeclaringClass().isAssignableFrom(getMethod.getDeclaringClass())) {
throw new IntrospectionException("set and get methods are not in the same class.");
}
}
if (getIndex != null
&& (getIndex.getParameterTypes().length != 1
|| !(getIndex.getParameterTypes()[0]).equals(java.lang.Integer.TYPE)))
{
throw new IntrospectionException("get index method has wrong "
+ "parameters");
}
if (setIndex != null
&& (setIndex.getParameterTypes().length != 2
|| !(setIndex.getParameterTypes()[0]).equals(java.lang.Integer.TYPE)))
{
throw new IntrospectionException("set index method has wrong "
+ "parameters");
}
if (getIndex != null && setIndex != null)
{
if(!getIndex.getReturnType().equals(setIndex.getParameterTypes()[1]))
{
throw new IntrospectionException("set index methods do not share "
+ "the same type");
}
if(!getIndex.getDeclaringClass().isAssignableFrom
(setIndex.getDeclaringClass())
&& !setIndex.getDeclaringClass().isAssignableFrom
(getIndex.getDeclaringClass()))
{
throw new IntrospectionException("get and set index methods are "
+ "not in the same class.");
}
}
if(getIndex != null && (getIndex.getParameterTypes().length != 1
|| !(getIndex.getParameterTypes()[0]).equals(java.lang.Integer.TYPE))) {
throw new IntrospectionException("get index method has wrong parameters");
}
if(setIndex != null && (setIndex.getParameterTypes().length != 2
|| !(setIndex.getParameterTypes()[0]).equals(java.lang.Integer.TYPE))) {
throw new IntrospectionException("set index method has wrong parameters");
}
if(getIndex != null && setIndex != null) {
if(!getIndex.getReturnType().equals(setIndex.getParameterTypes()[1])) {
throw new IntrospectionException("set index methods do not share the same type");
}
if(!getIndex.getDeclaringClass().isAssignableFrom(setIndex.getDeclaringClass())
&& !setIndex.getDeclaringClass().isAssignableFrom(getIndex.getDeclaringClass())) {
throw new IntrospectionException("get and set index methods are not in the same class.");
}
}
if (getIndex != null && getMethod != null
&& !getIndex.getDeclaringClass().isAssignableFrom
(getMethod.getDeclaringClass())
&& !getMethod.getDeclaringClass().isAssignableFrom
(getIndex.getDeclaringClass()))
{
throw new IntrospectionException("methods are not in the same class.");
}
if(getIndex != null && getMethod != null && !getIndex.getDeclaringClass().isAssignableFrom(getMethod.getDeclaringClass())
&& !getMethod.getDeclaringClass().isAssignableFrom(getIndex.getDeclaringClass())) {
throw new IntrospectionException("methods are not in the same class.");
}
if (getIndex != null && getMethod != null
&& !Array.newInstance(getIndex.getReturnType(),0)
.getClass().equals(getMethod.getReturnType()))
{
throw new IntrospectionException("array methods do not match index "
+ "methods.");
}
if(getIndex != null && getMethod != null && !Array.newInstance(getIndex.getReturnType(),0).getClass().equals(getMethod.getReturnType())) {
throw new IntrospectionException("array methods do not match index methods.");
}
this.getMethod = getMethod;
this.setMethod = setMethod;
this.getIndex = getIndex;
this.setIndex = setIndex;
this.indexedPropertyType = getIndex != null ? getIndex.getReturnType()
: setIndex.getParameterTypes()[1];
this.propertyType = getMethod != null ? getMethod.getReturnType()
: (setMethod != null ? setMethod.getParameterTypes()[0]
: Array.newInstance(this.indexedPropertyType,0).getClass());
}
this.getMethod = getMethod;
this.setMethod = setMethod;
this.getIndex = getIndex;
this.setIndex = setIndex;
this.indexedPropertyType = getIndex != null ? getIndex.getReturnType() : setIndex.getParameterTypes()[1];
this.propertyType = getMethod != null ? getMethod.getReturnType() : (setMethod != null ? setMethod.getParameterTypes()[0] : Array.newInstance(this.indexedPropertyType,0).getClass());
}
public Class getIndexedPropertyType()
{
return indexedPropertyType;
}
public Class getIndexedPropertyType() {
return indexedPropertyType;
}
public Method getIndexedReadMethod()
{
return getIndex;
}
public Method getIndexedReadMethod() {
return getIndex;
}
/**
* Sets the method that is used to read an indexed property.
*
* @param m the method to set
*/
public void setIndexedReadMethod(Method m) throws IntrospectionException
{
getIndex = m;
}
public Method getIndexedWriteMethod() {
return setIndex;
}
public Method getIndexedWriteMethod()
{
return setIndex;
}
private void findMethods(Class beanClass, String getMethodName, String setMethodName, String getIndexName, String setIndexName) throws IntrospectionException {
try {
if(getIndexName != null) {
try {
Class[] getArgs = new Class[1];
getArgs[0] = java.lang.Integer.TYPE;
getIndex = beanClass.getMethod(getIndexName,getArgs);
indexedPropertyType = getIndex.getReturnType();
} catch(NoSuchMethodException E) {
}
}
if(getIndex != null) {
if(setIndexName != null) {
try {
Class[] setArgs = new Class[2];
setArgs[0] = java.lang.Integer.TYPE;
setArgs[1] = indexedPropertyType;
setIndex = beanClass.getMethod(setIndexName,setArgs);
if(!setIndex.getReturnType().equals(java.lang.Void.TYPE)) {
throw new IntrospectionException(setIndexName + " has non-void return type");
}
} catch(NoSuchMethodException E) {
}
}
} else if(setIndexName != null) {
Method[] m = beanClass.getMethods();
for(int i=0;i<m.length;i++) {
Method current = m[i];
if(current.getName().equals(setIndexName)
&& current.getParameterTypes().length == 2
&& (current.getParameterTypes()[0]).equals(java.lang.Integer.TYPE)
&& current.getReturnType().equals(java.lang.Void.TYPE)) {
if(setIndex != null) {
throw new IntrospectionException("Multiple, different set methods found that fit the bill!");
} else {
setIndex = current;
indexedPropertyType = current.getParameterTypes()[1];
}
}
}
if(setIndex == null) {
throw new IntrospectionException("Cannot find get or set methods.");
}
} else {
throw new IntrospectionException("Cannot find get or set methods.");
}
/**
* Sets the method that is used to write an indexed property.
*
* @param m the method to set
*/
public void setIndexedWriteMethod(Method m) throws IntrospectionException
{
setIndex = m;
}
Class arrayType = Array.newInstance(indexedPropertyType,0).getClass();
private void findMethods(Class beanClass, String getMethodName,
String setMethodName, String getIndexName,
String setIndexName)
throws IntrospectionException
{
try
{
if(getIndexName != null)
{
try
{
Class[] getArgs = new Class[1];
getArgs[0] = java.lang.Integer.TYPE;
getIndex = beanClass.getMethod(getIndexName,getArgs);
indexedPropertyType = getIndex.getReturnType();
}
catch(NoSuchMethodException E)
{
}
}
if(getIndex != null)
{
if(setIndexName != null)
{
try
{
Class[] setArgs = new Class[2];
setArgs[0] = java.lang.Integer.TYPE;
setArgs[1] = indexedPropertyType;
setIndex = beanClass.getMethod(setIndexName,setArgs);
if(!setIndex.getReturnType().equals(java.lang.Void.TYPE))
{
throw new IntrospectionException(setIndexName
+ " has non-void return type");
}
}
catch(NoSuchMethodException E)
{
}
}
}
else if(setIndexName != null)
{
Method[] m = beanClass.getMethods();
for(int i=0;i<m.length;i++)
{
Method current = m[i];
if(current.getName().equals(setIndexName)
&& current.getParameterTypes().length == 2
&& (current.getParameterTypes()[0])
.equals(java.lang.Integer.TYPE)
&& current.getReturnType().equals(java.lang.Void.TYPE))
{
if(setIndex != null)
{
throw new IntrospectionException("Multiple, different "
+ "set methods found that fit the bill!");
}
else
{
setIndex = current;
indexedPropertyType = current.getParameterTypes()[1];
}
}
}
if(setIndex == null)
{
throw new IntrospectionException("Cannot find get or set "
+ "methods.");
}
}
else
{
throw new IntrospectionException("Cannot find get or set methods.");
}
Class[] setArgs = new Class[1];
setArgs[0] = arrayType;
try {
setMethod = beanClass.getMethod(setMethodName,setArgs);
if(!setMethod.getReturnType().equals(java.lang.Void.TYPE)) {
setMethod = null;
}
} catch(NoSuchMethodException E) {
}
Class arrayType = Array.newInstance(indexedPropertyType,0).getClass();
Class[] getArgs = new Class[0];
try {
getMethod = beanClass.getMethod(getMethodName,getArgs);
if(!getMethod.getReturnType().equals(arrayType)) {
getMethod = null;
}
} catch(NoSuchMethodException E) {
}
} catch(SecurityException E) {
throw new IntrospectionException("SecurityException while trying to find methods.");
}
}
Class[] setArgs = new Class[1];
setArgs[0] = arrayType;
try
{
setMethod = beanClass.getMethod(setMethodName,setArgs);
if (!setMethod.getReturnType().equals(java.lang.Void.TYPE))
{
setMethod = null;
}
}
catch(NoSuchMethodException E)
{
}
Class[] getArgs = new Class[0];
try
{
getMethod = beanClass.getMethod(getMethodName,getArgs);
if (!getMethod.getReturnType().equals(arrayType))
{
getMethod = null;
}
}
catch(NoSuchMethodException E)
{
}
}
catch(SecurityException E)
{
throw new IntrospectionException("SecurityException while trying to "
+ "find methods.");
}
}
}
@@ -61,7 +61,6 @@ import java.lang.reflect.Method;
** @since 1.1
** @status updated to 1.4
**/
public class PropertyDescriptor extends FeatureDescriptor
{
Class propertyType;
@@ -521,6 +520,22 @@ public class PropertyDescriptor extends FeatureDescriptor
return newPropertyType;
}
/**
* Return a hash code for this object, conforming to the contract described
* in {@link Object#hashCode()}.
* @return the hash code
* @since 1.5
*/
public int hashCode()
{
return ((propertyType == null ? 0 : propertyType.hashCode())
| (propertyEditorClass == null ? 0 : propertyEditorClass.hashCode())
| (bound ? Boolean.TRUE : Boolean.FALSE).hashCode()
| (constrained ? Boolean.TRUE : Boolean.FALSE).hashCode()
| (getMethod == null ? 0 : getMethod.hashCode())
| (setMethod == null ? 0 : setMethod.hashCode()));
}
/** Compares this <code>PropertyDescriptor</code> against the
* given object.
* Two PropertyDescriptors are equals if
@@ -61,7 +61,7 @@ public class BeanContextServicesSupport
protected class BCSSChild
extends BeanContextSupport.BCSChild
{
private static final long serialVersionUID = -6848044915271367103L;
private static final long serialVersionUID = -3263851306889194873L;
}
protected class BCSSProxyServiceProvider
@@ -79,7 +79,7 @@ public class BeanContextSupport extends BeanContextChildSupport
protected class BCSChild implements Serializable
{
private static final long serialVersionUID = 3289144128843950629L;
private static final long serialVersionUID = -5815286101609939109L;
}
protected static final class BCSIterator implements Iterator
@@ -1,5 +1,6 @@
/* BufferedReader.java
Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005 Free Software Foundation, Inc.
Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005
Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -192,7 +193,7 @@ public class ByteArrayOutputStream extends OutputStream
*/
public String toString (int hibyte)
{
return new String (buf, 0, count, hibyte);
return new String (buf, hibyte, 0, count);
}
// Resize buffer to accommodate new bytes.
@@ -302,7 +302,7 @@ public class DataOutputStream extends FilterOutputStream implements DataOutput
*
* @exception IOException If an error occurs
*
* @see writeInt
* @see #writeInt(int)
* @see DataInput#readFloat
* @see Float#floatToIntBits
*/
@@ -326,7 +326,7 @@ public class DataOutputStream extends FilterOutputStream implements DataOutput
*
* @exception IOException If an error occurs
*
* @see writeLong
* @see #writeLong(long)
* @see DataInput#readDouble
* @see Double#doubleToLongBits
*/
@@ -363,7 +363,7 @@ public class DataOutputStream extends FilterOutputStream implements DataOutput
*
* @exception IOException If an error occurs
*
* @see writeChar
* @see #writeChar(char)
*/
public final void writeChars (String value) throws IOException
{
+34 -5
View File
@@ -100,6 +100,17 @@ public class File implements Serializable, Comparable
* may be an absolute or relative path name.
*/
private String path;
/**
* The time (millisecond), when the last temporary file was created.
*/
private static long last_tmp;
/**
* The number of files, created during the current millisecond.
*/
private static int n_created;
/**
* This method tests whether or not the current thread is allowed to
@@ -446,6 +457,8 @@ public class File implements Serializable, Comparable
else
return drvDir;
}
else if (path.equals(""))
return System.getProperty ("user.dir");
else
return System.getProperty ("user.dir") + separatorChar + path;
}
@@ -532,6 +545,9 @@ public class File implements Serializable, Comparable
{
String prefix = null;
int nameSeqIndex = 0;
if (path.equals(""))
return null;
// The "prefix", if present, is the leading "/" on UNIX and
// either the drive specifier (e.g. "C:") or the leading "\\"
@@ -943,8 +959,8 @@ public class File implements Serializable, Comparable
public URI toURI()
{
String abspath = getAbsolutePath();
if (isDirectory())
if (isDirectory() || path.equals(""))
abspath = abspath + separatorChar;
if (separatorChar == '\\')
@@ -1059,7 +1075,7 @@ public class File implements Serializable, Comparable
*
* @since 1.2
*/
public static File createTempFile(String prefix, String suffix,
public static synchronized File createTempFile(String prefix, String suffix,
File directory)
throws IOException
{
@@ -1091,10 +1107,23 @@ public class File implements Serializable, Comparable
// Now identify a file name and make sure it doesn't exist.
File file;
if (!VMFile.IS_DOS_8_3)
{
{
do
{
String filename = prefix + System.currentTimeMillis() + suffix;
long now = System.currentTimeMillis();
if (now > last_tmp)
{
// The last temporary file was created more than 1 ms ago.
last_tmp = now;
n_created = 0;
}
else
n_created++;
String name = Long.toHexString(now);
if (n_created > 0)
name += '_'+Integer.toHexString(n_created);
String filename = prefix + name + suffix;
file = new File(directory, filename);
}
while (VMFile.exists(file.path));
+1 -1
View File
@@ -119,7 +119,7 @@ public class FileWriter extends OutputStreamWriter
* This method intializes a new <code>FileWriter</code> object to
* write to the
* specified named file. This form of the constructor allows the caller
* to determin whether data should be written starting at the beginning or
* to determine whether data should be written starting at the beginning or
* the end of the file.
*
* @param name The name of the file to write to
+1 -1
View File
@@ -131,7 +131,7 @@ public abstract class FilterReader extends Reader
/**
* Calls the <code>in.skip(long)</code> method
*
* @param numBytes The requested number of chars to skip.
* @param num_chars The requested number of chars to skip.
*
* @return The value returned from <code>in.skip(long)</code>
*
@@ -38,16 +38,14 @@ exception statement from your version. */
package java.io;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import gnu.java.nio.charset.EncodingHelper;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import gnu.java.nio.charset.EncodingHelper;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
/**
* This class reads characters from a byte input stream. The characters
@@ -251,8 +249,12 @@ public class InputStreamReader extends Reader
this.in = in;
this.decoder = decoder;
Charset charset = decoder.charset();
try {
maxBytesPerChar = decoder.charset().newEncoder().maxBytesPerChar();
if (charset == null)
maxBytesPerChar = 1f;
else
maxBytesPerChar = charset.newEncoder().maxBytesPerChar();
} catch(UnsupportedOperationException _){
maxBytesPerChar = 1f;
}
@@ -260,7 +262,10 @@ public class InputStreamReader extends Reader
decoder.onMalformedInput(CodingErrorAction.REPLACE);
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
decoder.reset();
encoding = EncodingHelper.getOldCanonical(decoder.charset().name());
if (charset == null)
encoding = "US-ASCII";
else
encoding = EncodingHelper.getOldCanonical(decoder.charset().name());
}
/**
@@ -115,7 +115,7 @@ public class LineNumberReader extends BufferedReader
/**
* This method sets the current line number to the specified value.
*
* @param line_number The new line number
* @param lineNumber The new line number
*/
public void setLineNumber(int lineNumber)
{
@@ -139,7 +139,7 @@ public class LineNumberReader extends BufferedReader
* is called, the line number will be restored to the saved line number in
* addition to the stream position.
*
* @param readlimit The number of chars that can be read before the
* @param readLimit The number of chars that can be read before the
* mark becomes invalid
*
* @exception IOException If an error occurs
@@ -269,7 +269,7 @@ public class LineNumberReader extends BufferedReader
*
* @param buf The array into which the chars read should be stored
* @param offset The offset into the array to start storing chars
* @param len The requested number of chars to read
* @param count The requested number of chars to read
*
* @return The actual number of chars read, or -1 if end of stream
*
+318 -294
View File
@@ -39,7 +39,6 @@ exception statement from your version. */
package java.io;
import gnu.classpath.Configuration;
import gnu.java.io.ObjectIdentityWrapper;
import java.lang.reflect.Array;
@@ -53,6 +52,8 @@ import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.Vector;
public class ObjectInputStream extends InputStream
@@ -91,7 +92,6 @@ public class ObjectInputStream extends InputStream
}
this.resolveEnabled = false;
this.isDeserializing = false;
this.blockDataPosition = 0;
this.blockDataBytes = 0;
this.blockData = new byte[BUFFER_SIZE];
@@ -99,7 +99,6 @@ public class ObjectInputStream extends InputStream
this.realInputStream = new DataInputStream(in);
this.nextOID = baseWireHandle;
this.objectLookupTable = new Hashtable();
this.validators = new Vector();
this.classLookupTable = new Hashtable();
setBlockDataMode(true);
readStreamHeader();
@@ -113,7 +112,10 @@ public class ObjectInputStream extends InputStream
* <code>private void readObject (ObjectInputStream)</code>.
*
* If an exception is thrown from this method, the stream is left in
* an undefined state.
* an undefined state. This method can also throw Errors and
* RuntimeExceptions if caused by existing readResolve() user code.
*
* @return The object read from the underlying stream.
*
* @exception ClassNotFoundException The class that an object being
* read in belongs to cannot be found.
@@ -121,294 +123,315 @@ public class ObjectInputStream extends InputStream
* @exception IOException Exception from underlying
* <code>InputStream</code>.
*/
public final Object readObject() throws ClassNotFoundException, IOException
public final Object readObject()
throws ClassNotFoundException, IOException
{
if (this.useSubclassMethod)
return readObjectOverride();
boolean was_deserializing;
Object ret_val;
was_deserializing = this.isDeserializing;
boolean is_consumed = false;
boolean old_mode = setBlockDataMode(false);
this.isDeserializing = true;
byte marker = this.realInputStream.readByte();
depth += 2;
if (DEBUG)
depth += 2;
if(dump) dumpElement("MARKER: 0x" + Integer.toHexString(marker) + " ");
try
{
switch (marker)
{
case TC_ENDBLOCKDATA:
{
ret_val = null;
is_consumed = true;
break;
}
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
{
if (marker == TC_BLOCKDATALONG)
{ if(dump) dumpElementln("BLOCKDATALONG"); }
else
{ if(dump) dumpElementln("BLOCKDATA"); }
readNextBlock(marker);
throw new StreamCorruptedException("Unexpected blockData");
}
case TC_NULL:
{
if(dump) dumpElementln("NULL");
ret_val = null;
break;
}
case TC_REFERENCE:
{
if(dump) dumpElement("REFERENCE ");
Integer oid = new Integer(this.realInputStream.readInt());
if(dump) dumpElementln(Integer.toHexString(oid.intValue()));
ret_val = ((ObjectIdentityWrapper)
this.objectLookupTable.get(oid)).object;
break;
}
case TC_CLASS:
{
if(dump) dumpElementln("CLASS");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
assignNewHandle(clazz);
ret_val = clazz;
break;
}
case TC_PROXYCLASSDESC:
{
if(dump) dumpElementln("PROXYCLASS");
int n_intf = this.realInputStream.readInt();
String[] intfs = new String[n_intf];
for (int i = 0; i < n_intf; i++)
{
intfs[i] = this.realInputStream.readUTF();
System.out.println(intfs[i]);
}
boolean oldmode = setBlockDataMode(true);
Class cl = resolveProxyClass(intfs);
setBlockDataMode(oldmode);
ObjectStreamClass osc = lookupClass(cl);
assignNewHandle(osc);
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
ObjectStreamClass superosc = (ObjectStreamClass)readObject();
osc.setSuperclass(superosc);
ret_val = osc;
break;
}
case TC_CLASSDESC:
{
ObjectStreamClass osc = readClassDescriptor();
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
osc.setSuperclass ((ObjectStreamClass)readObject());
ret_val = osc;
break;
}
case TC_STRING:
case TC_LONGSTRING:
{
if(dump) dumpElement("STRING=");
String s = this.realInputStream.readUTF();
if(dump) dumpElementln(s);
ret_val = processResolution(null, s, assignNewHandle(s));
break;
}
case TC_ARRAY:
{
if(dump) dumpElementln("ARRAY");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class componentType = osc.forClass().getComponentType();
if(dump) dumpElement("ARRAY LENGTH=");
int length = this.realInputStream.readInt();
if(dump) dumpElementln (length + "; COMPONENT TYPE=" + componentType);
Object array = Array.newInstance(componentType, length);
int handle = assignNewHandle(array);
readArrayElements(array, componentType);
if(dump)
for (int i = 0, len = Array.getLength(array); i < len; i++)
dumpElementln(" ELEMENT[" + i + "]=" + Array.get(array, i));
ret_val = processResolution(null, array, handle);
break;
}
case TC_OBJECT:
{
if(dump) dumpElementln("OBJECT");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
if (!osc.realClassIsSerializable)
throw new NotSerializableException
(clazz + " is not Serializable, and thus cannot be deserialized.");
if (osc.realClassIsExternalizable)
{
Externalizable obj = osc.newInstance();
int handle = assignNewHandle(obj);
boolean read_from_blocks = ((osc.getFlags() & SC_BLOCK_DATA) != 0);
boolean oldmode = this.readDataFromBlock;
if (read_from_blocks)
setBlockDataMode(true);
obj.readExternal(this);
if (read_from_blocks)
{
setBlockDataMode(oldmode);
if (!oldmode)
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException("No end of block data seen for class with readExternal (ObjectInputStream) method.");
}
ret_val = processResolution(osc, obj, handle);
break;
} // end if (osc.realClassIsExternalizable)
Object obj = newObject(clazz, osc.firstNonSerializableParentConstructor);
int handle = assignNewHandle(obj);
Object prevObject = this.currentObject;
ObjectStreamClass prevObjectStreamClass = this.currentObjectStreamClass;
this.currentObject = obj;
ObjectStreamClass[] hierarchy =
inputGetObjectStreamClasses(clazz);
for (int i = 0; i < hierarchy.length; i++)
{
this.currentObjectStreamClass = hierarchy[i];
if(dump) dumpElementln("Reading fields of " + this.currentObjectStreamClass.getName ());
// XXX: should initialize fields in classes in the hierarchy
// that aren't in the stream
// should skip over classes in the stream that aren't in the
// real classes hierarchy
Method readObjectMethod = this.currentObjectStreamClass.readObjectMethod;
if (readObjectMethod != null)
{
fieldsAlreadyRead = false;
boolean oldmode = setBlockDataMode(true);
callReadMethod(readObjectMethod, this.currentObjectStreamClass.forClass(), obj);
setBlockDataMode(oldmode);
}
else
{
readFields(obj, currentObjectStreamClass);
}
if (this.currentObjectStreamClass.hasWriteMethod())
{
if(dump) dumpElement("ENDBLOCKDATA? ");
try
{
// FIXME: XXX: This try block is to
// catch EOF which is thrown for some
// objects. That indicates a bug in
// the logic.
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException
("No end of block data seen for class with readObject (ObjectInputStream) method.");
if(dump) dumpElementln("yes");
}
// catch (EOFException e)
// {
// if(dump) dumpElementln("no, got EOFException");
// }
catch (IOException e)
{
if(dump) dumpElementln("no, got IOException");
}
}
}
this.currentObject = prevObject;
this.currentObjectStreamClass = prevObjectStreamClass;
ret_val = processResolution(osc, obj, handle);
break;
}
case TC_RESET:
if(dump) dumpElementln("RESET");
clearHandles();
ret_val = readObject();
break;
case TC_EXCEPTION:
{
if(dump) dumpElement("EXCEPTION=");
Exception e = (Exception)readObject();
if(dump) dumpElementln(e.toString());
clearHandles();
throw new WriteAbortedException("Exception thrown during writing of stream", e);
}
default:
throw new IOException("Unknown marker on stream: " + marker);
}
ret_val = parseContent(marker);
}
finally
{
setBlockDataMode(old_mode);
this.isDeserializing = was_deserializing;
depth -= 2;
if (! was_deserializing)
{
if (validators.size() > 0)
invokeValidators();
}
setBlockDataMode(old_mode);
if (DEBUG)
depth -= 2;
}
return ret_val;
}
/**
* Handles a content block within the stream, which begins with a marker
* byte indicating its type.
*
* @param marker the byte marker.
* @return an object which represents the parsed content.
* @throws ClassNotFoundException if the class of an object being
* read in cannot be found.
* @throws IOException if invalid data occurs or one is thrown by the
* underlying <code>InputStream</code>.
*/
private Object parseContent(byte marker)
throws ClassNotFoundException, IOException
{
Object ret_val;
boolean is_consumed = false;
switch (marker)
{
case TC_ENDBLOCKDATA:
{
ret_val = null;
is_consumed = true;
break;
}
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
{
if (marker == TC_BLOCKDATALONG)
{ if(dump) dumpElementln("BLOCKDATALONG"); }
else
{ if(dump) dumpElementln("BLOCKDATA"); }
readNextBlock(marker);
}
case TC_NULL:
{
if(dump) dumpElementln("NULL");
ret_val = null;
break;
}
case TC_REFERENCE:
{
if(dump) dumpElement("REFERENCE ");
Integer oid = new Integer(this.realInputStream.readInt());
if(dump) dumpElementln(Integer.toHexString(oid.intValue()));
ret_val = ((ObjectIdentityWrapper)
this.objectLookupTable.get(oid)).object;
break;
}
case TC_CLASS:
{
if(dump) dumpElementln("CLASS");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
assignNewHandle(clazz);
ret_val = clazz;
break;
}
case TC_PROXYCLASSDESC:
{
if(dump) dumpElementln("PROXYCLASS");
int n_intf = this.realInputStream.readInt();
String[] intfs = new String[n_intf];
for (int i = 0; i < n_intf; i++)
{
intfs[i] = this.realInputStream.readUTF();
}
boolean oldmode = setBlockDataMode(true);
Class cl = resolveProxyClass(intfs);
setBlockDataMode(oldmode);
ObjectStreamClass osc = lookupClass(cl);
if (osc.firstNonSerializableParentConstructor == null)
{
osc.realClassIsSerializable = true;
osc.fields = osc.fieldMapping = new ObjectStreamField[0];
try
{
osc.firstNonSerializableParentConstructor =
Object.class.getConstructor(new Class[0]);
}
catch (NoSuchMethodException x)
{
throw (InternalError)
new InternalError("Object ctor missing").initCause(x);
}
}
assignNewHandle(osc);
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
ObjectStreamClass superosc = (ObjectStreamClass)readObject();
osc.setSuperclass(superosc);
ret_val = osc;
break;
}
case TC_CLASSDESC:
{
ObjectStreamClass osc = readClassDescriptor();
if (!is_consumed)
{
byte b = this.realInputStream.readByte();
if (b != TC_ENDBLOCKDATA)
throw new IOException("Data annotated to class was not consumed." + b);
}
else
is_consumed = false;
osc.setSuperclass ((ObjectStreamClass)readObject());
ret_val = osc;
break;
}
case TC_STRING:
case TC_LONGSTRING:
{
if(dump) dumpElement("STRING=");
String s = this.realInputStream.readUTF();
if(dump) dumpElementln(s);
ret_val = processResolution(null, s, assignNewHandle(s));
break;
}
case TC_ARRAY:
{
if(dump) dumpElementln("ARRAY");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class componentType = osc.forClass().getComponentType();
if(dump) dumpElement("ARRAY LENGTH=");
int length = this.realInputStream.readInt();
if(dump) dumpElementln (length + "; COMPONENT TYPE=" + componentType);
Object array = Array.newInstance(componentType, length);
int handle = assignNewHandle(array);
readArrayElements(array, componentType);
if(dump)
for (int i = 0, len = Array.getLength(array); i < len; i++)
dumpElementln(" ELEMENT[" + i + "]=" + Array.get(array, i));
ret_val = processResolution(null, array, handle);
break;
}
case TC_OBJECT:
{
if(dump) dumpElementln("OBJECT");
ObjectStreamClass osc = (ObjectStreamClass)readObject();
Class clazz = osc.forClass();
if (!osc.realClassIsSerializable)
throw new NotSerializableException
(clazz + " is not Serializable, and thus cannot be deserialized.");
if (osc.realClassIsExternalizable)
{
Externalizable obj = osc.newInstance();
int handle = assignNewHandle(obj);
boolean read_from_blocks = ((osc.getFlags() & SC_BLOCK_DATA) != 0);
boolean oldmode = this.readDataFromBlock;
if (read_from_blocks)
setBlockDataMode(true);
obj.readExternal(this);
if (read_from_blocks)
{
setBlockDataMode(oldmode);
if (!oldmode)
if (this.realInputStream.readByte() != TC_ENDBLOCKDATA)
throw new IOException("No end of block data seen for class with readExternal (ObjectInputStream) method.");
}
ret_val = processResolution(osc, obj, handle);
break;
} // end if (osc.realClassIsExternalizable)
Object obj = newObject(clazz, osc.firstNonSerializableParentConstructor);
int handle = assignNewHandle(obj);
Object prevObject = this.currentObject;
ObjectStreamClass prevObjectStreamClass = this.currentObjectStreamClass;
TreeSet prevObjectValidators = this.currentObjectValidators;
this.currentObject = obj;
this.currentObjectValidators = null;
ObjectStreamClass[] hierarchy =
inputGetObjectStreamClasses(clazz);
for (int i = 0; i < hierarchy.length; i++)
{
this.currentObjectStreamClass = hierarchy[i];
if(dump) dumpElementln("Reading fields of " + this.currentObjectStreamClass.getName ());
// XXX: should initialize fields in classes in the hierarchy
// that aren't in the stream
// should skip over classes in the stream that aren't in the
// real classes hierarchy
Method readObjectMethod = this.currentObjectStreamClass.readObjectMethod;
if (readObjectMethod != null)
{
fieldsAlreadyRead = false;
boolean oldmode = setBlockDataMode(true);
callReadMethod(readObjectMethod, this.currentObjectStreamClass.forClass(), obj);
setBlockDataMode(oldmode);
}
else
{
readFields(obj, currentObjectStreamClass);
}
if (this.currentObjectStreamClass.hasWriteMethod())
{
if(dump) dumpElement("ENDBLOCKDATA? ");
try
{
/* Read blocks until an end marker */
byte writeMarker = this.realInputStream.readByte();
while (writeMarker != TC_ENDBLOCKDATA)
{
parseContent(writeMarker);
writeMarker = this.realInputStream.readByte();
}
if(dump) dumpElementln("yes");
}
catch (EOFException e)
{
throw (IOException) new IOException
("No end of block data seen for class with readObject (ObjectInputStream) method.").initCause(e);
}
}
}
this.currentObject = prevObject;
this.currentObjectStreamClass = prevObjectStreamClass;
ret_val = processResolution(osc, obj, handle);
if (currentObjectValidators != null)
invokeValidators();
this.currentObjectValidators = prevObjectValidators;
break;
}
case TC_RESET:
if(dump) dumpElementln("RESET");
clearHandles();
ret_val = readObject();
break;
case TC_EXCEPTION:
{
if(dump) dumpElement("EXCEPTION=");
Exception e = (Exception)readObject();
if(dump) dumpElementln(e.toString());
clearHandles();
throw new WriteAbortedException("Exception thrown during writing of stream", e);
}
default:
throw new IOException("Unknown marker on stream: " + marker);
}
return ret_val;
}
/**
* This method makes a partial check of types for the fields
* contained given in arguments. It checks primitive types of
@@ -716,8 +739,10 @@ public class ObjectInputStream extends InputStream
throw new InvalidObjectException("attempt to add a null "
+ "ObjectInputValidation object");
this.validators.addElement(new ValidatorAndPriority (validator,
priority));
if (currentObjectValidators == null)
currentObjectValidators = new TreeSet();
currentObjectValidators.add(new ValidatorAndPriority(validator, priority));
}
@@ -805,7 +830,7 @@ public class ObjectInputStream extends InputStream
/**
* Reconstruct class hierarchy the same way
* {@link java.io.ObjectStreamClass.getObjectStreamClasses(java.lang.Class)} does
* {@link java.io.ObjectStreamClass#getObjectStreamClasses(Class)} does
* but using lookupClass instead of ObjectStreamClass.lookup. This
* dup is necessary localize the lookup table. Hopefully some future
* rewritings will be able to prevent this.
@@ -874,7 +899,7 @@ public class ObjectInputStream extends InputStream
}
else
for (int i = 0; i < intfs.length; i++)
clss[i] = cl.loadClass(intfs[i]);
clss[i] = Class.forName(intfs[i], false, cl);
try
{
return Proxy.getProxyClass(cl, clss);
@@ -1195,7 +1220,7 @@ public class ObjectInputStream extends InputStream
* This method should be called by a method called 'readObject' in the
* deserializing class (if present). It cannot (and should not)be called
* outside of it. Its goal is to read all fields in the real input stream
* and keep them accessible through the {@link #GetField} class. Calling
* and keep them accessible through the {@link GetField} class. Calling
* this method will not alter the deserializing object.
*
* @return A valid freshly created 'GetField' instance to get access to
@@ -1543,8 +1568,15 @@ public class ObjectInputStream extends InputStream
catch (IllegalAccessException ignore)
{
}
catch (InvocationTargetException ignore)
catch (InvocationTargetException exception)
{
Throwable cause = exception.getCause();
if (cause instanceof ObjectStreamException)
throw (ObjectStreamException) cause;
else if (cause instanceof RuntimeException)
throw (RuntimeException) cause;
else if (cause instanceof Error)
throw (Error) cause;
}
}
@@ -1821,18 +1853,19 @@ public class ObjectInputStream extends InputStream
// on OBJ
private void invokeValidators() throws InvalidObjectException
{
Object[] validators = new Object[this.validators.size()];
this.validators.copyInto (validators);
Arrays.sort (validators);
try
{
for (int i=0; i < validators.length; i++)
((ObjectInputValidation)validators[i]).validateObject();
Iterator it = currentObjectValidators.iterator();
while(it.hasNext())
{
ValidatorAndPriority vap = (ValidatorAndPriority) it.next();
ObjectInputValidation validator = vap.validator;
validator.validateObject();
}
}
finally
{
this.validators.removeAllElements();
currentObjectValidators = null;
}
}
@@ -1881,10 +1914,9 @@ public class ObjectInputStream extends InputStream
private Hashtable objectLookupTable;
private Object currentObject;
private ObjectStreamClass currentObjectStreamClass;
private TreeSet currentObjectValidators;
private boolean readDataFromBlock;
private boolean isDeserializing;
private boolean fieldsAlreadyRead;
private Vector validators;
private Hashtable classLookupTable;
private GetField prereadFields;
@@ -1908,14 +1940,6 @@ public class ObjectInputStream extends InputStream
System.out.print (Thread.currentThread() + ": ");
}
static
{
if (Configuration.INIT_LOAD_LIBRARY)
{
System.loadLibrary ("javaio");
}
}
// used to keep a prioritized list of object validators
private static final class ValidatorAndPriority implements Comparable
{
@@ -39,7 +39,6 @@ exception statement from your version. */
package java.io;
import gnu.classpath.Configuration;
import gnu.java.io.ObjectIdentityWrapper;
import gnu.java.lang.reflect.TypeSignature;
import gnu.java.security.action.SetAccessibleAction;
@@ -362,7 +361,9 @@ public class ObjectOutputStream extends OutputStream
break;
}
throw new NotSerializableException(clazz.getName ());
throw new NotSerializableException(clazz.getName()
+ " in "
+ obj.getClass());
} // end pseudo-loop
}
catch (ObjectStreamException ose)
@@ -412,37 +413,53 @@ public class ObjectOutputStream extends OutputStream
protected void writeClassDescriptor(ObjectStreamClass osc) throws IOException
{
realOutput.writeByte(TC_CLASSDESC);
realOutput.writeUTF(osc.getName());
realOutput.writeLong(osc.getSerialVersionUID());
assignNewHandle(osc);
int flags = osc.getFlags();
if (protocolVersion == PROTOCOL_VERSION_2
&& osc.isExternalizable())
flags |= SC_BLOCK_DATA;
realOutput.writeByte(flags);
ObjectStreamField[] fields = osc.fields;
realOutput.writeShort(fields.length);
ObjectStreamField field;
for (int i = 0; i < fields.length; i++)
if (osc.isProxyClass)
{
field = fields[i];
realOutput.writeByte(field.getTypeCode ());
realOutput.writeUTF(field.getName ());
realOutput.writeByte(TC_PROXYCLASSDESC);
Class[] intfs = osc.forClass().getInterfaces();
realOutput.writeInt(intfs.length);
for (int i = 0; i < intfs.length; i++)
realOutput.writeUTF(intfs[i].getName());
if (! field.isPrimitive())
writeObject(field.getTypeString());
boolean oldmode = setBlockDataMode(true);
annotateProxyClass(osc.forClass());
setBlockDataMode(oldmode);
realOutput.writeByte(TC_ENDBLOCKDATA);
}
else
{
realOutput.writeByte(TC_CLASSDESC);
realOutput.writeUTF(osc.getName());
realOutput.writeLong(osc.getSerialVersionUID());
assignNewHandle(osc);
boolean oldmode = setBlockDataMode(true);
annotateClass(osc.forClass());
setBlockDataMode(oldmode);
realOutput.writeByte(TC_ENDBLOCKDATA);
int flags = osc.getFlags();
if (protocolVersion == PROTOCOL_VERSION_2
&& osc.isExternalizable())
flags |= SC_BLOCK_DATA;
realOutput.writeByte(flags);
ObjectStreamField[] fields = osc.fields;
realOutput.writeShort(fields.length);
ObjectStreamField field;
for (int i = 0; i < fields.length; i++)
{
field = fields[i];
realOutput.writeByte(field.getTypeCode ());
realOutput.writeUTF(field.getName ());
if (! field.isPrimitive())
writeObject(field.getTypeString());
}
boolean oldmode = setBlockDataMode(true);
annotateClass(osc.forClass());
setBlockDataMode(oldmode);
realOutput.writeByte(TC_ENDBLOCKDATA);
}
if (osc.isSerializable() || osc.isExternalizable())
writeObject(osc.getSuper());
@@ -531,7 +548,7 @@ public class ObjectOutputStream extends OutputStream
* version)</code> is provided to change the default protocol
* version.
*
* For an explination of the differences beween the two protocols
* For an explanation of the differences between the two protocols
* see XXX: the Java ObjectSerialization Specification.
*
* @exception IOException if <code>version</code> is not a valid
@@ -1567,12 +1584,4 @@ public class ObjectOutputStream extends OutputStream
private boolean dump = false;
private static final boolean DEBUG = false;
static
{
if (Configuration.INIT_LOAD_LIBRARY)
{
System.loadLibrary("javaio");
}
}
}
@@ -208,7 +208,7 @@ public class ObjectStreamField implements Comparable
* This method sets the current offset of the field.
*
* @param off The offset of the field in bytes.
* @see getOffset()
* @see #getOffset()
*/
protected void setOffset (int off)
{
+100 -62
View File
@@ -39,16 +39,14 @@ exception statement from your version. */
package java.io;
import gnu.java.nio.charset.EncodingHelper;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
/**
* This class writes characters to an output stream that is byte oriented
@@ -124,52 +122,58 @@ public class OutputStreamWriter extends Writer
{
this.out = out;
try
{
// Don't use NIO if avoidable
if(EncodingHelper.isISOLatin1(encoding_scheme))
{
// Don't use NIO if avoidable
if(EncodingHelper.isISOLatin1(encoding_scheme))
{
encodingName = "ISO8859_1";
encoder = null;
return;
}
/*
* Workraround for encodings with a byte-order-mark.
* We only want to write it once per stream.
*/
try
{
if(encoding_scheme.equalsIgnoreCase("UnicodeBig") ||
encoding_scheme.equalsIgnoreCase("UTF-16") ||
encoding_scheme.equalsIgnoreCase("UTF16"))
{
encoding_scheme = "UTF-16BE";
out.write((byte)0xFE);
out.write((byte)0xFF);
}
else if(encoding_scheme.equalsIgnoreCase("UnicodeLittle")){
encoding_scheme = "UTF-16LE";
out.write((byte)0xFF);
out.write((byte)0xFE);
}
}
catch(IOException ioe)
{
}
outputBuffer = CharBuffer.allocate(BUFFER_SIZE);
Charset cs = EncodingHelper.getCharset(encoding_scheme);
if(cs == null)
throw new UnsupportedEncodingException("Encoding "+encoding_scheme+
" unknown");
encoder = cs.newEncoder();
encodingName = EncodingHelper.getOldCanonical(cs.name());
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
}
catch(RuntimeException e)
{
// Default to ISO Latin-1, will happen if this is called, for instance,
// before the NIO provider is loadable.
encoder = null;
encodingName = "ISO8859_1";
encoder = null;
return;
}
/*
* Workraround for encodings with a byte-order-mark.
* We only want to write it once per stream.
*/
try {
if(encoding_scheme.equalsIgnoreCase("UnicodeBig") ||
encoding_scheme.equalsIgnoreCase("UTF-16") ||
encoding_scheme.equalsIgnoreCase("UTF16"))
{
encoding_scheme = "UTF-16BE";
out.write((byte)0xFE);
out.write((byte)0xFF);
} else if(encoding_scheme.equalsIgnoreCase("UnicodeLittle")){
encoding_scheme = "UTF-16LE";
out.write((byte)0xFF);
out.write((byte)0xFE);
}
} catch(IOException ioe){
}
outputBuffer = CharBuffer.allocate(BUFFER_SIZE);
Charset cs = EncodingHelper.getCharset(encoding_scheme);
if(cs == null)
throw new UnsupportedEncodingException("Encoding "+encoding_scheme+
" unknown");
encoder = cs.newEncoder();
encodingName = EncodingHelper.getOldCanonical(cs.name());
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
} catch(RuntimeException e) {
// Default to ISO Latin-1, will happen if this is called, for instance,
// before the NIO provider is loadable.
encoder = null;
encodingName = "ISO8859_1";
}
}
/**
@@ -183,21 +187,55 @@ public class OutputStreamWriter extends Writer
this.out = out;
outputBuffer = null;
try
{
String encoding = System.getProperty("file.encoding");
Charset cs = Charset.forName(encoding);
encoder = cs.newEncoder();
encodingName = EncodingHelper.getOldCanonical(cs.name());
} catch(RuntimeException e) {
encoder = null;
encodingName = "ISO8859_1";
}
{
String encoding = System.getProperty("file.encoding");
Charset cs = Charset.forName(encoding);
encoder = cs.newEncoder();
encodingName = EncodingHelper.getOldCanonical(cs.name());
}
catch(RuntimeException e)
{
encoder = null;
encodingName = "ISO8859_1";
}
if(encoder != null)
{
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
outputBuffer = CharBuffer.allocate(BUFFER_SIZE);
}
{
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
outputBuffer = CharBuffer.allocate(BUFFER_SIZE);
}
}
/**
* This method initializes a new instance of <code>OutputStreamWriter</code>
* to write to the specified stream using a given <code>Charset</code>.
*
* @param out The <code>OutputStream</code> to write to
* @param cs The <code>Charset</code> of the encoding to use
*/
public OutputStreamWriter(OutputStream out, Charset cs)
{
this.out = out;
encoder = cs.newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
outputBuffer = CharBuffer.allocate(BUFFER_SIZE);
}
/**
* This method initializes a new instance of <code>OutputStreamWriter</code>
* to write to the specified stream using a given
* <code>CharsetEncoder</code>.
*
* @param out The <code>OutputStream</code> to write to
* @param enc The <code>CharsetEncoder</code> to encode the output with
*/
public OutputStreamWriter(OutputStream out, CharsetEncoder enc)
{
this.out = out;
encoder = enc;
outputBuffer = CharBuffer.allocate(BUFFER_SIZE);
}
/**
@@ -130,7 +130,7 @@ public class PipedInputStream extends InputStream
* This stream is then ready for reading. If this stream is already
* connected or has been previously closed, then an exception is thrown
*
* @param src The <code>PipedOutputStream</code> to connect this stream to
* @param source The <code>PipedOutputStream</code> to connect this stream to
*
* @exception IOException If this PipedInputStream or <code>source</code>
* has been connected already.
+72 -3
View File
@@ -70,6 +70,11 @@ public class PrintWriter extends Writer
* on this stream.
*/
private boolean error;
/**
* Indicates whether or not the stream has been closed.
*/
private boolean closed;
/**
* This is the underlying <code>Writer</code> we are sending output
@@ -138,6 +143,68 @@ public class PrintWriter extends Writer
this.autoflush = autoflush;
}
/**
* This initializes a new PrintWriter object to write to the specified
* file. It creates a FileOutputStream object and wraps it in an
* OutputStreamWriter using the default encoding.
* @param file name of the file to write to
* @throws FileNotFoundException if the file cannot be written or created
*
* @since 1.5
*/
public PrintWriter(String file) throws FileNotFoundException
{
this(new FileOutputStream(file));
}
/**
* This initializes a new PrintWriter object to write to the specified
* file. It creates a FileOutputStream object and wraps it in an
* OutputStreamWriter using the specified encoding.
* @param file name of the file to write to
* @param enc the encoding to use
* @throws FileNotFoundException if the file cannot be written or created
* @throws UnsupportedEncodingException if the encoding is not supported
*
* @since 1.5
*/
public PrintWriter(String file, String enc)
throws FileNotFoundException, UnsupportedEncodingException
{
this(new OutputStreamWriter(new FileOutputStream(file), enc));
}
/**
* This initializes a new PrintWriter object to write to the specified
* file. It creates a FileOutputStream object and wraps it in an
* OutputStreamWriter using the default encoding.
* @param file the file to write to
* @throws FileNotFoundException if the file cannot be written or created
*
* @since 1.5
*/
public PrintWriter(File file) throws FileNotFoundException
{
this(new FileOutputStream(file));
}
/**
* This initializes a new PrintWriter object to write to the specified
* file. It creates a FileOutputStream object and wraps it in an
* OutputStreamWriter using the specified encoding.
* @param file the file to write to
* @param enc the encoding to use
* @throws FileNotFoundException if the file cannot be written or created
* @throws UnsupportedEncodingException if the encoding is not supported
*
* @since 1.5
*/
public PrintWriter(File file, String enc)
throws FileNotFoundException, UnsupportedEncodingException
{
this(new OutputStreamWriter(new FileOutputStream(file), enc));
}
/**
* This method can be called by subclasses to indicate that an error
* has occurred and should be reported by <code>checkError</code>.
@@ -158,7 +225,8 @@ public class PrintWriter extends Writer
*/
public boolean checkError()
{
flush();
if (! closed)
flush();
return error;
}
@@ -185,7 +253,8 @@ public class PrintWriter extends Writer
{
try
{
out.close();
out.close();
closed = true;
}
catch (IOException ex)
{
@@ -310,7 +379,7 @@ public class PrintWriter extends Writer
* This is the system dependent line separator
*/
private static final char[] line_separator
= System.getProperty("line.separator").toCharArray();
= System.getProperty("line.separator", "\n").toCharArray();
/**
* This method prints a line separator sequence to the stream. The value
@@ -116,7 +116,14 @@ public class PushbackInputStream extends FilterInputStream
*/
public int available() throws IOException
{
return (buf.length - pos) + super.available();
try
{
return (buf.length - pos) + super.available();
}
catch (NullPointerException npe)
{
throw new IOException ("Stream closed");
}
}
/**
+32
View File
@@ -221,4 +221,36 @@ public final class Boolean implements Serializable
return false;
return "true".equalsIgnoreCase(System.getProperty(name));
}
/**
* If the String argument is "true", ignoring case, return true.
* Otherwise, return false.
*
* @param b String to parse
* @since 1.5
*/
public static boolean parseBoolean(String b)
{
return "true".equalsIgnoreCase(b) ? true : false;
}
/**
* Compares this Boolean to another.
* @param b the Boolean to compare this Boolean to
* @return 0 if both Booleans represent the same value, a positive number
* if this Boolean represents true and b represents false, or a negative
* number otherwise.
* @since 1.5
*/
public int compareTo (Boolean b)
{
if (b == null)
throw new NullPointerException("argument passed to compareTo(Boolean) cannot be null");
if (this.value == b.value)
return 0;
if (this.value == true)
return 1;
return -1;
}
}
+31 -1
View File
@@ -50,7 +50,7 @@ package java.lang;
* @author Per Bothner
* @author Eric Blake (ebb9@email.byu.edu)
* @since 1.1
* @status updated to 1.4
* @status updated to 1.5
*/
public final class Byte extends Number implements Comparable
{
@@ -77,6 +77,16 @@ public final class Byte extends Number implements Comparable
*/
public static final Class TYPE = VMClassLoader.getPrimitiveClass('B');
/**
* The number of bits needed to represent a <code>byte</code>.
* @since 1.5
*/
public static final int SIZE = 8;
// This caches Byte values, and is used by boxing conversions via
// valueOf(). We're required to cache all possible values here.
private static Byte[] byteCache = new Byte[MAX_VALUE - MIN_VALUE + 1];
/**
* The immutable value of this Byte.
*
@@ -192,6 +202,26 @@ public final class Byte extends Number implements Comparable
}
/**
* Returns a <code>Byte</code> object wrapping the value.
* In contrast to the <code>Byte</code> constructor, this method
* will cache some values. It is used by boxing conversion.
*
* @param val the value to wrap
* @return the <code>Byte</code>
*
* @since 1.5
*/
public static Byte valueOf(byte val)
{
synchronized (byteCache)
{
if (byteCache[val - MIN_VALUE] == null)
byteCache[val - MIN_VALUE] = new Byte(val);
return byteCache[val - MIN_VALUE];
}
}
/**
* Convert the specified <code>String</code> into a <code>Byte</code>.
* The <code>String</code> may represent decimal, hexadecimal, or
* octal numbers.
+269 -6
View File
@@ -1,5 +1,5 @@
/* java.lang.Character -- Wrapper class for char, and Unicode subsets
Copyright (C) 1998, 1999, 2001, 2002 Free Software Foundation, Inc.
Copyright (C) 1998, 1999, 2001, 2002, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -1033,6 +1033,18 @@ public final class Character implements Serializable, Comparable
*/
public static final Class TYPE = VMClassLoader.getPrimitiveClass('C');
/**
* The number of bits needed to represent a <code>char</code>.
* @since 1.5
*/
public static final int SIZE = 16;
// This caches some Character values, and is used by boxing
// conversions via valueOf(). We must cache at least 0..127;
// this constant controls how much we actually cache.
private static final int MAX_CACHE = 127;
private static Character[] charCache = new Character[MAX_CACHE + 1];
/**
* Lu = Letter, Uppercase (Informative).
*
@@ -1480,33 +1492,47 @@ public final class Character implements Serializable, Comparable
/**
* Minimum high surrrogate code in UTF-16 encoding.
* Minimum high surrogate code in UTF-16 encoding.
*
* @since 1.5
*/
public static final char MIN_HIGH_SURROGATE = '\ud800';
/**
* Maximum high surrrogate code in UTF-16 encoding.
* Maximum high surrogate code in UTF-16 encoding.
*
* @since 1.5
*/
public static final char MAX_HIGH_SURROGATE = '\udbff';
/**
* Minimum low surrrogate code in UTF-16 encoding.
* Minimum low surrogate code in UTF-16 encoding.
*
* @since 1.5
*/
public static final char MIN_LOW_SURROGATE = '\udc00';
/**
* Maximum low surrrogate code in UTF-16 encoding.
* Maximum low surrogate code in UTF-16 encoding.
*
* @since 1.5
*/
public static final char MAX_LOW_SURROGATE = '\udfff';
/**
* Minimum surrogate code in UTF-16 encoding.
*
* @since 1.5
*/
public static final char MIN_SURROGATE = MIN_HIGH_SURROGATE;
/**
* Maximum low surrogate code in UTF-16 encoding.
*
* @since 1.5
*/
public static final char MAX_SURROGATE = MAX_LOW_SURROGATE;
/**
* Grabs an attribute offset from the Unicode attribute database. The lower
* 5 bits are the character type, the next 2 bits are flags, and the top
@@ -2302,6 +2328,37 @@ public final class Character implements Serializable, Comparable
return compareTo((Character) o);
}
/**
* Returns an <code>Character</code> object wrapping the value.
* In contrast to the <code>Character</code> constructor, this method
* will cache some values. It is used by boxing conversion.
*
* @param val the value to wrap
* @return the <code>Character</code>
*
* @since 1.5
*/
public static Character valueOf(char val)
{
if (val > MAX_CACHE)
return new Character(val);
synchronized (charCache)
{
if (charCache[val - MIN_VALUE] == null)
charCache[val - MIN_VALUE] = new Character(val);
return charCache[val - MIN_VALUE];
}
}
/**
* Reverse the bytes in val.
* @since 1.5
*/
public static char reverseBytes(char val)
{
return (char) (((val >> 8) & 0xff) | ((val << 8) & 0xff00));
}
/**
* Converts a unicode code point to a UTF-16 representation of that
* code point.
@@ -2370,7 +2427,7 @@ public final class Character implements Serializable, Comparable
* Return number of 16-bit characters required to represent the given
* code point.
*
* @param codePoint a uncode code point
* @param codePoint a unicode code point
*
* @return 2 if codePoint >= 0x10000, 1 otherwise.
*
@@ -2415,4 +2472,210 @@ public final class Character implements Serializable, Comparable
{
return codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT;
}
/**
* Return true if the given character is a high surrogate.
* @param ch the character
* @return true if the character is a high surrogate character
*
* @since 1.5
*/
public static boolean isHighSurrogate(char ch)
{
return ch >= MIN_HIGH_SURROGATE && ch <= MAX_HIGH_SURROGATE;
}
/**
* Return true if the given character is a low surrogate.
* @param ch the character
* @return true if the character is a low surrogate character
*
* @since 1.5
*/
public static boolean isLowSurrogate(char ch)
{
return ch >= MIN_LOW_SURROGATE && ch <= MAX_LOW_SURROGATE;
}
/**
* Return true if the given characters compose a surrogate pair.
* This is true if the first character is a high surrogate and the
* second character is a low surrogate.
* @param ch1 the first character
* @param ch2 the first character
* @return true if the characters compose a surrogate pair
*
* @since 1.5
*/
public static boolean isSurrogatePair(char ch1, char ch2)
{
return isHighSurrogate(ch1) && isLowSurrogate(ch2);
}
/**
* Given a valid surrogate pair, this returns the corresponding
* code point.
* @param high the high character of the pair
* @param low the low character of the pair
* @return the corresponding code point
*
* @since 1.5
*/
public static int toCodePoint(char high, char low)
{
return ((high - MIN_HIGH_SURROGATE) << 10) + (low - MIN_LOW_SURROGATE);
}
/**
* Get the code point at the specified index in the CharSequence.
* This is like CharSequence#charAt(int), but if the character is
* the start of a surrogate pair, and there is a following
* character, and this character completes the pair, then the
* corresponding supplementary code point is returned. Otherwise,
* the character at the index is returned.
*
* @param sequence the CharSequence
* @param index the index of the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public static int codePointAt(CharSequence sequence, int index)
{
int len = sequence.length();
if (index < 0 || index >= len)
throw new IndexOutOfBoundsException();
char high = sequence.charAt(index);
if (! isHighSurrogate(high) || ++index >= len)
return high;
char low = sequence.charAt(index);
if (! isLowSurrogate(low))
return high;
return toCodePoint(high, low);
}
/**
* Get the code point at the specified index in the CharSequence.
* If the character is the start of a surrogate pair, and there is a
* following character, and this character completes the pair, then
* the corresponding supplementary code point is returned.
* Otherwise, the character at the index is returned.
*
* @param chars the character array in which to look
* @param index the index of the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public static int codePointAt(char[] chars, int index)
{
return codePointAt(chars, index, chars.length);
}
/**
* Get the code point at the specified index in the CharSequence.
* If the character is the start of a surrogate pair, and there is a
* following character within the specified range, and this
* character completes the pair, then the corresponding
* supplementary code point is returned. Otherwise, the character
* at the index is returned.
*
* @param chars the character array in which to look
* @param index the index of the codepoint to get, starting at 0
* @param limit the limit past which characters should not be examined
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;=
* limit, or if limit is negative or &gt;= the length of the array
* @since 1.5
*/
public static int codePointAt(char[] chars, int index, int limit)
{
if (index < 0 || index >= limit || limit < 0 || limit >= chars.length)
throw new IndexOutOfBoundsException();
char high = chars[index];
if (! isHighSurrogate(high) || ++index >= limit)
return high;
char low = chars[index];
if (! isLowSurrogate(low))
return high;
return toCodePoint(high, low);
}
/**
* Get the code point before the specified index. This is like
* #codePointAt(char[], int), but checks the characters at
* <code>index-1</code> and <code>index-2</code> to see if they form
* a supplementary code point. If they do not, the character at
* <code>index-1</code> is returned.
*
* @param chars the character array
* @param index the index just past the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public static int codePointBefore(char[] chars, int index)
{
return codePointBefore(chars, index, 1);
}
/**
* Get the code point before the specified index. This is like
* #codePointAt(char[], int), but checks the characters at
* <code>index-1</code> and <code>index-2</code> to see if they form
* a supplementary code point. If they do not, the character at
* <code>index-1</code> is returned. The start parameter is used to
* limit the range of the array which may be examined.
*
* @param chars the character array
* @param index the index just past the codepoint to get, starting at 0
* @param start the index before which characters should not be examined
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is &gt; start or &gt;
* the length of the array, or if limit is negative or &gt;= the
* length of the array
* @since 1.5
*/
public static int codePointBefore(char[] chars, int index, int start)
{
if (index < start || index > chars.length
|| start < 0 || start >= chars.length)
throw new IndexOutOfBoundsException();
--index;
char low = chars[index];
if (! isLowSurrogate(low) || --index < start)
return low;
char high = chars[index];
if (! isHighSurrogate(high))
return low;
return toCodePoint(high, low);
}
/**
* Get the code point before the specified index. This is like
* #codePointAt(CharSequence, int), but checks the characters at
* <code>index-1</code> and <code>index-2</code> to see if they form
* a supplementary code point. If they do not, the character at
* <code>index-1</code> is returned.
*
* @param sequence the CharSequence
* @param index the index just past the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public static int codePointBefore(CharSequence sequence, int index)
{
int len = sequence.length();
if (index < 1 || index > len)
throw new IndexOutOfBoundsException();
--index;
char low = sequence.charAt(index);
if (! isLowSurrogate(low) || --index < 0)
return low;
char high = sequence.charAt(index);
if (! isHighSurrogate(high))
return low;
return toCodePoint(high, low);
}
} // class Character
+7 -4
View File
@@ -41,7 +41,9 @@ package java.lang;
import gnu.classpath.VMStackWalker;
import java.io.InputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
@@ -99,7 +101,7 @@ public final class Class implements Serializable
/** The class signers. */
private Object[] signers = null;
/** The class protection domain. */
private final ProtectionDomain pd;
private final transient ProtectionDomain pd;
/* We use an inner class, so that Class doesn't have a static initializer */
private static final class StaticData
@@ -592,7 +594,8 @@ public final class Class implements Serializable
ClassLoader cl = getClassLoader();
if (cl != null)
return cl.getPackage(getPackagePortion(getName()));
return null;
else
return VMClassLoader.getPackage(getPackagePortion(getName()));
}
/**
@@ -721,7 +724,7 @@ public final class Class implements Serializable
* @param list List of methods to search
* @param name Name of method
* @param args Method parameter types
* @see #getMethod()
* @see #getMethod(String, Class[])
*/
private static Method matchMethod(Method[] list, String name, Class[] args)
{
@@ -829,7 +832,7 @@ public final class Class implements Serializable
* public and final, but not an interface.
*
* @return the modifiers of this class
* @see Modifer
* @see Modifier
* @since 1.1
*/
public int getModifiers()
+33 -3
View File
@@ -49,6 +49,7 @@ import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Policy;
@@ -471,6 +472,35 @@ public abstract class ClassLoader
return VMClassLoader.defineClass(this, name, data, offset, len, domain);
}
/**
* Helper to define a class using the contents of a byte buffer. If
* the domain is null, the default of
* <code>Policy.getPolicy().getPermissions(new CodeSource(null,
* null))</code> is used. Once a class has been defined in a
* package, all further classes in that package must have the same
* set of certificates or a SecurityException is thrown.
*
* @param name the name to give the class. null if unknown
* @param buf a byte buffer containing bytes that form a class.
* @param domain the ProtectionDomain to give to the class, null for the
* default protection domain
* @return the class that was defined
* @throws ClassFormatError if data is not in proper classfile format
* @throws NoClassDefFoundError if the supplied name is not the same as
* the one specified by the byte buffer.
* @throws SecurityException if name starts with "java.", or if certificates
* do not match up
* @since 1.5
*/
protected final Class defineClass(String name, ByteBuffer buf,
ProtectionDomain domain)
throws ClassFormatError
{
byte[] data = new byte[buf.remaining()];
buf.get(data);
return defineClass(name, data, 0, data.length, domain);
}
/**
* Links the class, if that has not already been done. Linking basically
* resolves all references to other classes made by this class.
@@ -883,7 +913,7 @@ public abstract class ClassLoader
*
* @param name the (system specific) name of the requested library
* @return the full pathname to the requested library, or null
* @see Runtime#loadLibrary()
* @see Runtime#loadLibrary(String)
* @since 1.2
*/
protected String findLibrary(String name)
@@ -913,7 +943,7 @@ public abstract class ClassLoader
*
* @param name the package (and subpackages) to affect
* @param enabled true to set the default to enabled
* @see #setDefaultAssertionStatus(String, boolean)
* @see #setDefaultAssertionStatus(boolean)
* @see #setClassAssertionStatus(String, boolean)
* @see #clearAssertionStatus()
* @since 1.4
@@ -934,7 +964,7 @@ public abstract class ClassLoader
* @param name the class to affect
* @param enabled true to set the default to enabled
* @throws NullPointerException if name is null
* @see #setDefaultAssertionStatus(String, boolean)
* @see #setDefaultAssertionStatus(boolean)
* @see #setPackageAssertionStatus(String, boolean)
* @see #clearAssertionStatus()
* @since 1.4
+22 -1
View File
@@ -38,7 +38,6 @@ exception statement from your version. */
package java.lang;
import gnu.classpath.Configuration;
/**
* Instances of class <code>Double</code> represent primitive
@@ -89,6 +88,12 @@ public final class Double extends Number implements Comparable
public static final double NaN = 0.0 / 0.0;
/**
* The number of bits needed to represent a <code>double</code>.
* @since 1.5
*/
public static final int SIZE = 64;
/**
* The primitive type <code>double</code> is represented by this
* <code>Class</code> object.
* @since 1.1
@@ -168,6 +173,22 @@ public final class Double extends Number implements Comparable
}
/**
* Returns a <code>Double</code> object wrapping the value.
* In contrast to the <code>Double</code> constructor, this method
* may cache some values. It is used by boxing conversion.
*
* @param val the value to wrap
* @return the <code>Double</code>
*
* @since 1.5
*/
public static Double valueOf(double val)
{
// We don't actually cache, but we could.
return new Double(val);
}
/**
* Create a new <code>Double</code> object using the <code>String</code>.
*
* @param s the <code>String</code> to convert
@@ -0,0 +1,93 @@
/* EnumConstantNotPresentException.java -- thrown when enum constant
not available
Copyright (C) 2005 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 java.lang;
/**
* An exception of this type is thrown when a symbolic reference is
* made to an enum constant which does not exist.
*
* @author Tom Tromey (tromey@redhat.com)
* @since 1.5
*/
public class EnumConstantNotPresentException extends RuntimeException
{
/**
* The enum's type. Note that the name is fixed by the
* serialization spec.
*/
private Class enumType;
/**
* The name of the missing enum constant. Note that the name is
* fixed by the serialization spec.
*/
private String constantName;
/**
* Create a new EnumConstantNotPresentException with the indicated
* enum type and enum constant name.
* @param theEnum the enum's class
* @param name the name of the missing enum constant
*/
public EnumConstantNotPresentException(Class theEnum, String name)
{
super("enum " + theEnum + " is missing the constant " + name);
enumType = theEnum;
constantName = name;
}
/**
* Return the name of the missing constant.
* @return the name of the missing constant
*/
public String constantName()
{
return constantName;
}
/**
* Return the enum type which is missing a constant.
* @return the enum type which is missing a constant
*/
public Class enumType()
{
return enumType;
}
}
+22
View File
@@ -93,6 +93,12 @@ public final class Float extends Number implements Comparable
*/
public static final Class TYPE = VMClassLoader.getPrimitiveClass('F');
/**
* The number of bits needed to represent a <code>float</code>.
* @since 1.5
*/
public static final int SIZE = 32;
/**
* The immutable value of this Float.
*
@@ -191,6 +197,22 @@ public final class Float extends Number implements Comparable
return new Float(parseFloat(s));
}
/**
* Returns a <code>Float</code> object wrapping the value.
* In contrast to the <code>Float</code> constructor, this method
* may cache some values. It is used by boxing conversion.
*
* @param val the value to wrap
* @return the <code>Float</code>
*
* @since 1.5
*/
public static Float valueOf(float val)
{
// We don't actually cache, but we could.
return new Float(val);
}
/**
* Parse the specified <code>String</code> as a <code>float</code>. The
* extended BNF grammar is as follows:<br>
+2 -2
View File
@@ -707,8 +707,8 @@ public final class Integer extends Number implements Comparable
* @throws NullPointerException if decode is true and str if null
* @see #parseInt(String, int)
* @see #decode(String)
* @see Byte#parseInt(String, int)
* @see Short#parseInt(String, int)
* @see Byte#parseByte(String, int)
* @see Short#parseShort(String, int)
*/
static int parseInt(String str, int radix, boolean decode)
{
+152 -1
View File
@@ -50,7 +50,7 @@ package java.lang;
* @author Warren Levy
* @author Eric Blake (ebb9@email.byu.edu)
* @since 1.0
* @status updated to 1.4
* @status updated to 1.5
*/
public final class Long extends Number implements Comparable
{
@@ -78,6 +78,12 @@ public final class Long extends Number implements Comparable
*/
public static final Class TYPE = VMClassLoader.getPrimitiveClass ('J');
/**
* The number of bits needed to represent a <code>long</code>.
* @since 1.5
*/
public static final int SIZE = 64;
/**
* The immutable value of this Long.
*
@@ -281,6 +287,21 @@ public final class Long extends Number implements Comparable
return new Long(parseLong(s, 10, false));
}
/**
* Returns a <code>Long</code> object wrapping the value.
*
* @param val the value to wrap
* @return the <code>Long</code>
*
* @since 1.5
*/
public static synchronized Long valueOf(long val)
{
// We aren't required to cache here. We could, though perhaps we
// ought to consider that as an empirical question.
return new Long(val);
}
/**
* Convert the specified <code>String</code> into a <code>Long</code>.
* The <code>String</code> may represent decimal, hexadecimal, or
@@ -511,6 +532,136 @@ public final class Long extends Number implements Comparable
return compareTo((Long) o);
}
/**
* Return the number of bits set in x.
* @param x value to examine
* @since 1.5
*/
public static int bitCount(long x)
{
// Successively collapse alternating bit groups into a sum.
x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
int v = (int) ((x >>> 32) + x);
v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
}
/**
* Rotate x to the left by distance bits.
* @param x the value to rotate
* @param distance the number of bits by which to rotate
* @since 1.5
*/
public static long rotateLeft(long x, int distance)
{
// This trick works because the shift operators implicitly mask
// the shift count.
return (x << distance) | (x >>> - distance);
}
/**
* Rotate x to the right by distance bits.
* @param x the value to rotate
* @param distance the number of bits by which to rotate
* @since 1.5
*/
public static long rotateRight(long x, int distance)
{
// This trick works because the shift operators implicitly mask
// the shift count.
return (x << - distance) | (x >>> distance);
}
/**
* Find the highest set bit in value, and return a new value
* with only that bit set.
* @param value the value to examine
* @since 1.5
*/
public static long highestOneBit(long value)
{
value |= value >>> 1;
value |= value >>> 2;
value |= value >>> 4;
value |= value >>> 8;
value |= value >>> 16;
value |= value >>> 32;
return value ^ (value >>> 1);
}
/**
* Return the number of leading zeros in value.
* @param value the value to examine
* @since 1.5
*/
public static int numberOfLeadingZeros(long value)
{
value |= value >>> 1;
value |= value >>> 2;
value |= value >>> 4;
value |= value >>> 8;
value |= value >>> 16;
value |= value >>> 32;
return bitCount(~value);
}
/**
* Find the lowest set bit in value, and return a new value
* with only that bit set.
* @param value the value to examine
* @since 1.5
*/
public static long lowestOneBit(long value)
{
// Classic assembly trick.
return value & - value;
}
/**
* Find the number of trailing zeros in value.
* @param value the value to examine
* @since 1.5
*/
public static int numberOfTrailingZeros(long value)
{
return bitCount((value & -value) - 1);
}
/**
* Return 1 if x is positive, -1 if it is negative, and 0 if it is
* zero.
* @param x the value to examine
* @since 1.5
*/
public static int signum(long x)
{
return x < 0 ? -1 : (x > 0 ? 1 : 0);
}
/**
* Reverse the bytes in val.
* @since 1.5
*/
public static long reverseBytes(long val)
{
int hi = Integer.reverseBytes((int) val);
int lo = Integer.reverseBytes((int) (val >>> 32));
return (((long) hi) << 32) | lo;
}
/**
* Reverse the bits in val.
* @since 1.5
*/
public static long reverse(long val)
{
long hi = Integer.reverse((int) val) & 0xffffffffL;
long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
return (hi << 32) | lo;
}
/**
* Helper for converting unsigned numbers to String.
*
+2 -2
View File
@@ -343,7 +343,7 @@ public class Object
*
* <p>This thread still holds a lock on the object, so it is
* typical to release the lock by exiting the synchronized
* code, calling wait(), or calling {@link Thread#sleep()}, so
* code, calling wait(), or calling {@link Thread#sleep(long)}, so
* that the newly awakened thread can actually resume. The
* awakened thread will most likely be awakened with an
* {@link InterruptedException}, but that is not guaranteed.
@@ -372,7 +372,7 @@ public class Object
*
* <p>This thread still holds a lock on the object, so it is
* typical to release the lock by exiting the synchronized
* code, calling wait(), or calling {@link Thread#sleep()}, so
* code, calling wait(), or calling {@link Thread#sleep(long)}, so
* that one of the newly awakened threads can actually resume.
* The resuming thread will most likely be awakened with an
* {@link InterruptedException}, but that is not guaranteed.
+1
View File
@@ -39,6 +39,7 @@ exception statement from your version. */
package java.lang;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
@@ -39,6 +39,7 @@ package java.lang;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.ReadOnlyBufferException;
/**
* A <code>Readable</code> object is simply a source for Unicode character
@@ -39,6 +39,7 @@ exception statement from your version. */
package java.lang;
import java.security.BasicPermission;
import java.security.Permission;
/**
* A <code>RuntimePermission</code> contains a permission name, but no
@@ -41,19 +41,35 @@ package java.lang;
import gnu.classpath.VMStackWalker;
import java.awt.AWTPermission;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.Window;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.RandomAccessFile;
import java.lang.reflect.Member;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImplFactory;
import java.net.SocketPermission;
import java.net.URL;
import java.net.URLStreamHandlerFactory;
import java.security.AccessControlContext;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.AllPermission;
import java.security.BasicPermission;
import java.security.Permission;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.Security;
import java.security.SecurityPermission;
import java.util.Properties;
import java.util.PropertyPermission;
import java.util.StringTokenizer;
@@ -196,7 +212,7 @@ public class SecurityManager
* <ul>
* <li>All methods on the stack are from system classes</li>
* <li>All methods on the stack up to the first "privileged" caller, as
* created by {@link AccessController.doPrivileged(PrivilegedAction)},
* created by {@link AccessController#doPrivileged(PrivilegedAction)},
* are from system classes</li>
* <li>A check of <code>java.security.AllPermission</code> succeeds.</li>
* </ul>
@@ -219,7 +235,7 @@ public class SecurityManager
* <ul>
* <li>All methods on the stack are from system classes</li>
* <li>All methods on the stack up to the first "privileged" caller, as
* created by {@link AccessController.doPrivileged(PrivilegedAction)},
* created by {@link AccessController#doPrivileged(PrivilegedAction)},
* are from system classes</li>
* <li>A check of <code>java.security.AllPermission</code> succeeds.</li>
* </ul>
@@ -258,7 +274,7 @@ public class SecurityManager
* <ul>
* <li>All methods on the stack are from system classes</li>
* <li>All methods on the stack up to the first "privileged" caller, as
* created by {@link AccessController.doPrivileged(PrivilegedAction)},
* created by {@link AccessController#doPrivileged(PrivilegedAction)},
* are from system classes</li>
* <li>A check of <code>java.security.AllPermission</code> succeeds.</li>
* </ul>
@@ -431,7 +447,7 @@ public class SecurityManager
* @throws SecurityException if permission is denied
* @throws NullPointerException if g is null
* @see Thread#Thread()
* @see ThreadGroup#ThreadGroup()
* @see ThreadGroup#ThreadGroup(String)
* @see ThreadGroup#stop()
* @see ThreadGroup#suspend()
* @see ThreadGroup#resume()
@@ -537,7 +553,7 @@ public class SecurityManager
* @throws NullPointerException if filename is null
* @see File
* @see FileInputStream#FileInputStream(String)
* @see RandomAccessFile#RandomAccessFile(String)
* @see RandomAccessFile#RandomAccessFile(String, String)
*/
public void checkRead(String filename)
{
@@ -602,9 +618,9 @@ public class SecurityManager
* @see File
* @see File#canWrite()
* @see File#mkdir()
* @see File#renameTo()
* @see File#renameTo(File)
* @see FileOutputStream#FileOutputStream(String)
* @see RandomAccessFile#RandomAccessFile(String)
* @see RandomAccessFile#RandomAccessFile(String, String)
*/
public void checkWrite(String filename)
{
+44
View File
@@ -76,6 +76,19 @@ public final class Short extends Number implements Comparable
*/
public static final Class TYPE = VMClassLoader.getPrimitiveClass('S');
/**
* The number of bits needed to represent a <code>short</code>.
* @since 1.5
*/
public static final int SIZE = 16;
// This caches some Short values, and is used by boxing conversions
// via valueOf(). We must cache at least -128..127; these constants
// control how much we actually cache.
private static final int MIN_CACHE = -128;
private static final int MAX_CACHE = 127;
private static Short[] shortCache = new Short[MAX_CACHE - MIN_CACHE + 1];
/**
* The immutable value of this Short.
*
@@ -188,6 +201,28 @@ public final class Short extends Number implements Comparable
return new Short(parseShort(s, 10));
}
/**
* Returns a <code>Short</code> object wrapping the value.
* In contrast to the <code>Short</code> constructor, this method
* will cache some values. It is used by boxing conversion.
*
* @param val the value to wrap
* @return the <code>Short</code>
*
* @since 1.5
*/
public static Short valueOf(short val)
{
if (val < MIN_CACHE || val > MAX_CACHE)
return new Short(val);
synchronized (shortCache)
{
if (shortCache[val - MIN_CACHE] == null)
shortCache[val - MIN_CACHE] = new Short(val);
return shortCache[val - MIN_CACHE];
}
}
/**
* Convert the specified <code>String</code> into a <code>Short</code>.
* The <code>String</code> may represent decimal, hexadecimal, or
@@ -350,4 +385,13 @@ public final class Short extends Number implements Comparable
{
return compareTo((Short)o);
}
/**
* Reverse the bytes in val.
* @since 1.5
*/
public static short reverseBytes(short val)
{
return (short) (((val >> 8) & 0xff) | ((val << 8) & 0xff00));
}
}
+5 -5
View File
@@ -1254,7 +1254,7 @@ public final strictfp class StrictMath
/**
* Super precision for 2/pi in 24-bit chunks, for use in
* {@link #remPiOver2()}.
* {@link #remPiOver2(double, double[])}.
*/
private static final int TWO_OVER_PI[] = {
0xa2f983, 0x6e4e44, 0x1529fc, 0x2757d1, 0xf534dd, 0xc0db62,
@@ -1272,7 +1272,7 @@ public final strictfp class StrictMath
/**
* Super precision for pi/2 in 24-bit chunks, for use in
* {@link #remPiOver2()}.
* {@link #remPiOver2(double, double[])}.
*/
private static final double PI_OVER_TWO[] = {
1.570796251296997, // Long bits 0x3ff921fb40000000L.
@@ -1286,8 +1286,8 @@ public final strictfp class StrictMath
};
/**
* More constants related to pi, used in {@link #remPiOver2()} and
* elsewhere.
* More constants related to pi, used in
* {@link #remPiOver2(double, double[])} and elsewhere.
*/
private static final double
PI_L = 1.2246467991473532e-16, // Long bits 0x3ca1a62633145c07L.
@@ -1301,7 +1301,7 @@ public final strictfp class StrictMath
/**
* Natural log and square root constants, for calculation of
* {@link #exp(double)}, {@link #log(double)} and
* {@link #power(double, double)}. CP is 2/(3*ln(2)).
* {@link #pow(double, double)}. CP is 2/(3*ln(2)).
*/
private static final double
SQRT_1_5 = 1.224744871391589, // Long bits 0x3ff3988e1409212eL.
+186 -21
View File
@@ -98,7 +98,7 @@ public final class String implements Serializable, Comparable, CharSequence
/**
* Stores unicode multi-character uppercase expansion table.
* @see #toUpperCase(char)
* @see #toUpperCase(Locale)
* @see CharData#UPPER_EXPAND
*/
private static final char[] upperExpand
@@ -139,7 +139,7 @@ public final class String implements Serializable, Comparable, CharSequence
final int offset;
/**
* An implementation for {@link CASE_INSENSITIVE_ORDER}.
* An implementation for {@link #CASE_INSENSITIVE_ORDER}.
* This must be {@link Serializable}. The class name is dictated by
* compatibility with Sun's JDK.
*/
@@ -233,6 +233,7 @@ public final class String implements Serializable, Comparable, CharSequence
* @param count the number of characters from data to copy
* @throws NullPointerException if data is null
* @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
* || offset + count &lt; 0 (overflow)
* || offset + count &gt; data.length)
* (while unspecified, this is a StringIndexOutOfBoundsException)
*/
@@ -256,6 +257,7 @@ public final class String implements Serializable, Comparable, CharSequence
* @param count the number of characters from ascii to copy
* @throws NullPointerException if ascii is null
* @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
* || offset + count &lt; 0 (overflow)
* || offset + count &gt; ascii.length)
* (while unspecified, this is a StringIndexOutOfBoundsException)
* @see #String(byte[])
@@ -267,8 +269,13 @@ public final class String implements Serializable, Comparable, CharSequence
*/
public String(byte[] ascii, int hibyte, int offset, int count)
{
if (offset < 0 || count < 0 || offset + count > ascii.length)
throw new StringIndexOutOfBoundsException();
if (offset < 0)
throw new StringIndexOutOfBoundsException("offset: " + offset);
if (count < 0)
throw new StringIndexOutOfBoundsException("count: " + count);
if (offset + count < 0 || offset + count > ascii.length)
throw new StringIndexOutOfBoundsException("offset + count: "
+ (offset + count));
value = new char[count];
this.offset = 0;
this.count = count;
@@ -327,8 +334,13 @@ public final class String implements Serializable, Comparable, CharSequence
public String(byte[] data, int offset, int count, String encoding)
throws UnsupportedEncodingException
{
if (offset < 0 || count < 0 || offset + count > data.length)
throw new StringIndexOutOfBoundsException();
if (offset < 0)
throw new StringIndexOutOfBoundsException("offset: " + offset);
if (count < 0)
throw new StringIndexOutOfBoundsException("count: " + count);
if (offset + count < 0 || offset + count > data.length)
throw new StringIndexOutOfBoundsException("offset + count: "
+ (offset + count));
try
{
CharsetDecoder csd = Charset.forName(encoding).newDecoder();
@@ -402,8 +414,13 @@ public final class String implements Serializable, Comparable, CharSequence
*/
public String(byte[] data, int offset, int count)
{
if (offset < 0 || count < 0 || offset + count > data.length)
throw new StringIndexOutOfBoundsException();
if (offset < 0)
throw new StringIndexOutOfBoundsException("offset: " + offset);
if (count < 0)
throw new StringIndexOutOfBoundsException("count: " + count);
if (offset + count < 0 || offset + count > data.length)
throw new StringIndexOutOfBoundsException("offset + count: "
+ (offset + count));
int o, c;
char[] v;
String encoding;
@@ -512,8 +529,13 @@ public final class String implements Serializable, Comparable, CharSequence
*/
String(char[] data, int offset, int count, boolean dont_copy)
{
if (offset < 0 || count < 0 || offset + count > data.length)
throw new StringIndexOutOfBoundsException();
if (offset < 0)
throw new StringIndexOutOfBoundsException("offset: " + offset);
if (count < 0)
throw new StringIndexOutOfBoundsException("count: " + count);
if (offset + count < 0 || offset + count > data.length)
throw new StringIndexOutOfBoundsException("offset + count: "
+ (offset + count));
if (dont_copy)
{
value = data;
@@ -553,6 +575,40 @@ public final class String implements Serializable, Comparable, CharSequence
return value[offset + index];
}
/**
* Get the code point at the specified index. This is like #charAt(int),
* but if the character is the start of a surrogate pair, and the
* following character completes the pair, then the corresponding
* supplementary code point is returned.
* @param index the index of the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public synchronized int codePointAt(int index)
{
// Use the CharSequence overload as we get better range checking
// this way.
return Character.codePointAt(this, index);
}
/**
* Get the code point before the specified index. This is like
* #codePointAt(int), but checks the characters at <code>index-1</code> and
* <code>index-2</code> to see if they form a supplementary code point.
* @param index the index just past the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* (while unspecified, this is a StringIndexOutOfBoundsException)
* @since 1.5
*/
public synchronized int codePointBefore(int index)
{
// Use the CharSequence overload as we get better range checking
// this way.
return Character.codePointBefore(this, index);
}
/**
* Copies characters from this String starting at a specified start index,
* ending at a specified stop index, to a character array starting at
@@ -628,21 +684,26 @@ public final class String implements Serializable, Comparable, CharSequence
ByteBuffer bbuf = cse.encode(CharBuffer.wrap(value, offset, count));
if(bbuf.hasArray())
return bbuf.array();
// Doubt this will happen. But just in case.
byte[] bytes = new byte[bbuf.remaining()];
bbuf.get(bytes);
return bytes;
} catch(IllegalCharsetNameException e){
throw new UnsupportedEncodingException("Encoding: "+enc+
" not found.");
} catch(UnsupportedCharsetException e){
throw new UnsupportedEncodingException("Encoding: "+enc+
" not found.");
} catch(CharacterCodingException e){
// XXX - Ignore coding exceptions? They shouldn't really happen.
return null;
}
catch(IllegalCharsetNameException e)
{
throw new UnsupportedEncodingException("Encoding: " + enc
+ " not found.");
}
catch(UnsupportedCharsetException e)
{
throw new UnsupportedEncodingException("Encoding: " + enc
+ " not found.");
}
catch(CharacterCodingException e)
{
// This shouldn't ever happen.
throw (InternalError) new InternalError().initCause(e);
}
}
@@ -725,6 +786,26 @@ public final class String implements Serializable, Comparable, CharSequence
}
}
/**
* Compares the given CharSequence to this String. This is true if
* the CharSequence has the same content as this String at this
* moment.
*
* @param seq the CharSequence to compare to
* @return true if CharSequence has the same character sequence
* @throws NullPointerException if the given CharSequence is null
* @since 1.5
*/
public boolean contentEquals(CharSequence seq)
{
if (seq.length() != count)
return false;
for (int i = 0; i < count; ++i)
if (value[offset + i] != seq.charAt(i))
return false;
return true;
}
/**
* Compares a String to this String, ignoring case. This does not handle
* multi-character capitalization exceptions; instead the comparison is
@@ -1546,6 +1627,7 @@ public final class String implements Serializable, Comparable, CharSequence
* @return String containing the chars from data[offset..offset+count]
* @throws NullPointerException if data is null
* @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
* || offset + count &lt; 0 (overflow)
* || offset + count &gt; data.length)
* (while unspecified, this is a StringIndexOutOfBoundsException)
* @see #String(char[], int, int)
@@ -1566,6 +1648,7 @@ public final class String implements Serializable, Comparable, CharSequence
* @return String containing the chars from data[offset..offset+count]
* @throws NullPointerException if data is null
* @throws IndexOutOfBoundsException if (offset &lt; 0 || count &lt; 0
* || offset + count &lt; 0 (overflow)
* || offset + count &gt; data.length)
* (while unspecified, this is a StringIndexOutOfBoundsException)
* @see #String(char[], int, int)
@@ -1676,6 +1759,49 @@ public final class String implements Serializable, Comparable, CharSequence
return VMString.intern(this);
}
/**
* Return the number of code points between two indices in the
* <code>StringBuffer</code>. An unpaired surrogate counts as a
* code point for this purpose. Characters outside the indicated
* range are not examined, even if the range ends in the middle of a
* surrogate pair.
*
* @param start the starting index
* @param end one past the ending index
* @return the number of code points
* @since 1.5
*/
public synchronized int codePointCount(int start, int end)
{
if (start < 0 || end >= count || start > end)
throw new StringIndexOutOfBoundsException();
start += offset;
end += offset;
int count = 0;
while (start < end)
{
char base = value[start];
if (base < Character.MIN_HIGH_SURROGATE
|| base > Character.MAX_HIGH_SURROGATE
|| start == end
|| start == count
|| value[start + 1] < Character.MIN_LOW_SURROGATE
|| value[start + 1] > Character.MAX_LOW_SURROGATE)
{
// Nothing.
}
else
{
// Surrogate pair.
++start;
}
++start;
++count;
}
return count;
}
/**
* Helper function used to detect which characters have a multi-character
* uppercase expansion. Note that this is only used in locations which
@@ -1747,4 +1873,43 @@ public final class String implements Serializable, Comparable, CharSequence
return value;
}
/**
* Returns true iff this String contains the sequence of Characters
* described in s.
* @param s the CharSequence
* @return true iff this String contains s
*/
public boolean contains (CharSequence s)
{
return this.indexOf(s.toString()) != -1;
}
/**
* Returns a string that is this string with all instances of the sequence
* represented by <code>target</code> replaced by the sequence in
* <code>replacement</code>.
* @param target the sequence to be replaced
* @param replacement the sequence used as the replacement
* @return the string constructed as above
*/
public String replace (CharSequence target, CharSequence replacement)
{
String targetString = target.toString();
String replaceString = replacement.toString();
int targetLength = target.length();
int replaceLength = replacement.length();
int startPos = this.indexOf(targetString);
StringBuilder result = new StringBuilder(this);
while (startPos != -1)
{
// Replace the target with the replacement
result.replace(startPos, startPos + targetLength, replaceString);
// Search for a new occurrence of the target
startPos = result.indexOf(targetString, startPos + replaceLength);
}
return result.toString();
}
}
+258 -1
View File
@@ -147,6 +147,24 @@ public final class StringBuffer implements Serializable, CharSequence
str.getChars(0, count, value, 0);
}
/**
* Create a new <code>StringBuffer</code> with the characters from the
* specified <code>CharSequence</code>. Initial capacity will be the
* size of the CharSequence plus 16.
*
* @param sequence the <code>String</code> to convert
* @throws NullPointerException if str is null
*
* @since 1.5
*/
public StringBuffer(CharSequence sequence)
{
count = Math.max(0, sequence.length());
value = new char[count + DEFAULT_CAPACITY];
for (int i = 0; i < count; ++i)
value[i] = sequence.charAt(i);
}
/**
* Get the length of the <code>String</code> this <code>StringBuffer</code>
* would create. Not to be confused with the <em>capacity</em> of the
@@ -234,7 +252,6 @@ public final class StringBuffer implements Serializable, CharSequence
* @param index the index of the character to get, starting at 0
* @return the character at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* (while unspecified, this is a StringIndexOutOfBoundsException)
*/
public synchronized char charAt(int index)
{
@@ -243,6 +260,39 @@ public final class StringBuffer implements Serializable, CharSequence
return value[index];
}
/**
* Get the code point at the specified index. This is like #charAt(int),
* but if the character is the start of a surrogate pair, and the
* following character completes the pair, then the corresponding
* supplementary code point is returned.
* @param index the index of the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public synchronized int codePointAt(int index)
{
return Character.codePointAt(value, index, count);
}
/**
* Get the code point before the specified index. This is like
* #codePointAt(int), but checks the characters at <code>index-1</code> and
* <code>index-2</code> to see if they form a supplementary code point.
* @param index the index just past the codepoint to get, starting at 0
* @return the codepoint at the specified index
* @throws IndexOutOfBoundsException if index is negative or &gt;= length()
* @since 1.5
*/
public synchronized int codePointBefore(int index)
{
// Character.codePointBefore() doesn't perform this check. We
// could use the CharSequence overload, but this is just as easy.
if (index >= count)
throw new IndexOutOfBoundsException();
return Character.codePointBefore(value, index, 1);
}
/**
* Get the specified array of characters. <code>srcOffset - srcEnd</code>
* characters will be copied into the array you pass in.
@@ -340,6 +390,46 @@ public final class StringBuffer implements Serializable, CharSequence
return this;
}
/**
* Append the <code>CharSequence</code> value of the argument to this
* <code>StringBuffer</code>.
*
* @param sequence the <code>CharSequence</code> to append
* @return this <code>StringBuffer</code>
* @see #append(Object)
* @since 1.5
*/
public synchronized StringBuffer append(CharSequence sequence)
{
if (sequence == null)
sequence = "null";
return append(sequence, 0, sequence.length());
}
/**
* Append the specified subsequence of the <code>CharSequence</code>
* argument to this <code>StringBuffer</code>.
*
* @param sequence the <code>CharSequence</code> to append
* @param start the starting index
* @param end one past the ending index
* @return this <code>StringBuffer</code>
* @see #append(Object)
* @since 1.5
*/
public synchronized StringBuffer append(CharSequence sequence,
int start, int end)
{
if (sequence == null)
sequence = "null";
if (start < 0 || end < 0 || start > end || end > sequence.length())
throw new IndexOutOfBoundsException();
ensureCapacity_unsynchronized(this.count + end - start);
for (int i = start; i < end; ++i)
value[count++] = sequence.charAt(i);
return this;
}
/**
* Append the <code>char</code> array to this <code>StringBuffer</code>.
* This is similar (but more efficient) than
@@ -406,6 +496,25 @@ public final class StringBuffer implements Serializable, CharSequence
return this;
}
/**
* Append the code point to this <code>StringBuffer</code>.
* This is like #append(char), but will append two characters
* if a supplementary code point is given.
*
* @param code the code point to append
* @return this <code>StringBuffer</code>
* @see Character#toChars(int, char[], int)
* @since 1.5
*/
public synchronized StringBuffer appendCodePoint(int code)
{
int len = Character.charCount(code);
ensureCapacity_unsynchronized(count + len);
Character.toChars(code, value, count);
count += len;
return this;
}
/**
* Append the <code>String</code> value of the argument to this
* <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
@@ -659,6 +768,54 @@ public final class StringBuffer implements Serializable, CharSequence
return this;
}
/**
* Insert the <code>CharSequence</code> argument into this
* <code>StringBuffer</code>. If the sequence is null, the String
* "null" is used instead.
*
* @param offset the place to insert in this buffer
* @param sequence the <code>CharSequence</code> to insert
* @return this <code>StringBuffer</code>
* @throws IndexOutOfBoundsException if offset is out of bounds
* @since 1.5
*/
public synchronized StringBuffer insert(int offset, CharSequence sequence)
{
if (sequence == null)
sequence = "null";
return insert(offset, sequence, 0, sequence.length());
}
/**
* Insert a subsequence of the <code>CharSequence</code> argument into this
* <code>StringBuffer</code>. If the sequence is null, the String
* "null" is used instead.
*
* @param offset the place to insert in this buffer
* @param sequence the <code>CharSequence</code> to insert
* @param start the starting index of the subsequence
* @param end one past the ending index of the subsequence
* @return this <code>StringBuffer</code>
* @throws IndexOutOfBoundsException if offset, start,
* or end are out of bounds
* @since 1.5
*/
public synchronized StringBuffer insert(int offset, CharSequence sequence,
int start, int end)
{
if (sequence == null)
sequence = "null";
if (start < 0 || end < 0 || start > end || end > sequence.length())
throw new IndexOutOfBoundsException();
int len = end - start;
ensureCapacity_unsynchronized(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
for (int i = start; i < end; ++i)
value[offset++] = sequence.charAt(i);
count += len;
return this;
}
/**
* Insert the <code>char[]</code> argument into this
* <code>StringBuffer</code>.
@@ -879,6 +1036,106 @@ public final class StringBuffer implements Serializable, CharSequence
return new String(this);
}
/**
* This may reduce the amount of memory used by the StringBuffer,
* by resizing the internal array to remove unused space. However,
* this method is not required to resize, so this behavior cannot
* be relied upon.
* @since 1.5
*/
public synchronized void trimToSize()
{
int wouldSave = value.length - count;
// Some random heuristics: if we save less than 20 characters, who
// cares.
if (wouldSave < 20)
return;
// If we save more than 200 characters, shrink.
// If we save more than 1/4 of the buffer, shrink.
if (wouldSave > 200 || wouldSave * 4 > value.length)
{
char[] newValue = new char[count];
VMSystem.arraycopy(value, 0, newValue, 0, count);
value = newValue;
}
}
/**
* Return the number of code points between two indices in the
* <code>StringBuffer</code>. An unpaired surrogate counts as a
* code point for this purpose. Characters outside the indicated
* range are not examined, even if the range ends in the middle of a
* surrogate pair.
*
* @param start the starting index
* @param end one past the ending index
* @return the number of code points
* @since 1.5
*/
public synchronized int codePointCount(int start, int end)
{
if (start < 0 || end >= count || start > end)
throw new StringIndexOutOfBoundsException();
int count = 0;
while (start < end)
{
char base = value[start];
if (base < Character.MIN_HIGH_SURROGATE
|| base > Character.MAX_HIGH_SURROGATE
|| start == end
|| start == count
|| value[start + 1] < Character.MIN_LOW_SURROGATE
|| value[start + 1] > Character.MAX_LOW_SURROGATE)
{
// Nothing.
}
else
{
// Surrogate pair.
++start;
}
++start;
++count;
}
return count;
}
/**
* Starting at the given index, this counts forward by the indicated
* number of code points, and then returns the resulting index. An
* unpaired surrogate counts as a single code point for this
* purpose.
*
* @param start the starting index
* @param codePoints the number of code points
* @return the resulting index
* @since 1.5
*/
public synchronized int offsetByCodePoints(int start, int codePoints)
{
while (codePoints > 0)
{
char base = value[start];
if (base < Character.MIN_HIGH_SURROGATE
|| base > Character.MAX_HIGH_SURROGATE
|| start == count
|| value[start + 1] < Character.MIN_LOW_SURROGATE
|| value[start + 1] > Character.MAX_LOW_SURROGATE)
{
// Nothing.
}
else
{
// Surrogate pair.
++start;
}
++start;
--codePoints;
}
return start;
}
/**
* An unsynchronized version of ensureCapacity, used internally to avoid
* the cost of a second lock on the same object. This also has the side
@@ -463,6 +463,25 @@ public final class StringBuilder
return this;
}
/**
* Append the code point to this <code>StringBuilder</code>.
* This is like #append(char), but will append two characters
* if a supplementary code point is given.
*
* @param code the code point to append
* @return this <code>StringBuilder</code>
* @see Character#toChars(int, char[], int)
* @since 1.5
*/
public synchronized StringBuilder appendCodePoint(int code)
{
int len = Character.charCount(code);
ensureCapacity(count + len);
Character.toChars(code, value, count);
count += len;
return this;
}
/**
* Append the <code>String</code> value of the argument to this
* <code>StringBuilder</code>. Uses <code>String.valueOf()</code> to convert
@@ -704,6 +723,52 @@ public final class StringBuilder
return this;
}
/**
* Insert the <code>CharSequence</code> argument into this
* <code>StringBuilder</code>. If the sequence is null, the String
* "null" is used instead.
*
* @param offset the place to insert in this buffer
* @param sequence the <code>CharSequence</code> to insert
* @return this <code>StringBuilder</code>
* @throws IndexOutOfBoundsException if offset is out of bounds
*/
public synchronized StringBuilder insert(int offset, CharSequence sequence)
{
if (sequence == null)
sequence = "null";
return insert(offset, sequence, 0, sequence.length());
}
/**
* Insert a subsequence of the <code>CharSequence</code> argument into this
* <code>StringBuilder</code>. If the sequence is null, the String
* "null" is used instead.
*
* @param offset the place to insert in this buffer
* @param sequence the <code>CharSequence</code> to insert
* @param start the starting index of the subsequence
* @param end one past the ending index of the subsequence
* @return this <code>StringBuilder</code>
* @throws IndexOutOfBoundsException if offset, start,
* or end are out of bounds
*/
public synchronized StringBuilder insert(int offset, CharSequence sequence,
int start, int end)
{
if (sequence == null)
sequence = "null";
if (start < 0 || end < 0 || start > end || end > sequence.length())
throw new IndexOutOfBoundsException();
int len = end - start;
ensureCapacity(count + len);
VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
for (int i = start; i < end; ++i)
value[offset++] = sequence.charAt(i);
count += len;
return this;
}
/**
* Insert the <code>char[]</code> argument into this
* <code>StringBuilder</code>.
+1 -1
View File
@@ -464,7 +464,7 @@ public final class System
*
* @param finalizeOnExit whether to run finalizers on exit
* @throws SecurityException if permission is denied
* @see Runtime#runFinalizersOnExit()
* @see Runtime#runFinalizersOnExit(boolean)
* @since 1.1
* @deprecated never rely on finalizers to do a clean, thread-safe,
* mop-up from your code
+8 -4
View File
@@ -38,6 +38,7 @@ exception statement from your version. */
package java.lang;
import java.security.Permission;
import java.util.Map;
import java.util.WeakHashMap;
@@ -704,7 +705,7 @@ public class Thread implements Runnable
*
* @return the context class loader
* @throws SecurityException when permission is denied
* @see setContextClassLoader(ClassLoader)
* @see #setContextClassLoader(ClassLoader)
* @since 1.2
*/
public synchronized ClassLoader getContextClassLoader()
@@ -726,7 +727,7 @@ public class Thread implements Runnable
*
* @param classloader the new context class loader
* @throws SecurityException when permission is denied
* @see getContextClassLoader()
* @see #getContextClassLoader()
* @since 1.2
*/
public synchronized void setContextClassLoader(ClassLoader classloader)
@@ -812,8 +813,11 @@ public class Thread implements Runnable
{
// Check parameters
if (ms < 0 || ns < 0 || ns > 999999)
throw new IllegalArgumentException();
if (ms < 0 )
throw new IllegalArgumentException("Negative milliseconds: " + ms);
if (ns < 0 || ns > 999999)
throw new IllegalArgumentException("Nanoseconds ouf of range: " + ns);
// Really sleep
VMThread.sleep(ms, ns);
@@ -38,7 +38,6 @@ exception statement from your version. */
package java.lang;
import java.util.Map;
import java.util.WeakHashMap;
/**
@@ -68,7 +68,7 @@ package java.lang.ref;
* work. It is useful to keep track, when an object is finalized.
*
* @author Jochen Hoenicke
* @see java.util.WeakHashtable
* @see java.util.WeakHashMap
*/
public abstract class Reference
{
@@ -104,7 +104,7 @@ public abstract class Reference
* Creates a new reference that is not registered to any queue.
* Since it is package private, it is not possible to overload this
* class in a different package.
* @param referent the object we refer to.
* @param ref the object we refer to.
*/
Reference(Object ref)
{
@@ -115,7 +115,7 @@ public abstract class Reference
* Creates a reference that is registered to a queue. Since this is
* package private, it is not possible to overload this class in a
* different package.
* @param referent the object we refer to.
* @param ref the object we refer to.
* @param q the reference queue to register on.
* @exception NullPointerException if q is null.
*/
@@ -52,7 +52,7 @@ package java.lang.ref;
* automatically cleared, and you may remove it from the set. <br>
*
* @author Jochen Hoenicke
* @see java.util.WeakHashtable
* @see java.util.WeakHashMap
*/
public class WeakReference
extends Reference

Some files were not shown because too many files have changed in this diff Show More