提交 f82929a3 编写于 作者: L lana

Merge

/*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -72,10 +72,6 @@ public class GenerateCurrencyData {
private static String formatVersion;
private static String dataVersion;
private static String validCurrencyCodes;
private static String currenciesWith0MinorUnitDecimals;
private static String currenciesWith1MinorUnitDecimal;
private static String currenciesWith3MinorUnitDecimal;
private static String currenciesWithMinorUnitsUndefined;
// handy constants - must match definitions in java.util.Currency
// magic number
......@@ -83,29 +79,31 @@ public class GenerateCurrencyData {
// number of characters from A to Z
private static final int A_TO_Z = ('Z' - 'A') + 1;
// entry for invalid country codes
private static final int INVALID_COUNTRY_ENTRY = 0x007F;
private static final int INVALID_COUNTRY_ENTRY = 0x0000007F;
// entry for countries without currency
private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x0080;
private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x00000200;
// mask for simple case country entries
private static final int SIMPLE_CASE_COUNTRY_MASK = 0x0000;
private static final int SIMPLE_CASE_COUNTRY_MASK = 0x00000000;
// mask for simple case country entry final character
private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x001F;
private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x0000001F;
// mask for simple case country entry default currency digits
private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x0060;
private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x000001E0;
// shift count for simple case country entry default currency digits
private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5;
// maximum number for simple case country entry default currency digits
private static final int SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS = 9;
// mask for special case country entries
private static final int SPECIAL_CASE_COUNTRY_MASK = 0x0080;
private static final int SPECIAL_CASE_COUNTRY_MASK = 0x00000200;
// mask for special case country index
private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x001F;
private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x0000001F;
// delta from entry index component in main table to index into special case tables
private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1;
// mask for distinguishing simple and special case countries
private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK | SPECIAL_CASE_COUNTRY_MASK;
// mask for the numeric code of the currency
private static final int NUMERIC_CODE_MASK = 0x0003FF00;
private static final int NUMERIC_CODE_MASK = 0x000FFC00;
// shift count for the numeric code of the currency
private static final int NUMERIC_CODE_SHIFT = 8;
private static final int NUMERIC_CODE_SHIFT = 10;
// generated data
private static int[] mainTable = new int[A_TO_Z * A_TO_Z];
......@@ -120,7 +118,7 @@ public class GenerateCurrencyData {
private static int[] specialCaseOldCurrenciesNumericCode = new int[maxSpecialCases];
private static int[] specialCaseNewCurrenciesNumericCode = new int[maxSpecialCases];
private static final int maxOtherCurrencies = 70;
private static final int maxOtherCurrencies = 128;
private static int otherCurrenciesCount = 0;
private static StringBuffer otherCurrencies = new StringBuffer();
private static int[] otherCurrenciesDefaultFractionDigits = new int[maxOtherCurrencies];
......@@ -129,6 +127,11 @@ public class GenerateCurrencyData {
// date format for parsing cut-over times
private static SimpleDateFormat format;
// Minor Units
private static String[] currenciesWithDefinedMinorUnitDecimals =
new String[SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS + 1];
private static String currenciesWithMinorUnitsUndefined;
public static void main(String[] args) {
// Look for "-o outputfilename" option
......@@ -171,16 +174,14 @@ public class GenerateCurrencyData {
formatVersion = (String) currencyData.get("formatVersion");
dataVersion = (String) currencyData.get("dataVersion");
validCurrencyCodes = (String) currencyData.get("all");
currenciesWith0MinorUnitDecimals = (String) currencyData.get("minor0");
currenciesWith1MinorUnitDecimal = (String) currencyData.get("minor1");
currenciesWith3MinorUnitDecimal = (String) currencyData.get("minor3");
for (int i = 0; i <= SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS; i++) {
currenciesWithDefinedMinorUnitDecimals[i]
= (String) currencyData.get("minor"+i);
}
currenciesWithMinorUnitsUndefined = (String) currencyData.get("minorUndefined");
if (formatVersion == null ||
dataVersion == null ||
validCurrencyCodes == null ||
currenciesWith0MinorUnitDecimals == null ||
currenciesWith1MinorUnitDecimal == null ||
currenciesWith3MinorUnitDecimal == null ||
currenciesWithMinorUnitsUndefined == null) {
throw new NullPointerException("not all required data is defined in input");
}
......@@ -207,7 +208,7 @@ public class GenerateCurrencyData {
if (currencyInfo.charAt(0) == firstChar && currencyInfo.charAt(1) == secondChar) {
checkCurrencyCode(currencyInfo);
int digits = getDefaultFractionDigits(currencyInfo);
if (digits < 0 || digits > 3) {
if (digits < 0 || digits > SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS) {
throw new RuntimeException("fraction digits out of range for " + currencyInfo);
}
int numericCode= getNumericCode(currencyInfo);
......@@ -231,13 +232,14 @@ public class GenerateCurrencyData {
}
private static int getDefaultFractionDigits(String currencyCode) {
if (currenciesWith0MinorUnitDecimals.indexOf(currencyCode) != -1) {
return 0;
} else if (currenciesWith1MinorUnitDecimal.indexOf(currencyCode) != -1) {
return 1;
} else if (currenciesWith3MinorUnitDecimal.indexOf(currencyCode) != -1) {
return 3;
} else if (currenciesWithMinorUnitsUndefined.indexOf(currencyCode) != -1) {
for (int i = 0; i <= SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS; i++) {
if (currenciesWithDefinedMinorUnitDecimals[i] != null &&
currenciesWithDefinedMinorUnitDecimals[i].indexOf(currencyCode) != -1) {
return i;
}
}
if (currenciesWithMinorUnitsUndefined.indexOf(currencyCode) != -1) {
return -1;
} else {
return 2;
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -68,8 +68,9 @@ public abstract class AquaBorder implements Border, UIResource {
painter.state.set(size);
}
@Override
public Insets getBorderInsets(final Component c) {
return sizeVariant.margins;
return (Insets) sizeVariant.margins.clone();
}
protected AquaBorder deriveBorderForSize(final Size size) {
......@@ -130,8 +131,10 @@ public abstract class AquaBorder implements Border, UIResource {
return (focusable != null && focusable instanceof JComponent && ((JComponent)focusable).hasFocus());
}
@Override
public boolean isBorderOpaque() { return false; }
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) {
painter.paint(g, c, x, y, w, h);
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -1089,8 +1089,15 @@ public class AquaFileChooserUI extends FileChooserUI {
super(f);
}
public Component getTableCellRendererComponent(final JTable list, final Object value, final boolean isSelected, final boolean cellHasFocus, final int index, final int col) {
super.getTableCellRendererComponent(list, value, isSelected, false, index, col); // No focus border, thanks
public Component getTableCellRendererComponent(final JTable list,
final Object value,
final boolean isSelected,
final boolean cellHasFocus,
final int index,
final int col) {
super.getTableCellRendererComponent(list, value, isSelected, false,
index,
col); // No focus border, thanks
final File file = (File)value;
final JFileChooser fc = getFileChooser();
setText(fc.getName(file));
......@@ -1105,8 +1112,14 @@ public class AquaFileChooserUI extends FileChooserUI {
super(f);
}
public Component getTableCellRendererComponent(final JTable list, final Object value, final boolean isSelected, final boolean cellHasFocus, final int index, final int col) {
super.getTableCellRendererComponent(list, value, isSelected, false, index, col);
public Component getTableCellRendererComponent(final JTable list,
final Object value,
final boolean isSelected,
final boolean cellHasFocus,
final int index,
final int col) {
super.getTableCellRendererComponent(list, value, isSelected, false,
index, col);
final File file = (File)fFileList.getValueAt(index, 0);
setEnabled(isSelectableInList(file));
final DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT);
......@@ -1122,14 +1135,17 @@ public class AquaFileChooserUI extends FileChooserUI {
}
}
@Override
public Dimension getPreferredSize(final JComponent c) {
return PREF_SIZE;
return new Dimension(PREF_WIDTH, PREF_HEIGHT);
}
@Override
public Dimension getMinimumSize(final JComponent c) {
return MIN_SIZE;
return new Dimension(MIN_WIDTH, MIN_HEIGHT);
}
@Override
public Dimension getMaximumSize(final JComponent c) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
......@@ -1793,12 +1809,8 @@ public class AquaFileChooserUI extends FileChooserUI {
private static final int PREF_WIDTH = 550;
private static final int PREF_HEIGHT = 400;
private static final Dimension PREF_SIZE = new Dimension(PREF_WIDTH, PREF_HEIGHT);
private static final int MIN_WIDTH = 400;
private static final int MIN_HEIGHT = 250;
private static final Dimension MIN_SIZE = new Dimension(MIN_WIDTH, MIN_HEIGHT);
private static final int LIST_MIN_WIDTH = 400;
private static final int LIST_MIN_HEIGHT = 100;
private static final Dimension LIST_MIN_SIZE = new Dimension(LIST_MIN_WIDTH, LIST_MIN_HEIGHT);
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -25,46 +25,33 @@
package com.apple.laf;
import java.awt.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.border.Border;
import sun.swing.SwingUtilities2;
/**
* The class represents the border of a {@code JMenuBar}.
*/
public class AquaMenuBarBorder implements Border {
public AquaMenuBarBorder() {
super();
}
/**
* Paints the border for the specified component with the specified
* position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
// for now we don't paint a border. We let the button paint it since there
// needs to be a strict ordering for aqua components.
//paintButton(c, g, x, y, width, height);
@Override
public void paintBorder(final Component c, final Graphics g, final int x,
final int y, final int width, final int height) {
g.setColor(Color.gray);
g.drawLine(x, y + height - 1, x + width, y + height - 1);
SwingUtilities2.drawHLine(g, x, x + width - 1, y + height - 1);
}
/**
* Returns the insets of the border.
* @param c the component for which this border insets value applies
*/
@Override
public Insets getBorderInsets(final Component c) {
return new Insets(0, 0, 1, 0);
}
/**
* Returns whether or not the border is opaque. If the border
* is opaque, it is responsible for filling in it's own
* background when painting.
*/
@Override
public boolean isBorderOpaque() {
return false;
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -132,7 +132,9 @@ final class LWCheckboxPeer
@Override
public void setState(final boolean state) {
synchronized (getDelegateLock()) {
getDelegate().getCurrentButton().removeItemListener(this);
getDelegate().setSelected(state);
getDelegate().getCurrentButton().addItemListener(this);
}
repaintPeer();
}
......
/*
* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -28,7 +28,6 @@
//#define USE_VERBOSE_TRACE
#include <AudioUnit/AudioUnit.h>
#include <CoreServices/CoreServices.h>
#include <AudioToolbox/AudioConverter.h>
#include <pthread.h>
#include <math.h>
......@@ -617,7 +616,7 @@ struct OSX_DirectAudioDevice {
~OSX_DirectAudioDevice() {
if (audioUnit) {
CloseComponent(audioUnit);
AudioComponentInstanceDispose(audioUnit);
}
if (resampler) {
delete resampler;
......@@ -629,17 +628,16 @@ static AudioUnit CreateOutputUnit(AudioDeviceID deviceID, int isSource)
{
OSStatus err;
AudioUnit unit;
UInt32 size;
ComponentDescription desc;
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = (deviceID == 0 && isSource) ? kAudioUnitSubType_DefaultOutput : kAudioUnitSubType_HALOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
Component comp = FindNextComponent(NULL, &desc);
err = OpenAComponent(comp, &unit);
AudioComponent comp = AudioComponentFindNext(NULL, &desc);
err = AudioComponentInstanceNew(comp, &unit);
if (err) {
OS_ERROR0(err, "CreateOutputUnit:OpenAComponent");
......@@ -664,7 +662,7 @@ static AudioUnit CreateOutputUnit(AudioDeviceID deviceID, int isSource)
// get real AudioDeviceID for default input device (macosx current input device)
deviceID = GetDefaultDevice(isSource);
if (!deviceID) {
CloseComponent(unit);
AudioComponentInstanceDispose(unit);
return NULL;
}
}
......@@ -675,7 +673,7 @@ static AudioUnit CreateOutputUnit(AudioDeviceID deviceID, int isSource)
0, &deviceID, sizeof(deviceID));
if (err) {
OS_ERROR0(err, "SetProperty (CurrentDevice)");
CloseComponent(unit);
AudioComponentInstanceDispose(unit);
return NULL;
}
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -28,8 +28,6 @@
#import <Cocoa/Cocoa.h>
#import <JavaNativeFoundation/JavaNativeFoundation.h>
#import <CoreServices/CoreServices.h>
#import <AudioToolbox/AudioToolbox.h>
#define DEBUG 1
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -43,8 +43,6 @@ import org.w3c.dom.Node;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.SampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
......@@ -1048,7 +1046,13 @@ public class JPEGImageWriter extends ImageWriter {
// Call the writer, who will call back for every scanline
processImageStarted(currentImage);
clearAbortRequest();
cbLock.lock();
try {
processImageStarted(currentImage);
} finally {
cbLock.unlock();
}
boolean aborted = false;
......@@ -1100,6 +1104,11 @@ public class JPEGImageWriter extends ImageWriter {
currentImage++; // After a successful write
}
@Override
public boolean canWriteSequence() {
return true;
}
public void prepareWriteSequence(IIOMetadata streamMetadata)
throws IOException {
setThreadLock();
......@@ -1225,6 +1234,23 @@ public class JPEGImageWriter extends ImageWriter {
}
}
@Override
protected synchronized void clearAbortRequest() {
setThreadLock();
try {
cbLock.check();
if (abortRequested()) {
super.clearAbortRequest();
// reset C structures
resetWriter(structPointer);
// reset the native destination
setDest(structPointer);
}
} finally {
clearThreadLock();
}
}
private void resetInternalState() {
// reset C structures
resetWriter(structPointer);
......
......@@ -100,7 +100,8 @@ class GTKFileChooserUI extends SynthFileChooserUI {
private static Dimension prefListSize = new Dimension(75, 150);
private static Dimension PREF_SIZE = new Dimension(435, 360);
private static Dimension MIN_SIZE = new Dimension(200, 300);
private static final int MIN_WIDTH = 200;
private static final int MIN_HEIGHT = 300;
private static Dimension ZERO_ACC_SIZE = new Dimension(1, 1);
......@@ -1038,6 +1039,7 @@ class GTKFileChooserUI extends SynthFileChooserUI {
}
}
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension prefSize = new Dimension(PREF_SIZE);
JComponent accessory = getFileChooser().getAccessory();
......@@ -1053,10 +1055,12 @@ class GTKFileChooserUI extends SynthFileChooserUI {
}
}
public Dimension getMinimumSize(JComponent x) {
return new Dimension(MIN_SIZE);
@Override
public Dimension getMinimumSize(JComponent x) {
return new Dimension(MIN_WIDTH, MIN_HEIGHT);
}
@Override
public Dimension getMaximumSize(JComponent x) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -65,8 +65,8 @@ public class MotifFileChooserUI extends BasicFileChooserUI {
private static Dimension WITH_ACCELERATOR_PREF_SIZE = new Dimension(650, 450);
private static Dimension PREF_SIZE = new Dimension(350, 450);
private static Dimension MIN_SIZE = new Dimension(200, 300);
private static final int MIN_WIDTH = 200;
private static final int MIN_HEIGHT = 300;
private static Dimension PREF_ACC_SIZE = new Dimension(10, 10);
private static Dimension ZERO_ACC_SIZE = new Dimension(1, 1);
......@@ -615,6 +615,7 @@ public class MotifFileChooserUI extends BasicFileChooserUI {
return scrollpane;
}
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension prefSize =
(getFileChooser().getAccessory() != null) ? WITH_ACCELERATOR_PREF_SIZE : PREF_SIZE;
......@@ -627,10 +628,12 @@ public class MotifFileChooserUI extends BasicFileChooserUI {
}
}
public Dimension getMinimumSize(JComponent x) {
return MIN_SIZE;
@Override
public Dimension getMinimumSize(JComponent x) {
return new Dimension(MIN_WIDTH, MIN_HEIGHT);
}
@Override
public Dimension getMaximumSize(JComponent x) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
......
......@@ -93,7 +93,6 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
private static int MIN_WIDTH = 425;
private static int MIN_HEIGHT = 245;
private static Dimension MIN_SIZE = new Dimension(MIN_WIDTH, MIN_HEIGHT);
private static int LIST_PREF_WIDTH = 444;
private static int LIST_PREF_HEIGHT = 138;
......@@ -631,6 +630,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
* @return a <code>Dimension</code> specifying the preferred
* width and height of the file chooser
*/
@Override
public Dimension getPreferredSize(JComponent c) {
int prefWidth = PREF_SIZE.width;
Dimension d = c.getLayout().preferredLayoutSize(c);
......@@ -649,8 +649,9 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
* @return a <code>Dimension</code> specifying the minimum
* width and height of the file chooser
*/
@Override
public Dimension getMinimumSize(JComponent c) {
return MIN_SIZE;
return new Dimension(MIN_WIDTH, MIN_HEIGHT);
}
/**
......@@ -660,6 +661,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI {
* @return a <code>Dimension</code> specifying the maximum
* width and height of the file chooser
*/
@Override
public Dimension getMaximumSize(JComponent c) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
......
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -130,6 +130,15 @@ final public class InterfaceTypeImpl extends InvokableTypeImpl
return null;
}
@Override
boolean isAssignableTo(ReferenceType type) {
if (type.name().equals("java.lang.Object")) {
// interfaces are always assignable to j.l.Object
return true;
}
return super.isAssignableTo(type);
}
@Override
List<InterfaceType> interfaces() {
return superinterfaces();
......@@ -140,4 +149,4 @@ final public class InterfaceTypeImpl extends InvokableTypeImpl
// method must be directly in this interface
return this.equals(method.declaringType());
}
}
\ No newline at end of file
}
......@@ -28,6 +28,7 @@ package java.awt;
import java.awt.image.BufferedImage;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Locale;
import sun.font.FontManager;
......@@ -160,43 +161,38 @@ public abstract class GraphicsEnvironment {
*/
private static boolean getHeadlessProperty() {
if (headless == null) {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Object>() {
public Object run() {
String nm = System.getProperty("java.awt.headless");
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
String nm = System.getProperty("java.awt.headless");
if (nm == null) {
/* No need to ask for DISPLAY when run in a browser */
if (System.getProperty("javaplugin.version") != null) {
headless = defaultHeadless = Boolean.FALSE;
if (nm == null) {
/* No need to ask for DISPLAY when run in a browser */
if (System.getProperty("javaplugin.version") != null) {
headless = defaultHeadless = Boolean.FALSE;
} else {
String osName = System.getProperty("os.name");
if (osName.contains("OS X") && "sun.awt.HToolkit".equals(
System.getProperty("awt.toolkit")))
{
headless = defaultHeadless = Boolean.TRUE;
} else {
String osName = System.getProperty("os.name");
if (osName.contains("OS X") && "sun.awt.HToolkit".equals(
System.getProperty("awt.toolkit")))
{
headless = defaultHeadless = Boolean.TRUE;
} else {
headless = defaultHeadless =
Boolean.valueOf(("Linux".equals(osName) ||
"SunOS".equals(osName) ||
"FreeBSD".equals(osName) ||
"NetBSD".equals(osName) ||
"OpenBSD".equals(osName) ||
"AIX".equals(osName)) &&
(System.getenv("DISPLAY") == null));
}
final String display = System.getenv("DISPLAY");
headless = defaultHeadless =
("Linux".equals(osName) ||
"SunOS".equals(osName) ||
"FreeBSD".equals(osName) ||
"NetBSD".equals(osName) ||
"OpenBSD".equals(osName) ||
"AIX".equals(osName)) &&
(display == null || display.trim().isEmpty());
}
} else if (nm.equals("true")) {
headless = Boolean.TRUE;
} else {
headless = Boolean.FALSE;
}
return null;
}
} else {
headless = Boolean.valueOf(nm);
}
);
return null;
});
}
return headless.booleanValue();
return headless;
}
/**
......
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -181,7 +181,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
* removed from the menu bar, and replaced with the specified menu.
* @param m the menu to be set as the help menu
*/
public void setHelpMenu(Menu m) {
public void setHelpMenu(final Menu m) {
synchronized (getTreeLock()) {
if (helpMenu == m) {
return;
......@@ -189,11 +189,11 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
if (helpMenu != null) {
remove(helpMenu);
}
if (m.parent != this) {
add(m);
}
helpMenu = m;
if (m != null) {
if (m.parent != this) {
add(m);
}
m.isHelpMenu = true;
m.parent = this;
MenuBarPeer peer = (MenuBarPeer)this.peer;
......@@ -242,7 +242,7 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
* @param index the position of the menu to be removed.
* @see java.awt.MenuBar#add(java.awt.Menu)
*/
public void remove(int index) {
public void remove(final int index) {
synchronized (getTreeLock()) {
Menu m = getMenu(index);
menus.removeElementAt(index);
......@@ -252,6 +252,10 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible
m.parent = null;
peer.delMenu(index);
}
if (helpMenu == m) {
helpMenu = null;
m.isHelpMenu = false;
}
}
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -25,26 +25,23 @@
package java.awt.image;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.ImageCapabilities;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Point2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
import java.util.Set;
import java.util.Vector;
import sun.awt.image.BytePackedRaster;
import sun.awt.image.ShortComponentRaster;
import sun.awt.image.ByteComponentRaster;
import sun.awt.image.BytePackedRaster;
import sun.awt.image.IntegerComponentRaster;
import sun.awt.image.OffScreenImageSource;
import sun.awt.image.ShortComponentRaster;
/**
*
......@@ -68,18 +65,14 @@ import sun.awt.image.OffScreenImageSource;
* @see Raster
* @see WritableRaster
*/
public class BufferedImage extends java.awt.Image
implements WritableRenderedImage, Transparency
{
int imageType = TYPE_CUSTOM;
ColorModel colorModel;
WritableRaster raster;
OffScreenImageSource osis;
Hashtable properties;
boolean isAlphaPremultiplied;// If true, alpha has been premultiplied in
// color channels
private int imageType = TYPE_CUSTOM;
private ColorModel colorModel;
private final WritableRaster raster;
private OffScreenImageSource osis;
private Hashtable<String, Object> properties;
/**
* Image Type Constants
......@@ -328,8 +321,8 @@ public class BufferedImage extends java.awt.Image
0x000000ff, // Blue
0x0 // Alpha
);
raster = colorModel.createCompatibleWritableRaster(width,
height);
raster = colorModel.createCompatibleWritableRaster(width,
height);
}
break;
......@@ -355,9 +348,8 @@ public class BufferedImage extends java.awt.Image
true, // Alpha Premultiplied
DataBuffer.TYPE_INT
);
raster = colorModel.createCompatibleWritableRaster(width,
height);
raster = colorModel.createCompatibleWritableRaster(width,
height);
}
break;
......@@ -368,8 +360,8 @@ public class BufferedImage extends java.awt.Image
0x0000ff00, // Green
0x00ff0000 // Blue
);
raster = colorModel.createCompatibleWritableRaster(width,
height);
raster = colorModel.createCompatibleWritableRaster(width,
height);
}
break;
......@@ -642,7 +634,14 @@ public class BufferedImage extends java.awt.Image
colorModel = cm;
this.raster = raster;
this.properties = properties;
if (properties != null && !properties.isEmpty()) {
this.properties = new Hashtable<>();
for (final Object key : properties.keySet()) {
if (key instanceof String) {
this.properties.put((String) key, properties.get(key));
}
}
}
int numBands = raster.getNumBands();
boolean isAlphaPre = cm.isAlphaPremultiplied();
final boolean isStandard = isStandard(cm, raster);
......@@ -1272,7 +1271,11 @@ public class BufferedImage extends java.awt.Image
* or <code>null</code> if no property names are recognized.
*/
public String[] getPropertyNames() {
return null;
if (properties == null || properties.isEmpty()) {
return null;
}
final Set<String> keys = properties.keySet();
return keys.toArray(new String[keys.size()]);
}
/**
......
<!--
Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
......@@ -147,8 +147,8 @@ you register it using the
For overview, architecture, and tutorial documentation, please see:
<ul>
<li><a href="http://java.sun.com/docs/books/tutorial/javabeans/">JavaBeans</a>, a trail in <em>The Java Tutorial</em>.
<li><a href="http://java.sun.com/products/jfc/tsc/articles/persistence2/">Long-Term Persistence</a>, an article in <em>The Swing Connection</em>.
<li><a href="http://docs.oracle.com/javase/tutorial/javabeans/">JavaBeans</a>, a trail in <em>The Java Tutorial</em>.
<li><a href="http://www.oracle.com/technetwork/java/persistence2-141443.html">Long-Term Persistence</a>, an article in <em>The Swing Connection</em>.
</ul>
<p>
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -139,11 +139,11 @@ public final class Currency implements Serializable {
// - maps country code to 32-bit int
// - 26*26 entries, corresponding to [A-Z]*[A-Z]
// - \u007F -> not valid country
// - bits 18-31: unused
// - bits 8-17: numeric code (0 to 1023)
// - bit 7: 1 - special case, bits 0-4 indicate which one
// - bits 20-31: unused
// - bits 10-19: numeric code (0 to 1023)
// - bit 9: 1 - special case, bits 0-4 indicate which one
// 0 - simple country, bits 0-4 indicate final char of currency code
// - bits 5-6: fraction digits for simple countries, 0 for special cases
// - bits 5-8: fraction digits for simple countries, 0 for special cases
// - bits 0-4: final char for currency code for simple country, or ID of special case
// - special case IDs:
// - 0: country has no currency
......@@ -181,32 +181,34 @@ public final class Currency implements Serializable {
// number of characters from A to Z
private static final int A_TO_Z = ('Z' - 'A') + 1;
// entry for invalid country codes
private static final int INVALID_COUNTRY_ENTRY = 0x007F;
private static final int INVALID_COUNTRY_ENTRY = 0x0000007F;
// entry for countries without currency
private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x0080;
private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x00000200;
// mask for simple case country entries
private static final int SIMPLE_CASE_COUNTRY_MASK = 0x0000;
private static final int SIMPLE_CASE_COUNTRY_MASK = 0x00000000;
// mask for simple case country entry final character
private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x001F;
private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x0000001F;
// mask for simple case country entry default currency digits
private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x0060;
private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x000001E0;
// shift count for simple case country entry default currency digits
private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5;
// maximum number for simple case country entry default currency digits
private static final int SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS = 9;
// mask for special case country entries
private static final int SPECIAL_CASE_COUNTRY_MASK = 0x0080;
private static final int SPECIAL_CASE_COUNTRY_MASK = 0x00000200;
// mask for special case country index
private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x001F;
private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x0000001F;
// delta from entry index component in main table to index into special case tables
private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1;
// mask for distinguishing simple and special case countries
private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK | SPECIAL_CASE_COUNTRY_MASK;
// mask for the numeric code of the currency
private static final int NUMERIC_CODE_MASK = 0x0003FF00;
private static final int NUMERIC_CODE_MASK = 0x000FFC00;
// shift count for the numeric code of the currency
private static final int NUMERIC_CODE_SHIFT = 8;
private static final int NUMERIC_CODE_SHIFT = 10;
// Currency data format version
private static final int VALID_FORMAT_VERSION = 1;
private static final int VALID_FORMAT_VERSION = 2;
static {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
......@@ -261,7 +263,7 @@ public final class Currency implements Serializable {
Set<String> keys = props.stringPropertyNames();
Pattern propertiesPattern =
Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +
"([0-3])\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
"(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
"\\d{2}:\\d{2})?");
for (String key : keys) {
replaceCurrencyData(propertiesPattern,
......@@ -682,7 +684,7 @@ public final class Currency implements Serializable {
* @param ctry country code
* @param curdata currency data. This is a comma separated string that
* consists of "three-letter alphabet code", "three-digit numeric code",
* and "one-digit (0,1,2, or 3) default fraction digit".
* and "one-digit (0-9) default fraction digit".
* For example, "JPZ,392,0".
* An optional UTC date can be appended to the string (comma separated)
* to allow a currency change take effect after date specified.
......@@ -721,8 +723,14 @@ public final class Currency implements Serializable {
String code = m.group(1);
int numeric = Integer.parseInt(m.group(2));
int fraction = Integer.parseInt(m.group(3));
int entry = numeric << NUMERIC_CODE_SHIFT;
int fraction = Integer.parseInt(m.group(3));
if (fraction > SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS) {
info("currency.properties entry for " + ctry +
" ignored since the fraction is more than " +
SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS + ":" + curdata, null);
return;
}
int index;
for (index = 0; index < scOldCurrencies.length; index++) {
......
......@@ -23,7 +23,10 @@
# questions.
#
formatVersion=1
# Version of the currency data format.
# 1: initial
# 2: Change in minor unit (allowing 4-9 digits)
formatVersion=2
# Version of the currency code information in this class.
# It is a serial number that accompanies with each amendment.
......@@ -36,7 +39,7 @@ dataVersion=159
all=ADP020-AED784-AFA004-AFN971-ALL008-AMD051-ANG532-AOA973-ARS032-ATS040-AUD036-\
AWG533-AYM945-AZM031-AZN944-BAM977-BBD052-BDT050-BEF056-BGL100-BGN975-BHD048-BIF108-\
BMD060-BND096-BOB068-BOV984-BRL986-BSD044-BTN064-BWP072-BYB112-BYR974-\
BZD084-CAD124-CDF976-CHF756-CLF990-CLP152-CNY156-COP170-CRC188-CSD891-CUP192-CUC931-\
BZD084-CAD124-CDF976-CHE947-CHF756-CHW948-CLF990-CLP152-CNY156-COP170-COU970-CRC188-CSD891-CUP192-CUC931-\
CVE132-CYP196-CZK203-DEM276-DJF262-DKK208-DOP214-DZD012-EEK233-EGP818-\
ERN232-ESP724-ETB230-EUR978-FIM246-FJD242-FKP238-FRF250-GBP826-GEL981-\
GHC288-GHS936-GIP292-GMD270-GNF324-GRD300-GTQ320-GWP624-GYD328-HKD344-HNL340-\
......@@ -49,7 +52,7 @@ all=ADP020-AED784-AFA004-AFN971-ALL008-AMD051-ANG532-AOA973-ARS032-ATS040-AUD036
PKR586-PLN985-PTE620-PYG600-QAR634-ROL946-RON946-RSD941-RUB643-RUR810-RWF646-SAR682-\
SBD090-SCR690-SDD736-SDG938-SEK752-SGD702-SHP654-SIT705-SKK703-SLL694-SOS706-\
SRD968-SRG740-SSP728-STD678-SVC222-SYP760-SZL748-THB764-TJS972-TMM795-TMT934-TND788-TOP776-\
TPE626-TRL792-TRY949-TTD780-TWD901-TZS834-UAH980-UGX800-USD840-USN997-USS998-\
TPE626-TRL792-TRY949-TTD780-TWD901-TZS834-UAH980-UGX800-USD840-USN997-USS998-UYI940-\
UYU858-UZS860-VEB862-VEF937-VND704-VUV548-WST882-XAF950-XAG961-XAU959-XBA955-\
XBB956-XBC957-XBD958-XCD951-XDR960-XFO000-XFU000-XOF952-XPD964-XPF953-\
XPT962-XSU994-XTS963-XUA965-XXX999-YER886-YUM891-ZAR710-ZMK894-ZMW967-ZWD716-ZWL932-\
......@@ -579,16 +582,17 @@ ZM=ZMW
ZW=ZWL
# List of currencies with 0, 1, OR 3 decimals for minor units, or where there
# are no minor units defined. All others use 2 decimals.
# List of currencies with non-2digit decimals for minor units,
# or where there are no minor units defined. All others use 2 decimals.
minor0=\
ADP-BEF-BIF-BYB-BYR-CLF-CLP-DJF-ESP-GNF-\
ADP-BEF-BIF-BYB-BYR-CLP-DJF-ESP-GNF-\
GRD-ISK-ITL-JPY-KMF-KRW-LUF-MGF-PYG-PTE-RWF-\
TPE-TRL-UGX-VND-VUV-XAF-XOF-XPF
minor1=
TPE-TRL-UGX-UYI-VND-VUV-XAF-XOF-XPF
minor3=\
BHD-IQD-JOD-KWD-LYD-OMR-TND
minor4=\
CLF
minorUndefined=\
XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-\
XPT-XSU-XTS-XUA-XXX
......@@ -25,7 +25,11 @@
package javax.crypto;
import java.io.*;
import java.io.InputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
/**
* A CipherInputStream is composed of an InputStream and a Cipher so
......@@ -88,8 +92,6 @@ public class CipherInputStream extends FilterInputStream {
private int ofinish = 0;
// stream status
private boolean closed = false;
// The stream has been read from. False if the stream has never been read.
private boolean read = false;
/**
* private convenience function.
......@@ -101,11 +103,15 @@ public class CipherInputStream extends FilterInputStream {
* return (ofinish-ostart) (we have this many bytes for you)
* return 0 (no data now, but could have more later)
* return -1 (absolutely no more data)
*
* Note: Exceptions are only thrown after the stream is completely read.
* For AEAD ciphers a read() of any length will internally cause the
* whole stream to be read fully and verify the authentication tag before
* returning decrypted data or exceptions.
*/
private int getMoreData() throws IOException {
if (done) return -1;
int readin = input.read(ibuffer);
read = true;
if (readin == -1) {
done = true;
try {
......@@ -308,17 +314,16 @@ public class CipherInputStream extends FilterInputStream {
closed = true;
input.close();
try {
// throw away the unprocessed data
if (!done) {
// Throw away the unprocessed data and throw no crypto exceptions.
// AEAD ciphers are fully readed before closing. Any authentication
// exceptions would occur while reading.
if (!done) {
try {
cipher.doFinal();
}
}
catch (BadPaddingException | IllegalBlockSizeException ex) {
/* If no data has been read from the stream to be en/decrypted,
we supress any exceptions, and close quietly. */
if (read) {
throw new IOException(ex);
catch (BadPaddingException | IllegalBlockSizeException ex) {
// Catch exceptions as the rest of the stream is unused.
}
}
ostart = 0;
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -2197,10 +2197,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl
*/
public boolean imageUpdate(Image img, int infoflags,
int x, int y, int w, int h) {
Icon iconDisplayed = getIcon();
if (iconDisplayed == null) {
return false;
}
Icon iconDisplayed = null;
if (!model.isEnabled()) {
if (model.isSelected()) {
......@@ -2220,7 +2217,12 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl
iconDisplayed = getSelectedIcon();
}
if (!SwingUtilities.doesIconReferenceImage(iconDisplayed, img)) {
if (iconDisplayed == null) {
iconDisplayed = getIcon();
}
if (iconDisplayed == null
|| !SwingUtilities.doesIconReferenceImage(iconDisplayed, img)) {
// We don't know about this image, disable the notification so
// we don't keep repainting.
return false;
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -30,7 +30,6 @@ import java.awt.im.InputContext;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.UIManager;
import javax.swing.event.*;
import javax.swing.plaf.UIResource;
import javax.swing.text.*;
......@@ -151,7 +150,7 @@ import javax.swing.text.*;
* will be created to handle formatting of numbers:
* <pre>
* JFormattedTextField tf = new JFormattedTextField();
* tf.setValue(new Number(100));
* tf.setValue(100);
* </pre>
* <p>
* <strong>Warning:</strong> As the <code>AbstractFormatter</code> will
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -491,7 +491,6 @@ public class JTextArea extends JTextComponent {
* @exception IllegalArgumentException if part of the range is an
* invalid position in the model
* @see #insert
* @see #replaceRange
*/
public void replaceRange(String str, int start, int end) {
if (end < start) {
......
......@@ -44,9 +44,7 @@ import java.awt.Font;
import java.awt.Color;
import java.awt.Insets;
import java.awt.Dimension;
import java.lang.reflect.Method;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
......@@ -74,7 +72,7 @@ import sun.util.CoreResourceBundleControl;
*/
public class UIDefaults extends Hashtable<Object,Object>
{
private static final Object PENDING = "Pending";
private static final Object PENDING = new Object();
private SwingPropertyChangeSupport changeSupport;
......@@ -168,7 +166,7 @@ public class UIDefaults extends Hashtable<Object,Object>
* Looks up up the given key in our Hashtable and resolves LazyValues
* or ActiveValues.
*/
private Object getFromHashtable(Object key) {
private Object getFromHashtable(final Object key) {
/* Quickly handle the common case, without grabbing
* a lock.
*/
......
......@@ -3,7 +3,7 @@
<HEAD>
<!--
Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
......@@ -68,6 +68,8 @@ invokeLater} method schedules a {@code Runnable} to be processed on
the event dispatching thread. The following two examples work equally
well for transferring control and starting up a Swing application:
<pre>
import javax.swing.SwingUtilities;
public class MyApp implements Runnable {
public void run() {
// Invoked on the event dispatching thread.
......@@ -75,16 +77,18 @@ public class MyApp implements Runnable {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MyApp(args));
SwingUtilities.invokeLater(new MyApp());
}
}
</pre>
Or:
<pre>
import javax.swing.SwingUtilities;
public class MyApp {
MyApp(String[] args) {
// Invoked on the event dispatching thread. Do any initialization
// here.
// Invoked on the event dispatching thread.
// Do any initialization here.
}
public void show() {
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -37,6 +37,8 @@ import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Graphics;
import sun.swing.SwingUtilities2;
/**
* Factory object that can vend Borders appropriate for the basic L &amp; F.
* @author Georges Saab
......@@ -337,10 +339,10 @@ public class BasicBorders {
Color oldColor = g.getColor();
g.translate(x, y);
g.setColor(shadow);
g.drawLine(0, height-2, width, height-2);
SwingUtilities2.drawHLine(g, 0, width - 1, height - 2);
g.setColor(highlight);
g.drawLine(0, height-1, width, height-1);
g.translate(-x,-y);
SwingUtilities2.drawHLine(g, 0, width - 1, height - 1);
g.translate(-x, -y);
g.setColor(oldColor);
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -36,10 +36,9 @@ import java.awt.Insets;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.*;
import java.util.Vector;
import sun.swing.DefaultLookup;
import sun.swing.UIAction;
import sun.awt.AppContext;
/**
* Basic L&amp;F for a desktop.
......@@ -49,9 +48,6 @@ import sun.awt.AppContext;
public class BasicDesktopPaneUI extends DesktopPaneUI {
// Old actions forward to an instance of this.
private static final Actions SHARED_ACTION = new Actions();
private static Dimension minSize = new Dimension(0,0);
private static Dimension maxSize = new Dimension(Integer.MAX_VALUE,
Integer.MAX_VALUE);
private Handler handler;
private PropertyChangeListener pcl;
......@@ -264,13 +260,19 @@ public class BasicDesktopPaneUI extends DesktopPaneUI {
public void paint(Graphics g, JComponent c) {}
public Dimension getPreferredSize(JComponent c) {return null;}
@Override
public Dimension getPreferredSize(JComponent c) {
return null;
}
@Override
public Dimension getMinimumSize(JComponent c) {
return minSize;
}
public Dimension getMaximumSize(JComponent c){
return maxSize;
return new Dimension(0, 0);
}
@Override
public Dimension getMaximumSize(JComponent c) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
......
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -40,6 +40,7 @@ import java.awt.Graphics;
import java.awt.Window;
import sun.swing.StringUIClientPropertyKey;
import sun.swing.SwingUtilities2;
/**
......@@ -528,25 +529,22 @@ public class MetalBorders {
protected static Insets borderInsets = new Insets( 1, 0, 1, 0 );
public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) {
g.translate( x, y );
g.translate(x, y);
if (MetalLookAndFeel.usingOcean()) {
// Only paint a border if we're not next to a horizontal
// toolbar
if ((c instanceof JMenuBar) && !MetalToolBarUI.doesMenuBarBorderToolBar((JMenuBar)c)) {
// Only paint a border if we're not next to a horizontal toolbar
if (c instanceof JMenuBar
&& !MetalToolBarUI.doesMenuBarBorderToolBar((JMenuBar)c)) {
g.setColor(MetalLookAndFeel.getControl());
g.drawLine(0, h - 2, w, h - 2);
SwingUtilities2.drawHLine(g, 0, w - 1, h - 2);
g.setColor(UIManager.getColor("MenuBar.borderColor"));
g.drawLine(0, h - 1, w, h - 1);
SwingUtilities2.drawHLine(g, 0, w - 1, h - 1);
}
} else {
g.setColor(MetalLookAndFeel.getControlShadow());
SwingUtilities2.drawHLine(g, 0, w - 1, h - 1);
}
else {
g.setColor( MetalLookAndFeel.getControlShadow() );
g.drawLine( 0, h-1, w, h-1 );
}
g.translate( -x, -y );
g.translate(-x, -y);
}
public Insets getBorderInsets(Component c, Insets newInsets) {
......
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -92,8 +92,6 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
private static int MIN_WIDTH = 500;
private static int MIN_HEIGHT = 326;
private static Dimension MIN_SIZE = new Dimension(MIN_WIDTH, MIN_HEIGHT);
private static int LIST_PREF_WIDTH = 405;
private static int LIST_PREF_HEIGHT = 135;
private static Dimension LIST_PREF_SIZE = new Dimension(LIST_PREF_WIDTH, LIST_PREF_HEIGHT);
......@@ -565,6 +563,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
* @return a <code>Dimension</code> specifying the preferred
* width and height of the file chooser
*/
@Override
public Dimension getPreferredSize(JComponent c) {
int prefWidth = PREF_SIZE.width;
Dimension d = c.getLayout().preferredLayoutSize(c);
......@@ -583,8 +582,9 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
* @return a <code>Dimension</code> specifying the minimum
* width and height of the file chooser
*/
@Override
public Dimension getMinimumSize(JComponent c) {
return MIN_SIZE;
return new Dimension(MIN_WIDTH, MIN_HEIGHT);
}
/**
......@@ -594,6 +594,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
* @return a <code>Dimension</code> specifying the maximum
* width and height of the file chooser
*/
@Override
public Dimension getMaximumSize(JComponent c) {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
......@@ -604,7 +605,8 @@ public class MetalFileChooserUI extends BasicFileChooserUI {
} else {
JFileChooser fc = getFileChooser();
if ((fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled()) ||
(fc.isDirectorySelectionEnabled() && fc.isFileSelectionEnabled() && fc.getFileSystemView().isFileSystemRoot(file))) {
(fc.isDirectorySelectionEnabled() && fc.isFileSelectionEnabled()
&& fc.getFileSystemView().isFileSystemRoot(file))) {
return file.getPath();
} else {
return file.getName();
......
......@@ -169,10 +169,9 @@ public final class ContentModel implements Serializable {
case '|':
case '&': {
Element e = (Element) token;
if (valSet == null) {
if (valSet == null || valSet.length <= Element.getMaxIndex()) {
valSet = new boolean[Element.getMaxIndex() + 1];
val = new boolean[valSet.length];
// All Element instances are created before this ever executes
}
if (valSet[e.index]) {
return val[e.index];
......
......@@ -889,14 +889,17 @@ public abstract class SunToolkit extends Toolkit
}
protected static boolean imageExists(String filename) {
checkPermissions(filename);
return filename != null && new File(filename).exists();
if (filename != null) {
checkPermissions(filename);
return new File(filename).exists();
}
return false;
}
@SuppressWarnings("try")
protected static boolean imageExists(URL url) {
checkPermissions(url);
if (url != null) {
checkPermissions(url);
try (InputStream is = url.openStream()) {
return true;
}catch(IOException e){
......
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -39,7 +39,7 @@ import java.awt.datatransfer.UnsupportedFlavorException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
......@@ -75,12 +75,11 @@ public abstract class SunClipboard extends Clipboard
private volatile int numberOfFlavorListeners = 0;
/**
* A set of <code>DataFlavor</code>s that is available on
* this clipboard. It is used for tracking changes
* of <code>DataFlavor</code>s available on this clipboard.
* A set of {@code DataFlavor}s that is available on this clipboard. It is
* used for tracking changes of {@code DataFlavor}s available on this
* clipboard. Can be {@code null}.
*/
private volatile Set currentDataFlavors;
private volatile long[] currentFormats;
public SunClipboard(String name) {
super(name);
......@@ -367,11 +366,11 @@ public abstract class SunClipboard extends Clipboard
try {
openClipboard(null);
currentFormats = getClipboardFormats();
} catch (IllegalStateException exc) {
} catch (final IllegalStateException ignored) {
} finally {
closeClipboard();
}
currentDataFlavors = formatArrayAsDataFlavorSet(currentFormats);
this.currentFormats = currentFormats;
registerClipboardViewerChecked();
}
......@@ -391,7 +390,7 @@ public abstract class SunClipboard extends Clipboard
if (contextFlavorListeners.remove(listener) &&
--numberOfFlavorListeners == 0) {
unregisterClipboardViewerChecked();
currentDataFlavors = null;
currentFormats = null;
}
}
......@@ -420,17 +419,15 @@ public abstract class SunClipboard extends Clipboard
* @param formats data formats that have just been retrieved from
* this clipboard
*/
public void checkChange(long[] formats) {
Set prevDataFlavors = currentDataFlavors;
currentDataFlavors = formatArrayAsDataFlavorSet(formats);
if ((prevDataFlavors != null) && (currentDataFlavors != null) &&
prevDataFlavors.equals(currentDataFlavors)) {
protected final void checkChange(final long[] formats) {
if (Arrays.equals(formats, currentFormats)) {
// we've been able to successfully get available on the clipboard
// DataFlavors this and previous time and they are coincident;
// don't notify
return;
}
currentFormats = formats;
class SunFlavorChangeNotifier implements Runnable {
private final FlavorListener flavorListener;
......
/*
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -33,6 +33,7 @@ import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.PrinterGraphics;
import java.text.BreakIterator;
import java.text.CharacterIterator;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
......@@ -464,16 +465,15 @@ public class SwingUtilities2 {
}
}
if (needsTextLayout) {
FontRenderContext frc = getFontRenderContext(c, fm);
AttributedString aString = new AttributedString(string);
if (c != null) {
aString.addAttribute(TextAttribute.NUMERIC_SHAPING,
c.getClientProperty(TextAttribute.NUMERIC_SHAPING));
}
LineBreakMeasurer measurer =
new LineBreakMeasurer(aString.getIterator(), frc);
int nChars = measurer.nextOffset(availTextWidth);
string = string.substring(0, nChars);
LineBreakMeasurer measurer = new LineBreakMeasurer(
aString.getIterator(), BreakIterator.getCharacterInstance(),
getFontRenderContext(c, fm));
string = string.substring(0, measurer.nextOffset(availTextWidth));
}
return string + clipString;
......
......@@ -28,7 +28,6 @@ import javax.swing.plaf.synth.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
/**
......@@ -44,7 +43,8 @@ import javax.swing.plaf.*;
* @author Scott Violet
*/
public class DefaultSynthStyle extends SynthStyle implements Cloneable {
private static final String PENDING = "Pending";
private static final Object PENDING = new Object();
/**
* Should the component be opaque?
......
......@@ -47,6 +47,7 @@ import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
......@@ -250,17 +251,17 @@ public class LocaleResources {
return (String) localeName;
}
String[] getTimeZoneNames(String key, int size) {
String[] getTimeZoneNames(String key) {
String[] names = null;
String cacheKey = TIME_ZONE_NAMES + size + '.' + key;
String cacheKey = TIME_ZONE_NAMES + '.' + key;
removeEmptyReferences();
ResourceReference data = cache.get(cacheKey);
if (data == null || ((names = (String[]) data.get()) == null)) {
if (Objects.isNull(data) || Objects.isNull((names = (String[]) data.get()))) {
TimeZoneNamesBundle tznb = localeData.getTimeZoneNames(locale);
if (tznb.containsKey(key)) {
names = tznb.getStringArray(key, size);
names = tznb.getStringArray(key);
cache.put(cacheKey,
new ResourceReference(cacheKey, (Object) names, referenceQueue));
}
......
......@@ -26,6 +26,7 @@
package sun.util.locale.provider;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.TimeZone;
import java.util.spi.TimeZoneNameProvider;
......@@ -95,8 +96,9 @@ public class TimeZoneNameProviderImpl extends TimeZoneNameProvider {
*/
@Override
public String getDisplayName(String id, boolean daylight, int style, Locale locale) {
String[] names = getDisplayNameArray(id, 5, locale);
if (names != null) {
String[] names = getDisplayNameArray(id, locale);
if (Objects.nonNull(names)) {
assert names.length >= 7;
int index = daylight ? 3 : 1;
if (style == TimeZone.SHORT) {
index++;
......@@ -108,18 +110,18 @@ public class TimeZoneNameProviderImpl extends TimeZoneNameProvider {
@Override
public String getGenericDisplayName(String id, int style, Locale locale) {
String[] names = getDisplayNameArray(id, 7, locale);
if (names != null && names.length >= 7) {
String[] names = getDisplayNameArray(id, locale);
if (Objects.nonNull(names)) {
assert names.length >= 7;
return names[(style == TimeZone.LONG) ? 5 : 6];
}
return null;
}
private String[] getDisplayNameArray(String id, int n, Locale locale) {
if (id == null || locale == null) {
throw new NullPointerException();
}
return LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id, n);
private String[] getDisplayNameArray(String id, Locale locale) {
Objects.requireNonNull(id);
Objects.requireNonNull(locale);
return LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id);
}
/**
......
......@@ -30,6 +30,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.spi.TimeZoneNameProvider;
......@@ -100,9 +101,9 @@ public final class TimeZoneNameUtility {
* Retrieve display names for a time zone ID.
*/
public static String[] retrieveDisplayNames(String id, Locale locale) {
if (id == null || locale == null) {
throw new NullPointerException();
}
Objects.requireNonNull(id);
Objects.requireNonNull(locale);
return retrieveDisplayNamesImpl(id, locale);
}
......@@ -115,9 +116,12 @@ public final class TimeZoneNameUtility {
* @return the requested generic time zone display name, or null if not found.
*/
public static String retrieveGenericDisplayName(String id, int style, Locale locale) {
LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class);
return pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale, "generic", style, id);
String[] names = retrieveDisplayNamesImpl(id, locale);
if (Objects.nonNull(names)) {
return names[6 - style];
} else {
return null;
}
}
/**
......@@ -130,140 +134,53 @@ public final class TimeZoneNameUtility {
* @return the requested time zone name, or null if not found.
*/
public static String retrieveDisplayName(String id, boolean daylight, int style, Locale locale) {
LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class);
return pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale, daylight ? "dst" : "std", style, id);
String[] names = retrieveDisplayNamesImpl(id, locale);
if (Objects.nonNull(names)) {
return names[(daylight ? 4 : 2) - style];
} else {
return null;
}
}
private static String[] retrieveDisplayNamesImpl(String id, Locale locale) {
LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class);
String[] names;
Map<Locale, String[]> perLocale = null;
SoftReference<Map<Locale, String[]>> ref = cachedDisplayNames.get(id);
if (ref != null) {
Map<Locale, String[]> perLocale = ref.get();
if (perLocale != null) {
String[] names = perLocale.get(locale);
if (names != null) {
if (Objects.nonNull(ref)) {
perLocale = ref.get();
if (Objects.nonNull(perLocale)) {
names = perLocale.get(locale);
if (Objects.nonNull(names)) {
return names;
}
names = pool.getLocalizedObject(TimeZoneNameArrayGetter.INSTANCE, locale, id);
if (names != null) {
perLocale.put(locale, names);
}
return names;
}
}
String[] names = pool.getLocalizedObject(TimeZoneNameArrayGetter.INSTANCE, locale, id);
if (names != null) {
Map<Locale, String[]> perLocale = new ConcurrentHashMap<>();
perLocale.put(locale, names);
ref = new SoftReference<>(perLocale);
cachedDisplayNames.put(id, ref);
// build names array
names = new String[7];
names[0] = id;
for (int i = 1; i <= 6; i ++) {
names[i] = pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale,
i<5 ? (i<3 ? "std" : "dst") : "generic", i%2, id);
}
if (Objects.isNull(perLocale)) {
perLocale = new ConcurrentHashMap<>();
}
perLocale.put(locale, names);
ref = new SoftReference<>(perLocale);
cachedDisplayNames.put(id, ref);
return names;
}
/**
* Obtains a localized time zone strings from a TimeZoneNameProvider
* implementation.
*/
private static class TimeZoneNameArrayGetter
implements LocaleServiceProviderPool.LocalizedObjectGetter<TimeZoneNameProvider,
String[]>{
private static final TimeZoneNameArrayGetter INSTANCE =
new TimeZoneNameArrayGetter();
@Override
public String[] getObject(TimeZoneNameProvider timeZoneNameProvider,
Locale locale,
String requestID,
Object... params) {
assert params.length == 0;
// First, try to get names with the request ID
String[] names = buildZoneStrings(timeZoneNameProvider, locale, requestID);
if (names == null) {
Map<String, String> aliases = ZoneInfo.getAliasTable();
if (aliases != null) {
// Check whether this id is an alias, if so,
// look for the standard id.
String canonicalID = aliases.get(requestID);
if (canonicalID != null) {
names = buildZoneStrings(timeZoneNameProvider, locale, canonicalID);
}
if (names == null) {
// There may be a case that a standard id has become an
// alias. so, check the aliases backward.
names = examineAliases(timeZoneNameProvider, locale,
canonicalID == null ? requestID : canonicalID, aliases);
}
}
}
if (names != null) {
names[0] = requestID;
}
return names;
}
private static String[] examineAliases(TimeZoneNameProvider tznp, Locale locale,
String id,
Map<String, String> aliases) {
if (aliases.containsValue(id)) {
for (Map.Entry<String, String> entry : aliases.entrySet()) {
if (entry.getValue().equals(id)) {
String alias = entry.getKey();
String[] names = buildZoneStrings(tznp, locale, alias);
if (names != null) {
return names;
}
names = examineAliases(tznp, locale, alias, aliases);
if (names != null) {
return names;
}
}
}
}
return null;
}
private static String[] buildZoneStrings(TimeZoneNameProvider tznp,
Locale locale, String id) {
String[] names = new String[5];
for (int i = 1; i <= 4; i ++) {
names[i] = tznp.getDisplayName(id, i>=3, i%2, locale);
if (names[i] == null) {
switch (i) {
case 1:
// this id seems not localized by this provider
return null;
case 2:
case 4:
// If the display name for SHORT is not supplied,
// copy the LONG name.
names[i] = names[i-1];
break;
case 3:
// If the display name for DST is not supplied,
// copy the "standard" name.
names[3] = names[1];
break;
}
}
}
return names;
}
}
private static class TimeZoneNameGetter
implements LocaleServiceProviderPool.LocalizedObjectGetter<TimeZoneNameProvider,
String> {
......@@ -299,18 +216,16 @@ public final class TimeZoneNameUtility {
private static String examineAliases(TimeZoneNameProvider tznp, Locale locale,
String requestID, String tzid, int style,
Map<String, String> aliases) {
if (aliases.containsValue(tzid)) {
for (Map.Entry<String, String> entry : aliases.entrySet()) {
if (entry.getValue().equals(tzid)) {
String alias = entry.getKey();
String name = getName(tznp, locale, requestID, style, alias);
if (name != null) {
return name;
}
name = examineAliases(tznp, locale, requestID, alias, style, aliases);
if (name != null) {
return name;
}
for (Map.Entry<String, String> entry : aliases.entrySet()) {
if (entry.getValue().equals(tzid)) {
String alias = entry.getKey();
String name = getName(tznp, locale, requestID, style, alias);
if (name != null) {
return name;
}
name = examineAliases(tznp, locale, requestID, alias, style, aliases);
if (name != null) {
return name;
}
}
}
......
......@@ -44,6 +44,7 @@ import java.util.Map;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.MissingResourceException;
import java.util.Objects;
import java.util.Set;
/**
......@@ -60,26 +61,6 @@ import java.util.Set;
*/
public abstract class TimeZoneNamesBundle extends OpenListResourceBundle {
/**
* Returns a String array containing time zone names. The String array has
* at most size elements.
*
* @param key the time zone ID for which names are obtained
* @param size the requested size of array for names
* @return a String array containing names
*/
public String[] getStringArray(String key, int size) {
String[] names = handleGetObject(key, size);
if ((names == null || names.length != size) && parent != null) {
names = ((TimeZoneNamesBundle)parent).getStringArray(key, size);
}
if (names == null) {
throw new MissingResourceException("no time zone names", getClass().getName(), key);
}
return names;
}
/**
* Maps time zone IDs to locale-specific names.
* The value returned is an array of five strings:
......@@ -89,6 +70,8 @@ public abstract class TimeZoneNamesBundle extends OpenListResourceBundle {
* <li>The short name of the time zone in standard time (localized).
* <li>The long name of the time zone in daylight savings time (localized).
* <li>The short name of the time zone in daylight savings time (localized).
* <li>The long name of the time zone in generic form (localized).
* <li>The short name of the time zone in generic form (localized).
* </ul>
* The localized names come from the subclasses's
* <code>getContents</code> implementations, while the time zone
......@@ -96,16 +79,12 @@ public abstract class TimeZoneNamesBundle extends OpenListResourceBundle {
*/
@Override
public Object handleGetObject(String key) {
return handleGetObject(key, 5);
}
private String[] handleGetObject(String key, int n) {
String[] contents = (String[]) super.handleGetObject(key);
if (contents == null) {
if (Objects.isNull(contents)) {
return null;
}
int clen = Math.min(n - 1, contents.length);
String[] tmpobj = new String[clen+1];
int clen = contents.length;
String[] tmpobj = new String[7];
tmpobj[0] = key;
System.arraycopy(contents, 0, tmpobj, 1, clen);
return tmpobj;
......
......@@ -47,7 +47,8 @@ public final class TimeZoneNames_en_IE extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
return new Object[][] {
{"Europe/London", new String[] {"Greenwich Mean Time", "GMT",
"Irish Summer Time", "IST" /*Dublin*/}},
"Irish Summer Time", "IST", /*Dublin*/
"Irish Time", "IT" /*Dublin*/}},
};
}
}
......@@ -2778,6 +2778,14 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
pb = &data->pixelBuf;
if (setPixelBuffer(env, pb, buffer) == NOT_OK) {
if (scale != NULL) {
for (i = 0; i < numBands; i++) {
if (scale[i] != NULL) {
free(scale[i]);
}
}
free(scale);
}
return data->abortFlag; // We already threw an out of memory exception
}
......
......@@ -32,6 +32,7 @@ import sun.java2d.SurfaceData;
import java.awt.Graphics;
public interface X11ComponentPeer {
long getWindow();
long getContentWindow();
SurfaceData getSurfaceData();
GraphicsConfiguration getGraphicsConfiguration();
......
......@@ -298,11 +298,7 @@ public class X11GraphicsDevice
@Override
public boolean isFullScreenSupported() {
// REMIND: for now we will only allow fullscreen exclusive mode
// on the primary screen; we could change this behavior slightly
// in the future by allowing only one screen to be in fullscreen
// exclusive mode at any given time...
boolean fsAvailable = (screen == 0) && isXrandrExtensionSupported();
boolean fsAvailable = isXrandrExtensionSupported();
if (fsAvailable) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
......@@ -328,7 +324,7 @@ public class X11GraphicsDevice
private static void enterFullScreenExclusive(Window w) {
X11ComponentPeer peer = (X11ComponentPeer)w.getPeer();
if (peer != null) {
enterFullScreenExclusive(peer.getContentWindow());
enterFullScreenExclusive(peer.getWindow());
peer.setFullScreenExclusiveModeState(true);
}
}
......@@ -337,7 +333,7 @@ public class X11GraphicsDevice
X11ComponentPeer peer = (X11ComponentPeer)w.getPeer();
if (peer != null) {
peer.setFullScreenExclusiveModeState(false);
exitFullScreenExclusive(peer.getContentWindow());
exitFullScreenExclusive(peer.getWindow());
}
}
......@@ -379,7 +375,11 @@ public class X11GraphicsDevice
@Override
public synchronized DisplayMode getDisplayMode() {
if (isFullScreenSupported()) {
return getCurrentDisplayMode(screen);
DisplayMode mode = getCurrentDisplayMode(screen);
if (mode == null) {
mode = getDefaultDisplayMode();
}
return mode;
} else {
if (origDisplayMode == null) {
origDisplayMode = getDefaultDisplayMode();
......
......@@ -85,6 +85,15 @@ public class ResolverConfigurationImpl
if (val.charAt(0) == '#' || val.charAt(0) == ';') {
break;
}
if ("nameserver".equals(keyword)) {
if (val.indexOf(':') >= 0 &&
val.indexOf('.') < 0 && // skip for IPv4 literals with port
val.indexOf('[') < 0 &&
val.indexOf(']') < 0 ) {
// IPv6 literal, in non-BSD-style.
val = "[" + val + "]";
}
}
ll.add(val);
if (--maxvalues == 0) {
break;
......
......@@ -1716,9 +1716,9 @@ X11GD_InitXrandrFuncs(JNIEnv *env)
/*
* REMIND: Fullscreen mode doesn't work quite right with multi-monitor
* setups and RANDR 1.2. So for now we also require a single screen.
* setups and RANDR 1.2.
*/
if (awt_numScreens > 1 ) {
if ((rr_maj_ver == 1 && rr_min_ver <= 2) && awt_numScreens > 1) {
J2dRlsTraceLn(J2D_TRACE_INFO, "X11GD_InitXrandrFuncs: Can't use Xrandr. "
"Multiple screens in use");
dlclose(pLibRandR);
......@@ -1806,40 +1806,14 @@ X11GD_SetFullscreenMode(Window win, jboolean enabled)
Atom wmState = XInternAtom(awt_display, "_NET_WM_STATE", False);
Atom wmStateFs = XInternAtom(awt_display,
"_NET_WM_STATE_FULLSCREEN", False);
Window root, parent, *children = NULL;
unsigned int numchildren;
XWindowAttributes attr;
XEvent event;
Status status;
if (wmState == None || wmStateFs == None) {
if (wmState == None || wmStateFs == None
|| !XGetWindowAttributes(awt_display, win, &attr)) {
return;
}
/*
* Note: the Window passed to this method is typically the "content
* window" of the top-level, but we need the actual shell window for
* the purposes of constructing the XEvent. Therefore, we walk up the
* window hierarchy here to find the true top-level.
*/
do {
if (!XQueryTree(awt_display, win,
&root, &parent,
&children, &numchildren))
{
return;
}
if (children != NULL) {
XFree(children);
}
if (parent == root) {
break;
}
win = parent;
} while (root != parent);
memset(&event, 0, sizeof(event));
event.xclient.type = ClientMessage;
event.xclient.message_type = wmState;
......@@ -1849,7 +1823,7 @@ X11GD_SetFullscreenMode(Window win, jboolean enabled)
event.xclient.data.l[0] = enabled ? 1 : 0; // 1==add, 0==remove
event.xclient.data.l[1] = wmStateFs;
XSendEvent(awt_display, root, False,
XSendEvent(awt_display, attr.root, False,
SubstructureRedirectMask | SubstructureNotifyMask,
&event);
XSync(awt_display, False);
......
......@@ -234,7 +234,7 @@ Java_sun_font_NativeFont_getGlyphAdvance
NativeScalerContext *context = (NativeScalerContext*)pScalerContext;
AWTFont xFont = (AWTFont)context->xFont;
AWTChar xcs;
AWTChar xcs = NULL;
jfloat advance = 0.0f;
if (xFont == NULL || context->ptSize == NO_POINTSIZE) {
......
......@@ -28,6 +28,7 @@
#include <stdlib.h>
#include "jvm.h"
#include "TimeZone_md.h"
#include "jdk_util.h"
#define VALUE_UNKNOWN 0
#define VALUE_KEY 1
......@@ -49,6 +50,20 @@ typedef struct _TziValue {
SYSTEMTIME dstDate;
} TziValue;
#if _WIN32_WINNT < 0x0600 /* < _WIN32_WINNT_VISTA */
typedef struct _TIME_DYNAMIC_ZONE_INFORMATION {
LONG Bias;
WCHAR StandardName[32];
SYSTEMTIME StandardDate;
LONG StandardBias;
WCHAR DaylightName[32];
SYSTEMTIME DaylightDate;
LONG DaylightBias;
WCHAR TimeZoneKeyName[128];
BOOLEAN DynamicDaylightTimeDisabled;
} DYNAMIC_TIME_ZONE_INFORMATION, *PDYNAMIC_TIME_ZONE_INFORMATION;
#endif
/*
* Registry key names
*/
......@@ -142,6 +157,33 @@ static void customZoneName(LONG bias, char *buffer) {
}
}
/*
* Use NO_DYNAMIC_TIME_ZONE_INFO as the return value indicating that no
* dynamic time zone information is available.
*/
#define NO_DYNAMIC_TIME_ZONE_INFO (-128)
static int getDynamicTimeZoneInfo(PDYNAMIC_TIME_ZONE_INFORMATION pdtzi) {
DWORD timeType = NO_DYNAMIC_TIME_ZONE_INFO;
HMODULE dllHandle;
/*
* Dynamically load the dll to call GetDynamicTimeZoneInformation.
*/
dllHandle = JDK_LoadSystemLibrary("Kernel32.dll");
if (dllHandle != NULL) {
typedef DWORD (WINAPI *GetDynamicTimezoneInfoType)(PDYNAMIC_TIME_ZONE_INFORMATION);
GetDynamicTimezoneInfoType getDynamicTimeZoneInfoFunc =
(GetDynamicTimezoneInfoType) GetProcAddress(dllHandle,
"GetDynamicTimeZoneInformation");
if (getDynamicTimeZoneInfo != NULL) {
timeType = getDynamicTimeZoneInfoFunc(pdtzi);
}
}
return timeType;
}
/*
* Gets the current time zone entry in the "Time Zones" registry.
*/
......@@ -161,22 +203,95 @@ static int getWinTimeZone(char *winZoneName, char *winMapID)
WCHAR *stdNamePtr = tzi.StandardName;
DWORD valueSize;
DWORD timeType;
int isVista;
int isVistaOrLater;
/*
* Get the current time zone setting of the platform.
* Determine if this is a Vista or later.
*/
timeType = GetTimeZoneInformation(&tzi);
if (timeType == TIME_ZONE_ID_INVALID) {
goto err;
ver.dwOSVersionInfoSize = sizeof(ver);
GetVersionEx(&ver);
isVistaOrLater = (ver.dwMajorVersion >= 6);
if (isVistaOrLater) {
DYNAMIC_TIME_ZONE_INFORMATION dtzi;
DWORD bufSize;
DWORD val;
/*
* Get the dynamic time zone information, if available, so that time
* zone redirection can be supported. (see JDK-7044727)
*/
timeType = getDynamicTimeZoneInfo(&dtzi);
if (timeType == TIME_ZONE_ID_INVALID) {
goto err;
}
if (timeType != NO_DYNAMIC_TIME_ZONE_INFO) {
/*
* Make sure TimeZoneKeyName is available from the API call. If
* DynamicDaylightTime is disabled, return a custom time zone name
* based on the GMT offset. Otherwise, return the TimeZoneKeyName
* value.
*/
if (dtzi.TimeZoneKeyName[0] != 0) {
if (dtzi.DynamicDaylightTimeDisabled) {
customZoneName(dtzi.Bias, winZoneName);
return VALUE_GMTOFFSET;
}
wcstombs(winZoneName, dtzi.TimeZoneKeyName, MAX_ZONE_CHAR);
return VALUE_KEY;
}
/*
* If TimeZoneKeyName is not available, check whether StandardName
* is available to fall back to the older API GetTimeZoneInformation.
* If not, directly read the value from registry keys.
*/
if (dtzi.StandardName[0] == 0) {
ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_CURRENT_TZ_KEY, 0,
KEY_READ, (PHKEY)&hKey);
if (ret != ERROR_SUCCESS) {
goto err;
}
/*
* Determine if auto-daylight time adjustment is turned off.
*/
bufSize = sizeof(val);
ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled", NULL,
&valueType, (LPBYTE) &val, &bufSize);
if (ret != ERROR_SUCCESS) {
goto err;
}
/*
* Return a custom time zone name if auto-daylight time
* adjustment is disabled.
*/
if (val == 1) {
customZoneName(dtzi.Bias, winZoneName);
(void) RegCloseKey(hKey);
return VALUE_GMTOFFSET;
}
bufSize = MAX_ZONE_CHAR;
ret = RegQueryValueExA(hKey, "TimeZoneKeyName",NULL,
&valueType, (LPBYTE)winZoneName, &bufSize);
if (ret != ERROR_SUCCESS) {
goto err;
}
(void) RegCloseKey(hKey);
return VALUE_KEY;
}
}
}
/*
* Determine if this is an NT system.
* Fall back to GetTimeZoneInformation
*/
ver.dwOSVersionInfoSize = sizeof(ver);
GetVersionEx(&ver);
isVista = ver.dwMajorVersion >= 6;
timeType = GetTimeZoneInformation(&tzi);
if (timeType == TIME_ZONE_ID_INVALID) {
goto err;
}
ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_CURRENT_TZ_KEY, 0,
KEY_READ, (PHKEY)&hKey);
......@@ -187,23 +302,23 @@ static int getWinTimeZone(char *winZoneName, char *winMapID)
/*
* Determine if auto-daylight time adjustment is turned off.
*/
valueType = 0;
bufSize = sizeof(val);
ret = RegQueryValueExA(hKey, "DisableAutoDaylightTimeSet",
NULL, &valueType, (LPBYTE) &val, &bufSize);
/*
* Vista uses the different key name.
*/
ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled", NULL,
&valueType, (LPBYTE) &val, &bufSize);
if (ret != ERROR_SUCCESS) {
/*
* Try the old key name.
*/
bufSize = sizeof(val);
ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled",
NULL, &valueType, (LPBYTE) &val, &bufSize);
ret = RegQueryValueExA(hKey, "DisableAutoDaylightTimeSet", NULL,
&valueType, (LPBYTE) &val, &bufSize);
}
if (ret == ERROR_SUCCESS) {
int daylightSavingsUpdateDisabledOther = val == 1 && tzi.DaylightDate.wMonth != 0;
int daylightSavingsUpdateDisabledVista = val == 1;
int daylightSavingsUpdateDisabled = isVista ? daylightSavingsUpdateDisabledVista : daylightSavingsUpdateDisabledOther;
int daylightSavingsUpdateDisabledOther = (val == 1 && tzi.DaylightDate.wMonth != 0);
int daylightSavingsUpdateDisabledVista = (val == 1);
int daylightSavingsUpdateDisabled
= (isVistaOrLater ? daylightSavingsUpdateDisabledVista : daylightSavingsUpdateDisabledOther);
if (daylightSavingsUpdateDisabled) {
(void) RegCloseKey(hKey);
......@@ -212,29 +327,13 @@ static int getWinTimeZone(char *winZoneName, char *winMapID)
}
}
/*
* Vista has the key for the current "Time Zones" entry.
*/
if (isVista) {
valueType = 0;
bufSize = MAX_ZONE_CHAR;
ret = RegQueryValueExA(hKey, "TimeZoneKeyName", NULL,
&valueType, (LPBYTE) winZoneName, &bufSize);
if (ret != ERROR_SUCCESS) {
goto err;
}
(void) RegCloseKey(hKey);
return VALUE_KEY;
}
/*
* Win32 problem: If the length of the standard time name is equal
* to (or probably longer than) 32 in the registry,
* GetTimeZoneInformation() on NT returns a null string as its
* standard time name. We need to work around this problem by
* getting the same information from the TimeZoneInformation
* registry. The function on Win98 seems to return its key name.
* We can't do anything in that case.
* registry.
*/
if (tzi.StandardName[0] == 0) {
bufSize = sizeof(stdNameInReg);
......
......@@ -3761,12 +3761,14 @@ void AwtComponent::SetCompositionWindow(RECT& r)
void AwtComponent::OpenCandidateWindow(int x, int y)
{
UINT bits = 1;
RECT rc;
GetWindowRect(GetHWnd(), &rc);
POINT p = {0, 0}; // upper left corner of the client area
HWND hWnd = GetHWnd();
HWND hTop = GetTopLevelParentForWindow(hWnd);
::ClientToScreen(hTop, &p);
for (int iCandType=0; iCandType<32; iCandType++, bits<<=1) {
if ( m_bitsCandType & bits )
SetCandidateWindow(iCandType, x-rc.left, y-rc.top);
SetCandidateWindow(iCandType, x - p.x, y - p.y);
}
if (m_bitsCandType != 0) {
// REMIND: is there any chance GetProxyFocusOwner() returns NULL here?
......
/*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -310,6 +310,8 @@ int AwtInputTextInfor::GetClauseInfor(int*& lpBndClauseW, jstring*& lpReadingCla
readingMergedClauseW = new jstring[cMergedClauseW];
} catch (std::bad_alloc&) {
delete [] bndMergedClauseW;
delete [] bndClauseW;
delete [] readingClauseW;
throw;
}
......@@ -394,6 +396,8 @@ int AwtInputTextInfor::GetAttributeInfor(int*& lpBndAttrW, BYTE*& lpValAttrW) {
valMergedAttrW = new BYTE[cMergedAttrW];
} catch (std::bad_alloc&) {
delete [] bndMergedAttrW;
delete [] bndAttrW;
delete [] valAttrW;
throw;
}
bndMergedAttrW[0] = 0;
......
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8075331
* @summary Verify that we can call varargs methods
* @run build TestScaffold VMConnection TargetAdapter TargetListener
* @run compile -g InvokeVarArgs.java
* @run driver InvokeVarArgs
*/
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import java.util.Arrays;
interface MyInterface {
}
class SomeClass implements MyInterface {
}
class InvokeVarArgsTarg {
public static void main(String args[]) {
new InvokeVarArgsTarg().run();
}
SomeClass someClass1 = new SomeClass();
SomeClass someClass2 = new SomeClass();
MyInterface[] array = new MyInterface[]{someClass1, someClass2};
SomeClass[] array2 = new SomeClass[]{someClass1, someClass2};
public void run() {
System.out.println("size(array) : " + size(array));
System.out.println("size(array2) : " + size(array2));
}
int size(Object... value) {
return value.length;
}
}
public class InvokeVarArgs extends TestScaffold {
public static void main(String args[]) throws Exception {
new InvokeVarArgs(args).startTests();
}
InvokeVarArgs(String args[]) throws Exception {
super(args);
}
protected void runTests() throws Exception {
BreakpointEvent bpe = startTo("InvokeVarArgsTarg", "run", "()V");
StackFrame frame = bpe.thread().frame(0);
ObjectReference targetObj = frame.thisObject();
ReferenceType targetType = (ReferenceType) targetObj.type();
Value arrayVal = targetObj.getValue(targetType.fieldByName("array"));
Value array2Val = targetObj.getValue(targetType.fieldByName("array2"));
Method sizeMethod = targetType.methodsByName("size", "([Ljava/lang/Object;)I").get(0);
IntegerValue size = (IntegerValue) targetObj.invokeMethod(bpe.thread(), sizeMethod, Arrays.asList(new Value[]{arrayVal}), 0);
if (size.value() != 2) {
throw new Exception("size(array) should be 2, but was " + size.value());
}
size = (IntegerValue) targetObj.invokeMethod(bpe.thread(), sizeMethod, Arrays.asList(new Value[]{array2Val}), 0);
if (size.value() != 2) {
throw new Exception("size(array2) should be 2, but was " + size.value());
}
listenUntilVMDisconnect();
}
}
/*
* Copyright (c) 2015, Red Hat, Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.lang.reflect.Field;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.NamingManager;
import com.sun.jndi.dns.DnsContext;
/**
* @test
* @bug 6991580
* @summary IPv6 Nameservers in resolv.conf throws NumberFormatException
* @run main/manual IPv6NameserverPlatformParsingTest
*
* In order to run this test be sure to place, for example, the following
* snippet into your platform's {@code /etc/resolv.conf}:
* <pre>
* nameserver 127.0.0.1
* nameserver 2001:4860:4860::8888
* nameserver [::1]:5353
* nameserver 127.0.0.1:5353
* </pre>
*
* Then, run this test as manual jtreg test.
*
* @author Severin Gehwolf
*
*/
public class IPv6NameserverPlatformParsingTest {
private static boolean foundIPv6 = false;
public static void main(String[] args) {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.dns.DnsContextFactory.class.getName());
String[] servers;
try {
Context ctx = NamingManager.getInitialContext(env);
if (!com.sun.jndi.dns.DnsContextFactory.platformServersAvailable()) {
throw new RuntimeException("FAIL: no platform servers available, test does not make sense");
}
DnsContext context = (DnsContext)ctx;
servers = getServersFromContext(context);
} catch (NamingException e) {
throw new RuntimeException(e);
}
for (String server: servers) {
System.out.println("DEBUG: 'nameserver = " + server + "'");
if (server.indexOf(':') >= 0 && server.indexOf('.') < 0) {
System.out.println("DEBUG: ==> Found IPv6 address in servers list: " + server);
foundIPv6 = true;
}
}
try {
new com.sun.jndi.dns.DnsClient(servers, 100, 1);
} catch (NumberFormatException e) {
throw new RuntimeException("FAIL: Tried to parse non-[]-encapsulated IPv6 address.", e);
} catch (Exception e) {
throw new RuntimeException("ERROR: Something unexpected happened.");
}
if (!foundIPv6) {
// This is a manual test, since it requires changing /etc/resolv.conf on Linux/Unix
// platforms. See comment as to how to run this test.
throw new RuntimeException("ERROR: No IPv6 address returned from platform.");
}
System.out.println("PASS: Found IPv6 address and DnsClient parsed it correctly.");
}
private static String[] getServersFromContext(DnsContext context) {
try {
Field serversField = DnsContext.class.getDeclaredField("servers");
serversField.setAccessible(true);
return (String[])serversField.get(context);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
......@@ -26,6 +26,7 @@
* @bug 4406033
* @summary ConfigFile throws an inconsistent error message
* when the configuration file is not found
* @run main/othervm -Duser.language=en InconsistentError
*/
import com.sun.security.auth.login.*;
......
......@@ -25,6 +25,7 @@
* @test
* @bug 4919147
* @summary Support for token-based KeyStores
* @run main/othervm -Duser.language=en OptionTest
*/
import java.io.File;
......
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.Robot;
/**
* @test
* @bug 8074500
* @summary Checkbox.setState() call should not post ItemEvent
* @author Sergey Bylokhov
*/
public final class SetStateExcessEvent {
private static boolean failed;
public static void main(final String[] args) throws Exception {
final Robot robot = new Robot();
final CheckboxGroup group = new CheckboxGroup();
final Checkbox[] cbs = {new Checkbox("checkbox1", true, group),
new Checkbox("checkbox2", false, group),
new Checkbox("checkbox3", true, group),
new Checkbox("checkbox4", true),
new Checkbox("checkbox5", false),
new Checkbox("checkbox6", true)};
final Frame frame = new Frame();
frame.setLayout(new GridBagLayout());
try {
for (final Checkbox cb : cbs) {
cb.addItemListener(e -> {
failed = true;
});
}
for (final Checkbox cb : cbs) {
frame.add(cb);
}
frame.pack();
for (final Checkbox cb : cbs) {
cb.setState(!cb.getState());
}
for (final Checkbox cb : cbs) {
group.setSelectedCheckbox(cb);
}
robot.waitForIdle();
} finally {
frame.dispose();
}
if (failed) {
throw new RuntimeException("Listener should not be called");
}
System.out.println("Test passed");
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Label;
import java.awt.List;
import java.awt.Panel;
import java.awt.ScrollPane;
import java.awt.Scrollbar;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Window;
import java.util.ArrayList;
import java.util.Objects;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.JViewport;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.JTableHeader;
import static javax.swing.UIManager.getInstalledLookAndFeels;
/**
* @test
* @bug 6459798
* @author Sergey Bylokhov
*/
public final class DimensionEncapsulation implements Runnable {
java.util.List<Component> failures = new ArrayList<>();
public static void main(final String[] args) throws Exception {
for (final LookAndFeelInfo laf : getInstalledLookAndFeels()) {
SwingUtilities.invokeAndWait(() -> setLookAndFeel(laf));
SwingUtilities.invokeAndWait(new DimensionEncapsulation());
}
}
@Override
public void run() {
runTest(new Panel());
runTest(new Button());
runTest(new Checkbox());
runTest(new Canvas());
runTest(new Choice());
runTest(new Label());
runTest(new Scrollbar());
runTest(new TextArea());
runTest(new TextField());
runTest(new Dialog(new JFrame()));
runTest(new Frame());
runTest(new Window(new JFrame()));
runTest(new FileDialog(new JFrame()));
runTest(new List());
runTest(new ScrollPane());
runTest(new JFrame());
runTest(new JDialog(new JFrame()));
runTest(new JWindow(new JFrame()));
runTest(new JLabel("hi"));
runTest(new JMenu());
runTest(new JTree());
runTest(new JTable());
runTest(new JMenuItem());
runTest(new JCheckBoxMenuItem());
runTest(new JToggleButton());
runTest(new JSpinner());
runTest(new JSlider());
runTest(Box.createVerticalBox());
runTest(Box.createHorizontalBox());
runTest(new JTextField());
runTest(new JTextArea());
runTest(new JTextPane());
runTest(new JPasswordField());
runTest(new JFormattedTextField());
runTest(new JEditorPane());
runTest(new JButton());
runTest(new JColorChooser());
runTest(new JFileChooser());
runTest(new JCheckBox());
runTest(new JInternalFrame());
runTest(new JDesktopPane());
runTest(new JTableHeader());
runTest(new JLayeredPane());
runTest(new JRootPane());
runTest(new JMenuBar());
runTest(new JOptionPane());
runTest(new JRadioButton());
runTest(new JRadioButtonMenuItem());
runTest(new JPopupMenu());
//runTest(new JScrollBar()); --> don't test defines max and min in
// terms of preferred
runTest(new JScrollPane());
runTest(new JViewport());
runTest(new JSplitPane());
runTest(new JTabbedPane());
runTest(new JToolBar());
runTest(new JSeparator());
runTest(new JProgressBar());
if (!failures.isEmpty()) {
System.out.println("These classes failed");
for (final Component failure : failures) {
System.out.println(failure.getClass());
}
throw new RuntimeException("Test failed");
}
}
public void runTest(final Component c) {
try {
test(c);
c.setMinimumSize(new Dimension(100, 10));
c.setMaximumSize(new Dimension(200, 20));
c.setPreferredSize(new Dimension(300, 30));
test(c);
} catch (final Throwable ignored) {
failures.add(c);
}
}
public void test(final Component component) {
final Dimension psize = component.getPreferredSize();
psize.width += 200;
if (Objects.equals(psize, component.getPreferredSize())) {
throw new RuntimeException("PreferredSize is wrong");
}
final Dimension msize = component.getMaximumSize();
msize.width += 200;
if (Objects.equals(msize, component.getMaximumSize())) {
throw new RuntimeException("MaximumSize is wrong");
}
final Dimension misize = component.getMinimumSize();
misize.width += 200;
if (Objects.equals(misize, component.getMinimumSize())) {
throw new RuntimeException("MinimumSize is wrong");
}
}
private static void setLookAndFeel(final LookAndFeelInfo laf) {
try {
UIManager.setLookAndFeel(laf.getClassName());
System.out.println("LookAndFeel: " + laf.getClassName());
} catch (ClassNotFoundException | InstantiationException |
UnsupportedLookAndFeelException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Component;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JRootPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.JTableHeader;
import static javax.swing.UIManager.LookAndFeelInfo;
import static javax.swing.UIManager.getInstalledLookAndFeels;
/**
* @test
* @bug 6459800
* @author Sergey Bylokhov
*/
public final class InsetsEncapsulation implements Runnable {
private final Collection<Component> failures = new ArrayList<>();
public static void main(final String[] args) throws Exception {
for (final LookAndFeelInfo laf : getInstalledLookAndFeels()) {
SwingUtilities.invokeAndWait(() -> setLookAndFeel(laf));
SwingUtilities.invokeAndWait(new InsetsEncapsulation());
}
}
@Override
public void run() {
runTest(new JLabel("hi"));
runTest(new JMenu());
runTest(new JTree());
runTest(new JTable());
runTest(new JMenuItem());
runTest(new JCheckBoxMenuItem());
runTest(new JToggleButton());
runTest(new JSpinner());
runTest(new JSlider());
runTest(Box.createVerticalBox());
runTest(Box.createHorizontalBox());
runTest(new JTextField());
runTest(new JTextArea());
runTest(new JTextPane());
runTest(new JPasswordField());
runTest(new JFormattedTextField());
runTest(new JEditorPane());
runTest(new JButton());
runTest(new JColorChooser());
runTest(new JFileChooser());
runTest(new JCheckBox());
runTest(new JInternalFrame());
runTest(new JDesktopPane());
runTest(new JTableHeader());
runTest(new JLayeredPane());
runTest(new JRootPane());
runTest(new JMenuBar());
runTest(new JOptionPane());
runTest(new JRadioButton());
runTest(new JRadioButtonMenuItem());
runTest(new JPopupMenu());
runTest(new JScrollBar());
runTest(new JScrollPane());
runTest(new JViewport());
runTest(new JSplitPane());
runTest(new JTabbedPane());
runTest(new JToolBar());
runTest(new JSeparator());
runTest(new JProgressBar());
if (!failures.isEmpty()) {
System.out.println("These classes failed");
for (final Component failure : failures) {
System.out.println(failure.getClass());
}
throw new RuntimeException("Test failed");
}
}
void runTest(final JComponent component) {
try {
test(component);
} catch (final Throwable ignored) {
failures.add(component);
}
}
void test(final JComponent component) {
final Insets p = component.getInsets();
p.top += 3;
if (p.equals(component.getInsets())) {
throw new RuntimeException("Insets altered by altering Insets!");
}
}
private static void setLookAndFeel(final LookAndFeelInfo laf) {
try {
UIManager.setLookAndFeel(laf.getClassName());
System.out.println("LookAndFeel: " + laf.getClassName());
} catch (ClassNotFoundException | InstantiationException |
UnsupportedLookAndFeelException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
\ No newline at end of file
......@@ -28,7 +28,7 @@
#
# @test
# @bug 8058930
# @bug 8058930 7077826
# @summary java.awt.GraphicsEnvironment.getHeadlessProperty() does not work for AIX
#
# @build TestDetectHeadless
......@@ -36,11 +36,21 @@
OS=`uname -s`
case "$OS" in
Windows* | CYGWIN* )
Windows* | CYGWIN* | Darwin)
echo "Passed"; exit 0 ;;
* ) unset DISPLAY ;;
esac
${TESTJAVA}/bin/java ${TESTVMOPTS} \
-cp ${TESTCLASSES} TestDetectHeadless
if [ $? -ne 0 ]; then
exit 1;
fi
DISPLAY=
export DISPLAY
${TESTJAVA}/bin/java ${TESTVMOPTS} \
-cp ${TESTCLASSES} TestDetectHeadless
......
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
/**
* @test
* @bug 6475361
* @author Sergey Bylokhov
*/
public final class RemoveHelpMenu {
public static void main(final String[] args) {
final Frame frame = new Frame("RemoveHelpMenu Test");
try {
frame.pack();
// peer exists
test1(getMenuBar(frame));
test2(getMenuBar(frame));
test3(getMenuBar(frame));
test4(getMenuBar(frame));
} finally {
frame.dispose();
}
// peer is null
test1(getMenuBar(frame));
test2(getMenuBar(frame));
test3(getMenuBar(frame));
test4(getMenuBar(frame));
}
private static MenuBar getMenuBar(final Frame frame) {
final MenuBar menuBar = new MenuBar();
frame.setMenuBar(menuBar);
return menuBar;
}
private static void checkHelpMenu(final Menu menu, final boolean expected) {
final boolean actual = menu.toString().contains("isHelpMenu=true");
if (actual != expected) {
throw new RuntimeException("Incorrect menu type");
}
}
private static void checkMenuCount(final MenuBar bar, final int expected) {
final int actual = bar.getMenuCount();
if (actual != expected) {
throw new RuntimeException("Incorrect menus count");
}
}
private static void checkCurrentMenu(final MenuBar bar, final Menu menu) {
if (bar.getHelpMenu() != menu) {
throw new RuntimeException("Wrong HelpMenu");
}
}
private static void test1(final MenuBar menuBar) {
checkCurrentMenu(menuBar, null);
checkMenuCount(menuBar, 0);
}
private static void test2(final MenuBar menuBar) {
final Menu helpMenu = new Menu("Help Menu");
menuBar.setHelpMenu(helpMenu);
checkCurrentMenu(menuBar, helpMenu);
checkMenuCount(menuBar, 1);
checkHelpMenu(helpMenu, true);
menuBar.remove(helpMenu);
checkCurrentMenu(menuBar, null);
checkMenuCount(menuBar, 0);
checkHelpMenu(helpMenu, false);
}
private static void test3(final MenuBar menuBar) {
final Menu helpMenu1 = new Menu("Help Menu1");
final Menu helpMenu2 = new Menu("Help Menu2");
menuBar.setHelpMenu(helpMenu1);
checkCurrentMenu(menuBar, helpMenu1);
checkMenuCount(menuBar, 1);
checkHelpMenu(helpMenu1, true);
checkHelpMenu(helpMenu2, false);
menuBar.setHelpMenu(helpMenu2);
checkCurrentMenu(menuBar, helpMenu2);
checkMenuCount(menuBar, 1);
checkHelpMenu(helpMenu1, false);
checkHelpMenu(helpMenu2, true);
menuBar.remove(helpMenu2);
checkCurrentMenu(menuBar, null);
checkMenuCount(menuBar, 0);
checkHelpMenu(helpMenu1, false);
checkHelpMenu(helpMenu2, false);
}
private static void test4(final MenuBar menuBar) {
final Menu helpMenu = new Menu("Help Menu");
menuBar.setHelpMenu(helpMenu);
checkCurrentMenu(menuBar, helpMenu);
checkMenuCount(menuBar, 1);
checkHelpMenu(helpMenu, true);
menuBar.setHelpMenu(null);
checkCurrentMenu(menuBar, null);
checkMenuCount(menuBar, 0);
checkHelpMenu(helpMenu, false);
}
}
\ No newline at end of file
# Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
......@@ -21,23 +21,15 @@
${TESTJAVA}/bin/javac -cp ${TESTSRC} -d . ${TESTSRC}/BadDisplayTest.java
DISPLAY=
export DISPLAY
OS=`uname -s`
case "$OS" in
SunOS )
${TESTJAVA}/bin/java BadDisplayTest
;;
Linux )
${TESTJAVA}/bin/java BadDisplayTest
;;
* )
echo "Unsupported System: ${OS}"
exit 0;
;;
Windows* | CYGWIN* | Darwin)
echo "Passed"; exit 0 ;;
esac
exit $?
DISPLAY=SomeBadDisplay
export DISPLAY
${TESTJAVA}/bin/java ${TESTVMOPTS} BadDisplayTest
exit $?
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.*;
import java.net.URL;
import java.security.Permission;
/**
* @test
* @bug 8078165
* @summary NPE when attempting to get image from toolkit
* @author Anton Nashatyrev
*/
public final class bug8078165 {
public static void main(final String[] args) throws Exception {
// Mac only
System.setSecurityManager(new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
// Just allows everything
}
});
// The method shouldn't throw NPE
Toolkit.getDefaultToolkit().getImage(new URL("file://./dummyImage@2x.png"));
Toolkit.getDefaultToolkit().getImage("./dummyImage@2x.png");
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Properties;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
/**
* @test
* @bug 8066132
* @author Sergey Bylokhov
*/
public final class GetPropertyNames {
static BufferedImage defaultProps = new BufferedImage(1, 1, TYPE_INT_ARGB);
public static void main(final String[] args) {
// default result is null
if (defaultProps.getPropertyNames() != null) {
throw new RuntimeException("PropertyNames should be null");
}
// for null properties result is null
final BufferedImage emptyProps = getBufferedImage(null);
if (emptyProps.getPropertyNames() != null) {
throw new RuntimeException("PropertyNames should be null");
}
// for empty properties result is null
final BufferedImage nullProps = getBufferedImage(new Properties());
if (nullProps.getPropertyNames() != null) {
throw new RuntimeException("PropertyNames should be null");
}
// for non-string keys result is null
final Properties properties = new Properties();
properties.put(1, 1);
properties.put(2, 2);
properties.put(3, 3);
final BufferedImage nonStringProps = getBufferedImage(properties);
if (nonStringProps.getPropertyNames() != null) {
throw new RuntimeException("PropertyNames should be null");
}
// for string keys result is not null
properties.clear();
properties.setProperty("1", "1");
properties.setProperty("2", "2");
validate(getBufferedImage(properties), 2);
// for the mix of strings and objects result is not null
properties.clear();
properties.put(1, 1);
properties.put(2, 2);
properties.put(3, 3);
properties.setProperty("key1", "value1");
properties.setProperty("key2", "value2");
final BufferedImage mixProps = getBufferedImage(properties);
validate(mixProps, 2);
if (!"value1".equals(mixProps.getProperty("key1"))
|| !"value2".equals(mixProps.getProperty("key2"))) {
throw new RuntimeException("Wrong key-value pair");
}
}
private static BufferedImage getBufferedImage(final Properties properties) {
return new BufferedImage(defaultProps.getColorModel(),
defaultProps.getRaster(),
defaultProps.isAlphaPremultiplied(),
properties);
}
private static void validate(final BufferedImage bi, final int expected) {
final String[] names = bi.getPropertyNames();
if (names.length != expected) {
throw new RuntimeException("Wrong number of names");
}
for (final String name : names) {
final Object property = bi.getProperty(name);
if (property == Image.UndefinedProperty || property == null) {
throw new RuntimeException("Unexpected property");
}
}
}
}
......@@ -23,7 +23,7 @@
/*
* @test
* @bug 4290801 4692419 4693631 5101540 5104960 6296410 6336600 6371531
* 6488442 7036905
* 6488442 7036905 8074350 8074351
* @summary Basic tests for Currency class.
*/
......@@ -49,6 +49,7 @@ public class CurrencyTest {
testFractionDigits();
testSerialization();
testDisplayNames();
testFundsCodes();
}
static void testCurrencyCodeValidation() {
......@@ -265,4 +266,41 @@ public class CurrencyTest {
}
}
static void testFundsCodes() {
testValidCurrency("BOV");
testValidCurrency("CHE");
testValidCurrency("CHW");
testValidCurrency("CLF");
testValidCurrency("COU");
testValidCurrency("MXV");
testValidCurrency("USN");
testValidCurrency("UYI");
testFractionDigits("BOV", 2);
testFractionDigits("CHE", 2);
testFractionDigits("CHW", 2);
testFractionDigits("CLF", 4);
testFractionDigits("COU", 2);
testFractionDigits("MXV", 2);
testFractionDigits("USN", 2);
testFractionDigits("UYI", 0);
testNumericCode("BOV", 984);
testNumericCode("CHE", 947);
testNumericCode("CHW", 948);
testNumericCode("CLF", 990);
testNumericCode("COU", 970);
testNumericCode("MXV", 979);
testNumericCode("USN", 997);
testNumericCode("UYI", 940);
}
static void testNumericCode(String currencyCode, int expectedNumeric) {
int numeric = Currency.getInstance(currencyCode).getNumericCode();
if (numeric != expectedNumeric) {
throw new RuntimeException("Wrong numeric code for currency " +
currencyCode +": expected " + expectedNumeric +
", got " + numeric);
}
}
}
/*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -107,7 +107,7 @@ public class PropertiesTest {
keys = p.stringPropertyNames();
Pattern propertiesPattern =
Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +
"([0-3])\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
"(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
"\\d{2}:\\d{2})?");
for (String key: keys) {
String val = p.getProperty(key);
......@@ -135,14 +135,20 @@ public class PropertiesTest {
// ignore this
continue;
}
String code = m.group(1);
int numeric = Integer.parseInt(m.group(2));
int fraction = Integer.parseInt(m.group(3));
if (fraction > 9) {
System.out.println("Skipping since the fraction is greater than 9");
continue;
}
Matcher mAfter = propertiesPattern.matcher(afterVal);
mAfter.find();
String code = m.group(1);
String codeAfter = mAfter.group(1);
int numeric = Integer.parseInt(m.group(2));
int numericAfter = Integer.parseInt(mAfter.group(2));
int fraction = Integer.parseInt(m.group(3));
int fractionAfter = Integer.parseInt(mAfter.group(3));
if (code.equals(codeAfter) &&
(numeric == numericAfter)&&
......
#!/bin/sh
# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
......@@ -23,7 +23,7 @@
#
# @test
# @bug 6332666 6863624 7180362 8003846
# @bug 6332666 6863624 7180362 8003846 8074350 8074351
# @summary tests the capability of replacing the currency data with user
# specified currency properties file
# @build PropertiesTest
......
......@@ -23,6 +23,7 @@
/*
* @test
* @bug 4691089 4819436 4942982 5104960 6544471 6627549 7066203 7195759
* 8074350 8074351
* @summary Validate ISO 4217 data for Currency class.
*/
......@@ -92,7 +93,7 @@ public class ValidateISO4217 {
/* Codes that are obsolete, do not have related country */
static final String otherCodes =
"ADP-AFA-ATS-AYM-AZM-BEF-BGL-BOV-BYB-CLF-CUC-CYP-DEM-EEK-ESP-FIM-FRF-GHC-GRD-GWP-IEP-ITL-LUF-MGF-MTL-MXV-MZM-NLG-PTE-ROL-RUR-SDD-SIT-SKK-SRG-TMM-TPE-TRL-VEF-USN-USS-VEB-XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-XPT-XSU-XTS-XUA-XXX-YUM-ZMK-ZWD-ZWN-ZWR";
"ADP-AFA-ATS-AYM-AZM-BEF-BGL-BOV-BYB-CHE-CHW-CLF-COU-CUC-CYP-DEM-EEK-ESP-FIM-FRF-GHC-GRD-GWP-IEP-ITL-LUF-MGF-MTL-MXV-MZM-NLG-PTE-ROL-RUR-SDD-SIT-SKK-SRG-TMM-TPE-TRL-VEF-UYI-USN-USS-VEB-XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-XPT-XSU-XTS-XUA-XXX-YUM-ZMK-ZWD-ZWN-ZWR";
static boolean err = false;
......
#
# Test data for replacing the currency data
#
JP=JPZ,123,2
ES=ESD,877,2
US=euR,978,2,2001-01-01T00:00:00
# valid entries
CL=CLF,990,4
CM=IED,111,2, 2004-01-01T00:70:00
ES=ESD,877,2
JP=JPZ,123,2
MA=MAA,555,5
MC=MCC,555,6
MD=MDD,555,7
ME=MEE,555,8
MF=MFF,555,9
NO=EUR ,978 ,2, 2099-01-01T00:00:00
SB=EUR,111,2, 2099-01-01T00:00:00
US=euR,978,2,2001-01-01T00:00:00
ZZ = ZZZ , 999 , 3
NO=EUR ,978 ,2, 2099-01-01T00:00:00
# invalid entries
GB=123
FR=zzzzz.123
DE=2009-01-01T00:00:00,EUR,111,2
IE=euR,111,2,#testcomment
=euR,111,2, 2099-01-01-00-00-00
FM=DED,194,2,eeee-01-01T00:00:00
PE=EUR ,978 ,2, 20399-01-01T00:00:00
FR=zzzzz.123
GB=123
IE=euR,111,2,#testcomment
MG=MGG,990,10
MX=SSS,493,2,2001-01-01-00-00-00
PE=EUR ,978 ,2, 20399-01-01T00:00:00
MG=MGG,990,10
=euR,111,2, 2099-01-01-00-00-00
......@@ -5,7 +5,7 @@
#
# Version
FILEVERSION=1
FILEVERSION=2
DATAVERSION=159
# ISO 4217 currency data
......@@ -55,7 +55,7 @@ KY KYD 136 2
CF XAF 950 0
TD XAF 950 0
CL CLP 152 0
#CL CLF 990 0
#CL CLF 990 4
CN CNY 156 2
CX AUD 36 2
CC AUD 36 2
......@@ -265,6 +265,7 @@ US USD 840 2
#US USN 997 2
UM USD 840 2
UY UYU 858 2
#UY UYI 940 0
UZ UZS 860 2
VU VUV 548 0
VE VEF 937 2
......
......@@ -25,6 +25,7 @@
*/
import java.text.*;
import java.time.format.TextStyle;
import java.util.*;
import sun.util.locale.provider.*;
import sun.util.resources.*;
......@@ -42,6 +43,7 @@ public class TimeZoneNameProviderTest extends ProviderTest {
test2();
test3();
aliasTest();
genericFallbackTest();
}
void test1() {
......@@ -169,9 +171,9 @@ public class TimeZoneNameProviderTest extends ProviderTest {
for (int style : new int[] { TimeZone.LONG, TimeZone.SHORT }) {
String osakaStd = tz.getDisplayName(false, style, OSAKA);
if (osakaStd != null) {
// No API for getting generic time zone names
String generic = TimeZoneNameUtility.retrieveGenericDisplayName(tzname,
style, GENERIC);
String generic = tz.toZoneId().getDisplayName(
style == TimeZone.LONG ? TextStyle.FULL : TextStyle.SHORT,
GENERIC);
String expected = "Generic " + osakaStd;
if (!expected.equals(generic)) {
throw new RuntimeException("Wrong generic name: got=\"" + generic
......@@ -230,4 +232,20 @@ public class TimeZoneNameProviderTest extends ProviderTest {
throw new RuntimeException("Provider's localized name is not available for an alias ID: "+JAPAN+". result: "+japan+" expected: "+JST_IN_OSAKA);
}
}
/*
* Tests whether generic names can be retrieved through fallback.
* The test assumes the provider impl for OSAKA locale does NOT
* provide generic names.
*/
final String PT = "PT"; // SHORT generic name for "America/Los_Angeles"
void genericFallbackTest() {
String generic =
TimeZone.getTimeZone(LATIME)
.toZoneId()
.getDisplayName(TextStyle.SHORT, OSAKA);
if (!PT.equals(generic)) {
throw new RuntimeException("Generic name fallback failed. got: "+generic);
}
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8064546
* @summary Throw exceptions during reading but not closing of a
* CipherInputStream:
* - Make sure authenticated algorithms continue to throwing exceptions
* when the authentication tag fails verification.
* - Make sure other algorithms do not throw exceptions when the stream
* calls close() and only throw when read() errors.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.Exception;
import java.lang.RuntimeException;
import java.lang.Throwable;
import java.security.AlgorithmParameters;
import javax.crypto.AEADBadTagException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.GCMParameterSpec;
public class CipherInputStreamExceptions {
static SecretKeySpec key = new SecretKeySpec(new byte[16], "AES");
static GCMParameterSpec gcmspec = new GCMParameterSpec(128, new byte[16]);
static IvParameterSpec iv = new IvParameterSpec(new byte[16]);
static boolean failure = false;
/* Full read stream, check that getMoreData() is throwing an exception
* This test
* 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
* 2) Changes the last byte to invalidate the authetication tag.
* 3) Fully reads CipherInputStream to decrypt the message and closes
*/
static void gcm_AEADBadTag() throws Exception {
Cipher c;
byte[] read = new byte[200];
System.out.println("Running gcm_AEADBadTag");
// Encrypt 100 bytes with AES/GCM/PKCS5Padding
byte[] ct = encryptedText("GCM", 100);
// Corrupt the encrypted message
ct = corruptGCM(ct);
// Create stream for decryption
CipherInputStream in = getStream("GCM", ct);
try {
int size = in.read(read);
throw new RuntimeException("Fail: CipherInputStream.read() " +
"returned " + size + " and didn't throw an exception.");
} catch (IOException e) {
Throwable ec = e.getCause();
if (ec instanceof AEADBadTagException) {
System.out.println(" Pass.");
} else {
System.out.println(" Fail: " + ec.getMessage());
throw new RuntimeException(ec);
}
} finally {
in.close();
}
}
/* Short read stream,
* This test
* 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
* 2) Reads 100 bytes from stream to decrypt the message and closes
* 3) Make sure no value is returned by read()
* 4) Make sure no exception is thrown
*/
static void gcm_shortReadAEAD() throws Exception {
Cipher c;
byte[] read = new byte[100];
System.out.println("Running gcm_shortReadAEAD");
byte[] pt = new byte[600];
pt[0] = 1;
// Encrypt provided 600 bytes with AES/GCM/PKCS5Padding
byte[] ct = encryptedText("GCM", pt);
// Create stream for decryption
CipherInputStream in = getStream("GCM", ct);
int size = 0;
try {
size = in.read(read);
in.close();
if (read.length != 100) {
throw new RuntimeException("Fail: read size = " + read.length +
"should be 100.");
}
if (read[0] != 1) {
throw new RuntimeException("Fail: The decrypted text does " +
"not match the plaintext: '" + read[0] +"'");
}
} catch (IOException e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
System.out.println(" Pass.");
}
/*
* Verify doFinal() exception is suppressed when input stream is not
* read before it is closed.
* This test:
* 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
* 2) Changes the last byte to invalidate the authetication tag.
* 3) Opens a CipherInputStream and the closes it. Never reads from it.
*
* There should be no exception thrown.
*/
static void gcm_suppressUnreadCorrupt() throws Exception {
Cipher c;
byte[] read = new byte[200];
System.out.println("Running supressUnreadCorrupt test");
// Encrypt 100 bytes with AES/GCM/PKCS5Padding
byte[] ct = encryptedText("GCM", 100);
// Corrupt the encrypted message
ct = corruptGCM(ct);
// Create stream for decryption
CipherInputStream in = getStream("GCM", ct);
try {
in.close();
System.out.println(" Pass.");
} catch (IOException e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
}
/*
* Verify noexception thrown when 1 byte is read from a GCM stream
* and then closed
* This test:
* 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
* 2) Read one byte from the stream, expect no exception thrown.
* 4) Close stream,expect no exception thrown.
*/
static void gcm_oneReadByte() throws Exception {
System.out.println("Running gcm_oneReadByte test");
// Encrypt 100 bytes with AES/GCM/PKCS5Padding
byte[] ct = encryptedText("GCM", 100);
// Create stream for decryption
CipherInputStream in = getStream("GCM", ct);
try {
in.read();
System.out.println(" Pass.");
} catch (Exception e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
}
/*
* Verify exception thrown when 1 byte is read from a corrupted GCM stream
* and then closed
* This test:
* 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
* 2) Changes the last byte to invalidate the authetication tag.
* 3) Read one byte from the stream, expect exception thrown.
* 4) Close stream,expect no exception thrown.
*/
static void gcm_oneReadByteCorrupt() throws Exception {
System.out.println("Running gcm_oneReadByteCorrupt test");
// Encrypt 100 bytes with AES/GCM/PKCS5Padding
byte[] ct = encryptedText("GCM", 100);
// Corrupt the encrypted message
ct = corruptGCM(ct);
// Create stream for decryption
CipherInputStream in = getStream("GCM", ct);
try {
in.read();
System.out.println(" Fail. No exception thrown.");
} catch (IOException e) {
Throwable ec = e.getCause();
if (ec instanceof AEADBadTagException) {
System.out.println(" Pass.");
} else {
System.out.println(" Fail: " + ec.getMessage());
throw new RuntimeException(ec);
}
}
}
/* Check that close() does not throw an exception with full message in
* CipherInputStream's ibuffer.
* This test:
* 1) Encrypts a 97 byte message with AES/CBC/PKCS5Padding
* 2) Create a stream that sends 96 bytes.
* 3) Read stream once,
* 4) Close and expect no exception
*/
static void cbc_shortStream() throws Exception {
Cipher c;
AlgorithmParameters params;
byte[] read = new byte[200];
System.out.println("Running cbc_shortStream");
// Encrypt 97 byte with AES/CBC/PKCS5Padding
byte[] ct = encryptedText("CBC", 97);
// Create stream with only 96 bytes of encrypted data
CipherInputStream in = getStream("CBC", ct, 96);
try {
int size = in.read(read);
in.close();
if (size != 80) {
throw new RuntimeException("Fail: CipherInputStream.read() " +
"returned " + size + ". Should have been 80");
}
System.out.println(" Pass.");
} catch (IOException e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
}
/* Check that close() does not throw an exception when the whole message is
* inside the internal buffer (ibuffer) in CipherInputStream and we read
* one byte and close the stream.
* This test:
* 1) Encrypts a 400 byte message with AES/CBC/PKCS5Padding
* 2) Read one byte from the stream
* 3) Close and expect no exception
*/
static void cbc_shortRead400() throws Exception {
System.out.println("Running cbc_shortRead400");
// Encrypt 400 byte with AES/CBC/PKCS5Padding
byte[] ct = encryptedText("CBC", 400);
// Create stream with encrypted data
CipherInputStream in = getStream("CBC", ct);
try {
in.read();
in.close();
System.out.println(" Pass.");
} catch (IOException e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
}
/* Check that close() does not throw an exception when the inside the
* internal buffer (ibuffer) in CipherInputStream does not contain the
* whole message.
* This test:
* 1) Encrypts a 600 byte message with AES/CBC/PKCS5Padding
* 2) Read one byte from the stream
* 3) Close and expect no exception
*/
static void cbc_shortRead600() throws Exception {
System.out.println("Running cbc_shortRead600");
// Encrypt 600 byte with AES/CBC/PKCS5Padding
byte[] ct = encryptedText("CBC", 600);
// Create stream with encrypted data
CipherInputStream in = getStream("CBC", ct);
try {
in.read();
in.close();
System.out.println(" Pass.");
} catch (IOException e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
}
/* Check that exception is thrown when message is fully read
* This test:
* 1) Encrypts a 96 byte message with AES/CBC/PKCS5Padding
* 2) Create a stream that sends 95 bytes.
* 3) Read stream to the end
* 4) Expect IllegalBlockSizeException thrown
*/
static void cbc_readAllIllegalBlockSize() throws Exception {
byte[] read = new byte[200];
System.out.println("Running cbc_readAllIllegalBlockSize test");
// Encrypt 96 byte with AES/CBC/PKCS5Padding
byte[] ct = encryptedText("CBC", 96);
// Create a stream with only 95 bytes of encrypted data
CipherInputStream in = getStream("CBC", ct, 95);
try {
int s, size = 0;
while ((s = in.read(read)) != -1) {
size += s;
}
throw new RuntimeException("Fail: No IllegalBlockSizeException. " +
"CipherInputStream.read() returned " + size);
} catch (IOException e) {
Throwable ec = e.getCause();
if (ec instanceof IllegalBlockSizeException) {
System.out.println(" Pass.");
} else {
System.out.println(" Fail: " + ec.getMessage());
throw new RuntimeException(ec);
}
}
}
/* Generic method to create encrypted text */
static byte[] encryptedText(String mode, int length) throws Exception{
return encryptedText(mode, new byte[length]);
}
/* Generic method to create encrypted text */
static byte[] encryptedText(String mode, byte[] pt) throws Exception{
Cipher c;
if (mode.compareTo("GCM") == 0) {
c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE");
c.init(Cipher.ENCRYPT_MODE, key, gcmspec);
} else if (mode.compareTo("CBC") == 0) {
c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
c.init(Cipher.ENCRYPT_MODE, key, iv);
} else {
return null;
}
return c.doFinal(pt);
}
/* Generic method to get a properly setup CipherInputStream */
static CipherInputStream getStream(String mode, byte[] ct) throws Exception {
return getStream(mode, ct, ct.length);
}
/* Generic method to get a properly setup CipherInputStream */
static CipherInputStream getStream(String mode, byte[] ct, int length)
throws Exception {
Cipher c;
if (mode.compareTo("GCM") == 0) {
c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE");
c.init(Cipher.DECRYPT_MODE, key, gcmspec);
} else if (mode.compareTo("CBC") == 0) {
c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
c.init(Cipher.DECRYPT_MODE, key, iv);
} else {
return null;
}
return new CipherInputStream(new ByteArrayInputStream(ct, 0, length), c);
}
/* Generic method for corrupting a GCM message. Change the last
* byte on of the authentication tag
*/
static byte[] corruptGCM(byte[] ct) {
ct[ct.length - 1] = (byte) (ct[ct.length - 1] + 1);
return ct;
}
public static void main(String[] args) throws Exception {
gcm_AEADBadTag();
gcm_shortReadAEAD();
gcm_suppressUnreadCorrupt();
gcm_oneReadByte();
gcm_oneReadByteCorrupt();
cbc_shortStream();
cbc_shortRead400();
cbc_shortRead600();
cbc_readAllIllegalBlockSize();
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;
/**
* @test
* @bug 4958064
* @author Sergey Bylokhov
*/
public final class CanWriteSequence {
public static void main(final String[] args) throws Exception {
final IIORegistry registry = IIORegistry.getDefaultInstance();
final Iterator<ImageWriterSpi> iter =
registry.getServiceProviders(ImageWriterSpi.class,
provider -> true, true);
// Validates all supported ImageWriters
while (iter.hasNext()) {
final ImageWriter writer = iter.next().createWriterInstance();
System.out.println("ImageWriter = " + writer);
test(writer);
}
System.out.println("Test passed");
}
private static void test(final ImageWriter writer) throws Exception {
final File file = File.createTempFile("temp", ".img");
file.deleteOnExit();
final FileOutputStream fos = new FileOutputStream(file);
final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
final IIOMetadata data = writer.getDefaultStreamMetadata(null);
if (writer.canWriteSequence()) {
writer.prepareWriteSequence(data);
} else {
try {
writer.prepareWriteSequence(data);
throw new RuntimeException(
"UnsupportedOperationException was not thrown");
} catch (final UnsupportedOperationException ignored) {
// expected
}
}
writer.dispose();
ios.close();
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.event.IIOWriteProgressListener;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;
import static java.awt.image.BufferedImage.TYPE_BYTE_BINARY;
/**
* @test
* @bug 4952954
* @summary abortFlag must be cleared for every ImageWriter.write operation
* @author Sergey Bylokhov
*/
public final class WriteAfterAbort implements IIOWriteProgressListener {
private volatile boolean abortFlag = true;
private volatile boolean isAbortCalled;
private volatile boolean isCompleteCalled;
private volatile boolean isProgressCalled;
private volatile boolean isStartedCalled;
private static final int WIDTH = 100;
private static final int HEIGHT = 100;
private void test(final ImageWriter writer) throws IOException {
// Image initialization
final BufferedImage imageWrite = new BufferedImage(WIDTH, HEIGHT,
TYPE_BYTE_BINARY);
final Graphics2D g = imageWrite.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.dispose();
// File initialization
final File file = File.createTempFile("temp", ".img");
file.deleteOnExit();
final FileOutputStream fos = new SkipWriteOnAbortOutputStream(file);
final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
writer.addIIOWriteProgressListener(this);
// This write will be aborted, and file will not be touched
writer.write(imageWrite);
if (!isStartedCalled) {
throw new RuntimeException("Started should be called");
}
if (!isProgressCalled) {
throw new RuntimeException("Progress should be called");
}
if (!isAbortCalled) {
throw new RuntimeException("Abort should be called");
}
if (isCompleteCalled) {
throw new RuntimeException("Complete should not be called");
}
// Flush aborted data
ios.flush();
// This write should be completed successfully and the file should
// contain correct image data.
abortFlag = false;
isAbortCalled = false;
isCompleteCalled = false;
isProgressCalled = false;
isStartedCalled = false;
writer.write(imageWrite);
if (!isStartedCalled) {
throw new RuntimeException("Started should be called");
}
if (!isProgressCalled) {
throw new RuntimeException("Progress should be called");
}
if (isAbortCalled) {
throw new RuntimeException("Abort should not be called");
}
if (!isCompleteCalled) {
throw new RuntimeException("Complete should be called");
}
writer.dispose();
ios.close();
// Validates content of the file.
final BufferedImage imageRead = ImageIO.read(file);
for (int x = 0; x < WIDTH; ++x) {
for (int y = 0; y < HEIGHT; ++y) {
if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
throw new RuntimeException("Test failed.");
}
}
}
}
public static void main(final String[] args) throws IOException {
final IIORegistry registry = IIORegistry.getDefaultInstance();
final Iterator<ImageWriterSpi> iter = registry.getServiceProviders(
ImageWriterSpi.class, provider -> true, true);
// Validates all supported ImageWriters
while (iter.hasNext()) {
final WriteAfterAbort writeAfterAbort = new WriteAfterAbort();
final ImageWriter writer = iter.next().createWriterInstance();
System.out.println("ImageWriter = " + writer);
writeAfterAbort.test(writer);
}
System.out.println("Test passed");
}
// Callbacks
@Override
public void imageComplete(ImageWriter source) {
isCompleteCalled = true;
}
@Override
public void imageProgress(ImageWriter source, float percentageDone) {
isProgressCalled = true;
if (percentageDone > 50 && abortFlag) {
source.abort();
}
}
@Override
public void imageStarted(ImageWriter source, int imageIndex) {
isStartedCalled = true;
}
@Override
public void writeAborted(final ImageWriter source) {
isAbortCalled = true;
}
@Override
public void thumbnailComplete(ImageWriter source) {
}
@Override
public void thumbnailProgress(ImageWriter source, float percentageDone) {
}
@Override
public void thumbnailStarted(ImageWriter source, int imageIndex,
int thumbnailIndex) {
}
/**
* We need to skip writes on abort, because content of the file after abort
* is undefined.
*/
private class SkipWriteOnAbortOutputStream extends FileOutputStream {
SkipWriteOnAbortOutputStream(File file) throws FileNotFoundException {
super(file);
}
@Override
public void write(int b) throws IOException {
if (!abortFlag) {
super.write(b);
}
}
@Override
public void write(byte[] b) throws IOException {
if (!abortFlag) {
super.write(b);
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (!abortFlag) {
super.write(b, off, len);
}
}
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Toolkit;
import javax.sound.midi.MidiSystem;
/**
* @test
* @bug 8068412
* @author Sergey Bylokhov
*/
public final class InitializationHang {
public static void main(final String[] argv) throws Exception {
MidiSystem.getReceiver();
Toolkit.getDefaultToolkit();
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import static java.awt.image.BufferedImage.TYPE_INT_RGB;
/**
* @test
* @bug 6573305
* @summary Animated icon should animate when the JButton is pressed.
* @author Sergey Bylokhov
*/
public final class AnimatedIcon {
public static void main(final String[] args) throws Exception {
SwingUtilities.invokeAndWait(() -> {
final BufferedImage bi = new BufferedImage(1, 1, TYPE_INT_RGB);
final ImageIcon icon = new ImageIcon(bi);
final JButton button = new JButton(icon);
// Default icon is set => imageUpdate should return true for it
isAnimated(bi, button);
button.getModel().setPressed(true);
button.getModel().setArmed(true);
isAnimated(bi, button);
button.getModel().setPressed(false);
button.getModel().setArmed(false);
button.getModel().setSelected(true);
isAnimated(bi, button);
button.getModel().setSelected(false);
button.getModel().setRollover(true);
button.setRolloverEnabled(true);
isAnimated(bi, button);
button.getModel().setSelected(true);
isAnimated(bi, button);
// Default icon is not set => imageUpdate should return true for
// other icons if any
button.setIcon(null);
button.setPressedIcon(icon);
button.getModel().setPressed(true);
button.getModel().setArmed(true);
isAnimated(bi, button);
});
}
private static void isAnimated(BufferedImage bi, JButton button) {
if (!button.imageUpdate(bi, ImageObserver.SOMEBITS, 0, 0, 1, 1)) {
throw new RuntimeException();
}
}
}
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE;
import static javax.swing.UIManager.getInstalledLookAndFeels;
/**
* @test
* @bug 8073795
* @summary JMenuBar has incorrect border when the window is on retina display.
* @author Sergey Bylokhov
* @run main/othervm MisplacedBorder
* @run main/othervm -Dswing.metalTheme=steel MisplacedBorder
*/
public final class MisplacedBorder implements Runnable {
public static final int W = 400;
public static final int H = 400;
public static void main(final String[] args) throws Exception {
for (final UIManager.LookAndFeelInfo laf : getInstalledLookAndFeels()) {
SwingUtilities.invokeAndWait(() -> setLookAndFeel(laf));
SwingUtilities.invokeAndWait(new MisplacedBorder());
}
System.out.println("Test passed");
}
@Override
public void run() {
final JMenuBar menubar = new JMenuBar();
menubar.add(new JMenu(""));
menubar.add(new JMenu(""));
final JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.setJMenuBar(menubar);
frame.setSize(W / 3, H / 3);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// draw menu bar using standard order.
final BufferedImage bi1 = step1(menubar);
// draw menu border on top of the menu bar, nothing should be changed.
final BufferedImage bi2 = step2(menubar);
frame.dispose();
for (int x = 0; x < W; ++x) {
for (int y = 0; y < H; ++y) {
if (bi1.getRGB(x, y) != bi2.getRGB(x, y)) {
try {
ImageIO.write(bi1, "png", new File("image1.png"));
ImageIO.write(bi2, "png", new File("image2.png"));
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException("Failed: wrong color");
}
}
}
}
/**
* Draws standard JMenuBar.
*/
private BufferedImage step1(final JMenuBar menubar) {
final BufferedImage bi1 = new BufferedImage(W, H, TYPE_INT_ARGB_PRE);
final Graphics2D g2d = bi1.createGraphics();
g2d.scale(2, 2);
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, W, H);
menubar.paintAll(g2d);
g2d.dispose();
return bi1;
}
/**
* Draws standard JMenuBar and border on top of it.
*/
private BufferedImage step2(final JMenuBar menubar) {
final BufferedImage bi2 = new BufferedImage(W, H, TYPE_INT_ARGB_PRE);
final Graphics2D g2d2 = bi2.createGraphics();
g2d2.scale(2, 2);
g2d2.setColor(Color.RED);
g2d2.fillRect(0, 0, W, H);
menubar.paintAll(g2d2);
menubar.getBorder().paintBorder(menubar, g2d2, menubar.getX(), menubar
.getX(), menubar.getWidth(), menubar.getHeight());
g2d2.dispose();
return bi2;
}
private static void setLookAndFeel(final UIManager.LookAndFeelInfo laf) {
try {
UIManager.setLookAndFeel(laf.getClassName());
System.out.println("LookAndFeel: " + laf.getClassName());
} catch (ClassNotFoundException | InstantiationException |
UnsupportedLookAndFeelException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
/**
* @test
* @bug 8015085
* @summary Shortening via " ... " is broken for Strings containing a combining
* diaeresis.
* @author Sergey Bylokhov
*/
public class TestBadBreak {
static JFrame frame;
static Robot robot;
static final String withCombiningDiaeresis = "123p://.aaaaaaaaaaaaaaaaaaaaaa.123/a\u0308" ;
static final String withoutCombiningDiaeresis = "123p://.aaaaaaaaaaaaaaaaaaaaaa.123/\u00E4" ;
public static void main(final String[] args) throws Exception {
robot = new Robot();
final BufferedImage bi1 = new BufferedImage(200, 90, TYPE_INT_ARGB);
final BufferedImage bi2 = new BufferedImage(200, 90, TYPE_INT_ARGB);
test(withCombiningDiaeresis, bi1);
test(withoutCombiningDiaeresis, bi2);
for (int x = 0; x < bi1.getWidth(); ++x) {
for (int y = 0; y < bi1.getHeight(); ++y) {
if (bi1.getRGB(x, y) != bi2.getRGB(x, y)) {
ImageIO.write(bi1, "png", new File("image1.png"));
ImageIO.write(bi2, "png", new File("image2.png"));
throw new RuntimeException("Wrong color");
}
}
}
}
private static void test(final String text, final BufferedImage i1)
throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame = new JFrame();
final JLabel label = new JLabel(text) {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = i1.createGraphics();
super.paintComponent(g2d);
g2d.dispose();
}
};
frame.getContentPane().add(label);
frame.setBounds(200, 200, 200, 90);
}
});
robot.waitForIdle();
SwingUtilities.invokeAndWait(() -> frame.setVisible(true));
robot.waitForIdle();
SwingUtilities.invokeAndWait(frame::dispose);
robot.waitForIdle();
}
}
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* @test
* @bug 7180976
* @author Sergey Bylokhov
*/
public final class Pending implements Runnable {
private static volatile boolean passed;
public static void main(final String[] args) throws Exception {
SwingUtilities.invokeLater(new Pending());
Thread.sleep(10000);
if (!passed) {
throw new RuntimeException("Test failed");
}
}
@Override
public void run() {
UIManager.put("foobar", "Pending");
UIManager.get("foobar");
passed = true;
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import javax.swing.text.html.parser.ContentModel;
import javax.swing.text.html.parser.DTD;
import javax.swing.text.html.parser.Element;
/*
* @test
* @bug 8074956
* @author Alexey Ivanov
* @summary Tests correct handling of additional HTML elements in ContentModel
* @run main bug8074956
*/
public class bug8074956 {
public static void main(String[] args) throws Exception {
final DTD html32 = DTD.getDTD("html32");
ContentModel contentModel = new ContentModel('&', new ContentModel());
Element elem1 = html32.getElement("html-element");
contentModel.first(elem1);
Element elem2 = html32.getElement("test-element");
// Shouldn't throw ArrayIndexOutOfBoundsException
contentModel.first(elem2);
}
}
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -23,57 +23,83 @@
/*
* @test
* @bug 8046817
* @summary schemagen fails to generate xsd for enum types
* @bug 8046817 8073357
* @summary schemagen fails to generate xsd for enum types.
* Check that order of Enum values is preserved.
* @run main/othervm GenerateEnumSchema
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Collectors;
public class GenerateEnumSchema {
private static final String SCHEMA_OUTPUT_FILENAME = "schema1.xsd";
private static final File schemaOutputFile = new File(SCHEMA_OUTPUT_FILENAME);
private static final String[] expectedEnums = {
"\"FIRST\"", "\"ONE\"", "\"TWO\"", "\"THREE\"",
"\"FOUR\"", "\"FIVE\"", "\"SIX\"", "\"LAST\""};
private static String schemaContent = "";
public static void main(String[] args) throws Exception {
public static void main(String[] args) throws Exception, IOException {
//Check schema generation for class type
runSchemaGen("TestClassType.java");
checkIfSchemaGenerated();
readSchemaContent();
checkSchemaContent("<xs:complexType name=\"testClassType\">");
checkSchemaContent("<xs:element name=\"a\" type=\"xs:int\"/>");
schemaOutputFile.delete();
//Check schema generation for enum type
runSchemaGen("TestEnumType.java");
checkIfSchemaGenerated();
readSchemaContent();
//Check if Enum type schema is generated
checkSchemaContent("<xs:simpleType name=\"testEnumType\">");
checkSchemaContent("<xs:enumeration value=\"ONE\"/>");
checkSchemaContent("<xs:enumeration value=\"TWO\"/>");
checkSchemaContent("<xs:enumeration value=\"THREE\"/>");
//Check the sequence of enum values order
checkEnumOrder();
schemaOutputFile.delete();
}
// Check if schema file successfully generated by schemagen
private static void checkIfSchemaGenerated() {
if (!schemaOutputFile.exists()) {
throw new RuntimeException("FAIL:" + SCHEMA_OUTPUT_FILENAME + " was not generated by schemagen tool");
}
}
private static void checkSchemaContent(String exp_token) throws FileNotFoundException {
System.out.print("Check if generated schema contains '" + exp_token + "' string: ");
try (Scanner scanner = new Scanner(schemaOutputFile)) {
if (scanner.findWithinHorizon(exp_token, 0) != null) {
System.out.println("OK");
return;
}
//Read schema content from file
private static void readSchemaContent() throws Exception {
schemaContent = Files.lines(schemaOutputFile.toPath()).collect(Collectors.joining(""));
}
// Check if schema file contains specific string
private static void checkSchemaContent(String expContent) {
System.out.print("Check if generated schema contains '" + expContent + "' string: ");
if (schemaContent.contains(expContent)) {
System.out.println("OK");
return;
}
System.out.println("FAIL");
throw new RuntimeException("The '" + exp_token + "' is not found in generated schema");
throw new RuntimeException("The '" + expContent + "' is not found in generated schema");
}
// Check if the generated schema contains all enum constants
// and their order is preserved
private static void checkEnumOrder() throws Exception {
int prevElem = -1;
for (String elem : expectedEnums) {
int curElem = schemaContent.indexOf(elem);
System.out.println(elem + " position = " + curElem);
if (curElem < prevElem) {
throw new RuntimeException("FAIL: Enum values order is incorrect or " + elem + " element is not found");
}
prevElem = curElem;
}
}
private static String getClassFilePath(String filename) {
......
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -25,5 +25,5 @@ import javax.xml.bind.annotation.XmlEnum;
@XmlEnum(String.class)
public enum TestEnumType {
ONE, TWO, THREE
FIRST, ONE, TWO, THREE, FOUR, FIVE, SIX, LAST
}
/*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.testlibrary;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import static jdk.testlibrary.OSInfo.OSType.*;
/**
* @author Pavel Porvatov
* copied to testlibrary by yan
*/
public class OSInfo {
public static enum OSType {
WINDOWS,
LINUX,
SOLARIS,
MACOSX,
UNKNOWN
}
/*
The map windowsVersionMap must contain all windows version constants except WINDOWS_UNKNOWN,
and so the method getWindowsVersion() will return the constant for known OS.
It allows compare objects by "==" instead of "equals".
*/
public static final WindowsVersion WINDOWS_UNKNOWN = new WindowsVersion(-1, -1);
public static final WindowsVersion WINDOWS_95 = new WindowsVersion(4, 0);
public static final WindowsVersion WINDOWS_98 = new WindowsVersion(4, 10);
public static final WindowsVersion WINDOWS_ME = new WindowsVersion(4, 90);
public static final WindowsVersion WINDOWS_2000 = new WindowsVersion(5, 0);
public static final WindowsVersion WINDOWS_XP = new WindowsVersion(5, 1);
public static final WindowsVersion WINDOWS_2003 = new WindowsVersion(5, 2);
public static final WindowsVersion WINDOWS_VISTA = new WindowsVersion(6, 0);
private static final String OS_NAME = "os.name";
private static final String OS_VERSION = "os.version";
private final static Map<String, WindowsVersion> windowsVersionMap = new HashMap<String, OSInfo.WindowsVersion>();
static {
windowsVersionMap.put(WINDOWS_95.toString(), WINDOWS_95);
windowsVersionMap.put(WINDOWS_98.toString(), WINDOWS_98);
windowsVersionMap.put(WINDOWS_ME.toString(), WINDOWS_ME);
windowsVersionMap.put(WINDOWS_2000.toString(), WINDOWS_2000);
windowsVersionMap.put(WINDOWS_XP.toString(), WINDOWS_XP);
windowsVersionMap.put(WINDOWS_2003.toString(), WINDOWS_2003);
windowsVersionMap.put(WINDOWS_VISTA.toString(), WINDOWS_VISTA);
}
private static final PrivilegedAction<OSType> osTypeAction = new PrivilegedAction<OSType>() {
public OSType run() {
return getOSType();
}
};
private OSInfo() {
// Don't allow to create instances
}
/**
* Returns type of operating system.
*/
public static OSType getOSType() throws SecurityException {
String osName = System.getProperty(OS_NAME);
if (osName != null) {
if (osName.contains("Windows")) {
return WINDOWS;
}
if (osName.contains("Linux")) {
return LINUX;
}
if (osName.contains("Solaris") || osName.contains("SunOS")) {
return SOLARIS;
}
if (osName.contains("OS X")) {
return MACOSX;
}
// determine another OS here
}
return UNKNOWN;
}
public static PrivilegedAction<OSType> getOSTypeAction() {
return osTypeAction;
}
public static WindowsVersion getWindowsVersion() throws SecurityException {
String osVersion = System.getProperty(OS_VERSION);
if (osVersion == null) {
return WINDOWS_UNKNOWN;
}
synchronized (windowsVersionMap) {
WindowsVersion result = windowsVersionMap.get(osVersion);
if (result == null) {
// Try parse version and put object into windowsVersionMap
String[] arr = osVersion.split("\\.");
if (arr.length == 2) {
try {
result = new WindowsVersion(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]));
} catch (NumberFormatException e) {
return WINDOWS_UNKNOWN;
}
} else {
return WINDOWS_UNKNOWN;
}
windowsVersionMap.put(osVersion, result);
}
return result;
}
}
public static class WindowsVersion implements Comparable<WindowsVersion> {
private final int major;
private final int minor;
private WindowsVersion(int major, int minor) {
this.major = major;
this.minor = minor;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int compareTo(WindowsVersion o) {
int result = major - o.getMajor();
if (result == 0) {
result = minor - o.getMinor();
}
return result;
}
public boolean equals(Object obj) {
return obj instanceof WindowsVersion && compareTo((WindowsVersion) obj) == 0;
}
public int hashCode() {
return 31 * major + minor;
}
public String toString() {
return major + "." + minor;
}
}
}
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -24,6 +24,8 @@
package jdk.testlibrary;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
......@@ -394,4 +396,23 @@ public final class OutputAnalyzer {
public int getExitValue() {
return exitValue;
}
/**
* Get the contents of the output buffer (stdout and stderr) as list of strings.
* Output will be split by system property 'line.separator'.
*
* @return Contents of the output buffer as list of strings
*/
public List<String> asLines() {
return asLines(getOutput());
}
private List<String> asLines(String buffer) {
List<String> l = new ArrayList<>();
String[] a = buffer.split(Utils.NEW_LINE);
for (String string : a) {
l.add(string);
}
return l;
}
}
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -31,6 +31,7 @@ import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.Map;
......@@ -41,6 +42,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import sun.management.VMManagement;
......@@ -374,4 +376,40 @@ public final class ProcessTools {
}
return cmd.toString().trim();
}
/**
* Executes a process, waits for it to finish, prints the process output
* to stdout, and returns the process output.
*
* The process will have exited before this method returns.
*
* @param cmds The command line to execute.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
public static OutputAnalyzer executeCommand(String... cmds)
throws Throwable {
String cmdLine = Arrays.stream(cmds).collect(Collectors.joining(" "));
System.out.println("Command line: [" + cmdLine + "]");
OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds);
System.out.println(analyzer.getOutput());
return analyzer;
}
/**
* Executes a process, waits for it to finish, prints the process output
* to stdout and returns the process output.
*
* The process will have exited before this method returns.
*
* @param pb The ProcessBuilder to execute.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
public static OutputAnalyzer executeCommand(ProcessBuilder pb)
throws Throwable {
String cmdLine = pb.command().stream().collect(Collectors.joining(" "));
System.out.println("Command line: [" + cmdLine + "]");
OutputAnalyzer analyzer = ProcessTools.executeProcess(pb);
System.out.println(analyzer.getOutput());
return analyzer;
}
}
/*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -45,7 +45,7 @@ import javax.net.ssl.*;
public class CipherTest {
// use any available port for the server socket
static int serverPort = 0;
static volatile int serverPort = 0;
final int THREADS;
......
/*
* Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -42,7 +42,7 @@ class JSSEServer extends CipherTest.Server {
serverContext.init(new KeyManager[] {cipherTest.keyManager}, new TrustManager[] {cipherTest.trustManager}, cipherTest.secureRandom);
SSLServerSocketFactory factory = (SSLServerSocketFactory)serverContext.getServerSocketFactory();
serverSocket = (SSLServerSocket)factory.createServerSocket(cipherTest.serverPort);
serverSocket = (SSLServerSocket)factory.createServerSocket(0);
cipherTest.serverPort = serverSocket.getLocalPort();
serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites());
serverSocket.setWantClientAuth(true);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册