From b585c203ace79ec19ec3757d9ba5faf3d3c287e7 Mon Sep 17 00:00:00 2001 From: Kim Barrett Date: Thu, 31 Jul 2014 11:10:02 +0200 Subject: [PATCH 001/149] 8048949: Requeue queue implementation Devirtualize flush and move calls. Reviewed-by: brutisso, tschatzl, mschoene --- .../vm/gc_implementation/g1/dirtyCardQueue.hpp | 9 ++++++++- .../src/share/vm/gc_implementation/g1/ptrQueue.cpp | 8 ++++++-- .../src/share/vm/gc_implementation/g1/ptrQueue.hpp | 13 ++++++++----- .../src/share/vm/gc_implementation/g1/satbQueue.cpp | 2 +- .../src/share/vm/gc_implementation/g1/satbQueue.hpp | 7 +++---- 5 files changed, 26 insertions(+), 13 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp index ac066a08143..27d287ea962 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -47,6 +47,13 @@ public: // active field set to true. PtrQueue(qset_, perm, true /* active */) { } + // Flush before destroying; queue may be used to capture pending work while + // doing something else, with auto-flush on completion. + ~DirtyCardQueue() { if (!is_permanent()) flush(); } + + // Process queue entries and release resources. + void flush() { flush_impl(); } + // Apply the closure to all elements, and reset the index to make the // buffer empty. If a closure application returns "false", return // "false" immediately, halting the iteration. If "consume" is true, diff --git a/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.cpp b/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.cpp index 45069c77ed3..f7202ab2c2a 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.cpp @@ -31,11 +31,15 @@ #include "runtime/thread.inline.hpp" PtrQueue::PtrQueue(PtrQueueSet* qset, bool perm, bool active) : - _qset(qset), _buf(NULL), _index(0), _active(active), + _qset(qset), _buf(NULL), _index(0), _sz(0), _active(active), _perm(perm), _lock(NULL) {} -void PtrQueue::flush() { +PtrQueue::~PtrQueue() { + assert(_perm || (_buf == NULL), "queue must be flushed before delete"); +} + +void PtrQueue::flush_impl() { if (!_perm && _buf != NULL) { if (_index == _sz) { // No work to do. diff --git a/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.hpp b/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.hpp index 37f0d6562f8..988e90ba8c9 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -65,15 +65,18 @@ protected: Mutex* _lock; PtrQueueSet* qset() { return _qset; } + bool is_permanent() const { return _perm; } + + // Process queue entries and release resources, if not permanent. + void flush_impl(); public: // Initialize this queue to contain a null buffer, and be part of the // given PtrQueueSet. PtrQueue(PtrQueueSet* qset, bool perm = false, bool active = false); - // Release any contained resources. - virtual void flush(); - // Calls flush() when destroyed. - ~PtrQueue() { flush(); } + + // Requires queue flushed or permanent. + ~PtrQueue(); // Associate a lock with a ptr queue. void set_lock(Mutex* lock) { _lock = lock; } diff --git a/hotspot/src/share/vm/gc_implementation/g1/satbQueue.cpp b/hotspot/src/share/vm/gc_implementation/g1/satbQueue.cpp index cc9cc2d5242..2ab59657776 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/satbQueue.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/satbQueue.cpp @@ -39,7 +39,7 @@ void ObjPtrQueue::flush() { // first before we flush it, otherwise we might end up with an // enqueued buffer with refs into the CSet which breaks our invariants. filter(); - PtrQueue::flush(); + flush_impl(); } // This method removes entries from an SATB buffer that will not be diff --git a/hotspot/src/share/vm/gc_implementation/g1/satbQueue.hpp b/hotspot/src/share/vm/gc_implementation/g1/satbQueue.hpp index a295ebc6c04..89c42c8947e 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/satbQueue.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/satbQueue.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -60,9 +60,8 @@ public: // field to true. This is done in JavaThread::initialize_queues(). PtrQueue(qset, perm, false /* active */) { } - // Overrides PtrQueue::flush() so that it can filter the buffer - // before it is flushed. - virtual void flush(); + // Process queue entries and free resources. + void flush(); // Overrides PtrQueue::should_enqueue_buffer(). See the method's // definition for more information. From 0cb7282446080ed5112818bd69161859f827e72f Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Fri, 8 Aug 2014 13:23:30 -0700 Subject: [PATCH 002/149] 8047130: Fewer escapes from escape analysis Treat max_stack attribute as an int in bytecode escape analyzer Reviewed-by: kvn, twisti, ahgross --- hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp index ae9def38b26..4c0cd3d8083 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp @@ -89,8 +89,8 @@ class BCEscapeAnalyzer::StateInfo { public: ArgumentMap *_vars; ArgumentMap *_stack; - short _stack_height; - short _max_stack; + int _stack_height; + int _max_stack; bool _initialized; ArgumentMap empty_map; From b986429c73f40fe21633f2ee229ebdff9da9280d Mon Sep 17 00:00:00 2001 From: Bengt Rutisson Date: Tue, 19 Aug 2014 11:17:36 +0200 Subject: [PATCH 003/149] 8049253: Better GC validation Also reviewed by: boris.molodenkov@oracle.com Co-authored-by: Yasumasa Suenaga Reviewed-by: dcubed, minqi, mschoene --- .../src/share/vm/utilities/defaultStream.hpp | 2 + hotspot/src/share/vm/utilities/ostream.cpp | 182 +++++++++++++----- 2 files changed, 135 insertions(+), 49 deletions(-) diff --git a/hotspot/src/share/vm/utilities/defaultStream.hpp b/hotspot/src/share/vm/utilities/defaultStream.hpp index 8b5c1a85a8a..bdc29551155 100644 --- a/hotspot/src/share/vm/utilities/defaultStream.hpp +++ b/hotspot/src/share/vm/utilities/defaultStream.hpp @@ -41,6 +41,8 @@ class defaultStream : public xmlTextStream { void init(); void init_log(); + fileStream* open_file(const char* log_name); + void start_log(); void finish_log(); void finish_log_on_error(char *buf, int buflen); public: diff --git a/hotspot/src/share/vm/utilities/ostream.cpp b/hotspot/src/share/vm/utilities/ostream.cpp index d77eb0f3355..b187f7a029f 100644 --- a/hotspot/src/share/vm/utilities/ostream.cpp +++ b/hotspot/src/share/vm/utilities/ostream.cpp @@ -367,7 +367,6 @@ extern Mutex* tty_lock; #define EXTRACHARLEN 32 #define CURRENTAPPX ".current" -#define FILENAMEBUFLEN 1024 // convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS char* get_datetime_string(char *buf, size_t len) { os::local_time_string(buf, len); @@ -401,7 +400,6 @@ static const char* make_log_name_internal(const char* log_name, const char* forc buffer_length = strlen(log_name) + 1; } - // const char* star = strchr(basename, '*'); const char* pts = strstr(basename, "%p"); int pid_pos = (pts == NULL) ? -1 : (pts - nametail); @@ -416,6 +414,11 @@ static const char* make_log_name_internal(const char* log_name, const char* forc buffer_length += strlen(tms); } + // File name is too long. + if (buffer_length > JVM_MAXPATHLEN) { + return NULL; + } + // Create big enough buffer. char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal); @@ -489,46 +492,88 @@ static const char* make_log_name(const char* log_name, const char* force_directo void test_loggc_filename() { int pid; char tms[32]; - char i_result[FILENAMEBUFLEN]; + char i_result[JVM_MAXPATHLEN]; const char* o_result; get_datetime_string(tms, sizeof(tms)); pid = os::current_process_id(); // test.log - jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "test.log", tms); + jio_snprintf(i_result, JVM_MAXPATHLEN, "test.log", tms); o_result = make_log_name_internal("test.log", NULL, pid, tms); assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test.log\", NULL)"); FREE_C_HEAP_ARRAY(char, o_result); // test-%t-%p.log - jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "test-%s-pid%u.log", tms, pid); + jio_snprintf(i_result, JVM_MAXPATHLEN, "test-%s-pid%u.log", tms, pid); o_result = make_log_name_internal("test-%t-%p.log", NULL, pid, tms); assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t-%%p.log\", NULL)"); FREE_C_HEAP_ARRAY(char, o_result); // test-%t%p.log - jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "test-%spid%u.log", tms, pid); + jio_snprintf(i_result, JVM_MAXPATHLEN, "test-%spid%u.log", tms, pid); o_result = make_log_name_internal("test-%t%p.log", NULL, pid, tms); assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t%%p.log\", NULL)"); FREE_C_HEAP_ARRAY(char, o_result); // %p%t.log - jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "pid%u%s.log", pid, tms); + jio_snprintf(i_result, JVM_MAXPATHLEN, "pid%u%s.log", pid, tms); o_result = make_log_name_internal("%p%t.log", NULL, pid, tms); assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p%%t.log\", NULL)"); FREE_C_HEAP_ARRAY(char, o_result); // %p-test.log - jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "pid%u-test.log", pid); + jio_snprintf(i_result, JVM_MAXPATHLEN, "pid%u-test.log", pid); o_result = make_log_name_internal("%p-test.log", NULL, pid, tms); assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p-test.log\", NULL)"); FREE_C_HEAP_ARRAY(char, o_result); // %t.log - jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "%s.log", tms); + jio_snprintf(i_result, JVM_MAXPATHLEN, "%s.log", tms); o_result = make_log_name_internal("%t.log", NULL, pid, tms); assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%t.log\", NULL)"); FREE_C_HEAP_ARRAY(char, o_result); + + { + // longest filename + char longest_name[JVM_MAXPATHLEN]; + memset(longest_name, 'a', sizeof(longest_name)); + longest_name[JVM_MAXPATHLEN - 1] = '\0'; + o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms); + assert(strcmp(longest_name, o_result) == 0, err_msg("longest name does not match. expected '%s' but got '%s'", longest_name, o_result)); + FREE_C_HEAP_ARRAY(char, o_result); + } + + { + // too long file name + char too_long_name[JVM_MAXPATHLEN + 100]; + int too_long_length = sizeof(too_long_name); + memset(too_long_name, 'a', too_long_length); + too_long_name[too_long_length - 1] = '\0'; + o_result = make_log_name_internal((const char*)&too_long_name, NULL, pid, tms); + assert(o_result == NULL, err_msg("Too long file name should return NULL, but got '%s'", o_result)); + } + + { + // too long with timestamp + char longest_name[JVM_MAXPATHLEN]; + memset(longest_name, 'a', JVM_MAXPATHLEN); + longest_name[JVM_MAXPATHLEN - 3] = '%'; + longest_name[JVM_MAXPATHLEN - 2] = 't'; + longest_name[JVM_MAXPATHLEN - 1] = '\0'; + o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms); + assert(o_result == NULL, err_msg("Too long file name after timestamp expansion should return NULL, but got '%s'", o_result)); + } + + { + // too long with pid + char longest_name[JVM_MAXPATHLEN]; + memset(longest_name, 'a', JVM_MAXPATHLEN); + longest_name[JVM_MAXPATHLEN - 3] = '%'; + longest_name[JVM_MAXPATHLEN - 2] = 'p'; + longest_name[JVM_MAXPATHLEN - 1] = '\0'; + o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms); + assert(o_result == NULL, err_msg("Too long file name after pid expansion should return NULL, but got '%s'", o_result)); + } } #endif // PRODUCT @@ -637,9 +682,16 @@ gcLogFileStream::gcLogFileStream(const char* file_name) { _bytes_written = 0L; _file_name = make_log_name(file_name, NULL); + if (_file_name == NULL) { + warning("Cannot open file %s: file name is too long.\n", file_name); + _need_close = false; + UseGCLogFileRotation = false; + return; + } + // gc log file rotation if (UseGCLogFileRotation && NumberOfGCLogFiles > 1) { - char tempbuf[FILENAMEBUFLEN]; + char tempbuf[JVM_MAXPATHLEN]; jio_snprintf(tempbuf, sizeof(tempbuf), "%s.%d" CURRENTAPPX, _file_name, _cur_file_num); _file = fopen(tempbuf, "w"); } else { @@ -671,10 +723,10 @@ void gcLogFileStream::write(const char* s, size_t len) { // concurrent GC threads to run parallel with VMThread at safepoint, write and rotate_log // must be synchronized. void gcLogFileStream::rotate_log(bool force, outputStream* out) { - char time_msg[FILENAMEBUFLEN]; + char time_msg[O_BUFLEN]; char time_str[EXTRACHARLEN]; - char current_file_name[FILENAMEBUFLEN]; - char renamed_file_name[FILENAMEBUFLEN]; + char current_file_name[JVM_MAXPATHLEN]; + char renamed_file_name[JVM_MAXPATHLEN]; if (!should_rotate(force)) { return; @@ -713,12 +765,15 @@ void gcLogFileStream::rotate_log(bool force, outputStream* out) { // have a form of extended_filename..current where i is the current rotation // file number. After it reaches max file size, the file will be saved and renamed // with .current removed from its tail. - size_t filename_len = strlen(_file_name); if (_file != NULL) { - jio_snprintf(renamed_file_name, filename_len + EXTRACHARLEN, "%s.%d", - _file_name, _cur_file_num); - jio_snprintf(current_file_name, filename_len + EXTRACHARLEN, "%s.%d" CURRENTAPPX, + jio_snprintf(renamed_file_name, JVM_MAXPATHLEN, "%s.%d", _file_name, _cur_file_num); + int result = jio_snprintf(current_file_name, JVM_MAXPATHLEN, + "%s.%d" CURRENTAPPX, _file_name, _cur_file_num); + if (result >= JVM_MAXPATHLEN) { + warning("Cannot create new log file name: %s: file name is too long.\n", current_file_name); + return; + } const char* msg = force ? "GC log rotation request has been received." : "GC log file has reached the maximum size."; @@ -757,19 +812,23 @@ void gcLogFileStream::rotate_log(bool force, outputStream* out) { _cur_file_num++; if (_cur_file_num > NumberOfGCLogFiles - 1) _cur_file_num = 0; - jio_snprintf(current_file_name, filename_len + EXTRACHARLEN, "%s.%d" CURRENTAPPX, + int result = jio_snprintf(current_file_name, JVM_MAXPATHLEN, "%s.%d" CURRENTAPPX, _file_name, _cur_file_num); + if (result >= JVM_MAXPATHLEN) { + warning("Cannot create new log file name: %s: file name is too long.\n", current_file_name); + return; + } + _file = fopen(current_file_name, "w"); if (_file != NULL) { _bytes_written = 0L; _need_close = true; // reuse current_file_name for time_msg - jio_snprintf(current_file_name, filename_len + EXTRACHARLEN, + jio_snprintf(current_file_name, JVM_MAXPATHLEN, "%s.%d", _file_name, _cur_file_num); jio_snprintf(time_msg, sizeof(time_msg), "%s GC log file created %s\n", - os::local_time_string((char *)time_str, sizeof(time_str)), - current_file_name); + os::local_time_string((char *)time_str, sizeof(time_str)), current_file_name); write(time_msg, strlen(time_msg)); if (out != NULL) { @@ -817,32 +876,64 @@ bool defaultStream::has_log_file() { return _log_file != NULL; } +fileStream* defaultStream::open_file(const char* log_name) { + const char* try_name = make_log_name(log_name, NULL); + if (try_name == NULL) { + warning("Cannot open file %s: file name is too long.\n", log_name); + return NULL; + } + + fileStream* file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name); + FREE_C_HEAP_ARRAY(char, try_name); + if (file->is_open()) { + return file; + } + + // Try again to open the file in the temp directory. + delete file; + char warnbuf[O_BUFLEN*2]; + jio_snprintf(warnbuf, sizeof(warnbuf), "Warning: Cannot open log file: %s\n", log_name); + // Note: This feature is for maintainer use only. No need for L10N. + jio_print(warnbuf); + try_name = make_log_name(log_name, os::get_temp_directory()); + if (try_name == NULL) { + warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory()); + return NULL; + } + + jio_snprintf(warnbuf, sizeof(warnbuf), + "Warning: Forcing option -XX:LogFile=%s\n", try_name); + jio_print(warnbuf); + + file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name); + FREE_C_HEAP_ARRAY(char, try_name); + if (file->is_open()) { + return file; + } + + delete file; + return NULL; +} + void defaultStream::init_log() { // %%% Need a MutexLocker? const char* log_name = LogFile != NULL ? LogFile : "hotspot_%p.log"; - const char* try_name = make_log_name(log_name, NULL); - fileStream* file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name); - if (!file->is_open()) { - // Try again to open the file. - char warnbuf[O_BUFLEN*2]; - jio_snprintf(warnbuf, sizeof(warnbuf), - "Warning: Cannot open log file: %s\n", try_name); - // Note: This feature is for maintainer use only. No need for L10N. - jio_print(warnbuf); - FREE_C_HEAP_ARRAY(char, try_name); - try_name = make_log_name(log_name, os::get_temp_directory()); - jio_snprintf(warnbuf, sizeof(warnbuf), - "Warning: Forcing option -XX:LogFile=%s\n", try_name); - jio_print(warnbuf); - delete file; - file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name); - } - FREE_C_HEAP_ARRAY(char, try_name); + fileStream* file = open_file(log_name); - if (file->is_open()) { + if (file != NULL) { _log_file = file; - xmlStream* xs = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file); - _outer_xmlStream = xs; + _outer_xmlStream = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file); + start_log(); + } else { + // and leave xtty as NULL + LogVMOutput = false; + DisplayVMOutput = true; + LogCompilation = false; + } +} + +void defaultStream::start_log() { + xmlStream*xs = _outer_xmlStream; if (this == tty) xtty = xs; // Write XML header. xs->print_cr(""); @@ -897,13 +988,6 @@ void defaultStream::init_log() { xs->head("tty"); // All further non-markup text gets copied to the tty: xs->_text = this; // requires friend declaration! - } else { - delete(file); - // and leave xtty as NULL - LogVMOutput = false; - DisplayVMOutput = true; - LogCompilation = false; - } } // finish_log() is called during normal VM shutdown. finish_log_on_error() is From 1409c46772b02ec91ec81456a42b605beefef769 Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Wed, 17 Dec 2014 14:58:58 +0300 Subject: [PATCH 004/149] 6219960: null reference in ToolTipManager Reviewed-by: serb, azvegint --- .../classes/javax/swing/ToolTipManager.java | 5 +- .../swing/JToolTip/6219960/bug6219960.java | 210 ++++++++++++++++++ 2 files changed, 213 insertions(+), 2 deletions(-) create mode 100644 jdk/test/javax/swing/JToolTip/6219960/bug6219960.java diff --git a/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java b/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java index b127284be09..9bb7f00f14b 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java @@ -28,6 +28,7 @@ package javax.swing; import java.awt.event.*; import java.awt.*; +import java.util.Objects; /** * Manages all the ToolTips in the system. @@ -476,8 +477,8 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener preferredLocation.equals(newPreferredLocation) : (newPreferredLocation == null); - if (!sameComponent || !toolTipText.equals(newToolTipText) || - !sameLoc) { + if (!sameComponent || !Objects.equals(toolTipText, newToolTipText) + || !sameLoc) { toolTipText = newToolTipText; preferredLocation = newPreferredLocation; showTipWindow(); diff --git a/jdk/test/javax/swing/JToolTip/6219960/bug6219960.java b/jdk/test/javax/swing/JToolTip/6219960/bug6219960.java new file mode 100644 index 00000000000..c23fa2c8472 --- /dev/null +++ b/jdk/test/javax/swing/JToolTip/6219960/bug6219960.java @@ -0,0 +1,210 @@ +/* + * 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 java.awt.Component; +import java.awt.Container; +import java.awt.GridLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.AWTException; +import java.awt.IllegalComponentStateException; +import java.awt.event.InputEvent; +import javax.swing.JButton; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.ToolTipManager; +import javax.swing.table.DefaultTableModel; + +/** + * @test + * @bug 6219960 + * @summary null reference in ToolTipManager + * @run main bug6219960 + */ +public class bug6219960 { + + private static final String QUESTION = "Question"; + + static volatile JFrame frame; + static JTable table; + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + SwingUtilities.invokeAndWait(bug6219960::createAndShowGUI); + robot.waitForIdle(); + showModal("The tooltip should be showing. Press ok with mouse. And don't move it."); + robot.waitForIdle(); + showModal("Now press ok and move the mouse inside the table (don't leave it)."); + robot.waitForIdle(); + } + + private static void createAndShowGUI() { + ToolTipManager.sharedInstance().setDismissDelay(10 * 60 * 1000); + frame = new JFrame(); + frame.setLocation(20, 20); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JDesktopPane desk = new JDesktopPane(); + JInternalFrame iframe = new JInternalFrame(); + iframe.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE); + desk.add(iframe); + JButton save = new JButton(); + save.setToolTipText("Wait for dialog to show."); + save.setText("Wait for the tooltip to show."); + JPanel panel = new JPanel(new GridLayout(1, 2)); + panel.add(save); + table = createTable(); + panel.add(new JScrollPane(table)); + iframe.setContentPane(panel); + frame.getContentPane().add(desk); + frame.setSize(800, 600); + iframe.setSize(640, 480); + iframe.validate(); + iframe.setVisible(true); + frame.validate(); + frame.setVisible(true); + try { + iframe.setSelected(true); + } catch (Exception e) { + throw new AssertionError(e); + } + + try { + Robot robot = new Robot(); + Rectangle bounds = frame.getBounds(); + int centerX = (int) (bounds.getX() + bounds.getWidth() / 6); + int centerY = (int) (bounds.getY() + bounds.getHeight() / 6); + robot.mouseMove(centerX, centerY); + } catch (AWTException e) { + throw new RuntimeException(e); + } + } + + private static void showModal(final String msg) throws Exception { + + new Thread(() -> { + + int timeout = 3000; + long endTime = System.currentTimeMillis() + timeout; + + while (System.currentTimeMillis() <= endTime) { + if (pressOK(frame)) { + return; + } + } + throw new RuntimeException("Internal frame has not been found!"); + }).start(); + + Thread.sleep(900); + + SwingUtilities.invokeAndWait(() -> { + JOptionPane.showInternalMessageDialog(table, msg, + QUESTION, + JOptionPane.PLAIN_MESSAGE); + }); + } + + private static JTable createTable() { + DefaultTableModel model = new DefaultTableModel(); + JTable table = new JTable(model); + table.setFillsViewportHeight(true); + return table; + } + + private static boolean pressOK(Component comp) { + + JInternalFrame internalFrame + = findModalInternalFrame(comp, QUESTION); + + if (internalFrame == null) { + return false; + } + + JButton button = (JButton) findButton(internalFrame); + + if (button == null) { + return false; + } + + try { + Robot robot = new Robot(); + Point location = button.getLocationOnScreen(); + Rectangle bounds = button.getBounds(); + int centerX = (int) (location.getX() + bounds.getWidth() / 2); + int centerY = (int) (location.getY() + bounds.getHeight() / 2); + robot.mouseMove(centerX, centerY); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } catch (IllegalComponentStateException ignore) { + return false; + } catch (AWTException e) { + throw new RuntimeException(e); + } + return true; + } + + private static JInternalFrame findModalInternalFrame(Component comp, String title) { + + if (comp instanceof JInternalFrame) { + JInternalFrame internalFrame = (JInternalFrame) comp; + if (internalFrame.getTitle().equals(title)) { + return (JInternalFrame) comp; + } + } + + if (comp instanceof Container) { + Container cont = (Container) comp; + for (int i = 0; i < cont.getComponentCount(); i++) { + JInternalFrame result = findModalInternalFrame(cont.getComponent(i), title); + if (result != null) { + return result; + } + } + } + return null; + } + + private static JButton findButton(Component comp) { + + if (comp instanceof JButton) { + return (JButton) comp; + } + + if (comp instanceof Container) { + Container cont = (Container) comp; + for (int i = 0; i < cont.getComponentCount(); i++) { + JButton result = findButton(cont.getComponent(i)); + if (result != null) { + return result; + } + } + } + return null; + } +} From e047f11b3bbc6ce2ccef964adb3ca30c75691d63 Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Wed, 17 Dec 2014 17:56:11 +0300 Subject: [PATCH 005/149] 4796987: XP Only JButton.setBorderPainted() does not work with XP L&F Reviewed-by: serb --- .../swing/plaf/windows/WindowsButtonUI.java | 3 +- .../swing/JButton/4796987/bug4796987.java | 102 ++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 jdk/test/javax/swing/JButton/4796987/bug4796987.java diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsButtonUI.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsButtonUI.java index 0ea400d53da..89a2a18e115 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsButtonUI.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsButtonUI.java @@ -248,7 +248,8 @@ public class WindowsButtonUI extends BasicButtonUI Part part = getXPButtonType(b); - if (b.isContentAreaFilled() && xp != null) { + if (b.isContentAreaFilled() && b.getBorder() != null + && b.isBorderPainted() && xp != null) { Skin skin = xp.getSkin(b, part); diff --git a/jdk/test/javax/swing/JButton/4796987/bug4796987.java b/jdk/test/javax/swing/JButton/4796987/bug4796987.java new file mode 100644 index 00000000000..ac41799da61 --- /dev/null +++ b/jdk/test/javax/swing/JButton/4796987/bug4796987.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * 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 4796987 + * @summary XP Only: JButton.setBorderPainted() does not work with XP L&F + * @author Alexander Scherbatiy + * @library ../../regtesthelpers + * @build Util + * @run main bug4796987 + */ + +import java.awt.*; +import javax.swing.*; +import sun.awt.OSInfo; +import sun.awt.SunToolkit; +import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; + +public class bug4796987 { + + private static JButton button1; + private static JButton button2; + + public static void main(String[] args) throws Exception { + if (OSInfo.getOSType() == OSInfo.OSType.WINDOWS + && OSInfo.getWindowsVersion() == OSInfo.WINDOWS_XP) { + UIManager.setLookAndFeel(new WindowsLookAndFeel()); + testButtonBorder(); + } + } + + private static void testButtonBorder() throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoDelay(50); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + createAndShowGUI(); + } + }); + + toolkit.realSync(); + Thread.sleep(500); + + Point p1 = Util.getCenterPoint(button1); + Point p2 = Util.getCenterPoint(button2); + + Color color = robot.getPixelColor(p1.x, p2.x); + for (int dx = p1.x; dx < p2.x - p1.x; dx++) { + robot.mouseMove(p1.x + dx, p1.y); + if (!color.equals(robot.getPixelColor(p1.x + dx, p1.y))) { + throw new RuntimeException("Button has border and background!"); + } + } + } + + private static JButton getButton() { + JButton button = new JButton(); + button.setBorderPainted(false); + button.setFocusable(false); + return button; + } + + private static void createAndShowGUI() { + JFrame frame = new JFrame("Test"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(200, 200); + + JButton button = new JButton(); + button.setBorder(null); + + JPanel panel = new JPanel(new BorderLayout(50, 50)); + panel.add(getButton(), BorderLayout.CENTER); + panel.add(button1 = getButton(), BorderLayout.WEST); + panel.add(button2 = getButton(), BorderLayout.EAST); + frame.getContentPane().add(panel); + frame.setVisible(true); + } +} From d5a220d6737bbd0a3cc22e15b5fe19ea8e974f94 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Thu, 25 Dec 2014 14:43:49 +0300 Subject: [PATCH 006/149] 7180976: Pending String deadlocks UIDefaults Reviewed-by: azvegint, alexsch --- .../share/classes/javax/swing/UIDefaults.java | 6 +-- .../swing/plaf/synth/DefaultSynthStyle.java | 4 +- .../swing/UIDefaults/7180976/Pending.java | 50 +++++++++++++++++++ 3 files changed, 54 insertions(+), 6 deletions(-) create mode 100644 jdk/test/javax/swing/UIDefaults/7180976/Pending.java diff --git a/jdk/src/java.desktop/share/classes/javax/swing/UIDefaults.java b/jdk/src/java.desktop/share/classes/javax/swing/UIDefaults.java index 82e4e2e5103..95cdb149aa9 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/UIDefaults.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/UIDefaults.java @@ -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; @@ -76,7 +74,7 @@ import sun.util.CoreResourceBundleControl; @SuppressWarnings("serial") // Same-version serialization only public class UIDefaults extends Hashtable { - private static final Object PENDING = "Pending"; + private static final Object PENDING = new Object(); private SwingPropertyChangeSupport changeSupport; @@ -170,7 +168,7 @@ public class UIDefaults extends Hashtable * Looks 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. */ diff --git a/jdk/src/java.desktop/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java b/jdk/src/java.desktop/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java index 4906d6ba14c..8829f369460 100644 --- a/jdk/src/java.desktop/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java +++ b/jdk/src/java.desktop/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java @@ -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? diff --git a/jdk/test/javax/swing/UIDefaults/7180976/Pending.java b/jdk/test/javax/swing/UIDefaults/7180976/Pending.java new file mode 100644 index 00000000000..23ece57ebb0 --- /dev/null +++ b/jdk/test/javax/swing/UIDefaults/7180976/Pending.java @@ -0,0 +1,50 @@ +/* + * 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 From 6a1f047a778c22f187d609ba16b7945d2f076e54 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Thu, 25 Dec 2014 14:54:32 +0300 Subject: [PATCH 007/149] 8067657: Dead/outdated links in Javadoc of package java.beans Reviewed-by: azvegint, prr --- jdk/src/java.desktop/share/classes/java/beans/package.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/java/beans/package.html b/jdk/src/java.desktop/share/classes/java/beans/package.html index 2b68012cee5..81a9cdafd7b 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/package.html +++ b/jdk/src/java.desktop/share/classes/java/beans/package.html @@ -1,5 +1,5 @@ /d' ) fi if test -n "$TMP"; then echo Files $OTHER_FILE and $THIS_FILE differ @@ -158,7 +160,7 @@ compare_dirs() { (cd $THIS_DIR && $FIND . -type d | $SORT > $WORK_DIR/dirs_this) $DIFF $WORK_DIR/dirs_other $WORK_DIR/dirs_this > $WORK_DIR/dirs_diff - + echo -n Directory structure... if [ -s $WORK_DIR/dirs_diff ]; then echo Differences found. @@ -192,7 +194,7 @@ compare_files() { (cd $OTHER_DIR && $FIND . ! -type d | $SORT > $WORK_DIR/files_other) (cd $THIS_DIR && $FIND . ! -type d | $SORT > $WORK_DIR/files_this) - + $DIFF $WORK_DIR/files_other $WORK_DIR/files_this > $WORK_DIR/files_diff echo -n File names... @@ -236,11 +238,11 @@ compare_permissions() { TP=`ls -l ${THIS_DIR}/$f | awk '{printf("%.10s\n", $1);}'` if [ "$OP" != "$TP" ] then - if [ -z "$found" ]; then echo ; found="yes"; fi - $PRINTF "\told: ${OP} new: ${TP}\t$f\n" + if [ -z "$found" ]; then echo ; found="yes"; fi + $PRINTF "\tother: ${OP} this: ${TP}\t$f\n" fi done - if [ -z "$found" ]; then + if [ -z "$found" ]; then echo "Identical!" else REGRESSIONS=true @@ -265,24 +267,22 @@ compare_file_types() { if [ ! -f ${THIS_DIR}/$f ]; then continue; fi OF=`cd ${OTHER_DIR} && $FILE -h $f | $SED 's/BuildID[^,]*//g'` TF=`cd ${THIS_DIR} && $FILE -h $f | $SED 's/BuildID[^,]*//g'` - if [ "$f" = "./src.zip" ] || [[ "$f" = *"/Home/src.zip" ]] || [[ "$f" = *"/lib/JObjC.jar" ]] - then - if [ "`echo $OF | $GREP -ic zip`" -gt 0 -a "`echo $TF | $GREP -ic zip`" -gt 0 ] - then - # the way we produces zip-files make it so that directories are stored in old file - # but not in new (only files with full-path) - # this makes file-5.09 report them as different - continue; - fi - fi - if [ "$OF" != "$TF" ] then - if [ -z "$found" ]; then echo ; found="yes"; fi - $PRINTF "\tother: ${OF}\n\tthis : ${TF}\n" + if [ "`echo $OF | $GREP -c 'Zip archive data'`" -gt 0 ] \ + && [ "`echo $TF | $GREP -c 'Zip archive data'`" -gt 0 ] + then + # the way we produce zip-files make it so that directories are stored in + # old file but not in new (only files with full-path) this makes file + # report them as different + continue + else + if [ -z "$found" ]; then echo ; found="yes"; fi + $PRINTF "\tother: ${OF}\n\tthis : ${TF}\n" + fi fi done - if [ -z "$found" ]; then + if [ -z "$found" ]; then echo "Identical!" else REGRESSIONS=true @@ -296,12 +296,13 @@ compare_general_files() { THIS_DIR=$1 OTHER_DIR=$2 WORK_DIR=$3 - + GENERAL_FILES=$(cd $THIS_DIR && $FIND . -type f ! -name "*.so" ! -name "*.jar" ! -name "*.zip" \ ! -name "*.debuginfo" ! -name "*.dylib" ! -name "jexec" ! -name "*.jimage" \ - ! -name "ct.sym" ! -name "*.diz" ! -name "*.dll" \ + ! -name "ct.sym" ! -name "*.diz" ! -name "*.dll" ! -name "*.cpl" \ ! -name "*.pdb" ! -name "*.exp" ! -name "*.ilk" \ ! -name "*.lib" ! -name "*.war" ! -name "JavaControlPanel" \ + ! -name "*.obj" ! -name "*.o" ! -name "JavaControlPanelHelper" ! -name "JavaUpdater" \ | $GREP -v "./bin/" | $SORT | $FILTER) echo General files... @@ -377,7 +378,7 @@ compare_zip_file() { THIS_SUFFIX="${THIS_ZIP##*.}" OTHER_SUFFIX="${OTHER_ZIP##*.}" if [ "$THIS_SUFFIX" != "$OTHER_SUFFIX" ]; then - echo The files do not have the same suffix type! + echo "The files do not have the same suffix type! ($THIS_SUFFIX != $OTHER_SUFFIX)" return 2 fi @@ -389,7 +390,7 @@ compare_zip_file() { fi # Not quite identical, the might still contain the same data. # Unpack the jar/zip files in temp dirs - + THIS_UNZIPDIR=$WORK_DIR/$ZIP_FILE.this OTHER_UNZIPDIR=$WORK_DIR/$ZIP_FILE.other $RM -rf $THIS_UNZIPDIR $OTHER_UNZIPDIR @@ -464,9 +465,9 @@ compare_zip_file() { $RM -f $WORK_DIR/$ZIP_FILE.diffs for file in $DIFFING_FILES; do - if [[ "$ACCEPTED_JARZIP_CONTENTS $EXCEPTIONS" != *"$file"* ]]; then + if [[ "$ACCEPTED_JARZIP_CONTENTS $EXCEPTIONS" != *"$file"* ]]; then diff_text $OTHER_UNZIPDIR/$file $THIS_UNZIPDIR/$file >> $WORK_DIR/$ZIP_FILE.diffs - fi + fi done if [ -s "$WORK_DIR/$ZIP_FILE.diffs" ]; then @@ -573,6 +574,10 @@ compare_bin_file() { $MKDIR -p $FILE_WORK_DIR + # Make soft links to original files from work dir to facilitate debugging + $LN -f -s $THIS_FILE $WORK_FILE_BASE.this + $LN -f -s $OTHER_FILE $WORK_FILE_BASE.other + ORIG_THIS_FILE="$THIS_FILE" ORIG_OTHER_FILE="$OTHER_FILE" @@ -589,50 +594,51 @@ compare_bin_file() { fi if [ "$OPENJDK_TARGET_OS" = "windows" ]; then - unset _NT_SYMBOL_PATH - # On windows we need to unzip the debug symbols, if present - OTHER_FILE_BASE=${OTHER_FILE/.dll/} - OTHER_FILE_BASE=${OTHER_FILE_BASE/.exe/} - DIZ_NAME=$(basename $OTHER_FILE_BASE).diz + unset _NT_SYMBOL_PATH + # On windows we need to unzip the debug symbols, if present + OTHER_FILE_BASE=${OTHER_FILE/.dll/} + OTHER_FILE_BASE=${OTHER_FILE_BASE/.exe/} + OTHER_FILE_BASE=${OTHER_FILE_BASE/.cpl/} + DIZ_NAME=$(basename $OTHER_FILE_BASE).diz # java.exe and java.dll diz files will have the same name. Have to - # make sure java.exe gets the right one. This is only needed for - # OTHER since in the new build, all pdb files are left around. - if [ "$NAME" = "java.exe" ] && [ -f "$OTHER/tmp/java/java/obj64/java.diz" ]; then - OTHER_DIZ_FILE="$OTHER/tmp/java/java/obj64/java.diz" - elif [ -f "${OTHER_FILE_BASE}.diz" ]; then - OTHER_DIZ_FILE=${OTHER_FILE_BASE}.diz - else + # make sure java.exe gets the right one. This is only needed for + # OTHER since in the new build, all pdb files are left around. + if [ "$NAME" = "java.exe" ] && [ -f "$OTHER/tmp/java/java/obj64/java.diz" ]; then + OTHER_DIZ_FILE="$OTHER/tmp/java/java/obj64/java.diz" + elif [ -f "${OTHER_FILE_BASE}.diz" ]; then + OTHER_DIZ_FILE=${OTHER_FILE_BASE}.diz + else # Some files, jli.dll, appears twice in the image but only one of - # thme has a diz file next to it. - OTHER_DIZ_FILE="$($FIND $OTHER_DIR -name $DIZ_NAME | $SED 1q)" - if [ ! -f "$OTHER_DIZ_FILE" ]; then - # As a last resort, look for diz file in the whole build output - # dir. - OTHER_DIZ_FILE="$($FIND $OTHER -name $DIZ_NAME | $SED 1q)" - fi - fi - if [ -n "$OTHER_DIZ_FILE" ]; then - $MKDIR -p $FILE_WORK_DIR/other - (cd $FILE_WORK_DIR/other ; $UNARCHIVE -o $OTHER_DIZ_FILE) - export _NT_SYMBOL_PATH="$FILE_WORK_DIR/other" - fi - THIS_FILE_BASE=${THIS_FILE/.dll/} - THIS_FILE_BASE=${THIS_FILE_BASE/.exe/} - if [ -f "${THIS_FILE/.dll/}.diz" ]; then - THIS_DIZ_FILE=${THIS_FILE/.dll/}.diz - else - THIS_DIZ_FILE="$($FIND $THIS_DIR -name $DIZ_NAME | $SED 1q)" - if [ ! -f "$THIS_DIZ_FILE" ]; then - # As a last resort, look for diz file in the whole build output - # dir. - THIS_DIZ_FILE="$($FIND $THIS -name $DIZ_NAME | $SED 1q)" - fi - fi - if [ -n "$THIS_DIZ_FILE" ]; then - $MKDIR -p $FILE_WORK_DIR/this - (cd $FILE_WORK_DIR/this ; $UNARCHIVE -o $THIS_DIZ_FILE) - export _NT_SYMBOL_PATH="$_NT_SYMBOL_PATH;$FILE_WORK_DIR/this" - fi + # thme has a diz file next to it. + OTHER_DIZ_FILE="$($FIND $OTHER_DIR -name $DIZ_NAME | $SED 1q)" + if [ ! -f "$OTHER_DIZ_FILE" ]; then + # As a last resort, look for diz file in the whole build output + # dir. + OTHER_DIZ_FILE="$($FIND $OTHER -name $DIZ_NAME | $SED 1q)" + fi + fi + if [ -n "$OTHER_DIZ_FILE" ]; then + $MKDIR -p $FILE_WORK_DIR/other + (cd $FILE_WORK_DIR/other ; $UNARCHIVE -o $OTHER_DIZ_FILE) + export _NT_SYMBOL_PATH="$FILE_WORK_DIR/other" + fi + THIS_FILE_BASE=${THIS_FILE/.dll/} + THIS_FILE_BASE=${THIS_FILE_BASE/.exe/} + if [ -f "${THIS_FILE/.dll/}.diz" ]; then + THIS_DIZ_FILE=${THIS_FILE/.dll/}.diz + else + THIS_DIZ_FILE="$($FIND $THIS_DIR -name $DIZ_NAME | $SED 1q)" + if [ ! -f "$THIS_DIZ_FILE" ]; then + # As a last resort, look for diz file in the whole build output + # dir. + THIS_DIZ_FILE="$($FIND $THIS -name $DIZ_NAME | $SED 1q)" + fi + fi + if [ -n "$THIS_DIZ_FILE" ]; then + $MKDIR -p $FILE_WORK_DIR/this + (cd $FILE_WORK_DIR/this ; $UNARCHIVE -o $THIS_DIZ_FILE) + export _NT_SYMBOL_PATH="$_NT_SYMBOL_PATH;$FILE_WORK_DIR/this" + fi fi if [ -z "$SKIP_BIN_DIFF" ]; then @@ -670,19 +676,19 @@ compare_bin_file() { DIFF_SIZE_REL=$($EXPR $THIS_SIZE \* 100 / $OTHER_SIZE) SIZE_MSG=$($PRINTF "%3d%% %4d" $DIFF_SIZE_REL $DIFF_SIZE_NUM) if [[ "$ACCEPTED_SMALL_SIZE_DIFF" = *"$BIN_FILE"* ]] && [ "$DIFF_SIZE_REL" -gt 98 ] \ - && [ "$DIFF_SIZE_REL" -lt 102 ]; then + && [ "$DIFF_SIZE_REL" -lt 102 ]; then SIZE_MSG="($SIZE_MSG)" DIFF_SIZE= elif [ "$OPENJDK_TARGET_OS" = "windows" ] \ - && [[ "$ACCEPTED_SMALL_SIZE_DIFF" = *"$BIN_FILE"* ]] \ - && [ "$DIFF_SIZE_NUM" = 512 ]; then - # On windows, size of binaries increase in 512 increments. + && [[ "$ACCEPTED_SMALL_SIZE_DIFF" = *"$BIN_FILE"* ]] \ + && [ "$DIFF_SIZE_NUM" = 512 ]; then + # On windows, size of binaries increase in 512 increments. SIZE_MSG="($SIZE_MSG)" DIFF_SIZE= elif [ "$OPENJDK_TARGET_OS" = "windows" ] \ - && [[ "$ACCEPTED_SMALL_SIZE_DIFF" = *"$BIN_FILE"* ]] \ - && [ "$DIFF_SIZE_NUM" = -512 ]; then - # On windows, size of binaries increase in 512 increments. + && [[ "$ACCEPTED_SMALL_SIZE_DIFF" = *"$BIN_FILE"* ]] \ + && [ "$DIFF_SIZE_NUM" = -512 ]; then + # On windows, size of binaries increase in 512 increments. SIZE_MSG="($SIZE_MSG)" DIFF_SIZE= else @@ -717,18 +723,18 @@ compare_bin_file() { if [ "$OPENJDK_TARGET_OS" = "windows" ]; then # The output from dumpbin on windows differs depending on if the debug symbol # files are still around at the location the binary is pointing too. Need - # to filter out that extra information. - $DUMPBIN -exports $OTHER_FILE | $GREP -E '^ +[0-9A-F]+ +[0-9A-F]+ [0-9A-F]+' | sed 's/ = .*//g' | cut -c27- | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.other - $DUMPBIN -exports $THIS_FILE | $GREP -E '^ +[0-9A-F]+ +[0-9A-F]+ [0-9A-F]+' | sed 's/ = .*//g' | cut -c27- | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.this + # to filter out that extra information. + $DUMPBIN -exports $OTHER_FILE | $GREP -E '^ +[0-9A-F]+ +[0-9A-F]+ [0-9A-F]+' | sed 's/ = .*//g' | cut -c27- | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.other + $DUMPBIN -exports $THIS_FILE | $GREP -E '^ +[0-9A-F]+ +[0-9A-F]+ [0-9A-F]+' | sed 's/ = .*//g' | cut -c27- | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.this elif [ "$OPENJDK_TARGET_OS" = "solaris" ]; then # Some symbols get seemingly random 15 character prefixes. Filter them out. $NM -a $ORIG_OTHER_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SED 's/^\([a-zA-Z] [\.\$]\)[a-zA-Z0-9_\$]\{15,15\}\./\1./g' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.other - $NM -a $ORIG_THIS_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SED 's/^\([a-zA-Z] [\.\$]\)[a-zA-Z0-9_\$]\{15,15\}\./\1./g' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.this + $NM -a $ORIG_THIS_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SED 's/^\([a-zA-Z] [\.\$]\)[a-zA-Z0-9_\$]\{15,15\}\./\1./g' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.this else - $NM -a $ORIG_OTHER_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.other - $NM -a $ORIG_THIS_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.this + $NM -a $ORIG_OTHER_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.other + $NM -a $ORIG_THIS_FILE 2> /dev/null | $GREP -v $NAME | $AWK '{print $2, $3, $4, $5}' | $SYM_SORT_CMD > $WORK_FILE_BASE.symbols.this fi - + LC_ALL=C $DIFF $WORK_FILE_BASE.symbols.other $WORK_FILE_BASE.symbols.this > $WORK_FILE_BASE.symbols.diff if [ -s $WORK_FILE_BASE.symbols.diff ]; then SYM_MSG=" diff " @@ -741,7 +747,7 @@ compare_bin_file() { SYM_MSG=" $SYM_MSG " fi else - SYM_MSG="($SYM_MSG)" + SYM_MSG="($SYM_MSG)" DIFF_SYM= fi else @@ -754,48 +760,48 @@ compare_bin_file() { # Check dependencies if [ -n "$LDD_CMD" ]; then - (cd $FILE_WORK_DIR && $CP $OTHER_FILE . && $LDD_CMD $NAME 2>/dev/null | $AWK '{ print $1;}' | $SORT | $TEE $WORK_FILE_BASE.deps.other | $UNIQ > $WORK_FILE_BASE.deps.other.uniq) - (cd $FILE_WORK_DIR && $CP $THIS_FILE . && $LDD_CMD $NAME 2 $WORK_FILE_BASE.deps.this.uniq) - (cd $FILE_WORK_DIR && $RM -f $NAME) - - LC_ALL=C $DIFF $WORK_FILE_BASE.deps.other $WORK_FILE_BASE.deps.this > $WORK_FILE_BASE.deps.diff - LC_ALL=C $DIFF $WORK_FILE_BASE.deps.other.uniq $WORK_FILE_BASE.deps.this.uniq > $WORK_FILE_BASE.deps.diff.uniq - - if [ -s $WORK_FILE_BASE.deps.diff ]; then + (cd $FILE_WORK_DIR && $CP $OTHER_FILE . && $LDD_CMD $NAME 2>/dev/null | $AWK '{ print $1;}' | $SORT | $TEE $WORK_FILE_BASE.deps.other | $UNIQ > $WORK_FILE_BASE.deps.other.uniq) + (cd $FILE_WORK_DIR && $CP $THIS_FILE . && $LDD_CMD $NAME 2 $WORK_FILE_BASE.deps.this.uniq) + (cd $FILE_WORK_DIR && $RM -f $NAME) + + LC_ALL=C $DIFF $WORK_FILE_BASE.deps.other $WORK_FILE_BASE.deps.this > $WORK_FILE_BASE.deps.diff + LC_ALL=C $DIFF $WORK_FILE_BASE.deps.other.uniq $WORK_FILE_BASE.deps.this.uniq > $WORK_FILE_BASE.deps.diff.uniq + + if [ -s $WORK_FILE_BASE.deps.diff ]; then if [ -s $WORK_FILE_BASE.deps.diff.uniq ]; then - DEP_MSG=" diff " + DEP_MSG=" diff " else - DEP_MSG=" redun " + DEP_MSG=" redun " fi if [[ "$ACCEPTED_DEP_DIFF" != *"$BIN_FILE"* ]]; then - DIFF_DEP=true - if [[ "$KNOWN_DEP_DIFF" != *"$BIN_FILE"* ]]; then + DIFF_DEP=true + if [[ "$KNOWN_DEP_DIFF" != *"$BIN_FILE"* ]]; then DEP_MSG="*$DEP_MSG*" REGRESSIONS=true - else + else DEP_MSG=" $DEP_MSG " - fi + fi else - DEP_MSG="($DEP_MSG)" - DIFF_DEP= + DEP_MSG="($DEP_MSG)" + DIFF_DEP= fi - else - DEP_MSG=" " - DIFF_DEP= + else + DEP_MSG=" " + DIFF_DEP= if [[ "$KNOWN_DEP_DIFF $ACCEPTED_DEP_DIFF" = *"$BIN_FILE"* ]]; then DEP_MSG=" ! " fi - fi + fi else - DEP_MSG=" - " + DEP_MSG=" - " fi - + # Compare fulldump output if [ -n "$FULLDUMP_CMD" ] && [ -z "$SKIP_FULLDUMP_DIFF" ]; then $FULLDUMP_CMD $OTHER_FILE > $WORK_FILE_BASE.fulldump.other 2>&1 $FULLDUMP_CMD $THIS_FILE > $WORK_FILE_BASE.fulldump.this 2>&1 LC_ALL=C $DIFF $WORK_FILE_BASE.fulldump.other $WORK_FILE_BASE.fulldump.this > $WORK_FILE_BASE.fulldump.diff - + if [ -s $WORK_FILE_BASE.fulldump.diff ]; then ELF_DIFF_SIZE=$(ls -n $WORK_FILE_BASE.fulldump.diff | awk '{print $5}') ELF_MSG=$($PRINTF "%8d" $ELF_DIFF_SIZE) @@ -822,14 +828,17 @@ compare_bin_file() { # Compare disassemble output if [ -n "$DIS_CMD" ] && [ -z "$SKIP_DIS_DIFF" ]; then - if [ -z "$DIS_DIFF_FILTER" ]; then - DIS_DIFF_FILTER="$CAT" - fi - $DIS_CMD $OTHER_FILE | $GREP -v $NAME | $DIS_DIFF_FILTER > $WORK_FILE_BASE.dis.other 2>&1 - $DIS_CMD $THIS_FILE | $GREP -v $NAME | $DIS_DIFF_FILTER > $WORK_FILE_BASE.dis.this 2>&1 - + # By default we filter out differences that include references to symbols. + # To get a raw diff with the complete disassembly, set + # DIS_DIFF_FILTER="$CAT" + if [ -z "$DIS_DIFF_FILTER" ]; then + DIS_DIFF_FILTER="$GREP -v ' # .* <.*>$'" + fi + $DIS_CMD $OTHER_FILE | $GREP -v $NAME | eval "$DIS_DIFF_FILTER" > $WORK_FILE_BASE.dis.other 2>&1 + $DIS_CMD $THIS_FILE | $GREP -v $NAME | eval "$DIS_DIFF_FILTER" > $WORK_FILE_BASE.dis.this 2>&1 + LC_ALL=C $DIFF $WORK_FILE_BASE.dis.other $WORK_FILE_BASE.dis.this > $WORK_FILE_BASE.dis.diff - + if [ -s $WORK_FILE_BASE.dis.diff ]; then DIS_DIFF_SIZE=$(ls -n $WORK_FILE_BASE.dis.diff | awk '{print $5}') DIS_MSG=$($PRINTF "%8d" $DIS_DIFF_SIZE) @@ -907,7 +916,9 @@ compare_all_libs() { OTHER_DIR=$2 WORK_DIR=$3 - LIBS=$(cd $THIS_DIR && $FIND . -type f \( -name 'lib*.so' -o -name '*.dylib' -o -name '*.dll' -o -name 'JavaControlPanel' \) | $SORT | $FILTER) + LIBS=$(cd $THIS_DIR && $FIND . -type f \( -name 'lib*.so' -o -name '*.dylib' \ + -o -name '*.dll' -o -name '*.obj' -o -name '*.o' \ + -o -name '*.cpl' \) | $SORT | $FILTER) if [ -n "$LIBS" ]; then echo Libraries... @@ -967,7 +978,7 @@ COMPARE_ROOT=/tmp/cimages.$USER $MKDIR -p $COMPARE_ROOT if [ "$OPENJDK_TARGET_OS" = "windows" ]; then if [ "$(uname -o)" = "Cygwin" ]; then - COMPARE_ROOT=$(cygpath -msa $COMPARE_ROOT) + COMPARE_ROOT=$(cygpath -msa $COMPARE_ROOT) fi fi @@ -1091,7 +1102,7 @@ while [ -n "$1" ]; do CMP_JARS=true CMP_LIBS=true CMP_EXECS=true - + if [ -z "$FILTER" ]; then FILTER="$GREP" fi @@ -1177,8 +1188,8 @@ if [ "$SKIP_DEFAULT" != "true" ]; then OTHER_J2RE="$OTHER/images/jre" echo "Selecting jdk images for compare" else - echo "No common images found." - exit 1 + echo "No common images found." + exit 1 fi if [ -d "$THIS/images/jdk-bundle" ] && [ -d "$OTHER/images/jdk-bundle" ]; then @@ -1189,6 +1200,17 @@ if [ "$SKIP_DEFAULT" != "true" ]; then echo "Also comparing macosx bundles" fi + if [ -d "$THIS/deploy" ] && [ -d "$OTHER/deploy" ]; then + THIS_DEPLOY_BUNDLE_DIR="$THIS/deploy/dist/installer/bundles" + OTHER_DEPLOY_BUNDLE_DIR="$OTHER/deploy/bundles" + echo "Also comparing deploy/bundles" + if [ "$OPENJDK_TARGET_OS" = "macosx" ]; then + THIS_DEPLOY_APPLET_PLUGIN_DIR="$THIS/deploy/JavaAppletPlugin.plugin" + OTHER_DEPLOY_APPLET_PLUGIN_DIR="$OTHER/deploy/JavaAppletPlugin.plugin" + echo "Also comparing JavaAppletPlugin" + fi + fi + if [ -d "$OTHER/images" ]; then OTHER_SEC_DIR="$OTHER/images" else @@ -1212,7 +1234,7 @@ if [ "$SKIP_DEFAULT" != "true" ]; then if [ -d "$THIS/docs" ] && [ -d "$OTHER/docs" ]; then THIS_DOCS="$THIS/docs" OTHER_DOCS="$OTHER/docs" - echo "Also comparing docs" + echo "Also comparing docs" else echo "WARNING! Docs haven't been built and won't be compared." fi @@ -1227,7 +1249,7 @@ if [ "$CMP_NAMES" = "true" ]; then compare_dirs $THIS_J2SDK $OTHER_J2SDK $COMPARE_ROOT/j2sdk echo -n "J2RE " compare_dirs $THIS_J2RE $OTHER_J2RE $COMPARE_ROOT/j2re - + echo -n "J2SDK " compare_files $THIS_J2SDK $OTHER_J2SDK $COMPARE_ROOT/j2sdk echo -n "J2RE " @@ -1238,7 +1260,7 @@ if [ "$CMP_NAMES" = "true" ]; then compare_dirs $THIS_J2SDK_BUNDLE $OTHER_J2SDK_BUNDLE $COMPARE_ROOT/jdk-bundle echo -n "J2RE Bundle " compare_dirs $THIS_J2RE_BUNDLE $OTHER_J2RE_BUNDLE $COMPARE_ROOT/jre-bundle - + echo -n "J2SDK Bundle " compare_files $THIS_J2SDK_BUNDLE $OTHER_J2SDK_BUNDLE $COMPARE_ROOT/jdk-bundle echo -n "J2RE Bundle " @@ -1254,6 +1276,12 @@ if [ "$CMP_NAMES" = "true" ]; then compare_dirs $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir compare_files $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + echo -n "JavaAppletPlugin " + compare_dirs $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + echo -n "JavaAppletPlugin " + compare_files $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_PERMS" = "true" ]; then @@ -1266,6 +1294,10 @@ if [ "$CMP_PERMS" = "true" ]; then if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_permissions $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + echo -n "JavaAppletPlugin " + compare_permissions $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_TYPES" = "true" ]; then @@ -1284,6 +1316,10 @@ if [ "$CMP_TYPES" = "true" ]; then if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_file_types $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + echo -n "JavaAppletPlugin " + compare_file_types $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_GENERAL" = "true" ]; then @@ -1306,6 +1342,10 @@ if [ "$CMP_GENERAL" = "true" ]; then if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_general_files $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + echo -n "JavaAppletPlugin " + compare_general_files $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_ZIPS" = "true" ]; then @@ -1333,6 +1373,12 @@ if [ "$CMP_ZIPS" = "true" ]; then if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_all_zip_files $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_BUNDLE_DIR" ] && [ -n "$OTHER_DEPLOY_BUNDLE_DIR" ]; then + compare_all_zip_files $THIS_DEPLOY_BUNDLE_DIR $OTHER_DEPLOY_BUNDLE_DIR $COMPARE_ROOT/deploy-bundle + fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + compare_all_zip_files $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_JARS" = "true" ]; then @@ -1342,6 +1388,9 @@ if [ "$CMP_JARS" = "true" ]; then if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_all_jar_files $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + compare_all_jar_files $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_LIBS" = "true" ]; then @@ -1356,15 +1405,27 @@ if [ "$CMP_LIBS" = "true" ]; then if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_all_libs $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + echo -n "JavaAppletPlugin " + compare_all_libs $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi if [ "$CMP_EXECS" = "true" ]; then if [ -n "$THIS_J2SDK" ] && [ -n "$OTHER_J2SDK" ]; then compare_all_execs $THIS_J2SDK $OTHER_J2SDK $COMPARE_ROOT/j2sdk + if [ "$OPENJDK_TARGET_OS" = "macosx" ]; then + echo -n "J2RE " + compare_all_execs $THIS_J2RE $OTHER_J2RE $COMPARE_ROOT/j2re + fi fi if [ -n "$THIS_BASE_DIR" ] && [ -n "$OTHER_BASE_DIR" ]; then compare_all_execs $THIS_BASE_DIR $OTHER_BASE_DIR $COMPARE_ROOT/base_dir fi + if [ -n "$THIS_DEPLOY_APPLET_PLUGIN_DIR" ] && [ -n "$OTHER_DEPLOY_APPLET_PLUGIN_DIR" ]; then + echo -n "JavaAppletPlugin " + compare_all_execs $THIS_DEPLOY_APPLET_PLUGIN_DIR $OTHER_DEPLOY_APPLET_PLUGIN_DIR $COMPARE_ROOT/plugin + fi fi echo diff --git a/make/Images.gmk b/make/Images.gmk index 93a73a5b1b7..20c5e1011de 100644 --- a/make/Images.gmk +++ b/make/Images.gmk @@ -29,7 +29,7 @@ include $(SPEC) include MakeBase.gmk TOOL_TARGETS := -JDK_TARGETS := +JDK_TARGETS := JRE_TARGETS := # Hook to include the corresponding custom file, if present. @@ -69,7 +69,7 @@ JDK_COMPACT3_MODULES := java.compact3 java.smartcardio jdk.httpserver jdk.naming jdk.naming.rmi jdk.sctp jdk.security.auth # Replacing double-comma with a single comma is to workaround the issue -# with some version of make on windows that doesn't substitute spaces +# with some version of make on windows that doesn't substitute spaces # with one comma properly as with make 4.0 define SubstComma $(subst $(COMMA)$(COMMA),$(COMMA),$(subst $(SPACE),$(COMMA),$(strip $1))) diff --git a/make/MakeHelpers.gmk b/make/MakeHelpers.gmk index 359fb7ee2ea..8441e95d356 100644 --- a/make/MakeHelpers.gmk +++ b/make/MakeHelpers.gmk @@ -353,7 +353,7 @@ MAKE_MAKEDIR_LIST := make # Helper macro for DeclareRecipesForPhase # Declare a recipe for calling the module and phase specific makefile. # If there are multiple makefiles to call, create a rule for each topdir -# that contains a makefile with the target $module-$suffix-$repodir, +# that contains a makefile with the target $module-$suffix-$repodir, # (i.e: java.base-gensrc-jdk) # Normally there is only one makefile, and the target will just be # $module-$suffix diff --git a/make/ModuleWrapper.gmk b/make/ModuleWrapper.gmk index 40d2c837b97..ba8cfab8aa5 100644 --- a/make/ModuleWrapper.gmk +++ b/make/ModuleWrapper.gmk @@ -26,7 +26,7 @@ ################################################################################ # This makefile is called from Main.gmk, through a macro in MakeHelpers.gmk # and wraps calls to makefiles for specific modules and build phases. Having -# this wrapper reduces the need for boilerplate code. It also provides +# this wrapper reduces the need for boilerplate code. It also provides # opportunity for automatic copying of files to an interim exploded runnable # image. From 963ea242c9fad06a2f0c50346fd2f9419f9528ee Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Thu, 15 Jan 2015 15:40:56 +0100 Subject: [PATCH 081/149] 8069063: More merge errors following JDK-8049367 Reviewed-by: erikj --- make/common/NativeCompilation.gmk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/make/common/NativeCompilation.gmk b/make/common/NativeCompilation.gmk index d8ca38090df..9088a61e645 100644 --- a/make/common/NativeCompilation.gmk +++ b/make/common/NativeCompilation.gmk @@ -577,7 +577,7 @@ define SetupNativeCompilationInner $$($1_TARGET): $$($1_EXPECTED_OBJS) $$($1_RES) $$($1_REAL_MAPFILE) \ $$($1_DEBUGINFO_EXTRA_DEPS) - $$(call LINKING_MSG,$$($1_BASENAME)) + $(ECHO) $(LOG_INFO) "Linking $$($1_BASENAME)" $$($1_LD) $$($1_LDFLAGS) $$($1_EXTRA_LDFLAGS) $(SYSROOT_LDFLAGS) \ $(LD_OUT_OPTION)$$@ \ $$($1_EXPECTED_OBJS) $$($1_RES) \ @@ -605,7 +605,7 @@ define SetupNativeCompilationInner $$($1_TARGET): $$($1_EXPECTED_OBJS) $$($1_RES) $$($1_GEN_MANIFEST) \ $$($1_DEBUGINFO_EXTRA_DEPS) - $$(call LINKING_EXE_MSG,$$($1_BASENAME)) + $(ECHO) $(LOG_INFO) "Linking executable $$($1_BASENAME)" $$($1_LDEXE) $$($1_LDFLAGS) $$($1_EXTRA_LDFLAGS) $(SYSROOT_LDFLAGS) \ $(EXE_OUT_OPTION)$$($1_TARGET) \ $$($1_EXPECTED_OBJS) $$($1_RES) \ From 721b7a43be891b27abee56b94bcfaf9ba5927331 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Thu, 15 Jan 2015 15:43:28 +0100 Subject: [PATCH 082/149] 8069057: Make sure configure is run by bash Reviewed-by: erikj --- common/autoconf/configure | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/common/autoconf/configure b/common/autoconf/configure index b49e03e7fad..b6a38a307e3 100644 --- a/common/autoconf/configure +++ b/common/autoconf/configure @@ -36,6 +36,13 @@ else shift fi +if test "x$BASH" = x; then + echo "Error: This script must be run using bash." 1>&2 + exit 1 +fi +# Force autoconf to use bash +export CONFIG_SHELL=$BASH + conf_script_dir="$TOPDIR/common/autoconf" if [ "$CUSTOM_CONFIG_DIR" = "" ]; then From 71d4cfb1ada85784c22cbb4c1ed47c22ed7d285a Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Thu, 15 Jan 2015 16:05:20 +0100 Subject: [PATCH 083/149] 8068026: [TESTBUG] Check for -client in gc/g1/TestHumongousCodeCacheRoots.java Skip test if -client is not supported. Reviewed-by: jwilhelm, simonis --- hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java b/hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java index c4a81e2d5f0..c24b3ecf867 100644 --- a/hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java +++ b/hotspot/test/gc/g1/TestHumongousCodeCacheRoots.java @@ -116,7 +116,14 @@ public class TestHumongousCodeCacheRoots { ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs.toArray(new String[0])); OutputAnalyzer output = new OutputAnalyzer(pb.start()); - output.shouldHaveExitValue(0); + try { + output.shouldHaveExitValue(0); + } catch (RuntimeException e) { + // It's ok if there is no client vm in the jdk. + if (output.firstMatch("Unrecognized option: -client") == null) { + throw e; + } + } return output; } From cd582fa380a31a9220ce18606fa2fc255d39fbdb Mon Sep 17 00:00:00 2001 From: Michail Chernov Date: Thu, 15 Jan 2015 19:16:17 +0400 Subject: [PATCH 084/149] 8066122: CollectionUsageThreshold.java times out when run with -XX:+ExplicitGCInvokesConcurrent CollectionUsageThreshold.java hangs due to VM performs concurrent GC with -XX:+ExplicitGCInvokesConcurrent flag, as result - notification is not received. Excluded test execution with -XX:+ExplicitGCInvokesConcurrent. Reviewed-by: dfazunen, tschatzl --- .../lang/management/MemoryMXBean/CollectionUsageThreshold.java | 3 ++- jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java index 64224d23306..74e06e6aa6e 100644 --- a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java +++ b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -32,6 +32,7 @@ * * @library /lib/testlibrary/ * @build jdk.testlibrary.* CollectionUsageThreshold MemoryUtil RunUtil + * @requires vm.opt.ExplicitGCInvokesConcurrent == "false" | vm.opt.ExplicitGCInvokesConcurrent == "null" * @run main/timeout=300 CollectionUsageThreshold */ diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java index 6bf2e8f1ee2..e0d30f0e3c8 100644 --- a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java +++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java @@ -32,6 +32,7 @@ * * @library /lib/testlibrary/ * @build jdk.testlibrary.* LowMemoryTest MemoryUtil RunUtil + * @requires vm.opt.ExplicitGCInvokesConcurrent == "false" | vm.opt.ExplicitGCInvokesConcurrent == "null" * @run main/timeout=600 LowMemoryTest */ From 484ca4753c01ea6f44796bbac25b6e10b8b41639 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Thu, 15 Jan 2015 16:24:25 +0000 Subject: [PATCH 085/149] 8069069: Build failure because of dependency on generated file Make build spuriously fails to build property classes Reviewed-by: jlahoda --- .../share/classes/com/sun/tools/javac/comp/DeferredAttr.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java index 2fb3b0fe757..d2dc52167c4 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java @@ -28,8 +28,6 @@ package com.sun.tools.javac.comp; import com.sun.source.tree.LambdaExpressionTree.BodyKind; import com.sun.tools.javac.code.*; import com.sun.tools.javac.comp.Resolve.ResolveError; -import com.sun.tools.javac.resources.CompilerProperties; -import com.sun.tools.javac.resources.CompilerProperties.Fragments; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.DefinedBy.Api; @@ -798,7 +796,7 @@ public class DeferredAttr extends JCTree.Visitor { case WRONG_MTHS: //note: as argtypes are erroneous types, type-errors must //have been caused by arity mismatch - checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInMref)); + checkContext.report(tree, diags.fragment("incompatible.arg.types.in.mref")); break; case ABSENT_MTH: case STATICERR: From 00b2f7005de70a7cc9c6ff3bcb6a719fc36bd088 Mon Sep 17 00:00:00 2001 From: Chris Hegarty Date: Thu, 15 Jan 2015 17:05:06 +0000 Subject: [PATCH 086/149] 8042581: Intermittent failure in java/net/DatagramSocket/InheritHandle.java Reviewed-by: alanb, chegar --- .../net/DatagramSocket/InheritHandle.java | 52 ++++++++++++++----- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/jdk/test/java/net/DatagramSocket/InheritHandle.java b/jdk/test/java/net/DatagramSocket/InheritHandle.java index b351177644d..80360e7b96c 100644 --- a/jdk/test/java/net/DatagramSocket/InheritHandle.java +++ b/jdk/test/java/net/DatagramSocket/InheritHandle.java @@ -22,27 +22,51 @@ */ /* @test - * @bug 4945514 + * @bug 4945514 8042581 * @summary DatagramSocket should make handle not inherited */ -import java.net.*; +import java.net.BindException; +import java.net.DatagramSocket; +import java.net.InetSocketAddress; public class InheritHandle { + private static final long SLEEPTIME_MS = 1000L; + public static void main(String[] args) throws Exception { - DatagramSocket sock = new DatagramSocket (0); - sock.setReuseAddress(true); - int port = sock.getLocalPort(); + int port; + try (DatagramSocket sock = new DatagramSocket(0);) { + sock.setReuseAddress(true); + port = sock.getLocalPort(); - /** - * spawn a child to check whether handle passed to it or not; - * it shouldn't - */ - Runtime.getRuntime().exec ("sleep 10"); + /** + * spawn a child to check whether handle passed to it or not; it + * shouldn't + */ + Runtime.getRuntime().exec("sleep 10"); + } - sock.close(); - sock = new DatagramSocket (null); - sock.setReuseAddress(true); - sock.bind(new InetSocketAddress(port)); + try (DatagramSocket sock = new DatagramSocket(null);) { + sock.setReuseAddress(true); + int retries = 0; + boolean isWindows = System.getProperty("os.name").startsWith("Windows"); + InetSocketAddress addr = new InetSocketAddress(port); + while (true) { + try { + sock.bind(addr); + break; + } catch (BindException e) { + if (isWindows && retries++ < 5) { + Thread.sleep(SLEEPTIME_MS); + System.out.println("BindException \"" + e.getMessage() + "\", retrying..."); + continue; + } else { + throw e; + } + } + } + + } } } + From f46b3d442f5869aa47e360b472b2029a5607225d Mon Sep 17 00:00:00 2001 From: Artem Smotrakov Date: Thu, 15 Jan 2015 17:57:52 +0000 Subject: [PATCH 087/149] 8059009: LDAPCertStore fails to retrieve CRL after LDAP server closes idle connection Reviewed-by: vinnie --- .../classes/com/sun/jndi/ldap/LdapCtx.java | 7 ++-- .../provider/certpath/ldap/LDAPCertStore.java | 34 ++++++++++++++++--- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java index d8bf38be60a..f89faab4138 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -224,6 +224,7 @@ final public class LdapCtx extends ComponentDirContext String hostname = null; // host name of server (no brackets // for IPv6 literals) LdapClient clnt = null; // connection handle + private boolean reconnect = false; // indicates that re-connect requested Hashtable envprops = null; // environment properties of context int handleReferrals = DEFAULT_REFERRAL_MODE; // how referral is handled boolean hasLdapsScheme = false; // true if the context was created @@ -2663,6 +2664,7 @@ final public class LdapCtx extends ComponentDirContext } sharable = false; // can't share with existing contexts + reconnect = true; ensureOpen(); // open or reauthenticated } @@ -2739,7 +2741,7 @@ final public class LdapCtx extends ComponentDirContext try { boolean initial = (clnt == null); - if (initial) { + if (initial || reconnect) { ldapVersion = (ver != null) ? Integer.parseInt(ver) : DEFAULT_LDAP_VERSION; @@ -2767,6 +2769,7 @@ final public class LdapCtx extends ComponentDirContext // Required for SASL client identity envprops); + reconnect = false; /** * Pooled connections are preauthenticated; diff --git a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java index 05499ead984..3a050d6b55e 100644 --- a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java +++ b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java @@ -37,12 +37,13 @@ import javax.naming.NameNotFoundException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; +import javax.naming.CommunicationException; +import javax.naming.ldap.InitialLdapContext; +import javax.naming.ldap.LdapContext; import javax.security.auth.x500.X500Principal; import sun.misc.HexDumpEncoder; @@ -160,7 +161,12 @@ public final class LDAPCertStore extends CertStoreSpi { /** * The JNDI directory context. */ - private DirContext ctx; + private LdapContext ctx; + + /** + * Flag indicating that communication error occurred. + */ + private boolean communicationError = false; /** * Flag indicating whether we should prefetch CRLs. @@ -218,6 +224,11 @@ public final class LDAPCertStore extends CertStoreSpi { certStoreCache = Cache.newSoftMemoryCache(185); static synchronized CertStore getInstance(LDAPCertStoreParameters params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { + // if necessary, convert params to SunLDAPCertStoreParameters because + // LDAPCertStoreParameters does not override equals() and hashCode() + if (! (params instanceof SunLDAPCertStoreParameters)) { + params = new SunLDAPCertStoreParameters(params.getServerName(), params.getPort()); + } CertStore lcs = certStoreCache.get(params); if (lcs == null) { lcs = CertStore.getInstance("LDAP", params); @@ -256,7 +267,7 @@ public final class LDAPCertStore extends CertStoreSpi { } try { - ctx = new InitialDirContext(env); + ctx = new InitialLdapContext(env, null); /* * By default, follow referrals unless application has * overridden property in an application resource file. @@ -369,8 +380,17 @@ public final class LDAPCertStore extends CertStoreSpi { valueMap = new HashMap<>(8); String[] attrIds = requestedAttributes.toArray(STRING0); Attributes attrs; + + if (communicationError) { + ctx.reconnect(null); + communicationError = false; + } + try { attrs = ctx.getAttributes(name, attrIds); + } catch (CommunicationException ce) { + communicationError = true; + throw ce; } catch (NameNotFoundException e) { // name does not exist on this LDAP server // treat same as not attributes found @@ -884,7 +904,12 @@ public final class LDAPCertStore extends CertStoreSpi { SunLDAPCertStoreParameters() { super(); } + @Override public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof LDAPCertStoreParameters)) { return false; } @@ -892,6 +917,7 @@ public final class LDAPCertStore extends CertStoreSpi { return (getPort() == params.getPort() && getServerName().equalsIgnoreCase(params.getServerName())); } + @Override public int hashCode() { if (hashCode == 0) { int result = 17; From 9d14d4b1e74a704dc20258fb5022a87110eea161 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:36 -0800 Subject: [PATCH 088/149] Added tag jdk9-b46 for changeset 2602be4290e7 --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 0ad3d644f11..2539f7e2c81 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -288,3 +288,4 @@ f7c11da0b0481d49cc7a65a453336c108191e821 jdk9-b42 02ee8c65622e8bd97496d584e22fc7dcf0edc4ae jdk9-b43 8994f5d87b3bb5e8d317d4e8ccb326da1a73684a jdk9-b44 3dd628fde2086218d548841022ee8436b6b88185 jdk9-b45 +12f1e276447bcc81516e85367d53e4f08897049d jdk9-b46 From af90d9fe8a172384256a051df1cd556f39caf69e Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:37 -0800 Subject: [PATCH 089/149] Added tag jdk9-b46 for changeset 87aeabf7ffa2 --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index 859c412f8a7..b7b87c5d34e 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -288,3 +288,4 @@ e27c725d6c9d155667b35255f442d4ceb8c3c084 jdk9-b40 9645e35616b60c5c07b4fdf11a132afc8081dfa8 jdk9-b43 1f57bd728c9e6865ccb9d43ccd80a1c11230a32f jdk9-b44 9e3f2bed80c0e5a84a256ce41f1d10c5ade48466 jdk9-b45 +326f2068b4a4c05e2fa27d6acf93eba7b54b090d jdk9-b46 From 17e982a08fd3de84f3e76b0833758f8c73c1f92f Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:39 -0800 Subject: [PATCH 090/149] Added tag jdk9-b46 for changeset a41296327b3d --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index b4e518b36eb..d53cf114653 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -448,3 +448,4 @@ c363a8b87e477ee45d6d3cb2a36cb365141bc596 jdk9-b38 65a9747147b8090037541040ba67156ec914db6a jdk9-b43 43a44b56dca61a4d766a20f0528fdd8b5ceff873 jdk9-b44 5dc8184af1e2bb30b0103113d1f1a58a21a80c37 jdk9-b45 +a184ee1d717297bd35b7c3e35393e137921a3ed2 jdk9-b46 From 7c78550130566b552db9f565ddf7de990f19bd76 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:42 -0800 Subject: [PATCH 091/149] Added tag jdk9-b46 for changeset b037890ea772 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index cf9a1867715..38503a0b86f 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -288,3 +288,4 @@ a12d347f84176200593999f4da91ae2bb86865b2 jdk9-b39 40b242363040229a05224fbc5dc203a3f46a8f8f jdk9-b43 0cb0844b58924d6086d2850c22087d06679d5eef jdk9-b44 0dab3e848229127c7aca4c58b98e2d90ba70372f jdk9-b45 +74eaf7ad986576c792df4dbff05eed63e5727695 jdk9-b46 From 6472b680e14ee26d569cb3455d9808842b0b5bed Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:43 -0800 Subject: [PATCH 092/149] Added tag jdk9-b46 for changeset 76ad1de0fd63 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index e529fdaecfb..c59b9b39f40 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -291,3 +291,4 @@ dd4ba422dba858b1c3c4b38f49a3e514be4e2790 jdk9-b38 edc13d27dc871be57d7ca77eef77e6d04972fee2 jdk9-b43 2a03baa4d849818ff6d635f110c2813b12fc2326 jdk9-b44 e529374fbe526dbd668e5e98fc047b42b3bc6d33 jdk9-b45 +64ca52b0bda8028636e4ccafbe1107befcdda47d jdk9-b46 From 3e2e519ce8fffc0f18f708670f4805ec4adaac0e Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:48 -0800 Subject: [PATCH 093/149] Added tag jdk9-b46 for changeset 1548d75015bd --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index 7a8ce5643e2..b3c46658a54 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -288,3 +288,4 @@ e336cbd8b15e959e70ed02f0f5e93fa76ebd4c07 jdk9-b41 8c6ad41974f9ab6c33d544b088648314963f2a50 jdk9-b43 8cc4dc300041eb70a7a40e4b2431a8f4d4965ea4 jdk9-b44 9acaa4f57b0b9e3757a7b4576ca9418a75ea8287 jdk9-b45 +efedac7f44ed41cea2b1038138047271f55aacba jdk9-b46 From 1e645dd9ddb59cfec833c3cde18edad032637098 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:52 -0800 Subject: [PATCH 094/149] Added tag jdk9-b46 for changeset 867b8b80696e --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index 78871157c37..119a43b7586 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -288,3 +288,4 @@ f7ce2cfa4cdbec0ae0f46080484eace66be7987a jdk9-b41 6a06008aec10d32898ca665685f531c681b28f5f jdk9-b43 de2ce70d907c9f227b802cea29285bece5194cd5 jdk9-b44 73bbdcf236b297a0c1b8875f2eeba65eaf7ade60 jdk9-b45 +e272d9be5f90edb6bb6b40f7816ec85eec0f5dc2 jdk9-b46 From 3a01ee0832af4602650c05d01062a9a4866b5ea8 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 15 Jan 2015 13:09:53 -0800 Subject: [PATCH 095/149] Added tag jdk9-b46 for changeset 167aecd0161e --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index 924fdc2e2ad..b31c41f7e17 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -279,3 +279,4 @@ dd7bbdf81a537106cfa9227d1a9a57849cb26b4d jdk9-b37 8ae8dff2a28f3b8831cce97ae0c7a957c5dc650a jdk9-b43 50ee576062726e536d1bb9a5eadd8fd4470128fc jdk9-b44 3c2bbeda038aef7061455fec604db7d8a342fac5 jdk9-b45 +2ecf0a617f0f9af1ffd278a0c70e76f1946ce773 jdk9-b46 From 163f2e001ee810013783af3aa80b884219be5877 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Thu, 15 Jan 2015 14:51:05 -0800 Subject: [PATCH 096/149] 8067099: Add deprecation lint warning to build of jdk repository Reviewed-by: erikj --- make/common/SetupJavaCompilers.gmk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/make/common/SetupJavaCompilers.gmk b/make/common/SetupJavaCompilers.gmk index 395de38f6ce..91c37932d91 100644 --- a/make/common/SetupJavaCompilers.gmk +++ b/make/common/SetupJavaCompilers.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2014, 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 @@ -30,9 +30,9 @@ include JavaCompilation.gmk DISABLE_WARNINGS := -Xlint:all,-deprecation,-unchecked,-rawtypes,-cast,-serial,-dep-ann,-static,-fallthrough,-try,-varargs,-empty,-finally -# To build with all warnings enabled, do the following: +# If warnings needs to be non-fatal for testing purposes use a command like: # make JAVAC_WARNINGS="-Xlint:all -Xmaxwarns 10000" -JAVAC_WARNINGS := -Xlint:all,-deprecation -Werror +JAVAC_WARNINGS := -Xlint:all -Werror # The BOOT_JAVAC setup uses the boot jdk compiler to compile the tools # and the interim javac, to be run by the boot jdk. From c0500545f76895294f79682d7578ea8da504103c Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Thu, 15 Jan 2015 16:45:02 -0800 Subject: [PATCH 097/149] 8069127: Suppress deprecation warnings in jdk.deploy.osx module Reviewed-by: wetmore, juh --- .../macosx/classes/apple/security/KeychainStore.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jdk/src/jdk.deploy.osx/macosx/classes/apple/security/KeychainStore.java b/jdk/src/jdk.deploy.osx/macosx/classes/apple/security/KeychainStore.java index a2436e587e1..36f146b9ba7 100644 --- a/jdk/src/jdk.deploy.osx/macosx/classes/apple/security/KeychainStore.java +++ b/jdk/src/jdk.deploy.osx/macosx/classes/apple/security/KeychainStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, 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 @@ -911,6 +911,7 @@ public final class KeychainStore extends KeyStoreSpi { return true; } + @SuppressWarnings("deprecation") private byte[] fetchPrivateKeyFromBag(byte[] privateKeyInfo) throws IOException, NoSuchAlgorithmException, CertificateException { byte[] returnValue = null; @@ -971,6 +972,7 @@ public final class KeychainStore extends KeyStoreSpi { return returnValue; } + @SuppressWarnings("deprecation") private byte[] extractKeyData(DerInputStream stream) throws IOException, NoSuchAlgorithmException, CertificateException { From 120cde915bd3b8406d65e37e214b52db68df014b Mon Sep 17 00:00:00 2001 From: Tristan Yan Date: Thu, 15 Jan 2015 19:10:56 -0800 Subject: [PATCH 098/149] 8051563: Update JAXP functional tests Reviewed-by: lancea, joehw --- .../xml/parsers/ptests/DBFNamespaceTest.java | 61 +- .../ptests/DocumentBuilderFactory01.java | 451 ---------- .../ptests/DocumentBuilderFactory02.java | 87 -- .../ptests/DocumentBuilderFactoryTest.java | 462 ++++++++++ .../parsers/ptests/DocumentBuilderImpl01.java | 106 ++- .../parsers/ptests/FactoryConfErrorTest.java | 15 +- .../xml/parsers/ptests/SAXParserFactTest.java | 202 ++--- .../xml/parsers/ptests/SAXParserTest.java | 811 +++++++++--------- .../xml/parsers/ptests/SAXParserTest02.java | 211 ++--- .../xml/parsers/ptests/SAXParserTest03.java | 76 +- ...OMResultTest01.java => DOMResultTest.java} | 60 +- .../transform/ptests/ErrorListenerTest.java | 9 +- ...AXSourceTest01.java => SAXSourceTest.java} | 57 +- .../xml/transform/ptests/SAXTFactoryTest.java | 423 +++++++++ .../transform/ptests/SAXTFactoryTest001.java | 91 -- .../transform/ptests/SAXTFactoryTest002.java | 95 -- .../transform/ptests/SAXTFactoryTest003.java | 102 --- .../transform/ptests/SAXTFactoryTest004.java | 65 -- .../transform/ptests/SAXTFactoryTest005.java | 104 --- .../transform/ptests/SAXTFactoryTest006.java | 97 --- .../transform/ptests/SAXTFactoryTest008.java | 91 -- .../transform/ptests/SAXTFactoryTest009.java | 93 -- .../transform/ptests/SAXTFactoryTest010.java | 91 -- .../transform/ptests/SAXTFactoryTest011.java | 103 --- .../transform/ptests/SAXTFactoryTest012.java | 93 -- .../transform/ptests/SAXTFactoryTest013.java | 94 -- ...esultTest01.java => StreamResultTest.java} | 9 +- .../transform/ptests/TfClearParamTest.java | 307 +++---- .../transform/ptests/TransformerExcpTest.java | 11 +- .../ptests/TransformerFactoryTest.java | 27 +- .../xml/transform/ptests/TransformerTest.java | 179 ++-- .../transform/ptests/TransformerTest02.java | 45 +- .../transform/ptests/TransformerTest03.java | 47 +- .../xml/transform/ptests/URIResolverTest.java | 189 ++-- .../ptests/othervm/TFCErrorTest.java | 15 +- .../xml/xpath/ptests/XPathExpressionTest.java | 316 +++---- .../xml/xpath/ptests/XPathFactoryTest.java | 56 +- .../ptests/XPathFunctionResolverTest.java | 26 +- .../javax/xml/xpath/ptests/XPathTest.java | 384 ++++----- .../org/xml/sax/ptests/AttrImplTest.java | 5 +- .../org/xml/sax/ptests/AttributesNSTest.java | 57 +- .../org/xml/sax/ptests/AttributesTest.java | 54 +- .../xml/sax/ptests/ContentHandlerTest.java | 51 +- .../xml/sax/ptests/DefaultHandlerTest.java | 61 +- .../org/xml/sax/ptests/EHFatalTest.java | 41 +- .../org/xml/sax/ptests/NSSupportTest.java | 5 +- .../org/xml/sax/ptests/NSTableTest.java | 161 ++++ .../org/xml/sax/ptests/NSTableTest01.java | 193 ----- .../org/xml/sax/ptests/ParserAdapterTest.java | 120 ++- .../org/xml/sax/ptests/ResolverTest.java | 36 +- .../xml/sax/ptests/SAXParserNSTableTest.java | 113 +-- .../org/xml/sax/ptests/XMLFilterCBTest.java | 58 +- .../org/xml/sax/ptests/XMLFilterTest.java | 147 ++-- .../xml/sax/ptests/XMLReaderAdapterTest.java | 58 +- .../xml/sax/ptests/XMLReaderFactoryTest.java | 12 +- .../xml/sax/ptests/XMLReaderNSTableTest.java | 96 +-- .../org/xml/sax/ptests/XMLReaderTest.java | 621 ++++++-------- .../test/auctionportal/AuctionController.java | 314 +++---- .../auctionportal/AuctionItemRepository.java | 467 ++++------ .../test/auctionportal/UserController.java | 296 +++---- .../javax/xml/parsers/ptests/MyCHandler.java} | 61 +- .../xml/parsers/ptests/MyErrorHandler.java | 88 ++ .../xml/parsers/ptests/ParserTestConst.java | 46 + .../transform/ptests/MyContentHandler.java | 2 +- .../ptests/TransformerTestConst.java | 36 +- .../xml/xpath/ptests/XPathTestConst.java | 22 +- .../jaxp/libs/jaxp/library/JAXPBaseTest.java | 138 +++ .../libs/jaxp/library/JAXPFileBaseTest.java | 105 +++ .../library/JAXPFileReadOnlyBaseTest.java | 55 ++ .../libs/jaxp/library/JAXPTestUtilities.java | 171 +++- .../jaxp/libs/jaxp/library/TestPolicy.java | 149 ++++ .../org/xml/sax/ptests/MyAttrCHandler.java | 2 +- .../xml/sax/ptests/MyNSContentHandler.java | 15 +- .../libs/org/xml/sax/ptests/SAXTestConst.java | 36 +- .../test/auctionportal/HiBidConstants.java | 35 +- .../test/auctionportal/MyDOMErrorHandler.java | 2 +- .../test/auctionportal/MyDOMOutput.java | 4 +- .../test/auctionportal/MyErrorHandler.java | 2 +- .../test/auctionportal/XInclHandler.java | 31 +- 79 files changed, 4393 insertions(+), 5334 deletions(-) delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory01.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory02.java create mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactoryTest.java rename jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/{DOMResultTest01.java => DOMResultTest.java} (63%) rename jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/{SAXSourceTest01.java => SAXSourceTest.java} (65%) create mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest001.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest002.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest003.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest004.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest005.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest006.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest008.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest009.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest010.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest011.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest012.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest013.java rename jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/{StreamResultTest01.java => StreamResultTest.java} (92%) create mode 100644 jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest.java delete mode 100644 jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest01.java rename jaxp/test/javax/xml/jaxp/{functional/javax/xml/parsers/ptests/TestUtils.java => libs/javax/xml/parsers/ptests/MyCHandler.java} (83%) create mode 100644 jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyErrorHandler.java create mode 100644 jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/ParserTestConst.java create mode 100644 jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPBaseTest.java create mode 100644 jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileBaseTest.java create mode 100644 jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileReadOnlyBaseTest.java create mode 100644 jaxp/test/javax/xml/jaxp/libs/jaxp/library/TestPolicy.java rename jaxp/test/javax/xml/jaxp/{functional => libs}/org/xml/sax/ptests/MyAttrCHandler.java (98%) rename jaxp/test/javax/xml/jaxp/{functional => libs}/org/xml/sax/ptests/MyNSContentHandler.java (94%) rename jaxp/test/javax/xml/jaxp/{functional => libs}/test/auctionportal/MyDOMErrorHandler.java (96%) rename jaxp/test/javax/xml/jaxp/{functional => libs}/test/auctionportal/MyDOMOutput.java (96%) rename jaxp/test/javax/xml/jaxp/{functional => libs}/test/auctionportal/MyErrorHandler.java (97%) rename jaxp/test/javax/xml/jaxp/{functional => libs}/test/auctionportal/XInclHandler.java (92%) diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DBFNamespaceTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DBFNamespaceTest.java index 930ef818341..6c2f073342b 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DBFNamespaceTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DBFNamespaceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -23,64 +23,59 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; - import java.io.File; -import java.io.IOException; - import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; +import static javax.xml.parsers.ptests.ParserTestConst.GOLDEN_DIR; +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; - +import jaxp.library.JAXPFileBaseTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.w3c.dom.Document; -import org.xml.sax.SAXException; /** * This tests DocumentBuilderFactory for namespace processing and no-namespace * processing. */ -public class DBFNamespaceTest { +public class DBFNamespaceTest extends JAXPFileBaseTest { /** * Provide input for the cases that supporting namespace or not. + * @return a two-dimensional array contains factory, output file name and + * golden validate file name. */ @DataProvider(name = "input-provider") public Object[][] getInput() { DocumentBuilderFactory dbf1 = DocumentBuilderFactory.newInstance(); - String outputfile1 = USER_DIR + FILE_SEP + "dbfnstest01.out"; - String goldfile1 = TestUtils.GOLDEN_DIR + FILE_SEP + "dbfnstest01GF.out"; + String outputfile1 = USER_DIR + "dbfnstest01.out"; + String goldfile1 = GOLDEN_DIR + "dbfnstest01GF.out"; DocumentBuilderFactory dbf2 = DocumentBuilderFactory.newInstance(); dbf2.setNamespaceAware(true); - String outputfile2 = USER_DIR + FILE_SEP + "dbfnstest02.out"; - String goldfile2 = TestUtils.GOLDEN_DIR + FILE_SEP + "dbfnstest02GF.out"; + String outputfile2 = USER_DIR + "dbfnstest02.out"; + String goldfile2 = GOLDEN_DIR + "dbfnstest02GF.out"; return new Object[][] { { dbf1, outputfile1, goldfile1 }, { dbf2, outputfile2, goldfile2 } }; } /** * Test to parse and transform a document without supporting namespace and * with supporting namespace. + * @param dbf a Document Builder factory for creating document object. + * @param outputfile output file name. + * @param goldfile golden validate file name. + * @throws Exception If any errors occur. */ @Test(dataProvider = "input-provider") - public void testNamespaceTest(DocumentBuilderFactory dbf, String outputfile, String goldfile) { - try { - Document doc = dbf.newDocumentBuilder().parse(new File(TestUtils.XML_DIR, "namespace1.xml")); - dummyTransform(doc, outputfile); - assertTrue(compareWithGold(goldfile, outputfile)); - } catch (SAXException | IOException | ParserConfigurationException | TransformerFactoryConfigurationError | TransformerException e) { - failUnexpected(e); - } + public void testNamespaceTest(DocumentBuilderFactory dbf, String outputfile, + String goldfile) throws Exception { + Document doc = dbf.newDocumentBuilder().parse(new File(XML_DIR, "namespace1.xml")); + dummyTransform(doc, outputfile); + assertTrue(compareWithGold(goldfile, outputfile)); } /** @@ -89,16 +84,14 @@ public class DBFNamespaceTest { * not chosen, namespaceURI in callbacks should be an empty string otherwise * it should be namespaceURI. * - * @throws TransformerFactoryConfigurationError - * @throws TransformerException - * @throws IOException + * @throws Exception If any errors occur. */ - private void dummyTransform(Document document, String fileName) throws TransformerFactoryConfigurationError, TransformerException, IOException { + private void dummyTransform(Document document, String fileName) + throws Exception { DOMSource domSource = new DOMSource(document); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - File file = new File(fileName); - System.out.println("The fileName is " + file.getAbsolutePath()); - transformer.transform(domSource, new SAXResult(MyCHandler.newInstance(file))); + try(MyCHandler chandler = MyCHandler.newInstance(new File(fileName))) { + TransformerFactory.newInstance().newTransformer(). + transform(domSource, new SAXResult(chandler)); + } } - } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory01.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory01.java deleted file mode 100644 index fddfaaa89b1..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory01.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * 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. - */ - -package javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * This checks the methods of DocumentBuilderFactoryImpl - */ -public class DocumentBuilderFactory01 { - /** - * Testcase to test the default functionality of schema support method. - */ - @Test - public void testCheckSchemaSupport1() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - dbf.setNamespaceAware(true); - dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "test.xml")); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the default functionality of schema support method. In - * this case the schema source property is set. - */ - @Test - public void testCheckSchemaSupport2() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - dbf.setNamespaceAware(true); - dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", new InputSource(new FileInputStream( - new File(TestUtils.XML_DIR, "test.xsd")))); - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "test1.xml")); - assertFalse(eh.errorOccured); - } catch (IllegalArgumentException | ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the default functionality of schema support method. In - * this case the schema source property is set. - */ - @Test - public void testCheckSchemaSupport3() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setValidating(true); - spf.setNamespaceAware(true); - SAXParser sp = spf.newSAXParser(); - sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", - new InputSource(new FileInputStream(new File(TestUtils.XML_DIR, "test.xsd")))); - DefaultHandler dh = new DefaultHandler(); - sp.parse(new File(TestUtils.XML_DIR, "test1.xml"), dh); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the default functionality of newInstance method. To test - * the isCoalescing method and setCoalescing This checks to see if the CDATA - * and text nodes got combined In that case it will print "<xml>This - * is not parsed</xml> yet". - */ - @Test - public void testCheckDocumentBuilderFactory02() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setCoalescing(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory01.xml")); - Element e = (Element) doc.getElementsByTagName("html").item(0); - NodeList nl = e.getChildNodes(); - assertEquals(nl.item(0).getNodeValue().trim(), "This is not parsed yet"); - } catch (IOException | SAXException | ParserConfigurationException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the isIgnoringComments. By default it is false. - */ - @Test - public void testCheckDocumentBuilderFactory03() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - assertFalse(dbf.isIgnoringComments()); - } - - /** - * Testcase to test the isValidating. By default it is false, set it to true - * and then use a document which is not valid. It should throw a warning or - * an error at least. The test passes in case retval 0 is set in the error - * method . - */ - @Test - public void testCheckDocumentBuilderFactory04() { - try { - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory05.xml")); - assertTrue(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setValidating. By default it is false, use a - * document which is not valid. It should not throw a warning or an error. - * The test passes in case the retval equals 1 . - */ - @Test - public void testCheckDocumentBuilderFactory16() { - try { - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory05.xml")); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the setValidating. By default it is false, use a - * document which is valid. It should not throw a warning or an error. The - * test passes in case the retval equals 1. - */ - @Test - public void testCheckDocumentBuilderFactory17() { - try { - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory04.xml")); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * To test the isExpandEntityReferences. By default it is true. - */ - @Test - public void testCheckDocumentBuilderFactory05() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory02.xml"))); - Element e = (Element) doc.getElementsByTagName("title").item(0); - NodeList nl = e.getChildNodes(); - assertTrue(dbf.isExpandEntityReferences()); - assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the default functionality of setValidating method. The - * xml file has a DTD which has namespaces defined. The parser takes care to - * check if the namespaces using elements and defined attributes are there - * or not. - */ - @Test - public void testCheckDocumentBuilderFactory06() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - MyErrorHandler eh = MyErrorHandler.newInstance(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory04.xml")); - assertTrue(doc instanceof Document); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the setExpandEntityReferences. - */ - @Test - public void testCheckDocumentBuilderFactory07() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setExpandEntityReferences(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory02.xml"))); - Element e = (Element) doc.getElementsByTagName("title").item(0); - NodeList nl = e.getChildNodes(); - assertTrue(dbf.isExpandEntityReferences()); - assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setExpandEntityReferences. - */ - @Test - public void testCheckDocumentBuilderFactory08() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setExpandEntityReferences(false); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory02.xml"))); - Element e = (Element) doc.getElementsByTagName("title").item(0); - NodeList nl = e.getChildNodes(); - assertNull(nl.item(0).getNodeValue()); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setIgnoringComments. By default it is set to false. - * explicitly setting it to false, it recognizes the comment which is in - * Element Node Hence the Element's child node is not null. - */ - @Test - public void testCheckDocumentBuilderFactory09() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setIgnoringComments(false); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory07.xml"))); - Element e = (Element) doc.getElementsByTagName("body").item(0); - NodeList nl = e.getChildNodes(); - assertNotNull(nl.item(0).getNodeValue()); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * This tests for the parse(InputSource). - */ - @Test - public void testCheckDocumentBuilderFactory10() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new InputSource(new BufferedReader(new FileReader(new File(TestUtils.XML_DIR, "DocumentBuilderFactory07.xml"))))); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse InputStream with SystemID as a second parameter. - */ - @Test - public void testCheckDocumentBuilderFactory11() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "dbf10import.xsl")), new File(TestUtils.XML_DIR).toURI() - .toASCIIString()); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse InputStream with empty SystemID as a second - * parameter. - */ - @Test - public void testCheckDocumentBuilderFactory12() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "dbf10import.xsl")), " "); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse(uri). - */ - @Test - public void testCheckDocumentBuilderFactory13() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new File(TestUtils.XML_DIR + FILE_SEP + "dbf10import.xsl").toURI().toASCIIString()); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse (uri) with empty string as parameter should - * throw Sax Exception. - * - * @throws SAXException - * If any parse errors occur. - */ - @Test(expectedExceptions = SAXException.class) - public void testCheckDocumentBuilderFactory14() throws SAXException { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - docBuilder.parse(""); - } catch (ParserConfigurationException | IOException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse (uri) with null uri as parameter should throw - * IllegalArgumentException. - * - */ - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckDocumentBuilderFactory15() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - String uri = null; - docBuilder.parse(uri); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setIgnoringComments. By default it is set to false, - * setting this to true, It does not recognize the comment, Here the - * nodelist has a length 0 because the ignoring comments is true. - */ - @Test - public void testCheckIgnoringComments() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setIgnoringComments(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory08.xml"))); - Element e = (Element) doc.getElementsByTagName("body").item(0); - NodeList nl = e.getChildNodes(); - assertEquals(nl.getLength(), 0); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the default behaviour of setIgnoringComments. By default - * it is set to false, this is similar to case 9 but not setIgnoringComments - * explicitly, it does not recognize the comment. - */ - @Test - public void testCheckIgnoringComments1() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory07.xml"))); - Element e = (Element) doc.getElementsByTagName("body").item(0); - NodeList nl = e.getChildNodes(); - assertFalse(dbf.isIgnoringComments()); - assertNotNull(nl.item(0).getNodeValue()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory02.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory02.java deleted file mode 100644 index 68722085ba2..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory02.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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. - */ - -package javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.sax.SAXResult; - -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; - -/** - * This tests the setIgnoringElementWhitespace and setIgnoringComments of - * DocumentBuilderFactory - */ -public class DocumentBuilderFactory02 { - - /** - * This testcase tests for the isIgnoringElementContentWhitespace and the - * setIgnoringElementContentWhitespace. The xml file has all kinds of - * whitespace,tab and newline characters, it uses the MyNSContentHandler - * which does not invoke the characters callback when this - * setIgnoringElementContentWhitespace is set to true. - */ - @Test - public void testCheckElementContentWhitespace() { - try { - String goldFile = TestUtils.GOLDEN_DIR + FILE_SEP + "dbfactory02GF.out"; - String outputFile = USER_DIR + FILE_SEP + "dbfactory02.out"; - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - assertFalse(dbf.isIgnoringElementContentWhitespace()); - dbf.setIgnoringElementContentWhitespace(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory06.xml")); - assertFalse(eh.errorOccured); - DOMSource domSource = new DOMSource(doc); - TransformerFactory tfactory = TransformerFactory.newInstance(); - Transformer transformer = tfactory.newTransformer(); - SAXResult saxResult = new SAXResult(); - saxResult.setHandler(MyCHandler.newInstance(new File(outputFile))); - transformer.transform(domSource, saxResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { - failUnexpected(e); - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactoryTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactoryTest.java new file mode 100644 index 00000000000..28ef7b0f226 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactoryTest.java @@ -0,0 +1,462 @@ +/* + * 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 + * 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. + */ + +package javax.xml.parsers.ptests; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FilePermission; +import java.io.FileReader; +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import static javax.xml.parsers.ptests.ParserTestConst.GOLDEN_DIR; +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXResult; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * This checks the methods of DocumentBuilderFactoryImpl. + */ +public class DocumentBuilderFactoryTest extends JAXPFileBaseTest { + /** + * Test the default functionality of schema support method. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckSchemaSupport1() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + dbf.setNamespaceAware(true); + dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + W3C_XML_SCHEMA_NS_URI); + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "test.xml")); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the default functionality of schema support method. In + * this case the schema source property is set. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckSchemaSupport2() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "test.xsd"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + dbf.setNamespaceAware(true); + dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + W3C_XML_SCHEMA_NS_URI); + dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", + new InputSource(fis)); + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "test1.xml")); + assertFalse(eh.isErrorOccured()); + } + } + + /** + * Test the default functionality of schema support method. In + * this case the schema source property is set. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckSchemaSupport3() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "test.xsd"))) { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(true); + spf.setNamespaceAware(true); + SAXParser sp = spf.newSAXParser(); + sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + W3C_XML_SCHEMA_NS_URI); + sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", + new InputSource(fis)); + DefaultHandler dh = new DefaultHandler(); + // Not expect any unrecoverable error here. + sp.parse(new File(XML_DIR, "test1.xml"), dh); + } + } + + /** + * Test the default functionality of newInstance method. To test + * the isCoalescing method and setCoalescing This checks to see if the CDATA + * and text nodes got combined In that case it will print "<xml>This + * is not parsed</xml> yet". + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory02() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setCoalescing(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(new File(XML_DIR, "DocumentBuilderFactory01.xml")); + Element e = (Element) doc.getElementsByTagName("html").item(0); + NodeList nl = e.getChildNodes(); + assertEquals(nl.getLength(), 1); + } + + /** + * Test the isIgnoringComments. By default it is false. + */ + @Test + public void testCheckDocumentBuilderFactory03() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + assertFalse(dbf.isIgnoringComments()); + } + + /** + * Test the isValidating. By default it is false, set it to true and then + * use a document which is not valid. It should throw a warning or + * an error at least. The test passes in case retval 0 is set in the error + * method . + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory04() throws Exception { + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "DocumentBuilderFactory05.xml")); + assertTrue(eh.isErrorOccured()); + } + + /** + * Test the setValidating. By default it is false, use a + * document which is not valid. It should not throw a warning or an error. + * The test passes in case the return value equals 1. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory16() throws Exception { + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "DocumentBuilderFactory05.xml")); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the setValidating. By default it is false, use a + * document which is valid. It should not throw a warning or an error. The + * test passes in case the return value equals 1. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory17() throws Exception { + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "DocumentBuilderFactory04.xml")); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the isExpandEntityReferences. By default it is true. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory05() throws Exception { + try(FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory02.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("title").item(0); + NodeList nl = e.getChildNodes(); + assertTrue(dbf.isExpandEntityReferences()); + assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); + } + } + + /** + * Test the default functionality of setValidating method. The + * XML file has a DTD which has namespaces defined. The parser takes care to + * check if the namespaces using elements and defined attributes are there + * or not. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory06() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + MyErrorHandler eh = MyErrorHandler.newInstance(); + db.setErrorHandler(eh); + Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory04.xml")); + assertTrue(doc instanceof Document); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the setExpandEntityReferences. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory07() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory02.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setExpandEntityReferences(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("title").item(0); + NodeList nl = e.getChildNodes(); + assertTrue(dbf.isExpandEntityReferences()); + assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); + } + } + + /** + * Test the setExpandEntityReferences. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory08() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory02.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setExpandEntityReferences(false); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("title").item(0); + NodeList nl = e.getChildNodes(); + assertNull(nl.item(0).getNodeValue()); + } + } + + /** + * Test the setIgnoringComments. By default it is set to false. + * explicitly setting it to false, it recognizes the comment which is in + * Element Node Hence the Element's child node is not null. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory09() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory07.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(false); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("body").item(0); + NodeList nl = e.getChildNodes(); + assertNotNull(nl.item(0).getNodeValue()); + } + } + + /** + * This tests for the parse(InputSource). + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory10() throws Exception { + try (BufferedReader br = new BufferedReader(new FileReader(new File( + XML_DIR, "DocumentBuilderFactory07.xml")))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(new InputSource(br)); + assertNotNull(doc); + } + } + + /** + * This tests for the parse InputStream with SystemID as a second parameter. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory11() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "dbf10import.xsl"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis, new File(XML_DIR).toURI() + .toASCIIString()); + assertNotNull(doc); + } + } + + /** + * This tests for the parse InputStream with empty SystemID as a second + * parameter. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory12() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "dbf10import.xsl"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis, " "); + assertNotNull(doc); + } + } + + /** + * This tests for the parse(uri). + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory13() throws Exception { + // Accesing default working directory. + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir + "/*", "read")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(new File(XML_DIR + "dbf10import.xsl") + .toURI().toASCIIString()); + assertNotNull(doc); + } + + /** + * This tests for the parse(uri) with empty string as parameter should + * throw Sax Exception. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = SAXException.class) + public void testCheckDocumentBuilderFactory14() throws Exception { + // Accesing default working directory. + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + docBuilder.parse(""); + } + + /** + * This tests for the parse (uri) with null uri as parameter should throw + * IllegalArgumentException. + * @throws Exception If any errors occur. + * + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void testCheckDocumentBuilderFactory15() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + String uri = null; + docBuilder.parse(uri); + } + + /** + * Test the setIgnoringComments. By default it is set to false, + * setting this to true, It does not recognize the comment, Here the + * nodelist has a length 0 because the ignoring comments is true. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckIgnoringComments() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory08.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("body").item(0); + NodeList nl = e.getChildNodes(); + assertEquals(nl.getLength(), 0); + } + } + + /** + * Test the default behaviour of setIgnoringComments. By default + * it is set to false, this is similar to case 9 but not setIgnoringComments + * explicitly, it does not recognize the comment. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckIgnoringComments1() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory07.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("body").item(0); + NodeList nl = e.getChildNodes(); + assertFalse(dbf.isIgnoringComments()); + assertNotNull(nl.item(0).getNodeValue()); + } + } + + /** + * Test for the isIgnoringElementContentWhitespace and the + * setIgnoringElementContentWhitespace. The xml file has all kinds of + * whitespace,tab and newline characters, it uses the MyNSContentHandler + * which does not invoke the characters callback when this + * setIgnoringElementContentWhitespace is set to true. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckElementContentWhitespace() throws Exception { + String goldFile = GOLDEN_DIR + "dbfactory02GF.out"; + String outputFile = USER_DIR + "dbfactory02.out"; + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + assertFalse(dbf.isIgnoringElementContentWhitespace()); + dbf.setIgnoringElementContentWhitespace(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml")); + assertFalse(eh.isErrorOccured()); + DOMSource domSource = new DOMSource(doc); + TransformerFactory tfactory = TransformerFactory.newInstance(); + Transformer transformer = tfactory.newTransformer(); + SAXResult saxResult = new SAXResult(); + try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) { + saxResult.setHandler(handler); + transformer.transform(domSource, saxResult); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderImpl01.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderImpl01.java index d565748c37a..144df205131 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderImpl01.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderImpl01.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -24,33 +24,32 @@ package javax.xml.parsers.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; - import java.io.File; import java.io.FileInputStream; -import java.io.IOException; - +import java.io.FilePermission; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import jaxp.library.JAXPFileReadOnlyBaseTest; +import static org.testng.Assert.assertNotNull; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * This checks for the methods of DocumentBuilder */ -public class DocumentBuilderImpl01 implements EntityResolver { - +public class DocumentBuilderImpl01 extends JAXPFileReadOnlyBaseTest + implements EntityResolver { /** * Provide DocumentBuilder. * - * @throws ParserConfigurationException + * @return data provider has single DocumentBuilder. + * @throws ParserConfigurationException if a DocumentBuilder cannot be + * created which satisfies the configuration requested. */ @DataProvider(name = "builder-provider") public Object[][] getBuilder() throws ParserConfigurationException { @@ -60,17 +59,18 @@ public class DocumentBuilderImpl01 implements EntityResolver { } /** - * Testcase to test the default functionality of isValidation method. Expect + * Test the default functionality of isValidation method. Expect * to return false because not setting the validation. + * @param docBuilder document builder instance. */ @Test(dataProvider = "builder-provider") public void testCheckDocumentBuilderImpl01(DocumentBuilder docBuilder) { assertFalse(docBuilder.isValidating()); - } /** - * Testcase to test the default functionality of isNamespaceAware method. + * Test the default functionality of isNamespaceAware method. + * @param docBuilder document builder instance. */ @Test(dataProvider = "builder-provider") public void testCheckDocumentBuilderImpl02(DocumentBuilder docBuilder) { @@ -78,51 +78,71 @@ public class DocumentBuilderImpl01 implements EntityResolver { } /** - * Testcase to test the parse(InputStream). + * Test the parse(InputStream). + * @param docBuilder document builder instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "builder-provider") - public void testCheckDocumentBuilderImpl04(DocumentBuilder docBuilder) { - try { - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderImpl01.xml"))); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "builder-provider") + public void testCheckDocumentBuilderImpl04(DocumentBuilder docBuilder) + throws Exception { + try (FileInputStream fis = new FileInputStream(new File(XML_DIR, + "DocumentBuilderImpl01.xml"))) { + assertNotNull(docBuilder.parse(fis)); } } /** - * Testcase to test the parse(File). + * Test the parse(File). + * + * @param docBuilder document builder instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "builder-provider") - public void testCheckDocumentBuilderImpl05(DocumentBuilder docBuilder) { - try { - Document doc = docBuilder.parse(new File(TestUtils.XML_DIR, "DocumentBuilderImpl01.xml")); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "builder-provider") + public void testCheckDocumentBuilderImpl05(DocumentBuilder docBuilder) + throws Exception { + assertNotNull(docBuilder.parse(new File(XML_DIR, + "DocumentBuilderImpl01.xml"))); + } + + /** + * Test the parse(InputStream,systemId). + * @param docBuilder document builder instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "builder-provider") + public void testCheckDocumentBuilderImpl06(DocumentBuilder docBuilder) + throws Exception { + setPermissions(new FilePermission(XML_DIR + "../-", + "read")); + try (FileInputStream fis = new FileInputStream(new File(XML_DIR, + "DocumentBuilderImpl02.xml"))) { + assertNotNull(docBuilder.parse(fis, new File(XML_DIR).toURI() + .toASCIIString() + FILE_SEP)); } } /** - * Testcase to test the parse(InputStream,systemId). - */ - @Test(dataProvider = "builder-provider") - public void testCheckDocumentBuilderImpl06(DocumentBuilder docBuilder) { - try { - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderImpl02.xml")), new File(TestUtils.XML_DIR).toURI() - .toASCIIString() + FILE_SEP); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setEntityResolver. + * Test the setEntityResolver. + * @param docBuilder document builder instance. */ @Test(dataProvider = "builder-provider") public void testCheckDocumentBuilderImpl07(DocumentBuilder docBuilder) { docBuilder.setEntityResolver(this); - resolveEntity("publicId", "http://www.myhost.com/today"); + assertNotNull(resolveEntity("publicId", "http://www.myhost.com/today")); } + /** + * Allow the application to resolve external entities. + * + * @param publicId The public identifier of the external entity + * being referenced, or null if none was supplied. + * @param systemId The system identifier of the external entity + * being referenced. + * @return An InputSource object describing the new input source, + * or null to request that the parser open a regular + * URI connection to the system identifier. + */ + @Override public InputSource resolveEntity(String publicId, String systemId) { if (systemId.equals("http://www.myhost.com/today")) return new InputSource(systemId); diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/FactoryConfErrorTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/FactoryConfErrorTest.java index 947d6d8dd7d..88a66dd5506 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/FactoryConfErrorTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/FactoryConfErrorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -26,6 +26,7 @@ package javax.xml.parsers.ptests; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPBaseTest; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; @@ -35,7 +36,7 @@ import org.testng.annotations.Test; * Class containing the test cases for SAXParserFactory/DocumentBuilderFactory * newInstance methods. */ -public class FactoryConfErrorTest { +public class FactoryConfErrorTest extends JAXPBaseTest { /** * Set properties DocumentBuilderFactory and SAXParserFactory to invalid @@ -43,8 +44,8 @@ public class FactoryConfErrorTest { */ @BeforeTest public void setup() { - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "xx"); - System.setProperty("javax.xml.parsers.SAXParserFactory", "xx"); + setSystemProperty("javax.xml.parsers.DocumentBuilderFactory", "xx"); + setSystemProperty("javax.xml.parsers.SAXParserFactory", "xx"); } /** @@ -53,8 +54,8 @@ public class FactoryConfErrorTest { */ @AfterTest public void cleanup() { - System.clearProperty("javax.xml.parsers.DocumentBuilderFactory"); - System.clearProperty("javax.xml.parsers.SAXParserFactory"); + setSystemProperty("javax.xml.parsers.DocumentBuilderFactory", null); + setSystemProperty("javax.xml.parsers.SAXParserFactory", null); } /** @@ -67,7 +68,7 @@ public class FactoryConfErrorTest { } /** - * To test exeception thrown if javax.xml.parsers.DocumentBuilderFactory is + * To test exception thrown if javax.xml.parsers.DocumentBuilderFactory is * invalid. */ @Test(expectedExceptions = FactoryConfigurationError.class) diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserFactTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserFactTest.java index da87e006f58..8c84ed85cc0 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserFactTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserFactTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -22,24 +22,16 @@ */ package javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import jaxp.library.JAXPBaseTest; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; /** - * Class containing the test cases for SAXParserFactory API + * Class containing the test cases for SAXParserFactory API. */ -public class SAXParserFactTest { +public class SAXParserFactTest extends JAXPBaseTest { private static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; private static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; @@ -49,20 +41,17 @@ public class SAXParserFactTest { private static final String EXTERNAL_P_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; /** - * Testcase to test if newSAXParser() method returns SAXParser. + * Test if newSAXParser() method returns SAXParser. + * @throws Exception If any errors occur. */ @Test - public void testParser01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxparser = spf.newSAXParser(); - } catch (ParserConfigurationException | SAXException e) { - failUnexpected(e); - } + public void testParser01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.newSAXParser(); } /** - * Testcase to test the default functionality (No validation) of the parser. + * Test the default functionality (No validation) of the parser. */ @Test public void testValidate01() { @@ -71,7 +60,7 @@ public class SAXParserFactTest { } /** - * Testcase to test the functionality of setValidating and isvalidating + * Test the functionality of setValidating and isvalidating * methods. */ @Test @@ -82,7 +71,7 @@ public class SAXParserFactTest { } /** - * Parser should not be namespaceaware by default. + * Parser should not be namespace-aware by default. */ @Test public void testNamespace01() { @@ -91,7 +80,7 @@ public class SAXParserFactTest { } /** - * Testcase to test the functionality of setNamespaceAware and + * Test the functionality of setNamespaceAware and * isNamespaceAware methods. */ @Test @@ -102,167 +91,132 @@ public class SAXParserFactTest { } /** - * Testcase to test the functionality of setNamespaceAware and getFeature() + * Test the functionality of setNamespaceAware and getFeature() * methods for namespaces property. + * @throws Exception If any errors occur. */ @Test - public void testFeature01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.getFeature(NAMESPACES)); + public void testFeature01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.getFeature(NAMESPACES)); - spf.setNamespaceAware(true); - assertTrue(spf.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + spf.setNamespaceAware(true); + assertTrue(spf.getFeature(NAMESPACES)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for namespaces property. + * @throws Exception If any errors occur. */ @Test - public void testFeature02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); + public void testFeature02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(NAMESPACES, true); - assertTrue(spf.getFeature(NAMESPACES)); + spf.setFeature(NAMESPACES, true); + assertTrue(spf.getFeature(NAMESPACES)); - spf.setFeature(NAMESPACES, false); - assertFalse(spf.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + spf.setFeature(NAMESPACES, false); + assertFalse(spf.getFeature(NAMESPACES)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for namespace-prefixes property. + * @throws Exception If any errors occur. */ @Test - public void testFeature03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); + public void testFeature03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); + spf.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); - spf.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + spf.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); } /** - * Testcase to test the functionality of getFeature method for + * Test the functionality of getFeature method for * string-interning property. + * @throws Exception If any errors occur. */ @Test - public void testFeature04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertTrue(spf.getFeature(STRING_INTERNING)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + public void testFeature04() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertTrue(spf.getFeature(STRING_INTERNING)); } /** - * Testcase to test the functionality of getFeature and setValidating + * Test the functionality of getFeature and setValidating * methods for validation property. + * @throws Exception If any errors occur. */ @Test - public void testFeature05() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.getFeature(VALIDATION)); - spf.setValidating(true); - assertTrue(spf.getFeature(VALIDATION)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature05() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.getFeature(VALIDATION)); + spf.setValidating(true); + assertTrue(spf.getFeature(VALIDATION)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for validation property. + * @throws Exception If any errors occur. */ @Test - public void testFeature06() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - - spf.setFeature(VALIDATION, true); - assertTrue(spf.getFeature(VALIDATION)); - - spf.setFeature(VALIDATION, false); - assertFalse(spf.getFeature(VALIDATION)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature06() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(VALIDATION, true); + assertTrue(spf.getFeature(VALIDATION)); + spf.setFeature(VALIDATION, false); + assertFalse(spf.getFeature(VALIDATION)); } /** - * Testcase to test the functionality of getFeature method for + * Test the functionality of getFeature method for * external-general-entities property. + * @throws Exception If any errors occur. */ @Test - public void testFeature07() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertTrue(spf.getFeature(EXTERNAL_G_ENTITIES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature07() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertTrue(spf.getFeature(EXTERNAL_G_ENTITIES)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for external-general-entities property. + * @throws Exception If any errors occur. */ @Test - public void testFeature08() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(EXTERNAL_G_ENTITIES, false); - assertFalse(spf.getFeature(EXTERNAL_G_ENTITIES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + public void testFeature08() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(EXTERNAL_G_ENTITIES, false); + assertFalse(spf.getFeature(EXTERNAL_G_ENTITIES)); } /** - * Testcase to test the functionality of getFeature method for + * Test the functionality of getFeature method for * external-parameter-entities property. + * @throws Exception If any errors occur. */ @Test - public void testFeature09() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertTrue(spf.getFeature(EXTERNAL_P_ENTITIES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + public void testFeature09() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertTrue(spf.getFeature(EXTERNAL_P_ENTITIES)); } /** - * Testcase to test the functionality of setFeature method for + * Test the functionality of setFeature method for * external-parameter-entitie property. + * @throws Exception If any errors occur. */ @Test - public void testFeature10() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(EXTERNAL_P_ENTITIES, false); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature10() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(EXTERNAL_P_ENTITIES, false); + assertFalse(spf.getFeature(EXTERNAL_P_ENTITIES)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest.java index af2c5a683b7..920f0917ff7 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -23,16 +23,14 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.failUnexpected; - import java.io.File; import java.io.FileInputStream; +import java.io.FilePermission; import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import jaxp.library.JAXPFileReadOnlyBaseTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.xml.sax.HandlerBase; @@ -43,16 +41,15 @@ import org.xml.sax.helpers.DefaultHandler; /** * Class contains the test cases for SAXParser API */ -public class SAXParserTest { - +public class SAXParserTest extends JAXPFileReadOnlyBaseTest { /** * Provide SAXParser. * - * @throws SAXException - * @throws ParserConfigurationException + * @return a data provider contains a SAXParser instance. + * @throws Exception If any errors occur. */ @DataProvider(name = "parser-provider") - public Object[][] getParser() throws ParserConfigurationException, SAXException { + public Object[][] getParser() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxparser = spf.newSAXParser(); return new Object[][] { { saxparser } }; @@ -62,498 +59,454 @@ public class SAXParserTest { * Test case with FileInputStream null, parsing should fail and throw * IllegalArgumentException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse01(SAXParser saxparser) throws IllegalArgumentException { + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse01(SAXParser saxparser) throws Exception { + FileInputStream instream = null; + saxparser.parse(instream, new HandlerBase()); + } + + /** + * Test with by setting URI as null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse02(SAXParser saxparser) throws Exception { + String uri = null; + saxparser.parse(uri, new HandlerBase()); + } + + /** + * Test with non-existence URI, parsing should fail and throw IOException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = { SAXException.class }, + dataProvider = "parser-provider") + public void testParse03(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); try { - FileInputStream instream = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + saxparser.parse("", new HandlerBase()); + } finally { + setPermissions(); } } /** - * Testcase with an error in xml file, parsing should fail and throw + * Test with File null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse04(SAXParser saxparser) throws Exception { + File file = null; + saxparser.parse(file, new HandlerBase()); + } + + /** + * Test with empty string as File, parsing should fail and throw * SAXException. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse02(SAXParser saxparser) throws SAXException { + public void testParse05(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - saxparser.parse(instream, handler); - } catch (IOException e) { - failUnexpected(e); + saxparser.parse(new File(""), new HandlerBase()); + } finally { + setPermissions(); } } /** - * Testcase with a valid in xml file, parser should parse the xml document. - */ - @Test(dataProvider = "parser-provider") - public void testParse03(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - saxparser.parse(new File(TestUtils.XML_DIR, "parsertest.xml"), handler); - } catch (IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase with valid input stream, parser should parse the xml document - * successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse04(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with valid input source, parser should parse the xml document - * successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse05(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "parsertest.xml")); - saxparser.parse(instream, handler, new File(TestUtils.XML_DIR).toURI().toASCIIString()); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with uri null, parsing should fail and throw + * Test with input source null, parsing should fail and throw * IllegalArgumentException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse07(SAXParser saxparser) throws IllegalArgumentException { - try { - String uri = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(uri, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse06(SAXParser saxparser) throws Exception { + InputSource is = null; + saxparser.parse(is, new HandlerBase()); } /** - * Testcase with non-existant uri, parsing should fail and throw - * IOException. - * - * @throws SAXException - * @throws IOException - */ - @Test(expectedExceptions = { SAXException.class, IOException.class }, dataProvider = "parser-provider") - public void testParse08(SAXParser saxparser) throws SAXException, IOException { - String uri = " "; - - HandlerBase handler = new HandlerBase(); - saxparser.parse(uri, handler); - - } - - /** - * Testcase with proper uri, parser should parse successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse09(SAXParser saxparser) { - try { - File file = new File(TestUtils.XML_DIR, "correct.xml"); - HandlerBase handler = new HandlerBase(); - saxparser.parse(file.toURI().toASCIIString(), handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with File null, parsing should fail and throw + * Test with FileInputStream null, parsing should fail and throw * IllegalArgumentException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse10(SAXParser saxparser) throws IllegalArgumentException { - try { - File file = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(file, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse07(SAXParser saxparser) throws Exception { + FileInputStream instream = null; + saxparser.parse(instream, new DefaultHandler()); } /** - * Testcase with empty string as File, parsing should fail and throw - * SAXException. - * - * @throws SAXException - */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse11(SAXParser saxparser) throws SAXException { - try { - HandlerBase handler = new HandlerBase(); - File file = new File(""); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with xml file that has errors parsing should fail and throw - * SAXException. - * - * @throws SAXException - */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse12(SAXParser saxparser) throws SAXException { - try { - HandlerBase handler = new HandlerBase(); - File file = new File(TestUtils.XML_DIR, "valid.xml"); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with xml file that has no errors Parser should successfully - * parse the xml document. - */ - @Test(dataProvider = "parser-provider") - public void testParse13(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - File file = new File(TestUtils.XML_DIR, "correct.xml"); - saxparser.parse(file, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - - } - - /** - * Testcase with input source null, parsing should fail and throw + * Test with URI null, parsing should fail and throw * IllegalArgumentException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse14(SAXParser saxparser) throws IllegalArgumentException { - try { - InputSource is = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse08(SAXParser saxparser) throws Exception { + String uri = null; + saxparser.parse(uri, new DefaultHandler()); } /** - * Testcase with input source attached an invaild xml, parsing should fail - * and throw SAXException. - * - * @throws SAXException - */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse15(SAXParser saxparser) throws SAXException { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with input source attached an vaild xml, parser should - * successfully parse the xml document. - */ - @Test(dataProvider = "parser-provider") - public void testParse16(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with FileInputStream null, parsing should fail and throw - * IllegalArgumentException. - * - * @throws IllegalArgumentException - */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse17(SAXParser saxparser) throws IllegalArgumentException { - try { - FileInputStream instream = null; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with an error in xml file, parsing should fail and throw - * SAXException. - * - * @throws SAXException - */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse18(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - saxparser.parse(instream, handler); - } catch (IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with valid input stream, parser should parse the xml document - * successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse19(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(new File(TestUtils.XML_DIR, "parsertest.xml"), handler); - } catch (IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase with valid input stream, parser should parse the xml document - * successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse20(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with valid input source, parser should parse the xml document - * successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse21(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "parsertest.xml")); - saxparser.parse(instream, handler, new File(TestUtils.XML_DIR).toURI().toASCIIString()); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - - } - - /** - * Testcase with uri null, parsing should fail and throw - * IllegalArgumentException. - * - * @throws IllegalArgumentException - */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse23(SAXParser saxparser) throws IllegalArgumentException { - try { - String uri = null; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(uri, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with non-existant uri, parsing should fail and throw + * Test with non-existence URI, parsing should fail and throw * SAXException or IOException. * - * @throws SAXException - * @throws IOException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = { SAXException.class, IOException.class }, dataProvider = "parser-provider") - public void testParse24(SAXParser saxparser) throws SAXException, IOException { + @Test(expectedExceptions = { SAXException.class, IOException.class }, + dataProvider = "parser-provider") + public void testParse09(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir + "/../-", "read")); String uri = " "; + try { + saxparser.parse(uri, new DefaultHandler()); + } finally { + setPermissions(); + } + } + + /** + * Test with empty string as File, parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") + public void testParse10(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); + File file = new File(""); + try { + saxparser.parse(file, new DefaultHandler()); + } finally { + setPermissions(); + } + } + + /** + * Test with File null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse11(SAXParser saxparser) throws Exception { + saxparser.parse((File) null, new DefaultHandler()); + } + + /** + * Test with input source null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse12(SAXParser saxparser) throws Exception { + InputSource is = null; + saxparser.parse(is, new DefaultHandler()); + } + + /** + * Test with an error in XML file, parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse13(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File( + XML_DIR, "invalid.xml"))) { + saxparser.parse(instream, new HandlerBase()); + } + } + + /** + * Test with a valid in XML file, parser should parse the XML document. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse14(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "parsertest.xml"), + new HandlerBase()); + } + + /** + * Test with valid input stream, parser should parse the XML document + * successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse15(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File(XML_DIR, + "correct.xml"))) { + saxparser.parse(instream, new HandlerBase()); + } + } + + /** + * Test with valid input source, parser should parse the XML document + * successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse16(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "parsertest.xml"))) { + saxparser.parse(instream, new HandlerBase(), + new File(XML_DIR).toURI().toASCIIString()); + } + } + + /** + * Test with proper URI, parser should parse successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse17(SAXParser saxparser) throws Exception { + File file = new File(XML_DIR, "correct.xml"); + saxparser.parse(file.toURI().toASCIIString(), new HandlerBase()); + } + + /** + * Test with XML file that has errors parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse18(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "valid.xml"), new HandlerBase()); + } + + /** + * Test with XML file that has no errors Parser should successfully + * parse the XML document. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse19(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "correct.xml"), new HandlerBase()); + } + + /** + * Test with input source attached an invalid XML, parsing should fail + * and throw SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse20(SAXParser saxparser) throws Exception { + try(FileInputStream instream = new FileInputStream(new File(XML_DIR, + "invalid.xml"))) { + saxparser.parse(new InputSource(instream), new HandlerBase()); + } + } + + /** + * Test with input source attached an valid XML, parser should + * successfully parse the XML document. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse21(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File(XML_DIR, + "correct.xml"))) { + saxparser.parse(new InputSource(instream), new HandlerBase()); + } + } + + /** + * Test with an error in xml file, parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse22(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "invalid.xml"))) { + saxparser.parse(instream, new DefaultHandler()); + } + } + + /** + * Test with valid input stream, parser should parse the XML document + * successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse23(SAXParser saxparser) throws Exception { DefaultHandler handler = new DefaultHandler(); - saxparser.parse(uri, handler); - + saxparser.parse(new File(XML_DIR, "parsertest.xml"), handler); } /** - * Testcase with proper uri, parser should parse successfully. - */ - @Test(dataProvider = "parser-provider") - public void testParse25(SAXParser saxparser) { - try { - File file = new File(TestUtils.XML_DIR, "correct.xml"); - - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(file.toURI().toASCIIString(), handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with File null, parsing should fail and throw - * IllegalArgumentException. + * Test with valid input stream, parser should parse the XML document + * successfully. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse26(SAXParser saxparser) throws IllegalArgumentException { - try { + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse24(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File(XML_DIR, + "correct.xml"))) { DefaultHandler handler = new DefaultHandler(); - saxparser.parse((File) null, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + saxparser.parse(instream, handler); } } /** - * Testcase with empty string as File, parsing should fail and throw + * Test with valid input source, parser should parse the XML document + * successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse25(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "parsertest.xml"))) { + saxparser.parse(instream, new DefaultHandler(), + new File(XML_DIR).toURI().toASCIIString()); + } + } + + /** + * Test with proper URI, parser should parse successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse26(SAXParser saxparser) throws Exception { + File file = new File(XML_DIR, "correct.xml"); + saxparser.parse(file.toURI().toASCIIString(), new DefaultHandler()); + } + + /** + * Test with XML file that has errors, parsing should fail and throw * SAXException. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse27(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - File file = new File(""); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse27(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "valid.xml"), new DefaultHandler()); } /** - * Testcase with xml file that has errors, parsing should fail and throw - * SAXException. + * Test with XML file that has no errors, parser should successfully + * parse the XML document. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse28(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - File file = new File(TestUtils.XML_DIR, "valid.xml"); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse28(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "correct.xml"), new DefaultHandler()); } /** - * Testcase with xml file that has no errors, parser should successfully - * parse the xml document. - */ - @Test(dataProvider = "parser-provider") - public void testParse29(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - File file = new File(TestUtils.XML_DIR, "correct.xml"); - saxparser.parse(file, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase with input source null, parsing should fail and throw - * IllegalArgumentException. + * Test with an invalid XML file, parser should throw SAXException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse30(SAXParser saxparser) throws IllegalArgumentException { - try { - InputSource is = null; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse29(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "invalid.xml"))) { + saxparser.parse(new InputSource(instream), new DefaultHandler()); } } /** - * Testcase with an invalid xml file, parser should throw SAXException. + * Test case to parse an XML file that not use namespaces. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse31(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse30(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "correct.xml"))) { + saxparser.parse(new InputSource(instream), new DefaultHandler()); } } /** - * Test case to parse an xml file that not use namespaces. + * Test case to parse an XML file that uses namespaces. + * + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse32(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Test case to parse an xml file that uses namespaces. - */ - @Test - public void testParse33() { - try { + @Test(groups = {"readLocalFiles"}) + public void testParse31() throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "ns4.xml"))) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "ns4.xml")); - saxparser.parse(instream, handler); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); + spf.newSAXParser().parse(instream, new HandlerBase()); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest02.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest02.java index 9bfd3ef4c4e..c396d73259b 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest02.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest02.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -23,260 +23,239 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.assertNotNull; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import org.xml.sax.Parser; import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.XMLReader; import org.xml.sax.ext.DeclHandler; import org.xml.sax.ext.LexicalHandler; /** * Class contains the test cases for SAXParser API */ -public class SAXParserTest02 { - final String DOM_NODE = "http://xml.org/sax/properties/dom-node"; - final String XML_STRING = "http://xml.org/sax/properties/xml-string"; - final String DECL_HANDLER = "http://xml.org/sax/properties/declaration-handler"; - final String LEXICAL_HANDLER = "http://xml.org/sax/properties/lexical-handler"; +public class SAXParserTest02 extends JAXPBaseTest { + private static final String DOM_NODE = "http://xml.org/sax/properties/dom-node"; + private static final String XML_STRING = "http://xml.org/sax/properties/xml-string"; + private static final String DECL_HANDLER = "http://xml.org/sax/properties/declaration-handler"; + private static final String LEXICAL_HANDLER = "http://xml.org/sax/properties/lexical-handler"; /** * Provide SAXParser. * - * @throws SAXException - * @throws ParserConfigurationException + * @return a data provider contains a SAXParser instance. + * @throws Exception If any errors occur. */ @DataProvider(name = "parser-provider") - public Object[][] getParser() throws ParserConfigurationException, SAXException { + public Object[][] getParser() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxparser = spf.newSAXParser(); return new Object[][] { { saxparser } }; } /** - * Testcase to test the default functionality (No validation) of the parser. + * Test to test the default functionality (No validation) of the parser. + * + * @param saxparser a SAXParser instance. */ @Test(dataProvider = "parser-provider") public void testValidate01(SAXParser saxparser) { - try { - assertFalse(saxparser.isValidating()); - } catch (FactoryConfigurationError e) { - failUnexpected(e); - } - + assertFalse(saxparser.isValidating()); } /** - * Testcase to test the functionality of setValidating and isvalidating + * Test to test the functionality of setValidating and isValidating * methods. + * + * @throws Exception If any errors occur. */ @Test - public void testValidate02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setValidating(true); - spf.newSAXParser(); - assertTrue(spf.isValidating()); - } catch (FactoryConfigurationError | ParserConfigurationException | SAXException e) { - failUnexpected(e); - } - + public void testValidate02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setValidating(true); + spf.newSAXParser(); + assertTrue(spf.isValidating()); } /** - * Test case to test isNamespaceAware() method. By default, namespaces are + * Test isNamespaceAware() method. By default, namespaces are * not supported. + * + * @param saxparser a SAXParser instance. */ @Test(dataProvider = "parser-provider") public void testNamespace01(SAXParser saxparser) { - try { - assertFalse(saxparser.isNamespaceAware()); - } catch (FactoryConfigurationError e) { - failUnexpected(e); - } - + assertFalse(saxparser.isNamespaceAware()); } /** * Test case to test setnamespaceAware() method. + * + * @throws Exception If any errors occur. */ @Test - public void testNamespace02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - assertTrue(saxparser.isNamespaceAware()); - } catch (FactoryConfigurationError | ParserConfigurationException | SAXException e) { - failUnexpected(e); - } - + public void testNamespace02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxparser = spf.newSAXParser(); + assertTrue(saxparser.isNamespaceAware()); } /** * Test case to test if the getParser() method returns instance of Parser. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testParser01(SAXParser saxparser) { - try { - Parser parser = saxparser.getParser(); - } catch (FactoryConfigurationError | SAXException e) { - failUnexpected(e); - } - + public void testParser01(SAXParser saxparser) throws SAXException { + assertNotNull(saxparser.getParser()); } /** * Test case to test if the getXMLReader() method returns instance of * XMLReader. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testXmlReader01(SAXParser saxparser) { - try { - XMLReader xmlReader = saxparser.getXMLReader(); - } catch (FactoryConfigurationError | SAXException e) { - failUnexpected(e); - } + public void testXmlReader01(SAXParser saxparser) throws SAXException { + assertNotNull(saxparser.getXMLReader()); } /** * Test whether the xml-string property is not supported. * - * @throws SAXNotSupportedException + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ - @Test(expectedExceptions = SAXNotSupportedException.class, dataProvider = "parser-provider") - public void testProperty01(SAXParser saxparser) throws SAXNotSupportedException { - try { - Object object = saxparser.getProperty(XML_STRING); - } catch (SAXNotRecognizedException e) { - failUnexpected(e); - } + @Test(expectedExceptions = SAXNotSupportedException.class, + dataProvider = "parser-provider") + public void testProperty01(SAXParser saxparser) throws SAXException { + saxparser.getProperty(XML_STRING); } /** * Test whether the dom-node property is not supported. * - * @throws SAXNotSupportedException + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ - @Test(expectedExceptions = SAXNotSupportedException.class, dataProvider = "parser-provider") - public void testProperty02(SAXParser saxparser) throws SAXNotSupportedException { - try { - Object object = saxparser.getProperty(DOM_NODE); - } catch (SAXNotRecognizedException e) { - failUnexpected(e); - } + @Test(expectedExceptions = SAXNotSupportedException.class, + dataProvider = "parser-provider") + public void testProperty02(SAXParser saxparser) throws SAXException { + saxparser.getProperty(DOM_NODE); } /** * Test the default lexical-handler not exists. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty03(SAXParser saxparser) { - try { - assertNull(saxparser.getProperty(LEXICAL_HANDLER)); - } catch (SAXException e) { - failUnexpected(e); - } - + public void testProperty03(SAXParser saxparser) throws SAXException { + assertNull(saxparser.getProperty(LEXICAL_HANDLER)); } /** * Test the default declaration-handler not exists. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty04(SAXParser saxparser) { - - try { - assertNull(saxparser.getProperty(DECL_HANDLER)); - } catch (SAXException e) { - failUnexpected(e); - } + public void testProperty04(SAXParser saxparser) throws SAXException { + assertNull(saxparser.getProperty(DECL_HANDLER)); } /** * Test to set and get the lexical-handler. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty05(SAXParser saxparser) { - try { - MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); - saxparser.setProperty(LEXICAL_HANDLER, myLexicalHandler); - Object object = saxparser.getProperty(LEXICAL_HANDLER); - assertTrue(object instanceof LexicalHandler); - } catch (SAXException e) { - failUnexpected(e); - } + public void testProperty05(SAXParser saxparser) throws SAXException { + MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); + saxparser.setProperty(LEXICAL_HANDLER, myLexicalHandler); + assertTrue(saxparser.getProperty(LEXICAL_HANDLER) instanceof LexicalHandler); } /** * Test to set and get the declaration-handler. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty06(SAXParser saxparser) { - try { - MyDeclHandler myDeclHandler = new MyDeclHandler(); - saxparser.setProperty(DECL_HANDLER, myDeclHandler); - Object object = saxparser.getProperty(DECL_HANDLER); - assertTrue(object instanceof DeclHandler); - } catch (SAXException e) { - failUnexpected(e); - } - + public void testProperty06(SAXParser saxparser) throws SAXException { + MyDeclHandler myDeclHandler = new MyDeclHandler(); + saxparser.setProperty(DECL_HANDLER, myDeclHandler); + assertTrue(saxparser.getProperty(DECL_HANDLER) instanceof DeclHandler); } /** - * Customized LexicalHandler used for test. + * Customized LexicalHandler used for test. An empty implementation for + * LexicalHandler. */ private class MyLexicalHandler implements LexicalHandler { + @Override public void comment(char[] ch, int start, int length) { } + @Override public void endCDATA() { } + @Override public void endDTD() { } + @Override public void endEntity(String name) { } + @Override public void startCDATA() { } + @Override public void startDTD(String name, String publicId, String systemId) { } + @Override public void startEntity(String name) { } } /** - * Customized DeclHandler used for test. + * Customized DeclHandler used for test. An empty implementation for + * DeclHandler. */ private class MyDeclHandler implements DeclHandler { + @Override public void attributeDecl(String eName, String aName, String type, String valueDefault, String value) { } + @Override public void elementDecl(String name, String model) { } + @Override public void externalEntityDecl(String name, String publicId, String systemId) { } + @Override public void internalEntityDecl(String name, String value) { } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest03.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest03.java index efe12c595d6..636b1e29a90 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest03.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest03.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -23,17 +23,17 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; - import java.io.File; -import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; +import java.io.FilePermission; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import jaxp.library.JAXPFileReadOnlyBaseTest; +import static org.testng.Assert.fail; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.xml.sax.SAXException; @@ -41,68 +41,70 @@ import org.xml.sax.SAXException; /** * Class contains the test cases for SAXParser API */ -public class SAXParserTest03 { +public class SAXParserTest03 extends JAXPFileReadOnlyBaseTest { /** * Provide SAXParserFactory. * - * @throws Exception + * @return a dimensional contains. */ @DataProvider(name = "input-provider") public Object[][] getFactory() { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(true); - MyErrorHandler handler = MyErrorHandler.newInstance(); - return new Object[][] { { spf, handler } }; + return new Object[][] { { spf, MyErrorHandler.newInstance() } }; } /** * parsertest.xml holds a valid document. This method tests the validating * parser. + * + * @param spf a Parser factory. + * @param handler an error handler for capturing events. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "input-provider") - public void testParseValidate01(SAXParserFactory spf, MyErrorHandler handler) { - try { - SAXParser saxparser = spf.newSAXParser(); - saxparser.parse(new File(TestUtils.XML_DIR, "parsertest.xml"), handler); - assertFalse(handler.errorOccured); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "input-provider") + public void testParseValidate01(SAXParserFactory spf, MyErrorHandler handler) + throws Exception { + spf.newSAXParser().parse(new File(XML_DIR, "parsertest.xml"), handler); + assertFalse(handler.isErrorOccured()); } /** * validns.xml holds a valid document with XML namespaces in it. This method * tests the Validating parser with namespace processing on. + * + * @param spf a Parser factory. + * @param handler an error handler for capturing events. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "input-provider") - public void testParseValidate02(SAXParserFactory spf, MyErrorHandler handler) { - try { + @Test(groups = {"readLocalFiles"}, dataProvider = "input-provider") + public void testParseValidate02(SAXParserFactory spf, MyErrorHandler handler) + throws Exception { spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - saxparser.parse(new File(TestUtils.XML_DIR, "validns.xml"), handler); - assertFalse(handler.errorOccured); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + spf.newSAXParser().parse(new File(XML_DIR, "validns.xml"), handler); + assertFalse(handler.isErrorOccured()); } /** * invalidns.xml holds an invalid document with XML namespaces in it. This * method tests the validating parser with namespace processing on. It * should throw validation error. + * + * @param spf a Parser factory. + * @param handler an error handler for capturing events. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "input-provider") - public void testParseValidate03(SAXParserFactory spf, MyErrorHandler handler) { + @Test(groups = {"readLocalFiles"}, dataProvider = "input-provider") + public void testParseValidate03(SAXParserFactory spf, MyErrorHandler handler) + throws Exception { try { spf.setNamespaceAware(true); SAXParser saxparser = spf.newSAXParser(); - saxparser.parse(new File(TestUtils.XML_DIR, "invalidns.xml"), handler); - failUnexpected(new RuntimeException()); - } catch (ParserConfigurationException | SAXException | IOException e) { - if (e instanceof SAXException) { - assertTrue(handler.errorOccured); - } + saxparser.parse(new File(XML_DIR, "invalidns.xml"), handler); + fail("Expecting SAXException here"); + } catch (SAXException e) { + assertTrue(handler.isErrorOccured()); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest01.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest.java similarity index 63% rename from jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest01.java rename to jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest.java index 504ee8626c4..42069ea2785 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest01.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,21 +26,16 @@ package javax.xml.transform.ptests; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.w3c.dom.Attr; @@ -48,7 +43,6 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; @@ -56,48 +50,36 @@ import org.xml.sax.helpers.XMLReaderFactory; * DOM parse on test file to be compared with golden output file. No Exception * is expected. */ -public class DOMResultTest01 { +public class DOMResultTest extends JAXPFileBaseTest { /** * Unit test for simple DOM parsing. + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String resultFile = CLASS_DIR + "domresult01.out"; + public void testcase01() throws Exception { + String resultFile = USER_DIR + "domresult01.out"; String goldFile = GOLDEN_DIR + "domresult01GF.out"; String xsltFile = XML_DIR + "cities.xsl"; String xmlFile = XML_DIR + "cities.xml"; - try { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - SAXSource saxSource = new SAXSource(new InputSource(xsltFile)); - TransformerHandler handler - = saxTFactory.newTransformerHandler(saxSource); + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + SAXSource saxSource = new SAXSource(new InputSource(xsltFile)); + TransformerHandler handler + = saxTFactory.newTransformerHandler(saxSource); - DOMResult result = new DOMResult(); + DOMResult result = new DOMResult(); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(xmlFile); - Node node = result.getNode(); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writeNodes(node, writer); - } - assertTrue(compareWithGold(goldFile, resultFile)); - } catch (SAXException | TransformerConfigurationException - | IllegalArgumentException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if(Files.exists(resultPath)) - Files.delete(resultPath); - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + Node node = result.getNode(); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writeNodes(node, writer); } + assertTrue(compareWithGold(goldFile, resultFile)); } /** diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/ErrorListenerTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/ErrorListenerTest.java index 9867ab44c56..19417830ac6 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/ErrorListenerTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/ErrorListenerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,12 +24,14 @@ package javax.xml.transform.ptests; import java.io.File; +import java.io.FilePermission; import javax.xml.transform.ErrorListener; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import org.testng.annotations.Test; @@ -37,7 +39,7 @@ import org.testng.annotations.Test; /** * Class containing the test cases for ErrorListener interface */ -public class ErrorListenerTest implements ErrorListener { +public class ErrorListenerTest extends JAXPBaseTest implements ErrorListener { /** * Define ErrorListener's status. */ @@ -58,9 +60,10 @@ public class ErrorListenerTest implements ErrorListener { try { TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setErrorListener (listener); + setPermissions(new FilePermission(XML_DIR + "invalid.xsl", "read")); tfactory.newTransformer(new StreamSource( new File(XML_DIR + "invalid.xsl"))); - fail("We expect an Exception here"); + fail("Expect TransformerConfigurationException here"); } catch (TransformerConfigurationException ex) { assertEquals(listener.status, ListenerStatus.FATAL); } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXSourceTest01.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXSourceTest.java similarity index 65% rename from jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXSourceTest01.java rename to jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXSourceTest.java index abb558f32f9..ca4c67ed21b 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXSourceTest01.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,80 +25,73 @@ package javax.xml.transform.ptests; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.dom.DOMSource; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Unit test for SAXSource sourceToInputSource API. */ -public class SAXSourceTest01 { +public class SAXSourceTest extends JAXPFileReadOnlyBaseTest { /** - * Test file name + * Test style-sheet file name */ private final String TEST_FILE = XML_DIR + "cities.xsl"; /** * Test obtaining a SAX InputSource object from a Source object. + * + * @throws IOException reading file error. */ - @Test - public void source2inputsource01() { - try { - StreamSource streamSource = new StreamSource ( - new FileInputStream (TEST_FILE)); + @Test(groups = {"readLocalFiles"}) + public void source2inputsource01() throws IOException { + try (FileInputStream fis = new FileInputStream(TEST_FILE)) { + StreamSource streamSource = new StreamSource(fis); assertNotNull(SAXSource.sourceToInputSource(streamSource)); - } catch (FileNotFoundException ex) { - failUnexpected(ex); } } /** * This test case tries to get InputSource from DOMSource using * sourceToInputSource method. It is not possible and hence null is - * expected. This is a negative test case + * expected. This is a negative test case, + * + * @throws Exception If any errors occur. */ - @Test - public void source2inputsource02() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.newDocumentBuilder().parse(new File(TEST_FILE)); - assertNull(SAXSource.sourceToInputSource(new DOMSource(null))); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } - + @Test(groups = {"readLocalFiles"}) + public void source2inputsource02() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.newDocumentBuilder().parse(new File(TEST_FILE)); + assertNull(SAXSource.sourceToInputSource(new DOMSource(null))); } /** * This test case tries to get InputSource from SAXSource using * sourceToInputSource method. This will also check if the systemId * remained the same. This is a positive test case. + * + * @throws IOException reading file error. */ - @Test - public void source2inputsource03() { + @Test(groups = {"readLocalFiles"}) + public void source2inputsource03() throws IOException { String SYSTEM_ID = "file:///" + XML_DIR; - try { + try (FileInputStream fis = new FileInputStream(TEST_FILE)) { SAXSource saxSource = - new SAXSource(new InputSource(new FileInputStream(TEST_FILE))); + new SAXSource(new InputSource(fis)); saxSource.setSystemId(SYSTEM_ID); assertEquals(SAXSource.sourceToInputSource(saxSource).getSystemId(), SYSTEM_ID); - } catch (FileNotFoundException ex) { - failUnexpected(ex); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest.java new file mode 100644 index 00000000000..60da93acc73 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest.java @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2003, 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. + */ + +package javax.xml.transform.ptests; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; +import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TemplatesHandler; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.XMLFilter; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * Test newTransformerhandler() method which takes StreamSource as argument can + * be set to XMLReader. + */ +public class SAXTFactoryTest extends JAXPFileBaseTest { + /** + * Test style-sheet file. + */ + private static final String XSLT_FILE = XML_DIR + "cities.xsl"; + + /** + * Test style-sheet file. + */ + private static final String XSLT_INCL_FILE = XML_DIR + "citiesinclude.xsl"; + + /** + * Test XML file. + */ + private static final String XML_FILE = XML_DIR + "cities.xml"; + + /** + * SAXTFactory.newTransformerhandler() method which takes SAXSource as + * argument can be set to XMLReader. SAXSource has input XML file as its + * input source. XMLReader has a transformer handler which write out the + * result to output file. Test verifies output file is same as golden file. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase01() throws Exception { + String outputFile = USER_DIR + "saxtf001.out"; + String goldFile = GOLDEN_DIR + "saxtf001GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE)); + Result result = new StreamResult(fos); + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * SAXTFactory.newTransformerhandler() method which takes SAXSource as + * argument can be set to XMLReader. SAXSource has input XML file as its + * input source. XMLReader has a content handler which write out the result + * to output file. Test verifies output file is same as golden file. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase02() throws Exception { + String outputFile = USER_DIR + "saxtf002.out"; + String goldFile = GOLDEN_DIR + "saxtf002GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile); + FileInputStream fis = new FileInputStream(XSLT_FILE)) { + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + SAXSource ss = new SAXSource(); + ss.setInputSource(new InputSource(fis)); + + TransformerHandler handler = saxTFactory.newTransformerHandler(ss); + Result result = new StreamResult(fos); + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is + * namespace awareness, DocumentBuilder parse xslt file as DOMSource. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase03() throws Exception { + String outputFile = USER_DIR + "saxtf003.out"; + String goldFile = GOLDEN_DIR + "saxtf003GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(new File(XSLT_FILE)); + Node node = (Node)document; + DOMSource domSource= new DOMSource(node); + + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + TransformerHandler handler = + saxTFactory.newTransformerHandler(domSource); + Result result = new StreamResult(fos); + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Negative test for newTransformerHandler when relative URI is in XML file. + * + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = TransformerConfigurationException.class) + public void transformerHandlerTest04() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(new File(XSLT_INCL_FILE)); + DOMSource domSource= new DOMSource(document); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + saxTFactory.newTransformerHandler(domSource); + } + + /** + * Unit test for XMLReader parsing when relative URI is used in xsl file and + * SystemId was set. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase05() throws Exception { + String outputFile = USER_DIR + "saxtf005.out"; + String goldFile = GOLDEN_DIR + "saxtf005GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(new File(XSLT_INCL_FILE)); + Node node = (Node)document; + DOMSource domSource= new DOMSource(node); + + domSource.setSystemId("file:///" + XML_DIR); + + TransformerHandler handler = + saxTFactory.newTransformerHandler(domSource); + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Unit test newTransformerHandler with a DOMSource. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase06() throws Exception { + String outputFile = USER_DIR + "saxtf006.out"; + String goldFile = GOLDEN_DIR + "saxtf006GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Node node = (Node)docBuilder.parse(new File(XSLT_INCL_FILE)); + + DOMSource domSource = new DOMSource(node, "file:///" + XML_DIR); + TransformerHandler handler = + saxTFactory.newTransformerHandler(domSource); + + Result result = new StreamResult(fos); + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Test newTransformerHandler with a Template Handler. + * + * @throws Exception If any errors occur. + */ + public void testcase08() throws Exception { + String outputFile = USER_DIR + "saxtf008.out"; + String goldFile = GOLDEN_DIR + "saxtf008GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + + TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); + reader.setContentHandler(thandler); + reader.parse(XSLT_FILE); + TransformerHandler tfhandler + = saxTFactory.newTransformerHandler(thandler.getTemplates()); + + Result result = new StreamResult(fos); + tfhandler.setResult(result); + + reader.setContentHandler(tfhandler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Test newTransformerHandler with a Template Handler along with a relative + * URI in the style-sheet file. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase09() throws Exception { + String outputFile = USER_DIR + "saxtf009.out"; + String goldFile = GOLDEN_DIR + "saxtf009GF.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + + TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); + thandler.setSystemId("file:///" + XML_DIR); + reader.setContentHandler(thandler); + reader.parse(XSLT_INCL_FILE); + TransformerHandler tfhandler= + saxTFactory.newTransformerHandler(thandler.getTemplates()); + Result result = new StreamResult(fos); + tfhandler.setResult(result); + reader.setContentHandler(tfhandler); + reader.parse(XML_FILE); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Unit test for contentHandler setter/getter along reader as handler's + * parent. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase10() throws Exception { + String outputFile = USER_DIR + "saxtf010.out"; + String goldFile = GOLDEN_DIR + "saxtf010GF.out"; + // The transformer will use a SAX parser as it's reader. + XMLReader reader = XMLReaderFactory.createXMLReader(); + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + XMLFilter filter = + saxTFactory.newXMLFilter(new StreamSource(XSLT_FILE)); + filter.setParent(reader); + filter.setContentHandler(new MyContentHandler(outputFile)); + + // Now, when you call transformer.parse, it will set itself as + // the content handler for the parser object (it's "parent"), and + // will then call the parse method on the parser. + filter.parse(new InputSource(XML_FILE)); + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Unit test for contentHandler setter/getter with parent. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase11() throws Exception { + String outputFile = USER_DIR + "saxtf011.out"; + String goldFile = GOLDEN_DIR + "saxtf011GF.out"; + // The transformer will use a SAX parser as it's reader. + XMLReader reader = XMLReaderFactory.createXMLReader(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(new File(XSLT_FILE)); + Node node = (Node)document; + DOMSource domSource= new DOMSource(node); + + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory)TransformerFactory.newInstance(); + XMLFilter filter = saxTFactory.newXMLFilter(domSource); + + filter.setParent(reader); + filter.setContentHandler(new MyContentHandler(outputFile)); + + // Now, when you call transformer.parse, it will set itself as + // the content handler for the parser object (it's "parent"), and + // will then call the parse method on the parser. + filter.parse(new InputSource(XML_FILE)); + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Unit test for contentHandler setter/getter. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase12() throws Exception { + String outputFile = USER_DIR + "saxtf012.out"; + String goldFile = GOLDEN_DIR + "saxtf012GF.out"; + // The transformer will use a SAX parser as it's reader. + XMLReader reader = XMLReaderFactory.createXMLReader(); + + InputSource is = new InputSource(new FileInputStream(XSLT_FILE)); + SAXSource saxSource = new SAXSource(); + saxSource.setInputSource(is); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); + XMLFilter filter = saxTFactory.newXMLFilter(saxSource); + + filter.setParent(reader); + filter.setContentHandler(new MyContentHandler(outputFile)); + + // Now, when you call transformer.parse, it will set itself as + // the content handler for the parser object (it's "parent"), and + // will then call the parse method on the parser. + filter.parse(new InputSource(XML_FILE)); + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Unit test for TemplatesHandler setter/getter. + * + * @throws Exception If any errors occur. + */ + @Test + public void testcase13() throws Exception { + String outputFile = USER_DIR + "saxtf013.out"; + String goldFile = GOLDEN_DIR + "saxtf013GF.out"; + try(FileInputStream fis = new FileInputStream(XML_FILE)) { + // The transformer will use a SAX parser as it's reader. + XMLReader reader = XMLReaderFactory.createXMLReader(); + + SAXTransformerFactory saxTFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); + // I have put this as it was complaining about systemid + thandler.setSystemId("file:///" + USER_DIR); + + reader.setContentHandler(thandler); + reader.parse(XSLT_FILE); + XMLFilter filter + = saxTFactory.newXMLFilter(thandler.getTemplates()); + filter.setParent(reader); + + filter.setContentHandler(new MyContentHandler(outputFile)); + filter.parse(new InputSource(fis)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest001.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest001.java deleted file mode 100644 index 112b1996fbf..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest001.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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. - */ - -package javax.xml.transform.ptests; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerhandler() method which takes StreamSource as argument can - * be set to XMLReader. - */ -public class SAXTFactoryTest001 { - /** - * SAXTFactory.newTransformerhandler() method which takes SAXSource as - * argument can be set to XMLReader. SAXSource has input XML file as its - * input source. XMLReader has a transformer handler which write out the - * result to output file. Test verifies output file is same as golden file. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf001.out"; - String goldFile = GOLDEN_DIR + "saxtf001GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - TransformerHandler handler = saxTFactory.newTransformerHandler( - new StreamSource(xsltFile)); - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | TransformerConfigurationException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest002.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest002.java deleted file mode 100644 index 775edb7d0b9..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest002.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerhandler() method which takes SAXSource as argument can - * be set to XMLReader. - */ -public class SAXTFactoryTest002 { - /** - * SAXTFactory.newTransformerhandler() method which takes SAXSource as - * argument can be set to XMLReader. SAXSource has input XML file as its - * input source. XMLReader has a content handler which write out the result - * to output file. Test verifies output file is same as golden file. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf002.out"; - String goldFile = GOLDEN_DIR + "saxtf002GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile); - FileInputStream fis = new FileInputStream(xsltFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - SAXSource ss = new SAXSource(); - ss.setInputSource(new InputSource(fis)); - - TransformerHandler handler = saxTFactory.newTransformerHandler(ss); - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest003.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest003.java deleted file mode 100644 index b7bc37bd403..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest003.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerhandler() method which takes DOMSource as argument can - * be set to XMLReader. - */ -public class SAXTFactoryTest003 { - /** - * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is - * namespace awareness, DocumentBuilder parse xslt file as DOMSource. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf003.out"; - String goldFile = GOLDEN_DIR + "saxtf003GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(xsltFile)); - Node node = (Node)document; - DOMSource domSource= new DOMSource(node); - - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - TransformerHandler handler = - saxTFactory.newTransformerHandler(domSource); - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (TransformerConfigurationException | ParserConfigurationException - | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest004.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest004.java deleted file mode 100644 index 419cae137d8..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest004.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.File; -import java.io.IOException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; - -/* - * TransformerConfigurationException expected when there is relative URI is used - * in citiesinclude.xsl file - */ -public class SAXTFactoryTest004 { - /** - * Negative test for newTransformerHandler when relative URI is in XML file. - * @throws TransformerConfigurationException If for some reason the - * TransformerHandler can not be created. - */ - @Test(expectedExceptions = TransformerConfigurationException.class) - public void transformerHandlerTest01() throws TransformerConfigurationException { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(XML_DIR + "citiesinclude.xsl")); - DOMSource domSource= new DOMSource(document); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - saxTFactory.newTransformerHandler(domSource); - } catch (ParserConfigurationException | IOException | SAXException ex) { - failUnexpected(ex); - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest005.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest005.java deleted file mode 100644 index 51691500543..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest005.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test SAXSource API when relative URI is used in xsl file and SystemId was set - */ -public class SAXTFactoryTest005 { - /** - * Unit test for XMLReader parsing when relative URI is used in xsl file and - * SystemId was set. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf005.out"; - String goldFile = GOLDEN_DIR + "saxtf005GF.out"; - String xsltFile = XML_DIR + "citiesinclude.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(xsltFile)); - Node node = (Node)document; - DOMSource domSource= new DOMSource(node); - - domSource.setSystemId("file:///" + XML_DIR); - - TransformerHandler handler = - saxTFactory.newTransformerHandler(domSource); - Result result = new StreamResult(fos); - - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (TransformerConfigurationException | ParserConfigurationException - | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest006.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest006.java deleted file mode 100644 index 9dd330cb125..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest006.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerHandler with a DOMSource and StreamResult set. - */ -public class SAXTFactoryTest006 extends TransformerTestConst{ - /** - * Unit test newTransformerHandler with a DOMSource. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf006.out"; - String goldFile = GOLDEN_DIR + "saxtf006GF.out"; - String xsltFile = XML_DIR + "citiesinclude.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Node node = (Node)docBuilder.parse(new File(xsltFile)); - - DOMSource domSource = new DOMSource(node, "file:///" + XML_DIR); - TransformerHandler handler = - saxTFactory.newTransformerHandler(domSource); - - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (TransformerConfigurationException | ParserConfigurationException - | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest008.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest008.java deleted file mode 100644 index d4353c0bc0d..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest008.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerHandler with a Template Handler. - */ -public class SAXTFactoryTest008 { - /** - * Test newTransformerHandler with a Template Handler. - */ - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf008.out"; - String goldFile = GOLDEN_DIR + "saxtf008GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - - TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); - reader.setContentHandler(thandler); - reader.parse(xsltFile); - TransformerHandler tfhandler - = saxTFactory.newTransformerHandler(thandler.getTemplates()); - - Result result = new StreamResult(fos); - tfhandler.setResult(result); - - reader.setContentHandler(tfhandler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } - -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest009.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest009.java deleted file mode 100644 index 4930928a3aa..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest009.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerHandler with a Template Handler along with a relative URI - * in the xslt file. - */ -public class SAXTFactoryTest009 { - /** - * Test newTransformerHandler with a Template Handler along with a relative - * URI in the xslt file. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf009.out"; - String goldFile = GOLDEN_DIR + "saxtf009GF.out"; - String xsltFile = XML_DIR + "citiesinclude.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - - TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); - thandler.setSystemId("file:///" + XML_DIR); - reader.setContentHandler(thandler); - reader.parse(xsltFile); - TransformerHandler tfhandler= - saxTFactory.newTransformerHandler(thandler.getTemplates()); - Result result = new StreamResult(fos); - tfhandler.setResult(result); - reader.setContentHandler(tfhandler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest010.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest010.java deleted file mode 100644 index e2aaa39ec0f..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest010.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with customized ContentHandler. - */ -public class SAXTFactoryTest010 { - /** - * Unit test for contentHandler setter/getter along reader as handler's - * parent. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf010.out"; - String goldFile = GOLDEN_DIR + "saxtf010GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - XMLFilter filter = - saxTFactory.newXMLFilter(new StreamSource(xsltFile)); - - filter.setParent(reader); - filter.setContentHandler(new MyContentHandler(outputFile)); - - // Now, when you call transformer.parse, it will set itself as - // the content handler for the parser object (it's "parent"), and - // will then call the parse method on the parser. - filter.parse(new InputSource(xmlFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest011.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest011.java deleted file mode 100644 index 8676995f703..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest011.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with customized ContentHandler by - * using SAX parser as it's reader. - */ -public class SAXTFactoryTest011 { - /** - * Unit test for contentHandler setter/getter with parent. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf011.out"; - String goldFile = GOLDEN_DIR + "saxtf011GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(xsltFile)); - Node node = (Node)document; - DOMSource domSource= new DOMSource(node); - - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - XMLFilter filter = saxTFactory.newXMLFilter(domSource); - - filter.setParent(reader); - filter.setContentHandler(new MyContentHandler(outputFile)); - - // Now, when you call transformer.parse, it will set itself as - // the content handler for the parser object (it's "parent"), and - // will then call the parse method on the parser. - filter.parse(new InputSource(xmlFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException - | ParserConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest012.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest012.java deleted file mode 100644 index 42ca180cd99..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest012.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with customized ContentHandler by - * using SAX parser as it's reader. - */ -public class SAXTFactoryTest012 { - /** - * Unit test for contentHandler setter/getter. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf012.out"; - String goldFile = GOLDEN_DIR + "saxtf012GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - - InputSource is = new InputSource(new FileInputStream(xsltFile)); - SAXSource saxSource = new SAXSource(); - saxSource.setInputSource(is); - - SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); - XMLFilter filter = saxTFactory.newXMLFilter(saxSource); - - filter.setParent(reader); - filter.setContentHandler(new MyContentHandler(outputFile)); - - // Now, when you call transformer.parse, it will set itself as - // the content handler for the parser object (it's "parent"), and - // will then call the parse method on the parser. - filter.parse(new InputSource(xmlFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest013.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest013.java deleted file mode 100644 index 9c4bddd8801..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest013.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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. - */ -package javax.xml.transform.ptests; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with TemplatesHandler. - */ -public class SAXTFactoryTest013 { - /** - * Unit test for TemplatesHandler setter/getter. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf013.out"; - String goldFile = GOLDEN_DIR + "saxtf013GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); - // I have put this as it was complaining about systemid - thandler.setSystemId("file:///" + CLASS_DIR); - - reader.setContentHandler(thandler); - reader.parse(xsltFile); - XMLFilter filter - = saxTFactory.newXMLFilter(thandler.getTemplates()); - filter.setParent(reader); - - filter.setContentHandler( - new MyContentHandler(outputFile)); - filter.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest01.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest.java similarity index 92% rename from jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest01.java rename to jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest.java index f5166978203..9ff71b900ae 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest01.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -34,10 +34,11 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.failUnexpected; import org.testng.annotations.Test; import org.w3c.dom.Document; @@ -47,7 +48,7 @@ import org.xml.sax.SAXException; * Test a StreamResult using a file name that contains URL characters that need * to be encoded. */ -public class StreamResultTest01 { +public class StreamResultTest extends JAXPFileBaseTest { /** * Unit test for StreamResult. */ @@ -82,7 +83,7 @@ public class StreamResultTest01 { DOMSource domSource = new DOMSource(document); StreamSource streamSource = new StreamSource(new FileInputStream(xmlFile)); - File streamResultFile = new File(CLASS_DIR + file); + File streamResultFile = new File(USER_DIR + file); StreamResult streamResult = new StreamResult(streamResultFile); Transformer transformer = TransformerFactory.newInstance().newTransformer(domSource); diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TfClearParamTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TfClearParamTest.java index 74219b25f01..02384973de7 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TfClearParamTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TfClearParamTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,11 +24,8 @@ package javax.xml.transform.ptests; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; @@ -36,21 +33,20 @@ import javax.xml.transform.dom.DOMSource; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Class containing the test cases for SAXParserFactory API */ -public class TfClearParamTest { +public class TfClearParamTest extends JAXPFileReadOnlyBaseTest { /** - * Test xslt file. + * Test style-sheet file name. */ private final String XSL_FILE = XML_DIR + "cities.xsl"; @@ -72,193 +68,164 @@ public class TfClearParamTest { /** * Obtains transformer's parameter with the same name that set before. Value * should be same as set one. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ @Test - public void clear01() { - try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME).toString(), PARAM_VALUE); - } catch (TransformerConfigurationException ex) { - failUnexpected(ex); - } - + public void clear01() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME).toString(), PARAM_VALUE); } /** * Obtains transformer's parameter with the a name that wasn't set before. * Null is expected. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ @Test - public void clear02() { - try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter whose initiated with a stream source with - * the a name that set before. Value should be same as set one. - */ - @Test - public void clear03() { - try { - Transformer transformer = TransformerFactory.newInstance(). - newTransformer(new StreamSource(new File(XSL_FILE))); - - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter whose initiated with a stream source with - * the a name that wasn't set before. Null is expected. - */ - @Test - public void clear04() { - try { - Transformer transformer = TransformerFactory.newInstance(). - newTransformer(new StreamSource(new File(XSL_FILE))); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } - - } - - /** - * Obtains transformer's parameter whose initiated with a sax source with - * the a name that set before. Value should be same as set one. - */ - @Test - public void clear05() { - try { - InputSource is = new InputSource(new FileInputStream(XSL_FILE)); - SAXSource saxSource = new SAXSource(); - saxSource.setInputSource(is); - - Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); - - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter whose initiated with a sax source with - * the a name that wasn't set before. Null is expected. - */ - @Test - public void clear06() { - try { - InputSource is = new InputSource(new FileInputStream(XSL_FILE)); - SAXSource saxSource = new SAXSource(); - saxSource.setInputSource(is); - - Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); - - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter whose initiated with a dom source with - * the a name that set before. Value should be same as set one. - */ - @Test - public void clear07() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(XSL_FILE)); - DOMSource domSource = new DOMSource((Node)document); - - Transformer transformer = tfactory.newTransformer(domSource); - - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); - } catch (IOException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter whose initiated with a dom source with - * the a name that wasn't set before. Null is expected. - */ - @Test - public void clear08() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(XSL_FILE)); - DOMSource domSource = new DOMSource((Node)document); - - Transformer transformer = tfactory.newTransformer(domSource); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (IOException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } + public void clear02() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); } /** * Obtains transformer's parameter with a short name that set before. Value * should be same as set one. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ @Test - public void clear09() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - Transformer transformer = tfactory.newTransformer(); + public void clear03() throws TransformerConfigurationException { + TransformerFactory tfactory = TransformerFactory.newInstance(); + Transformer transformer = tfactory.newTransformer(); - transformer.setParameter(SHORT_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(SHORT_PARAM_NAME).toString(), PARAM_VALUE); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } + transformer.setParameter(SHORT_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(SHORT_PARAM_NAME).toString(), PARAM_VALUE); } /** * Obtains transformer's parameter with a short name that set with an integer * object before. Value should be same as the set integer object. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ @Test - public void clear10() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - Transformer transformer = tfactory.newTransformer(); + public void clear04() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); - int intObject = 5; - transformer.setParameter(SHORT_PARAM_NAME, intObject); - assertEquals(transformer.getParameter(SHORT_PARAM_NAME), intObject); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); + int intObject = 5; + transformer.setParameter(SHORT_PARAM_NAME, intObject); + assertEquals(transformer.getParameter(SHORT_PARAM_NAME), intObject); + } + + /** + * Obtains transformer's parameter whose initiated with a stream source with + * the a name that set before. Value should be same as set one. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. + */ + @Test (groups = {"readLocalFiles"}) + public void clear05() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance(). + newTransformer(new StreamSource(new File(XSL_FILE))); + + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); + } + + /** + * Obtains transformer's parameter whose initiated with a stream source with + * the a name that wasn't set before. Null is expected. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. + */ + @Test (groups = {"readLocalFiles"}) + public void clear06() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance(). + newTransformer(new StreamSource(new File(XSL_FILE))); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); + } + + /** + * Obtains transformer's parameter whose initiated with a sax source with + * the a name that set before. Value should be same as set one. + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void clear07() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_FILE)) { + SAXSource saxSource = new SAXSource(); + saxSource.setInputSource(new InputSource(fis)); + + Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); } } + + /** + * Obtains transformer's parameter whose initiated with a sax source with + * the a name that wasn't set before. Null is expected. + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void clear08() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_FILE)) { + SAXSource saxSource = new SAXSource(); + saxSource.setInputSource(new InputSource(fis)); + + Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); + } + } + + /** + * Obtains transformer's parameter whose initiated with a dom source with + * the a name that set before. Value should be same as set one. + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void clear09() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(XSL_FILE)); + DOMSource domSource = new DOMSource((Node)document); + + Transformer transformer = tfactory.newTransformer(domSource); + + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); + } + + /** + * Obtains transformer's parameter whose initiated with a dom source with + * the a name that wasn't set before. Null is expected. + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void clear10() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(XSL_FILE)); + DOMSource domSource = new DOMSource((Node)document); + + Transformer transformer = tfactory.newTransformer(domSource); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); + } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerExcpTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerExcpTest.java index 866c1c0597d..1a936cbaa4b 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerExcpTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerExcpTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,12 +23,14 @@ package javax.xml.transform.ptests; import java.io.File; +import java.io.FilePermission; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @@ -38,13 +40,14 @@ import org.testng.annotations.Test; /** * Basic test for TransformerException specification. */ -public class TransformerExcpTest { +public class TransformerExcpTest extends JAXPBaseTest { /** - * Transform an unformatted xslt file. TransformerException is thrown. + * Transform an unformatted style-sheet file. TransformerException is thrown. */ @Test public void tfexception() { try { + setPermissions(new FilePermission(XML_DIR + "-", "read")); // invalid.xsl has well-formedness error. Therefore transform throws // TransformerException StreamSource streamSource @@ -60,6 +63,8 @@ public class TransformerExcpTest { assertNotNull(e.getException()); assertNull(e.getLocationAsString()); assertEquals(e.getMessageAndLocation(),e.getMessage()); + } finally { + setPermissions(); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerFactoryTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerFactoryTest.java index 45099ebb19c..04c255aceb9 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerFactoryTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,39 +24,35 @@ package javax.xml.transform.ptests; import java.io.*; import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.*; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.w3c.dom.*; -import org.xml.sax.SAXException; /** * Class containing the test cases for TransformerFactory API's * getAssociatedStyleSheet method. */ -public class TransformerFactoryTest { +public class TransformerFactoryTest extends JAXPFileBaseTest { /** * This test case checks for the getAssociatedStylesheet method * of TransformerFactory. * The style sheet returned is then copied to an tfactory01.out - * It will then be verified to see if it matches the golden files + * It will then be verified to see if it matches the golden files. + * + * @throws Exception If any errors occur. */ @Test - public void tfactory01() { - String outputFile = CLASS_DIR + "tfactory01.out"; + public void tfactory01() throws Exception { + String outputFile = USER_DIR + "tfactory01.out"; String goldFile = GOLDEN_DIR + "tfactory01GF.out"; String xmlFile = XML_DIR + "TransformerFactoryTest.xml"; String xmlURI = "file:///" + XML_DIR; @@ -76,10 +72,7 @@ public class TransformerFactoryTest { "Modern", null); Transformer t = tFactory.newTransformer(); t.transform(s, streamResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | ParserConfigurationException - | TransformerException | SAXException ex) { - failUnexpected(ex); } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest.java index f138c7d157a..8e718b082d3 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,12 +24,9 @@ package javax.xml.transform.ptests; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.ErrorListener; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; @@ -39,150 +36,132 @@ import javax.xml.transform.dom.DOMSource; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Basic test cases for Transformer API */ -public class TransformerTest { +public class TransformerTest extends JAXPFileReadOnlyBaseTest { /** * XSLT file serves every test method. */ private final static String TEST_XSL = XML_DIR + "cities.xsl"; /** - * This tests if newTransformer(StreamSource) method returns Transformer + * This tests if newTransformer(StreamSource) method returns Transformer. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ - @Test - public void transformer01() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - StreamSource streamSource = new StreamSource( - new File(TEST_XSL)); - Transformer transformer = tfactory.newTransformer(streamSource); - assertNotNull(transformer); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } + @Test (groups = {"readLocalFiles"}) + public void transformer01() throws TransformerConfigurationException { + TransformerFactory tfactory = TransformerFactory.newInstance(); + StreamSource streamSource = new StreamSource( + new File(TEST_XSL)); + Transformer transformer = tfactory.newTransformer(streamSource); + assertNotNull(transformer); } /** - * This tests if newTransformer(SAXSource) method returns Transformer + * This tests if newTransformer(SAXSource) method returns Transformer. + * @throws Exception If any errors occur. */ - @Test - public void transformer02() { - try { + @Test (groups = {"readLocalFiles"}) + public void transformer02() throws Exception { + try (FileInputStream fis = new FileInputStream(TEST_XSL)) { TransformerFactory tfactory = TransformerFactory.newInstance(); - InputSource is = new InputSource( - new FileInputStream(TEST_XSL)); - SAXSource saxSource = new SAXSource(is); + SAXSource saxSource = new SAXSource(new InputSource(fis)); Transformer transformer = tfactory.newTransformer(saxSource); assertNotNull(transformer); - } catch (TransformerConfigurationException | FileNotFoundException ex){ - failUnexpected(ex); } } /** - * This tests if newTransformer(DOMSource) method returns Transformer + * This tests if newTransformer(DOMSource) method returns Transformer. + * + * @throws Exception If any errors occur. */ - @Test - public void transformer03() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); + @Test (groups = {"readLocalFiles"}) + public void transformer03() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); - Transformer transformer = tfactory.newTransformer(domSource); - assertNotNull(transformer); - } catch (TransformerConfigurationException | IOException - | ParserConfigurationException | SAXException ex){ - failUnexpected(ex); - } + Transformer transformer = tfactory.newTransformer(domSource); + assertNotNull(transformer); } /** - * This tests set/get ErrorListener methods of Transformer + * This tests set/get ErrorListener methods of Transformer. + * + * @throws Exception If any errors occur. */ - @Test - public void transformer04() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); + @Test (groups = {"readLocalFiles"}) + public void transformer04() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(domSource); - transformer.setErrorListener(new MyErrorListener()); - assertNotNull(transformer.getErrorListener()); - assertTrue(transformer.getErrorListener() instanceof MyErrorListener); - } catch (IOException | IllegalArgumentException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(domSource); + transformer.setErrorListener(new MyErrorListener()); + assertNotNull(transformer.getErrorListener()); + assertTrue(transformer.getErrorListener() instanceof MyErrorListener); } /** - * This tests getOutputProperties() method of Transformer + * This tests getOutputProperties() method of Transformer. + * + * @throws Exception If any errors occur. */ - @Test - public void transformer05() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); + @Test (groups = {"readLocalFiles"}) + public void transformer05() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); - Transformer transformer = TransformerFactory.newInstance(). - newTransformer(domSource); - Properties prop = transformer.getOutputProperties(); + Transformer transformer = TransformerFactory.newInstance(). + newTransformer(domSource); + Properties prop = transformer.getOutputProperties(); - assertEquals(prop.getProperty("indent"), "yes"); - assertEquals(prop.getProperty("method"), "xml"); - assertEquals(prop.getProperty("encoding"), "UTF-8"); - assertEquals(prop.getProperty("standalone"), "no"); - assertEquals(prop.getProperty("version"), "1.0"); - assertEquals(prop.getProperty("omit-xml-declaration"), "no"); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerConfigurationException ex){ - failUnexpected(ex); - } + assertEquals(prop.getProperty("indent"), "yes"); + assertEquals(prop.getProperty("method"), "xml"); + assertEquals(prop.getProperty("encoding"), "UTF-8"); + assertEquals(prop.getProperty("standalone"), "no"); + assertEquals(prop.getProperty("version"), "1.0"); + assertEquals(prop.getProperty("omit-xml-declaration"), "no"); } /** - * This tests getOutputProperty() method of Transformer + * This tests getOutputProperty() method of Transformer. + * + * @throws Exception If any errors occur. */ - @Test - public void transformer06() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); + @Test (groups = {"readLocalFiles"}) + public void transformer06() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); - Transformer transformer = tfactory.newTransformer(domSource); - assertEquals(transformer.getOutputProperty("method"), "xml"); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerConfigurationException | IllegalArgumentException ex){ - failUnexpected(ex); - } + Transformer transformer = tfactory.newTransformer(domSource); + assertEquals(transformer.getOutputProperty("method"), "xml"); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest02.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest02.java index 9f6a2bef82f..0f50b349eec 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest02.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest02.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,42 +25,34 @@ package javax.xml.transform.ptests; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; /** * Here a transformer is created using DOMSource. Some specific output property * is set on transformer. Then transform(StreamSource, StreamResult) is tested. */ -public class TransformerTest02 { +public class TransformerTest02 extends JAXPFileBaseTest { /** * Unit test for transform(StreamSource, StreamResult). + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "transformer02.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "transformer02.out"; String goldFile = GOLDEN_DIR + "transformer02GF.out"; String xsltFile = XML_DIR + "cities.xsl"; String xmlFile = XML_DIR + "cities.xml"; @@ -69,9 +61,8 @@ public class TransformerTest02 { FileOutputStream fos = new FileOutputStream(outputFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(xsltFile)); - DOMSource domSource = new DOMSource(document); + DOMSource domSource = new DOMSource(dbf.newDocumentBuilder(). + parse(new File(xsltFile))); Transformer transformer = TransformerFactory.newInstance(). newTransformer(domSource); @@ -79,20 +70,8 @@ public class TransformerTest02 { StreamResult streamResult = new StreamResult(fos); transformer.setOutputProperty("indent", "no"); - transformer.transform( streamSource, streamResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | IllegalArgumentException - | ParserConfigurationException | TransformerException - | SAXException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + transformer.transform(streamSource, streamResult); } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest03.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest03.java index 2035d16b0c7..23855e52cb2 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest03.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest03.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,30 +25,20 @@ package javax.xml.transform.ptests; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Properties; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; /** * Here Properties Object is populated with required properties.A transformer @@ -56,13 +46,15 @@ import org.xml.sax.SAXException; * for transformer. Then transform(StreamSource, StreamResult) is used for * transformation. This tests the setOutputProperties() method. */ -public class TransformerTest03 { +public class TransformerTest03 extends JAXPFileBaseTest { /** * Test for Transformer.setOutputProperties method. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "transformer03.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "transformer03.out"; String goldFile = GOLDEN_DIR + "transformer03GF.out"; String xsltFile = XML_DIR + "cities.xsl"; String xmlFile = XML_DIR + "cities.xml"; @@ -81,29 +73,14 @@ public class TransformerTest03 { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(xsltFile)); - DOMSource domSource = new DOMSource(document); + DOMSource domSource = new DOMSource(dbf.newDocumentBuilder(). + parse(new File(xsltFile))); Transformer transformer = TransformerFactory.newInstance(). newTransformer(domSource); - StreamSource streamSource = new StreamSource(fis); - StreamResult streamResult = new StreamResult(fos); - transformer.setOutputProperties(properties); - transformer.transform( streamSource, streamResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException - | IOException | TransformerException ex){ - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + transformer.transform(new StreamSource(fis), new StreamResult(fos)); } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/URIResolverTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/URIResolverTest.java index d5ddfaeb9be..05889f6715c 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/URIResolverTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/URIResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,15 +24,10 @@ package javax.xml.transform.ptests; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMSource; @@ -40,18 +35,17 @@ import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileBaseTest; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * URIResolver should be invoked when transform happens. */ -public class URIResolverTest implements URIResolver { +public class URIResolverTest extends JAXPFileBaseTest implements URIResolver { /** * System ID constant. */ @@ -72,9 +66,8 @@ public class URIResolverTest implements URIResolver { */ private final static String XSL_TEMP_FILE = "temp/cities.xsl"; - /** - * expected Href. + * expected HREF. */ private final String validateHref; @@ -83,6 +76,14 @@ public class URIResolverTest implements URIResolver { */ private final String validateBase; + /** + * Default constructor for testng invocation. + */ + public URIResolverTest(){ + validateHref = null; + validateBase = null; + } + /** * Constructor for setting expected Href and expected Base URI. * @param validateHref expected Href @@ -110,166 +111,144 @@ public class URIResolverTest implements URIResolver { /** * This is to test the URIResolver.resolve() method when a transformer is - * created using StreamSource. xsl file has xsl:include in it + * created using StreamSource. style-sheet file has xsl:include in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver01() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver01() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_INCLUDE_FILE)) { TransformerFactory tfactory = TransformerFactory.newInstance(); URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); tfactory.setURIResolver(resolver); - StreamSource streamSource = new StreamSource(new FileInputStream(XSL_INCLUDE_FILE)); + StreamSource streamSource = new StreamSource(fis); streamSource.setSystemId(SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(streamSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(streamSource)); } } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using DOMSource. xsl file has xsl:include in it + * created using DOMSource. style-sheet file has xsl:include in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver02() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); - tfactory.setURIResolver(resolver); + @Test (groups = {"readLocalFiles"}) + public static void resolver02() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); + tfactory.setURIResolver(resolver); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(XSL_INCLUDE_FILE); - DOMSource domSource = new DOMSource(document, SYSTEM_ID); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(XSL_INCLUDE_FILE); + DOMSource domSource = new DOMSource(document, SYSTEM_ID); - Transformer transformer = tfactory.newTransformer(domSource); - } catch (IOException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } + assertNotNull(tfactory.newTransformer(domSource)); } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using SAXSource. xsl file has xsl:include in it + * created using SAXSource. style-sheet file has xsl:include in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver03() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver03() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_INCLUDE_FILE)){ URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setURIResolver(resolver); - InputSource is = new InputSource(new FileInputStream(XSL_INCLUDE_FILE)); + InputSource is = new InputSource(fis); is.setSystemId(SYSTEM_ID); SAXSource saxSource = new SAXSource(is); - - Transformer transformer = tfactory.newTransformer(saxSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(saxSource)); } } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using StreamSource. xsl file has xsl:import in it + * created using StreamSource. style-sheet file has xsl:import in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver04() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver04() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_IMPORT_FILE)) { URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setURIResolver(resolver); - - StreamSource streamSource = new StreamSource(new FileInputStream(XSL_IMPORT_FILE)); + StreamSource streamSource = new StreamSource(fis); streamSource.setSystemId(SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(streamSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(streamSource)); } } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using DOMSource. xsl file has xsl:import in it + * created using DOMSource. style-sheet file has xsl:import in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver05() { - try { - URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); - TransformerFactory tfactory = TransformerFactory.newInstance(); - tfactory.setURIResolver(resolver); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(XSL_IMPORT_FILE)); - DOMSource domSource = new DOMSource(document, SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(domSource); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerConfigurationException ex){ - failUnexpected(ex); - } - + @Test (groups = {"readLocalFiles"}) + public static void resolver05() throws Exception { + URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); + TransformerFactory tfactory = TransformerFactory.newInstance(); + tfactory.setURIResolver(resolver); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(XSL_IMPORT_FILE)); + DOMSource domSource = new DOMSource(document, SYSTEM_ID); + assertNotNull(tfactory.newTransformer(domSource)); } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using SAXSource. xsl file has xsl:import in it + * created using SAXSource. style-sheet file has xsl:import in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver06() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver06() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_IMPORT_FILE)){ URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setURIResolver(resolver); - - InputSource is = new InputSource(new FileInputStream(XSL_IMPORT_FILE)); + InputSource is = new InputSource(fis); is.setSystemId(SYSTEM_ID); SAXSource saxSource = new SAXSource(is); - - Transformer transformer = tfactory.newTransformer(saxSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(saxSource)); } - } /** * This is to test the URIResolver.resolve() method when there is an error * in the file. + * + * @throws Exception If any errors occur. */ - @Test - public static void docResolver01() { - try { + @Test (groups = {"readLocalFiles"}) + public static void docResolver01() throws Exception { + try (FileInputStream fis = new FileInputStream(XML_DIR + "doctest.xsl")) { URIResolverTest resolver = new URIResolverTest("temp/colors.xml", SYSTEM_ID); - TransformerFactory tfactory = TransformerFactory.newInstance(); - - StreamSource streamSource = new StreamSource( - new FileInputStream(XML_DIR + FILE_SEP + "doctest.xsl")); + StreamSource streamSource = new StreamSource(fis); streamSource.setSystemId(SYSTEM_ID); - System.err.println(streamSource.getSystemId()); - Transformer transformer = tfactory.newTransformer(streamSource); + Transformer transformer = TransformerFactory.newInstance().newTransformer(streamSource); transformer.setURIResolver(resolver); - File f = new File(XML_DIR + FILE_SEP + "myFake.xml"); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(f); + File f = new File(XML_DIR + "myFake.xml"); + Document document = DocumentBuilderFactory.newInstance(). + newDocumentBuilder().parse(f); // Use a Transformer for output DOMSource source = new DOMSource(document); - System.err.println("Ignore the following output -- just dumping it here"); StreamResult result = new StreamResult(System.err); + // No exception is expected because resolver resolve wrong URI. transformer.transform(source, result); - } catch (IOException | ParserConfigurationException | SAXException - | TransformerException ex) { - failUnexpected(ex); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/othervm/TFCErrorTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/othervm/TFCErrorTest.java index ee2420eb7e7..489fe838d32 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/othervm/TFCErrorTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/othervm/TFCErrorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -23,19 +23,22 @@ package javax.xml.transform.ptests.othervm; import javax.xml.transform.*; +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.fail; import org.testng.annotations.Test; /** * Negative test for set invalid TransformerFactory property. */ -public class TFCErrorTest{ +public class TFCErrorTest extends JAXPBaseTest { @Test(expectedExceptions = ClassNotFoundException.class) public void tfce01() throws Exception { try{ - System.setProperty("javax.xml.transform.TransformerFactory","xx"); - TransformerFactory tFactory = TransformerFactory.newInstance(); - } catch (TransformerFactoryConfigurationError error) { - throw error.getException(); + setSystemProperty("javax.xml.transform.TransformerFactory","xx"); + TransformerFactory.newInstance(); + fail("Expect TransformerFactoryConfigurationError here"); + } catch (TransformerFactoryConfigurationError expected) { + throw expected.getException(); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathExpressionTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathExpressionTest.java index bbd4a58678d..bf9c2502ee9 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathExpressionTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathExpressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ package javax.xml.xpath.ptests; -import java.io.IOException; +import java.io.FilePermission; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -31,7 +31,6 @@ import java.nio.file.Paths; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import static javax.xml.xpath.XPathConstants.BOOLEAN; import static javax.xml.xpath.XPathConstants.NODE; @@ -41,7 +40,7 @@ import static javax.xml.xpath.XPathConstants.STRING; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static javax.xml.xpath.ptests.XPathTestConst.XML_DIR; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -49,12 +48,11 @@ import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Class containing the test cases for XPathExpression API. */ -public class XPathExpressionTest { +public class XPathExpressionTest extends JAXPFileReadOnlyBaseTest { /** * Document object for testing XML file. */ @@ -87,13 +85,11 @@ public class XPathExpressionTest { /** * Create Document object and XPath object for every time - * @throws ParserConfigurationException If the factory class cannot be - * loaded, instantiated - * @throws SAXException If any parse errors occur. - * @throws IOException If operation on xml file failed. + * @throws Exception If any errors occur. */ @BeforeTest - public void setup() throws ParserConfigurationException, SAXException, IOException { + public void setup() throws Exception { + setPermissions(new FilePermission(XML_PATH.toFile().toString(), "read")); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(XML_PATH.toFile()); xpath = XPathFactory.newInstance().newXPath(); } @@ -101,230 +97,200 @@ public class XPathExpressionTest { /** * Test for evaluate(java.lang.Object item,QName returnType)throws * XPathExpressionException. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression01() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A). - evaluate(document, STRING), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression01() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A). + evaluate(document, STRING), "6"); } /** * evaluate(java.lang.Object item,QName returnType) throws NPE if input * source is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression02() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression02() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); } /** * evaluate(java.lang.Object item,QName returnType) throws NPE if returnType * is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression03() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(document, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression03() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(document, null); } /** * Test for method evaluate(java.lang.Object item,QName returnType).If a * request is made to evaluate the expression in the absence of a context * item, simple expressions, such as "1+1", can be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression04() { - try { - assertEquals(xpath.compile("1+1").evaluate(document, STRING), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression04() throws XPathExpressionException { + assertEquals(xpath.compile("1+1").evaluate(document, STRING), "2"); } /** * evaluate(java.lang.Object item,QName returnType) throws IAE If returnType * is not one of the types defined in XPathConstants. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPathExpression05() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(document, TEST_QNAME); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression05() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(document, TEST_QNAME); } /** * evaluate(java.lang.Object item,QName returnType) return correct boolean * value if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression06() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A). + public void testCheckXPathExpression06() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(document, BOOLEAN), true); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } } /** * evaluate(java.lang.Object item,QName returnType) return correct boolean * value if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression07() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_B). - evaluate(document, BOOLEAN), false); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression07() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_B). + evaluate(document, BOOLEAN), false); } /** * evaluate(java.lang.Object item,QName returnType) return correct number * value when return type is Double. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression08() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A). - evaluate(document, NUMBER), 6d); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression08() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A). + evaluate(document, NUMBER), 6d); } /** * evaluate(java.lang.Object item,QName returnType) evaluate an attribute * value which returnType is Node. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression09() { - try { - Attr attr = (Attr) xpath.compile(EXPRESSION_NAME_A). - evaluate(document, NODE); - assertEquals(attr.getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression09() throws XPathExpressionException { + Attr attr = (Attr) xpath.compile(EXPRESSION_NAME_A). + evaluate(document, NODE); + assertEquals(attr.getValue(), "6"); } /** * evaluate(java.lang.Object item,QName returnType) evaluate an attribute * value which returnType is NodeList. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression10() { - try { - NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). - evaluate(document, NODESET); - Attr attr = (Attr) nodeList.item(0); - assertEquals(attr.getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression10() throws XPathExpressionException { + NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). + evaluate(document, NODESET); + Attr attr = (Attr) nodeList.item(0); + assertEquals(attr.getValue(), "6"); } /** * Test for evaluate(java.lang.Object item) when returnType is left off of * the XPath.evaluate method, all expressions are evaluated to a String * value. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression11() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression11() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document), "6"); } /** * evaluate(java.lang.Object item) throws NPE if expression is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression12() { - try { - xpath.compile(null).evaluate(document); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression12() throws XPathExpressionException { + xpath.compile(null).evaluate(document); } /** * evaluate(java.lang.Object item) when a request is made to evaluate the * expression in the absence of a context item, simple expressions, such as * "1+1", can be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression13() { - try { - assertEquals(xpath.compile("1+1").evaluate(document), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression13() throws XPathExpressionException { + assertEquals(xpath.compile("1+1").evaluate(document), "2"); } /** * evaluate(java.lang.Object item) throws NPE if document is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression14() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression14() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null); } /** * valuate(InputSource source) return a string value if return type is * String. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression15() { + @Test (groups = {"readLocalFiles"}) + public void testCheckXPathExpression15() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is)), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source) throws NPE if input source is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression16() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression16() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null); } /** - * evaluate(InputSource source) throws NPE if expression is null + * evaluate(InputSource source) throws NPE if expression is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression17() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPathExpression17() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(null).evaluate(new InputSource(is)); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -332,14 +298,12 @@ public class XPathExpressionTest { * evaluate(InputSource source) throws XPathExpressionException if * returnType is String junk characters. * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression18() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression18() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile("-*&").evaluate(new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -347,67 +311,63 @@ public class XPathExpressionTest { * evaluate(InputSource source) throws XPathExpressionException if * expression is a blank string " ". * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression19() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression19() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(" ").evaluate(new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } /** * Test for evaluate(InputSource source,QName returnType) returns a string * value if returnType is String. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression20() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression20() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), STRING), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) throws NPE if source is * null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression21() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression21() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); } /** * evaluate(InputSource source,QName returnType) throws NPE if expression is * null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression22() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPathExpression22() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(null).evaluate(new InputSource(is), STRING); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) throws NPE if returnType is * null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression23() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPathExpression23() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(EXPRESSION_NAME_A).evaluate(new InputSource(is), null); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -415,14 +375,12 @@ public class XPathExpressionTest { * evaluate(InputSource source,QName returnType) throws * XPathExpressionException if expression is junk characters. * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression24() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression24() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile("-*&").evaluate(new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -430,14 +388,12 @@ public class XPathExpressionTest { * evaluate(InputSource source,QName returnType) throws * XPathExpressionException if expression is blank " ". * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression25() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression25() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(" ").evaluate(new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -445,85 +401,85 @@ public class XPathExpressionTest { * evaluate(InputSource source,QName returnType) throws * IllegalArgumentException if returnType is not one of the types defined * in XPathConstants. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPathExpression26() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = IllegalArgumentException.class) + public void testCheckXPathExpression26() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(EXPRESSION_NAME_A).evaluate(new InputSource(is), TEST_QNAME); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) return a correct boolean * value if returnType is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression27() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression27() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), BOOLEAN), true); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) return a correct boolean * value if returnType is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression28() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression28() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_B). evaluate(new InputSource(is), BOOLEAN), false); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) return a correct number * value if returnType is Number. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression29() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression29() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NUMBER), 6d); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * Test for evaluate(InputSource source,QName returnType) returns a node if * returnType is Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression30() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression30() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { Attr attr = (Attr) xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NODE); assertEquals(attr.getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * Test for evaluate(InputSource source,QName returnType) return a node list * if returnType is NodeList. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression31() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression31() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFactoryTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFactoryTest.java index d8e84c7f4a2..cc33e0a05cf 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFactoryTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,14 +26,14 @@ package javax.xml.xpath.ptests; import static javax.xml.xpath.XPathConstants.DOM_OBJECT_MODEL; import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactoryConfigurationException; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPBaseTest; import static org.testng.AssertJUnit.assertNotNull; import org.testng.annotations.Test; /** * Class containing the test cases for XPathFactory API. */ -public class XPathFactoryTest { +public class XPathFactoryTest extends JAXPBaseTest { /** * Valid URL for creating a XPath factory. */ @@ -54,21 +54,21 @@ public class XPathFactoryTest { /** * XPathFactory.newInstance(String uri) throws NPE if uri is null. + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test(expectedExceptions = NullPointerException.class) - private void testCheckXPathFactory02() { - try { - XPathFactory.newInstance(null); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory02() throws XPathFactoryConfigurationException { + XPathFactory.newInstance(null); } /** * XPathFactory.newInstance(String uri) throws XPFCE if uri is just a blank * string. * - * @throws XPathFactoryConfigurationException + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test(expectedExceptions = XPathFactoryConfigurationException.class) public void testCheckXPathFactory03() throws XPathFactoryConfigurationException { @@ -78,21 +78,21 @@ public class XPathFactoryTest { /** * Test for constructor - XPathFactory.newInstance(String uri) with valid * url - "http://java.sun.com/jaxp/xpath/dom". + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test - public void testCheckXPathFactory04() { - try { - assertNotNull(XPathFactory.newInstance(VALID_URL)); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory04() throws XPathFactoryConfigurationException { + assertNotNull(XPathFactory.newInstance(VALID_URL)); } /** * Test for constructor - XPathFactory.newInstance(String uri) with invalid * url - "http://java.sun.com/jaxp/xpath/dom1". * - * @throws XPathFactoryConfigurationException + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test(expectedExceptions = XPathFactoryConfigurationException.class) public void testCheckXPathFactory05() throws XPathFactoryConfigurationException { @@ -112,26 +112,24 @@ public class XPathFactoryTest { * Test for constructor - XPathFactory.newInstance(String uri) with valid * url - "http://java.sun.com/jaxp/xpath/dom" and creating XPath with * newXPath(). + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test - public void testCheckXPathFactory07() { - try { - assertNotNull(XPathFactory.newInstance(VALID_URL).newXPath()); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory07() throws XPathFactoryConfigurationException { + assertNotNull(XPathFactory.newInstance(VALID_URL).newXPath()); } /** * Test for constructor - XPathFactory.newInstance(String uri) with valid * uri - DOM_OBJECT_MODEL.toString(). + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test - public void testCheckXPathFactory08() { - try { - assertNotNull(XPathFactory.newInstance(DOM_OBJECT_MODEL)); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory08() throws XPathFactoryConfigurationException { + assertNotNull(XPathFactory.newInstance(DOM_OBJECT_MODEL)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFunctionResolverTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFunctionResolverTest.java index 80f75b75eb0..cf1046508b5 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFunctionResolverTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFunctionResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,7 +26,7 @@ package javax.xml.xpath.ptests; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -34,7 +34,7 @@ import org.testng.annotations.Test; /** * Class containing the test cases for XPathFunctionResolver. */ -public class XPathFunctionResolverTest { +public class XPathFunctionResolverTest extends JAXPBaseTest { /** * A XPath for evaluation environment and expressions. */ @@ -54,26 +54,22 @@ public class XPathFunctionResolverTest { /** * Test for resolveFunction(QName functionName,int arity). evaluate will * continue as long as functionName is meaningful. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathFunctionResolver01() { - try { - assertEquals(xpath.evaluate("round(1.7)", (Object)null), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathFunctionResolver01() throws XPathExpressionException { + assertEquals(xpath.evaluate("round(1.7)", (Object)null), "2"); } /** * Test for resolveFunction(QName functionName,int arity); evaluate throws * NPE if functionName is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathFunctionResolver02() { - try { - assertEquals(xpath.evaluate(null, "5"), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathFunctionResolver02() throws XPathExpressionException { + assertEquals(xpath.evaluate(null, "5"), "2"); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathTest.java b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathTest.java index 83688101435..765cf18bae1 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ package javax.xml.xpath.ptests; -import java.io.IOException; +import java.io.FilePermission; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -33,7 +33,6 @@ import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import static javax.xml.xpath.XPathConstants.BOOLEAN; import static javax.xml.xpath.XPathConstants.NODE; @@ -43,7 +42,7 @@ import static javax.xml.xpath.XPathConstants.STRING; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static javax.xml.xpath.ptests.XPathTestConst.XML_DIR; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; @@ -53,12 +52,11 @@ import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Class containing the test cases for XPath API. */ -public class XPathTest { +public class XPathTest extends JAXPFileReadOnlyBaseTest { /** * Document object for testing XML file. */ @@ -91,13 +89,11 @@ public class XPathTest { /** * Create Document object and XPath object for every time - * @throws ParserConfigurationException If the factory class cannot be - * loaded, instantiated - * @throws SAXException If any parse errors occur. - * @throws IOException If operation on xml file failed. + * @throws Exception If any errors occur. */ @BeforeTest - public void setup() throws ParserConfigurationException, SAXException, IOException { + public void setup() throws Exception { + setPermissions(new FilePermission(XML_DIR + "-", "read")); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(XML_PATH.toFile()); xpath = XPathFactory.newInstance().newXPath(); } @@ -105,62 +101,54 @@ public class XPathTest { /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType) which return type is String. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath01() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, STRING), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath01() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, STRING), "6"); } /** * Test for XPath.compile(java.lang.String expression) and then * evaluate(java.lang.Object item, QName returnType). + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath02() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document, STRING), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath02() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document, STRING), "6"); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item) when the third argument is left off of the XPath.evaluate method, * all expressions are evaluated to a String value. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath03() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath03() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document), "6"); } /** * Test for XPath.compile(java.lang.String expression). If expression is * null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath04() { - try { - xpath.compile(null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath04() throws XPathExpressionException { + xpath.compile(null); } /** * Test for XPath.compile(java.lang.String expression). If expression cannot * be compiled junk characters, should throw XPathExpressionException. * - * @throws XPathExpressionException + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = XPathExpressionException.class) public void testCheckXPath05() throws XPathExpressionException { @@ -171,7 +159,7 @@ public class XPathTest { * Test for XPath.compile(java.lang.String expression). If expression is * blank, should throw XPathExpressionException * - * @throws XPathExpressionException + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = XPathExpressionException.class) public void testCheckXPath06() throws XPathExpressionException { @@ -181,55 +169,46 @@ public class XPathTest { /** * Test for XPath.compile(java.lang.String expression). The expression * cannot be evaluated as this does not exist. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath07() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_B).evaluate(document, STRING), ""); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } - + public void testCheckXPath07() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_B).evaluate(document, STRING), ""); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object - * item, QName returnType). If String expression is null, should throw NPE + * item, QName returnType). If String expression is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath08() { - try { - xpath.evaluate(null, document, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath08() throws XPathExpressionException { + xpath.evaluate(null, document, STRING); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType). If item is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath09() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath09() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null, STRING); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType). If returnType is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath10() { - try { - xpath.evaluate(EXPRESSION_NAME_A, document, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath10() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, document, null); } /** @@ -237,23 +216,20 @@ public class XPathTest { * item, QName returnType). If a request is made to evaluate the expression * in the absence of a context item, simple expressions, such as "1+1", can * be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath11() { - try { - assertEquals(xpath.evaluate("1+1", document, STRING), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath11() throws XPathExpressionException { + assertEquals(xpath.evaluate("1+1", document, STRING), "2"); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) throws XPathExpressionException if expression is a empty * string "". - * . * - * @throws XPathExpressionException + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = XPathExpressionException.class) public void testCheckXPath12() throws XPathExpressionException { @@ -264,161 +240,141 @@ public class XPathTest { * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) throws IllegalArgumentException if returnType is not one of * the types defined in XPathConstants. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPath13() { - try { - xpath.evaluate(EXPRESSION_NAME_A, document, TEST_QNAME); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath13() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, document, TEST_QNAME); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns correct boolean value if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath14() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, BOOLEAN), true); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath14() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, BOOLEAN), true); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns false as expression is not successful in evaluating * to any result if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath15() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_B, document, BOOLEAN), false); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath15() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_B, document, BOOLEAN), false); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns correct number value if return type is Number. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath16() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, NUMBER), 6d); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath16() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, NUMBER), 6d); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns correct string value if return type is Node. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath17() { - try { - assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, document, NODE)).getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath17() throws XPathExpressionException { + assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, document, NODE)).getValue(), "6"); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType). If return type is NodeList,the evaluated value * equals to "6" as expected. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath18() { - try { - NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, document, NODESET); - assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath18() throws XPathExpressionException { + NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, document, NODESET); + assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item). If expression is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath19() { - try { - xpath.evaluate(null, document); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath19() throws XPathExpressionException { + xpath.evaluate(null, document); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item). If a request is made to evaluate the expression in the absence of * a context item, simple expressions, such as "1+1", can be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath20() { - try { - assertEquals(xpath.evaluate("1+1", document), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath20() throws XPathExpressionException { + assertEquals(xpath.evaluate("1+1", document), "2"); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item) throws * NPE if InputSource is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath21() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath21() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null); } /** * XPath.evaluate(java.lang.String expression, InputSource source) return * correct value by looking for Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath22() { + @Test (groups = {"readLocalFiles"}) + public void testCheckXPath22() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is)), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source) throws * NPE if InputSource is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath23() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath23() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null); } /** * XPath.evaluate(java.lang.String expression, InputSource source) throws * NPE if String expression is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath24() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPath24() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(null, new InputSource(is)); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -427,14 +383,12 @@ public class XPathTest { * If expression is junk characters, expression cannot be evaluated, should * throw XPathExpressionException. * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath25() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath25() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate("-*&", new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -442,66 +396,62 @@ public class XPathTest { * XPath.evaluate(java.lang.String expression, InputSource source) throws * XPathExpressionException if expression is blank " ". * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath26() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath26() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(" ", new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) returns correct string value which return type is String. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath27() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath27() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), STRING), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws NPE if source is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath28() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath28() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null, STRING); } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws NPE if expression is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath29() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPath29() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(null, new InputSource(is), STRING); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, - * QName returnType) throws NPE if returnType is null . + * QName returnType) throws NPE if returnType is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath30() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPath30() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), null); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -509,14 +459,12 @@ public class XPathTest { * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws XPathExpressionException if expression is junk characters. * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath31() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath31() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate("-*&", new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -524,14 +472,12 @@ public class XPathTest { * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws XPathExpressionException if expression is blank " ". * - * @throws XPathExpressionException + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath32() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath32() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(" ", new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -539,84 +485,84 @@ public class XPathTest { * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) throws IllegalArgumentException if returnType is not * one of the types defined in XPathConstants. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPath33() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = IllegalArgumentException.class) + public void testCheckXPath33() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), TEST_QNAME); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct boolean value if return type is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath34() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath34() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), BOOLEAN), true); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct boolean value if return type is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath35() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath35() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_B, new InputSource(is), BOOLEAN), false); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct number value if return type is Number. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath36() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath36() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NUMBER), 6d); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct string value if return type is Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath37() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath37() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODE)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * Test for XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) which return type is NodeList. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath38() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath38() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -624,57 +570,57 @@ public class XPathTest { * Test for XPath.evaluate(java.lang.String expression, InputSource iSource, * QName returnType). If return type is Boolean, should return false as * expression is not successful in evaluating to any result. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath52() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath52() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_B, new InputSource(is), BOOLEAN), false); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource iSource, QName * returnType) returns correct number value which return type is Number. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath53() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath53() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NUMBER), 6d); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource iSource, QName * returnType) returns a node value if returnType is Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath54() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath54() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODE)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource iSource, QName * returnType) returns a node list if returnType is NodeList. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath55() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath55() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttrImplTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttrImplTest.java index d6491704db3..708b53376df 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttrImplTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttrImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -22,6 +22,7 @@ */ package org.xml.sax.ptests; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; @@ -30,7 +31,7 @@ import org.xml.sax.helpers.AttributesImpl; /** * Class containing the test cases for AttributesImpl API. */ -public class AttrImplTest { +public class AttrImplTest extends JAXPBaseTest { private static final String CAR_URI = "http://www.cars.com/xml"; private static final String CAR_LOCALNAME = "part"; diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesNSTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesNSTest.java index 1b8d8a56c23..8309fc1b569 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesNSTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesNSTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,20 +23,13 @@ package org.xml.sax.ptests; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -45,39 +38,29 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * ContentHandler has Attributes as one of its arguments. Attributes * pertaining to an element are taken into this argument and various methods * of Attributes interfaces are tested. This program uses Namespace processing - * with namespaces in xml file. This program does not use Validation + * with namespaces in XML file. This program does not use Validation */ -public class AttributesNSTest { +public class AttributesNSTest extends JAXPFileBaseTest { /** * Test for Attribute Interface's setter/getter. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "AttributesNS.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "AttributesNS.out"; String goldFile = GOLDEN_DIR + "AttributesNSGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - // http://www.saxproject.com/?selected=namespaces namespace-prefixes - //set to false to supress xmlns attributes - spf.setFeature("http://xml.org/sax/features/namespace-prefixes", - false); - SAXParser saxParser = spf.newSAXParser(); - MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); - saxParser.parse(new File(xmlFile), myAttrCHandler); - myAttrCHandler.flushAndClose(); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + // http://www.saxproject.com/?selected=namespaces namespace-prefixes + //set to false to supress xmlns attributes + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", + false); + SAXParser saxParser = spf.newSAXParser(); + MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); + saxParser.parse(new File(xmlFile), myAttrCHandler); + myAttrCHandler.flushAndClose(); + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesTest.java index 3d310202401..351ceee914f 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,20 +23,13 @@ package org.xml.sax.ptests; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -48,37 +41,28 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * This program uses Namespace processing without any namepsaces in xml file. * This program uses Validation */ -public class AttributesTest { +public class AttributesTest extends JAXPFileBaseTest { /** * Unit test for Attributes interface. Prints all attributes into output * file. Check it with golden file. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "Attributes.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "Attributes.out"; String goldFile = GOLDEN_DIR + "AttributesGF.out"; String xmlFile = XML_DIR + "family.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setFeature("http://xml.org/sax/features/namespace-prefixes", - true); - spf.setValidating(true); - SAXParser saxParser = spf.newSAXParser(); - MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); - saxParser.parse(new File(xmlFile), myAttrCHandler); - myAttrCHandler.flushAndClose(); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", + true); + spf.setValidating(true); + SAXParser saxParser = spf.newSAXParser(); + MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); + saxParser.parse(new File(xmlFile), myAttrCHandler); + myAttrCHandler.flushAndClose(); + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ContentHandlerTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ContentHandlerTest.java index 729cef54aee..7ab081ee2b7 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ContentHandlerTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ContentHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,24 +26,18 @@ import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -52,43 +46,34 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * transverses XML and print all visited node when XMLreader parses XML. Test * verifies output is same as the golden file. */ -public class ContentHandlerTest { +public class ContentHandlerTest extends JAXPFileBaseTest { /** * Content event handler visit all nodes to print to output file. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "Content.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "Content.out"; String goldFile = GOLDEN_DIR + "ContentGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try(FileInputStream instream = new FileInputStream(xmlFile)) { + try(FileInputStream instream = new FileInputStream(xmlFile); + MyContentHandler cHandler = new MyContentHandler(outputFile)) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - ContentHandler cHandler = new MyContentHandler(outputFile); xmlReader.setContentHandler(cHandler); - InputSource is = new InputSource(instream); - xmlReader.parse(is); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch( IOException | SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + xmlReader.parse(new InputSource(instream)); } + assertTrue(compareWithGold(goldFile, outputFile)); } } /** * A content write out handler. */ -class MyContentHandler extends XMLFilterImpl { +class MyContentHandler extends XMLFilterImpl implements AutoCloseable { /** * Prefix to every exception. */ @@ -258,4 +243,14 @@ class MyContentHandler extends XMLFilterImpl { throw new SAXException(WRITE_ERROR, ex); } } + + /** + * Close the writer if it's initiated. + * @throws IOException if any IO error when close buffered writer. + */ + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/DefaultHandlerTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/DefaultHandlerTest.java index cc3eecb2d9b..309c95d27e3 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/DefaultHandlerTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/DefaultHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,15 +26,11 @@ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.xml.sax.Attributes; @@ -42,7 +38,6 @@ import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -50,46 +45,32 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * XMLReader parse XML with default handler that transverses XML and * print all visited node. Test verifies output is same as the golden file. */ -public class DefaultHandlerTest { +public class DefaultHandlerTest extends JAXPFileBaseTest { /** * Test default handler that transverses XML and print all visited node. + * + * @throws Exception If any errors occur. */ @Test - public void testDefaultHandler() { - String outputFile = CLASS_DIR + "DefaultHandler.out"; + public void testDefaultHandler() throws Exception { + String outputFile = USER_DIR + "DefaultHandler.out"; String goldFile = GOLDEN_DIR + "DefaultHandlerGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxparser = spf.newSAXParser(); + + MyDefaultHandler handler = new MyDefaultHandler(outputFile); + File file = new File(xmlFile); + String Absolutepath = file.getAbsolutePath(); + String newAbsolutePath = Absolutepath; + if (File.separatorChar == '\\') + newAbsolutePath = Absolutepath.replace('\\', '/'); + saxparser.parse("file:///" + newAbsolutePath, handler); + + assertTrue(compareWithGold(goldFile, outputFile)); - MyDefaultHandler handler = new MyDefaultHandler(outputFile); - File file = new File(xmlFile); - String Absolutepath = file.getAbsolutePath(); - String newAbsolutePath = Absolutepath; - if (File.separatorChar == '\\') - newAbsolutePath = Absolutepath.replace('\\', '/'); - String uri = "file:///" + newAbsolutePath; - saxparser.parse(uri, handler); - } catch (IOException | ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/EHFatalTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/EHFatalTest.java index 5cd660bbc1a..d8ad68cd5e8 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/EHFatalTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/EHFatalTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,23 +26,19 @@ import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import org.testng.annotations.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -50,14 +46,16 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * ErrorHandler unit test. Set a ErrorHandle to XMLReader. Capture fatal error * events in ErrorHandler. */ -public class EHFatalTest { +public class EHFatalTest extends JAXPFileBaseTest { /** * Error Handler to capture all error events to output file. Verifies the * output file is same as golden file. + * + * @throws Exception If any errors occur. */ @Test - public void testEHFatal() { - String outputFile = CLASS_DIR + "EHFatal.out"; + public void testEHFatal() throws Exception { + String outputFile = USER_DIR + "EHFatal.out"; String goldFile = GOLDEN_DIR + "EHFatalGF.out"; String xmlFile = XML_DIR + "invalid.xml"; @@ -68,25 +66,12 @@ public class EHFatalTest { xmlReader.setErrorHandler(eHandler); InputSource is = new InputSource(instream); xmlReader.parse(is); - } catch (IOException | ParserConfigurationException ex) { - failUnexpected(ex); - } catch (SAXException ex) { - System.out.println("This is expected:" + ex); + fail("Parse should throw SAXException"); + } catch (SAXException expected) { + // This is expected. } // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSSupportTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSSupportTest.java index 965e535b9e2..a8731a484da 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSSupportTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSSupportTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,6 +23,7 @@ package org.xml.sax.ptests; import java.util.Enumeration; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; @@ -31,7 +32,7 @@ import org.xml.sax.helpers.NamespaceSupport; /** * Unit test cases for NamespaceSupport API */ -public class NSSupportTest { +public class NSSupportTest extends JAXPBaseTest { /** * Empty prefix name. */ diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest.java new file mode 100644 index 00000000000..72a8cf37c59 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2003, 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. + */ +package org.xml.sax.ptests; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.xml.sax.XMLReader; + +/** + * Class containing the test cases for Namespace Table defined at + * http://www.megginson.com/SAX/Java/namespaces.html + */ +public class NSTableTest extends JAXPBaseTest { + private static final String NAMESPACES = + "http://xml.org/sax/features/namespaces"; + private static final String NAMESPACE_PREFIXES = + "http://xml.org/sax/features/namespace-prefixes"; + + /** + * Here namespace processing and namespace-prefixes are enabled. + * The testcase tests XMLReader for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxParser = spf.newSAXParser(); + + XMLReader xmlReader = saxParser.getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, true); + + assertTrue(xmlReader.getFeature(NAMESPACES)); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is enabled. This will make namespace-prefixes + * disabled. The testcase tests XMLReader for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(NAMESPACES)); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is disabled. This will make namespace-prefixes + * enabled. The testcase tests XMLReader for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable03() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + assertFalse(xmlReader.getFeature(NAMESPACES)); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is disabled, and namespace-prefixes is + * disabled. This will make namespace processing on.The testcase tests + * XMLReader for this. This behavior only apply to crimson, not + * XERCES. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable04() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing and namespace-prefixes are enabled. + * The testcase tests SAXParserFactory for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature(NAMESPACE_PREFIXES,true); + assertTrue(spf.getFeature(NAMESPACES)); + assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is enabled. This will make namespace-prefixes + * disabled. The testcase tests SAXParserFactory for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + assertTrue(spf.getFeature(NAMESPACES)); + assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is disabled. This will make namespace-prefixes + * enabled. The testcase tests SAXParserFactory for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.getFeature(NAMESPACES)); + assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); + } + /** + * Here namespace processing is disabled, and namespace-prefixes is + * disabled. This will make namespace processing on.The testcase tests + * SAXParserFactory for this. This behavior only apply to crimson, + * not xerces. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable04() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest01.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest01.java deleted file mode 100644 index 1dc28418e0a..00000000000 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest01.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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. - */ -package org.xml.sax.ptests; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.XMLReader; - -/** - * Class containing the test cases for Namespace Table defined at - * http://www.megginson.com/SAX/Java/namespaces.html - */ -public class NSTableTest01 { - private static final String NAMESPACES = - "http://xml.org/sax/features/namespaces"; - private static final String NAMESPACE_PREFIXES = - "http://xml.org/sax/features/namespace-prefixes"; - - /** - * Here namespace processing and namespace-prefixes are enabled. - * The testcase tests XMLReader for this. - */ - @Test - public void xrNSTable01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - - XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, true); - - assertTrue(xmlReader.getFeature(NAMESPACES)); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is enabled. This will make namespace-prefixes - * disabled. The testcase tests XMLReader for this. - */ - @Test - public void xrNSTable02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - - XMLReader xmlReader = saxParser.getXMLReader(); - assertTrue(xmlReader.getFeature(NAMESPACES)); - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - - } - - /** - * Here namespace processing is disabled. This will make namespace-prefixes - * enabled. The testcase tests XMLReader for this. - */ - @Test - public void xrNSTable03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - assertFalse(xmlReader.getFeature(NAMESPACES)); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is disabled, and namespace-prefixes is - * disabled. This will make namespace processing on.The testcase tests - * XMLReader for this. This behavior only apply to crimson, not - * xerces - */ - @Test - public void xrNSTable04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, false); - - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing and namespace-prefixes are enabled. - * The testcase tests SAXParserFactory for this. - */ - @Test - public void spNSTable01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setFeature(NAMESPACE_PREFIXES,true); - assertTrue(spf.getFeature(NAMESPACES)); - assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is enabled. This will make namespace-prefixes - * disabled. The testcase tests SAXParserFactory for this. - */ - @Test - public void spNSTable02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - assertTrue(spf.getFeature(NAMESPACES)); - assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is disabled. This will make namespace-prefixes - * enabled. The testcase tests SAXParserFactory for this. - */ - @Test - public void spNSTable03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.getFeature(NAMESPACES)); - assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } - /** - * Here namespace processing is disabled, and namespace-prefixes is - * disabled. This will make namespace processing on.The testcase tests - * SAXParserFactory for this. This behavior only apply to crimson, - * not xerces. - */ - @Test - public void spNSTable04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(NAMESPACE_PREFIXES, false); - - assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } -} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ParserAdapterTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ParserAdapterTest.java index 0453edc186e..f7ee1e92192 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ParserAdapterTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ParserAdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,10 +23,8 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @@ -35,7 +33,6 @@ import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.ParserAdapter; import org.xml.sax.helpers.XMLFilterImpl; @@ -47,7 +44,7 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * Unit test cases for ParserAdapter API. By default the only features recognized * are namespaces and namespace-prefixes. */ -public class ParserAdapterTest { +public class ParserAdapterTest extends JAXPFileReadOnlyBaseTest { /** * namespaces feature name. */ @@ -67,10 +64,9 @@ public class ParserAdapterTest { /** * Initiate ParserAdapter. - * @throws ParserConfigurationException - * @throws SAXException + * @throws Exception If any errors occur. */ - ParserAdapterTest() throws ParserConfigurationException, SAXException { + ParserAdapterTest() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); XMLReaderAdapter xmlReaderAdapter = new XMLReaderAdapter(xmlReader); @@ -151,129 +147,111 @@ public class ParserAdapterTest { /** * parserAdapter.getFeature(NAMESPACES) returns true be default. + * + * @exception Exception If any errors occur. */ @Test - public void getFeature01() { - try { - assertTrue(parserAdapter.getFeature(NAMESPACES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void getFeature01() throws Exception { + assertTrue(parserAdapter.getFeature(NAMESPACES)); } /** * parserAdapter.getFeature(NAMESPACE_PREFIXES) returns true be default. + * + * @exception Exception If any errors occur. */ @Test - public void getFeature02() { - try { - assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void getFeature02() throws Exception { + assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); } /** * SAXNotRecognizedException thrown when feature name is not known one. - * @throws org.xml.sax.SAXNotRecognizedException expected Exception + * + * @exception Exception If any errors occur. */ @Test(expectedExceptions = SAXNotRecognizedException.class) - public void getFeature03() throws SAXNotRecognizedException { - try { - parserAdapter.getFeature("no-meaning-feature"); - } catch (SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void getFeature03() throws Exception { + parserAdapter.getFeature("no-meaning-feature"); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature01() { - try { - parserAdapter.setFeature(NAMESPACES, false); - assertFalse(parserAdapter.getFeature(NAMESPACES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature01() throws Exception { + parserAdapter.setFeature(NAMESPACES, false); + assertFalse(parserAdapter.getFeature(NAMESPACES)); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature02() { - try { - parserAdapter.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature02() throws Exception { + parserAdapter.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature03() { - try { - parserAdapter.setFeature(NAMESPACES, true); - assertTrue(parserAdapter.getFeature(NAMESPACES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature03() throws Exception { + parserAdapter.setFeature(NAMESPACES, true); + assertTrue(parserAdapter.getFeature(NAMESPACES)); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature04() { - try { - parserAdapter.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(parserAdapter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature04() throws Exception { + parserAdapter.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(parserAdapter.getFeature(NAMESPACE_PREFIXES)); } /** * NPE expected when parsing a null object by ParserAdapter. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = NullPointerException.class) - public void parse01() { - try { - parserAdapter.parse((InputSource)null); - } catch (IOException | SAXException ex) { - failUnexpected(ex); - } + public void parse01() throws Exception { + parserAdapter.parse((InputSource)null); } /** * SAXException expected when parsing a wrong-formatter XML with ParserAdapter. - * @throws org.xml.sax.SAXException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class) - public void parse02() throws SAXException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class) + public void parse02() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")) { InputSource is = new InputSource(fis); parserAdapter.parse(is); - } catch (IOException ex) { - failUnexpected(ex); } } /** * Parse a well-formatter XML with ParserAdapter. + * + * @throws Exception If any errors occur. */ - @Test - public void parse03() { + @Test(groups = {"readLocalFiles"}) + public void parse03() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "correct.xml")) { InputSource is = new InputSource(fis); parserAdapter.parse(is); - } catch (IOException | SAXException ex) { - failUnexpected(ex); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ResolverTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ResolverTest.java index 3215b7eec48..38cece57424 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ResolverTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,21 +26,16 @@ import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -48,12 +43,14 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * Entity resolver should be invoked in XML parse. This test verifies parsing * process by checking the output with golden file. */ -public class ResolverTest { +public class ResolverTest extends JAXPFileBaseTest { /** * Unit test for entityResolver setter. + * + * @throws Exception If any errors occur. */ - public void testResolver() { - String outputFile = CLASS_DIR + "EntityResolver.out"; + public void testResolver() throws Exception { + String outputFile = USER_DIR + "EntityResolver.out"; String goldFile = GOLDEN_DIR + "EntityResolverGF.out"; String xmlFile = XML_DIR + "publish.xml"; @@ -64,23 +61,8 @@ public class ResolverTest { xmlReader.setEntityResolver(eResolver); InputSource is = new InputSource(instream); xmlReader.parse(is); - } catch(IOException | SAXException | ParserConfigurationException ex ) { - failUnexpected(ex); - } - // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/SAXParserNSTableTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/SAXParserNSTableTest.java index f3e04f1bc79..cb748b65fc6 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/SAXParserNSTableTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/SAXParserNSTableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,20 +23,12 @@ package org.xml.sax.ptests; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -44,91 +36,64 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * This class contains the testcases to test SAXParser with regard to * Namespace Table defined at http://www.megginson.com/SAX/Java/namespaces.html */ -public class SAXParserNSTableTest { +public class SAXParserNSTableTest extends JAXPFileBaseTest { /** * namespace processing is enabled. namespace-prefix is also is enabled. * So it is a True-True combination. - * The test is to test SAXParser with these conditions + * The test is to test SAXParser with these conditions. + * + * @throws Exception If any errors occur. */ @Test - public void testWithTrueTrue() { - String outputFile = CLASS_DIR + "SPNSTableTT.out"; + public void testWithTrueTrue() throws Exception { + String outputFile = USER_DIR + "SPNSTableTT.out"; String goldFile = GOLDEN_DIR + "NSTableTTGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setFeature("http://xml.org/sax/features/namespace-prefixes", - true); - - SAXParser saxParser = spf.newSAXParser(); - saxParser.parse(new File(xmlFile), new MyNSContentHandler(outputFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", + true); + try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + spf.newSAXParser().parse(new File(xmlFile), handler); } + assertTrue(compareWithGold(goldFile, outputFile)); + } /** * namespace processing is enabled. Hence namespace-prefix is - * expected to be automaically off. So it is a True-False combination. - * The test is to test SAXParser with these conditions + * expected to be automatically off. So it is a True-False combination. + * The test is to test SAXParser with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithTrueFalse() { - String outputFile = CLASS_DIR + "SPNSTableTF.out"; + public void testWithTrueFalse() throws Exception { + String outputFile = USER_DIR + "SPNSTableTF.out"; String goldFile = GOLDEN_DIR + "NSTableTFGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - saxParser.parse(new File(xmlFile), new MyNSContentHandler(outputFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + spf.newSAXParser().parse(new File(xmlFile), handler); } + assertTrue(compareWithGold(goldFile, outputFile)); } /** * namespace processing is not enabled. Hence namespace-prefix is - * expected to be automaically on. So it is a False-True combination. - * The test is to test SAXParser with these conditions + * expected to be automatically on. So it is a False-True combination. + * The test is to test SAXParser with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithFalseTrue() { - String outputFile = CLASS_DIR + "SPNSTableFT.out"; + public void testWithFalseTrue() throws Exception { + String outputFile = USER_DIR + "SPNSTableFT.out"; String goldFile = GOLDEN_DIR + "NSTableFTGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - saxParser.parse(new File(xmlFile), new MyNSContentHandler(outputFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + spf.newSAXParser().parse(new File(xmlFile), handler); } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterCBTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterCBTest.java index ccc6e81781d..0d8fba825fd 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterCBTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterCBTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -26,14 +26,10 @@ import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.xml.sax.Attributes; import org.xml.sax.InputSource; @@ -42,7 +38,6 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -50,45 +45,34 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * Set parent of XMLFilter to XMLReader. Parsing on XML file will invoke XMLFilter * to write to output file. Test verifies output is same as the golden file. */ -public class XMLFilterCBTest { - public void testXMLFilterCB() { - String outputFile = CLASS_DIR + "XMLFilter.out"; +public class XMLFilterCBTest extends JAXPFileBaseTest { + /** + * Test XMLFilter working with XML reader. + * + * @throws Exception If any errors occur. + */ + public void testXMLFilterCB() throws Exception { + String outputFile = USER_DIR + "XMLFilter.out"; String goldFile = GOLDEN_DIR + "XMLFilterGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try (FileInputStream fis = new FileInputStream(xmlFile)){ + try (FileInputStream fis = new FileInputStream(xmlFile); + MyXMLFilter myXmlFilter = new MyXMLFilter(outputFile)){ SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - MyXMLFilter myXmlFilter = new MyXMLFilter(outputFile); myXmlFilter.setParent(xmlReader); - InputSource is = new InputSource(fis); - myXmlFilter.parse(is); - } catch( SAXException | IOException | ParserConfigurationException ex) { - failUnexpected(ex); + myXmlFilter.parse(new InputSource(fis)); } // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + assertTrue(compareWithGold(goldFile, outputFile)); } } /** * Writer XMLFiler which write all tags to output file when event happens. */ -class MyXMLFilter extends XMLFilterImpl{ +class MyXMLFilter extends XMLFilterImpl implements AutoCloseable { /** * FileWriter to write string to output file. */ @@ -278,4 +262,14 @@ class MyXMLFilter extends XMLFilterImpl{ throw new SAXException(ex); } } + + /** + * Close writer handler. + * @throws IOException if any I/O error when close writer handler. + */ + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterTest.java index bb80d6b895a..52a91ce4f3e 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,18 +23,14 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -42,7 +38,7 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; /** * Unit test for XMLFilter. */ -public class XMLFilterTest { +public class XMLFilterTest extends JAXPFileReadOnlyBaseTest { /** * name spaces constant. */ @@ -129,139 +125,114 @@ public class XMLFilterTest { /** * By default true is expected get namespaces feature. - * @throws SAXException + * + * @throws Exception If any errors occur. */ @Test - public void getFeature01() throws SAXException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + public void getFeature01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - assertTrue(xmlFilter.getFeature(NAMESPACES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(xmlReader); + assertTrue(xmlFilter.getFeature(NAMESPACES)); } /** * By default false is expected get namespaces-prefix feature. + * + * @throws Exception If any errors occur. */ @Test - public void getFeature02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void getFeature02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(spf.newSAXParser().getXMLReader()); + assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); } /** * SAXNotRecognizedException is expected when get a feature by an invalid * feature name. - * @throws org.xml.sax.SAXNotRecognizedException If the feature - * value can't be assigned or retrieved from the parent. - * @throws org.xml.sax.SAXNotSupportedException When the - * parent recognizes the feature name but - * cannot determine its value at this time. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotRecognizedException.class) - public void getFeature03() throws SAXNotRecognizedException, - SAXNotSupportedException { + public void getFeature03() throws Exception { new XMLFilterImpl().getFeature("no-meaning-feature"); } /** * Set namespaces feature to a value to XMLFilter. it's expected same when * obtain it again. + * + * @throws Exception If any errors occur. */ @Test - public void setFeature01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + public void setFeature01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - xmlFilter.setFeature(NAMESPACES, false); - assertFalse(xmlFilter.getFeature(NAMESPACES)); - xmlFilter.setFeature(NAMESPACES, true); - assertTrue(xmlFilter.getFeature(NAMESPACES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(spf.newSAXParser().getXMLReader()); + xmlFilter.setFeature(NAMESPACES, false); + assertFalse(xmlFilter.getFeature(NAMESPACES)); + xmlFilter.setFeature(NAMESPACES, true); + assertTrue(xmlFilter.getFeature(NAMESPACES)); } /** * Set namespaces-prefix feature to a value to XMLFilter. it's expected same * when obtain it again. + * + * @throws Exception If any errors occur. */ @Test - public void setFeature02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + public void setFeature02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - xmlFilter.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); - xmlFilter.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(xmlFilter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(spf.newSAXParser().getXMLReader()); + xmlFilter.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); + xmlFilter.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(xmlFilter.getFeature(NAMESPACE_PREFIXES)); } /** * NullPointerException is expected when parse a null InputSource. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = NullPointerException.class) - public void parse01() { - try { - new XMLFilterImpl().parse((InputSource)null); - } catch (IOException | SAXException ex) { - failUnexpected(ex); - } + public void parse01() throws Exception { + new XMLFilterImpl().parse((InputSource)null); } /** * SAXException is expected when parsing a invalid formatted XML file. - * @throws org.xml.sax.SAXException when parse a incorrect formatted XML - * file. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void parse02() throws SAXException { - XMLFilterImpl xmlFilter = new XMLFilterImpl(); + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void parse02() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")) { - InputSource is = new InputSource(fis); - xmlFilter.parse(is); - } catch (IOException ex) { - failUnexpected(ex); + new XMLFilterImpl().parse(new InputSource(fis)); } } /** * No exception when parse a normal XML file. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void parse03() { - XMLFilterImpl xmlFilter = new XMLFilterImpl(); + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void parse03() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "correct2.xml")) { - InputSource is = new InputSource(fis); - xmlFilter.parse(is); - } catch (IOException | SAXException ex) { - failUnexpected(ex); + new XMLFilterImpl().parse(new InputSource(fis)); } } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderAdapterTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderAdapterTest.java index 364656fcdc9..fff624d1f34 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderAdapterTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderAdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,10 +23,9 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; +import java.io.FilePermission; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; @@ -40,7 +39,7 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; /** * Class containing the test cases for XMLReaderAdapter API */ -public class XMLReaderAdapterTest { +public class XMLReaderAdapterTest extends JAXPBaseTest { /** * http://xml.org/sax/features/namespace-prefixes property name. */ @@ -58,60 +57,51 @@ public class XMLReaderAdapterTest { } /** - * To test the constructor that uses XMLReader + * To test the constructor that uses XMLReader. + * + * @throws Exception If any errors occur. */ @Test - public void constructor02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - assertNotNull(new XMLReaderAdapter(xmlReader)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void constructor02() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + assertNotNull(new XMLReaderAdapter(xmlReader)); } /** * To test the parse method. The specification says that this method * will throw an exception if the embedded XMLReader does not support * the http://xml.org/sax/features/namespace-prefixes property. + * + * @throws Exception If any errors occur. */ @Test - public void nsfeature01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { - xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); - } - - assertTrue(xmlReader.getFeature(NM_PREFIXES_PROPERTY)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); + public void nsfeature01() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { + xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); } + assertTrue(xmlReader.getFeature(NM_PREFIXES_PROPERTY)); } /** * To test the parse method. The specification says that this method * will throw an exception if the embedded XMLReader does not support * the http://xml.org/sax/features/namespace-prefixes property. + * + * @throws Exception If any errors occur. */ @Test - public void parse01() { + public void parse01() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read")); try (FileInputStream fis = new FileInputStream(XML_DIR + "namespace1.xml")) { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); } XMLReaderAdapter xmlRA = new XMLReaderAdapter(xmlReader); - - InputSource is = new InputSource(fis); xmlRA.setDocumentHandler(new HandlerBase()); - xmlRA.parse(is); - } catch (IOException | SAXException | ParserConfigurationException ex) { - failUnexpected(ex); + xmlRA.parse(new InputSource(fis)); } + setPermissions(); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderFactoryTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderFactoryTest.java index 8e9eae0fa76..ae5e9215625 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderFactoryTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -22,6 +22,7 @@ */ package org.xml.sax.ptests; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertNotNull; import org.testng.annotations.Test; import org.xml.sax.SAXException; @@ -30,7 +31,7 @@ import org.xml.sax.helpers.XMLReaderFactory; /** * Unit test for XMLReaderFactory.createXMLReader API. */ -public class XMLReaderFactoryTest { +public class XMLReaderFactoryTest extends JAXPBaseTest { /** * No exception expected when create XMLReader by default. * @throws org.xml.sax.SAXException when xml reader creation failed. @@ -48,12 +49,7 @@ public class XMLReaderFactoryTest { */ @Test public void createReader02() throws SAXException { - //Disable this test because this is only work for apache implementation. - /*System.setProperty("org.xml.sax.driver", - "org.apache.xerces.parsers.SAXParser"); - assertNotNull(XMLReaderFactory. - createXMLReader("org.apache.xerces.parsers.SAXParser"));*/ - System.setProperty("org.xml.sax.driver", + setSystemProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.parsers.SAXParser"); assertNotNull(XMLReaderFactory. createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser")); diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderNSTableTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderNSTableTest.java index 396e67bcf96..f9a2be0b069 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderNSTableTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderNSTableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,17 +23,14 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.XMLReader; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -41,7 +38,7 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; * Namespace Table defined at * http://www.megginson.com/SAX/Java/namespaces.html */ -public class XMLReaderNSTableTest { +public class XMLReaderNSTableTest extends JAXPFileBaseTest { /** * XML file that used to be parsed. */ @@ -55,71 +52,70 @@ public class XMLReaderNSTableTest { /** * namespace processing is enabled. namespace-prefix is also is enabled. * So it is a True-True combination. - * The test is to test XMLReader with these conditions + * The test is to test XMLReader with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithTrueTrue() { - String outputFile = CLASS_DIR + "XRNSTableTT.out"; + public void testWithTrueTrue() throws Exception { + String outputFile = USER_DIR + "XRNSTableTT.out"; String goldFile = GOLDEN_DIR + "NSTableTTGF.out"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, true); - XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, true); - - xmlReader.setContentHandler(new MyNSContentHandler(outputFile)); - xmlReader.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); + try (FileInputStream fis = new FileInputStream(xmlFile); + MyNSContentHandler handler = new MyNSContentHandler(outputFile);) { + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(fis)); } + assertTrue(compareWithGold(goldFile, outputFile)); } /** * Namespace processing is enabled. Hence namespace-prefix is - * expected to be automaically off. So it is a True-False combination. - * The test is to test XMLReader with these conditions + * expected to be automatically off. So it is a True-False combination. + * The test is to test XMLReader with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithTrueFalse() { - String outputFile = CLASS_DIR + "XRNSTableTF.out"; + public void testWithTrueFalse() throws Exception { + String outputFile = USER_DIR + "XRNSTableTF.out"; String goldFile = GOLDEN_DIR + "NSTableTFGF.out"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxParser = spf.newSAXParser(); + XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setContentHandler(new MyNSContentHandler(outputFile)); - xmlReader.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); + try (FileInputStream fis = new FileInputStream(xmlFile); + MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(fis)); } + assertTrue(compareWithGold(goldFile, outputFile)); } /** * namespace processing is not enabled. Hence namespace-prefix is * expected to be automaically on. So it is a False-True combination. - * The test is to test XMLReader with these conditions + * The test is to test XMLReader with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithFalseTrue() { - String outputFile = CLASS_DIR + "XRNSTableFT.out"; + public void testWithFalseTrue()throws Exception { + String outputFile = USER_DIR + "XRNSTableFT.out"; String goldFile = GOLDEN_DIR + "NSTableFTGF.out"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - - xmlReader.setContentHandler(new MyNSContentHandler(outputFile)); - xmlReader.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + try (FileInputStream fis = new FileInputStream(xmlFile); + MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(fis)); } + assertTrue(compareWithGold(goldFile, outputFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderTest.java b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderTest.java index 1ec7dd64275..c01986f4299 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderTest.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,10 +23,9 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @@ -45,42 +44,43 @@ import static org.xml.sax.ptests.SAXTestConst.XML_DIR; /** * Class containing the test cases for SAXParser API */ -public class XMLReaderTest { +public class XMLReaderTest extends JAXPFileReadOnlyBaseTest { + /** * XML namespaces. */ - private static final String NAMESPACES = - "http://xml.org/sax/features/namespaces"; + private static final String NAMESPACES + = "http://xml.org/sax/features/namespaces"; /** * XML namespaces prefixes. */ - private static final String NAMESPACE_PREFIXES = - "http://xml.org/sax/features/namespace-prefixes"; + private static final String NAMESPACE_PREFIXES + = "http://xml.org/sax/features/namespace-prefixes"; /** * A string intern name. */ - private static final String STRING_INTERNING = - "http://xml.org/sax/features/string-interning"; + private static final String STRING_INTERNING + = "http://xml.org/sax/features/string-interning"; /** * Validation name. */ - private static final String VALIDATION = - "http://xml.org/sax/features/validation"; + private static final String VALIDATION + = "http://xml.org/sax/features/validation"; /** * A general external entities name */ - private static final String EXTERNAL_G_ENTITIES = - "http://xml.org/sax/features/external-general-entities"; + private static final String EXTERNAL_G_ENTITIES + = "http://xml.org/sax/features/external-general-entities"; /** * A external parameter entities name */ - private static final String EXTERNAL_P_ENTITIES = - "http://xml.org/sax/features/external-parameter-entities"; + private static final String EXTERNAL_P_ENTITIES + = "http://xml.org/sax/features/external-parameter-entities"; /** * XML DOM node name. @@ -95,526 +95,444 @@ public class XMLReaderTest { /** * Declare handler name */ - private static final String DECL_HANDLER = - "http://xml.org/sax/properties/declaration-handler"; + private static final String DECL_HANDLER + = "http://xml.org/sax/properties/declaration-handler"; /** * Lexical handler name */ - private static final String LEXICAL_HANDLER = - "http://xml.org/sax/properties/lexical-handler"; + private static final String LEXICAL_HANDLER + = "http://xml.org/sax/properties/lexical-handler"; /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespaces feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespaces feature names. This test case is + * to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNS01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertFalse(xmlReader.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNS01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertFalse(xmlReader.getFeature(NAMESPACES)); } /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespaces feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespaces feature names. This test case is + * to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNS02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNS02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(NAMESPACES)); } /** * Obtain http://xml.org/sax/features/namespaces feature name after it's * just set. Expect it's same as set value. + * + * @throws Exception If any errors occur. */ @Test - public void featureNS03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(NAMESPACES, true); - assertTrue(xmlReader.getFeature(NAMESPACES)); - xmlReader.setFeature(NAMESPACES, false); - assertFalse(xmlReader.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNS03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACES, true); + assertTrue(xmlReader.getFeature(NAMESPACES)); + xmlReader.setFeature(NAMESPACES, false); + assertFalse(xmlReader.getFeature(NAMESPACES)); } /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespace-prefixes feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespace-prefixes feature names. This test + * case is to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNSP01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNSP01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); } /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespace-prefixes feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespace-prefixes feature names. This test + * case is to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNSP02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNSP02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); } /** * Obtain http://xml.org/sax/features/namespaces-prefixes feature name after * it's just set. Expect it's same as set value. + * + * @throws Exception If any errors occur. */ @Test - public void featureNSP03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - xmlReader.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNSP03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); + xmlReader.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); } /** * getFeature returns true if a feature has not been preset when namespace * awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureSI01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(STRING_INTERNING)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureSI01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(STRING_INTERNING)); } /** * getFeature with validation feature name returns the value that * setValidation set. + * + * @throws Exception If any errors occur. */ @Test - public void featureV01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); - spf.setValidating(true); - assertTrue(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureV01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); + spf.setValidating(true); + assertTrue(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); } /** - * getFeature returns the value that a feature has been preset as when + * getFeature returns the value that a feature has been preset as when * namespace awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureV02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + public void featureV02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(VALIDATION, true); - assertTrue(xmlReader.getFeature(VALIDATION)); - - xmlReader.setFeature(VALIDATION, false); - assertFalse(xmlReader.getFeature(VALIDATION)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + xmlReader.setFeature(VALIDATION, true); + assertTrue(xmlReader.getFeature(VALIDATION)); + xmlReader.setFeature(VALIDATION, false); + assertFalse(xmlReader.getFeature(VALIDATION)); } /** * getFeature returns true if a feature has not been preset when namespace * awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEGE01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEGE01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); } /** - * getFeature returns false if a feature has been preset as false when + * getFeature returns false if a feature has been preset as false when * namespace awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEGE02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(EXTERNAL_G_ENTITIES, false); - assertFalse(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEGE02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(EXTERNAL_G_ENTITIES, false); + assertFalse(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); } /** * getFeature returns true if a feature has not been preset when namespace * awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEPE01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEPE01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); } /** - * getFeature returns false if a feature has been preset as false when + * getFeature returns false if a feature has been preset as false when * namespace awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEPE02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(EXTERNAL_P_ENTITIES, false); - assertFalse(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEPE02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(EXTERNAL_P_ENTITIES, false); + assertFalse(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); } /** * getFeature with a unknown feature name throws SAXNotRecognizedException. - * @throws SAXNotRecognizedException If the feature value can't be assigned - * or retrieved. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotRecognizedException.class) - public void featureNE01() throws SAXNotRecognizedException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - boolean noMeaningFeature = xmlReader.getFeature("no-meaning-feature"); - } catch(SAXNotRecognizedException ex) { - throw ex; - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureNE01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().getFeature("no-meaning-feature"); } /** * No exception expected when set entity resolver as simple entity resolver. + * + * @throws Exception If any errors occur. */ @Test - public void entity01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlReader.setEntityResolver(xmlFilter); - assertNotNull(xmlReader.getEntityResolver()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void entity01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlReader.setEntityResolver(xmlFilter); + assertEquals(xmlReader.getEntityResolver(), xmlFilter); } /** * No NPE expected when set entity resolver as null. + * + * @throws Exception If any errors occur. */ @Test - public void entity02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setEntityResolver(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void entity02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().setEntityResolver(null); } /** * No exception expected when set DTD handler as simple DTD handler. + * + * @throws Exception If any errors occur. */ @Test - public void dtdhandler01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlReader.setDTDHandler(xmlFilter); - assertNotNull(xmlReader.getDTDHandler()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void dtdhandler01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlReader.setDTDHandler(xmlFilter); + assertEquals(xmlReader.getDTDHandler(), xmlFilter); } /** * No NPE expected when set DTD handler as null. + * + * @throws Exception If any errors occur. */ @Test - public void dtdhandler02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setDTDHandler(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void dtdhandler02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().setDTDHandler(null); } /** * No exception expected when set content handler as simple content handler. + * + * @throws Exception If any errors occur. */ @Test - public void contenthandler01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlReader.setContentHandler(xmlFilter); - assertNotNull(xmlReader.getContentHandler()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void contenthandler01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlReader.setContentHandler(xmlFilter); + assertEquals(xmlReader.getContentHandler(), xmlFilter); } /** * No NPE expected when set content handler as null. + * + * @throws Exception If any errors occur. */ @Test - public void contenthandler02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setContentHandler(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void contenthandler02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().setContentHandler(null); } /** * No exception expected when set content handler as simple error handler. + * + * @throws Exception If any errors occur. */ @Test - public void errorhandler01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setErrorHandler(new XMLFilterImpl()); - assertNotNull(xmlReader.getErrorHandler()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void errorhandler01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setErrorHandler(new XMLFilterImpl()); + assertNotNull(xmlReader.getErrorHandler()); } /** * No NPE expected when set error handler as null. + * + * @throws Exception If any errors occur. */ @Test - public void errorhandler02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setErrorHandler(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void errorhandler02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setErrorHandler(null); } /** * Parse a null input source throw NPE. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = NullPointerException.class) - public void parse01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.parse((InputSource)null); - } catch (SAXException | ParserConfigurationException | IOException ex) { - failUnexpected(ex); - } + public void parse01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().parse((InputSource) null); } /** * Unit test for parse a error-formatted file. SAXException is expected. - * @throws org.xml.sax.SAXException parsing failed. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class) - public void parse02() throws SAXException { - try (FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")){ + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class) + public void parse02() throws Exception { + try (FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - InputSource is = new InputSource(fis); - xmlReader.parse(is); - } catch (ParserConfigurationException | IOException ex) { - failUnexpected(ex); + spf.newSAXParser().getXMLReader().parse(new InputSource(fis)); } } /** * Unit test for parse a well-formatted file. No exception is expected. + * + * @throws Exception If any errors occur. */ - @Test - public void parse03(){ + @Test(groups = {"readLocalFiles"}) + public void parse03() throws Exception { try (FileInputStream fis = new FileInputStream(XML_DIR + "correct2.xml")) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - InputSource is = new InputSource(fis); - xmlReader.parse(is); - } catch (IOException | SAXException | ParserConfigurationException ex) { - failUnexpected(ex); + spf.newSAXParser().getXMLReader().parse(new InputSource(fis)); } } /** - * Modified by IBM - * Xerces does not support this feature and it is not mandatory - * @throws org.xml.sax.SAXNotSupportedException + * Modified by IBM Xerces does not support this feature and it is not + * mandatory. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotSupportedException.class) - public void xrProperty01() throws SAXNotSupportedException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.getProperty(XML_STRING); - } catch(SAXNotSupportedException ex) { - throw ex; - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.getProperty(XML_STRING); } /** * SAXNotSupportedException thrown if property name is known but no value * assigned to this property. - * @throws org.xml.sax.SAXNotSupportedException when XMLReader recognizes - * the property name but cannot determine its value at this time. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotSupportedException.class) - public void xrProperty02() throws SAXNotSupportedException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertNull(xmlReader.getProperty(DOM_NODE)); - } catch (SAXNotSupportedException ex) { - throw ex; - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertNull(xmlReader.getProperty(DOM_NODE)); } - /** * XMLReader.getProperty returns null if LEXICAL_HANDLER wasn't set. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertNull(xmlReader.getProperty(LEXICAL_HANDLER)); - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertNull(xmlReader.getProperty(LEXICAL_HANDLER)); } /** * XMLReader.getProperty returns null if DECL_HANDLER wasn't set. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertNull(xmlReader.getProperty(DECL_HANDLER)); - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty04() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertNull(xmlReader.getProperty(DECL_HANDLER)); } /** * XMLReader.setProperty/getProperty for LEXICAL_HANDLER unit test. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty05() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); - xmlReader.setProperty(LEXICAL_HANDLER, myLexicalHandler); - assertNotNull(xmlReader.getProperty(LEXICAL_HANDLER)); - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty05() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); + xmlReader.setProperty(LEXICAL_HANDLER, myLexicalHandler); + assertNotNull(xmlReader.getProperty(LEXICAL_HANDLER)); } /** * XMLReader.setProperty/getProperty for DECL_HANDLER unit test. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty06() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - MyDeclHandler myDeclHandler = new MyDeclHandler(); - xmlReader.setProperty(DECL_HANDLER, myDeclHandler); - assertNotNull(xmlReader.getProperty(DECL_HANDLER)); - } catch (ParserConfigurationException | SAXException ex){ - failUnexpected(ex); - } + public void xrProperty06() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + MyDeclHandler myDeclHandler = new MyDeclHandler(); + xmlReader.setProperty(DECL_HANDLER, myDeclHandler); + assertNotNull(xmlReader.getProperty(DECL_HANDLER)); } } @@ -622,6 +540,7 @@ public class XMLReaderTest { * Simple LexicalHandler that skips every lexical event. */ class MyLexicalHandler implements LexicalHandler { + /** * Report an XML comment anywhere in the document. * @@ -667,8 +586,10 @@ class MyLexicalHandler implements LexicalHandler { * Report the start of DTD declarations, if any. * * @param name The document type name. - * @param publicId The declared public identifier for the external DTD subset. - * @param systemId The declared system identifier for the external DTD subset. + * @param publicId The declared public identifier for the external DTD + * subset. + * @param systemId The declared system identifier for the external DTD + * subset. */ @Override public void startDTD(String name, String publicId, String systemId) { @@ -688,16 +609,17 @@ class MyLexicalHandler implements LexicalHandler { * Simple DeclHandler that skips every DTD declaration event. */ class MyDeclHandler implements DeclHandler { + /** * Report an attribute type declaration. + * * @param eName The name of the associated element. * @param aName The name of the attribute. * @param type A string representing the attribute type. * @param mode A string representing the attribute defaulting mode - * ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if - * none of these applies. - * @param value A string representing the attribute's default value, - * or null if there is none. + * ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if none of these applies. + * @param value A string representing the attribute's default value, or null + * if there is none. */ @Override public void attributeDecl(String eName, String aName, String type, @@ -706,6 +628,7 @@ class MyDeclHandler implements DeclHandler { /** * Report an element type declaration. + * * @param name The element type name. * @param model The content model as a normalized string. */ @@ -715,10 +638,11 @@ class MyDeclHandler implements DeclHandler { /** * Report a parsed external entity declaration. - * @param name The name of the entity. If it is a parameter - * entity, the name will begin with '%'. - * @param publicId The entity's public identifier, or null if none - * was given. + * + * @param name The name of the entity. If it is a parameter entity, the name + * will begin with '%'. + * @param publicId The entity's public identifier, or null if none was + * given. * @param systemId The entity's system identifier. */ @Override @@ -728,8 +652,9 @@ class MyDeclHandler implements DeclHandler { /** * Report an internal entity declaration. - * @param name The name of the entity. If it is a parameter - * entity, the name will begin with '%'. + * + * @param name The name of the entity. If it is a parameter entity, the name + * will begin with '%'. * @param value The replacement text of the entity. */ @Override diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java b/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java index b21f7f889dc..005828687f5 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java +++ b/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -27,23 +27,18 @@ import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; - import java.io.File; import java.io.FileInputStream; -import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.nio.file.Paths; import java.util.GregorianCalendar; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; - -import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.dom.DOMResult; @@ -51,8 +46,8 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static jaxp.library.JAXPTestUtilities.bomStream; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import org.testng.annotations.Test; import org.w3c.dom.Attr; import org.w3c.dom.DOMConfiguration; @@ -63,173 +58,160 @@ import org.w3c.dom.TypeInfo; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; -import org.xml.sax.SAXException; import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS; import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is the user controller class for the Auction portal HiBid.com. */ -public class AuctionController { +public class AuctionController extends JAXPFileReadOnlyBaseTest { /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927 * DOMConfiguration.setParameter("well-formed",true) throws an exception. + * + * @throws Exception If any errors occur. */ - @Test - public void testCreateNewItem2Sell() { + @Test(groups = {"readLocalFiles"}) + public void testCreateNewItem2Sell() throws Exception { String xmlFile = XML_DIR + "novelsInvalid.xml"; - try { - Document document = DocumentBuilderFactory.newInstance() - .newDocumentBuilder().parse(xmlFile); + Document document = DocumentBuilderFactory.newInstance() + .newDocumentBuilder().parse(xmlFile); - document.getDomConfig().setParameter("well-formed", true); + document.getDomConfig().setParameter("well-formed", true); - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); - MyDOMOutput domOutput = new MyDOMOutput(); - domOutput.setByteStream(System.out); - LSSerializer writer = impl.createLSSerializer(); - writer.write(document, domOutput); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); - } + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + MyDOMOutput domOutput = new MyDOMOutput(); + domOutput.setByteStream(System.out); + LSSerializer writer = impl.createLSSerializer(); + writer.write(document, domOutput); } /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132 * test throws DOM Level 1 node error. + * + * @throws Exception If any errors occur. */ - @Test - public void testCreateNewItem2SellRetry() { + @Test(groups = {"readLocalFiles"}) + public void testCreateNewItem2SellRetry() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - Document document = dbf.newDocumentBuilder().parse(xmlFile); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + Document document = dbf.newDocumentBuilder().parse(xmlFile); - DOMConfiguration domConfig = document.getDomConfig(); - MyDOMErrorHandler errHandler = new MyDOMErrorHandler(); - domConfig.setParameter("error-handler", errHandler); + DOMConfiguration domConfig = document.getDomConfig(); + MyDOMErrorHandler errHandler = new MyDOMErrorHandler(); + domConfig.setParameter("error-handler", errHandler); - DOMImplementationLS impl = - (DOMImplementationLS) DOMImplementationRegistry.newInstance() - .getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - MyDOMOutput domoutput = new MyDOMOutput(); + DOMImplementationLS impl = + (DOMImplementationLS) DOMImplementationRegistry.newInstance() + .getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); + MyDOMOutput domoutput = new MyDOMOutput(); - domoutput.setByteStream(System.out); - writer.write(document, domoutput); + domoutput.setByteStream(System.out); + writer.write(document, domoutput); - document.normalizeDocument(); - writer.write(document, domoutput); - assertFalse(errHandler.isError()); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); - } + document.normalizeDocument(); + writer.write(document, domoutput); + assertFalse(errHandler.isError()); } /** * Check if setting the attribute to be of type ID works. This will affect * the Attr.isID method according to the spec. + * + * @throws Exception If any errors occur. */ - @Test - public void testCreateID() { + @Test(groups = {"readLocalFiles"}) + public void testCreateID() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); - Document document = dbf.newDocumentBuilder().parse(xmlFile); - Element account = (Element)document - .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); + Document document = dbf.newDocumentBuilder().parse(xmlFile); + Element account = (Element)document + .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); - account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true); - Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); - assertTrue(aID.isId()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true); + Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); + assertTrue(aID.isId()); } /** * Check the user data on the node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckingUserData() { + @Test(groups = {"readLocalFiles"}) + public void testCheckingUserData() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(xmlFile); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(xmlFile); - Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); - assertEquals(account.getNodeName(), "acc:Account"); - Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); - assertEquals(firstName.getNodeName(), "FirstName"); + Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); + assertEquals(account.getNodeName(), "acc:Account"); + Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); + assertEquals(firstName.getNodeName(), "FirstName"); - Document doc1 = docBuilder.newDocument(); - Element someName = doc1.createElement("newelem"); + Document doc1 = docBuilder.newDocument(); + Element someName = doc1.createElement("newelem"); - someName.setUserData("mykey", "dd", - (operation, key, data, src, dst) -> { - System.err.println("In UserDataHandler" + key); - System.out.println("In UserDataHandler"); - }); - Element impAccount = (Element)document.importNode(someName, true); - assertEquals(impAccount.getNodeName(), "newelem"); - document.normalizeDocument(); - String data = (someName.getUserData("mykey")).toString(); - assertEquals(data, "dd"); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + someName.setUserData("mykey", "dd", + (operation, key, data, src, dst) -> { + System.err.println("In UserDataHandler" + key); + System.out.println("In UserDataHandler"); + }); + Element impAccount = (Element)document.importNode(someName, true); + assertEquals(impAccount.getNodeName(), "newelem"); + document.normalizeDocument(); + String data = (someName.getUserData("mykey")).toString(); + assertEquals(data, "dd"); } /** * Check the UTF-16 XMLEncoding xml file. + * + * @throws Exception If any errors occur. * @see movies.xml */ - @Test - public void testCheckingEncoding() { + @Test(groups = {"readLocalFiles"}) + public void testCheckingEncoding() throws Exception { // Note since movies.xml is UTF-16 encoding. We're not using stanard XML // file suffix. String xmlFile = XML_DIR + "movies.xml.data"; - //try (FileInputStream is = new FileInputStream(xmlFile)) { - try { + try (InputStream source = bomStream("UTF-16", xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - InputStream source = bomStream("UTF-16", xmlFile); Document document = dbf.newDocumentBuilder().parse(source); assertEquals(document.getXmlEncoding(), "UTF-16"); assertEquals(document.getXmlStandalone(), true); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); } } /** * Check validation API features. A schema which is including in Bug 4909119 * used to be testing for the functionalities. + * + * @throws Exception If any errors occur. * @see userDetails.xsd */ - @Test - public void testGetOwnerInfo() { + @Test(groups = {"readLocalFiles"}) + public void testGetOwnerInfo() throws Exception { String schemaFile = XML_DIR + "userDetails.xsd"; String xmlFile = XML_DIR + "userDetails.xml"; - try { + try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); @@ -244,27 +226,27 @@ public class AuctionController { DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(eh); - Document document = docBuilder.parse(new FileInputStream(xmlFile)); + Document document = docBuilder.parse(fis); DOMResult dResult = new DOMResult(); DOMSource domSource = new DOMSource(document); validator.validate(domSource, dResult); assertFalse(eh.isAnyError()); - } catch (SAXException | ParserConfigurationException | IOException e) { - failUnexpected(e); } } /** * Check grammar caching with imported schemas. + * + * @throws Exception If any errors occur. * @see coins.xsd * @see coinsImportMe.xsd */ - @Test - public void testGetOwnerItemList() { + @Test(groups = {"readLocalFiles"}) + public void testGetOwnerItemList() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; - try { + try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); @@ -278,11 +260,9 @@ public class AuctionController { validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new FileInputStream(xmlFile)); + Document document = docBuilder.parse(fis); validator.validate(new DOMSource(document), new DOMResult()); assertFalse(eh.isAnyError()); - } catch (SAXException | ParserConfigurationException | IOException e) { - failUnexpected(e); } } @@ -291,96 +271,88 @@ public class AuctionController { * Check for the same imported schemas but will use SAXParserFactory and try * parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this * test. + * + * @throws Exception If any errors occur. * @see coins.xsd * @see coinsImportMe.xsd */ - @Test - public void testGetOwnerItemList1() { + @Test(groups = {"readLocalFiles"}) + public void testGetOwnerItemList1() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(true); - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setValidating(true); + SAXParser sp = spf.newSAXParser(); + sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile); - SAXParser sp = spf.newSAXParser(); - sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile); - - MyErrorHandler eh = new MyErrorHandler(); - sp.parse(new File(xmlFile), eh); - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + MyErrorHandler eh = new MyErrorHandler(); + sp.parse(new File(xmlFile), eh); + assertFalse(eh.isAnyError()); } /** * Check usage of javax.xml.datatype.Duration class. + * + * @throws Exception If any errors occur. */ - @Test - public void testGetItemDuration() { + @Test(groups = {"readLocalFiles"}) + public void testGetItemDuration() throws Exception { String xmlFile = XML_DIR + "itemsDuration.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - Document document = dbf.newDocumentBuilder().parse(xmlFile); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + Document document = dbf.newDocumentBuilder().parse(xmlFile); - Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0); + Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0); - NodeList childList = durationElement.getChildNodes(); + NodeList childList = durationElement.getChildNodes(); - for (int i = 0; i < childList.getLength(); i++) { - System.out.println("child " + i + childList.item(i)); - } - - Duration duration = DatatypeFactory.newInstance().newDuration("P365D"); - Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue()); - assertFalse(sellDuration.isShorterThan(duration)); - assertFalse(sellDuration.isLongerThan(duration)); - assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365)); - assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration); - - Duration myDuration = sellDuration.add(duration); - assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)), - DatatypeFactory.newInstance().newDuration("P730D")); - } catch (ParserConfigurationException | DatatypeConfigurationException - | SAXException | IOException e) { - failUnexpected(e); + for (int i = 0; i < childList.getLength(); i++) { + System.out.println("child " + i + childList.item(i)); } + + Duration duration = DatatypeFactory.newInstance().newDuration("P365D"); + Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue()); + assertFalse(sellDuration.isShorterThan(duration)); + assertFalse(sellDuration.isLongerThan(duration)); + assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365)); + assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration); + + Duration myDuration = sellDuration.add(duration); + assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)), + DatatypeFactory.newInstance().newDuration("P730D")); } /** * Check usage of TypeInfo interface introduced in DOM L3. + * + * @throws Exception If any errors occur. */ - @Test - public void testGetTypeInfo() { + @Test(groups = {"readLocalFiles"}) + public void testGetTypeInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - docBuilder.setErrorHandler(new MyErrorHandler()); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + docBuilder.setErrorHandler(new MyErrorHandler()); - Document document = docBuilder.parse(xmlFile); - Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); - TypeInfo typeInfo = userId.getSchemaTypeInfo(); - assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); - assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); + Document document = docBuilder.parse(xmlFile); + Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); + TypeInfo typeInfo = userId.getSchemaTypeInfo(); + assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); + assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); - Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); - TypeInfo roletypeInfo = role.getSchemaTypeInfo(); - assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); - assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); + TypeInfo roletypeInfo = role.getSchemaTypeInfo(); + assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); + assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionItemRepository.java b/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionItemRepository.java index ed03442ce9e..8fe1efa3598 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionItemRepository.java +++ b/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/AuctionItemRepository.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,39 +30,31 @@ import static org.testng.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; +import java.io.FilePermission; import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareDocumentWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; - import org.testng.annotations.Test; import org.w3c.dom.Document; -import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; -import static test.auctionportal.HiBidConstants.CLASS_DIR; import static test.auctionportal.HiBidConstants.GOLDEN_DIR; import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is a test class for the Auction portal HiBid.com. */ -public class AuctionItemRepository { +public class AuctionItemRepository extends JAXPFileBaseTest { /** * XML file for parsing. */ @@ -78,94 +70,92 @@ public class AuctionItemRepository { * document that has more than two levels of entity expansion is parsed or * not. Previous system property was changed to jdk.xml.entityExpansionLimit * see http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html. + * + * @throws Exception If any errors occur. */ @Test - public void testEntityExpansionSAXPos() { - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - // Secure processing will limit XML processing to conform to - // implementation limits. - factory.setFeature(FEATURE_SECURE_PROCESSING, true); - // Set entityExpansionLimit as 2 should expect fatalError - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(128000)); - SAXParser parser = factory.newSAXParser(); + public void testEntityExpansionSAXPos() throws Exception { + SAXParserFactory factory = SAXParserFactory.newInstance(); + // Secure processing will limit XML processing to conform to + // implementation limits. + factory.setFeature(FEATURE_SECURE_PROCESSING, true); + // Set entityExpansionLimit as 2 should expect fatalError + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(128000)); + SAXParser parser = factory.newSAXParser(); - MyErrorHandler fatalHandler = new MyErrorHandler(); - parser.parse(new File(ENTITY_XML), fatalHandler); - assertFalse(fatalHandler.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + MyErrorHandler fatalHandler = new MyErrorHandler(); + setPermissions(new FilePermission(ENTITY_XML, "read")); + parser.parse(new File(ENTITY_XML), fatalHandler); + assertFalse(fatalHandler.isAnyError()); } /** * Setting the EntityExpansion Limit to 2 and checks if the XML * document that has more than two levels of entity expansion is parsed or * not. Previous system property was changed to jdk.xml.entityExpansionLimit * see http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXParseException.class) - public void testEntityExpansionSAXNeg() throws SAXParseException { - // - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - // Secure processing will limit XML processing to conform to - // implementation limits. - factory.setFeature(FEATURE_SECURE_PROCESSING, true); - // Set entityExpansionLimit as 2 should expect SAXParseException - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); - SAXParser parser = factory.newSAXParser(); + public void testEntityExpansionSAXNeg() throws Exception { + SAXParserFactory factory = SAXParserFactory.newInstance(); + // Secure processing will limit XML processing to conform to + // implementation limits. + factory.setFeature(FEATURE_SECURE_PROCESSING, true); + // Set entityExpansionLimit as 2 should expect SAXParseException. + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); - MyErrorHandler fatalHandler = new MyErrorHandler(); - parser.parse(new File(ENTITY_XML), fatalHandler); - } catch (SAXParseException e) { - throw e; - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + SAXParser parser = factory.newSAXParser(); + MyErrorHandler fatalHandler = new MyErrorHandler(); + setPermissions(new FilePermission(ENTITY_XML, "read")); + parser.parse(new File(ENTITY_XML), fatalHandler); } /** * Testing set MaxOccursLimit to 10000 in the secure processing enabled for * SAXParserFactory. + * + * @throws Exception If any errors occur. */ @Test - public void testMaxOccurLimitPos() { + public void testMaxOccurLimitPos() throws Exception { String schema_file = XML_DIR + "toys.xsd"; String xml_file = XML_DIR + "toys.xml"; - + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(true); + factory.setFeature(FEATURE_SECURE_PROCESSING, true); + setSystemProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000)); + SAXParser parser = factory.newSAXParser(); + parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + setPermissions(new FilePermission(XML_DIR + "-", "read")); + parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file)); try (InputStream is = new FileInputStream(xml_file)) { - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setValidating(true); - factory.setFeature(FEATURE_SECURE_PROCESSING, true); - System.setProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000)); - SAXParser parser = factory.newSAXParser(); - parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file)); MyErrorHandler eh = new MyErrorHandler(); parser.parse(is, eh); assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); } } /** * Use a DocumentBuilder to create a DOM object and see if Secure Processing * feature affects the entity expansion. + * + * @throws Exception If any errors occur. */ @Test - public void testEntityExpansionDOMPos() { + public void testEntityExpansionDOMPos() throws Exception { + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000)); + DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + dBuilder.setErrorHandler(eh); try { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000)); - DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - dBuilder.setErrorHandler(eh); + setPermissions(new FilePermission(ENTITY_XML, "read")); dBuilder.parse(ENTITY_XML); assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); + } finally { + setPermissions(); } } @@ -173,310 +163,209 @@ public class AuctionItemRepository { * Use a DocumentBuilder to create a DOM object and see how does the Secure * Processing feature and entityExpansionLimit value affects output. * Negative test that when entityExpansionLimit is too small. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXParseException.class) - public void testEntityExpansionDOMNeg() throws SAXParseException { - try { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); - DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - dBuilder.setErrorHandler(eh); - dBuilder.parse(ENTITY_XML); - } catch (SAXParseException e) { - throw e; - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } + public void testEntityExpansionDOMNeg() throws Exception { + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); + DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + dBuilder.setErrorHandler(eh); + setPermissions(new FilePermission(ENTITY_XML, "read")); + dBuilder.parse(ENTITY_XML); } /** * Test xi:include with a SAXParserFactory. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeSAXPos() { - String resultFile = CLASS_DIR + "doc_xinclude.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeSAXPos() throws Exception { + String resultFile = USER_DIR + "doc_xinclude.out"; String goldFile = GOLDEN_DIR + "doc_xincludeGold.xml"; String xmlFile = XML_DIR + "doc_xinclude.xml"; - try { - try(FileOutputStream fos = new FileOutputStream(resultFile)) { - XInclHandler xh = new XInclHandler(fos, null); - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setXIncludeAware(true); - spf.setFeature(FEATURE_NAME, true); - spf.newSAXParser().parse(new File(xmlFile), xh); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + try(FileOutputStream fos = new FileOutputStream(resultFile)) { + XInclHandler xh = new XInclHandler(fos, null); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setXIncludeAware(true); + spf.setFeature(FEATURE_NAME, true); + spf.newSAXParser().parse(new File(xmlFile), xh); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test the simple case of including a document using xi:include using a * DocumentBuilder. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeDOMPos() { - String resultFile = CLASS_DIR + "doc_xincludeDOM.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeDOMPos() throws Exception { + String resultFile = USER_DIR + "doc_xincludeDOM.out"; String goldFile = GOLDEN_DIR + "doc_xincludeGold.xml"; String xmlFile = XML_DIR + "doc_xinclude.xml"; - try { - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); - - Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); - doc.setXmlStandalone(true); - - TransformerFactory.newInstance().newTransformer(). - transform(new DOMSource(doc), new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); + Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); + doc.setXmlStandalone(true); + TransformerFactory.newInstance().newTransformer(). + transform(new DOMSource(doc), new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test the simple case of including a document using xi:include within a * xi:fallback using a DocumentBuilder. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeFallbackDOMPos() { - String resultFile = CLASS_DIR + "doc_fallbackDOM.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeFallbackDOMPos() throws Exception { + String resultFile = USER_DIR + "doc_fallbackDOM.out"; String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml"; String xmlFile = XML_DIR + "doc_fallback.xml"; - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); - Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); - doc.setXmlStandalone(true); - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(doc), new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); + doc.setXmlStandalone(true); + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(doc), new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test for xi:fallback where the fall back text is parsed as text. This * test uses a nested xi:include for the fallback test. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeFallbackTextPos() { - String resultFile = CLASS_DIR + "doc_fallback_text.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeFallbackTextPos() throws Exception { + String resultFile = USER_DIR + "doc_fallback_text.out"; String goldFile = GOLDEN_DIR + "doc_fallback_textGold.xml"; String xmlFile = XML_DIR + "doc_fallback_text.xml"; + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); - - Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); - doc.setXmlStandalone(true); - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(doc), new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); + doc.setXmlStandalone(true); + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(doc), new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test the XPointer element() framework with XInclude. + * + * @throws Exception If any errors occur. */ - @Test - public void testXpointerElementPos() { - String resultFile = CLASS_DIR + "doc_xpointer_element.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXpointerElementPos() throws Exception { + String resultFile = USER_DIR + "doc_xpointer_element.out"; String goldFile = GOLDEN_DIR + "doc_xpointerGold.xml"; String xmlFile = XML_DIR + "doc_xpointer_element.xml"; + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(db.parse(new File(xmlFile))), - new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(db.parse(new File(xmlFile))), + new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test the XPointer framework with a SAX object. + * + * @throws Exception If any errors occur. */ - @Test - public void testXPointerPos() { - String resultFile = CLASS_DIR + "doc_xpointer.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXPointerPos() throws Exception { + String resultFile = USER_DIR + "doc_xpointer.out"; String goldFile = GOLDEN_DIR + "doc_xpointerGold.xml"; String xmlFile = XML_DIR + "doc_xpointer.xml"; - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setXIncludeAware(true); - spf.setFeature(FEATURE_NAME, true); - // parse the file - spf.newSAXParser().parse(new File(xmlFile), new XInclHandler(fos, null)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setXIncludeAware(true); + spf.setFeature(FEATURE_NAME, true); + // parse the file + spf.newSAXParser().parse(new File(xmlFile), new XInclHandler(fos, null)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test if xi:include may reference the doc containing the include if the * parse type is text. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeLoopPos() { - String resultFile = CLASS_DIR + "doc_xinc_loops.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeLoopPos() throws Exception { + String resultFile = USER_DIR + "doc_xinc_loops.out"; String goldFile = GOLDEN_DIR + "doc_xinc_loopGold.xml"; String xmlFile = XML_DIR + "doc_xinc_loops.xml"; - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.parse(new File(xmlFile)); - doc.normalizeDocument(); - doc.setXmlStandalone(true); + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new File(xmlFile)); + doc.normalizeDocument(); + doc.setXmlStandalone(true); - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(doc), new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(doc), new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test if two non nested xi:include elements can include the same document * with an xi:include statement. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeNestedPos() { - String resultFile = CLASS_DIR + "schedule.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeNestedPos() throws Exception { + String resultFile = USER_DIR + "schedule.out"; String goldFile = GOLDEN_DIR + "scheduleGold.xml"; String xmlFile = XML_DIR + "schedule.xml"; - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); - Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); - doc.setXmlStandalone(true); - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(doc), new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); + doc.setXmlStandalone(true); + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(doc), new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/UserController.java b/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/UserController.java index 548dd25b298..6236668ce8b 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/UserController.java +++ b/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/UserController.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,21 +25,17 @@ package test.auctionportal; import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE; import static org.testng.Assert.assertFalse; import java.io.FileOutputStream; -import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareDocumentWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; - import org.testng.annotations.Test; import org.w3c.dom.Attr; import org.w3c.dom.Document; @@ -50,8 +46,6 @@ import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSParser; import org.w3c.dom.ls.LSSerializer; -import org.xml.sax.SAXException; -import static test.auctionportal.HiBidConstants.CLASS_DIR; import static test.auctionportal.HiBidConstants.GOLDEN_DIR; import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS; import static test.auctionportal.HiBidConstants.XML_DIR; @@ -59,141 +53,127 @@ import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is the user controller class for the Auction portal HiBid.com. */ -public class UserController { +public class UserController extends JAXPFileBaseTest { /** * Checking when creating an XML document using DOM Level 2 validating * it without having a schema source or a schema location It must throw a * sax parse exception. + * + * @throws Exception If any errors occur. */ @Test - public void testCreateNewUser() { - String resultFile = CLASS_DIR + "accountInfoOut.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); + public void testCreateNewUser() throws Exception { + String resultFile = USER_DIR + "accountInfoOut.xml"; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); - Document document = docBuilder.newDocument(); + Document document = docBuilder.newDocument(); - Element account = document.createElementNS(PORTAL_ACCOUNT_NS, "acc:Account"); - Attr accountID = document.createAttributeNS(PORTAL_ACCOUNT_NS, "acc:accountID"); - account.setAttributeNode(accountID); + Element account = document.createElementNS(PORTAL_ACCOUNT_NS, "acc:Account"); + Attr accountID = document.createAttributeNS(PORTAL_ACCOUNT_NS, "acc:accountID"); + account.setAttributeNode(accountID); - account.appendChild(document.createElement("FirstName")); - account.appendChild(document.createElementNS(PORTAL_ACCOUNT_NS, "acc:LastName")); - account.appendChild(document.createElement("UserID")); + account.appendChild(document.createElement("FirstName")); + account.appendChild(document.createElementNS(PORTAL_ACCOUNT_NS, "acc:LastName")); + account.appendChild(document.createElement("UserID")); - DOMImplementationLS impl - = (DOMImplementationLS) DOMImplementationRegistry - .newInstance().getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); - FileOutputStream output = new FileOutputStream(resultFile); + DOMImplementationLS impl + = (DOMImplementationLS) DOMImplementationRegistry + .newInstance().getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); + LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + try(FileOutputStream output = new FileOutputStream(resultFile)) { MyDOMOutput domOutput = new MyDOMOutput(); - domOutput.setByteStream(output); writer.write(account, domOutput); docBuilder.parse(resultFile); - - assertTrue(eh.isAnyError()); - } catch (ParserConfigurationException | ClassNotFoundException | - InstantiationException | IllegalAccessException - | ClassCastException | SAXException | IOException e) { - failUnexpected(e); } + assertTrue(eh.isAnyError()); } /** * Checking conflicting namespaces and use renameNode and normalizeDocument. * @see accountInfo.xml + * + * @throws Exception If any errors occur. */ @Test - public void testAddUser() { - String resultFile = CLASS_DIR + "accountRole.out"; + public void testAddUser() throws Exception { + String resultFile = USER_DIR + "accountRole.out"; String xmlFile = XML_DIR + "accountInfo.xml"; - try { - // Copy schema for outputfile - Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"), - Paths.get(CLASS_DIR, "accountInfo.xsd"), - StandardCopyOption.REPLACE_EXISTING); - MyErrorHandler eh = new MyErrorHandler(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + // Copy schema for outputfile + Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"), + Paths.get(USER_DIR, "accountInfo.xsd"), + StandardCopyOption.REPLACE_EXISTING); + MyErrorHandler eh = new MyErrorHandler(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - dbf.setNamespaceAware(true); - dbf.setValidating(true); + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + dbf.setNamespaceAware(true); + dbf.setValidating(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - docBuilder.setErrorHandler(eh); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + docBuilder.setErrorHandler(eh); - Document document = docBuilder.parse(xmlFile); - Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0); - Element role = (Element) sell.getParentNode(); + Document document = docBuilder.parse(xmlFile); + Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0); + Element role = (Element) sell.getParentNode(); - Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy"); - role.appendChild(buy); + Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy"); + role.appendChild(buy); - DOMImplementationLS impl - = (DOMImplementationLS) DOMImplementationRegistry - .newInstance().getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); + DOMImplementationLS impl + = (DOMImplementationLS) DOMImplementationRegistry + .newInstance().getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); - try(FileOutputStream output = new FileOutputStream(resultFile)) { - MyDOMOutput mydomoutput = new MyDOMOutput(); - mydomoutput.setByteStream(output); - writer.write(document, mydomoutput); - } - - docBuilder.parse(resultFile); - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); + try(FileOutputStream output = new FileOutputStream(resultFile)) { + MyDOMOutput mydomoutput = new MyDOMOutput(); + mydomoutput.setByteStream(output); + writer.write(document, mydomoutput); } + + docBuilder.parse(resultFile); + assertFalse(eh.isAnyError()); } /** * Checking Text content in XML file. * @see accountInfo.xml + * + * @throws Exception If any errors occur. */ - @Test - public void testMoreUserInfo() { + @Test(groups = {"readLocalFiles"}) + public void testMoreUserInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - try { - System.out.println("Checking additional user info"); + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + dbf.setNamespaceAware(true); + dbf.setValidating(true); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - dbf.setNamespaceAware(true); - dbf.setValidating(true); + Document document = docBuilder.parse(xmlFile); + Element account = (Element)document + .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); + String textContent = account.getTextContent(); + assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6)); + assertEquals(textContent, "RachelGreen744"); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); + Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); + assertTrue(accountID.getTextContent().trim().equals("1")); - Document document = docBuilder.parse(xmlFile); - Element account = (Element)document - .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); - String textContent = account.getTextContent(); - assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6)); - assertEquals(textContent, "RachelGreen744"); - - Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); - assertTrue(accountID.getTextContent().trim().equals("1")); - - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + assertFalse(eh.isAnyError()); } /** @@ -204,83 +184,73 @@ public class UserController { * into an XML file which is validated by the schema This covers Row 5 * for the table * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed - * bug 4893745 because there was a difference in behavior + * bug 4893745 because there was a difference in behavior. + * + * @throws Exception If any errors occur. */ @Test - public void testCreateUserAccount() { - System.out.println("Creating user account"); + public void testCreateUserAccount() throws Exception { String userXmlFile = XML_DIR + "userInfo.xml"; String accountXmlFile = XML_DIR + "accountInfo.xml"; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); + Document document = docBuilder.parse(userXmlFile); + Element user = (Element) document.getElementsByTagName("FirstName").item(0); + // Set schema after parsing userInfo.xml. Otherwise it will conflict + // with DTD validation. + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + DocumentBuilder docBuilder1 = dbf.newDocumentBuilder(); + docBuilder1.setErrorHandler(eh); + Document accDocument = docBuilder1.parse(accountXmlFile); - Document document = docBuilder.parse(userXmlFile); - Element user = (Element) document.getElementsByTagName("FirstName").item(0); - // Set schema after parsing userInfo.xml. Otherwise it will conflict - // with DTD validation. - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - DocumentBuilder docBuilder1 = dbf.newDocumentBuilder(); - docBuilder1.setErrorHandler(eh); - Document accDocument = docBuilder1.parse(accountXmlFile); + Element firstName = (Element) accDocument + .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); + Element adoptedAccount = (Element) accDocument.adoptNode(user); - Element firstName = (Element) accDocument - .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); - Element adoptedAccount = (Element) accDocument.adoptNode(user); + Element parent = (Element) firstName.getParentNode(); + parent.replaceChild(adoptedAccount, firstName); - Element parent = (Element) firstName.getParentNode(); - parent.replaceChild(adoptedAccount, firstName); + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); + MyDOMOutput mydomoutput = new MyDOMOutput(); + mydomoutput.setByteStream(System.out); - MyDOMOutput mydomoutput = new MyDOMOutput(); - mydomoutput.setByteStream(System.out); + writer.write(document, mydomoutput); + writer.write(accDocument, mydomoutput); - writer.write(document, mydomoutput); - writer.write(accDocument, mydomoutput); - - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); - } + assertFalse(eh.isAnyError()); } /** * Checking for Row 8 from the schema table when setting the schemaSource * without the schemaLanguage must report an error. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = IllegalArgumentException.class) - public void testUserError() throws IllegalArgumentException { - System.out.println("Creating an error in user account"); - + public void testUserError() throws Exception { String xmlFile = XML_DIR + "userInfo.xml"; String schema = "http://java.sun.com/xml/jaxp/properties/schemaSource"; String schemaValue = "http://dummy.com/dummy.xsd"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - dbf.setAttribute(schema, schemaValue); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + dbf.setAttribute(schema, schemaValue); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); - Document document = docBuilder.parse(xmlFile); - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); + docBuilder.parse(xmlFile); + assertFalse(eh.isAnyError()); } /** @@ -288,10 +258,12 @@ public class UserController { * @see screenName.xml has prefix of * userName is bound to "http://hibid.com/user" namespace normalization * will create a namespace of prefix us and attach userEmail. + * + * @throws Exception If any errors occur. */ @Test - public void testCheckScreenNameExists() { - String resultFile = CLASS_DIR + "screenName.out"; + public void testCheckScreenNameExists() throws Exception { + String resultFile = USER_DIR + "screenName.out"; String xmlFile = XML_DIR + "screenName.xml"; String goldFile = GOLDEN_DIR + "screenNameGold.xml"; @@ -318,21 +290,7 @@ public class UserController { MyDOMOutput domoutput = new MyDOMOutput(); domoutput.setByteStream(output); writer.write(document, domoutput); - - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException | IOException - | ParserConfigurationException | SAXException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/TestUtils.java b/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyCHandler.java similarity index 83% rename from jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/TestUtils.java rename to jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyCHandler.java index 9f8dc355333..c43390d43b9 100644 --- a/jaxp/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/TestUtils.java +++ b/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyCHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 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 @@ -22,37 +22,22 @@ */ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.ERROR_MSG_HEADER; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; - import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; - +import static jaxp.library.JAXPTestUtilities.ERROR_MSG_HEADER; import org.xml.sax.Attributes; import org.xml.sax.Locator; -import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.LocatorImpl; -/** - * Utility interface which includes final variables of xml, golden file - * directories. - */ -interface TestUtils { - final String XML_DIR = System.getProperty("test.src", ".") + FILE_SEP + "javax/xml/parsers/xmlfiles"; - final String GOLDEN_DIR = XML_DIR + FILE_SEP + "out"; -} - /** * Customized DefaultHandler which writes output document when methods are * called by Transformer. Test may use output document to compare with golden * file for verification. */ -class MyCHandler extends DefaultHandler { +class MyCHandler extends DefaultHandler implements AutoCloseable { private final BufferedWriter bWriter; private final Locator locator = new LocatorImpl(); @@ -66,6 +51,7 @@ class MyCHandler extends DefaultHandler { return handler; } + @Override public void characters(char[] ch, int start, int length) { String s = new String(ch, start, length); String str = String.format("characters...length is:%d\n<%s>", s.length(), s); @@ -77,19 +63,19 @@ class MyCHandler extends DefaultHandler { } } + @Override public void endDocument() { String str = "endDocument..."; try { bWriter.write(str, 0, str.length()); bWriter.newLine(); bWriter.flush(); - bWriter.close(); - } catch (IOException e) { throw new RuntimeException(ERROR_MSG_HEADER, e); } } + @Override public void endElement(String namespaceURI, String localName, String qName) { String str = String.format("endElement...\nnamespaceURI: <%s> localName: <%s> qName: <%s>", namespaceURI, localName, qName); try { @@ -100,6 +86,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void endPrefixMapping(String prefix) { String str = String.format("endPrefixMapping...\nprefix: <%s>", prefix); try { @@ -110,6 +97,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void ignorableWhitespace(char[] ch, int start, int length) { String s = new String(ch, start, length); String str = String.format("ignorableWhitespace...\n%s ignorable white space string length: %d", s, s.length()); @@ -121,6 +109,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void processingInstruction(String target, String data) { String str = String.format("processingInstruction...target:<%s> data: <%s>", target, data); try { @@ -131,6 +120,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void skippedEntity(String name) { String str = String.format("skippedEntity...\nname: <%s>", name); try { @@ -141,6 +131,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void startDocument() { String str = "startDocument..."; try { @@ -151,6 +142,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { String str = String.format("startElement...\nnamespaceURI: <%s> localName: <%s> qName: <%s> Number of Attributes: <%d> Line# <%d>", namespaceURI, localName, qName, atts.getLength(), locator.getLineNumber()); @@ -162,6 +154,7 @@ class MyCHandler extends DefaultHandler { } } + @Override public void startPrefixMapping(String prefix, String uri) { String str = String.format("startPrefixMapping...\nprefix: <%s> uri: <%s>", prefix, uri); try { @@ -171,30 +164,10 @@ class MyCHandler extends DefaultHandler { throw new RuntimeException(ERROR_MSG_HEADER, e); } } -} -/** - * Customized DefaultHandler used for SAXParseException testing. - */ -class MyErrorHandler extends DefaultHandler { - boolean errorOccured = false; - - private MyErrorHandler() { - } - - public static MyErrorHandler newInstance() { - return new MyErrorHandler(); - } - - public void error(SAXParseException e) { - errorOccured = true; - } - - public void warning(SAXParseException e) { - errorOccured = true; - } - - public void fatalError(SAXParseException e) { - errorOccured = true; + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); } } diff --git a/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyErrorHandler.java b/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyErrorHandler.java new file mode 100644 index 00000000000..2910a6edef0 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyErrorHandler.java @@ -0,0 +1,88 @@ +/* + * 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 + * 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. + */ +package javax.xml.parsers.ptests; + +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Customized DefaultHandler used for SAXParseException testing. + */ +class MyErrorHandler extends DefaultHandler { + /** + * Flag whether any event was received. + */ + private volatile boolean errorOccured; + + /** + * Set no event received on constructor. + */ + private MyErrorHandler() { + errorOccured = false; + } + + /** + * Factory method to create a MyErrorHandler instance. + * @return a MyErrorHandler instance. + */ + public static MyErrorHandler newInstance() { + return new MyErrorHandler(); + } + + /** + * Receive notification of a recoverable error. + * @param e a recoverable parser exception error. + */ + @Override + public void error(SAXParseException e) { + errorOccured = true; + } + + /** + * Receive notification of a parser warning. + * @param e a parser warning event. + */ + @Override + public void warning(SAXParseException e) { + errorOccured = true; + } + + /** + * Report a fatal XML parsing error. + * @param e The error information encoded as an exception. + */ + @Override + public void fatalError(SAXParseException e) { + errorOccured = true; + } + + /** + * Has any event been received. + * + * @return true if any event has been received. + * false if no event has been received. + */ + public boolean isErrorOccured() { + return errorOccured; + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/ParserTestConst.java b/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/ParserTestConst.java new file mode 100644 index 00000000000..ac50221fec8 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/ParserTestConst.java @@ -0,0 +1,46 @@ +/* + * 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 + * 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. + */ +package javax.xml.parsers.ptests; + +import static jaxp.library.JAXPTestUtilities.FILE_SEP; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; + + +/** + * Utility interface which includes final variables of XML, golden file + * directories. + */ +public class ParserTestConst { + /** + * XML source file directory. + */ + public static final String XML_DIR = getPathByClassName(ParserTestConst.class, + ".." + FILE_SEP + "xmlfiles"); + + + /** + * Golden validation files directory. + */ + public static final String GOLDEN_DIR = getPathByClassName(ParserTestConst.class, + ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); +} diff --git a/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/MyContentHandler.java b/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/MyContentHandler.java index 898e008097d..f08d5f57546 100644 --- a/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/MyContentHandler.java +++ b/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/MyContentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/TransformerTestConst.java b/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/TransformerTestConst.java index df40a8c78c4..5f119360432 100644 --- a/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/TransformerTestConst.java +++ b/jaxp/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/TransformerTestConst.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,40 +23,22 @@ package javax.xml.transform.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for JAXP functional test */ public class TransformerTestConst { /** - * Current test directory. + * XML source file directory. */ - public static final String CLASS_DIR - = System.getProperty("test.classes", ".") + FILE_SEP; + public static final String XML_DIR = getPathByClassName(TransformerTestConst.class, + ".." + FILE_SEP + "xmlfiles"); + /** - * Package name that separates by slash. + * Golden validation files directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - TransformerTestConst.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - /** - * Test base directory. Every package has its own test package directory. - */ - public static final String BASE_DIR - = System.getProperty("test.src", USER_DIR).replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP + ".."; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = BASE_DIR + FILE_SEP + "xmlfiles" + FILE_SEP; - - /** - * Golden output file directory. We pre-define all expected output in golden - * output file. Test verifies whether the standard output is same as content - * of golden file. - */ - public static final String GOLDEN_DIR = XML_DIR + FILE_SEP + "out" + FILE_SEP; + public static final String GOLDEN_DIR = getPathByClassName(TransformerTestConst.class, + ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); } diff --git a/jaxp/test/javax/xml/jaxp/libs/javax/xml/xpath/ptests/XPathTestConst.java b/jaxp/test/javax/xml/jaxp/libs/javax/xml/xpath/ptests/XPathTestConst.java index 719d6712645..605dada1656 100644 --- a/jaxp/test/javax/xml/jaxp/libs/javax/xml/xpath/ptests/XPathTestConst.java +++ b/jaxp/test/javax/xml/jaxp/libs/javax/xml/xpath/ptests/XPathTestConst.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,27 +23,15 @@ package javax.xml.xpath.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for XPath functional test */ public class XPathTestConst { /** - * Package name that separates by slash. + * XML source file directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - XPathTestConst.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - /** - * Test base directory. Every package has its own test package directory. - */ - public static final String BASE_DIR - = System.getProperty("test.src", USER_DIR).replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP + ".."; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = BASE_DIR + FILE_SEP + "xmlfiles" + FILE_SEP; + public static final String XML_DIR = getPathByClassName(XPathTestConst.class, + ".." + FILE_SEP + "xmlfiles"); } diff --git a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPBaseTest.java b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPBaseTest.java new file mode 100644 index 00000000000..687ff7009d5 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPBaseTest.java @@ -0,0 +1,138 @@ +/* + * 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. + */ +package jaxp.library; + +import java.security.Permission; +import java.security.Permissions; +import java.security.Policy; +import java.util.PropertyPermission; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; + +/** + * This is a base class that every test class must extend if it needs to be run + * with security mode. + */ +public class JAXPBaseTest { + /** + * Backing up policy. + */ + protected static Policy policy; + + /** + * Backing up security manager. + */ + private static SecurityManager sm; + + /* + * Install a SecurityManager along with a base Policy to allow testNG to + * run when there is a security manager. + */ + @BeforeClass + public void setUpClass() throws Exception { + setPolicy(new TestPolicy()); + System.setSecurityManager(new SecurityManager()); + } + + /* + * Install the original Policy and SecurityManager when there is a security + * manager. + */ + @AfterClass + public void tearDownClass() throws Exception { + System.setSecurityManager(sm); + setPolicy(policy); + } + + /* + * Utility Method used to set the current Policy. + */ + protected static void setPolicy(Policy p) { + Policy.setPolicy(p); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permission... ps) { + Policy.setPolicy(new TestPolicy(ps)); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permissions ps) { + Policy.setPolicy(new TestPolicy(ps)); + } + + /** + * Backing up policy and security manager for restore when there is a + * security manager. + */ + public JAXPBaseTest() { + policy = Policy.getPolicy(); + sm = System.getSecurityManager(); + } + + /** + * Safety acquire a system property. + * Note invocation of this method will restore permission to limited + * minimal permission of tests. If there is additional permission set + * already, you need restore permission by yourself. + * @param propName System property name to be acquired. + * @return property value + */ + protected String getSystemProperty(final String propName) { + setPermissions(new PropertyPermission(propName, "read")); + try { + return System.getProperty(propName); + } finally { + setPermissions(); + } + } + + /** + * Safety set a system property by given system value. + * + * @param propName System property name to be set. + * @param propValue System property value to be set. + */ + protected void setSystemProperty(final String propName, final String propValue) { + setPermissions(new PropertyPermission(propName, "write")); + try { + if (propValue == null) { + System.clearProperty(propName); + } else { + System.setProperty(propName, propValue); + } + } finally { + setPermissions(); + } + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileBaseTest.java b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileBaseTest.java new file mode 100644 index 00000000000..c45c6d3a270 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileBaseTest.java @@ -0,0 +1,105 @@ +/* + * 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. + */ +package jaxp.library; + +import java.io.FilePermission; +import java.security.Permission; +import java.security.Permissions; +import java.security.Policy; +import static jaxp.library.JAXPBaseTest.setPolicy; +import org.testng.annotations.BeforeClass; + +/** + * This is a base class that every test class that need to access local XML + * files must extend if it needs to be run with security mode. + */ +public class JAXPFileBaseTest extends JAXPBaseTest { + /* + * Install a SecurityManager along with a base Policy to allow testNG to + * run when there is a security manager. + */ + @BeforeClass + @Override + public void setUpClass() throws Exception { + setPolicy(new FileTestPolicy()); + System.setSecurityManager(new SecurityManager()); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permission... ps) { + Policy.setPolicy(new FileTestPolicy(ps)); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permissions ps) { + Policy.setPolicy(new FileTestPolicy(ps)); + } +} + +/** + * This policy is only given to tests that need access local files. Additional + * permissions for accessing local files have been granted by default. + * @author HaiboYan + */ +class FileTestPolicy extends TestPolicy { + /** + * Constructor which sets the minimum permissions by default allowing testNG + * to work with a SecurityManager. + * @param ps permissions to be added. + */ + public FileTestPolicy(Permissions ps) { + super(ps); + } + + /** + * Constructor which sets the minimum permissions by default allowing testNG + * to work with a SecurityManager. + * @param ps permission array to be added. + */ + public FileTestPolicy(Permission... ps) { + super(ps); + } + + /** + * Defines the minimal permissions required by testNG when running these + * tests + */ + @Override + protected void setMinimalPermissions() { + super.setMinimalPermissions(); + permissions.add(new FilePermission(System.getProperty("user.dir") + "/-", + "read, write")); + permissions.add(new FilePermission(System.getProperty("test.src") + "/-", + "read")); + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileReadOnlyBaseTest.java b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileReadOnlyBaseTest.java new file mode 100644 index 00000000000..eed9a05b784 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileReadOnlyBaseTest.java @@ -0,0 +1,55 @@ +/* + * 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. + */ +package jaxp.library; + +import java.io.FilePermission; +import static jaxp.library.JAXPBaseTest.setPermissions; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; + +/** + * This is a base class that every test class that need to reading local XML + * files must extend if it needs to be run with security mode. + */ +public class JAXPFileReadOnlyBaseTest extends JAXPBaseTest { + /** + * Source files/XML files directory. + */ + private final String SRC_DIR = getSystemProperty("test.src"); + + /** + * Allowing access local file system for this group. + */ + @BeforeGroups (groups = {"readLocalFiles"}) + public void setFilePermissions() { + setPermissions(new FilePermission(SRC_DIR + "/-", "read")); + } + + /** + * Restore the system property. + */ + @AfterGroups (groups = {"readLocalFiles"}) + public void restoreFilePermissions() { + setPermissions(); + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPTestUtilities.java b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPTestUtilities.java index 33d0e1c01bc..a7f18083d30 100644 --- a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPTestUtilities.java +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPTestUtilities.java @@ -1,5 +1,5 @@ /* - * 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,21 +23,34 @@ package jaxp.library; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; import static org.testng.Assert.fail; import org.w3c.dom.Document; +import org.w3c.dom.Node; import org.xml.sax.SAXException; /** @@ -61,14 +74,17 @@ public class JAXPTestUtilities { public static final String FILE_SEP = "/"; /** - * User home. + * Current test directory. */ - public static final String USER_DIR = System.getProperty("user.dir", "."); + public static final String USER_DIR = + System.getProperty("user.dir", ".") + FILE_SEP;; /** - * TEMP file directory. + * A map storing every test's current test file pointer. File number should + * be incremental and it's a thread-safe reading on this file number. */ - public static final String TEMP_DIR = System.getProperty("java.io.tmpdir", "."); + private static final ConcurrentHashMap currentFileNumber + = new ConcurrentHashMap<>(); /** * BOM table for storing BOM header. @@ -94,12 +110,60 @@ public class JAXPTestUtilities { * @return true if two files are identical. * false if two files are not identical. * @throws IOException if an I/O error occurs reading from the file or a - * malformed or unmappable byte sequence is read + * malformed or unmappable byte sequence is read. */ public static boolean compareWithGold(String goldfile, String outputfile) throws IOException { + return compareWithGold(goldfile, outputfile, StandardCharsets.UTF_8); + } + + /** + * Compare contents of golden file with test output file line by line. + * return true if they're identical. + * @param goldfile Golden output file name. + * @param outputfile Test output file name. + * @param cs the charset to use for decoding. + * @return true if two files are identical. + * false if two files are not identical. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read. + */ + public static boolean compareWithGold(String goldfile, String outputfile, + Charset cs) throws IOException { return Files.readAllLines(Paths.get(goldfile)). - equals(Files.readAllLines(Paths.get(outputfile))); + equals(Files.readAllLines(Paths.get(outputfile), cs)); + } + + /** + * Compare contents of golden file with test output list line by line. + * return true if they're identical. + * @param goldfile Golden output file name. + * @param lines test output list. + * @return true if file's content is identical to given list. + * false if file's content is not identical to given list. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read + */ + public static boolean compareLinesWithGold(String goldfile, List lines) + throws IOException { + return Files.readAllLines(Paths.get(goldfile)).equals(lines); + } + + /** + * Compare contents of golden file with a test output string. + * return true if they're identical. + * @param goldfile Golden output file name. + * @param string test string. + * @return true if file's content is identical to given string. + * false if file's content is not identical to given string. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read + */ + public static boolean compareStringWithGold(String goldfile, String string) + throws IOException { + return Files.readAllLines(Paths.get(goldfile)).stream().collect( + Collectors.joining(System.getProperty("line.separator"))) + .equals(string); } /** @@ -132,6 +196,35 @@ public class JAXPTestUtilities { resultD.normalizeDocument(); return goldD.isEqualNode(resultD); } + + /** + * Compare contents of golden file with the serialization represent by given + * DOM node. + * Here we ignore the white space and comments. return true if they're + * lexical identical. + * @param goldfile Golden output file name. + * @param node A DOM node instance. + * @return true if file's content is identical to given node's serialization + * represent. + * false if file's content is not identical to given node's + * serialization represent. + * @throws TransformerException If an unrecoverable error occurs during the + * course of the transformation.. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read . + */ + public static boolean compareSerializeDOMWithGold(String goldfile, Node node) + throws TransformerException, IOException { + TransformerFactory factory = TransformerFactory.newInstance(); + // Use identity transformer to serialize + Transformer identityTransformer = factory.newTransformer(); + StringWriter sw = new StringWriter(); + StreamResult streamResult = new StreamResult(sw); + DOMSource nodeSource = new DOMSource(node); + identityTransformer.transform(nodeSource, streamResult); + return compareStringWithGold(goldfile, sw.toString()); + } + /** * Convert stream to ByteArrayInputStream by given character set. * @param charset target character set. @@ -159,6 +252,36 @@ public class JAXPTestUtilities { return new ByteArrayInputStream(bb.array()); } + /** + * Worker method to detect common absolute URLs. + * + * @param s String path\filename or URL (or any, really) + * @return true if s starts with a common URI scheme (namely + * the ones found in the examples of RFC2396); false otherwise + */ + protected static boolean isCommonURL(String s) { + if (null == s) + return false; + return Pattern.compile("^(file:|http:|ftp:|gopher:|mailto:|news:|telnet:)") + .matcher(s).matches(); + } + + /** + * Utility method to translate a String filename to URL. + * + * If the name starts with a common URI scheme (namely the ones + * found in the examples of RFC2396), then simply return the + * name as-is (the assumption is that it's already a URL). + * Otherwise we attempt (cheaply) to convert to a file:/ URL. + * + * @param filename local path/filename of a file. + * @return a file:/ URL if filename represent a file, the same string if + * it appears to already be a URL. + */ + public static String filenameToURL(String filename) { + return Paths.get(filename).toUri().toASCIIString(); + } + /** * Prints error message if an exception is thrown * @param ex The exception is thrown by test. @@ -175,4 +298,38 @@ public class JAXPTestUtilities { public static void failCleanup(IOException ex, String name) { fail(String.format(ERROR_MSG_CLEANUP, name), ex); } + + /** + * Retrieve next test output file name. This method is a thread-safe method. + * @param clazz test class. + * @return next test output file name. + */ + public static String getNextFile(Class clazz) { + int nextNumber = currentFileNumber.contains(clazz) + ? currentFileNumber.get(clazz) + 1 : 1; + Integer i = currentFileNumber.putIfAbsent(clazz, nextNumber); + if (i != null && i != nextNumber) { + do { + nextNumber = currentFileNumber.get(clazz) + 1; + } while (currentFileNumber.replace(clazz, nextNumber -1, nextNumber)); + } + return USER_DIR + clazz.getName() + nextNumber + ".out"; + } + + /** + * Acquire a full path string by given class name and relative path string. + * @param clazz Class name for the test. + * @param relativeDir relative path between java source file and expected + * path. + * @return a string represents the full path of accessing path. + */ + public static String getPathByClassName(Class clazz, String relativeDir) { + String packageName = FILE_SEP + + clazz.getPackage().getName().replaceAll("[.]", FILE_SEP); + String javaSourcePath = System.getProperty("test.src").replaceAll("\\" + File.separator, FILE_SEP) + + packageName + FILE_SEP; + String normalizedPath = Paths.get(javaSourcePath, relativeDir).normalize(). + toAbsolutePath().toString(); + return normalizedPath.replace("\\", FILE_SEP) + FILE_SEP; + } } diff --git a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/TestPolicy.java b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/TestPolicy.java new file mode 100644 index 00000000000..1e39fbc36eb --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/TestPolicy.java @@ -0,0 +1,149 @@ +/* + * 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. + */ +package jaxp.library; + +import java.security.AllPermission; +import java.security.CodeSource; +import java.security.Permission; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.security.Policy; +import java.security.ProtectionDomain; +import java.security.SecurityPermission; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.PropertyPermission; +import java.util.StringJoiner; + +/* + * Simple Policy class that supports the required Permissions to validate the + * JAXP concrete classes. + * Note: permission can only be added. You may want to create a new TestPolicy + * instance if you need remove permissions. + */ +public class TestPolicy extends Policy { + protected final PermissionCollection permissions = new Permissions(); + + /** + * Constructor which sets the minimum permissions by default allowing testNG + * to work with a SecurityManager. + */ + public TestPolicy() { + setMinimalPermissions(); + } + + /** + * Construct an instance with the minimal permissions required by the test + * environment and additional permission(s) as specified. + * @param ps permissions to be added. + */ + public TestPolicy(Permissions ps) { + setMinimalPermissions(); + TestPolicy.this.addPermissions(ps); + } + + /** + * Construct an instance with the minimal permissions required by the test + * environment and additional permission(s) as specified. + * @param ps permission array to be added. + */ + public TestPolicy(Permission... ps) { + setMinimalPermissions(); + addPermissions(ps); + } + + /** + * Defines the minimal permissions required by testNG when running these + * tests + */ + protected void setMinimalPermissions() { + permissions.add(new SecurityPermission("getPolicy")); + permissions.add(new SecurityPermission("setPolicy")); + permissions.add(new RuntimePermission("getClassLoader")); + permissions.add(new RuntimePermission("setSecurityManager")); + permissions.add(new RuntimePermission("createSecurityManager")); + permissions.add(new PropertyPermission("testng.show.stack.frames", + "read")); + permissions.add(new PropertyPermission("user.dir", "read")); + permissions.add(new PropertyPermission("test.src", "read")); + permissions.add(new PropertyPermission("file.separator", "read")); + permissions.add(new PropertyPermission("line.separator", "read")); + permissions.add(new PropertyPermission("fileStringBuffer", "read")); + permissions.add(new PropertyPermission("dataproviderthreadcount", "read")); + } + + /* + * Add permissions for your tests. + * @param permissions to be added. + */ + private void addPermissions(Permissions ps) { + Collections.list(ps.elements()).forEach(p -> permissions.add(p)); + } + + + /* + * Add permissions for your tests. + * @param permissions to be added. + */ + private void addPermissions(Permission[] ps) { + Arrays.stream(ps).forEach(p -> permissions.add(p)); + } + + /** + * Set all permissions. Caution: this should not called carefully unless + * it's really needed. + */ + private void setAllPermissions() { + permissions.add(new AllPermission()); + } + + /* + * Overloaded methods from the Policy class. + */ + @Override + public String toString() { + StringJoiner sj = new StringJoiner("\n", "policy: ", ""); + Enumeration perms = permissions.elements(); + while (perms.hasMoreElements()) { + sj.add(perms.nextElement().toString()); + } + return sj.toString(); + + } + + @Override + public PermissionCollection getPermissions(ProtectionDomain domain) { + return permissions; + } + + @Override + public PermissionCollection getPermissions(CodeSource codesource) { + return permissions; + } + + @Override + public boolean implies(ProtectionDomain domain, Permission perm) { + return permissions.implies(perm); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyAttrCHandler.java b/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyAttrCHandler.java similarity index 98% rename from jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyAttrCHandler.java rename to jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyAttrCHandler.java index b1f037f6ce5..700c05e22ec 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyAttrCHandler.java +++ b/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyAttrCHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyNSContentHandler.java b/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyNSContentHandler.java similarity index 94% rename from jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyNSContentHandler.java rename to jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyNSContentHandler.java index 1e686630377..af3f219b9b4 100644 --- a/jaxp/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyNSContentHandler.java +++ b/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyNSContentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,11 +31,12 @@ import java.io.IOException; import java.io.FileWriter; import org.xml.sax.SAXException; -class MyNSContentHandler extends DefaultHandler { +class MyNSContentHandler extends DefaultHandler implements AutoCloseable{ /** * Prefix for written string. */ private final static String WRITE_ERROR = "bWrite error"; + /** * FileWriter to write output file. */ @@ -205,4 +206,14 @@ class MyNSContentHandler extends DefaultHandler { throw new SAXException(WRITE_ERROR, ex); } } + + /** + * Close writer if it's initiated. + * @throws IOException if any I/O error when close writer. + */ + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } } diff --git a/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/SAXTestConst.java b/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/SAXTestConst.java index caac12f8c5a..6798d7879dc 100644 --- a/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/SAXTestConst.java +++ b/jaxp/test/javax/xml/jaxp/libs/org/xml/sax/ptests/SAXTestConst.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ package org.xml.sax.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for JAXP SAX functional @@ -32,33 +32,15 @@ import static jaxp.library.JAXPTestUtilities.USER_DIR; */ public class SAXTestConst { /** - * Current test directory. + * XML source file directory. */ - public static final String CLASS_DIR - = System.getProperty("test.classes", ".") + FILE_SEP; + public static final String XML_DIR = getPathByClassName(SAXTestConst.class, + ".." + FILE_SEP + "xmlfiles"); + /** - * Package name that separates by slash. + * Golden validation files directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - SAXTestConst.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - /** - * Test base directory. Every package has its own test package directory. - */ - public static final String BASE_DIR - = System.getProperty("test.src", USER_DIR).replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP + ".."; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = BASE_DIR + FILE_SEP + "xmlfiles" + FILE_SEP; - - /** - * Golden output file directory. We pre-define all expected output in golden - * output file. Test verifies whether the standard output is same as content - * of golden file. - */ - public static final String GOLDEN_DIR = XML_DIR + FILE_SEP + "out" + FILE_SEP; + public static final String GOLDEN_DIR = getPathByClassName(SAXTestConst.class, + ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); } diff --git a/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/HiBidConstants.java b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/HiBidConstants.java index a5dbdb91f71..9ee741b15a1 100644 --- a/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/HiBidConstants.java +++ b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/HiBidConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -22,44 +22,21 @@ */ package test.auctionportal; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for Auction portal test. */ public class HiBidConstants { /** - * Current test directory. + * XML source file directory. */ - public static final String CLASS_DIR - = System.getProperty("test.classes", ".") + FILE_SEP; + public static final String XML_DIR = getPathByClassName(HiBidConstants.class, "content"); /** - * Package name that separates by slash. + * Golden validation files directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - HiBidConstants.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - - /** - * Java source directory. - */ - public static final String SRC_DIR = System.getProperty("test.src", USER_DIR) - .replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = SRC_DIR + "content" + FILE_SEP; - - /** - * Golden output file directory. - * We pre-define all expected output in golden output file. Test verifies - * whether the standard output is same as content of golden file. - */ - public static final String GOLDEN_DIR = SRC_DIR + "golden" + FILE_SEP; + public static final String GOLDEN_DIR = getPathByClassName(HiBidConstants.class, "golden"); /** * Name space for account operation. diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMErrorHandler.java b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMErrorHandler.java similarity index 96% rename from jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMErrorHandler.java rename to jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMErrorHandler.java index d0432042199..2ab92f04873 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMErrorHandler.java +++ b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMErrorHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMOutput.java b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMOutput.java similarity index 96% rename from jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMOutput.java rename to jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMOutput.java index 9f2e7d3a5e9..64b16ddb1f7 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMOutput.java +++ b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -108,7 +108,7 @@ public class MyDOMOutput implements LSOutput { /** * Set 16 bits unit writable stream. * - * @param bs a Writer instance + * @param cs a Writer instance */ @Override public void setCharacterStream(Writer cs) { diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyErrorHandler.java b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyErrorHandler.java similarity index 97% rename from jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyErrorHandler.java rename to jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyErrorHandler.java index 0a1580ae517..aae83212bf5 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/MyErrorHandler.java +++ b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/MyErrorHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 diff --git a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/XInclHandler.java b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/XInclHandler.java similarity index 92% rename from jaxp/test/javax/xml/jaxp/functional/test/auctionportal/XInclHandler.java rename to jaxp/test/javax/xml/jaxp/libs/test/auctionportal/XInclHandler.java index b8d2bb35fcc..e8de8d878ae 100644 --- a/jaxp/test/javax/xml/jaxp/functional/test/auctionportal/XInclHandler.java +++ b/jaxp/test/javax/xml/jaxp/libs/test/auctionportal/XInclHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -57,6 +57,8 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { /** * Sets whether output is canonical. + * + * @param canonical if the output is canonical format. */ public void setCanonical(boolean canonical) { fCanonical = canonical; @@ -66,6 +68,8 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { * Sets the output stream for printing. * @param stream OutputStream for message output. * @param encoding File encoding for message output. + * @throws UnsupportedEncodingException if given encoding is an unsupported + * encoding name or invalid encoding name. */ public XInclHandler(OutputStream stream, String encoding) throws UnsupportedEncodingException { @@ -97,8 +101,8 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { * @param target The processing instruction target. * @param data The processing instruction data, or null if * none is supplied. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. + * @exception SAXException Any SAX exception, possibly wrapping another + * exception. */ @Override public void processingInstruction (String target, String data) @@ -119,14 +123,16 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. - * @param localName The local name (without prefix), or the + * @param local The local name (without prefix), or the * empty string if Namespace processing is not being * performed. - * @param qName The qualified name (with prefix), or the + * @param raw The qualified name (with prefix), or the * empty string if qualified names are not available. - * @param attributes The attributes attached to the element. If + * @param attrs The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. + * @throws SAXException Any SAX exception, possibly wrapping another + * exception. */ @Override public void startElement(String uri, String local, String raw, @@ -181,11 +187,13 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. - * @param localName The local name (without prefix), or the + * @param local The local name (without prefix), or the * empty string if Namespace processing is not being * performed. - * @param qName The qualified name (with prefix), or the + * @param raw The qualified name (with prefix), or the * empty string if qualified names are not available. + * @throws org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. */ @Override public void endElement(String uri, String local, String raw) @@ -196,7 +204,7 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { /** * Receive notification of a parser warning and print it out. - * @param e The warning information encoded as an exception. + * @param ex The warning information encoded as an exception. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. */ @@ -207,10 +215,9 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { /** * Receive notification of a parser error and print it out. - * @param e The error information encoded as an exception. + * @param ex The error information encoded as an exception. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. - */ @Override public void error(SAXParseException ex) throws SAXException { @@ -220,7 +227,7 @@ public class XInclHandler extends DefaultHandler implements LexicalHandler { /** * Receive notification of a parser fatal error. Throw out fatal error * following print fatal error message. - * @param e The fatal error information encoded as an exception. + * @param ex The fatal error information encoded as an exception. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. From 788b0d89f877a30a3ac539ce2a5eecdfddda8699 Mon Sep 17 00:00:00 2001 From: Jungwoo Ha Date: Fri, 16 Jan 2015 09:40:13 +0100 Subject: [PATCH 099/149] 8061259: ParNew promotion failed is serialized on a lock Reviewed-by: kbarrett, brutisso --- .../share/vm/gc_implementation/parNew/parNewGeneration.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp index a56c94823db..30ef7ceb2c1 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp @@ -1194,8 +1194,10 @@ oop ParNewGeneration::copy_to_survivor_space( return real_forwardee(old); } - new_obj = _next_gen->par_promote(par_scan_state->thread_num(), - old, m, sz); + if (!_promotion_failed) { + new_obj = _next_gen->par_promote(par_scan_state->thread_num(), + old, m, sz); + } if (new_obj == NULL) { // promotion failed, forward to self From da5d03e7843243ae960271455e9e9d4c33e04b9d Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Fri, 16 Jan 2015 10:15:54 +0100 Subject: [PATCH 100/149] 8069041: Bootcycle builds do not work with sjavac Reviewed-by: ihse --- make/common/JavaCompilation.gmk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/common/JavaCompilation.gmk b/make/common/JavaCompilation.gmk index 6c6e515c816..a183b30dead 100644 --- a/make/common/JavaCompilation.gmk +++ b/make/common/JavaCompilation.gmk @@ -538,7 +538,7 @@ define SetupJavaCompilationInner $1_REMOTE:=--server:portfile=$$($1_SJAVAC_PORTFILE),id=$1,sjavac=$$(subst $$(SPACE),%20,$$(subst $$(COMMA),%2C,$$(strip $$($1_SERVER_JVM) $$($1_SJAVAC)))) $$($1_BIN)/_the.$1_batch: $$($1_SRCS) $$($1_DEPENDS) - $(MKDIR) -p $$(@D) + $(MKDIR) -p $$(@D) $$(dir $$($1_SJAVAC_PORTFILE)) # As a workaround for sjavac not tracking api changed from the classpath, force full # recompile if an external dependency, which is something other than a source # change, triggered this compilation. From 86f95c464ff2c06fef9bed4c9fb80854691a095b Mon Sep 17 00:00:00 2001 From: Erik Helin Date: Fri, 16 Jan 2015 10:29:12 +0100 Subject: [PATCH 101/149] 8066875: VirtualSpace does not use large pages Reviewed-by: stefank, tschatzl, anoll, thartmann --- hotspot/src/share/vm/code/codeCache.cpp | 4 +- .../parallelScavenge/generationSizer.cpp | 4 +- .../parallelScavenge/parMarkBitMap.cpp | 2 +- .../parallelScavenge/psParallelCompact.cpp | 2 +- hotspot/src/share/vm/memory/heap.cpp | 4 +- hotspot/src/share/vm/runtime/os.cpp | 60 ++++++++++++++++--- hotspot/src/share/vm/runtime/os.hpp | 10 +++- hotspot/src/share/vm/runtime/virtualspace.cpp | 7 ++- 8 files changed, 71 insertions(+), 22 deletions(-) diff --git a/hotspot/src/share/vm/code/codeCache.cpp b/hotspot/src/share/vm/code/codeCache.cpp index af50207fbbf..5a546f50b4f 100644 --- a/hotspot/src/share/vm/code/codeCache.cpp +++ b/hotspot/src/share/vm/code/codeCache.cpp @@ -233,8 +233,8 @@ void CodeCache::initialize_heaps() { ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) { // Determine alignment const size_t page_size = os::can_execute_large_page_memory() ? - MIN2(os::page_size_for_region(InitialCodeCacheSize, 8), - os::page_size_for_region(size, 8)) : + MIN2(os::page_size_for_region_aligned(InitialCodeCacheSize, 8), + os::page_size_for_region_aligned(size, 8)) : os::vm_page_size(); const size_t granularity = os::vm_allocation_granularity(); const size_t r_align = MAX2(page_size, granularity); diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.cpp index 29fb547437f..a6cef462ad9 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.cpp @@ -61,9 +61,9 @@ void GenerationSizer::initialize_flags() { void GenerationSizer::initialize_size_info() { trace_gen_sizes("ps heap raw"); - const size_t max_page_sz = os::page_size_for_region(_max_heap_byte_size, 8); + const size_t max_page_sz = os::page_size_for_region_aligned(_max_heap_byte_size, 8); const size_t min_pages = 4; // 1 for eden + 1 for each survivor + 1 for old - const size_t min_page_sz = os::page_size_for_region(_min_heap_byte_size, min_pages); + const size_t min_page_sz = os::page_size_for_region_aligned(_min_heap_byte_size, min_pages); const size_t page_sz = MIN2(max_page_sz, min_page_sz); // Can a page size be something else than a power of two? diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp index a8ab19357ce..33e8f3f9b9c 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp @@ -41,7 +41,7 @@ ParMarkBitMap::initialize(MemRegion covered_region) const size_t words = bits / BitsPerWord; const size_t raw_bytes = words * sizeof(idx_t); - const size_t page_sz = os::page_size_for_region(raw_bytes, 10); + const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10); const size_t granularity = os::vm_allocation_granularity(); _reserved_byte_size = align_size_up(raw_bytes, MAX2(page_sz, granularity)); diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index a546e548370..28cff7813d7 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -403,7 +403,7 @@ PSVirtualSpace* ParallelCompactData::create_vspace(size_t count, size_t element_size) { const size_t raw_bytes = count * element_size; - const size_t page_sz = os::page_size_for_region(raw_bytes, 10); + const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10); const size_t granularity = os::vm_allocation_granularity(); _reserved_byte_size = align_size_up(raw_bytes, MAX2(page_sz, granularity)); diff --git a/hotspot/src/share/vm/memory/heap.cpp b/hotspot/src/share/vm/memory/heap.cpp index 5ba099e78e8..4612f6a80f7 100644 --- a/hotspot/src/share/vm/memory/heap.cpp +++ b/hotspot/src/share/vm/memory/heap.cpp @@ -104,8 +104,8 @@ bool CodeHeap::reserve(ReservedSpace rs, size_t committed_size, size_t segment_s size_t page_size = os::vm_page_size(); if (os::can_execute_large_page_memory()) { const size_t min_pages = 8; - page_size = MIN2(os::page_size_for_region(committed_size, min_pages), - os::page_size_for_region(rs.size(), min_pages)); + page_size = MIN2(os::page_size_for_region_aligned(committed_size, min_pages), + os::page_size_for_region_aligned(rs.size(), min_pages)); } const size_t granularity = os::vm_allocation_granularity(); diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 665688b6808..adf08340257 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -1399,15 +1399,17 @@ bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) { return (sp > (stack_limit + reserved_area)); } -size_t os::page_size_for_region(size_t region_size, size_t min_pages) { +size_t os::page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned) { assert(min_pages > 0, "sanity"); if (UseLargePages) { const size_t max_page_size = region_size / min_pages; for (size_t i = 0; _page_sizes[i] != 0; ++i) { const size_t page_size = _page_sizes[i]; - if (page_size <= max_page_size && is_size_aligned(region_size, page_size)) { - return page_size; + if (page_size <= max_page_size) { + if (!must_be_aligned || is_size_aligned(region_size, page_size)) { + return page_size; + } } } } @@ -1415,6 +1417,14 @@ size_t os::page_size_for_region(size_t region_size, size_t min_pages) { return vm_page_size(); } +size_t os::page_size_for_region_aligned(size_t region_size, size_t min_pages) { + return page_size_for_region(region_size, min_pages, true); +} + +size_t os::page_size_for_region_unaligned(size_t region_size, size_t min_pages) { + return page_size_for_region(region_size, min_pages, false); +} + #ifndef PRODUCT void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count) { @@ -1663,17 +1673,17 @@ class TestOS : AllStatic { static size_t large_page_size() { const size_t large_page_size_example = 4 * M; - return os::page_size_for_region(large_page_size_example, 1); + return os::page_size_for_region_aligned(large_page_size_example, 1); } - static void test_page_size_for_region() { + static void test_page_size_for_region_aligned() { if (UseLargePages) { const size_t small_page = small_page_size(); const size_t large_page = large_page_size(); if (large_page > small_page) { size_t num_small_pages_in_large = large_page / small_page; - size_t page = os::page_size_for_region(large_page, num_small_pages_in_large); + size_t page = os::page_size_for_region_aligned(large_page, num_small_pages_in_large); assert_eq(page, small_page); } @@ -1686,21 +1696,53 @@ class TestOS : AllStatic { const size_t large_page = large_page_size(); if (large_page > small_page) { const size_t unaligned_region = large_page + 17; - size_t page = os::page_size_for_region(unaligned_region, 1); + size_t page = os::page_size_for_region_aligned(unaligned_region, 1); assert_eq(page, small_page); const size_t num_pages = 5; const size_t aligned_region = large_page * num_pages; - page = os::page_size_for_region(aligned_region, num_pages); + page = os::page_size_for_region_aligned(aligned_region, num_pages); assert_eq(page, large_page); } } } + static void test_page_size_for_region_unaligned() { + if (UseLargePages) { + // Given exact page size, should return that page size. + for (size_t i = 0; os::_page_sizes[i] != 0; i++) { + size_t expected = os::_page_sizes[i]; + size_t actual = os::page_size_for_region_unaligned(expected, 1); + assert_eq(expected, actual); + } + + // Given slightly larger size than a page size, return the page size. + for (size_t i = 0; os::_page_sizes[i] != 0; i++) { + size_t expected = os::_page_sizes[i]; + size_t actual = os::page_size_for_region_unaligned(expected + 17, 1); + assert_eq(expected, actual); + } + + // Given a slightly smaller size than a page size, + // return the next smaller page size. + if (os::_page_sizes[1] > os::_page_sizes[0]) { + size_t expected = os::_page_sizes[0]; + size_t actual = os::page_size_for_region_unaligned(os::_page_sizes[1] - 17, 1); + assert_eq(actual, expected); + } + + // Return small page size for values less than a small page. + size_t small_page = small_page_size(); + size_t actual = os::page_size_for_region_unaligned(small_page - 17, 1); + assert_eq(small_page, actual); + } + } + public: static void run_tests() { - test_page_size_for_region(); + test_page_size_for_region_aligned(); test_page_size_for_region_alignment(); + test_page_size_for_region_unaligned(); } }; diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp index ecd2e24a0fa..67f22264d96 100644 --- a/hotspot/src/share/vm/runtime/os.hpp +++ b/hotspot/src/share/vm/runtime/os.hpp @@ -148,6 +148,7 @@ class os: AllStatic { static void pd_free_memory(char *addr, size_t bytes, size_t alignment_hint); static void pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint); + static size_t page_size_for_region(size_t region_size, size_t min_pages, bool must_be_aligned); public: static void init(void); // Called before command line parsing @@ -267,8 +268,13 @@ class os: AllStatic { // Returns the page size to use for a region of memory. // region_size / min_pages will always be greater than or equal to the - // returned value. - static size_t page_size_for_region(size_t region_size, size_t min_pages); + // returned value. The returned value will divide region_size. + static size_t page_size_for_region_aligned(size_t region_size, size_t min_pages); + + // Returns the page size to use for a region of memory. + // region_size / min_pages will always be greater than or equal to the + // returned value. The returned value might not divide region_size. + static size_t page_size_for_region_unaligned(size_t region_size, size_t min_pages); // Return the largest page size that can be used static size_t max_page_size() { diff --git a/hotspot/src/share/vm/runtime/virtualspace.cpp b/hotspot/src/share/vm/runtime/virtualspace.cpp index b659ec5eb06..d57f1be3973 100644 --- a/hotspot/src/share/vm/runtime/virtualspace.cpp +++ b/hotspot/src/share/vm/runtime/virtualspace.cpp @@ -38,7 +38,8 @@ ReservedSpace::ReservedSpace() : _base(NULL), _size(0), _noaccess_prefix(0), } ReservedSpace::ReservedSpace(size_t size) { - size_t page_size = os::page_size_for_region(size, 1); + // Want to use large pages where possible and pad with small pages. + size_t page_size = os::page_size_for_region_unaligned(size, 1); bool large_pages = page_size != (size_t)os::vm_page_size(); // Don't force the alignment to be large page aligned, // since that will waste memory. @@ -617,7 +618,7 @@ VirtualSpace::VirtualSpace() { bool VirtualSpace::initialize(ReservedSpace rs, size_t committed_size) { - const size_t max_commit_granularity = os::page_size_for_region(rs.size(), 1); + const size_t max_commit_granularity = os::page_size_for_region_unaligned(rs.size(), 1); return initialize_with_granularity(rs, committed_size, max_commit_granularity); } @@ -1239,7 +1240,7 @@ class TestVirtualSpace : AllStatic { case Disable: return vs.initialize_with_granularity(rs, 0, os::vm_page_size()); case Commit: - return vs.initialize_with_granularity(rs, 0, os::page_size_for_region(rs.size(), 1)); + return vs.initialize_with_granularity(rs, 0, os::page_size_for_region_unaligned(rs.size(), 1)); } } From 31f50fcff96fdeab57ea15c9830f301b763fa217 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Fri, 16 Jan 2015 12:41:36 +0100 Subject: [PATCH 102/149] 8068736: Avoid synchronization on Executable/Field.declaredAnnotations Reviewed-by: jfranck, psandoz --- .../classes/java/lang/reflect/Executable.java | 35 +++++++++++-------- .../classes/java/lang/reflect/Field.java | 33 ++++++++++------- 2 files changed, 41 insertions(+), 27 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Executable.java b/jdk/src/java.base/share/classes/java/lang/reflect/Executable.java index 21c90f41da3..ee82de46946 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Executable.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Executable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -588,22 +588,29 @@ public abstract class Executable extends AccessibleObject return AnnotationParser.toArray(declaredAnnotations()); } - private transient Map, Annotation> declaredAnnotations; + private transient volatile Map, Annotation> declaredAnnotations; - private synchronized Map, Annotation> declaredAnnotations() { - if (declaredAnnotations == null) { - Executable root = getRoot(); - if (root != null) { - declaredAnnotations = root.declaredAnnotations(); - } else { - declaredAnnotations = AnnotationParser.parseAnnotations( - getAnnotationBytes(), - sun.misc.SharedSecrets.getJavaLangAccess(). - getConstantPool(getDeclaringClass()), - getDeclaringClass()); + private Map, Annotation> declaredAnnotations() { + Map, Annotation> declAnnos; + if ((declAnnos = declaredAnnotations) == null) { + synchronized (this) { + if ((declAnnos = declaredAnnotations) == null) { + Executable root = getRoot(); + if (root != null) { + declAnnos = root.declaredAnnotations(); + } else { + declAnnos = AnnotationParser.parseAnnotations( + getAnnotationBytes(), + sun.misc.SharedSecrets.getJavaLangAccess(). + getConstantPool(getDeclaringClass()), + getDeclaringClass() + ); + } + declaredAnnotations = declAnnos; + } } } - return declaredAnnotations; + return declAnnos; } /** diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Field.java b/jdk/src/java.base/share/classes/java/lang/reflect/Field.java index bb23b22dc94..cb3cbf5e7d0 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Field.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Field.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -1139,21 +1139,28 @@ class Field extends AccessibleObject implements Member { return AnnotationParser.toArray(declaredAnnotations()); } - private transient Map, Annotation> declaredAnnotations; + private transient volatile Map, Annotation> declaredAnnotations; - private synchronized Map, Annotation> declaredAnnotations() { - if (declaredAnnotations == null) { - Field root = this.root; - if (root != null) { - declaredAnnotations = root.declaredAnnotations(); - } else { - declaredAnnotations = AnnotationParser.parseAnnotations( - annotations, - sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(getDeclaringClass()), - getDeclaringClass()); + private Map, Annotation> declaredAnnotations() { + Map, Annotation> declAnnos; + if ((declAnnos = declaredAnnotations) == null) { + synchronized (this) { + if ((declAnnos = declaredAnnotations) == null) { + Field root = this.root; + if (root != null) { + declAnnos = root.declaredAnnotations(); + } else { + declAnnos = AnnotationParser.parseAnnotations( + annotations, + sun.misc.SharedSecrets.getJavaLangAccess() + .getConstantPool(getDeclaringClass()), + getDeclaringClass()); + } + declaredAnnotations = declAnnos; + } } } - return declaredAnnotations; + return declAnnos; } private native byte[] getTypeAnnotationBytes0(); From 09d92134888a7d23569c63987bddb74bb1ac2b32 Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Fri, 16 Jan 2015 12:02:41 +0000 Subject: [PATCH 103/149] 8069164: Fix langtools make build so that diagnostic framework can be used Fix race condition between gensrc targets and output location of parseproperties task Reviewed-by: erikj, jlahoda --- langtools/make/Tools.gmk | 1 + langtools/make/gensrc/Gensrc-jdk.compiler.gmk | 10 +++++----- langtools/make/gensrc/GensrcCommon.gmk | 19 ++++++++++--------- .../sun/tools/javac/comp/DeferredAttr.java | 4 +++- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/langtools/make/Tools.gmk b/langtools/make/Tools.gmk index ea2452387cc..d6fae56280d 100644 --- a/langtools/make/Tools.gmk +++ b/langtools/make/Tools.gmk @@ -40,6 +40,7 @@ $(eval $(call SetupJavaCompilation,BUILD_TOOLS_LANGTOOLS, \ ADD_JAVAC_FLAGS := -Xprefer:source, \ SRC := $(LANGTOOLS_TOPDIR)/make/tools, \ INCLUDES := compileproperties propertiesparser, \ + COPY := .properties, \ BIN := $(BUILDTOOLS_OUTPUTDIR)/langtools_tools_classes)) all: $(BUILD_TOOLS_LANGTOOLS) diff --git a/langtools/make/gensrc/Gensrc-jdk.compiler.gmk b/langtools/make/gensrc/Gensrc-jdk.compiler.gmk index 04a0479fad7..0caef1da1ae 100644 --- a/langtools/make/gensrc/Gensrc-jdk.compiler.gmk +++ b/langtools/make/gensrc/Gensrc-jdk.compiler.gmk @@ -25,19 +25,19 @@ include GensrcCommon.gmk -$(eval $(call SetupVersionProperties,JAVAC_VERSION,\ +$(eval $(call SetupVersionProperties,JAVAC_VERSION, \ com/sun/tools/javac/resources/version.properties)) -$(eval $(call SetupVersionProperties,JAVAH_VERSION,\ +$(eval $(call SetupVersionProperties,JAVAH_VERSION, \ com/sun/tools/javah/resources/version.properties)) -$(eval $(call SetupVersionProperties,JAVAP_VERSION,\ +$(eval $(call SetupVersionProperties,JAVAP_VERSION, \ com/sun/tools/javap/resources/version.properties)) -$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES,\ +$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \ $(JAVAC_VERSION) $(JAVAH_VERSION) $(JAVAP_VERSION))) -$(eval $(call SetupParseProperties,PARSE_PROPERTIES,\ +$(eval $(call SetupParseProperties,PARSE_PROPERTIES, \ com/sun/tools/javac/resources/compiler.properties)) all: $(COMPILE_PROPERTIES) $(PARSE_PROPERTIES) diff --git a/langtools/make/gensrc/GensrcCommon.gmk b/langtools/make/gensrc/GensrcCommon.gmk index 0b38117030c..adf934aae0f 100644 --- a/langtools/make/gensrc/GensrcCommon.gmk +++ b/langtools/make/gensrc/GensrcCommon.gmk @@ -63,7 +63,8 @@ endef # Param 2 - Extra properties files to process define SetupCompileProperties # Lookup the properties that need to be compiled into resource bundles. - PROPSOURCES := $2 $$(shell $(FIND) $(LANGTOOLS_TOPDIR)/src/$(MODULE)/share/classes -name "*.properties") + PROPSOURCES := $2 \ + $$(shell $(FIND) $(LANGTOOLS_TOPDIR)/src/$(MODULE)/share/classes -name "*.properties") # Convert .../src//share/classes/com/sun/tools/javac/resources/javac_zh_CN.properties # to .../langtools/gensrc//com/sun/tools/javac/resources/javac_zh_CN.java @@ -74,7 +75,7 @@ define SetupCompileProperties $$(patsubst %.properties, %.java, \ $$(subst /share/classes,, $$(PROPSOURCES)))) - # Generate the package dirs for the tobe generated java files. Sort to remove + # Generate the package dirs for the to be generated java files. Sort to remove # duplicates. PROPDIRS := $$(sort $$(dir $$(PROPJAVAS))) @@ -88,8 +89,8 @@ define SetupCompileProperties # Now setup the rule for the generation of the resource bundles. $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/_the_props: $$(PROPSOURCES) - $(FIND) $$(@D) -name "*.java" $(FIND_DELETE) $(MKDIR) -p $$(@D) $$(PROPDIRS) + $(FIND) $$(@D) -name "*.java" -a ! -name "*Properties.java" $(FIND_DELETE) $(ECHO) Compiling $$(words $$(PROPSOURCES)) properties into resource bundles for $(MODULE) $(TOOL_COMPILEPROPS_CMD) $$(PROPCMDLINE) $(TOUCH) $$@ @@ -102,11 +103,11 @@ endef # Param 1 - Variable to add targets to # Param 2 - Extra properties files to process define SetupParseProperties - #property file to generate - PARSEPROPSOURCES := $$(foreach var,$2,$$(addsuffix $$(var),$(LANGTOOLS_TOPDIR)/src/$(MODULE)/share/classes/)) + # property files to process + PARSEPROPSOURCES := $$(addprefix $(LANGTOOLS_TOPDIR)/src/$(MODULE)/share/classes/, $2) - PARSEPROPALLDIRS := $$(patsubst $(LANGTOOLS_TOPDIR)/src/%, \ - $(SUPPORT_OUTPUTDIR)/gensrc/%, \ + PARSEPROPALLDIRS := $$(patsubst $(LANGTOOLS_TOPDIR)/src/$(MODULE)/share/classes/%, \ + $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/%, \ $$(dir $$(PARSEPROPSOURCES))) PARSEPROPDIRS := $$(sort $$(PARSEPROPALLDIRS)) @@ -114,11 +115,11 @@ define SetupParseProperties PARSEPROPCMDLINE := $$(subst _SPACE_, $$(SPACE), \ $$(join $$(foreach var,$$(PARSEPROPSOURCES),$$(addprefix -compile_SPACE_,$$(var))), \ $$(addprefix _SPACE_, $$(PARSEPROPALLDIRS)))) - + # Now setup the rule for the generation of the resource bundles. $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/_the_parsed_props: $(PARSEPROPSOURCES) - $(CP) -r $(LANGTOOLS_TOPDIR)/make/tools/propertiesparser/resources $(BUILDTOOLS_OUTPUTDIR)/langtools_tools_classes/propertiesparser/resources $(MKDIR) -p $$(@D) $$(PARSEPROPDIRS) + $(FIND) $$(@D) -name "*Properties.java" $(FIND_DELETE) $(ECHO) Parsing $$(words $$(PARSEPROPSOURCES)) properties into enum-like class for $(MODULE) $(TOOL_PARSEPROPS_CMD) $$(PARSEPROPCMDLINE) $(TOUCH) $$@ diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java index d2dc52167c4..2fb3b0fe757 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java @@ -28,6 +28,8 @@ package com.sun.tools.javac.comp; import com.sun.source.tree.LambdaExpressionTree.BodyKind; import com.sun.tools.javac.code.*; import com.sun.tools.javac.comp.Resolve.ResolveError; +import com.sun.tools.javac.resources.CompilerProperties; +import com.sun.tools.javac.resources.CompilerProperties.Fragments; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.DefinedBy.Api; @@ -796,7 +798,7 @@ public class DeferredAttr extends JCTree.Visitor { case WRONG_MTHS: //note: as argtypes are erroneous types, type-errors must //have been caused by arity mismatch - checkContext.report(tree, diags.fragment("incompatible.arg.types.in.mref")); + checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInMref)); break; case ABSENT_MTH: case STATICERR: From 427f25366eb336d3e6c4d0e511f600e40ecd4ac6 Mon Sep 17 00:00:00 2001 From: Dmitrij Pochepko Date: Fri, 16 Jan 2015 20:59:23 +0400 Subject: [PATCH 104/149] 8068385: [TESTBUG] hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java sometimes fails(unstable behaviour) Fixing unstable behaviour of 2 tests Reviewed-by: iignatyev --- .../codecache/jmx/PoolsIndependenceTest.java | 12 +++++++----- .../codecache/jmx/ThresholdNotificationsTest.java | 4 +++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java b/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java index 04551a2d2df..8e390c1d70d 100644 --- a/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java +++ b/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java @@ -98,11 +98,13 @@ public class PoolsIndependenceTest implements NotificationListener { return false; }); for (BlobType bt : BlobType.getAvailable()) { - int expectedNotificationsAmount = bt.equals(btype) ? 1 : 0; - Asserts.assertEQ(counters.get(bt.getMemoryPool().getName()).get(), - expectedNotificationsAmount, String.format("Unexpected " - + "amount of notifications for pool: %s", - bt.getMemoryPool().getName())); + if (CodeCacheUtils.isCodeHeapPredictable(bt)) { + int expectedNotificationsAmount = bt.equals(btype) ? 1 : 0; + Asserts.assertEQ(counters.get(bt.getMemoryPool().getName()).get(), + expectedNotificationsAmount, String.format("Unexpected " + + "amount of notifications for pool: %s", + bt.getMemoryPool().getName())); + } } try { ((NotificationEmitter) ManagementFactory.getMemoryMXBean()). diff --git a/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java b/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java index b03fbc2f4a7..fea786ebe1a 100644 --- a/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java +++ b/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java @@ -52,7 +52,9 @@ public class ThresholdNotificationsTest implements NotificationListener { public static void main(String[] args) { for (BlobType bt : BlobType.getAvailable()) { - new ThresholdNotificationsTest(bt).runTest(); + if (CodeCacheUtils.isCodeHeapPredictable(bt)) { + new ThresholdNotificationsTest(bt).runTest(); + } } } From 0b17d19f488958195d41e89b2ceda9f04a647a2b Mon Sep 17 00:00:00 2001 From: Pavel Chistyakov Date: Fri, 16 Jan 2015 15:08:20 +0300 Subject: [PATCH 105/149] 8068231: Several tests are still excluded Reviewed-by: kvn, iignatyev --- hotspot/test/compiler/loopopts/7052494/Test7052494.java | 1 - 1 file changed, 1 deletion(-) diff --git a/hotspot/test/compiler/loopopts/7052494/Test7052494.java b/hotspot/test/compiler/loopopts/7052494/Test7052494.java index fa454112b6d..62aa12fc427 100644 --- a/hotspot/test/compiler/loopopts/7052494/Test7052494.java +++ b/hotspot/test/compiler/loopopts/7052494/Test7052494.java @@ -25,7 +25,6 @@ /** * @test * @bug 7052494 - * @ignore 7154567 * @summary Eclipse test fails on JDK 7 b142 * * @run main/othervm -Xbatch Test7052494 From 0520df8a92404becac0f319ba59158e50dca112c Mon Sep 17 00:00:00 2001 From: Axel Siebenborn Date: Fri, 16 Jan 2015 13:58:22 +0100 Subject: [PATCH 106/149] 8068909: SIGSEGV in c2 compiled code with OptimizeStringConcat Reviewed-by: kvn --- hotspot/src/share/vm/opto/stringopts.cpp | 11 ++- .../stringopts/TestOptimizeStringConcat.java | 89 +++++++++++++++++++ 2 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 hotspot/test/compiler/stringopts/TestOptimizeStringConcat.java diff --git a/hotspot/src/share/vm/opto/stringopts.cpp b/hotspot/src/share/vm/opto/stringopts.cpp index 1d9bae5a6ac..5f7da1f8c74 100644 --- a/hotspot/src/share/vm/opto/stringopts.cpp +++ b/hotspot/src/share/vm/opto/stringopts.cpp @@ -1507,10 +1507,12 @@ void PhaseStringOpts::replace_string_concat(StringConcat* sc) { } case StringConcat::StringMode: { const Type* type = kit.gvn().type(arg); + Node* count = NULL; if (type == TypePtr::NULL_PTR) { // replace the argument with the null checked version arg = null_string; sc->set_argument(argi, arg); + count = kit.load_String_length(kit.control(), arg); } else if (!type->higher_equal(TypeInstPtr::NOTNULL)) { // s = s != null ? s : "null"; // length = length + (s.count - s.offset); @@ -1533,10 +1535,13 @@ void PhaseStringOpts::replace_string_concat(StringConcat* sc) { // replace the argument with the null checked version arg = phi; sc->set_argument(argi, arg); + count = kit.load_String_length(kit.control(), arg); + } else { + // A corresponding nullcheck will be connected during IGVN MemNode::Ideal_common_DU_postCCP + // kit.control might be a different test, that can be hoisted above the actual nullcheck + // in case, that the control input is not null, Ideal_common_DU_postCCP will not look for a nullcheck. + count = kit.load_String_length(NULL, arg); } - - Node* count = kit.load_String_length(kit.control(), arg); - length = __ AddI(length, count); string_sizes->init_req(argi, NULL); break; diff --git a/hotspot/test/compiler/stringopts/TestOptimizeStringConcat.java b/hotspot/test/compiler/stringopts/TestOptimizeStringConcat.java new file mode 100644 index 00000000000..771ffb0bd68 --- /dev/null +++ b/hotspot/test/compiler/stringopts/TestOptimizeStringConcat.java @@ -0,0 +1,89 @@ +/* + * Copyright 2015 SAP AG. 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 8068909 + * @key regression + * @summary test that string optimizations produce code, that doesn't lead to a crash. + * @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement TestOptimizeStringConcat + * @author axel.siebenborn@sap.com + */ +public class TestOptimizeStringConcat { + + static boolean checkArgumentSyntax(String value, String allowedchars, String notallowedchars, String logmsg) { + String rc = null; + + int maxchar = 99999; + int minchar = 1; + if ((allowedchars != null && notallowedchars != null) || minchar > maxchar) { + rc = "internal error"; + } else { + if (value == null) { + rc = "the value null is not allowed, it is missing"; + } else if (value != null && minchar > 0 && value.trim().equals("")) { + rc = "the value must not be empty"; + } else if (value != null) { + if (value.length() < minchar || value.length() > maxchar) { + if (rc == null) { + rc = "the value length must be between +minchar+ and +maxchar"; + } + } + char[] _value = value.toCharArray(); + boolean dotfound = false; + int i = 1; + if (_value[i] == '.' && !dotfound) { + dotfound = true; + } else if (allowedchars != null && allowedchars.indexOf(_value[i]) == -1) { + if (rc == null) { + rc = "the value contains an illegal character: '" + _value[i] + "', only following characters are allowed: '+allowedchars+'"; + } else { + rc += " / the value contains an illegal character: '" + _value[i] + "', only following characters are allowed: '+allowedchars+'"; + } + } else if (notallowedchars != null && notallowedchars.indexOf(_value[i]) != -1) { + if (rc == null) { + rc = "the value contains an illegal character: '" + _value[i] + "', following characters are not allowed '+notallowedchars+'"; + } else { + rc += " / the value contains an illegal character: '" + _value[i] + "', following characters are not allowed '+notallowedchars+'"; + } + } + } + } + + if (rc != null) { + System.out.println(logmsg + " ==> " + rc); + return false; + } + return true; + } + + public static void main(String[] args) { + boolean failed = false; + for (int i = 0; i < 10000; i++) { + failed |= !checkArgumentSyntax("theName", null, "\"<&", "Error consistencyCheck: name in component definition"); + failed |= !checkArgumentSyntax(null, null, "\"<&", "Error consistencyCheck: name in component definition"); + failed |= !checkArgumentSyntax("42", "0123456789.", null, "Error consistencyCheck: counter in component definition"); + } + System.out.println(failed); + } +} From 759740976be0bb7da8f3f4a7491cca7055201dfb Mon Sep 17 00:00:00 2001 From: Erik Helin Date: Fri, 16 Jan 2015 14:43:45 +0100 Subject: [PATCH 107/149] 8068971: A heap region being cleared should not belong to the cset Reviewed-by: brutisso, tschatzl --- hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp index 5ead54b16a5..d5eaf9f8da3 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp @@ -162,8 +162,8 @@ void HeapRegion::hr_clear(bool par, bool clear_space, bool locked) { "we should have already filtered out humongous regions"); assert(_end == orig_end(), "we should have already filtered out humongous regions"); - - _in_collection_set = false; + assert(!_in_collection_set, + err_msg("Should not clear heap region %u in the collection set", hrm_index())); set_allocation_context(AllocationContext::system()); set_young_index_in_cset(-1); From 56c4de876e2ddc45a6417c6774f4ae3d90356f3b Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Fri, 16 Jan 2015 14:47:25 +0100 Subject: [PATCH 108/149] 8068517: Compiler may generate wrong InnerClasses attribute for static enum reference Making sure enum's abstractness is resolved before writing InnerClasses entry about it. Reviewed-by: mcimadamore --- .../com/sun/tools/javac/code/Symbol.java | 10 ++ .../com/sun/tools/javac/code/Types.java | 55 +++++++++ .../com/sun/tools/javac/comp/Attr.java | 2 + .../com/sun/tools/javac/comp/Check.java | 68 ++-------- .../com/sun/tools/javac/jvm/ClassWriter.java | 1 + .../classfiles/InnerClasses/T8068517.java | 116 ++++++++++++++++++ 6 files changed, 191 insertions(+), 61 deletions(-) create mode 100644 langtools/test/tools/javac/classfiles/InnerClasses/T8068517.java diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java index a12083660cb..e4b88fa22c8 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java @@ -1175,6 +1175,16 @@ public abstract class Symbol extends AnnoConstruct implements Element { return v.visitClassSymbol(this, p); } + public void markAbstractIfNeeded(Types types) { + if (types.enter.getEnv(this) != null && + (flags() & ENUM) != 0 && types.supertype(type).tsym == types.syms.enumSym && + (flags() & (FINAL | ABSTRACT)) == 0) { + if (types.firstUnimplementedAbstract(this) != null) + // add the ABSTRACT flag to an enum + flags_field |= ABSTRACT; + } + } + /**Resets the Symbol into the state good for next round of annotation processing.*/ public void reset() { kind = TYP; diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java index f265e0651e2..fd71de9498f 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java @@ -48,6 +48,7 @@ import static com.sun.tools.javac.code.BoundKind.*; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.Kinds.Kind.*; import static com.sun.tools.javac.code.Scope.*; +import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; import static com.sun.tools.javac.code.Symbol.*; import static com.sun.tools.javac.code.Type.*; import static com.sun.tools.javac.code.TypeTag.*; @@ -82,6 +83,7 @@ public class Types { final JavacMessages messages; final Names names; final boolean allowObjectToPrimitiveCast; + final boolean allowDefaultMethods; final Check chk; final Enter enter; JCDiagnostic.Factory diags; @@ -105,6 +107,7 @@ public class Types { names = Names.instance(context); Source source = Source.instance(context); allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast(); + allowDefaultMethods = source.allowDefaultMethods(); chk = Check.instance(context); enter = Enter.instance(context); capturedName = names.fromString(""); @@ -2775,6 +2778,58 @@ public class Types { // + /** Return first abstract member of class `sym'. + */ + public MethodSymbol firstUnimplementedAbstract(ClassSymbol sym) { + try { + return firstUnimplementedAbstractImpl(sym, sym); + } catch (CompletionFailure ex) { + chk.completionError(enter.getEnv(sym).tree.pos(), ex); + return null; + } + } + //where: + private MethodSymbol firstUnimplementedAbstractImpl(ClassSymbol impl, ClassSymbol c) { + MethodSymbol undef = null; + // Do not bother to search in classes that are not abstract, + // since they cannot have abstract members. + if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) { + Scope s = c.members(); + for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { + if (sym.kind == MTH && + (sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) { + MethodSymbol absmeth = (MethodSymbol)sym; + MethodSymbol implmeth = absmeth.implementation(impl, this, true); + if (implmeth == null || implmeth == absmeth) { + //look for default implementations + if (allowDefaultMethods) { + MethodSymbol prov = interfaceCandidates(impl.type, absmeth).head; + if (prov != null && prov.overrides(absmeth, impl, this, true)) { + implmeth = prov; + } + } + } + if (implmeth == null || implmeth == absmeth) { + undef = absmeth; + break; + } + } + } + if (undef == null) { + Type st = supertype(c.type); + if (st.hasTag(CLASS)) + undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)st.tsym); + } + for (List l = interfaces(c.type); + undef == null && l.nonEmpty(); + l = l.tail) { + undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)l.head.tsym); + } + } + return undef; + } + + //where public List interfaceCandidates(Type site, MethodSymbol ms) { Filter filter = new MethodFilter(ms, site); diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index d2933a0521a..a7303bef959 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -4188,6 +4188,8 @@ public class Attr extends JCTree.Visitor { chk.validate(tree.implementing, env); } + c.markAbstractIfNeeded(types); + // If this is a non-abstract class, check that it has no abstract // methods or unimplemented methods of an implemented interface. if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 4db2a418875..4d3774fbf29 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -2019,69 +2019,15 @@ public class Check { * @param c The class. */ void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) { - try { - MethodSymbol undef = firstUndef(c, c); - if (undef != null) { - if ((c.flags() & ENUM) != 0 && - types.supertype(c.type).tsym == syms.enumSym && - (c.flags() & FINAL) == 0) { - // add the ABSTRACT flag to an enum - c.flags_field |= ABSTRACT; - } else { - MethodSymbol undef1 = - new MethodSymbol(undef.flags(), undef.name, - types.memberType(c.type, undef), undef.owner); - log.error(pos, "does.not.override.abstract", - c, undef1, undef1.location()); - } - } - } catch (CompletionFailure ex) { - completionError(pos, ex); + MethodSymbol undef = types.firstUnimplementedAbstract(c); + if (undef != null) { + MethodSymbol undef1 = + new MethodSymbol(undef.flags(), undef.name, + types.memberType(c.type, undef), undef.owner); + log.error(pos, "does.not.override.abstract", + c, undef1, undef1.location()); } } -//where - /** Return first abstract member of class `c' that is not defined - * in `impl', null if there is none. - */ - private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) { - MethodSymbol undef = null; - // Do not bother to search in classes that are not abstract, - // since they cannot have abstract members. - if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) { - Scope s = c.members(); - for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { - if (sym.kind == MTH && - (sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) { - MethodSymbol absmeth = (MethodSymbol)sym; - MethodSymbol implmeth = absmeth.implementation(impl, types, true); - if (implmeth == null || implmeth == absmeth) { - //look for default implementations - if (allowDefaultMethods) { - MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head; - if (prov != null && prov.overrides(absmeth, impl, types, true)) { - implmeth = prov; - } - } - } - if (implmeth == null || implmeth == absmeth) { - undef = absmeth; - break; - } - } - } - if (undef == null) { - Type st = types.supertype(c.type); - if (st.hasTag(CLASS)) - undef = firstUndef(impl, (ClassSymbol)st.tsym); - } - for (List l = types.interfaces(c.type); - undef == null && l.nonEmpty(); - l = l.tail) { - undef = firstUndef(impl, (ClassSymbol)l.head.tsym); - } - } - return undef; - } void checkNonCyclicDecl(JCClassDecl tree) { CycleChecker cc = new CycleChecker(); diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java index 3721b329571..1c0e957e45b 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java @@ -1000,6 +1000,7 @@ public class ClassWriter extends ClassFile { l.nonEmpty(); l = l.tail) { ClassSymbol inner = l.head; + inner.markAbstractIfNeeded(types); char flags = (char) adjustFlags(inner.flags_field); if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag diff --git a/langtools/test/tools/javac/classfiles/InnerClasses/T8068517.java b/langtools/test/tools/javac/classfiles/InnerClasses/T8068517.java new file mode 100644 index 00000000000..665474a7579 --- /dev/null +++ b/langtools/test/tools/javac/classfiles/InnerClasses/T8068517.java @@ -0,0 +1,116 @@ +/* + * 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 8034854 + * @summary Verify that nested enums have correct abstract flag in the InnerClasses attribute. + * @library /tools/lib + * @build ToolBox T8068517 + * @run main T8068517 + */ + +import com.sun.tools.javac.util.Assert; +import java.util.Arrays; +import javax.tools.JavaFileManager; +import javax.tools.StandardLocation; +import javax.tools.ToolProvider; + +public class T8068517 { + + public static void main(String[] args) throws Exception { + new T8068517().run(); + } + + void run() throws Exception { + runTest("class A {\n" + + " enum AInner implements Runnable {\n" + + " A {\n" + + " public void run() {}\n" + + " };\n" + + " }\n" + + "}\n", + "class B {\n" + + " A.AInner a;\n" + + "}"); + runTest("class A {\n" + + " enum AInner implements Runnable {\n" + + " A {\n" + + " public void run() {}\n" + + " };\n" + + " }\n" + + " AInner aInner;\n" + + "}\n", + "class B {\n" + + " void test(A a) {;\n" + + " switch (a.aInner) {\n" + + " case A: break;\n" + + " }\n" + + " };\n" + + "}"); + runTest("class A {\n" + + " enum AInner implements Runnable {\n" + + " A {\n" + + " public void run() {}\n" + + " };\n" + + " }\n" + + " AInner aInner;\n" + + "}\n", + "class B {\n" + + " void test(A a) {;\n" + + " System.err.println(a.aInner.toString());\n" + + " };\n" + + "}"); + runTest("class A {\n" + + " enum AInner implements Runnable {\n" + + " A {\n" + + " public void run() {}\n" + + " };\n" + + " }\n" + + " AInner aInner() {\n" + + " return null;\n" + + " }\n" + + "}\n", + "class B {\n" + + " void test(A a) {;\n" + + " System.err.println(a.aInner().toString());\n" + + " };\n" + + "}"); + } + + void runTest(String aJava, String bJava) throws Exception { + try (JavaFileManager fm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null)) { + ToolBox tb = new ToolBox(); + ToolBox.MemoryFileManager memoryFM1 = new ToolBox.MemoryFileManager(fm); + tb.new JavacTask().fileManager(memoryFM1) + .sources(aJava, bJava) + .run(); + ToolBox.MemoryFileManager memoryFM2 = new ToolBox.MemoryFileManager(fm); + tb.new JavacTask().fileManager(memoryFM2) + .sources(bJava, aJava) + .run(); + + Assert.check(Arrays.equals(memoryFM1.getFileBytes(StandardLocation.CLASS_OUTPUT, "B"), + memoryFM2.getFileBytes(StandardLocation.CLASS_OUTPUT, "B"))); + } + } +} From 6c9d4861a9b99c1d586bcddd9ada5f8b7c1ce4a2 Mon Sep 17 00:00:00 2001 From: Robert Field Date: Fri, 16 Jan 2015 20:03:30 -0800 Subject: [PATCH 109/149] 8068488: Facilitate extension of the javac parser -- missing modifier Reviewed-by: jjg --- .../sun/tools/javac/parser/JavacParser.java | 2 +- .../parser/extend/JavacExtensionTest.java | 93 +++++++ .../javac/parser/extend/TrialParser.java | 253 ++++++++++++++++++ .../parser/extend/TrialParserFactory.java | 55 ++++ 4 files changed, 402 insertions(+), 1 deletion(-) create mode 100644 langtools/test/tools/javac/parser/extend/JavacExtensionTest.java create mode 100644 langtools/test/tools/javac/parser/extend/TrialParser.java create mode 100644 langtools/test/tools/javac/parser/extend/TrialParserFactory.java diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java index 2ef5620a04a..191b1d5e703 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java @@ -85,7 +85,7 @@ public class JavacParser implements Parser { private Names names; /** End position mappings container */ - private final AbstractEndPosTable endPosTable; + protected final AbstractEndPosTable endPosTable; // Because of javac's limited lookahead, some contexts are ambiguous in // the presence of type annotations even though they are not ambiguous diff --git a/langtools/test/tools/javac/parser/extend/JavacExtensionTest.java b/langtools/test/tools/javac/parser/extend/JavacExtensionTest.java new file mode 100644 index 00000000000..834d3692030 --- /dev/null +++ b/langtools/test/tools/javac/parser/extend/JavacExtensionTest.java @@ -0,0 +1,93 @@ +/* + * 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 com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.Tree; +import com.sun.source.util.SourcePositions; +import com.sun.source.util.TreePath; +import com.sun.source.util.Trees; +import com.sun.tools.javac.api.JavacTaskImpl; +import com.sun.tools.javac.api.JavacTool; +import com.sun.tools.javac.util.Context; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import javax.lang.model.element.Element; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.ToolProvider; +import javax.tools.StandardJavaFileManager; +import com.sun.source.tree.ImportTree; +import java.util.Collections; +import java.io.PrintWriter; +import com.sun.source.tree.VariableTree; +import static javax.tools.StandardLocation.CLASS_OUTPUT; + +/* + * @test + * @bug 8067384 8068488 + * @summary Verify that JavacParser can be extended + */ +public class JavacExtensionTest { + + public static void main(String[] args) throws Exception { + PrintWriter pw = new PrintWriter("trialSource.java", "UTF-8"); + pw.println("int x = 9;"); + pw.close(); + List defs = parse("trialSource.java"); + if (defs.size() != 1) { + throw new AssertionError("Expected only one def, got: " + defs.size()); + } + Tree tree = defs.get(0); + if (tree instanceof VariableTree) { + System.out.println("Passes! --- " + tree); + } else { + throw new AssertionError("Expected VariableTree, got: " + tree); + } + } + + static List parse(String srcfile) throws Exception { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); + Iterable fileObjects = fileManager.getJavaFileObjects(srcfile); + String classPath = System.getProperty("java.class.path"); + List options = Arrays.asList("-classpath", classPath); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + Context context = new Context(); + JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null, + diagnostics, options, null, fileObjects, context); + TrialParserFactory.instance(context); + Iterable asts = task.parse(); + Iterator it = asts.iterator(); + if (it.hasNext()) { + CompilationUnitTree cut = it.next(); + return cut.getTypeDecls(); + } else { + throw new AssertionError("Expected compilation unit"); + } + } +} diff --git a/langtools/test/tools/javac/parser/extend/TrialParser.java b/langtools/test/tools/javac/parser/extend/TrialParser.java new file mode 100644 index 00000000000..0ff5b0cccbf --- /dev/null +++ b/langtools/test/tools/javac/parser/extend/TrialParser.java @@ -0,0 +1,253 @@ +/* + * 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 com.sun.tools.javac.code.TypeTag; +import com.sun.tools.javac.parser.JavacParser; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.parser.Tokens.Comment; +import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; +import com.sun.tools.javac.parser.Tokens.Token; +import static com.sun.tools.javac.parser.Tokens.TokenKind.CLASS; +import static com.sun.tools.javac.parser.Tokens.TokenKind.COLON; +import static com.sun.tools.javac.parser.Tokens.TokenKind.ENUM; +import static com.sun.tools.javac.parser.Tokens.TokenKind.EOF; +import static com.sun.tools.javac.parser.Tokens.TokenKind.IMPORT; +import static com.sun.tools.javac.parser.Tokens.TokenKind.INTERFACE; +import static com.sun.tools.javac.parser.Tokens.TokenKind.LPAREN; +import static com.sun.tools.javac.parser.Tokens.TokenKind.MONKEYS_AT; +import static com.sun.tools.javac.parser.Tokens.TokenKind.PACKAGE; +import static com.sun.tools.javac.parser.Tokens.TokenKind.SEMI; +import static com.sun.tools.javac.parser.Tokens.TokenKind.VOID; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; +import com.sun.tools.javac.tree.JCTree.JCModifiers; +import com.sun.tools.javac.tree.JCTree.JCPackageDecl; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.tree.JCTree.Tag; +import static com.sun.tools.javac.tree.JCTree.Tag.IDENT; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.Position; + +/** + * + * @author Robert Field + */ +class TrialParser extends JavacParser { + + public TrialParser(ParserFactory fac, + com.sun.tools.javac.parser.Lexer S, + boolean keepDocComments, + boolean keepLineMap, + boolean keepEndPositions) { + super(fac, S, keepDocComments, keepLineMap, keepEndPositions); + } + + @Override + public JCCompilationUnit parseCompilationUnit() { + Token firstToken = token; + JCModifiers mods = null; + boolean seenImport = false; + boolean seenPackage = false; + ListBuffer defs = new ListBuffer<>(); + if (token.kind == MONKEYS_AT) { + mods = modifiersOpt(); + } + + if (token.kind == PACKAGE) { + int packagePos = token.pos; + List annotations = List.nil(); + seenPackage = true; + if (mods != null) { + checkNoMods(mods.flags); + annotations = mods.annotations; + mods = null; + } + nextToken(); + JCExpression pid = qualident(false); + accept(SEMI); + JCPackageDecl pd = F.at(packagePos).PackageDecl(annotations, pid); + attach(pd, firstToken.comment(CommentStyle.JAVADOC)); + storeEnd(pd, token.pos); + defs.append(pd); + } + + boolean firstTypeDecl = true; + while (token.kind != EOF) { + if (token.pos > 0 && token.pos <= endPosTable.errorEndPos) { + // error recovery + skip(true, false, false, false); + if (token.kind == EOF) { + break; + } + } + if (mods == null && token.kind == IMPORT) { + seenImport = true; + defs.append(importDeclaration()); + break; + } else { + Comment docComment = token.comment(CommentStyle.JAVADOC); + if (firstTypeDecl && !seenImport && !seenPackage) { + docComment = firstToken.comment(CommentStyle.JAVADOC); + } + List udefs = aUnit(mods, docComment); + for (JCTree def : udefs) { + defs.append(def); + } + mods = null; + firstTypeDecl = false; + break; + } + } + List rdefs = defs.toList(); + class TrialUnit extends JCCompilationUnit { + + public TrialUnit(List defs) { + super(defs); + } + } + JCCompilationUnit toplevel = new TrialUnit(rdefs); + if (rdefs.isEmpty()) { + storeEnd(toplevel, S.prevToken().endPos); + } + toplevel.lineMap = S.getLineMap(); + this.endPosTable.setParser(null); // remove reference to parser + toplevel.endPositions = this.endPosTable; + return toplevel; + } + + List aUnit(JCModifiers pmods, Comment dc) { + switch (token.kind) { + case EOF: + return List.nil(); + case RBRACE: + case CASE: + case DEFAULT: + // These are illegal, fall through to handle as illegal statement + case LBRACE: + case IF: + case FOR: + case WHILE: + case DO: + case TRY: + case SWITCH: + case SYNCHRONIZED: + case RETURN: + case THROW: + case BREAK: + case CONTINUE: + case SEMI: + case ELSE: + case FINALLY: + case CATCH: + case ASSERT: + return List.of(parseStatement()); + default: + JCModifiers mods = modifiersOpt(pmods); + if (token.kind == CLASS + || token.kind == INTERFACE + || token.kind == ENUM) { + return List.of(classOrInterfaceOrEnumDeclaration(mods, dc)); + } else { + int pos = token.pos; + List typarams = typeParametersOpt(); + // if there are type parameters but no modifiers, save the start + // position of the method in the modifiers. + if (typarams.nonEmpty() && mods.pos == Position.NOPOS) { + mods.pos = pos; + storeEnd(mods, pos); + } + List annosAfterParams = annotationsOpt(Tag.ANNOTATION); + + if (annosAfterParams.nonEmpty()) { + checkAnnotationsAfterTypeParams(annosAfterParams.head.pos); + mods.annotations = mods.annotations.appendList(annosAfterParams); + if (mods.pos == Position.NOPOS) { + mods.pos = mods.annotations.head.pos; + } + } + + Token prevToken = token; + pos = token.pos; + JCExpression t; + boolean isVoid = token.kind == VOID; + if (isVoid) { + t = to(F.at(pos).TypeIdent(TypeTag.VOID)); + nextToken(); + } else { + // return type of method, declared type of variable, or an expression + t = term(EXPR | TYPE); + } + if (token.kind == COLON && t.hasTag(IDENT)) { + // labelled statement + nextToken(); + JCStatement stat = parseStatement(); + return List.of(F.at(pos).Labelled(prevToken.name(), stat)); + } else if ((isVoid || (lastmode & TYPE) != 0) && LAX_IDENTIFIER.accepts(token.kind)) { + // we have "Type Ident", so we can assume it is variable or method declaration + pos = token.pos; + Name name = ident(); + if (token.kind == LPAREN) { + // method declaration + //mods.flags |= Flags.STATIC; + return List.of(methodDeclaratorRest( + pos, mods, t, name, typarams, + false, isVoid, dc)); + } else if (!isVoid && typarams.isEmpty()) { + // variable declaration + //mods.flags |= Flags.STATIC; + List defs + = variableDeclaratorsRest(pos, mods, t, name, false, dc, + new ListBuffer()).toList(); + accept(SEMI); + storeEnd(defs.last(), S.prevToken().endPos); + return defs; + } else { + // malformed declaration, return error + pos = token.pos; + List err = isVoid + ? List.of(toP(F.at(pos).MethodDef(mods, name, t, typarams, + List.nil(), List.nil(), null, null))) + : null; + return List.of(syntaxError(token.pos, err, "expected", LPAREN)); + } + } else if (!typarams.isEmpty()) { + // type parameters on non-variable non-method -- error + return List.of(syntaxError(token.pos, "illegal.start.of.type")); + } else { + // expression-statement or expression to evaluate + accept(SEMI); + JCExpressionStatement expr = toP(F.at(pos).Exec(t)); + return List.of(expr); + } + + } + } + } +} diff --git a/langtools/test/tools/javac/parser/extend/TrialParserFactory.java b/langtools/test/tools/javac/parser/extend/TrialParserFactory.java new file mode 100644 index 00000000000..39ff06c4a8b --- /dev/null +++ b/langtools/test/tools/javac/parser/extend/TrialParserFactory.java @@ -0,0 +1,55 @@ +/* + * 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 com.sun.tools.javac.parser.JavacParser; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.parser.ScannerFactory; +import com.sun.tools.javac.util.Context; + +/** + * + * @author Robert Field + */ +class TrialParserFactory extends ParserFactory { + + public static ParserFactory instance(Context context) { + ParserFactory instance = context.get(parserFactoryKey); + if (instance == null) { + instance = new TrialParserFactory(context); + } + return instance; + } + + private final ScannerFactory scannerFactory; + + protected TrialParserFactory(Context context) { + super(context); + this.scannerFactory = ScannerFactory.instance(context); + } + + @Override + public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) { + com.sun.tools.javac.parser.Lexer lexer = scannerFactory.newScanner(input, keepDocComments); + return new TrialParser(this, lexer, keepDocComments, keepLineMap, keepEndPos); + } +} From eb5be4c2fe58e98b67d1da360d45ec8f9725f44c Mon Sep 17 00:00:00 2001 From: Zoltan Majo Date: Mon, 19 Jan 2015 09:32:40 +0100 Subject: [PATCH 110/149] 8066312: Add new Node* Node::find_out(int opc) method Added methods find_user_with() and has_user_with() for searching for a particular out type. Reviewed-by: kvn, jrose --- hotspot/src/share/vm/opto/escape.cpp | 36 ++++++--------------------- hotspot/src/share/vm/opto/ifg.cpp | 8 ++---- hotspot/src/share/vm/opto/macro.cpp | 9 +------ hotspot/src/share/vm/opto/memnode.cpp | 1 - hotspot/src/share/vm/opto/node.cpp | 28 +++++++++++++++++++++ hotspot/src/share/vm/opto/node.hpp | 36 +++++++++++++++++++-------- 6 files changed, 63 insertions(+), 55 deletions(-) diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index 736248113c7..42ba1262000 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -2010,14 +2010,9 @@ bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) { bt = field->layout_type(); } else { // Check for unsafe oop field access - for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { - int opcode = n->fast_out(i)->Opcode(); - if (opcode == Op_StoreP || opcode == Op_LoadP || - opcode == Op_StoreN || opcode == Op_LoadN) { - bt = T_OBJECT; - (*unsafe) = true; - break; - } + if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN)) { + bt = T_OBJECT; + (*unsafe) = true; } } } else if (adr_type->isa_aryptr()) { @@ -2031,13 +2026,8 @@ bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) { } } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) { // Allocation initialization, ThreadLocal field access, unsafe access - for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { - int opcode = n->fast_out(i)->Opcode(); - if (opcode == Op_StoreP || opcode == Op_LoadP || - opcode == Op_StoreN || opcode == Op_LoadN) { - bt = T_OBJECT; - break; - } + if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN)) { + bt = T_OBJECT; } } } @@ -3092,13 +3082,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) continue; } else if (n->Opcode() == Op_EncodeISOArray) { // get the memory projection - for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { - Node *use = n->fast_out(i); - if (use->Opcode() == Op_SCMemProj) { - n = use; - break; - } - } + n = n->find_out_with(Op_SCMemProj); assert(n->Opcode() == Op_SCMemProj, "memory projection required"); } else { assert(n->is_Mem(), "memory node required."); @@ -3122,13 +3106,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) continue; // don't push users } else if (n->is_LoadStore()) { // get the memory projection - for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { - Node *use = n->fast_out(i); - if (use->Opcode() == Op_SCMemProj) { - n = use; - break; - } - } + n = n->find_out_with(Op_SCMemProj); assert(n->Opcode() == Op_SCMemProj, "memory projection required"); } } diff --git a/hotspot/src/share/vm/opto/ifg.cpp b/hotspot/src/share/vm/opto/ifg.cpp index 61e13439637..f01cd40f7c9 100644 --- a/hotspot/src/share/vm/opto/ifg.cpp +++ b/hotspot/src/share/vm/opto/ifg.cpp @@ -535,12 +535,8 @@ bool PhaseChaitin::remove_node_if_not_used(Block* b, uint location, Node* n, uin // The method add_input_to_liveout() keeps such nodes alive (put them on liveout list) // when it sees SCMemProj node in a block. Unfortunately SCMemProj node could be placed // in block in such order that KILL MachProj nodes are processed first. - uint cnt = def->outcnt(); - for (uint i = 0; i < cnt; i++) { - Node* proj = def->raw_out(i); - if (proj->Opcode() == Op_SCMemProj) { - return false; - } + if (def->has_out_with(Op_SCMemProj)) { + return false; } } b->remove_node(location); diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp index b393745620b..93659c32ad4 100644 --- a/hotspot/src/share/vm/opto/macro.cpp +++ b/hotspot/src/share/vm/opto/macro.cpp @@ -258,14 +258,7 @@ void PhaseMacroExpand::eliminate_card_mark(Node* p2x) { // Search for CastP2X->Xor->URShift->Cmp path which // checks if the store done to a different from the value's region. // And replace Cmp with #0 (false) to collapse G1 post barrier. - Node* xorx = NULL; - for (DUIterator_Fast imax, i = p2x->fast_outs(imax); i < imax; i++) { - Node* u = p2x->fast_out(i); - if (u->Opcode() == Op_XorX) { - xorx = u; - break; - } - } + Node* xorx = p2x->find_out_with(Op_XorX); assert(xorx != NULL, "missing G1 post barrier"); Node* shift = xorx->unique_out(); Node* cmpx = shift->unique_out(); diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index 966bcbeb0f7..3afa49c4495 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -2609,7 +2609,6 @@ bool StoreNode::value_never_loaded( PhaseTransform *phase) const { return false; // if not a distinct instance, there may be aliases of the address for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) { Node *use = adr->fast_out(i); - int opc = use->Opcode(); if (use->is_Load() || use->is_LoadStore()) { return false; } diff --git a/hotspot/src/share/vm/opto/node.cpp b/hotspot/src/share/vm/opto/node.cpp index 8ed950a021e..225b20c55dd 100644 --- a/hotspot/src/share/vm/opto/node.cpp +++ b/hotspot/src/share/vm/opto/node.cpp @@ -881,6 +881,34 @@ Node* Node::uncast() const { return (Node*) this; } +// Find out of current node that matches opcode. +Node* Node::find_out_with(int opcode) { + for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { + Node* use = fast_out(i); + if (use->Opcode() == opcode) { + return use; + } + } + return NULL; +} + +// Return true if the current node has an out that matches opcode. +bool Node::has_out_with(int opcode) { + return (find_out_with(opcode) != NULL); +} + +// Return true if the current node has an out that matches any of the opcodes. +bool Node::has_out_with(int opcode1, int opcode2, int opcode3, int opcode4) { + for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { + int opcode = fast_out(i)->Opcode(); + if (opcode == opcode1 || opcode == opcode2 || opcode == opcode3 || opcode == opcode4) { + return true; + } + } + return false; +} + + //---------------------------uncast_helper------------------------------------- Node* Node::uncast_helper(const Node* p) { #ifdef ASSERT diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index bcf6911df52..5361a8bc4c8 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -436,6 +436,13 @@ protected: return (this->uncast() == n->uncast()); } + // Find out of current node that matches opcode. + Node* find_out_with(int opcode); + // Return true if the current node has an out that matches opcode. + bool has_out_with(int opcode); + // Return true if the current node has an out that matches any of the opcodes. + bool has_out_with(int opcode1, int opcode2, int opcode3, int opcode4); + private: static Node* uncast_helper(const Node* n); @@ -507,18 +514,25 @@ public: //----------------- Other Node Properties - // Generate class id for some ideal nodes to avoid virtual query - // methods is_(). - // Class id is the set of bits corresponded to the node class and all its - // super classes so that queries for super classes are also valid. - // Subclasses of the same super class have different assigned bit - // (the third parameter in the macro DEFINE_CLASS_ID). - // Classes with deeper hierarchy are declared first. - // Classes with the same hierarchy depth are sorted by usage frequency. + // Generate class IDs for (some) ideal nodes so that it is possible to determine + // the type of a node using a non-virtual method call (the method is_() below). // - // The query method masks the bits to cut off bits of subclasses - // and then compare the result with the class id - // (see the macro DEFINE_CLASS_QUERY below). + // A class ID of an ideal node is a set of bits. In a class ID, a single bit determines + // the type of the node the ID represents; another subset of an ID's bits are reserved + // for the superclasses of the node represented by the ID. + // + // By design, if A is a supertype of B, A.is_B() returns true and B.is_A() + // returns false. A.is_A() returns true. + // + // If two classes, A and B, have the same superclass, a different bit of A's class id + // is reserved for A's type than for B's type. That bit is specified by the third + // parameter in the macro DEFINE_CLASS_ID. + // + // By convention, classes with deeper hierarchy are declared first. Moreover, + // classes with the same hierarchy depth are sorted by usage frequency. + // + // The query method masks the bits to cut off bits of subclasses and then compares + // the result with the class id (see the macro DEFINE_CLASS_QUERY below). // // Class_MachCall=30, ClassMask_MachCall=31 // 12 8 4 0 From d508c520f086120e407979acc52572fb60eee1af Mon Sep 17 00:00:00 2001 From: Stefan Johansson Date: Mon, 19 Jan 2015 10:06:14 +0100 Subject: [PATCH 111/149] 8040935: -XX:+AggressiveOpts broken: GC triggered before VM initialization completed on several tests Reviewed-by: brutisso, kbarrett --- hotspot/test/gc/TestNUMAPageSize.java | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/test/gc/TestNUMAPageSize.java b/hotspot/test/gc/TestNUMAPageSize.java index 1a3b5ddbebf..9537f0f7ab6 100644 --- a/hotspot/test/gc/TestNUMAPageSize.java +++ b/hotspot/test/gc/TestNUMAPageSize.java @@ -25,6 +25,7 @@ * @test TestNUMAPageSize * @summary Make sure that start up with NUMA support does not cause problems. * @bug 8061467 + * @requires (vm.opt.AggressiveOpts == null) | (vm.opt.AggressiveOpts == false) * @key gc * @key regression * @run main/othervm -Xmx8M -XX:+UseNUMA TestNUMAPageSize From 3a11c1d75c7bb683424e51a7bb1a31d821c26944 Mon Sep 17 00:00:00 2001 From: Stefan Johansson Date: Mon, 19 Jan 2015 10:08:07 +0100 Subject: [PATCH 112/149] 8069011: gc/TestSmallHeap.java failing in nightly Using @requires to avoid running with AggressiveOpts turned on. Reviewed-by: jwilhelm, brutisso --- hotspot/test/gc/TestSmallHeap.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/hotspot/test/gc/TestSmallHeap.java b/hotspot/test/gc/TestSmallHeap.java index 170b5397740..abe6ed37f98 100644 --- a/hotspot/test/gc/TestSmallHeap.java +++ b/hotspot/test/gc/TestSmallHeap.java @@ -25,6 +25,7 @@ * @test TestSmallHeap * @bug 8067438 * @requires vm.gc=="null" + * @requires (vm.opt.AggressiveOpts=="null") | (vm.opt.AggressiveOpts=="false") * @summary Verify that starting the VM with a small heap works * @library /testlibrary /../../test/lib * @build TestSmallHeap @@ -33,8 +34,9 @@ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xmx2m -XX:+UseSerialGC TestSmallHeap * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xmx2m -XX:+UseG1GC TestSmallHeap * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xmx2m -XX:+UseConcMarkSweepGC TestSmallHeap - * - * Note: It would be nice to verify the minimal supported heap size (2m) here, + */ + +/* Note: It would be nice to verify the minimal supported heap size (2m) here, * but we align the heap size based on the card table size. And the card table * size is aligned based on the minimal pages size provided by the os. This * means that on most platforms, where the minimal page size is 4k, we get a From a8f4ccaa9de9d45dff1ee84691bd752e73908fc4 Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Mon, 19 Jan 2015 16:07:16 +0100 Subject: [PATCH 113/149] 8067880: Dead typed push methods in ArrayData Reviewed-by: hannesw, jlaskey --- .../internal/runtime/arrays/ArrayData.java | 34 +------------------ .../internal/runtime/arrays/IntArrayData.java | 12 +------ .../runtime/arrays/LongArrayData.java | 12 +------ .../runtime/arrays/NumberArrayData.java | 12 +------ 4 files changed, 4 insertions(+), 66 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ArrayData.java index ade9dce91b4..6c98028a602 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ArrayData.java @@ -26,6 +26,7 @@ package jdk.nashorn.internal.runtime.arrays; import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall; + import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Array; @@ -760,39 +761,6 @@ public abstract class ArrayData { return push(strict, new Object[] { item }); } - /** - * Push an array of items to the end of the array - * - * @param strict are we in strict mode - * @param item the item - * @return new array data (or same) - */ - public ArrayData push(final boolean strict, final double item) { - return push(strict, item); - } - - /** - * Push an array of items to the end of the array - * - * @param strict are we in strict mode - * @param item the item - * @return new array data (or same) - */ - public ArrayData push(final boolean strict, final long item) { - return push(strict, item); - } - - /** - * Push an array of items to the end of the array - * - * @param strict are we in strict mode - * @param item the item - * @return new array data (or same) - */ - public ArrayData push(final boolean strict, final int item) { - return push(strict, item); - } - /** * Pop an element from the end of the array * diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java index 381390ce911..a70dec2747c 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java @@ -26,6 +26,7 @@ package jdk.nashorn.internal.runtime.arrays; import static jdk.nashorn.internal.codegen.CompilerConstants.specialCall; + import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.Arrays; @@ -342,17 +343,6 @@ final class IntArrayData extends ContinuousArrayData implements IntElements { return new IntArrayData(Arrays.copyOfRange(array, (int)from, (int)to), (int)(to - (from < 0 ? from + length() : from))); } - @Override - public final ArrayData push(final boolean strict, final int item) { - final long len = length(); - final ArrayData newData = ensure(len); - if (newData == this) { - array[(int)len] = item; - return this; - } - return newData.set((int)len, item, strict); - } - @Override public ArrayData fastSplice(final int start, final int removed, final int added) throws UnsupportedOperationException { final long oldLength = length(); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java index 0437cdfecf7..bf3431926f0 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java @@ -27,6 +27,7 @@ package jdk.nashorn.internal.runtime.arrays; import static jdk.nashorn.internal.codegen.CompilerConstants.specialCall; import static jdk.nashorn.internal.lookup.Lookup.MH; + import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.Arrays; @@ -302,17 +303,6 @@ final class LongArrayData extends ContinuousArrayData implements IntOrLongElemen return new LongArrayData(Arrays.copyOfRange(array, (int)from, (int)to), (int)newLength); } - @Override - public final ArrayData push(final boolean strict, final long item) { - final long len = length(); - final ArrayData newData = ensure(len); - if (newData == this) { - array[(int)len] = item; - return this; - } - return newData.set((int)len, item, strict); - } - @Override public ArrayData fastSplice(final int start, final int removed, final int added) throws UnsupportedOperationException { final long oldLength = length(); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java index 2522b97902e..d938d1d02d7 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java @@ -28,6 +28,7 @@ package jdk.nashorn.internal.runtime.arrays; import static jdk.nashorn.internal.codegen.CompilerConstants.specialCall; import static jdk.nashorn.internal.lookup.Lookup.MH; import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; + import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.Arrays; @@ -276,17 +277,6 @@ final class NumberArrayData extends ContinuousArrayData implements NumericElemen return new NumberArrayData(Arrays.copyOfRange(array, (int)from, (int)to), (int)newLength); } - @Override - public final ArrayData push(final boolean strict, final double item) { - final long len = length(); - final ArrayData newData = ensure(len); - if (newData == this) { - array[(int)len] = item; - return this; - } - return newData.set((int)len, item, strict); - } - @Override public ArrayData fastSplice(final int start, final int removed, final int added) throws UnsupportedOperationException { final long oldLength = length(); From ca4dba303fdd89e45feb858be96eeeb4ec767b38 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Mon, 19 Jan 2015 18:29:45 +0000 Subject: [PATCH 114/149] 8069229: new .java file with no copyright notice Add missing copyright header Reviewed-by: jlahoda --- .../propertiesparser/gen/ClassGenerator.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/langtools/make/tools/propertiesparser/gen/ClassGenerator.java b/langtools/make/tools/propertiesparser/gen/ClassGenerator.java index f46d10a0bee..16310c10bda 100644 --- a/langtools/make/tools/propertiesparser/gen/ClassGenerator.java +++ b/langtools/make/tools/propertiesparser/gen/ClassGenerator.java @@ -1,3 +1,26 @@ +/* + * 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. + */ + package propertiesparser.gen; import propertiesparser.parser.Message; From aca3a19f56dfe30459394f0d3b7c8c998b231adc Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Mon, 19 Jan 2015 12:29:50 -0800 Subject: [PATCH 115/149] 8068881: SIGBUS in C2 compiled method weblogic.wsee.jaxws.framework.jaxrpc.EnvironmentFactory$SimulatedWsdlDefinitions. Use MachMerge to hook together defs of the same multidef value in a block Reviewed-by: kvn, vlivanov --- hotspot/src/share/vm/opto/chaitin.cpp | 3 + hotspot/src/share/vm/opto/chaitin.hpp | 26 +++++++ hotspot/src/share/vm/opto/machnode.hpp | 23 ++++++ hotspot/src/share/vm/opto/node.hpp | 3 + hotspot/src/share/vm/opto/phase.cpp | 2 + hotspot/src/share/vm/opto/phase.hpp | 1 + hotspot/src/share/vm/opto/postaloc.cpp | 102 +++++++++++++++++++++---- 7 files changed, 146 insertions(+), 14 deletions(-) diff --git a/hotspot/src/share/vm/opto/chaitin.cpp b/hotspot/src/share/vm/opto/chaitin.cpp index c03c0f4052e..106e22879b7 100644 --- a/hotspot/src/share/vm/opto/chaitin.cpp +++ b/hotspot/src/share/vm/opto/chaitin.cpp @@ -582,6 +582,9 @@ void PhaseChaitin::Register_Allocate() { // Peephole remove copies post_allocate_copy_removal(); + // Merge multidefs if multiple defs representing the same value are used in a single block. + merge_multidefs(); + #ifdef ASSERT // Veify the graph after RA. verify(&live_arena); diff --git a/hotspot/src/share/vm/opto/chaitin.hpp b/hotspot/src/share/vm/opto/chaitin.hpp index 99194cfe925..51915c52133 100644 --- a/hotspot/src/share/vm/opto/chaitin.hpp +++ b/hotspot/src/share/vm/opto/chaitin.hpp @@ -681,6 +681,32 @@ private: // Extend the node to LRG mapping void add_reference( const Node *node, const Node *old_node); + // Record the first use of a def in the block for a register. + class RegDefUse { + Node* _def; + Node* _first_use; + public: + RegDefUse() : _def(NULL), _first_use(NULL) { } + Node* def() const { return _def; } + Node* first_use() const { return _first_use; } + + void update(Node* def, Node* use) { + if (_def != def) { + _def = def; + _first_use = use; + } + } + void clear() { + _def = NULL; + _first_use = NULL; + } + }; + typedef GrowableArray RegToDefUseMap; + int possibly_merge_multidef(Node *n, uint k, Block *block, RegToDefUseMap& reg2defuse); + + // Merge nodes that are a part of a multidef lrg and produce the same value within a block. + void merge_multidefs(); + private: static int _final_loads, _final_stores, _final_copies, _final_memoves; diff --git a/hotspot/src/share/vm/opto/machnode.hpp b/hotspot/src/share/vm/opto/machnode.hpp index a557c02e6c6..e30e23406c6 100644 --- a/hotspot/src/share/vm/opto/machnode.hpp +++ b/hotspot/src/share/vm/opto/machnode.hpp @@ -616,6 +616,29 @@ public: #endif }; +// MachMergeNode is similar to a PhiNode in a sense it merges multiple values, +// however it doesn't have a control input and is more like a MergeMem. +// It is inserted after the register allocation is done to ensure that nodes use single +// definition of a multidef lrg in a block. +class MachMergeNode : public MachIdealNode { +public: + MachMergeNode(Node *n1) { + init_class_id(Class_MachMerge); + add_req(NULL); + add_req(n1); + } + virtual const RegMask &out_RegMask() const { return in(1)->out_RegMask(); } + virtual const RegMask &in_RegMask(uint idx) const { return in(1)->in_RegMask(idx); } + virtual const class Type *bottom_type() const { return in(1)->bottom_type(); } + virtual uint ideal_reg() const { return bottom_type()->ideal_reg(); } + virtual uint oper_input_base() const { return 1; } + virtual void emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const { } + virtual uint size(PhaseRegAlloc *ra_) const { return 0; } +#ifndef PRODUCT + virtual const char *Name() const { return "MachMerge"; } +#endif +}; + //------------------------------MachBranchNode-------------------------------- // Abstract machine branch Node class MachBranchNode : public MachIdealNode { diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index 5361a8bc4c8..ce591dce482 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -98,6 +98,7 @@ class MachReturnNode; class MachSafePointNode; class MachSpillCopyNode; class MachTempNode; +class MachMergeNode; class Matcher; class MemBarNode; class MemBarStoreStoreNode; @@ -606,6 +607,7 @@ public: DEFINE_CLASS_ID(MachTemp, Mach, 3) DEFINE_CLASS_ID(MachConstantBase, Mach, 4) DEFINE_CLASS_ID(MachConstant, Mach, 5) + DEFINE_CLASS_ID(MachMerge, Mach, 6) DEFINE_CLASS_ID(Type, Node, 2) DEFINE_CLASS_ID(Phi, Type, 0) @@ -777,6 +779,7 @@ public: DEFINE_CLASS_QUERY(MachSafePoint) DEFINE_CLASS_QUERY(MachSpillCopy) DEFINE_CLASS_QUERY(MachTemp) + DEFINE_CLASS_QUERY(MachMerge) DEFINE_CLASS_QUERY(Mem) DEFINE_CLASS_QUERY(MemBar) DEFINE_CLASS_QUERY(MemBarStoreStore) diff --git a/hotspot/src/share/vm/opto/phase.cpp b/hotspot/src/share/vm/opto/phase.cpp index 0c9c697414d..9662bbcbbfb 100644 --- a/hotspot/src/share/vm/opto/phase.cpp +++ b/hotspot/src/share/vm/opto/phase.cpp @@ -110,6 +110,7 @@ void Phase::print_timers() { tty->print_cr (" Compute Liveness: %7.3f s", timers[_t_computeLive].seconds()); tty->print_cr (" Regalloc Split: %7.3f s", timers[_t_regAllocSplit].seconds()); tty->print_cr (" Postalloc Copy Rem: %7.3f s", timers[_t_postAllocCopyRemoval].seconds()); + tty->print_cr (" Merge multidefs: %7.3f s", timers[_t_mergeMultidefs].seconds()); tty->print_cr (" Fixup Spills: %7.3f s", timers[_t_fixupSpills].seconds()); tty->print_cr (" Compact: %7.3f s", timers[_t_chaitinCompact].seconds()); tty->print_cr (" Coalesce 1: %7.3f s", timers[_t_chaitinCoalesce1].seconds()); @@ -126,6 +127,7 @@ void Phase::print_timers() { timers[_t_computeLive].seconds() + timers[_t_regAllocSplit].seconds() + timers[_t_postAllocCopyRemoval].seconds() + + timers[_t_mergeMultidefs].seconds() + timers[_t_fixupSpills].seconds() + timers[_t_chaitinCompact].seconds() + timers[_t_chaitinCoalesce1].seconds() + diff --git a/hotspot/src/share/vm/opto/phase.hpp b/hotspot/src/share/vm/opto/phase.hpp index f273947a1d9..4b5d53d1656 100644 --- a/hotspot/src/share/vm/opto/phase.hpp +++ b/hotspot/src/share/vm/opto/phase.hpp @@ -88,6 +88,7 @@ public: _t_computeLive, _t_regAllocSplit, _t_postAllocCopyRemoval, + _t_mergeMultidefs, _t_fixupSpills, _t_chaitinCompact, _t_chaitinCoalesce1, diff --git a/hotspot/src/share/vm/opto/postaloc.cpp b/hotspot/src/share/vm/opto/postaloc.cpp index 35e3974d3a1..d6ac1020266 100644 --- a/hotspot/src/share/vm/opto/postaloc.cpp +++ b/hotspot/src/share/vm/opto/postaloc.cpp @@ -263,20 +263,6 @@ int PhaseChaitin::elide_copy( Node *n, int k, Block *current_block, Node_List &v // intermediate copies might be illegal, i.e., value is stored down to stack // then reloaded BUT survives in a register the whole way. Node *val = skip_copies(n->in(k)); - - if (val == x && nk_idx != 0 && - regnd[nk_reg] != NULL && regnd[nk_reg] != x && - _lrg_map.live_range_id(x) == _lrg_map.live_range_id(regnd[nk_reg])) { - // When rematerialzing nodes and stretching lifetimes, the - // allocator will reuse the original def for multidef LRG instead - // of the current reaching def because it can't know it's safe to - // do so. After allocation completes if they are in the same LRG - // then it should use the current reaching def instead. - n->set_req(k, regnd[nk_reg]); - blk_adjust += yank_if_dead(val, current_block, &value, ®nd); - val = skip_copies(n->in(k)); - } - if (val == x) return blk_adjust; // No progress? int n_regs = RegMask::num_registers(val->ideal_reg()); @@ -382,6 +368,94 @@ bool PhaseChaitin::eliminate_copy_of_constant(Node* val, Node* n, return false; } +// The algorithms works as follows: +// We traverse the block top to bottom. possibly_merge_multidef() is invoked for every input edge k +// of the instruction n. We check to see if the input is a multidef lrg. If it is, we record the fact that we've +// seen a definition (coming as an input) and add that fact to the reg2defuse array. The array maps registers to their +// current reaching definitions (we track only multidefs though). With each definition we also associate the first +// instruction we saw use it. If we encounter the situation when we observe an def (an input) that is a part of the +// same lrg but is different from the previous seen def we merge the two with a MachMerge node and substitute +// all the uses that we've seen so far to use the merge. After that we keep replacing the new defs in the same lrg +// as they get encountered with the merge node and keep adding these defs to the merge inputs. +void PhaseChaitin::merge_multidefs() { + Compile::TracePhase tp("mergeMultidefs", &timers[_t_mergeMultidefs]); + ResourceMark rm; + // Keep track of the defs seen in registers and collect their uses in the block. + RegToDefUseMap reg2defuse(_max_reg, _max_reg, RegDefUse()); + for (uint i = 0; i < _cfg.number_of_blocks(); i++) { + Block* block = _cfg.get_block(i); + for (uint j = 1; j < block->number_of_nodes(); j++) { + Node* n = block->get_node(j); + if (n->is_Phi()) continue; + for (uint k = 1; k < n->req(); k++) { + j += possibly_merge_multidef(n, k, block, reg2defuse); + } + // Null out the value produced by the instruction itself, since we're only interested in defs + // implicitly defined by the uses. We are actually interested in tracking only redefinitions + // of the multidef lrgs in the same register. For that matter it's enough to track changes in + // the base register only and ignore other effects of multi-register lrgs and fat projections. + // It is also ok to ignore defs coming from singledefs. After an implicit overwrite by one of + // those our register is guaranteed to be used by another lrg and we won't attempt to merge it. + uint lrg = _lrg_map.live_range_id(n); + if (lrg > 0 && lrgs(lrg).is_multidef()) { + OptoReg::Name reg = lrgs(lrg).reg(); + reg2defuse.at(reg).clear(); + } + } + // Clear reg->def->use tracking for the next block + for (int j = 0; j < reg2defuse.length(); j++) { + reg2defuse.at(j).clear(); + } + } +} + +int PhaseChaitin::possibly_merge_multidef(Node *n, uint k, Block *block, RegToDefUseMap& reg2defuse) { + int blk_adjust = 0; + + uint lrg = _lrg_map.live_range_id(n->in(k)); + if (lrg > 0 && lrgs(lrg).is_multidef()) { + OptoReg::Name reg = lrgs(lrg).reg(); + + Node* def = reg2defuse.at(reg).def(); + if (def != NULL && lrg == _lrg_map.live_range_id(def) && def != n->in(k)) { + // Same lrg but different node, we have to merge. + MachMergeNode* merge; + if (def->is_MachMerge()) { // is it already a merge? + merge = def->as_MachMerge(); + } else { + merge = new MachMergeNode(def); + + // Insert the merge node into the block before the first use. + uint use_index = block->find_node(reg2defuse.at(reg).first_use()); + block->insert_node(merge, use_index++); + + // Let the allocator know about the new node, use the same lrg + _lrg_map.extend(merge->_idx, lrg); + blk_adjust++; + + // Fixup all the uses (there is at least one) that happened between the first + // use and before the current one. + for (; use_index < block->number_of_nodes(); use_index++) { + Node* use = block->get_node(use_index); + if (use == n) { + break; + } + use->replace_edge(def, merge); + } + } + if (merge->find_edge(n->in(k)) == -1) { + merge->add_req(n->in(k)); + } + n->set_req(k, merge); + } + + // update the uses + reg2defuse.at(reg).update(n->in(k), n); + } + + return blk_adjust; +} + //------------------------------post_allocate_copy_removal--------------------- // Post-Allocation peephole copy removal. We do this in 1 pass over the From 3d814126c2799aa378ab66326b7dace58860588d Mon Sep 17 00:00:00 2001 From: Zoltan Majo Date: Tue, 20 Jan 2015 09:45:11 +0100 Subject: [PATCH 116/149] 8069162: quarantine serviceability/dcmd/compiler/CompilerQueueTest.java Added '@ignore 8069160' to the test. Reviewed-by: anoll, kvn --- hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java b/hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java index 1a96dd8c200..3bd7cf3ede1 100644 --- a/hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java +++ b/hotspot/test/serviceability/dcmd/compiler/CompilerQueueTest.java @@ -25,6 +25,7 @@ * @test CompilerQueueTest * @bug 8054889 * @library .. + * @ignore 8069160 * @build DcmdUtil CompilerQueueTest * @run main CompilerQueueTest * @run main/othervm -XX:-TieredCompilation CompilerQueueTest From 671f90ddc7524b58f5e7599b389bf2db8428d261 Mon Sep 17 00:00:00 2001 From: Srikanth Adayapalam Date: Tue, 20 Jan 2015 09:51:17 +0100 Subject: [PATCH 117/149] 8052070: javac crashes when there are duplicated type parameters Avoid eager completion of ClassSymbol while type parameters are being processed. Reviewed-by: jlahoda, mcimadamore --- .../classes/com/sun/tools/javac/comp/Enter.java | 5 ++++- .../javac/8052070/DuplicateTypeParameter.java | 15 +++++++++++++++ .../javac/8052070/DuplicateTypeParameter.out | 5 +++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 langtools/test/tools/javac/8052070/DuplicateTypeParameter.java create mode 100644 langtools/test/tools/javac/8052070/DuplicateTypeParameter.out diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java index 12346622a8d..d8abe3b6855 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java @@ -385,7 +385,7 @@ public class Enter extends JCTree.Visitor { typeEnvs.put(c, localEnv); // Fill out class fields. - c.completer = typeEnter; + c.completer = null; // do not allow the initial completer linger on. c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree); c.sourcefile = env.toplevel.sourcefile; c.members_field = WriteableScope.create(c); @@ -409,6 +409,9 @@ public class Enter extends JCTree.Visitor { // Enter type parameters. ct.typarams_field = classEnter(tree.typarams, localEnv); + // install further completer for this type. + c.completer = typeEnter; + // Add non-local class to uncompleted, to make sure it will be // completed later. if (!c.isLocal() && uncompleted != null) uncompleted.append(c); diff --git a/langtools/test/tools/javac/8052070/DuplicateTypeParameter.java b/langtools/test/tools/javac/8052070/DuplicateTypeParameter.java new file mode 100644 index 00000000000..309cc61e7cb --- /dev/null +++ b/langtools/test/tools/javac/8052070/DuplicateTypeParameter.java @@ -0,0 +1,15 @@ +/* + * @test /nodynamiccopyright/ + * @bug 8052070 + * @summary javac crashes when there are duplicated type parameters + * @compile/fail/ref=DuplicateTypeParameter.out -XDrawDiagnostics DuplicateTypeParameter.java + */ + +public class DuplicateTypeParameter { + class Inner {} + public void foo() { + class Local {}; + } +} + +class Secondary {} diff --git a/langtools/test/tools/javac/8052070/DuplicateTypeParameter.out b/langtools/test/tools/javac/8052070/DuplicateTypeParameter.out new file mode 100644 index 00000000000..5822c8bfe72 --- /dev/null +++ b/langtools/test/tools/javac/8052070/DuplicateTypeParameter.out @@ -0,0 +1,5 @@ +DuplicateTypeParameter.java:8:40: compiler.err.already.defined: kindname.type.variable, T, kindname.class, DuplicateTypeParameter +DuplicateTypeParameter.java:9:21: compiler.err.already.defined: kindname.type.variable, P, kindname.class, DuplicateTypeParameter.Inner +DuplicateTypeParameter.java:15:20: compiler.err.already.defined: kindname.type.variable, D, kindname.class, Secondary +DuplicateTypeParameter.java:11:25: compiler.err.already.defined: kindname.type.variable, M, kindname.class, Local +4 errors From 8944d18416b56a46be4b4e6fdcb0b2357b5f7bb2 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Tue, 20 Jan 2015 12:00:25 +0100 Subject: [PATCH 118/149] 8069094: SuppressWarnings(\"deprecation\") not respected on default clause on annotation declarations Properly deferring warnings that are reported during entering of annotation's default value. Reviewed-by: mcimadamore --- .../com/sun/tools/javac/comp/MemberEnter.java | 7 +++++-- .../tools/javac/warnings/suppress/T8069094.java | 17 +++++++++++++++++ .../tools/javac/warnings/suppress/T8069094.out | 3 +++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 langtools/test/tools/javac/warnings/suppress/T8069094.java create mode 100644 langtools/test/tools/javac/warnings/suppress/T8069094.out diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java index 721612d5e68..92072680708 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java @@ -227,7 +227,7 @@ public class MemberEnter extends JCTree.Visitor { annotate.annotateTypeLater(tree, localEnv, m, tree.pos()); if (tree.defaultValue != null) - annotateDefaultValueLater(tree.defaultValue, localEnv, m); + annotateDefaultValueLater(tree.defaultValue, localEnv, m, tree.pos()); } /** Create a fresh environment for method bodies. @@ -438,7 +438,8 @@ public class MemberEnter extends JCTree.Visitor { /** Queue processing of an attribute default value. */ void annotateDefaultValueLater(final JCExpression defaultValue, final Env localEnv, - final MethodSymbol m) { + final MethodSymbol m, + final DiagnosticPosition deferPos) { annotate.normal(new Annotate.Worker() { @Override public String toString() { @@ -449,9 +450,11 @@ public class MemberEnter extends JCTree.Visitor { @Override public void run() { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); + DiagnosticPosition prevLintPos = deferredLintHandler.setPos(deferPos); try { enterDefaultValue(defaultValue, localEnv, m); } finally { + deferredLintHandler.setPos(prevLintPos); log.useSource(prev); } } diff --git a/langtools/test/tools/javac/warnings/suppress/T8069094.java b/langtools/test/tools/javac/warnings/suppress/T8069094.java new file mode 100644 index 00000000000..2e272f6e3ba --- /dev/null +++ b/langtools/test/tools/javac/warnings/suppress/T8069094.java @@ -0,0 +1,17 @@ +/** + * @test /nodynamiccopyright/ + * @bug 8069094 + * @summary Verify that \\@SuppressWarnings("unchecked") works correctly for annotation default values + * @build VerifySuppressWarnings + * @compile/ref=T8069094.out -XDrawDiagnostics -Xlint:unchecked,deprecation,cast T8069094.java + * @run main VerifySuppressWarnings T8069094.java + */ + +@interface T8069094 { + T8069094A foo() default T8069094A.Bar; +} + +@Deprecated +enum T8069094A { + Bar +} diff --git a/langtools/test/tools/javac/warnings/suppress/T8069094.out b/langtools/test/tools/javac/warnings/suppress/T8069094.out new file mode 100644 index 00000000000..63741a3fe2c --- /dev/null +++ b/langtools/test/tools/javac/warnings/suppress/T8069094.out @@ -0,0 +1,3 @@ +T8069094.java:11:5: compiler.warn.has.been.deprecated: T8069094A, compiler.misc.unnamed.package +T8069094.java:11:29: compiler.warn.has.been.deprecated: T8069094A, compiler.misc.unnamed.package +2 warnings From bf990aa8138363974de1dc9bb64a99c724726f19 Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Tue, 20 Jan 2015 12:34:21 +0100 Subject: [PATCH 119/149] 8068603: ScriptObjectMirror should reject null/empty string/non-string parameters in Bindings methods Reviewed-by: hannesw, sundar --- .../api/scripting/ScriptObjectMirror.java | 35 ++++- .../api/scripting/ScriptEngineTest.java | 124 ++++++++++++++++++ 2 files changed, 155 insertions(+), 4 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptObjectMirror.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptObjectMirror.java index 1108a34e775..d18316e81f6 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptObjectMirror.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptObjectMirror.java @@ -340,9 +340,10 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin @Override public boolean containsKey(final Object key) { + checkKey(key); return inGlobal(new Callable() { @Override public Boolean call() { - return sobj.containsKey(unwrap(key, global)); + return sobj.containsKey(key); } }); } @@ -376,6 +377,7 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin @Override public Object get(final Object key) { + checkKey(key); return inGlobal(new Callable() { @Override public Object call() { return translateUndefined(wrap(sobj.get(key), global)); @@ -410,6 +412,7 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin @Override public Object put(final String key, final Object value) { + checkKey(key); final ScriptObject oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != global); return inGlobal(new Callable() { @@ -422,6 +425,9 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin @Override public void putAll(final Map map) { + if (map == null) { + throw new NullPointerException("map is null"); + } final ScriptObject oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != global); inGlobal(new Callable() { @@ -429,7 +435,9 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin for (final Map.Entry entry : map.entrySet()) { final Object value = entry.getValue(); final Object modValue = globalChanged? wrap(value, oldGlobal) : value; - sobj.set(entry.getKey(), unwrap(modValue, global), getCallSiteFlags()); + final String key = entry.getKey(); + checkKey(key); + sobj.set(key, unwrap(modValue, global), getCallSiteFlags()); } return null; } @@ -438,9 +446,10 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin @Override public Object remove(final Object key) { + checkKey(key); return inGlobal(new Callable() { @Override public Object call() { - return wrap(sobj.remove(unwrap(key, global), strict), global); + return wrap(sobj.remove(key, strict), global); } }); } @@ -629,7 +638,7 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin } /** - * Utilitity to convert this script object to the given type. + * Utility to convert this script object to the given type. * * @param destination type to convert to * @param type destination type to convert to @@ -786,6 +795,24 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin } } + /** + * Ensures the key is not null, empty string, or a non-String object. The contract of the {@link Bindings} + * interface requires that these are not accepted as keys. + * @param key the key to check + * @throws NullPointerException if key is null + * @throws ClassCastException if key is not a String + * @throws IllegalArgumentException if key is empty string + */ + private static void checkKey(final Object key) { + if (key == null) { + throw new NullPointerException("key can not be null"); + } else if (!(key instanceof String)) { + throw new ClassCastException("key should be a String. It is " + key.getClass().getName() + " instead."); + } else if (((String)key).length() == 0) { + throw new IllegalArgumentException("key can not be empty"); + } + } + @Override public double toNumber() { return inGlobal(new Callable() { diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java index 751b505d8f9..a32e2e95df8 100644 --- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java +++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java @@ -36,10 +36,12 @@ import java.io.StringWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Function; +import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.Invocable; @@ -719,6 +721,128 @@ public class ScriptEngineTest { assertTrue(invoked.get()); } + // @bug JDK-8068603: NashornScriptEngine.put/get() impls don't conform to NPE, IAE spec assertions + @Test + public void illegalBindingsValuesTest() throws Exception { + final ScriptEngineManager manager = new ScriptEngineManager(); + final ScriptEngine e = manager.getEngineByName("nashorn"); + + try { + e.put(null, "null-value"); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + e.put("", "empty-value"); + fail(); + } catch (IllegalArgumentException x) { + // expected + } + + final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE); + assertTrue(b instanceof ScriptObjectMirror); + + try { + b.put(null, "null-value"); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + b.put("", "empty-value"); + fail(); + } catch (IllegalArgumentException x) { + // expected + } + + try { + b.get(null); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + b.get(""); + fail(); + } catch (IllegalArgumentException x) { + // expected + } + + try { + b.get(1); + fail(); + } catch (ClassCastException x) { + // expected + } + + try { + b.remove(null); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + b.remove(""); + fail(); + } catch (IllegalArgumentException x) { + // expected + } + + try { + b.remove(1); + fail(); + } catch (ClassCastException x) { + // expected + } + + try { + b.containsKey(null); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + b.containsKey(""); + fail(); + } catch (IllegalArgumentException x) { + // expected + } + + try { + b.containsKey(1); + fail(); + } catch (ClassCastException x) { + // expected + } + + try { + b.putAll(null); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + b.putAll(Collections.singletonMap((String)null, "null-value")); + fail(); + } catch (NullPointerException x) { + // expected + } + + try { + b.putAll(Collections.singletonMap("", "empty-value")); + fail(); + } catch (IllegalArgumentException x) { + // expected + } + } + private static void checkProperty(final ScriptEngine e, final String name) throws ScriptException { final String value = System.getProperty(name); From 22e2343e572f9ed58201ddbf547f1502e1f6b18c Mon Sep 17 00:00:00 2001 From: Srikanth Adayapalam Date: Tue, 20 Jan 2015 21:49:55 +0100 Subject: [PATCH 120/149] 8046977: ClassCastException: typing information needed for method reference bridging not preserved Reviewed-by: mcimadamore --- .../classes/com/sun/tools/javac/comp/Attr.java | 15 +++++++++++++-- .../com/sun/tools/javac/comp/LambdaToMethod.java | 4 +++- .../classes/com/sun/tools/javac/tree/JCTree.java | 1 + 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index a7303bef959..09b83fdc35b 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -2783,7 +2783,8 @@ public class Attr extends JCTree.Visitor { @SuppressWarnings("fallthrough") void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { - Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); + InferenceContext inferenceContext = checkContext.inferenceContext(); + Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType()); Type resType; switch (tree.getMode()) { @@ -2812,10 +2813,20 @@ public class Attr extends JCTree.Visitor { if (incompatibleReturnType != null) { checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref", diags.fragment("inconvertible.types", resType, descriptor.getReturnType()))); + } else { + if (inferenceContext.free(refType)) { + // we need to wait for inference to finish and then replace inference vars in the referent type + inferenceContext.addFreeTypeListener(List.of(refType), + instantiatedContext -> { + tree.referentType = instantiatedContext.asInstType(refType); + }); + } else { + tree.referentType = refType; + } } if (!speculativeAttr) { - List thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes()); + List thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes()); if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); } diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java index b450b9f7f59..5ea3e5253ad 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java @@ -889,7 +889,9 @@ public class LambdaToMethod extends TreeTranslator { convertArgs(tree.sym, args.toList(), tree.varargsElement)). setType(tree.sym.erasure(types).getReturnType()); - apply = transTypes.coerce(apply, localContext.generatedRefSig().getReturnType()); + apply = transTypes.coerce(attrEnv, apply, + types.erasure(localContext.tree.referentType.getReturnType())); + setVarargsIfNeeded(apply, tree.varargsElement); return apply; } diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java index 11fff6cdd69..f1c6549247d 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java @@ -2101,6 +2101,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { public PolyKind refPolyKind; public boolean ownerAccessible; public OverloadKind overloadKind; + public Type referentType; public enum OverloadKind { OVERLOADED, From e559c179548b59885ecfc43494bc12029883fc5e Mon Sep 17 00:00:00 2001 From: Zoltan Majo Date: Wed, 21 Jan 2015 10:51:35 +0100 Subject: [PATCH 121/149] 8059606: Enable per-method usage of CompileThresholdScaling (per-method compilation thresholds) Changed interpreter and compilation policies to allow using CompileThresholdScaling on a per-method level Reviewed-by: jrose, kvn --- .../src/cpu/sparc/vm/interp_masm_sparc.cpp | 21 +++--- .../src/cpu/sparc/vm/interp_masm_sparc.hpp | 6 +- .../sparc/vm/templateInterpreter_sparc.cpp | 27 +++---- .../src/cpu/sparc/vm/templateTable_sparc.cpp | 20 +++--- hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp | 2 +- hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp | 2 +- hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp | 2 +- hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp | 2 +- .../cpu/x86/vm/templateInterpreter_x86_32.cpp | 15 ++-- .../cpu/x86/vm/templateInterpreter_x86_64.cpp | 11 +-- .../src/cpu/x86/vm/templateTable_x86_32.cpp | 14 ++-- .../src/cpu/x86/vm/templateTable_x86_64.cpp | 14 ++-- hotspot/src/share/vm/c1/c1_LIRGenerator.cpp | 14 +++- .../src/share/vm/compiler/compileBroker.cpp | 4 +- .../vm/interpreter/bytecodeInterpreter.cpp | 2 +- .../vm/interpreter/invocationCounter.hpp | 4 +- hotspot/src/share/vm/oops/method.cpp | 5 +- hotspot/src/share/vm/oops/methodCounters.cpp | 7 +- hotspot/src/share/vm/oops/methodCounters.hpp | 63 +++++++++++++--- hotspot/src/share/vm/oops/methodData.cpp | 8 +++ hotspot/src/share/vm/oops/methodData.hpp | 11 +++ .../vm/runtime/advancedThresholdPolicy.cpp | 22 +++--- .../vm/runtime/advancedThresholdPolicy.hpp | 12 ++-- hotspot/src/share/vm/runtime/arguments.cpp | 72 ++++++++++++------- hotspot/src/share/vm/runtime/arguments.hpp | 15 +++- hotspot/src/share/vm/runtime/globals.hpp | 13 +++- .../vm/runtime/simpleThresholdPolicy.cpp | 20 +++--- .../vm/runtime/simpleThresholdPolicy.hpp | 10 +-- .../runtime/simpleThresholdPolicy.inline.hpp | 14 +++- hotspot/src/share/vm/runtime/vmStructs.cpp | 7 ++ .../share/vm/utilities/globalDefinitions.hpp | 9 +-- .../CheckCompileThresholdScaling.java | 2 +- 32 files changed, 293 insertions(+), 157 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp index 51f237ba626..153bfbdda55 100644 --- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp @@ -1374,6 +1374,7 @@ void InterpreterMacroAssembler::verify_method_data_pointer() { } void InterpreterMacroAssembler::test_invocation_counter_for_mdp(Register invocation_count, + Register method_counters, Register Rtmp, Label &profile_continue) { assert(ProfileInterpreter, "must be profiling interpreter"); @@ -1386,9 +1387,8 @@ void InterpreterMacroAssembler::test_invocation_counter_for_mdp(Register invocat br_notnull_short(ImethodDataPtr, Assembler::pn, done); // Test to see if we should create a method data oop - AddressLiteral profile_limit((address) &InvocationCounter::InterpreterProfileLimit); - sethi(profile_limit, Rtmp); - ld(Rtmp, profile_limit.low10(), Rtmp); + Address profile_limit(method_counters, MethodCounters::interpreter_profile_limit_offset()); + ld(profile_limit, Rtmp); cmp(invocation_count, Rtmp); // Use long branches because call_VM() code and following code generated by // test_backedge_count_for_osr() is large in debug VM. @@ -2375,6 +2375,7 @@ void InterpreterMacroAssembler::increment_backedge_counter( Register Rcounters, #ifndef CC_INTERP void InterpreterMacroAssembler::test_backedge_count_for_osr( Register backedge_count, + Register method_counters, Register branch_bcp, Register Rtmp ) { Label did_not_overflow; @@ -2382,8 +2383,8 @@ void InterpreterMacroAssembler::test_backedge_count_for_osr( Register backedge_c assert_different_registers(backedge_count, Rtmp, branch_bcp); assert(UseOnStackReplacement,"Must UseOnStackReplacement to test_backedge_count_for_osr"); - AddressLiteral limit(&InvocationCounter::InterpreterBackwardBranchLimit); - load_contents(limit, Rtmp); + Address limit(method_counters, in_bytes(MethodCounters::interpreter_backward_branch_limit_offset())); + ld(limit, Rtmp); cmp_and_br_short(backedge_count, Rtmp, Assembler::lessUnsigned, Assembler::pt, did_not_overflow); // When ProfileInterpreter is on, the backedge_count comes from the @@ -2500,17 +2501,13 @@ void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) { // Jump if ((*counter_addr += increment) & mask) satisfies the condition. void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, - int increment, int mask, + int increment, Address mask_addr, Register scratch1, Register scratch2, Condition cond, Label *where) { ld(counter_addr, scratch1); add(scratch1, increment, scratch1); - if (is_simm13(mask)) { - andcc(scratch1, mask, G0); - } else { - set(mask, scratch2); - andcc(scratch1, scratch2, G0); - } + ld(mask_addr, scratch2); + andcc(scratch1, scratch2, G0); br(cond, false, Assembler::pn, *where); delayed()->st(scratch1, counter_addr); } diff --git a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.hpp b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.hpp index 5ba547d2241..862611c4252 100644 --- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.hpp @@ -267,7 +267,7 @@ class InterpreterMacroAssembler: public MacroAssembler { void increment_invocation_counter( Register Rcounters, Register Rtmp, Register Rtmp2 ); void increment_backedge_counter( Register Rcounters, Register Rtmp, Register Rtmp2 ); #ifndef CC_INTERP - void test_backedge_count_for_osr( Register backedge_count, Register branch_bcp, Register Rtmp ); + void test_backedge_count_for_osr(Register backedge_count, Register method_counters, Register branch_bcp, Register Rtmp ); #endif /* CC_INTERP */ // Object locking @@ -280,7 +280,7 @@ class InterpreterMacroAssembler: public MacroAssembler { void set_method_data_pointer_for_bcp(); void test_method_data_pointer(Label& zero_continue); void verify_method_data_pointer(); - void test_invocation_counter_for_mdp(Register invocation_count, Register Rtmp, Label &profile_continue); + void test_invocation_counter_for_mdp(Register invocation_count, Register method_counters, Register Rtmp, Label &profile_continue); void set_mdp_data_at(int constant, Register value); void increment_mdp_data_at(Address counter, Register bumped_count, @@ -291,7 +291,7 @@ class InterpreterMacroAssembler: public MacroAssembler { Register bumped_count, Register scratch2, bool decrement = false); void increment_mask_and_jump(Address counter_addr, - int increment, int mask, + int increment, Address mask_addr, Register scratch1, Register scratch2, Condition cond, Label *where); void set_mdp_flag_at(int flag_constant, Register scratch); diff --git a/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp b/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp index 93f87807482..c3039d51337 100644 --- a/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp @@ -282,12 +282,11 @@ address TemplateInterpreterGenerator::generate_continuation_for(TosState state) void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) { // Note: In tiered we increment either counters in MethodCounters* or in // MDO depending if we're profiling or not. - const Register Rcounters = G3_scratch; + const Register G3_method_counters = G3_scratch; Label done; if (TieredCompilation) { const int increment = InvocationCounter::count_increment; - const int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift; Label no_mdo; if (ProfileInterpreter) { // If no method data exists, go to profile_continue. @@ -297,6 +296,7 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile Address mdo_invocation_counter(G4_scratch, in_bytes(MethodData::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + Address mask(G4_scratch, in_bytes(MethodData::invoke_mask_offset())); __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, G3_scratch, Lscratch, Assembler::zero, overflow); @@ -305,20 +305,21 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile // Increment counter in MethodCounters* __ bind(no_mdo); - Address invocation_counter(Rcounters, + Address invocation_counter(G3_method_counters, in_bytes(MethodCounters::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); - __ get_method_counters(Lmethod, Rcounters, done); + __ get_method_counters(Lmethod, G3_method_counters, done); + Address mask(G3_method_counters, in_bytes(MethodCounters::invoke_mask_offset())); __ increment_mask_and_jump(invocation_counter, increment, mask, G4_scratch, Lscratch, Assembler::zero, overflow); __ bind(done); - } else { + } else { // not TieredCompilation // Update standard invocation counters - __ get_method_counters(Lmethod, Rcounters, done); - __ increment_invocation_counter(Rcounters, O0, G4_scratch); + __ get_method_counters(Lmethod, G3_method_counters, done); + __ increment_invocation_counter(G3_method_counters, O0, G4_scratch); if (ProfileInterpreter) { - Address interpreter_invocation_counter(Rcounters, + Address interpreter_invocation_counter(G3_method_counters, in_bytes(MethodCounters::interpreter_invocation_counter_offset())); __ ld(interpreter_invocation_counter, G4_scratch); __ inc(G4_scratch); @@ -327,16 +328,16 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile if (ProfileInterpreter && profile_method != NULL) { // Test to see if we should create a method data oop - AddressLiteral profile_limit((address)&InvocationCounter::InterpreterProfileLimit); - __ load_contents(profile_limit, G3_scratch); - __ cmp_and_br_short(O0, G3_scratch, Assembler::lessUnsigned, Assembler::pn, *profile_method_continue); + Address profile_limit(G3_method_counters, in_bytes(MethodCounters::interpreter_profile_limit_offset())); + __ ld(profile_limit, G1_scratch); + __ cmp_and_br_short(O0, G1_scratch, Assembler::lessUnsigned, Assembler::pn, *profile_method_continue); // if no method data exists, go to profile_method __ test_method_data_pointer(*profile_method); } - AddressLiteral invocation_limit((address)&InvocationCounter::InterpreterInvocationLimit); - __ load_contents(invocation_limit, G3_scratch); + Address invocation_limit(G3_method_counters, in_bytes(MethodCounters::interpreter_invocation_limit_offset())); + __ ld(invocation_limit, G3_scratch); __ cmp(O0, G3_scratch); __ br(Assembler::greaterEqualUnsigned, false, Assembler::pn, *overflow); // Far distance __ delayed()->nop(); diff --git a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp index 9424b1be1f6..438d376b2c6 100644 --- a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp @@ -1599,13 +1599,12 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { // Bump bytecode pointer by displacement (take the branch) __ delayed()->add( O1_disp, Lbcp, Lbcp ); // add to bc addr - const Register Rcounters = G3_scratch; - __ get_method_counters(Lmethod, Rcounters, Lforward); + const Register G3_method_counters = G3_scratch; + __ get_method_counters(Lmethod, G3_method_counters, Lforward); if (TieredCompilation) { Label Lno_mdo, Loverflow; int increment = InvocationCounter::count_increment; - int mask = ((1 << Tier0BackedgeNotifyFreqLog) - 1) << InvocationCounter::count_shift; if (ProfileInterpreter) { // If no method data exists, go to profile_continue. __ ld_ptr(Lmethod, Method::method_data_offset(), G4_scratch); @@ -1614,6 +1613,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { // Increment backedge counter in the MDO Address mdo_backedge_counter(G4_scratch, in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + Address mask(G4_scratch, in_bytes(MethodData::backedge_mask_offset())); __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, G3_scratch, O0, Assembler::notZero, &Lforward); __ ba_short(Loverflow); @@ -1621,9 +1621,10 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { // If there's no MDO, increment counter in MethodCounters* __ bind(Lno_mdo); - Address backedge_counter(Rcounters, + Address backedge_counter(G3_method_counters, in_bytes(MethodCounters::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + Address mask(G3_method_counters, in_bytes(MethodCounters::backedge_mask_offset())); __ increment_mask_and_jump(backedge_counter, increment, mask, G4_scratch, O0, Assembler::notZero, &Lforward); __ bind(Loverflow); @@ -1663,18 +1664,19 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { __ jmp(O2, G0); __ delayed()->nop(); - } else { + } else { // not TieredCompilation // Update Backedge branch separately from invocations const Register G4_invoke_ctr = G4; - __ increment_backedge_counter(Rcounters, G4_invoke_ctr, G1_scratch); + __ increment_backedge_counter(G3_method_counters, G4_invoke_ctr, G1_scratch); if (ProfileInterpreter) { - __ test_invocation_counter_for_mdp(G4_invoke_ctr, G3_scratch, Lforward); + __ test_invocation_counter_for_mdp(G4_invoke_ctr, G3_method_counters, G1_scratch, Lforward); if (UseOnStackReplacement) { - __ test_backedge_count_for_osr(O2_bumped_count, l_cur_bcp, G3_scratch); + + __ test_backedge_count_for_osr(O2_bumped_count, G3_method_counters, l_cur_bcp, G1_scratch); } } else { if (UseOnStackReplacement) { - __ test_backedge_count_for_osr(G4_invoke_ctr, l_cur_bcp, G3_scratch); + __ test_backedge_count_for_osr(G4_invoke_ctr, G3_method_counters, l_cur_bcp, G1_scratch); } } } diff --git a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp index 181ee15251b..9aa4587f793 100644 --- a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp @@ -1360,7 +1360,7 @@ void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) { // Jump if ((*counter_addr += increment) & mask) satisfies the condition. void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, - int increment, int mask, + int increment, Address mask, Register scratch, bool preloaded, Condition cond, Label* where) { if (!preloaded) { diff --git a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp index e4d61364de4..2cd8e162fde 100644 --- a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp +++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp @@ -182,7 +182,7 @@ void increment_mdp_data_at(Register mdp_in, Register reg, int constant, bool decrement = false); void increment_mask_and_jump(Address counter_addr, - int increment, int mask, + int increment, Address mask, Register scratch, bool preloaded, Condition cond, Label* where); void set_mdp_flag_at(Register mdp_in, int flag_constant); diff --git a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp index 23e3b973041..76335ca9fcc 100644 --- a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp @@ -1426,7 +1426,7 @@ void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) { // Jump if ((*counter_addr += increment) & mask) satisfies the condition. void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, - int increment, int mask, + int increment, Address mask, Register scratch, bool preloaded, Condition cond, Label* where) { if (!preloaded) { diff --git a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp index a1cd4466bb9..c4ed238bc20 100644 --- a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp +++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp @@ -191,7 +191,7 @@ void increment_mdp_data_at(Register mdp_in, Register reg, int constant, bool decrement = false); void increment_mask_and_jump(Address counter_addr, - int increment, int mask, + int increment, Address mask, Register scratch, bool preloaded, Condition cond, Label* where); void set_mdp_flag_at(Register mdp_in, int flag_constant); diff --git a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp index 93772f3df4c..69c8533d12e 100644 --- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp @@ -346,7 +346,6 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile // depending if we're profiling or not. if (TieredCompilation) { int increment = InvocationCounter::count_increment; - int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift; Label no_mdo; if (ProfileInterpreter) { // Are we profiling? @@ -356,6 +355,7 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile // Increment counter in the MDO const Address mdo_invocation_counter(rax, in_bytes(MethodData::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + const Address mask(rax, in_bytes(MethodData::invoke_mask_offset())); __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow); __ jmp(done); } @@ -366,11 +366,12 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile InvocationCounter::counter_offset()); __ get_method_counters(rbx, rax, done); + const Address mask(rax, in_bytes(MethodCounters::invoke_mask_offset())); __ increment_mask_and_jump(invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow); __ bind(done); - } else { - const Address backedge_counter (rax, + } else { // not TieredCompilation + const Address backedge_counter(rax, MethodCounters::backedge_counter_offset() + InvocationCounter::counter_offset()); const Address invocation_counter(rax, @@ -400,16 +401,16 @@ void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile if (ProfileInterpreter && profile_method != NULL) { // Test to see if we should create a method data oop - __ cmp32(rcx, - ExternalAddress((address)&InvocationCounter::InterpreterProfileLimit)); + __ movptr(rax, Address(rbx, Method::method_counters_offset())); + __ cmp32(rcx, Address(rax, in_bytes(MethodCounters::interpreter_profile_limit_offset()))); __ jcc(Assembler::less, *profile_method_continue); // if no method data exists, go to profile_method __ test_method_data_pointer(rax, *profile_method); } - __ cmp32(rcx, - ExternalAddress((address)&InvocationCounter::InterpreterInvocationLimit)); + __ movptr(rax, Address(rbx, Method::method_counters_offset())); + __ cmp32(rcx, Address(rax, in_bytes(MethodCounters::interpreter_invocation_limit_offset()))); __ jcc(Assembler::aboveEqual, *overflow); __ bind(done); } diff --git a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp index f3390c94ca9..6318a958517 100644 --- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp @@ -299,7 +299,6 @@ void InterpreterGenerator::generate_counter_incr( // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not. if (TieredCompilation) { int increment = InvocationCounter::count_increment; - int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift; Label no_mdo; if (ProfileInterpreter) { // Are we profiling? @@ -309,6 +308,7 @@ void InterpreterGenerator::generate_counter_incr( // Increment counter in the MDO const Address mdo_invocation_counter(rax, in_bytes(MethodData::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + const Address mask(rax, in_bytes(MethodData::invoke_mask_offset())); __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow); __ jmp(done); } @@ -318,10 +318,11 @@ void InterpreterGenerator::generate_counter_incr( MethodCounters::invocation_counter_offset() + InvocationCounter::counter_offset()); __ get_method_counters(rbx, rax, done); + const Address mask(rax, in_bytes(MethodCounters::invoke_mask_offset())); __ increment_mask_and_jump(invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow); __ bind(done); - } else { + } else { // not TieredCompilation const Address backedge_counter(rax, MethodCounters::backedge_counter_offset() + InvocationCounter::counter_offset()); @@ -350,14 +351,16 @@ void InterpreterGenerator::generate_counter_incr( if (ProfileInterpreter && profile_method != NULL) { // Test to see if we should create a method data oop - __ cmp32(rcx, ExternalAddress((address)&InvocationCounter::InterpreterProfileLimit)); + __ movptr(rax, Address(rbx, Method::method_counters_offset())); + __ cmp32(rcx, Address(rax, in_bytes(MethodCounters::interpreter_profile_limit_offset()))); __ jcc(Assembler::less, *profile_method_continue); // if no method data exists, go to profile_method __ test_method_data_pointer(rax, *profile_method); } - __ cmp32(rcx, ExternalAddress((address)&InvocationCounter::InterpreterInvocationLimit)); + __ movptr(rax, Address(rbx, Method::method_counters_offset())); + __ cmp32(rcx, Address(rax, in_bytes(MethodCounters::interpreter_invocation_limit_offset()))); __ jcc(Assembler::aboveEqual, *overflow); __ bind(done); } diff --git a/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp b/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp index 2187056a384..d0bdc33905c 100644 --- a/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp @@ -1621,7 +1621,6 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (TieredCompilation) { Label no_mdo; int increment = InvocationCounter::count_increment; - int mask = ((1 << Tier0BackedgeNotifyFreqLog) - 1) << InvocationCounter::count_shift; if (ProfileInterpreter) { // Are we profiling? __ movptr(rbx, Address(rcx, in_bytes(Method::method_data_offset()))); @@ -1630,6 +1629,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { // Increment the MDO backedge counter const Address mdo_backedge_counter(rbx, in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + const Address mask(rbx, in_bytes(MethodData::backedge_mask_offset())); __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, rax, false, Assembler::zero, &backedge_counter_overflow); __ jmp(dispatch); @@ -1637,9 +1637,10 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { __ bind(no_mdo); // Increment backedge counter in MethodCounters* __ movptr(rcx, Address(rcx, Method::method_counters_offset())); + const Address mask(rcx, in_bytes(MethodCounters::backedge_mask_offset())); __ increment_mask_and_jump(Address(rcx, be_offset), increment, mask, rax, false, Assembler::zero, &backedge_counter_overflow); - } else { + } else { // not TieredCompilation // increment counter __ movptr(rcx, Address(rcx, Method::method_counters_offset())); __ movl(rax, Address(rcx, be_offset)); // load backedge counter @@ -1653,8 +1654,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (ProfileInterpreter) { // Test to see if we should create a method data oop - __ cmp32(rax, - ExternalAddress((address) &InvocationCounter::InterpreterProfileLimit)); + __ cmp32(rax, Address(rcx, in_bytes(MethodCounters::interpreter_profile_limit_offset()))); __ jcc(Assembler::less, dispatch); // if no method data exists, go to profile method @@ -1662,8 +1662,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (UseOnStackReplacement) { // check for overflow against rbx, which is the MDO taken count - __ cmp32(rbx, - ExternalAddress((address) &InvocationCounter::InterpreterBackwardBranchLimit)); + __ cmp32(rbx, Address(rcx, in_bytes(MethodCounters::interpreter_backward_branch_limit_offset()))); __ jcc(Assembler::below, dispatch); // When ProfileInterpreter is on, the backedge_count comes from the @@ -1678,8 +1677,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { } else { if (UseOnStackReplacement) { // check for overflow against rax, which is the sum of the counters - __ cmp32(rax, - ExternalAddress((address) &InvocationCounter::InterpreterBackwardBranchLimit)); + __ cmp32(rax, Address(rcx, in_bytes(MethodCounters::interpreter_backward_branch_limit_offset()))); __ jcc(Assembler::aboveEqual, backedge_counter_overflow); } diff --git a/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp b/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp index b1b1b00a615..82072f0c920 100644 --- a/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp @@ -1642,7 +1642,6 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (TieredCompilation) { Label no_mdo; int increment = InvocationCounter::count_increment; - int mask = ((1 << Tier0BackedgeNotifyFreqLog) - 1) << InvocationCounter::count_shift; if (ProfileInterpreter) { // Are we profiling? __ movptr(rbx, Address(rcx, in_bytes(Method::method_data_offset()))); @@ -1651,6 +1650,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { // Increment the MDO backedge counter const Address mdo_backedge_counter(rbx, in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset())); + const Address mask(rbx, in_bytes(MethodData::backedge_mask_offset())); __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, rax, false, Assembler::zero, &backedge_counter_overflow); __ jmp(dispatch); @@ -1658,9 +1658,10 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { __ bind(no_mdo); // Increment backedge counter in MethodCounters* __ movptr(rcx, Address(rcx, Method::method_counters_offset())); + const Address mask(rcx, in_bytes(MethodCounters::backedge_mask_offset())); __ increment_mask_and_jump(Address(rcx, be_offset), increment, mask, rax, false, Assembler::zero, &backedge_counter_overflow); - } else { + } else { // not TieredCompilation // increment counter __ movptr(rcx, Address(rcx, Method::method_counters_offset())); __ movl(rax, Address(rcx, be_offset)); // load backedge counter @@ -1674,8 +1675,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (ProfileInterpreter) { // Test to see if we should create a method data oop - __ cmp32(rax, - ExternalAddress((address) &InvocationCounter::InterpreterProfileLimit)); + __ cmp32(rax, Address(rcx, in_bytes(MethodCounters::interpreter_profile_limit_offset()))); __ jcc(Assembler::less, dispatch); // if no method data exists, go to profile method @@ -1683,8 +1683,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (UseOnStackReplacement) { // check for overflow against ebx which is the MDO taken count - __ cmp32(rbx, - ExternalAddress((address) &InvocationCounter::InterpreterBackwardBranchLimit)); + __ cmp32(rbx, Address(rcx, in_bytes(MethodCounters::interpreter_backward_branch_limit_offset()))); __ jcc(Assembler::below, dispatch); // When ProfileInterpreter is on, the backedge_count comes @@ -1702,8 +1701,7 @@ void TemplateTable::branch(bool is_jsr, bool is_wide) { if (UseOnStackReplacement) { // check for overflow against eax, which is the sum of the // counters - __ cmp32(rax, - ExternalAddress((address) &InvocationCounter::InterpreterBackwardBranchLimit)); + __ cmp32(rax, Address(rcx, in_bytes(MethodCounters::interpreter_backward_branch_limit_offset()))); __ jcc(Assembler::aboveEqual, backedge_counter_overflow); } diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp index 2beb72a60f1..8fe99af08ad 100644 --- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp +++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp @@ -32,6 +32,7 @@ #include "ci/ciArrayKlass.hpp" #include "ci/ciInstance.hpp" #include "ci/ciObjArray.hpp" +#include "runtime/arguments.hpp" #include "runtime/sharedRuntime.hpp" #include "runtime/stubRoutines.hpp" #include "runtime/vm_version.hpp" @@ -3351,7 +3352,12 @@ void LIRGenerator::do_ProfileInvoke(ProfileInvoke* x) { if (!x->inlinee()->is_accessor()) { CodeEmitInfo* info = state_for(x, x->state(), true); // Notify the runtime very infrequently only to take care of counter overflows - increment_event_counter_impl(info, x->inlinee(), (1 << Tier23InlineeNotifyFreqLog) - 1, InvocationEntryBci, false, true); + int freq_log = Tier23InlineeNotifyFreqLog; + double scale; + if (_method->has_option_value("CompileThresholdScaling", scale)) { + freq_log = Arguments::scaled_freq_log(freq_log, scale); + } + increment_event_counter_impl(info, x->inlinee(), right_n_bits(freq_log), InvocationEntryBci, false, true); } } @@ -3366,7 +3372,11 @@ void LIRGenerator::increment_event_counter(CodeEmitInfo* info, int bci, bool bac ShouldNotReachHere(); } // Increment the appropriate invocation/backedge counter and notify the runtime. - increment_event_counter_impl(info, info->scope()->method(), (1 << freq_log) - 1, bci, backedge, true); + double scale; + if (_method->has_option_value("CompileThresholdScaling", scale)) { + freq_log = Arguments::scaled_freq_log(freq_log, scale); + } + increment_event_counter_impl(info, info->scope()->method(), right_n_bits(freq_log), bci, backedge, true); } void LIRGenerator::decrement_age(CodeEmitInfo* info) { diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp index 4f0def89a20..71b3fc5b3bf 100644 --- a/hotspot/src/share/vm/compiler/compileBroker.cpp +++ b/hotspot/src/share/vm/compiler/compileBroker.cpp @@ -1470,7 +1470,9 @@ bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, // The method may be explicitly excluded by the user. bool quietly; - if (CompilerOracle::should_exclude(method, quietly)) { + double scale; + if (CompilerOracle::should_exclude(method, quietly) + || (CompilerOracle::has_option_value(method, "CompileThresholdScaling", scale) && scale == 0)) { if (!quietly) { // This does not happen quietly... ResourceMark rm; diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp index 2bf9a20f27d..5ec7ec89dbe 100644 --- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp +++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp @@ -53,7 +53,7 @@ /* * USELABELS - If using GCC, then use labels for the opcode dispatching * rather -then a switch statement. This improves performance because it - * gives us the oportunity to have the instructions that calculate the + * gives us the opportunity to have the instructions that calculate the * next opcode to jump to be intermixed with the rest of the instructions * that implement the opcode (see UPDATE_PC_AND_TOS_AND_CONTINUE macro). */ diff --git a/hotspot/src/share/vm/interpreter/invocationCounter.hpp b/hotspot/src/share/vm/interpreter/invocationCounter.hpp index e0cb50cbe09..0409b02f693 100644 --- a/hotspot/src/share/vm/interpreter/invocationCounter.hpp +++ b/hotspot/src/share/vm/interpreter/invocationCounter.hpp @@ -36,7 +36,7 @@ // Implementation notes: For space reasons, state & counter are both encoded in one word, // The state is encoded using some of the least significant bits, the counter is using the // more significant bits. The counter is incremented before a method is activated and an -// action is triggered when when count() > limit(). +// action is triggered when count() > limit(). class InvocationCounter VALUE_OBJ_CLASS_SPEC { friend class VMStructs; @@ -48,7 +48,6 @@ class InvocationCounter VALUE_OBJ_CLASS_SPEC { number_of_state_bits = 2, number_of_carry_bits = 1, number_of_noncount_bits = number_of_state_bits + number_of_carry_bits, - number_of_count_bits = BitsPerInt - number_of_noncount_bits, state_limit = nth_bit(number_of_state_bits), count_grain = nth_bit(number_of_state_bits + number_of_carry_bits), carry_mask = right_n_bits(number_of_carry_bits) << number_of_state_bits, @@ -68,6 +67,7 @@ class InvocationCounter VALUE_OBJ_CLASS_SPEC { count_increment = count_grain, // use this value to increment the 32bit _counter word count_mask_value = count_mask, // use this value to mask the backedge counter count_shift = number_of_noncount_bits, + number_of_count_bits = BitsPerInt - number_of_noncount_bits, count_limit = nth_bit(number_of_count_bits - 1) }; diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp index 62a1501ab95..9e37b0b8504 100644 --- a/hotspot/src/share/vm/oops/method.cpp +++ b/hotspot/src/share/vm/oops/method.cpp @@ -412,15 +412,14 @@ MethodCounters* Method::build_method_counters(Method* m, TRAPS) { } methodHandle mh(m); - ClassLoaderData* loader_data = mh->method_holder()->class_loader_data(); - MethodCounters* counters = MethodCounters::allocate(loader_data, THREAD); + MethodCounters* counters = MethodCounters::allocate(mh, THREAD); if (HAS_PENDING_EXCEPTION) { CompileBroker::log_metaspace_failure(); ClassLoaderDataGraph::set_metaspace_oom(true); return NULL; // return the exception (which is cleared) } if (!mh->init_method_counters(counters)) { - MetadataFactory::free_metadata(loader_data, counters); + MetadataFactory::free_metadata(mh->method_holder()->class_loader_data(), counters); } return mh->method_counters(); } diff --git a/hotspot/src/share/vm/oops/methodCounters.cpp b/hotspot/src/share/vm/oops/methodCounters.cpp index 25379d25658..b78b6e8046b 100644 --- a/hotspot/src/share/vm/oops/methodCounters.cpp +++ b/hotspot/src/share/vm/oops/methodCounters.cpp @@ -23,10 +23,11 @@ */ #include "precompiled.hpp" #include "oops/methodCounters.hpp" -#include "runtime/thread.inline.hpp" +#include "runtime/handles.inline.hpp" -MethodCounters* MethodCounters::allocate(ClassLoaderData* loader_data, TRAPS) { - return new(loader_data, size(), false, MetaspaceObj::MethodCountersType, THREAD) MethodCounters(); +MethodCounters* MethodCounters::allocate(methodHandle mh, TRAPS) { + ClassLoaderData* loader_data = mh->method_holder()->class_loader_data(); + return new(loader_data, size(), false, MetaspaceObj::MethodCountersType, THREAD) MethodCounters(mh); } void MethodCounters::clear_counters() { diff --git a/hotspot/src/share/vm/oops/methodCounters.hpp b/hotspot/src/share/vm/oops/methodCounters.hpp index a21d376b871..7d042bf72a1 100644 --- a/hotspot/src/share/vm/oops/methodCounters.hpp +++ b/hotspot/src/share/vm/oops/methodCounters.hpp @@ -26,7 +26,9 @@ #define SHARE_VM_OOPS_METHODCOUNTERS_HPP #include "oops/metadata.hpp" +#include "compiler/compilerOracle.hpp" #include "interpreter/invocationCounter.hpp" +#include "runtime/arguments.hpp" class MethodCounters: public MetaspaceObj { friend class VMStructs; @@ -45,7 +47,11 @@ class MethodCounters: public MetaspaceObj { // 3. (INT_MIN..0] - method is hot and will deopt and get // recompiled without the counters int _nmethod_age; - + int _interpreter_invocation_limit; // per-method InterpreterInvocationLimit + int _interpreter_backward_branch_limit; // per-method InterpreterBackwardBranchLimit + int _interpreter_profile_limit; // per-method InterpreterProfileLimit + int _invoke_mask; // per-method Tier0InvokeNotifyFreqLog + int _backedge_mask; // per-method Tier0BackedgeNotifyFreqLog #ifdef TIERED float _rate; // Events (invocation and backedge counter increments) per millisecond jlong _prev_time; // Previous time the rate was acquired @@ -53,15 +59,15 @@ class MethodCounters: public MetaspaceObj { u1 _highest_osr_comp_level; // Same for OSR level #endif - MethodCounters() : _interpreter_invocation_count(0), - _interpreter_throwout_count(0), - _number_of_breakpoints(0), - _nmethod_age(INT_MAX) + MethodCounters(methodHandle mh) : _interpreter_invocation_count(0), + _interpreter_throwout_count(0), + _number_of_breakpoints(0), + _nmethod_age(INT_MAX) #ifdef TIERED - , _rate(0), - _prev_time(0), - _highest_comp_level(0), - _highest_osr_comp_level(0) + , _rate(0), + _prev_time(0), + _highest_comp_level(0), + _highest_osr_comp_level(0) #endif { invocation_counter()->init(); @@ -70,10 +76,28 @@ class MethodCounters: public MetaspaceObj { if (StressCodeAging) { set_nmethod_age(HotMethodDetectionLimit); } + + // Set per-method thresholds. + double scale = 1.0; + CompilerOracle::has_option_value(mh, "CompileThresholdScaling", scale); + + int compile_threshold = Arguments::scaled_compile_threshold(CompileThreshold, scale); + _interpreter_invocation_limit = compile_threshold << InvocationCounter::count_shift; + if (ProfileInterpreter) { + // If interpreter profiling is enabled, the backward branch limit + // is compared against the method data counter rather than an invocation + // counter, therefore no shifting of bits is required. + _interpreter_backward_branch_limit = (compile_threshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100; + } else { + _interpreter_backward_branch_limit = ((compile_threshold * OnStackReplacePercentage) / 100) << InvocationCounter::count_shift; + } + _interpreter_profile_limit = ((compile_threshold * InterpreterProfilePercentage) / 100) << InvocationCounter::count_shift; + _invoke_mask = right_n_bits(Arguments::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift; + _backedge_mask = right_n_bits(Arguments::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift; } public: - static MethodCounters* allocate(ClassLoaderData* loader_data, TRAPS); + static MethodCounters* allocate(methodHandle mh, TRAPS); void deallocate_contents(ClassLoaderData* loader_data) {} DEBUG_ONLY(bool on_stack() { return false; }) // for template @@ -161,5 +185,24 @@ class MethodCounters: public MetaspaceObj { return offset_of(MethodCounters, _interpreter_invocation_count); } + static ByteSize interpreter_invocation_limit_offset() { + return byte_offset_of(MethodCounters, _interpreter_invocation_limit); + } + + static ByteSize interpreter_backward_branch_limit_offset() { + return byte_offset_of(MethodCounters, _interpreter_backward_branch_limit); + } + + static ByteSize interpreter_profile_limit_offset() { + return byte_offset_of(MethodCounters, _interpreter_profile_limit); + } + + static ByteSize invoke_mask_offset() { + return byte_offset_of(MethodCounters, _invoke_mask); + } + + static ByteSize backedge_mask_offset() { + return byte_offset_of(MethodCounters, _backedge_mask); + } }; #endif //SHARE_VM_OOPS_METHODCOUNTERS_HPP diff --git a/hotspot/src/share/vm/oops/methodData.cpp b/hotspot/src/share/vm/oops/methodData.cpp index ef215581df1..f9e187f9add 100644 --- a/hotspot/src/share/vm/oops/methodData.cpp +++ b/hotspot/src/share/vm/oops/methodData.cpp @@ -31,6 +31,7 @@ #include "memory/heapInspection.hpp" #include "oops/methodData.hpp" #include "prims/jvmtiRedefineClasses.hpp" +#include "runtime/arguments.hpp" #include "runtime/compilationPolicy.hpp" #include "runtime/deoptimization.hpp" #include "runtime/handles.inline.hpp" @@ -1131,6 +1132,13 @@ void MethodData::init() { _backedge_counter.init(); _invocation_counter_start = 0; _backedge_counter_start = 0; + + // Set per-method invoke- and backedge mask. + double scale = 1.0; + CompilerOracle::has_option_value(_method, "CompileThresholdScaling", scale); + _invoke_mask = right_n_bits(Arguments::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift; + _backedge_mask = right_n_bits(Arguments::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift; + _tenure_traps = 0; _num_loops = 0; _num_blocks = 0; diff --git a/hotspot/src/share/vm/oops/methodData.hpp b/hotspot/src/share/vm/oops/methodData.hpp index e91cffb8375..d06974672ee 100644 --- a/hotspot/src/share/vm/oops/methodData.hpp +++ b/hotspot/src/share/vm/oops/methodData.hpp @@ -2088,6 +2088,8 @@ private: int _invocation_counter_start; int _backedge_counter_start; uint _tenure_traps; + int _invoke_mask; // per-method Tier0InvokeNotifyFreqLog + int _backedge_mask; // per-method Tier0BackedgeNotifyFreqLog #if INCLUDE_RTM_OPT // State of RTM code generation during compilation of the method @@ -2447,10 +2449,19 @@ public: static ByteSize invocation_counter_offset() { return byte_offset_of(MethodData, _invocation_counter); } + static ByteSize backedge_counter_offset() { return byte_offset_of(MethodData, _backedge_counter); } + static ByteSize invoke_mask_offset() { + return byte_offset_of(MethodData, _invoke_mask); + } + + static ByteSize backedge_mask_offset() { + return byte_offset_of(MethodData, _backedge_mask); + } + static ByteSize parameters_type_data_di_offset() { return byte_offset_of(MethodData, _parameters_type_data_di); } diff --git a/hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp b/hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp index bd78c3dec77..eb83161ca43 100644 --- a/hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp +++ b/hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp @@ -155,7 +155,7 @@ bool AdvancedThresholdPolicy::is_method_profiled(Method* method) { if (mdo != NULL) { int i = mdo->invocation_count_delta(); int b = mdo->backedge_count_delta(); - return call_predicate_helper(i, b, 1); + return call_predicate_helper(i, b, 1, method); } return false; } @@ -229,32 +229,32 @@ double AdvancedThresholdPolicy::threshold_scale(CompLevel level, int feedback_k) // Tier?LoadFeedback is basically a coefficient that determines of // how many methods per compiler thread can be in the queue before // the threshold values double. -bool AdvancedThresholdPolicy::loop_predicate(int i, int b, CompLevel cur_level) { +bool AdvancedThresholdPolicy::loop_predicate(int i, int b, CompLevel cur_level, Method* method) { switch(cur_level) { case CompLevel_none: case CompLevel_limited_profile: { double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback); - return loop_predicate_helper(i, b, k); + return loop_predicate_helper(i, b, k, method); } case CompLevel_full_profile: { double k = threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback); - return loop_predicate_helper(i, b, k); + return loop_predicate_helper(i, b, k, method); } default: return true; } } -bool AdvancedThresholdPolicy::call_predicate(int i, int b, CompLevel cur_level) { +bool AdvancedThresholdPolicy::call_predicate(int i, int b, CompLevel cur_level, Method* method) { switch(cur_level) { case CompLevel_none: case CompLevel_limited_profile: { double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback); - return call_predicate_helper(i, b, k); + return call_predicate_helper(i, b, k, method); } case CompLevel_full_profile: { double k = threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback); - return call_predicate_helper(i, b, k); + return call_predicate_helper(i, b, k, method); } default: return true; @@ -271,7 +271,7 @@ bool AdvancedThresholdPolicy::should_create_mdo(Method* method, CompLevel cur_le int i = method->invocation_count(); int b = method->backedge_count(); double k = Tier0ProfilingStartPercentage / 100.0; - return call_predicate_helper(i, b, k) || loop_predicate_helper(i, b, k); + return call_predicate_helper(i, b, k, method) || loop_predicate_helper(i, b, k, method); } return false; } @@ -348,7 +348,7 @@ CompLevel AdvancedThresholdPolicy::common(Predicate p, Method* method, CompLevel // If we were at full profile level, would we switch to full opt? if (common(p, method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) { next_level = CompLevel_full_optimization; - } else if ((this->*p)(i, b, cur_level)) { + } else if ((this->*p)(i, b, cur_level, method)) { // C1-generated fully profiled code is about 30% slower than the limited profile // code that has only invocation and backedge counters. The observation is that // if C2 queue is large enough we can spend too much time in the fully profiled code @@ -374,7 +374,7 @@ CompLevel AdvancedThresholdPolicy::common(Predicate p, Method* method, CompLevel if (mdo->would_profile()) { if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <= Tier3DelayOff * compiler_count(CompLevel_full_optimization) && - (this->*p)(i, b, cur_level))) { + (this->*p)(i, b, cur_level, method))) { next_level = CompLevel_full_profile; } } else { @@ -390,7 +390,7 @@ CompLevel AdvancedThresholdPolicy::common(Predicate p, Method* method, CompLevel if (mdo->would_profile()) { int mdo_i = mdo->invocation_count_delta(); int mdo_b = mdo->backedge_count_delta(); - if ((this->*p)(mdo_i, mdo_b, cur_level)) { + if ((this->*p)(mdo_i, mdo_b, cur_level, method)) { next_level = CompLevel_full_optimization; } } else { diff --git a/hotspot/src/share/vm/runtime/advancedThresholdPolicy.hpp b/hotspot/src/share/vm/runtime/advancedThresholdPolicy.hpp index a22451102c2..5ec406388f3 100644 --- a/hotspot/src/share/vm/runtime/advancedThresholdPolicy.hpp +++ b/hotspot/src/share/vm/runtime/advancedThresholdPolicy.hpp @@ -84,7 +84,7 @@ class CompileQueue; * invocation and backedge notifications. Basically every n-th invocation or backedge a mutator thread * makes a call into the runtime. * - * - Tier?CompileThreshold, Tier?BackEdgeThreshold, Tier?MinInvocationThreshold control + * - Tier?InvocationThreshold, Tier?CompileThreshold, Tier?BackEdgeThreshold, Tier?MinInvocationThreshold control * compilation thresholds. * Level 2 thresholds are not used and are provided for option-compatibility and potential future use. * Other thresholds work as follows: @@ -100,7 +100,9 @@ class CompileQueue; * The same predicate is used to control the transition from level 3 to level 4 (C2). It should be * noted though that the thresholds are relative. Moreover i and b for the 0->3 transition come * from Method* and for 3->4 transition they come from MDO (since profiled invocations are - * counted separately). + * counted separately). Finally, if a method does not contain anything worth profiling, a transition + * from level 3 to level 4 occurs without considering thresholds (e.g., with fewer invocations than + * what is specified by Tier4InvocationThreshold). * * OSR transitions are controlled simply with b > TierXBackEdgeThreshold * s predicates. * @@ -164,9 +166,9 @@ class AdvancedThresholdPolicy : public SimpleThresholdPolicy { // Call and loop predicates determine whether a transition to a higher compilation // level should be performed (pointers to predicate functions are passed to common(). // Predicates also take compiler load into account. - typedef bool (AdvancedThresholdPolicy::*Predicate)(int i, int b, CompLevel cur_level); - bool call_predicate(int i, int b, CompLevel cur_level); - bool loop_predicate(int i, int b, CompLevel cur_level); + typedef bool (AdvancedThresholdPolicy::*Predicate)(int i, int b, CompLevel cur_level, Method* method); + bool call_predicate(int i, int b, CompLevel cur_level, Method* method); + bool loop_predicate(int i, int b, CompLevel cur_level, Method* method); // Common transition function. Given a predicate determines if a method should transition to another level. CompLevel common(Predicate p, Method* method, CompLevel cur_level, bool disable_feedback = false); // Transition functions. diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 66500908d85..0c31c9bc112 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1126,16 +1126,35 @@ static void no_shared_spaces(const char* message) { } #endif -// Returns threshold scaled with CompileThresholdScaling -intx Arguments::get_scaled_compile_threshold(intx threshold) { - return (intx)(threshold * CompileThresholdScaling); +intx Arguments::scaled_compile_threshold(intx threshold, double scale) { + if (scale == 1.0 || scale < 0.0) { + return threshold; + } else { + return (intx)(threshold * scale); + } } // Returns freq_log scaled with CompileThresholdScaling -intx Arguments::get_scaled_freq_log(intx freq_log) { - intx scaled_freq = get_scaled_compile_threshold((intx)1 << freq_log); - if (scaled_freq == 0) { - return 0; +intx Arguments::scaled_freq_log(intx freq_log, double scale) { + // Check if scaling is necessary or negative value was specified. + if (scale == 1.0 || scale < 0.0) { + return freq_log; + } + + // Check value to avoid calculating log2 of 0. + if (scale == 0.0) { + return 1; + } + + intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale); + // Determine the maximum notification frequency value currently supported. + // The largest mask value that the interpreter/C1 can handle is + // of length InvocationCounter::number_of_count_bits. Mask values are always + // one bit shorter then the value of the notification frequency. Set + // max_freq_bits accordingly. + intx max_freq_bits = InvocationCounter::number_of_count_bits + 1; + if (scaled_freq > nth_bit(max_freq_bits)) { + return max_freq_bits; } else { return log2_intptr(scaled_freq); } @@ -1180,31 +1199,36 @@ void Arguments::set_tiered_flags() { Tier3InvokeNotifyFreqLog = 0; Tier4InvocationThreshold = 0; } + + if (CompileThresholdScaling < 0) { + vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL); + } + // Scale tiered compilation thresholds if (!FLAG_IS_DEFAULT(CompileThresholdScaling)) { - FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, get_scaled_freq_log(Tier0InvokeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, get_scaled_freq_log(Tier0BackedgeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier3InvocationThreshold, get_scaled_compile_threshold(Tier3InvocationThreshold)); - FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, get_scaled_compile_threshold(Tier3MinInvocationThreshold)); - FLAG_SET_ERGO(intx, Tier3CompileThreshold, get_scaled_compile_threshold(Tier3CompileThreshold)); - FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, get_scaled_compile_threshold(Tier3BackEdgeThreshold)); + FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold)); + FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold)); + FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold)); + FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold)); // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here // once these thresholds become supported. - FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, get_scaled_freq_log(Tier2InvokeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, get_scaled_freq_log(Tier2BackedgeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, get_scaled_freq_log(Tier3InvokeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, get_scaled_freq_log(Tier3BackedgeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, get_scaled_freq_log(Tier23InlineeNotifyFreqLog)); + FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog)); - FLAG_SET_ERGO(intx, Tier4InvocationThreshold, get_scaled_compile_threshold(Tier4InvocationThreshold)); - FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, get_scaled_compile_threshold(Tier4MinInvocationThreshold)); - FLAG_SET_ERGO(intx, Tier4CompileThreshold, get_scaled_compile_threshold(Tier4CompileThreshold)); - FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, get_scaled_compile_threshold(Tier4BackEdgeThreshold)); + FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold)); + FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold)); + FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold)); + FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold)); } } @@ -3456,7 +3480,7 @@ jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_req } if ((TieredCompilation && CompileThresholdScaling == 0) - || (!TieredCompilation && get_scaled_compile_threshold(CompileThreshold) == 0)) { + || (!TieredCompilation && scaled_compile_threshold(CompileThreshold) == 0)) { set_mode_flags(_int); } @@ -3896,7 +3920,7 @@ jint Arguments::apply_ergo() { } // Scale CompileThreshold if (!FLAG_IS_DEFAULT(CompileThresholdScaling)) { - FLAG_SET_ERGO(intx, CompileThreshold, get_scaled_compile_threshold(CompileThreshold)); + FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold)); } } diff --git a/hotspot/src/share/vm/runtime/arguments.hpp b/hotspot/src/share/vm/runtime/arguments.hpp index a0edd81f2e6..ae726b82fdc 100644 --- a/hotspot/src/share/vm/runtime/arguments.hpp +++ b/hotspot/src/share/vm/runtime/arguments.hpp @@ -328,9 +328,6 @@ class Arguments : AllStatic { static bool _ClipInlining; static bool _CIDynamicCompilePriority; - // Scale compile thresholds - static intx get_scaled_compile_threshold(intx threshold); - static intx get_scaled_freq_log(intx freq_log); // Tiered static void set_tiered_flags(); static int get_min_number_of_compiler_threads(); @@ -452,6 +449,18 @@ class Arguments : AllStatic { static char* SharedArchivePath; public: + // Scale compile thresholds + // Returns threshold scaled with CompileThresholdScaling + static intx scaled_compile_threshold(intx threshold, double scale); + static intx scaled_compile_threshold(intx threshold) { + return scaled_compile_threshold(threshold, CompileThresholdScaling); + } + // Returns freq_log scaled with CompileThresholdScaling + static intx scaled_freq_log(intx freq_log, double scale); + static intx scaled_freq_log(intx freq_log) { + return scaled_freq_log(freq_log, CompileThresholdScaling); + } + // Parses the arguments, first phase static jint parse(const JavaVMInitArgs* args); // Apply ergonomics diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index 6d56c2f93d6..dd014368f69 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -2477,7 +2477,7 @@ class CommandLineFlags { "Number of compiler threads to run") \ \ product(intx, CompilationPolicyChoice, 0, \ - "which compilation policy (0/1)") \ + "which compilation policy (0-3)") \ \ develop(bool, UseStackBanging, true, \ "use stack banging for stack overflow checks (required for " \ @@ -3528,7 +3528,16 @@ class CommandLineFlags { \ product(double, CompileThresholdScaling, 1.0, \ "Factor to control when first compilation happens " \ - "(both with and without tiered compilation)") \ + "(both with and without tiered compilation): " \ + "values greater than 1.0 delay counter overflow, " \ + "values between 0 and 1.0 rush counter overflow, " \ + "value of 1.0 leave compilation thresholds unchanged " \ + "value of 0.0 is equivalent to -Xint. " \ + "" \ + "Flag can be set as per-method option. " \ + "If a value is specified for a method, compilation thresholds " \ + "for that method are scaled by both the value of the global flag "\ + "and the value of the per-method flag.") \ \ product(intx, Tier0InvokeNotifyFreqLog, 7, \ "Interpreter (tier 0) invocation notification frequency") \ diff --git a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.cpp b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.cpp index 11803f1f6a4..4b17ca2bc85 100644 --- a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.cpp +++ b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.cpp @@ -257,28 +257,28 @@ void SimpleThresholdPolicy::submit_compile(methodHandle mh, int bci, CompLevel l // Call and loop predicates determine whether a transition to a higher // compilation level should be performed (pointers to predicate functions // are passed to common() transition function). -bool SimpleThresholdPolicy::loop_predicate(int i, int b, CompLevel cur_level) { +bool SimpleThresholdPolicy::loop_predicate(int i, int b, CompLevel cur_level, Method* method) { switch(cur_level) { case CompLevel_none: case CompLevel_limited_profile: { - return loop_predicate_helper(i, b, 1.0); + return loop_predicate_helper(i, b, 1.0, method); } case CompLevel_full_profile: { - return loop_predicate_helper(i, b, 1.0); + return loop_predicate_helper(i, b, 1.0, method); } default: return true; } } -bool SimpleThresholdPolicy::call_predicate(int i, int b, CompLevel cur_level) { +bool SimpleThresholdPolicy::call_predicate(int i, int b, CompLevel cur_level, Method* method) { switch(cur_level) { case CompLevel_none: case CompLevel_limited_profile: { - return call_predicate_helper(i, b, 1.0); + return call_predicate_helper(i, b, 1.0, method); } case CompLevel_full_profile: { - return call_predicate_helper(i, b, 1.0); + return call_predicate_helper(i, b, 1.0, method); } default: return true; @@ -293,8 +293,8 @@ bool SimpleThresholdPolicy::is_mature(Method* method) { int i = mdo->invocation_count(); int b = mdo->backedge_count(); double k = ProfileMaturityPercentage / 100.0; - return call_predicate_helper(i, b, k) || - loop_predicate_helper(i, b, k); + return call_predicate_helper(i, b, k, method) || + loop_predicate_helper(i, b, k, method); } return false; } @@ -313,7 +313,7 @@ CompLevel SimpleThresholdPolicy::common(Predicate p, Method* method, CompLevel c // If we were at full profile level, would we switch to full opt? if (common(p, method, CompLevel_full_profile) == CompLevel_full_optimization) { next_level = CompLevel_full_optimization; - } else if ((this->*p)(i, b, cur_level)) { + } else if ((this->*p)(i, b, cur_level, method)) { next_level = CompLevel_full_profile; } break; @@ -325,7 +325,7 @@ CompLevel SimpleThresholdPolicy::common(Predicate p, Method* method, CompLevel c if (mdo->would_profile()) { int mdo_i = mdo->invocation_count_delta(); int mdo_b = mdo->backedge_count_delta(); - if ((this->*p)(mdo_i, mdo_b, cur_level)) { + if ((this->*p)(mdo_i, mdo_b, cur_level, method)) { next_level = CompLevel_full_optimization; } } else { diff --git a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.hpp b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.hpp index 49a9d893406..87d009e1360 100644 --- a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.hpp +++ b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.hpp @@ -43,9 +43,9 @@ class SimpleThresholdPolicy : public CompilationPolicy { // Call and loop predicates determine whether a transition to a higher compilation // level should be performed (pointers to predicate functions are passed to common_TF(). // Predicates also take compiler load into account. - typedef bool (SimpleThresholdPolicy::*Predicate)(int i, int b, CompLevel cur_level); - bool call_predicate(int i, int b, CompLevel cur_level); - bool loop_predicate(int i, int b, CompLevel cur_level); + typedef bool (SimpleThresholdPolicy::*Predicate)(int i, int b, CompLevel cur_level, Method* method); + bool call_predicate(int i, int b, CompLevel cur_level, Method* method); + bool loop_predicate(int i, int b, CompLevel cur_level, Method* method); // Common transition function. Given a predicate determines if a method should transition to another level. CompLevel common(Predicate p, Method* method, CompLevel cur_level); // Transition functions. @@ -76,8 +76,8 @@ protected: // Predicate helpers are used by .*_predicate() methods as well as others. // They check the given counter values, multiplied by the scale against the thresholds. - template static inline bool call_predicate_helper(int i, int b, double scale); - template static inline bool loop_predicate_helper(int i, int b, double scale); + template static inline bool call_predicate_helper(int i, int b, double scale, Method* method); + template static inline bool loop_predicate_helper(int i, int b, double scale, Method* method); // Get a compilation level for a given method. static CompLevel comp_level(Method* method) { diff --git a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.inline.hpp b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.inline.hpp index ff0a6cf8330..05b37c48084 100644 --- a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.inline.hpp +++ b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.inline.hpp @@ -25,8 +25,14 @@ #ifndef SHARE_VM_RUNTIME_SIMPLETHRESHOLDPOLICY_INLINE_HPP #define SHARE_VM_RUNTIME_SIMPLETHRESHOLDPOLICY_INLINE_HPP +#include "compiler/compilerOracle.hpp" + template -bool SimpleThresholdPolicy::call_predicate_helper(int i, int b, double scale) { +bool SimpleThresholdPolicy::call_predicate_helper(int i, int b, double scale, Method* method) { + double threshold_scaling; + if (CompilerOracle::has_option_value(method, "CompileThresholdScaling", threshold_scaling)) { + scale *= threshold_scaling; + } switch(level) { case CompLevel_none: case CompLevel_limited_profile: @@ -40,7 +46,11 @@ bool SimpleThresholdPolicy::call_predicate_helper(int i, int b, double scale) { } template -bool SimpleThresholdPolicy::loop_predicate_helper(int i, int b, double scale) { +bool SimpleThresholdPolicy::loop_predicate_helper(int i, int b, double scale, Method* method) { + double threshold_scaling; + if (CompilerOracle::has_option_value(method, "CompileThresholdScaling", threshold_scaling)) { + scale *= threshold_scaling; + } switch(level) { case CompLevel_none: case CompLevel_limited_profile: diff --git a/hotspot/src/share/vm/runtime/vmStructs.cpp b/hotspot/src/share/vm/runtime/vmStructs.cpp index 58b1a97a18e..d2dba088ea3 100644 --- a/hotspot/src/share/vm/runtime/vmStructs.cpp +++ b/hotspot/src/share/vm/runtime/vmStructs.cpp @@ -351,11 +351,18 @@ typedef TwoOopHashtable SymbolTwoOopHashtable; nonstatic_field(MethodData, _arg_stack, intx) \ nonstatic_field(MethodData, _arg_returned, intx) \ nonstatic_field(MethodData, _tenure_traps, uint) \ + nonstatic_field(MethodData, _invoke_mask, int) \ + nonstatic_field(MethodData, _backedge_mask, int) \ nonstatic_field(DataLayout, _header._struct._tag, u1) \ nonstatic_field(DataLayout, _header._struct._flags, u1) \ nonstatic_field(DataLayout, _header._struct._bci, u2) \ nonstatic_field(DataLayout, _cells[0], intptr_t) \ nonstatic_field(MethodCounters, _nmethod_age, int) \ + nonstatic_field(MethodCounters, _interpreter_invocation_limit, int) \ + nonstatic_field(MethodCounters, _interpreter_backward_branch_limit, int) \ + nonstatic_field(MethodCounters, _interpreter_profile_limit, int) \ + nonstatic_field(MethodCounters, _invoke_mask, int) \ + nonstatic_field(MethodCounters, _backedge_mask, int) \ nonstatic_field(MethodCounters, _interpreter_invocation_count, int) \ nonstatic_field(MethodCounters, _interpreter_throwout_count, u2) \ nonstatic_field(MethodCounters, _number_of_breakpoints, u2) \ diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.hpp b/hotspot/src/share/vm/utilities/globalDefinitions.hpp index 784db46775d..652da096e43 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp @@ -1142,17 +1142,18 @@ inline bool is_power_of_2_long(jlong x) { return ((x != NoLongBits) && (mask_long_bits(x, x - 1) == NoLongBits)); } -//* largest i such that 2^i <= x -// A negative value of 'x' will return '31' +// Returns largest i such that 2^i <= x. +// If x < 0, the function returns 31 on a 32-bit machine and 63 on a 64-bit machine. +// If x == 0, the function returns -1. inline int log2_intptr(intptr_t x) { int i = -1; - uintptr_t p = 1; + uintptr_t p = 1; while (p != 0 && p <= (uintptr_t)x) { // p = 2^(i+1) && p <= x (i.e., 2^(i+1) <= x) i++; p *= 2; } // p = 2^(i+1) && x < p (i.e., 2^i <= x < 2^(i+1)) - // (if p = 0 then overflow occurred and i = 31) + // If p = 0, overflow has occurred and i = 31 or i = 63 (depending on the machine word size). return i; } diff --git a/hotspot/test/compiler/arguments/CheckCompileThresholdScaling.java b/hotspot/test/compiler/arguments/CheckCompileThresholdScaling.java index b9837c2ba8d..5e611022762 100644 --- a/hotspot/test/compiler/arguments/CheckCompileThresholdScaling.java +++ b/hotspot/test/compiler/arguments/CheckCompileThresholdScaling.java @@ -54,7 +54,7 @@ public class CheckCompileThresholdScaling { // // Tier0InvokeNotifyFreqLog, Tier0BackedgeNotifyFreqLog, // Tier3InvocationThreshold, Tier3MinInvocationThreshold, - // Tier3CompileThreshold, and Tier3BackEdgeThreshold, + // Tier3CompileThreshold, Tier3BackEdgeThreshold, // Tier2InvokeNotifyFreqLog, Tier2BackedgeNotifyFreqLog, // Tier3InvokeNotifyFreqLog, Tier3BackedgeNotifyFreqLog, // Tier23InlineeNotifyFreqLog, Tier4InvocationThreshold, From 4b78cb3eb743b8d57842a8106b249f133650640a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joel=20Borggr=C3=A9n-Franck?= Date: Wed, 21 Jan 2015 19:02:20 +0100 Subject: [PATCH 122/149] 8070507: LambdaLambdaSerialized can fail in -agentvm mode Reviewed-by: mcimadamore --- .../tools/javac/lambda/LambdaLambdaSerialized.java | 10 +++++----- .../tools/javac/lambda/SerializedLambdaInInit.java | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/langtools/test/tools/javac/lambda/LambdaLambdaSerialized.java b/langtools/test/tools/javac/lambda/LambdaLambdaSerialized.java index f788e8a16c7..1e323888c0f 100644 --- a/langtools/test/tools/javac/lambda/LambdaLambdaSerialized.java +++ b/langtools/test/tools/javac/lambda/LambdaLambdaSerialized.java @@ -67,13 +67,13 @@ public class LambdaLambdaSerialized { out.writeObject(lamb); } - static void readAssert(ObjectInputStream in, String expected) throws IOException, ClassNotFoundException { - LSI> ls = (LSI>) in.readObject(); + static void readAssert(ObjectInputStream in, String expected) throws IOException, ClassNotFoundException { + LSI> ls = (LSI>)in.readObject(); Map result = ls.get().get(); System.out.printf("Result: %s\n", result); } -} -interface LSI extends Serializable { - T get(); + interface LSI extends Serializable { + T get(); + } } diff --git a/langtools/test/tools/javac/lambda/SerializedLambdaInInit.java b/langtools/test/tools/javac/lambda/SerializedLambdaInInit.java index cafa39c5bc7..4959fb64ab9 100644 --- a/langtools/test/tools/javac/lambda/SerializedLambdaInInit.java +++ b/langtools/test/tools/javac/lambda/SerializedLambdaInInit.java @@ -111,8 +111,8 @@ public class SerializedLambdaInInit { } } } -} -interface LSI extends Serializable { - String convert(String x); + interface LSI extends Serializable { + String convert(String x); + } } From 16cb5bbca26fd828303b9171854ff1433a65d7b1 Mon Sep 17 00:00:00 2001 From: Lance Andersen Date: Wed, 21 Jan 2015 13:19:08 -0500 Subject: [PATCH 123/149] 8068732: Adding Initial RowSet tests Reviewed-by: joehw --- .../testng/test/rowset/BaseRowSetTests.java | 1150 ++---------- .../testng/test/rowset/CommonRowSetTests.java | 1372 ++++++++++++++ .../cachedrowset/CachedRowSetTests.java | 35 + .../cachedrowset/CommonCachedRowSetTests.java | 1612 +++++++++++++++++ .../rowset/filteredrowset/CityFilter.java | 100 + .../filteredrowset/FilteredRowSetTests.java | 140 ++ .../filteredrowset/PrimaryKeyFilter.java | 93 + .../rowset/joinrowset/JoinRowSetTests.java | 324 ++++ .../webrowset/CommonWebRowSetTests.java | 400 ++++ .../test/rowset/webrowset/WebRowSetTests.java | 35 + .../sql/testng/util/StubSyncProvider.java | 6 +- jdk/test/javax/sql/testng/xml/COFFEE_ROWS.xml | 191 ++ .../sql/testng/xml/DELETED_COFFEE_ROWS.xml | 191 ++ .../sql/testng/xml/INSERTED_COFFEE_ROWS.xml | 207 +++ .../xml/MODFIED_DELETED_COFFEE_ROWS.xml | 191 ++ .../sql/testng/xml/UPDATED_COFFEE_ROWS.xml | 193 ++ .../xml/UPDATED_INSERTED_COFFEE_ROWS.xml | 201 ++ 17 files changed, 5426 insertions(+), 1015 deletions(-) create mode 100644 jdk/test/javax/sql/testng/test/rowset/CommonRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/cachedrowset/CachedRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/cachedrowset/CommonCachedRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/filteredrowset/CityFilter.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/filteredrowset/FilteredRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/filteredrowset/PrimaryKeyFilter.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/joinrowset/JoinRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/webrowset/CommonWebRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/test/rowset/webrowset/WebRowSetTests.java create mode 100644 jdk/test/javax/sql/testng/xml/COFFEE_ROWS.xml create mode 100644 jdk/test/javax/sql/testng/xml/DELETED_COFFEE_ROWS.xml create mode 100644 jdk/test/javax/sql/testng/xml/INSERTED_COFFEE_ROWS.xml create mode 100644 jdk/test/javax/sql/testng/xml/MODFIED_DELETED_COFFEE_ROWS.xml create mode 100644 jdk/test/javax/sql/testng/xml/UPDATED_COFFEE_ROWS.xml create mode 100644 jdk/test/javax/sql/testng/xml/UPDATED_INSERTED_COFFEE_ROWS.xml diff --git a/jdk/test/javax/sql/testng/test/rowset/BaseRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/BaseRowSetTests.java index 8e92f20af33..95883556a05 100644 --- a/jdk/test/javax/sql/testng/test/rowset/BaseRowSetTests.java +++ b/jdk/test/javax/sql/testng/test/rowset/BaseRowSetTests.java @@ -1,5 +1,5 @@ /* - * 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 @@ -30,13 +30,9 @@ import java.math.BigDecimal; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Date; import java.sql.Ref; -import java.sql.RowId; -import java.sql.SQLFeatureNotSupportedException; +import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; @@ -44,407 +40,74 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; +import javax.sql.RowSet; import javax.sql.rowset.serial.SerialArray; import javax.sql.rowset.serial.SerialBlob; import javax.sql.rowset.serial.SerialClob; import javax.sql.rowset.serial.SerialRef; import static org.testng.Assert.*; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import util.BaseTest; import util.StubArray; import util.StubBaseRowSet; import util.StubBlob; import util.StubClob; -import util.StubNClob; import util.StubRef; -import util.StubRowId; -import util.StubSQLXML; import util.TestRowSetListener; -public class BaseRowSetTests extends BaseTest { +public class BaseRowSetTests extends CommonRowSetTests { private StubBaseRowSet brs; - private StubBaseRowSet brs1; - private final String query = "SELECT * FROM SUPERHEROS"; - private final String url = "jdbc:derby://localhost:1527/myDB"; - private final String dsName = "jdbc/myDB"; - private final String user = "Bruce Wayne"; - private final String password = "The Dark Knight"; - private final Date aDate = Date.valueOf(LocalDate.now()); - private final Time aTime = Time.valueOf(LocalTime.now()); - private final Timestamp ts = Timestamp.valueOf(LocalDateTime.now()); - private final Calendar cal = Calendar.getInstance(); - private final byte[] bytes = new byte[10]; - private RowId aRowid; - private Ref aRef; - private Blob aBlob; - private Clob aClob; - private Array aArray; - private InputStream is; - private Reader rdr; - private Map> map = new HashMap<>(); - public BaseRowSetTests() { - brs1 = new StubBaseRowSet(); - is = new StringBufferInputStream(query); - rdr = new StringReader(query); - aRowid = new StubRowId(); - try { - aBlob = new SerialBlob(new StubBlob()); - aClob = new SerialClob(new StubClob()); - aRef = new SerialRef(new StubRef("INTEGER", query)); - aArray = new SerialArray(new StubArray("INTEGER", new Object[1])); - map.put("SUPERHERO", Class.forName("util.SuperHero")); - } catch (SQLException | ClassNotFoundException ex) { - Logger.getLogger(BaseRowSetTests.class.getName()).log(Level.SEVERE, null, ex); - } - } - - @BeforeMethod @Override - public void setUpMethod() throws Exception { - brs = new StubBaseRowSet(); - } - - /* - * Validate that getCommand() returns null by default - */ - @Test - public void test() { - assertTrue(brs.getCommand() == null); - } - - /* - * Validate that getCommand() returns command specified to setCommand - */ - @Test - public void test01() throws Exception { - brs.setCommand(query); - assertTrue(brs.getCommand().equals(query)); - } - - /* - * Validate that getCurrency() returns the correct default value - */ - @Test - public void test02() throws Exception { - assertTrue(brs.getConcurrency() == ResultSet.CONCUR_UPDATABLE); - } - - /* - * Validate that getCurrency() returns the correct value - * after a call to setConcurrency()) - */ - @Test(dataProvider = "concurTypes") - public void test03(int concurType) throws Exception { - brs.setConcurrency(concurType); - assertTrue(brs.getConcurrency() == concurType); - } - - /* - * Validate that getCurrency() throws a SQLException for an invalid value - */ - @Test(expectedExceptions = SQLException.class) - public void test04() throws Exception { - brs.setConcurrency(ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - - /* - * Validate that getDataSourceName() returns null by default - */ - @Test - public void test05() throws Exception { - assertTrue(brs.getDataSourceName() == null); - } - - /* - * Validate that getDataSourceName() returns the value specified - * by setDataSourceName() and getUrl() returns null - */ - @Test - public void test06() throws Exception { - brs.setUrl(url); - brs.setDataSourceName(dsName); - assertTrue(brs.getDataSourceName().equals(dsName)); - assertTrue(brs.getUrl() == null); - } - - /* - * Validate that setDataSourceName() throws a SQLException for an empty - * String specified for the data source name - */ - @Test(expectedExceptions = SQLException.class) - public void test07() throws Exception { - String dsname = ""; - brs.setDataSourceName(dsname); - } - - /* - * Validate that getEscapeProcessing() returns true by default - */ - @Test - public void test08() throws Exception { - assertTrue(brs.getEscapeProcessing()); - } - - /* - * Validate that getEscapeProcessing() returns value set by - * setEscapeProcessing() - */ - @Test(dataProvider = "trueFalse") - public void test09(boolean val) throws Exception { - brs.setEscapeProcessing(val); - assertTrue(brs.getEscapeProcessing() == val); - } - - /* - * Validate that getFetchDirection() returns the correct default value - */ - @Test - public void test10() throws Exception { - assertTrue(brs.getFetchDirection() == ResultSet.FETCH_FORWARD); - } - - /* - * Validate that getFetchDirection() returns the value set by - * setFetchDirection() - */ - @Test(dataProvider = "fetchDirection") - public void test11(int direction) throws Exception { - brs.setFetchDirection(direction); - assertTrue(brs.getFetchDirection() == direction); - } - - /* - * Validate that setConcurrency() throws a SQLException for an invalid value - */ - @Test(expectedExceptions = SQLException.class) - public void test12() throws Exception { - brs.setConcurrency(ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - - /* - * Validate that setFetchSize() throws a SQLException for an invalid value - */ - @Test(expectedExceptions = SQLException.class) - public void test13() throws Exception { - brs.setFetchSize(-1); - } - - /* - * Validate that setFetchSize() throws a SQLException for a - * value greater than getMaxRows() - */ - @Test(expectedExceptions = SQLException.class) - public void test14() throws Exception { - brs.setMaxRows(5); - brs.setFetchSize(brs.getMaxRows() + 1); - } - - /* - * Validate that getFetchSize() returns the correct value after - * setFetchSize() has been called - */ - @Test - public void test15() throws Exception { - int maxRows = 150; - brs.setFetchSize(0); - assertTrue(brs.getFetchSize() == 0); - brs.setFetchSize(100); - assertTrue(brs.getFetchSize() == 100); - brs.setMaxRows(maxRows); - brs.setFetchSize(maxRows); - assertTrue(brs.getFetchSize() == maxRows); - } - - /* - * Validate that setMaxFieldSize() throws a SQLException for an invalid value - */ - @Test(expectedExceptions = SQLException.class) - public void test16() throws Exception { - brs.setMaxFieldSize(-1); - } - - /* - * Validate that getMaxFieldSize() returns the value set by - * setMaxFieldSize() - */ - @Test - public void test17() throws Exception { - brs.setMaxFieldSize(0); - assertTrue(brs.getMaxFieldSize() == 0); - brs.setMaxFieldSize(100); - assertTrue(brs.getMaxFieldSize() == 100); - brs.setMaxFieldSize(50); - assertTrue(brs.getMaxFieldSize() == 50); - } - - /* - * Validate that isReadOnly() returns value set by - * setReadOnly() - */ - @Test(dataProvider = "trueFalse") - public void test18(boolean val) throws Exception { - brs.setReadOnly(val); - assertTrue(brs.isReadOnly() == val); - } - - /* - * Validate that getTransactionIsolation() returns value set by - * setTransactionIsolation() - */ - @Test(dataProvider = "isolationTypes") - public void test19(int val) throws Exception { - brs.setTransactionIsolation(val); - assertTrue(brs.getTransactionIsolation() == val); - } - - /* - * Validate that getType() returns value set by setType() - */ - @Test(dataProvider = "scrollTypes") - public void test20(int val) throws Exception { - brs.setType(val); - assertTrue(brs.getType() == val); - } - - /* - * Validate that getEscapeProcessing() returns value set by - * setEscapeProcessing() - */ - @Test(dataProvider = "trueFalse") - public void test21(boolean val) throws Exception { - brs.setShowDeleted(val); - assertTrue(brs.getShowDeleted() == val); - } - - /* - * Validate that getTypeMap() returns same value set by - * setTypeMap() - */ - @Test() - public void test22() throws Exception { - brs.setTypeMap(map); - assertTrue(brs.getTypeMap().equals(map)); - } - - /* - * Validate that getUsername() returns same value set by - * setUsername() - */ - @Test() - public void test23() throws Exception { - brs.setUsername(user); - assertTrue(brs.getUsername().equals(user)); - } - - /* - * Validate that getPassword() returns same password set by - * setPassword() - */ - @Test() - public void test24() throws Exception { - brs.setPassword(password); - assertTrue(brs.getPassword().equals(password)); - } - - /* - * Validate that getQueryTimeout() returns same value set by - * setQueryTimeout() and that 0 is a valid timeout value - */ - @Test() - public void test25() throws Exception { - int timeout = 0; - brs.setQueryTimeout(timeout); - assertTrue(brs.getQueryTimeout() == timeout); - } - - /* - * Validate that getQueryTimeout() returns same value set by - * setQueryTimeout() and that 0 is a valid timeout value - */ - @Test() - public void test26() throws Exception { - int timeout = 10000; - brs.setQueryTimeout(timeout); - assertTrue(brs.getQueryTimeout() == timeout); - } - - /* - * Validate that setQueryTimeout() throws a SQLException for a timeout - * value < 0 - */ - @Test(expectedExceptions = SQLException.class) - public void test27() throws Exception { - brs.setQueryTimeout(-1); - } - - /* - * Create a RowSetListener and validate that notifyRowSetChanged is called - */ - @Test() - public void test28() throws Exception { - TestRowSetListener rsl = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.notifyRowSetChanged(); - assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); - } - - /* - * Create a RowSetListener and validate that notifyRowChanged is called - */ - @Test() - public void test29() throws Exception { - TestRowSetListener rsl = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.notifyRowChanged(); - assertTrue(rsl.isNotified(TestRowSetListener.ROW_CHANGED)); + protected RowSet newInstance() throws SQLException { + return new StubBaseRowSet(); } /* * Create a RowSetListener and validate that notifyCursorMoved is called */ - @Test() - public void test30() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0000(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.notifyCursorMoved(); + rs.addRowSetListener(rsl); + rs.notifyCursorMoved(); assertTrue(rsl.isNotified(TestRowSetListener.CURSOR_MOVED)); } /* - * Create a RowSetListener and validate that notifyRowSetChanged, - * notifyRowChanged() and notifyCursorMoved are called + * Create a RowSetListener and validate that notifyRowChanged is called */ - @Test() - public void test31() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0001(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.notifyRowSetChanged(); - brs.notifyRowChanged(); - brs.notifyCursorMoved(); - assertTrue(rsl.isNotified( - TestRowSetListener.CURSOR_MOVED | TestRowSetListener.ROWSET_CHANGED - | TestRowSetListener.ROW_CHANGED)); + rs.addRowSetListener(rsl); + rs.notifyRowChanged(); + assertTrue(rsl.isNotified(TestRowSetListener.ROW_CHANGED)); + } + + /* + * Create a RowSetListener and validate that notifyRowSetChanged is called + */ + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0002(StubBaseRowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.notifyRowSetChanged(); + assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); } /* * Create multiple RowSetListeners and validate that notifyRowSetChanged * is called on all listeners */ - @Test() - public void test32() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0003(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); TestRowSetListener rsl2 = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.addRowSetListener(rsl2); - brs.notifyRowSetChanged(); + rs.addRowSetListener(rsl); + rs.addRowSetListener(rsl2); + rs.notifyRowSetChanged(); assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); assertTrue(rsl2.isNotified(TestRowSetListener.ROWSET_CHANGED)); } @@ -453,13 +116,13 @@ public class BaseRowSetTests extends BaseTest { * Create multiple RowSetListeners and validate that notifyRowChanged * is called on all listeners */ - @Test() - public void test33() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0004(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); TestRowSetListener rsl2 = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.addRowSetListener(rsl2); - brs.notifyRowChanged(); + rs.addRowSetListener(rsl); + rs.addRowSetListener(rsl2); + rs.notifyRowChanged(); assertTrue(rsl.isNotified(TestRowSetListener.ROW_CHANGED)); assertTrue(rsl2.isNotified(TestRowSetListener.ROW_CHANGED)); } @@ -468,30 +131,47 @@ public class BaseRowSetTests extends BaseTest { * Create multiple RowSetListeners and validate that notifyCursorMoved * is called on all listeners */ - @Test() - public void test34() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0005(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); TestRowSetListener rsl2 = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.addRowSetListener(rsl2); - brs.notifyCursorMoved(); + rs.addRowSetListener(rsl); + rs.addRowSetListener(rsl2); + rs.notifyCursorMoved(); assertTrue(rsl.isNotified(TestRowSetListener.CURSOR_MOVED)); assertTrue(rsl2.isNotified(TestRowSetListener.CURSOR_MOVED)); } + /* + * Create a RowSetListener and validate that notifyRowSetChanged, + * notifyRowChanged() and notifyCursorMoved are called + */ + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0006(StubBaseRowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.notifyRowSetChanged(); + rs.notifyRowChanged(); + rs.notifyCursorMoved(); + assertTrue(rsl.isNotified( + TestRowSetListener.CURSOR_MOVED | TestRowSetListener.ROWSET_CHANGED + | TestRowSetListener.ROW_CHANGED)); + } + + /* * Create multiple RowSetListeners and validate that notifyRowSetChanged, * notifyRowChanged() and notifyCursorMoved are called on all listeners */ - @Test() - public void test35() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0007(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); TestRowSetListener rsl2 = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.addRowSetListener(rsl2); - brs.notifyRowSetChanged(); - brs.notifyRowChanged(); - brs.notifyCursorMoved(); + rs.addRowSetListener(rsl); + rs.addRowSetListener(rsl2); + rs.notifyRowSetChanged(); + rs.notifyRowChanged(); + rs.notifyCursorMoved(); assertTrue(rsl.isNotified( TestRowSetListener.CURSOR_MOVED | TestRowSetListener.ROWSET_CHANGED | TestRowSetListener.ROW_CHANGED)); @@ -505,55 +185,25 @@ public class BaseRowSetTests extends BaseTest { * remove the listener, invoke notifyRowSetChanged again and verify the * listner is not called */ - @Test() - public void test36() throws Exception { + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0008(StubBaseRowSet rs) throws Exception { TestRowSetListener rsl = new TestRowSetListener(); - brs.addRowSetListener(rsl); - brs.notifyRowSetChanged(); + rs.addRowSetListener(rsl); + rs.notifyRowSetChanged(); assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); // Clear the flag indicating the listener has been called rsl.resetFlag(); - brs.removeRowSetListener(rsl); - brs.notifyRowSetChanged(); + rs.removeRowSetListener(rsl); + rs.notifyRowSetChanged(); assertFalse(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); } - /* - * Validate addRowSetListener does not throw an Exception when null is - * passed as the parameter - */ - @Test() - public void test37() throws Exception { - brs.addRowSetListener(null); - } - - /* - * Validate removeRowSetListener does not throw an Exception when null is - * passed as the parameter - */ - @Test() - public void test38() throws Exception { - brs.removeRowSetListener(null); - } - - /* - * Set two parameters and then validate clearParameters() will clear them - */ - @Test() - public void test39() throws Exception { - brs.setInt(1, 1); - brs.setString(2, query); - assertTrue(brs.getParams().length == 2); - brs.clearParameters(); - assertTrue(brs.getParams().length == 0); - } - /* * Set the base parameters and validate that the value set is * the correct type and value */ @Test(dataProvider = "testBaseParameters") - public void test40(int pos, Object o) throws Exception { + public void baseRowSetTest0009(int pos, Object o) throws Exception { assertTrue(getParam(pos, o).getClass().isInstance(o)); assertTrue(o.equals(getParam(pos, o))); } @@ -563,7 +213,7 @@ public class BaseRowSetTests extends BaseTest { * the correct type */ @Test(dataProvider = "testAdvancedParameters") - public void test41(int pos, Object o) throws Exception { + public void baseRowSetTest0010(int pos, Object o) throws Exception { assertTrue(getParam(pos, o).getClass().isInstance(o)); } @@ -571,7 +221,8 @@ public class BaseRowSetTests extends BaseTest { * Validate setNull specifying the supported type values */ @Test(dataProvider = "jdbcTypes") - public void test42(Integer type) throws Exception { + public void baseRowSetTest0011(Integer type) throws Exception { + brs = new StubBaseRowSet(); brs.setNull(1, type); assertTrue(checkNullParam(1, type, null)); } @@ -581,7 +232,8 @@ public class BaseRowSetTests extends BaseTest { * typeName is set internally */ @Test(dataProvider = "jdbcTypes") - public void test43(Integer type) throws Exception { + public void baseRowSetTest0012(Integer type) throws Exception { + brs = new StubBaseRowSet(); brs.setNull(1, type, "SUPERHERO"); assertTrue(checkNullParam(1, type, "SUPERHERO")); } @@ -590,8 +242,10 @@ public class BaseRowSetTests extends BaseTest { * Validate that setDate sets the specified Calendar internally */ @Test() - public void test44() throws Exception { - brs.setDate(1, aDate, cal); + public void baseRowSetTest0013() throws Exception { + Calendar cal = Calendar.getInstance(); + brs = new StubBaseRowSet(); + brs.setDate(1, Date.valueOf(LocalDate.now()), cal); assertTrue(checkCalendarParam(1, cal)); } @@ -599,8 +253,10 @@ public class BaseRowSetTests extends BaseTest { * Validate that setTime sets the specified Calendar internally */ @Test() - public void test45() throws Exception { - brs.setTime(1, aTime, cal); + public void baseRowSetTest0014() throws Exception { + Calendar cal = Calendar.getInstance(); + brs = new StubBaseRowSet(); + brs.setTime(1, Time.valueOf(LocalTime.now()), cal); assertTrue(checkCalendarParam(1, cal)); } @@ -608,564 +264,23 @@ public class BaseRowSetTests extends BaseTest { * Validate that setTimestamp sets the specified Calendar internally */ @Test() - public void test46() throws Exception { - brs.setTimestamp(1, ts, cal); + public void baseRowSetTest0015() throws Exception { + Calendar cal = Calendar.getInstance(); + brs = new StubBaseRowSet(); + brs.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()), cal); assertTrue(checkCalendarParam(1, cal)); } - /* - * Validate that getURL() returns same value set by - * setURL() - */ - @Test() - public void test47() throws Exception { - brs.setUrl(url); - assertTrue(brs.getUrl().equals(url)); - } - /* * Validate that initParams() initializes the parameters */ - @Test() - public void test48() throws Exception { - brs.setInt(1, 1); - brs.initParams(); - assertTrue(brs.getParams().length == 0); + @Test(dataProvider = "rowSetType") + public void baseRowSetTest0016(StubBaseRowSet rs) throws Exception { + rs.setInt(1, 1); + rs.initParams(); + assertTrue(rs.getParams().length == 0); } - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test100() throws Exception { - brs1.setAsciiStream(1, is); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test101() throws Exception { - brs1.setAsciiStream("one", is); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test102() throws Exception { - brs1.setAsciiStream("one", is, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test103() throws Exception { - brs1.setBinaryStream(1, is); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test104() throws Exception { - brs1.setBinaryStream("one", is); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test105() throws Exception { - brs1.setBinaryStream("one", is, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test106() throws Exception { - brs1.setBigDecimal("one", BigDecimal.ONE); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test107() throws Exception { - brs1.setBlob(1, is); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test108() throws Exception { - brs1.setBlob("one", is); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test109() throws Exception { - brs1.setBlob("one", is, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test110() throws Exception { - brs1.setBlob("one", aBlob); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test111() throws Exception { - brs1.setBoolean("one", true); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test112() throws Exception { - byte b = 1; - brs1.setByte("one", b); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test113() throws Exception { - byte b = 1; - brs1.setBytes("one", bytes); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test114() throws Exception { - brs1.setCharacterStream("one", rdr, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test115() throws Exception { - brs1.setCharacterStream("one", rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test116() throws Exception { - brs1.setCharacterStream(1, rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test117() throws Exception { - brs1.setClob(1, rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test118() throws Exception { - brs1.setClob("one", rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test119() throws Exception { - brs1.setClob("one", rdr, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test120() throws Exception { - brs1.setClob("one", aClob); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test121() throws Exception { - brs1.setDate("one", aDate); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test122() throws Exception { - brs1.setDate("one", aDate, cal); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test123() throws Exception { - brs1.setTime("one", aTime); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test124() throws Exception { - brs1.setTime("one", aTime, cal); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test125() throws Exception { - brs1.setTimestamp("one", ts); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test126() throws Exception { - brs1.setTimestamp("one", ts, cal); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test127() throws Exception { - brs1.setDouble("one", 2.0d); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test128() throws Exception { - brs1.setFloat("one", 2.0f); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test129() throws Exception { - brs1.setInt("one", 21); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test130() throws Exception { - brs1.setLong("one", 21l); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test131() throws Exception { - brs1.setNCharacterStream("one", rdr, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test132() throws Exception { - brs1.setNCharacterStream("one", rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test133() throws Exception { - brs1.setNCharacterStream(1, rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test134() throws Exception { - brs1.setNCharacterStream(1, rdr, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test135() throws Exception { - brs1.setClob("one", rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test136() throws Exception { - brs1.setClob("one", rdr, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test137() throws Exception { - brs1.setNClob("one", new StubNClob()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test138() throws Exception { - brs1.setNClob(1, rdr); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test139() throws Exception { - brs1.setNClob(1, rdr, query.length()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test140() throws Exception { - brs1.setNClob(1, new StubNClob()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test141() throws Exception { - brs1.setNString(1, query); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test142() throws Exception { - brs1.setNull("one", Types.INTEGER); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test143() throws Exception { - brs1.setNull("one", Types.INTEGER, "my.type"); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test144() throws Exception { - brs1.setObject("one", query, Types.VARCHAR); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test145() throws Exception { - brs1.setObject("one", query, Types.VARCHAR, 0); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test146() throws Exception { - brs1.setObject("one", query); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test147() throws Exception { - brs1.setRowId("one", aRowid); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test148() throws Exception { - brs1.setSQLXML("one", new StubSQLXML()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test149() throws Exception { - brs1.setSQLXML(1, new StubSQLXML()); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test150() throws Exception { - brs1.setNString(1, query); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test151() throws Exception { - brs1.setNString("one", query); - } - - /* - * This method is currently not implemented in BaseRowSet and will - * throw a SQLFeatureNotSupportedException - */ - @Test(expectedExceptions = SQLFeatureNotSupportedException.class) - public void test152() throws Exception { - short val = 21; - brs1.setShort("one", val); - } - - /* - * DataProvider used to specify the value to set and check for - * methods using transaction isolation types - */ - @DataProvider(name = "isolationTypes") - private Object[][] isolationTypes() { - return new Object[][]{ - {Connection.TRANSACTION_NONE}, - {Connection.TRANSACTION_READ_COMMITTED}, - {Connection.TRANSACTION_READ_UNCOMMITTED}, - {Connection.TRANSACTION_REPEATABLE_READ}, - {Connection.TRANSACTION_SERIALIZABLE} - }; - } - - /* - * DataProvider used to specify the value to set and check for the - * methods for fetch direction - */ - @DataProvider(name = "fetchDirection") - private Object[][] fetchDirection() { - return new Object[][]{ - {ResultSet.FETCH_FORWARD}, - {ResultSet.FETCH_REVERSE}, - {ResultSet.FETCH_UNKNOWN} - }; - } - - /* - * DataProvider used to specify the value to set and check for the - * methods for Concurrency - */ - @DataProvider(name = "concurTypes") - private Object[][] concurTypes() { - return new Object[][]{ - {ResultSet.CONCUR_READ_ONLY}, - {ResultSet.CONCUR_UPDATABLE} - }; - } - - /* - * DataProvider used to specify the value to set and check for the - * methods for Cursor Scroll Type - */ - @DataProvider(name = "scrollTypes") - private Object[][] scrollTypes() { - return new Object[][]{ - {ResultSet.TYPE_FORWARD_ONLY}, - {ResultSet.TYPE_SCROLL_INSENSITIVE}, - {ResultSet.TYPE_SCROLL_SENSITIVE} - }; - } /* * DataProvider used to set parameters for basic types that are supported @@ -1177,29 +292,33 @@ public class BaseRowSetTests extends BaseTest { Short aShort = Short.MIN_VALUE; BigDecimal bd = BigDecimal.ONE; Double aDouble = Double.MAX_VALUE; + Date aDate = Date.valueOf(LocalDate.now()); + Time aTime = Time.valueOf(LocalTime.now()); + Timestamp aTimeStamp = Timestamp.valueOf(LocalDateTime.now()); + Calendar cal = Calendar.getInstance(); Boolean aBoolean = true; Float aFloat = 1.5f; Byte aByte = 1; + brs = new StubBaseRowSet(); - brs1.clearParameters(); - brs1.setInt(1, aInt); - brs1.setString(2, query); - brs1.setLong(3, aLong); - brs1.setBoolean(4, aBoolean); - brs1.setShort(5, aShort); - brs1.setDouble(6, aDouble); - brs1.setBigDecimal(7, bd); - brs1.setFloat(8, aFloat); - brs1.setByte(9, aByte); - brs1.setDate(10, aDate); - brs1.setTime(11, aTime); - brs1.setTimestamp(12, ts); - brs1.setDate(13, aDate, cal); - brs1.setTime(14, aTime, cal); - brs1.setTimestamp(15, ts); - brs1.setObject(16, query); - brs1.setObject(17, query, Types.CHAR); - brs1.setObject(18, query, Types.CHAR, 0); + brs.setInt(1, aInt); + brs.setString(2, query); + brs.setLong(3, aLong); + brs.setBoolean(4, aBoolean); + brs.setShort(5, aShort); + brs.setDouble(6, aDouble); + brs.setBigDecimal(7, bd); + brs.setFloat(8, aFloat); + brs.setByte(9, aByte); + brs.setDate(10, aDate); + brs.setTime(11, aTime); + brs.setTimestamp(12, aTimeStamp); + brs.setDate(13, aDate, cal); + brs.setTime(14, aTime, cal); + brs.setTimestamp(15, aTimeStamp); + brs.setObject(16, query); + brs.setObject(17, query, Types.CHAR); + brs.setObject(18, query, Types.CHAR, 0); return new Object[][]{ {1, aInt}, @@ -1213,10 +332,10 @@ public class BaseRowSetTests extends BaseTest { {9, aByte}, {10, aDate}, {11, aTime}, - {12, ts}, + {12, aTimeStamp}, {13, aDate}, {14, aTime}, - {15, ts}, + {15, aTimeStamp}, {16, query}, {17, query}, {18, query} @@ -1230,16 +349,23 @@ public class BaseRowSetTests extends BaseTest { @DataProvider(name = "testAdvancedParameters") private Object[][] testAdvancedParameters() throws SQLException { - brs1.clearParameters(); - brs1.setBytes(1, bytes); - brs1.setAsciiStream(2, is, query.length()); - brs1.setRef(3, aRef); - brs1.setArray(4, aArray); - brs1.setBlob(5, aBlob); - brs1.setClob(6, aClob); - brs1.setBinaryStream(7, is, query.length()); - brs1.setUnicodeStream(8, is, query.length()); - brs1.setCharacterStream(9, rdr, query.length()); + byte[] bytes = new byte[10]; + Ref aRef = new SerialRef(new StubRef("INTEGER", query)); + Array aArray = new SerialArray(new StubArray("INTEGER", new Object[1])); + Blob aBlob = new SerialBlob(new StubBlob()); + Clob aClob = new SerialClob(new StubClob()); + Reader rdr = new StringReader(query); + InputStream is = new StringBufferInputStream(query);; + brs = new StubBaseRowSet(); + brs.setBytes(1, bytes); + brs.setAsciiStream(2, is, query.length()); + brs.setRef(3, aRef); + brs.setArray(4, aArray); + brs.setBlob(5, aBlob); + brs.setClob(6, aClob); + brs.setBinaryStream(7, is, query.length()); + brs.setUnicodeStream(8, is, query.length()); + brs.setCharacterStream(9, rdr, query.length()); return new Object[][]{ {1, bytes}, @@ -1261,7 +387,7 @@ public class BaseRowSetTests extends BaseTest { */ @SuppressWarnings("unchecked") private T getParam(int pos, T o) throws SQLException { - Object[] params = brs1.getParams(); + Object[] params = brs.getParams(); if (params[pos - 1] instanceof Object[]) { Object[] param = (Object[]) params[pos - 1]; return (T) param[0]; diff --git a/jdk/test/javax/sql/testng/test/rowset/CommonRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/CommonRowSetTests.java new file mode 100644 index 00000000000..89492aefed5 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/CommonRowSetTests.java @@ -0,0 +1,1372 @@ +/* + * 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. + */ +package test.rowset; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.Date; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.sql.RowSet; +import javax.sql.rowset.BaseRowSet; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetFactory; +import javax.sql.rowset.RowSetMetaDataImpl; +import javax.sql.rowset.RowSetProvider; +import org.testng.Assert; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import util.BaseTest; +import util.StubBlob; +import util.StubClob; +import util.StubNClob; +import util.StubSQLXML; + +public abstract class CommonRowSetTests extends BaseTest { + + protected final String stubProvider = "util.StubSyncProvider"; + protected final String query = "SELECT * FROM SUPERHEROS"; + private final String url = "jdbc:derby://localhost:1527/myDB"; + private final String dsName = "jdbc/myDB"; + private final String user = "Bruce Wayne"; + private final String password = "The Dark Knight"; + protected final String COFFEE_HOUSES_TABLE = "COFFEE_HOUSES"; + protected final String COFFEES_TABLE = "COFFEES"; + protected final int COFFEE_HOUSES_ROWS = 14; + protected final int COFFEES_ROWS = 5; + protected final Object[] COFFEES_PRIMARY_KEYS = {1, 2, 3, 4, 5}; + protected final Object[] COFFEE_HOUSES_PRIMARY_KEYS = { + 10023, 33002, 10040, 32001, 10042, 10024, 10039, 10041, + 33005, 33010, 10035, 10037, 10034, 32004 + }; + + /* + * COFFEES_HOUSES Table column names + */ + protected final String[] COFFEE_HOUSES_COLUMN_NAMES = { + "STORE_ID", "CITY", "COFFEE", "MERCH", "TOTAL" + }; + + /* + * COFFEES Table column names + */ + protected final String[] COFFEES_COLUMN_NAMES = { + "COF_ID", "COF_NAME", "SUP_ID", "PRICE", "SALES", "TOTAL" + }; + + protected RowSetFactory rsf; + + public CommonRowSetTests() { + try { + rsf = RowSetProvider.newFactory(); + } catch (SQLException ex) { + Assert.fail(ex.getMessage()); + } + } + + // Create an instance of the RowSet we are using + protected abstract T newInstance() throws SQLException; + + //DataProvider to use for common tests + + /* + * DataProvider used to specify the value to set and check for the + * methods for fetch direction + */ + @DataProvider(name = "rowSetFetchDirection") + protected Object[][] rowSetFetchDirection() throws Exception { + RowSet rs = newInstance(); + return new Object[][]{ + {rs, ResultSet.FETCH_FORWARD}, + {rs, ResultSet.FETCH_REVERSE}, + {rs, ResultSet.FETCH_UNKNOWN} + }; + } + + /* + * DataProvider used to specify the value to set and check for the + * methods for Cursor Scroll Type + */ + @DataProvider(name = "rowSetScrollTypes") + protected Object[][] rowSetScrollTypes() throws Exception { + RowSet rs = newInstance(); + + return new Object[][]{ + {rs, ResultSet.TYPE_FORWARD_ONLY}, + {rs, ResultSet.TYPE_SCROLL_INSENSITIVE}, + {rs, ResultSet.TYPE_SCROLL_SENSITIVE} + }; + } + + /* + * DataProvider used to specify the value to set and check for + * methods using transaction isolation types + */ + @DataProvider(name = "rowSetIsolationTypes") + protected Object[][] rowSetIsolationTypes() throws Exception { + RowSet rs = newInstance(); + + return new Object[][]{ + {rs, Connection.TRANSACTION_NONE}, + {rs, Connection.TRANSACTION_READ_COMMITTED}, + {rs, Connection.TRANSACTION_READ_UNCOMMITTED}, + {rs, Connection.TRANSACTION_REPEATABLE_READ}, + {rs, Connection.TRANSACTION_SERIALIZABLE} + }; + } + + /* + * DataProvider used to specify the value to set and check for the + * methods for Concurrency + */ + @DataProvider(name = "rowSetConcurrencyTypes") + protected Object[][] rowSetConcurrencyTypes() throws Exception { + RowSet rs = newInstance(); + return new Object[][]{ + {rs, ResultSet.CONCUR_READ_ONLY}, + {rs, ResultSet.CONCUR_UPDATABLE} + }; + } + + /* + * DataProvider used to specify the value to set and check for + * methods using boolean values + */ + @DataProvider(name = "rowSetTrueFalse") + protected Object[][] rowSetTrueFalse() throws Exception { + RowSet rs = newInstance(); + return new Object[][]{ + {rs, true}, + {rs, false} + }; + } + /* + * DataProvider used to specify the type of RowSet to use. We also must + * initialize the RowSet + */ + @DataProvider(name = "rowSetType") + protected Object[][] rowSetType() throws Exception { + + RowSet rs = newInstance(); + return new Object[][]{ + {rs} + }; + } + + /* + * Initializes a RowSet containing the COFFEE_HOUSES data + */ + protected T createCoffeeHousesRowSet() throws SQLException { + T rs = (T) newInstance(); + initCoffeeHousesMetaData((CachedRowSet) rs); + createCoffeeHouseRows(rs); + // Make sure you are not on the insertRow + rs.moveToCurrentRow(); + return rs; + } + + /* + * Initializes a RowSet containing the COFFEE_HOUSES data + */ + protected T createCoffeesRowSet() throws SQLException { + T rs = (T) newInstance(); + initCoffeesMetaData((CachedRowSet) rs); + createCoffeesRows(rs); + // Make sure you are not on the insertRow + rs.moveToCurrentRow(); + return rs; + } + + /* + * Initializes the COFFEE_HOUSES metadata + */ + private void initCoffeeHousesMetaData(CachedRowSet crs) throws SQLException { + RowSetMetaDataImpl rsmd = new RowSetMetaDataImpl(); + crs.setType(RowSet.TYPE_SCROLL_INSENSITIVE); + + /* + * CREATE TABLE COFFEE_HOUSES( + * STORE_ID Integer NOT NULL, + * CITY VARCHAR(32), + * COFFEE INTEGER NOT NULL, + * MERCH INTEGER NOT NULL, + * TOTAL INTEGER NOT NULL, + * PRIMARY KEY (STORE_ID)) + */ + rsmd.setColumnCount(COFFEE_HOUSES_COLUMN_NAMES.length); + for(int i = 1; i <= COFFEE_HOUSES_COLUMN_NAMES.length; i++){ + rsmd.setColumnName(i, COFFEE_HOUSES_COLUMN_NAMES[i-1]); + rsmd.setColumnLabel(i, rsmd.getColumnName(i)); + } + + rsmd.setColumnType(1, Types.INTEGER); + rsmd.setColumnType(2, Types.VARCHAR); + rsmd.setColumnType(3, Types.INTEGER); + rsmd.setColumnType(4, Types.INTEGER); + rsmd.setColumnType(5, Types.INTEGER); + crs.setMetaData(rsmd); + crs.setTableName(COFFEE_HOUSES_TABLE); + + } + + /* + * Add rows to COFFEE_HOUSES table + */ + protected void createCoffeeHouseRows(RowSet rs) throws SQLException { + + // insert into COFFEE_HOUSES values(10023, 'Mendocino', 3450, 2005, 5455) + rs.moveToInsertRow(); + rs.updateInt(1, 10023); + rs.updateString(2, "Mendocino"); + rs.updateInt(3, 3450); + rs.updateInt(4, 2005); + rs.updateInt(5, 5455); + rs.insertRow(); + // insert into COFFEE_HOUSES values(33002, 'Seattle', 4699, 3109, 7808) + rs.moveToInsertRow(); + rs.updateInt(1, 33002); + rs.updateString(2, "Seattle"); + rs.updateInt(3, 4699); + rs.updateInt(4, 3109); + rs.updateInt(5, 7808); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10040, 'SF', 5386, 2841, 8227) + rs.moveToInsertRow(); + rs.updateInt(1, 10040); + rs.updateString(2, "SF"); + rs.updateInt(3, 5386); + rs.updateInt(4, 2841); + rs.updateInt(5, 8227); + rs.insertRow(); + // insert into COFFEE_HOUSES values(32001, 'Portland', 3147, 3579, 6726) + rs.moveToInsertRow(); + rs.updateInt(1, 32001); + rs.updateString(2, "Portland"); + rs.updateInt(3, 3147); + rs.updateInt(4, 3579); + rs.updateInt(5, 6726); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10042, 'SF', 2863, 1874, 4710) + rs.moveToInsertRow(); + rs.updateInt(1, 10042); + rs.updateString(2, "SF"); + rs.updateInt(3, 2863); + rs.updateInt(4, 1874); + rs.updateInt(5, 4710); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10024, 'Sacramento', 1987, 2341, 4328) + rs.moveToInsertRow(); + rs.updateInt(1, 10024); + rs.updateString(2, "Sacramento"); + rs.updateInt(3, 1987); + rs.updateInt(4, 2341); + rs.updateInt(5, 4328); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10039, 'Carmel', 2691, 1121, 3812) + rs.moveToInsertRow(); + rs.updateInt(1, 10039); + rs.updateString(2, "Carmel"); + rs.updateInt(3, 2691); + rs.updateInt(4, 1121); + rs.updateInt(5, 3812); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10041, 'LA', 1533, 1007, 2540) + rs.moveToInsertRow(); + rs.updateInt(1, 10041); + rs.updateString(2, "LA"); + rs.updateInt(3, 1533); + rs.updateInt(4, 1007); + rs.updateInt(5, 2540); + rs.insertRow(); + // insert into COFFEE_HOUSES values(33005, 'Olympia', 2733, 1550, 1550) + rs.moveToInsertRow(); + rs.updateInt(1, 33005); + rs.updateString(2, "Olympia"); + rs.updateInt(3, 2733); + rs.updateInt(4, 1550); + rs.updateInt(5, 1550); + rs.insertRow(); + // insert into COFFEE_HOUSES values(33010, 'Seattle', 3210, 2177, 5387) + rs.moveToInsertRow(); + rs.updateInt(1, 33010); + rs.updateString(2, "Seattle"); + rs.updateInt(3, 3210); + rs.updateInt(4, 2177); + rs.updateInt(5, 5387); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10035, 'SF', 1922, 1056, 2978) + rs.moveToInsertRow(); + rs.updateInt(1, 10035); + rs.updateString(2, "SF"); + rs.updateInt(3, 1922); + rs.updateInt(4, 1056); + rs.updateInt(5, 2978); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10037, 'LA', 2143, 1876, 4019) + rs.moveToInsertRow(); + rs.updateInt(1, 10037); + rs.updateString(2, "LA"); + rs.updateInt(3, 2143); + rs.updateInt(4, 1876); + rs.updateInt(5, 4019); + rs.insertRow(); + // insert into COFFEE_HOUSES values(10034, 'San_Jose', 1234, 1032, 2266) + rs.moveToInsertRow(); + rs.updateInt(1, 10034); + rs.updateString(2, "San Jose"); + rs.updateInt(3, 1234); + rs.updateInt(4, 1032); + rs.updateInt(5, 2266); + rs.insertRow(); + // insert into COFFEE_HOUSES values(32004, 'Eugene', 1356, 1112, 2468) + rs.moveToInsertRow(); + rs.updateInt(1, 32004); + rs.updateString(2, "Eugene"); + rs.updateInt(3, 1356); + rs.updateInt(4, 1112); + rs.updateInt(5, 2468); + rs.insertRow(); + rs.moveToCurrentRow(); + } + + /* + * Initializes the COFFEES metadata + */ + protected void initCoffeesMetaData(CachedRowSet crs) throws SQLException { + RowSetMetaDataImpl rsmd = new RowSetMetaDataImpl(); + crs.setType(RowSet.TYPE_SCROLL_INSENSITIVE); + + /* + * CREATE TABLE COFFEES ( + * COF_ID INTEGER NOT NULL, + * COF_NAME VARCHAR(32) NOT NULL, + * SUP_ID INTEGER NOT NULL, + * PRICE NUMBERIC(10,2 NOT NULL, + * SALES INTEGER NOT NULL, + * TOTAL INTEGER NOT NULL, + * PRIMARY KEY (COF_ID), + * FOREIGN KEY (SUP_ID) REFERENCES SUPPLIERS (SUP_ID) ) + */ + rsmd.setColumnCount(COFFEES_COLUMN_NAMES.length); + for(int i = 1; i <= COFFEES_COLUMN_NAMES.length; i++){ + rsmd.setColumnName(i, COFFEES_COLUMN_NAMES[i-1]); + rsmd.setColumnLabel(i, rsmd.getColumnName(i)); + } + + rsmd.setColumnType(1, Types.INTEGER); + rsmd.setColumnType(2, Types.VARCHAR); + rsmd.setColumnType(3, Types.INTEGER); + rsmd.setColumnType(4, Types.NUMERIC); + rsmd.setPrecision(4, 10); + rsmd.setScale(4, 2); + rsmd.setColumnType(5, Types.INTEGER); + rsmd.setColumnType(6, Types.INTEGER); + crs.setMetaData(rsmd); + crs.setTableName(COFFEES_TABLE); + + } + + /* + * Add rows to COFFEES table + */ + protected void createCoffeesRows(RowSet rs) throws SQLException { + + // insert into COFFEES values(1, 'Colombian', 101, 7.99, 0, 0) + rs.moveToInsertRow(); + rs.updateInt(1, 1); + rs.updateString(2, "Colombian"); + rs.updateInt(3, 101); + rs.updateBigDecimal(4, BigDecimal.valueOf(7.99)); + rs.updateInt(5, 0); + rs.updateInt(6, 0); + rs.insertRow(); + // insert into COFFEES values(2, 'French_Roast', 49, 8.99, 0, 0) + rs.moveToInsertRow(); + rs.updateInt(1, 2); + rs.updateString(2, "French_Roast"); + rs.updateInt(3, 49); + rs.updateBigDecimal(4, BigDecimal.valueOf(8.99)); + rs.updateInt(5, 0); + rs.updateInt(6, 0); + rs.insertRow(); + // insert into COFFEES values(3, 'Espresso', 150, 9.99, 0, 0) + rs.moveToInsertRow(); + rs.updateInt(1, 3); + rs.updateString(2, "Espresso"); + rs.updateInt(3, 150); + rs.updateBigDecimal(4, BigDecimal.valueOf(9.99)); + rs.updateInt(5, 0); + rs.updateInt(6, 0); + rs.insertRow(); + // insert into COFFEES values(4, 'Colombian_Decaf', 101, 8.99, 0, 0) + rs.moveToInsertRow(); + rs.updateInt(1, 4); + rs.updateString(2, "Colombian_Decaf"); + rs.updateInt(3, 101); + rs.updateBigDecimal(4, BigDecimal.valueOf(8.99)); + rs.updateInt(5, 0); + rs.updateInt(6, 0); + rs.insertRow(); + // insert into COFFEES values(5, 'French_Roast_Decaf', 049, 9.99, 0, 0) + rs.moveToInsertRow(); + rs.updateInt(1, 5); + rs.updateString(2, "French_Roast_Decaf"); + rs.updateInt(3, 49); + rs.updateBigDecimal(4, BigDecimal.valueOf(9.99)); + rs.updateInt(5, 0); + rs.updateInt(6, 0); + rs.insertRow(); + + } + + + /* + * Utility method to return the Primary Keys for a RowSet. The Primary + * keys are assumed to be in the first column of the RowSet + */ + protected Object[] getPrimaryKeys(ResultSet rs) throws SQLException { + List result = new ArrayList<>(); + if (rs == null) { + return null; + } + rs.beforeFirst(); + while (rs.next()) { + result.add(rs.getInt(1)); + } + return result.toArray(); + } + + /* + * Utility method to display the RowSet and will return the row count + * it found + */ + protected int displayResults(ResultSet rs) throws SQLException { + int rows = 0; + ResultSetMetaData rsmd = rs.getMetaData(); + int cols = rsmd.getColumnCount(); + if (rs != null) { + rs.beforeFirst(); + while (rs.next()) { + rows++; + + for (int i = 0; i < cols; i++) { + System.out.print(rs.getString(i + 1) + " "); + } + System.out.println(); + } + } + + return rows; + } + + + // Insert common tests here + + /* + * Validate that getCommand() returns null by default + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0000(RowSet rs) { + assertNull(rs.getCommand()); + } + + /* + * Validate that getCommand() returns command specified to setCommand + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0001(RowSet rs) throws Exception { + rs.setCommand(query); + assertTrue(rs.getCommand().equals(query)); + } + + + /* + * Validate that getCurrency() returns the correct default value + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0002(RowSet rs) throws Exception { + assertTrue(rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE); + } + + /* + * Validate that getCurrency() returns the correct value + * after a call to setConcurrency()) + */ + @Test(dataProvider = "rowSetConcurrencyTypes") + public void commonRowSetTest0003(RowSet rs, int concurType) throws Exception { + rs.setConcurrency(concurType); + assertTrue(rs.getConcurrency() == concurType); + } + + /* + * Validate that getCurrency() throws a SQLException for an invalid value + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonRowSetTest0004(RowSet rs) throws Exception { + rs.setConcurrency(ResultSet.CLOSE_CURSORS_AT_COMMIT); + } + + /* + * Validate that getDataSourceName() returns null by default + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0005(RowSet rs) throws Exception { + assertTrue(rs.getDataSourceName() == null); + } + + /* + * Validate that getDataSourceName() returns the value specified + * by setDataSourceName() and getUrl() returns null + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0006(RowSet rs) throws Exception { + rs.setUrl(url); + rs.setDataSourceName(dsName); + assertTrue(rs.getDataSourceName().equals(dsName)); + assertNull(rs.getUrl()); + } + + /* + * Validate that setDataSourceName() throws a SQLException for an empty + * String specified for the data source name + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonRowSetTest0007(RowSet rs) throws Exception { + String dsname = ""; + rs.setDataSourceName(dsname); + } + + /* + * Validate that getEscapeProcessing() returns false by default + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0008(RowSet rs) throws Exception { + assertTrue(rs.getEscapeProcessing()); + } + + /* + * Validate that getEscapeProcessing() returns value set by + * setEscapeProcessing() + */ + @Test(dataProvider = "rowSetTrueFalse") + public void commonRowSetTest0009(RowSet rs, boolean val) throws Exception { + rs.setEscapeProcessing(val); + assertTrue(rs.getEscapeProcessing() == val); + } + + /* + * Validate that getFetchDirection() returns the correct default value + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0010(RowSet rs) throws Exception { + assertTrue(rs.getFetchDirection() == ResultSet.FETCH_FORWARD); + } + + /* + * Validate that getFetchDirection() returns the value set by + * setFetchDirection() + */ + @Test(dataProvider = "rowSetFetchDirection") + public void commonRowSetTest0011(RowSet rs, int direction) throws Exception { + rs.setFetchDirection(direction); + assertTrue(rs.getFetchDirection() == direction); + } + + /* + * Validate that setFetchSize() throws a SQLException for an invalid value + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonRowSetTest0013(RowSet rs) throws Exception { + rs.setFetchSize(-1); + } + + /* + * Validate that setFetchSize() throws a SQLException for a + * value greater than getMaxRows() + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonRowSetTest0014(RowSet rs) throws Exception { + rs.setMaxRows(5); + rs.setFetchSize(rs.getMaxRows() + 1); + } + + /* + * Validate that getFetchSize() returns the correct value after + * setFetchSize() has been called + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0015(RowSet rs) throws Exception { + int maxRows = 150; + rs.setFetchSize(0); + assertTrue(rs.getFetchSize() == 0); + rs.setFetchSize(100); + assertTrue(rs.getFetchSize() == 100); + rs.setMaxRows(maxRows); + rs.setFetchSize(maxRows); + assertTrue(rs.getFetchSize() == maxRows); + } + + /* + * Validate that setMaxFieldSize() throws a SQLException for an invalid value + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonRowSetTest0016(RowSet rs) throws Exception { + rs.setMaxFieldSize(-1); + } + + /* + * Validate that getMaxFieldSize() returns the value set by + * setMaxFieldSize() + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0017(RowSet rs) throws Exception { + rs.setMaxFieldSize(0); + assertTrue(rs.getMaxFieldSize() == 0); + rs.setMaxFieldSize(100); + assertTrue(rs.getMaxFieldSize() == 100); + rs.setMaxFieldSize(50); + assertTrue(rs.getMaxFieldSize() == 50); + } + + /* + * Validate that isReadOnly() returns value set by + * setReadOnly() + */ + @Test(dataProvider = "rowSetTrueFalse") + public void commonRowSetTest0018(RowSet rs, boolean val) throws Exception { + rs.setReadOnly(val); + assertTrue(rs.isReadOnly() == val); + } + + /* + * Validate that getTransactionIsolation() returns value set by + * setTransactionIsolation() + */ + @Test(dataProvider = "rowSetIsolationTypes") + public void commonRowSetTest0019(RowSet rs, int val) throws Exception { + rs.setTransactionIsolation(val); + assertTrue(rs.getTransactionIsolation() == val); + } + + /* + * Validate that getType() returns value set by setType() + */ + @Test(dataProvider = "rowSetScrollTypes") + public void commonRowSetTest0020(RowSet rs, int val) throws Exception { + rs.setType(val); + assertTrue(rs.getType() == val); + } + + /* + * Validate that getEscapeProcessing() returns value set by + * setEscapeProcessing() + */ + @Test(dataProvider = "rowSetTrueFalse") + public void commonRowSetTest0021(BaseRowSet rs, boolean val) throws Exception { + rs.setShowDeleted(val); + assertTrue(rs.getShowDeleted() == val); + } + + /* + * Validate that getTypeMap() returns same value set by + * setTypeMap() + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0022(RowSet rs) throws Exception { + Map> map = new HashMap<>(); + map.put("SUPERHERO", Class.forName("util.SuperHero")); + rs.setTypeMap(map); + assertTrue(rs.getTypeMap().equals(map)); + } + + /* + * Validate that getUsername() returns same value set by + * setUsername() + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0023(RowSet rs) throws Exception { + rs.setUsername(user); + assertTrue(rs.getUsername().equals(user)); + } + + /* + * Validate that getPassword() returns same password set by + * setPassword() + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0024(RowSet rs) throws Exception { + rs.setPassword(password); + assertTrue(rs.getPassword().equals(password)); + } + + /* + * Validate that getQueryTimeout() returns same value set by + * setQueryTimeout() and that 0 is a valid timeout value + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0025(RowSet rs) throws Exception { + int timeout = 0; + rs.setQueryTimeout(timeout); + assertTrue(rs.getQueryTimeout() == timeout); + } + + /* + * Validate that getQueryTimeout() returns same value set by + * setQueryTimeout() and that 0 is a valid timeout value + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0026(RowSet rs) throws Exception { + int timeout = 10000; + rs.setQueryTimeout(timeout); + assertTrue(rs.getQueryTimeout() == timeout); + } + + /* + * Validate that setQueryTimeout() throws a SQLException for a timeout + * value < 0 + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonRowSetTest0027(RowSet rs) throws Exception { + rs.setQueryTimeout(-1); + } + + + /* + * Validate addRowSetListener does not throw an Exception when null is + * passed as the parameter + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0028(RowSet rs) throws Exception { + rs.addRowSetListener(null); + } + + /* + * Validate removeRowSetListener does not throw an Exception when null is + * passed as the parameter + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0029(RowSet rs) throws Exception { + rs.removeRowSetListener(null); + } + + /* + * Set two parameters and then validate clearParameters() will clear them + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0030(BaseRowSet rs) throws Exception { + rs.setInt(1, 1); + rs.setString(2, query); + assertTrue(rs.getParams().length == 2); + rs.clearParameters(); + assertTrue(rs.getParams().length == 0); + } + + /* + * Validate that getURL() returns same value set by + * setURL() + */ + @Test(dataProvider = "rowSetType") + public void commonRowSetTest0031(RowSet rs) throws Exception { + rs.setUrl(url); + assertTrue(rs.getUrl().equals(url)); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0100(RowSet rs) throws Exception { + InputStream is = null; + rs.setAsciiStream(1, is); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0101(RowSet rs) throws Exception { + InputStream is = null; + rs.setAsciiStream("one", is); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0102(RowSet rs) throws Exception { + InputStream is = null; + rs.setAsciiStream("one", is, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0103(RowSet rs) throws Exception { + InputStream is = null; + rs.setBinaryStream(1, is); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0104(RowSet rs) throws Exception { + InputStream is = null; + rs.setBinaryStream("one", is); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0105(RowSet rs) throws Exception { + InputStream is = null; + rs.setBinaryStream("one", is, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0106(RowSet rs) throws Exception { + rs.setBigDecimal("one", BigDecimal.ONE); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0107(RowSet rs) throws Exception { + InputStream is = null; + rs.setBlob(1, is); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0108(RowSet rs) throws Exception { + InputStream is = null; + rs.setBlob("one", is); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0109(RowSet rs) throws Exception { + InputStream is = null; + rs.setBlob("one", is, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0110(RowSet rs) throws Exception { + rs.setBlob("one", new StubBlob()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0111(RowSet rs) throws Exception { + rs.setBoolean("one", true); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0112(RowSet rs) throws Exception { + byte b = 1; + rs.setByte("one", b); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0113(RowSet rs) throws Exception { + byte b = 1; + rs.setBytes("one", new byte[10]); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0114(RowSet rs) throws Exception { + Reader rdr = null; + rs.setCharacterStream("one", rdr, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0115(RowSet rs) throws Exception { + Reader rdr = null; + rs.setCharacterStream("one", rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0116(RowSet rs) throws Exception { + Reader rdr = null; + rs.setCharacterStream(1, rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0117(RowSet rs) throws Exception { + Reader rdr = null; + rs.setClob(1, rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0118(RowSet rs) throws Exception { + Reader rdr = null; + rs.setClob("one", rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0119(RowSet rs) throws Exception { + Reader rdr = null; + rs.setClob("one", rdr, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0120(RowSet rs) throws Exception { + rs.setClob("one", new StubClob()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0121(RowSet rs) throws Exception { + rs.setDate("one", Date.valueOf(LocalDate.now())); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0122(RowSet rs) throws Exception { + rs.setDate("one", Date.valueOf(LocalDate.now()), + Calendar.getInstance()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0123(RowSet rs) throws Exception { + rs.setTime("one", Time.valueOf(LocalTime.now())); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0124(RowSet rs) throws Exception { + rs.setTime("one", Time.valueOf(LocalTime.now()), + Calendar.getInstance()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0125(RowSet rs) throws Exception { + rs.setTimestamp("one", Timestamp.valueOf(LocalDateTime.now())); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0126(RowSet rs) throws Exception { + rs.setTimestamp("one", Timestamp.valueOf(LocalDateTime.now()), + Calendar.getInstance()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0127(RowSet rs) throws Exception { + rs.setDouble("one", 2.0d); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0128(RowSet rs) throws Exception { + rs.setFloat("one", 2.0f); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0129(RowSet rs) throws Exception { + rs.setInt("one", 21); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0130(RowSet rs) throws Exception { + rs.setLong("one", 21l); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0131(RowSet rs) throws Exception { + Reader rdr = null; + rs.setNCharacterStream("one", rdr, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0132(RowSet rs) throws Exception { + Reader rdr = null; + rs.setNCharacterStream("one", rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0133(RowSet rs) throws Exception { + Reader rdr = null; + rs.setNCharacterStream(1, rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0134(RowSet rs) throws Exception { + Reader rdr = null; + rs.setNCharacterStream(1, rdr, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0135(RowSet rs) throws Exception { + Reader rdr = null; + rs.setClob("one", rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0136(RowSet rs) throws Exception { + Reader rdr = null; + rs.setClob("one", rdr, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0137(RowSet rs) throws Exception { + rs.setNClob("one", new StubNClob()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0138(RowSet rs) throws Exception { + Reader rdr = null; + rs.setNClob(1, rdr); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0139(RowSet rs) throws Exception { + Reader rdr = null; + rs.setNClob(1, rdr, query.length()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0140(RowSet rs) throws Exception { + rs.setNClob(1, new StubNClob()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0141(RowSet rs) throws Exception { + rs.setNString(1, query); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0142(RowSet rs) throws Exception { + rs.setNull("one", Types.INTEGER); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0143(RowSet rs) throws Exception { + rs.setNull("one", Types.INTEGER, "my.type"); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0144(RowSet rs) throws Exception { + rs.setObject("one", query, Types.VARCHAR); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0145(RowSet rs) throws Exception { + rs.setObject("one", query, Types.VARCHAR, 0); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0146(RowSet rs) throws Exception { + rs.setObject("one", query); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0147(RowSet rs) throws Exception { + RowId aRowid = null; + rs.setRowId("one", aRowid); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0148(RowSet rs) throws Exception { + rs.setSQLXML("one", new StubSQLXML()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0149(RowSet rs) throws Exception { + rs.setSQLXML(1, new StubSQLXML()); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0150(RowSet rs) throws Exception { + rs.setNString(1, query); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0151(RowSet rs) throws Exception { + rs.setNString("one", query); + } + + /* + * This method is currently not implemented in BaseRowSet and will + * throw a SQLFeatureNotSupportedException + */ + @Test(dataProvider = "rowSetType", + expectedExceptions = SQLFeatureNotSupportedException.class) + public void commonRowSetTest0152(RowSet rs) throws Exception { + short val = 21; + rs.setShort("one", val); + } + +} diff --git a/jdk/test/javax/sql/testng/test/rowset/cachedrowset/CachedRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/cachedrowset/CachedRowSetTests.java new file mode 100644 index 00000000000..1155a889187 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/cachedrowset/CachedRowSetTests.java @@ -0,0 +1,35 @@ +/* + * 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. + */ +package test.rowset.cachedrowset; + +import java.sql.SQLException; +import javax.sql.rowset.CachedRowSet; + +public class CachedRowSetTests extends CommonCachedRowSetTests { + + @Override + protected CachedRowSet newInstance() throws SQLException { + return rsf.createCachedRowSet(); + } + +} diff --git a/jdk/test/javax/sql/testng/test/rowset/cachedrowset/CommonCachedRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/cachedrowset/CommonCachedRowSetTests.java new file mode 100644 index 00000000000..7b04443e23f --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/cachedrowset/CommonCachedRowSetTests.java @@ -0,0 +1,1612 @@ +/* + * 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. + */ +package test.rowset.cachedrowset; + +import java.math.BigDecimal; +import java.sql.Array; +import java.sql.Date; +import java.sql.JDBCType; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.Collection; +import javax.sql.RowSet; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetMetaDataImpl; +import javax.sql.rowset.serial.SerialRef; +import javax.sql.rowset.spi.SyncFactory; +import javax.sql.rowset.spi.SyncProvider; +import javax.sql.rowset.spi.SyncProviderException; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import test.rowset.CommonRowSetTests; +import util.StubArray; +import util.StubRef; +import util.StubSyncProvider; +import util.TestRowSetListener; + +public abstract class CommonCachedRowSetTests extends CommonRowSetTests { + + /* + * DATATYPES Table column names + */ + private final String[] DATATYPES_COLUMN_NAMES = {"AINTEGER", "ACHAR", + "AVARCHAR", "ALONG", "ABOOLEAN", "ASHORT", "ADOUBLE", "ABIGDECIMAL", + "AREAL", "ABYTE", "ADATE", "ATIME", "ATIMESTAMP", "ABYTES", "ARRAY", + "AREF", "AFLOAT"}; + + /* + * Initializes a RowSet containing the DATAYPES data + */ + protected T createDataTypesRowSet() throws SQLException { + T rs = (T) newInstance(); + initDataTypesMetaData((CachedRowSet) rs); + createDataTypesRows(rs); + // Make sure you are not on the insertRow + rs.moveToCurrentRow(); + return rs; + } + + //DataProviders to use for common tests + + /* + * DataProvider that uses a RowSet with the COFFEE_HOUSES Table + */ + @DataProvider(name = "rowsetUsingCoffeeHouses") + protected Object[][] rowsetUsingCoffeeHouses() throws Exception { + RowSet rs = createCoffeeHousesRowSet(); + return new Object[][]{ + {rs} + }; + } + + /* + * DataProvider that uses a RowSet with the COFFEES Table + */ + @DataProvider(name = "rowsetUsingCoffees") + protected Object[][] rowsetUsingCoffees() throws Exception { + RowSet rs = createCoffeesRowSet(); + return new Object[][]{ + {rs} + }; + } + + /* + * DataProvider that uses a RowSet with the DATAYPES Table and + * used to validate the various supported data types + */ + @DataProvider(name = "rowsetUsingDataTypes") + protected Object[][] rowsetUsingDataTypes() throws Exception { + + CachedRowSet rs = createDataTypesRowSet(); + return new Object[][]{ + {rs, JDBCType.INTEGER}, + {rs, JDBCType.CHAR}, + {rs, JDBCType.VARCHAR}, + {rs, JDBCType.BIGINT}, + {rs, JDBCType.BOOLEAN}, + {rs, JDBCType.SMALLINT}, + {rs, JDBCType.DOUBLE}, + {rs, JDBCType.DECIMAL}, + {rs, JDBCType.REAL}, + {rs, JDBCType.TINYINT}, + {rs, JDBCType.DATE}, + {rs, JDBCType.TIME}, + {rs, JDBCType.TIMESTAMP}, + {rs, JDBCType.VARBINARY}, + {rs, JDBCType.ARRAY}, + {rs, JDBCType.REF}, + {rs, JDBCType.FLOAT} + }; + } + + /* + * Initializes the DATAYPES table metadata + */ + protected void initDataTypesMetaData(CachedRowSet crs) throws SQLException { + RowSetMetaDataImpl rsmd = new RowSetMetaDataImpl(); + crs.setType(RowSet.TYPE_SCROLL_INSENSITIVE); + + rsmd.setColumnCount(DATATYPES_COLUMN_NAMES.length); + + for (int i = 1; i <= DATATYPES_COLUMN_NAMES.length; i++) { + rsmd.setColumnName(i, DATATYPES_COLUMN_NAMES[i - 1]); + rsmd.setColumnLabel(i, rsmd.getColumnName(i)); + } + + rsmd.setColumnType(1, Types.INTEGER); + rsmd.setColumnType(2, Types.CHAR); + rsmd.setColumnType(3, Types.VARCHAR); + rsmd.setColumnType(4, Types.BIGINT); + rsmd.setColumnType(5, Types.BOOLEAN); + rsmd.setColumnType(6, Types.SMALLINT); + rsmd.setColumnType(7, Types.DOUBLE); + rsmd.setColumnType(8, Types.DECIMAL); + rsmd.setColumnType(9, Types.REAL); + rsmd.setColumnType(10, Types.TINYINT); + rsmd.setColumnType(11, Types.DATE); + rsmd.setColumnType(12, Types.TIME); + rsmd.setColumnType(13, Types.TIMESTAMP); + rsmd.setColumnType(14, Types.VARBINARY); + rsmd.setColumnType(15, Types.ARRAY); + rsmd.setColumnType(16, Types.REF); + rsmd.setColumnType(17, Types.FLOAT); + crs.setMetaData(rsmd); + + } + + /* + * Add rows to DATAYPES table + */ + protected void createDataTypesRows(RowSet crs) throws SQLException { + + Integer aInteger = 100; + String aChar = "Oswald Cobblepot"; + Long aLong = Long.MAX_VALUE; + Short aShort = Short.MAX_VALUE; + Double aDouble = Double.MAX_VALUE; + BigDecimal aBigDecimal = BigDecimal.ONE; + Boolean aBoolean = false; + Float aFloat = Float.MAX_VALUE; + Byte aByte = Byte.MAX_VALUE; + Date aDate = Date.valueOf(LocalDate.now()); + Time aTime = Time.valueOf(LocalTime.now()); + Timestamp aTimeStamp = Timestamp.valueOf(LocalDateTime.now()); + Array aArray = new StubArray("INTEGER", new Object[1]); + Ref aRef = new SerialRef(new StubRef("INTEGER", query)); + byte[] bytes = new byte[10]; + crs.moveToInsertRow(); + crs.updateInt(1, aInteger); + crs.updateString(2, aChar); + crs.updateString(3, aChar); + crs.updateLong(4, aLong); + crs.updateBoolean(5, aBoolean); + crs.updateShort(6, aShort); + crs.updateDouble(7, aDouble); + crs.updateBigDecimal(8, aBigDecimal); + crs.updateFloat(9, aFloat); + crs.updateByte(10, aByte); + crs.updateDate(11, aDate); + crs.updateTime(12, aTime); + crs.updateTimestamp(13, aTimeStamp); + crs.updateBytes(14, bytes); + crs.updateArray(15, aArray); + crs.updateRef(16, aRef); + crs.updateDouble(17, aDouble); + crs.insertRow(); + crs.moveToCurrentRow(); + + } + + /* + * Dermine if a Row exists in a ResultSet by its primary key + * If the parameter deleteRow is true, delete the row and validate + * the RowSet indicates it is deleted + */ + protected boolean findRowByPrimaryKey(RowSet rs, int id, int idPos, + boolean deleteRow) throws Exception { + boolean foundRow = false; + rs.beforeFirst(); + while (rs.next()) { + if (rs.getInt(idPos) == id) { + foundRow = true; + if (deleteRow) { + rs.deleteRow(); + // validate row is marked as deleted + assertTrue(rs.rowDeleted()); + } + break; + } + } + return foundRow; + } + + /* + * Wrapper method to find if a row exists within a RowSet by its primary key + */ + protected boolean findRowByPrimaryKey(RowSet rs, int id, int idPos) throws Exception { + return findRowByPrimaryKey(rs, id, idPos, false); + } + + /* + * Wrapper method to find if a row exists within a RowSet by its primary key + * and delete it + */ + protected boolean deleteRowByPrimaryKey(RowSet rs, int id, int idPos) throws Exception { + return findRowByPrimaryKey(rs, id, idPos, true); + } + + /* + * Utility method that compares two ResultSetMetaDataImpls for containing + * the same values + */ + private void compareMetaData(ResultSetMetaData rsmd, + ResultSetMetaData rsmd1) throws SQLException { + + assertEquals(rsmd1.getColumnCount(), rsmd.getColumnCount()); + int cols = rsmd.getColumnCount(); + for (int i = 1; i <= cols; i++) { + assertTrue(rsmd1.getCatalogName(i).equals(rsmd.getCatalogName(i))); + assertTrue(rsmd1.getColumnClassName(i).equals(rsmd.getColumnClassName(i))); + assertTrue(rsmd1.getColumnDisplaySize(i) == rsmd.getColumnDisplaySize(i)); + assertTrue(rsmd1.getColumnLabel(i).equals(rsmd.getColumnLabel(i))); + assertTrue(rsmd1.getColumnName(i).equals(rsmd.getColumnName(i))); + assertTrue(rsmd1.getColumnType(i) == rsmd.getColumnType(i)); + assertTrue(rsmd1.getPrecision(i) == rsmd.getPrecision(i)); + assertTrue(rsmd1.getScale(i) == rsmd.getScale(i)); + assertTrue(rsmd1.getSchemaName(i).equals(rsmd.getSchemaName(i))); + assertTrue(rsmd1.getTableName(i).equals(rsmd.getTableName(i))); + assertTrue(rsmd1.isAutoIncrement(i) == rsmd.isAutoIncrement(i)); + assertTrue(rsmd1.isCaseSensitive(i) == rsmd.isCaseSensitive(i)); + assertTrue(rsmd1.isCurrency(i) == rsmd.isCurrency(i)); + assertTrue(rsmd1.isDefinitelyWritable(i) == rsmd.isDefinitelyWritable(i)); + assertTrue(rsmd1.isNullable(i) == rsmd.isNullable(i)); + assertTrue(rsmd1.isReadOnly(i) == rsmd.isReadOnly(i)); + assertTrue(rsmd1.isSearchable(i) == rsmd.isSearchable(i)); + assertTrue(rsmd1.isSigned(i) == rsmd.isSigned(i)); + assertTrue(rsmd1.isWritable(i) == rsmd.isWritable(i)); + + } + } + + /* + * Utility method to compare two rowsets + */ + private void compareRowSets(CachedRowSet crs, CachedRowSet crs1) throws Exception { + + int rows = crs.size(); + assertTrue(rows == crs1.size()); + + ResultSetMetaData rsmd = crs.getMetaData(); + + compareMetaData(rsmd, crs1.getMetaData()); + int cols = rsmd.getColumnCount(); + + for (int row = 1; row <= rows; row++) { + crs.absolute((row)); + crs1.absolute(row); + for (int col = 1; col <= cols; col++) { + compareColumnValue(JDBCType.valueOf(rsmd.getColumnType(col)), + crs, crs1, col); + } + } + + } + + /* + * Utility method to compare two columns + */ + private void compareColumnValue(JDBCType type, ResultSet rs, ResultSet rs1, + int col) throws SQLException { + + switch (type) { + case INTEGER: + assertTrue(rs.getInt(col) == rs1.getInt(col)); + break; + case CHAR: + case VARCHAR: + assertTrue(rs.getString(col).equals(rs1.getString(col))); + break; + case BIGINT: + assertTrue(rs.getLong(col) == rs1.getLong(col)); + break; + case BOOLEAN: + assertTrue(rs.getBoolean(col) == rs1.getBoolean(col)); + break; + case SMALLINT: + assertTrue(rs.getShort(col) == rs1.getShort(col)); + break; + case DOUBLE: + case FLOAT: + assertTrue(rs.getDouble(col) == rs1.getDouble(col)); + break; + case DECIMAL: + assertTrue(rs.getBigDecimal(col).equals(rs1.getBigDecimal(col))); + break; + case REAL: + assertTrue(rs.getFloat(col) == rs1.getFloat(col)); + break; + case TINYINT: + assertTrue(rs.getByte(col) == rs1.getByte(col)); + break; + case DATE: + assertTrue(rs.getDate(col).equals(rs1.getDate(col))); + break; + case TIME: + assertTrue(rs.getTime(col).equals(rs1.getTime(col))); + break; + case TIMESTAMP: + assertTrue(rs.getTimestamp(col).equals(rs1.getTimestamp(col))); + break; + } + } + + /* + * Validate SyncProviderException is thrown when acceptChanges is called + * but there is not a way to make a connection to the datasource + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SyncProviderException.class) + public void commonCachedRowSetTest0000(CachedRowSet rs) throws Exception { + rs.acceptChanges(); + rs.close(); + } + + /* + * Validate SyncProviderException is thrown when acceptChanges is called + * when null is passed as the datasource + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SyncProviderException.class) + public void commonCachedRowSetTest0001(CachedRowSet rs) throws Exception { + rs.acceptChanges(null); + rs.close(); + } + + /* + * Validate that that RIOPtimsticProvider is the default SyncProvider + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0002(CachedRowSet rs) throws SQLException { + SyncProvider sp = rs.getSyncProvider(); + assertTrue(sp instanceof com.sun.rowset.providers.RIOptimisticProvider); + rs.close(); + } + + /* + * Validate that you can specify a SyncProvider + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0003(CachedRowSet rs) throws SQLException { + + // Register a provider and make sure it is avaiable + SyncFactory.registerProvider(stubProvider); + rs.setSyncProvider(stubProvider); + SyncProvider sp = rs.getSyncProvider(); + assertTrue(sp instanceof StubSyncProvider); + SyncFactory.unregisterProvider(stubProvider); + rs.close(); + } + + /* + * Create a RowSetListener and validate that notifyRowSetChanged is called + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0004(CachedRowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.release(); + assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); + rs.close(); + } + + /* + * Create a RowSetListener and validate that notifyRowSetChanged is called + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0005(CachedRowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.restoreOriginal(); + assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); + rs.close(); + } + + /* + * Create a RowSetListener and validate that notifyRowChanged is called + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0006(RowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.moveToInsertRow(); + rs.updateInt(1, 10024); + rs.updateString(2, "Sacramento"); + rs.updateInt(3, 1987); + rs.updateInt(4, 2341); + rs.updateInt(5, 4328); + rs.insertRow(); + assertTrue(rsl.isNotified(TestRowSetListener.ROW_CHANGED)); + rs.close(); + } + + /* + * Create a multiple RowSetListeners and validate that notifyRowChanged, + * notifiyMoved is called on all listners + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0007(RowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + TestRowSetListener rsl2 = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.addRowSetListener(rsl2); + rs.first(); + rs.updateInt(1, 1961); + rs.updateString(2, "Pittsburgh"); + rs.updateInt(3, 1987); + rs.updateInt(4, 2341); + rs.updateInt(5, 6689); + rs.updateRow(); + assertTrue(rsl.isNotified(TestRowSetListener.CURSOR_MOVED + | TestRowSetListener.ROW_CHANGED)); + assertTrue(rsl2.isNotified(TestRowSetListener.CURSOR_MOVED + | TestRowSetListener.ROW_CHANGED)); + rs.close(); + } + + /* + * Create a RowSetListener and validate that notifyRowChanged and + * notifyCursorMoved are called + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0008(CachedRowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + + rs.first(); + assertTrue(rsl.isNotified(TestRowSetListener.CURSOR_MOVED)); + rs.deleteRow(); + assertTrue( + rsl.isNotified(TestRowSetListener.ROW_CHANGED | TestRowSetListener.CURSOR_MOVED)); + rsl.resetFlag(); + rs.setShowDeleted(true); + rs.undoDelete(); + assertTrue(rsl.isNotified(TestRowSetListener.ROW_CHANGED)); + rs.close(); + } + + /* + * Create a RowSetListener and validate that notifyCursorMoved is called + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0009(RowSet rs) throws Exception { + TestRowSetListener rsl = new TestRowSetListener(); + rs.addRowSetListener(rsl); + rs.beforeFirst(); + assertTrue(rsl.isNotified(TestRowSetListener.CURSOR_MOVED)); + rs.close(); + } + + /* + * Validate that getTableName() returns the proper values + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0010(CachedRowSet rs) throws Exception { + assertNull(rs.getTableName()); + rs.setTableName(COFFEE_HOUSES_TABLE); + assertTrue(rs.getTableName().equals(COFFEE_HOUSES_TABLE)); + rs.close(); + } + + /* + * Validate that getKeyColumns() returns the proper values + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0011(CachedRowSet rs) throws Exception { + int[] pkeys = {1, 3}; + assertNull(rs.getKeyColumns()); + rs.setKeyColumns(pkeys); + assertEquals(rs.getKeyColumns(), pkeys); + rs.close(); + } + + /* + * Validate that setMatchColumn throws a SQLException if the column + * index specified is out of range + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0012(CachedRowSet rs) throws Exception { + rs.setMatchColumn(-1); + rs.close(); + } + + /* + * Validate that setMatchColumn throws a SQLException if the column + * index specified is out of range + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0013(CachedRowSet rs) throws Exception { + int[] cols = {1, -1}; + rs.setMatchColumn(cols); + rs.close(); + } + + /* + * Validate that setMatchColumn throws a SQLException if the column + * index specified is out of range + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0014(CachedRowSet rs) throws Exception { + rs.setMatchColumn((String) null); + rs.close(); + } + + /* + * Validate that setMatchColumn throws a SQLException if the column + * index specified is out of range + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0015(CachedRowSet rs) throws Exception { + String[] cols = {"ID", null}; + rs.setMatchColumn(cols); + } + + /* + * Validate that getMatchColumn returns the same value specified by + * setMatchColumn + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", enabled = false) + public void commonCachedRowSetTest0016(CachedRowSet rs) throws Exception { + int[] expectedCols = {1}; + String[] expectedColNames = {"ID"}; + rs.setMatchColumn(1); + int[] actualCols = rs.getMatchColumnIndexes(); + String[] actualColNames = rs.getMatchColumnNames(); + for (int i = 0; i < actualCols.length; i++) { + System.out.println(actualCols[i]); + } + assertEquals(actualCols, expectedCols); + assertEquals(actualColNames, expectedColNames); + rs.close(); + } + + /* + * Validate that getMatchColumn returns the same value specified by + * setMatchColumn + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", enabled = false) + public void commonCachedRowSetTest0017(CachedRowSet rs) throws Exception { + int[] expectedCols = {1}; + String[] expectedColNames = {"ID"}; + rs.setMatchColumn(expectedColNames[0]); + int[] actualCols = rs.getMatchColumnIndexes(); + String[] actualColNames = rs.getMatchColumnNames(); + assertEquals(actualCols, expectedCols); + assertEquals(actualColNames, expectedColNames); + rs.close(); + } + + /* + * Validate that getMatchColumn returns the same valid value specified by + * setMatchColumn + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", enabled = false) + public void commonCachedRowSetTest0018(CachedRowSet rs) throws Exception { + int[] expectedCols = {1, 3}; + String[] expectedColNames = {"COF_ID", "SUP_ID"}; + rs.setMatchColumn(expectedCols); + int[] actualCols = rs.getMatchColumnIndexes(); + String[] actualColNames = rs.getMatchColumnNames(); + assertEquals(actualCols, expectedCols); + assertEquals(actualColNames, expectedColNames); + assertEquals(actualCols, expectedCols); + rs.close(); + } + + /* + * Validate that getMatchColumn returns the same valid value specified by + * setMatchColumn + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", enabled = false) + public void commonCachedRowSetTest0019(CachedRowSet rs) throws Exception { + int[] expectedCols = {1, 3}; + String[] expectedColNames = {"COF_ID", "SUP_ID"}; + rs.setMatchColumn(expectedColNames); + int[] actualCols = rs.getMatchColumnIndexes(); + String[] actualColNames = rs.getMatchColumnNames(); + assertEquals(actualCols, expectedCols); + assertEquals(actualColNames, expectedColNames); + rs.close(); + } + + /* + * Validate that getMatchColumnIndexes throws a SQLException if + * unsetMatchColumn has been called + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0020(CachedRowSet rs) throws Exception { + rs.setMatchColumn(1); + int[] actualCols = rs.getMatchColumnIndexes(); + assertTrue(actualCols != null); + rs.unsetMatchColumn(1); + actualCols = rs.getMatchColumnIndexes(); + rs.close(); + } + + /* + * Validate that getMatchColumnNames throws a SQLException if + * unsetMatchColumn has been called + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0021(CachedRowSet rs) throws Exception { + String matchColumn = "ID"; + rs.setMatchColumn(matchColumn); + String[] actualColNames = rs.getMatchColumnNames(); + assertTrue(actualColNames != null); + rs.unsetMatchColumn(matchColumn); + actualColNames = rs.getMatchColumnNames(); + rs.close(); + } + + /* + * Validate that getMatchColumnIndexes throws a SQLException if + * unsetMatchColumn has been called + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0022(CachedRowSet rs) throws Exception { + int[] expectedCols = {1, 3}; + rs.setMatchColumn(expectedCols); + int[] actualCols = rs.getMatchColumnIndexes(); + assertTrue(actualCols != null); + rs.unsetMatchColumn(expectedCols); + actualCols = rs.getMatchColumnIndexes(); + rs.close(); + } + + /* + * Validate that getMatchColumnNames throws a SQLException if + * unsetMatchColumn has been called + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0023(CachedRowSet rs) throws Exception { + String[] expectedColNames = {"COF_ID", "SUP_ID"}; + rs.setMatchColumn(expectedColNames); + String[] actualColNames = rs.getMatchColumnNames(); + assertTrue(actualColNames != null); + rs.unsetMatchColumn(expectedColNames); + actualColNames = rs.getMatchColumnNames(); + rs.close(); + } + + /* + * Validate size() returns the correct number of rows + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0024(CachedRowSet rs) throws Exception { + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + rs.close(); + } + + /* + * Validate that the correct rows are returned comparing the primary + * keys + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0025(RowSet rs) throws SQLException { + assertEquals(getPrimaryKeys(rs), COFFEE_HOUSES_PRIMARY_KEYS); + rs.close(); + } + + /* + * Delete a row within the RowSet using its primary key + * Validate the visibility of the row depending on the value of + * setShowdelete + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0026(CachedRowSet rs) throws Exception { + Object[] afterDelete = { + 10023, 33002, 10040, 32001, 10042, 10024, 10039, 10041, + 33005, 33010, 10037, 10034, 32004 + }; + int rowToDelete = 10035; + // All rows should be found + assertEquals(getPrimaryKeys(rs), COFFEE_HOUSES_PRIMARY_KEYS); + // Delete the row + assertTrue(deleteRowByPrimaryKey(rs, rowToDelete, 1)); + // With setShowDeleted(false) which is the default, + // the deleted row should not be visible + assertFalse(findRowByPrimaryKey(rs, rowToDelete, 1)); + assertEquals(getPrimaryKeys(rs), afterDelete); + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + // With setShowDeleted(true), the deleted row should be visible + rs.setShowDeleted(true); + assertTrue(findRowByPrimaryKey(rs, rowToDelete, 1)); + rs.close(); + } + + /* + * Validate that there is no page size by default + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0027(CachedRowSet rs) throws Exception { + assertTrue(rs.getPageSize() == 0); + rs.close(); + } + + /* + * Validate the value you set via setPageSize is returned by getPageSize + * then reset to having no limit + */ + @Test(dataProvider = "rowSetType") + public void commonCachedRowSetTest0028(CachedRowSet rs) throws Exception { + int rows = 100; + rs.setPageSize(rows); + assertTrue(rows == rs.getPageSize()); + rs.setPageSize(0); + assertTrue(rs.getPageSize() == 0); + rs.close(); + } + + /* + * Validate SQLException is thrown when an invalid value is specified + * for setPageSize + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0029(CachedRowSet rs) throws Exception { + rs.setPageSize(-1); + rs.close(); + } + + /* + * Validate SQLException is thrown when nextPage is called without a + * call to populate or execute + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0030(CachedRowSet rs) throws Exception { + rs.nextPage(); + rs.close(); + } + + /* + * Validate SQLException is thrown when previousPage is called without a + * call to populate or execute + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0031(CachedRowSet rs) throws Exception { + rs.previousPage(); + rs.close(); + } + + + /* + * Validate SQLException is thrown when execute is called + * but there is not a way to make a connection to the datasource + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0032(CachedRowSet rs) throws Exception { + rs.execute(null); + rs.close(); + } + + /* + * Validate SQLException is thrown when execute is called + * but there is not a way to make a connection to the datasource + */ + @Test(dataProvider = "rowSetType", expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0033(CachedRowSet rs) throws Exception { + rs.execute(); + rs.close(); + } + + /* + * Validate that toCollection() returns the proper values + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0034(CachedRowSet rs) throws Exception { + Object[] cities = {"Mendocino", "Seattle", "SF", "Portland", "SF", + "Sacramento", "Carmel", "LA", "Olympia", "Seattle", "SF", + "LA", "San Jose", "Eugene"}; + rs.beforeFirst(); + assertEquals(rs.toCollection(2).toArray(), cities); + assertEquals(rs.toCollection("CITY").toArray(), cities); + rs.close(); + } + + /* + * Validate that toCollection() returns the proper values + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0035(CachedRowSet rs) throws Exception { + Collection col = rs.toCollection(); + assertTrue(rs.size() == col.size()); + assertTrue(rs.toCollection().containsAll(col) + && col.containsAll(rs.toCollection())); + try ( // Validate that False is returned when compared to a different RowSet; + CachedRowSet crs1 = createCoffeesRowSet()) { + assertFalse(crs1.toCollection().containsAll(col) + && col.containsAll(crs1.toCollection())); + } + rs.close(); + + } + + /* + * Validate that createCopy() returns the proper values + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0036(CachedRowSet rs) throws Exception { + try (CachedRowSet crs1 = rs.createCopy()) { + compareRowSets(rs, crs1); + } + rs.close(); + } + + /* + * Validate that createCopySchema() returns the proper values + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0037(CachedRowSet rs) throws Exception { + try (CachedRowSet crs1 = rs.createCopySchema()) { + assertTrue(crs1.size() == 0); + compareMetaData(crs1.getMetaData(), rs.getMetaData()); + } + rs.close(); + } + + /* + * Validate that createCopyNoConstraints() returns the proper values + * and getMatchColumnIndexes should throw a SQLException. This test + * specifies setMatchColumn(int) + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0038(CachedRowSet rs) throws Exception { + rs.setMatchColumn(1); + try (CachedRowSet crs1 = rs.createCopyNoConstraints()) { + assertTrue(crs1.size() == COFFEE_HOUSES_ROWS); + compareRowSets(rs, crs1); + boolean recievedSQE = false; + try { + int[] indexes = crs1.getMatchColumnIndexes(); + } catch (SQLException e) { + recievedSQE = true; + } + assertTrue(recievedSQE); + recievedSQE = false; + try { + String[] colNames = crs1.getMatchColumnNames(); + } catch (SQLException e) { + recievedSQE = true; + } + assertTrue(recievedSQE); + } + rs.close(); + } + + /* + * Validate that createCopyNoConstraints() returns the proper values + * and getMatchColumnIndexes should throw a SQLException. This test + * specifies setMatchColumn(String) + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0039(CachedRowSet rs) throws Exception { + rs.setMatchColumn("ID"); + try (CachedRowSet crs1 = rs.createCopyNoConstraints()) { + assertTrue(crs1.size() == COFFEE_HOUSES_ROWS); + compareRowSets(rs, crs1); + boolean recievedSQE = false; + try { + int[] indexes = crs1.getMatchColumnIndexes(); + } catch (SQLException e) { + recievedSQE = true; + } + assertTrue(recievedSQE); + recievedSQE = false; + try { + String[] colNames = crs1.getMatchColumnNames(); + } catch (SQLException e) { + recievedSQE = true; + } + assertTrue(recievedSQE); + } + rs.close(); + } + + /* + * Validate that columnUpdated works with the various datatypes specifying + * the column index + */ + @Test(dataProvider = "rowsetUsingDataTypes") + public void commonCachedRowSetTest0040(CachedRowSet rs, JDBCType type) throws Exception { + rs.beforeFirst(); + assertTrue(rs.next()); + switch (type) { + case INTEGER: + assertFalse(rs.columnUpdated(1)); + rs.updateInt(1, Integer.MIN_VALUE); + assertTrue(rs.columnUpdated(1)); + break; + case CHAR: + assertFalse(rs.columnUpdated(2)); + rs.updateString(2, "foo"); + assertTrue(rs.columnUpdated(2)); + break; + case VARCHAR: + assertFalse(rs.columnUpdated(3)); + rs.updateString(3, "foo"); + assertTrue(rs.columnUpdated(3)); + break; + case BIGINT: + assertFalse(rs.columnUpdated(4)); + rs.updateLong(4, Long.MIN_VALUE); + assertTrue(rs.columnUpdated(4)); + break; + case BOOLEAN: + assertFalse(rs.columnUpdated(5)); + rs.updateBoolean(5, false); + assertTrue(rs.columnUpdated(5)); + break; + case SMALLINT: + assertFalse(rs.columnUpdated(6)); + rs.updateShort(6, Short.MIN_VALUE); + assertTrue(rs.columnUpdated(6)); + break; + case DOUBLE: + assertFalse(rs.columnUpdated(7)); + rs.updateDouble(7, Double.MIN_VALUE); + assertTrue(rs.columnUpdated(7)); + break; + case DECIMAL: + assertFalse(rs.columnUpdated(8)); + rs.updateBigDecimal(8, BigDecimal.TEN); + assertTrue(rs.columnUpdated(8)); + break; + case REAL: + assertFalse(rs.columnUpdated(9)); + rs.updateFloat(9, Float.MIN_VALUE); + assertTrue(rs.columnUpdated(9)); + break; + case TINYINT: + assertFalse(rs.columnUpdated(10)); + rs.updateByte(10, Byte.MIN_VALUE); + assertTrue(rs.columnUpdated(10)); + break; + case DATE: + assertFalse(rs.columnUpdated(11)); + rs.updateDate(11, Date.valueOf(LocalDate.now())); + assertTrue(rs.columnUpdated(11)); + break; + case TIME: + assertFalse(rs.columnUpdated(12)); + rs.updateTime(12, Time.valueOf(LocalTime.now())); + assertTrue(rs.columnUpdated(12)); + break; + case TIMESTAMP: + assertFalse(rs.columnUpdated(13)); + rs.updateTimestamp(13, Timestamp.valueOf(LocalDateTime.now())); + assertTrue(rs.columnUpdated(13)); + break; + case VARBINARY: + assertFalse(rs.columnUpdated(14)); + rs.updateBytes(14, new byte[1]); + assertTrue(rs.columnUpdated(14)); + break; + case ARRAY: + assertFalse(rs.columnUpdated(15)); + rs.updateArray(15, new StubArray("VARCHAR", new Object[10])); + assertTrue(rs.columnUpdated(15)); + break; + case REF: + assertFalse(rs.columnUpdated(16)); + rs.updateRef(16, new StubRef("INTEGER", query)); + assertTrue(rs.columnUpdated(16)); + break; + case FLOAT: + assertFalse(rs.columnUpdated(17)); + rs.updateDouble(17, Double.MIN_NORMAL); + assertTrue(rs.columnUpdated(17)); + } + + } + + /* + * Validate that columnUpdated works with the various datatypes specifying + * the column name + */ + @Test(dataProvider = "rowsetUsingDataTypes") + public void commonCachedRowSetTest0041(CachedRowSet rs, JDBCType type) throws Exception { + rs.beforeFirst(); + assertTrue(rs.next()); + switch (type) { + case INTEGER: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[0])); + rs.updateInt(DATATYPES_COLUMN_NAMES[0], Integer.MIN_VALUE); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[0])); + break; + case CHAR: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[1])); + rs.updateString(DATATYPES_COLUMN_NAMES[1], "foo"); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[1])); + break; + case VARCHAR: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[2])); + rs.updateString(DATATYPES_COLUMN_NAMES[2], "foo"); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[2])); + break; + case BIGINT: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[3])); + rs.updateLong(DATATYPES_COLUMN_NAMES[3], Long.MIN_VALUE); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[3])); + break; + case BOOLEAN: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[4])); + rs.updateBoolean(DATATYPES_COLUMN_NAMES[4], false); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[4])); + break; + case SMALLINT: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[5])); + rs.updateShort(DATATYPES_COLUMN_NAMES[5], Short.MIN_VALUE); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[5])); + break; + case DOUBLE: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[6])); + rs.updateDouble(DATATYPES_COLUMN_NAMES[6], Double.MIN_VALUE); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[6])); + break; + case DECIMAL: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[7])); + rs.updateBigDecimal(DATATYPES_COLUMN_NAMES[7], BigDecimal.TEN); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[7])); + break; + case REAL: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[8])); + rs.updateFloat(DATATYPES_COLUMN_NAMES[8], Float.MIN_VALUE); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[8])); + break; + case TINYINT: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[9])); + rs.updateByte(DATATYPES_COLUMN_NAMES[9], Byte.MIN_VALUE); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[9])); + break; + case DATE: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[10])); + rs.updateDate(DATATYPES_COLUMN_NAMES[10], Date.valueOf(LocalDate.now())); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[10])); + break; + case TIME: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[11])); + rs.updateTime(DATATYPES_COLUMN_NAMES[11], Time.valueOf(LocalTime.now())); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[11])); + break; + case TIMESTAMP: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[12])); + rs.updateTimestamp(DATATYPES_COLUMN_NAMES[12], Timestamp.valueOf(LocalDateTime.now())); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[12])); + break; + case VARBINARY: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[13])); + rs.updateBytes(DATATYPES_COLUMN_NAMES[13], new byte[1]); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[13])); + break; + case ARRAY: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[14])); + rs.updateArray(DATATYPES_COLUMN_NAMES[14], new StubArray("VARCHAR", new Object[10])); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[14])); + break; + case REF: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[15])); + rs.updateRef(DATATYPES_COLUMN_NAMES[15], new StubRef("INTEGER", query)); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[15])); + break; + case FLOAT: + assertFalse(rs.columnUpdated(DATATYPES_COLUMN_NAMES[16])); + rs.updateDouble(DATATYPES_COLUMN_NAMES[16], Double.MIN_NORMAL); + assertTrue(rs.columnUpdated(DATATYPES_COLUMN_NAMES[16])); + break; + } + + } + + /* + * Validate isBeforeFirst(), isFirst() and first() return the correct + * results + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0042(RowSet rs) throws Exception { + assertFalse(rs.isBeforeFirst()); + assertFalse(rs.isFirst()); + rs.beforeFirst(); + assertTrue(rs.isBeforeFirst()); + assertFalse(rs.isFirst()); + rs.next(); + assertFalse(rs.isBeforeFirst()); + assertTrue(rs.isFirst()); + rs.next(); + assertFalse(rs.isBeforeFirst()); + assertFalse(rs.isFirst()); + rs.first(); + assertFalse(rs.isBeforeFirst()); + assertTrue(rs.isFirst()); + rs.close(); + } + + /* + * Validate isAfterLast(), isLast() and last() return the correct + * results + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0043(RowSet rs) throws Exception { + assertFalse(rs.isAfterLast()); + assertFalse(rs.isLast()); + rs.afterLast(); + assertTrue(rs.isAfterLast()); + assertFalse(rs.isLast()); + rs.previous(); + assertFalse(rs.isAfterLast()); + assertTrue(rs.isLast()); + rs.previous(); + assertFalse(rs.isAfterLast()); + assertFalse(rs.isLast()); + rs.last(); + assertFalse(rs.isAfterLast()); + assertTrue(rs.isLast()); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoDelete is called on the + * insertRow + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0044(CachedRowSet rs) throws Exception { + rs.insertRow(); + rs.undoDelete(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoDelete is called when + * cursor is before the first row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0045(CachedRowSet rs) throws Exception { + rs.setShowDeleted(true); + rs.beforeFirst(); + rs.undoDelete(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoDelete is called when + * cursor is after the last row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0046(CachedRowSet rs) throws Exception { + rs.setShowDeleted(true); + rs.afterLast(); + rs.undoDelete(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoUpdate is called on the + * insertRow + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0047(CachedRowSet rs) throws Exception { + rs.insertRow(); + rs.undoUpdate(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoUpdate is called when + * cursor is before the first row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0048(CachedRowSet rs) throws Exception { + rs.setShowDeleted(true); + rs.beforeFirst(); + rs.undoUpdate(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoUpdate is called when + * cursor is after the last row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0049(CachedRowSet rs) throws Exception { + rs.setShowDeleted(true); + rs.afterLast(); + rs.undoUpdate(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoInsert is called on the + * insertRow + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0050(CachedRowSet rs) throws Exception { + rs.insertRow(); + rs.undoInsert(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoInsert is called when + * cursor is before the first row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0051(CachedRowSet rs) throws Exception { + rs.setShowDeleted(true); + rs.beforeFirst(); + rs.undoInsert(); + rs.close(); + } + + /* + * Validate a SQLException is thrown when undoInsert is called when + * cursor is after the last row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses", + expectedExceptions = SQLException.class) + public void commonCachedRowSetTest0052(CachedRowSet rs) throws Exception { + rs.setShowDeleted(true); + rs.afterLast(); + rs.undoInsert(); + rs.close(); + } + + /* + * Insert a row, then call undoInsert to roll back the insert and validate + * the row is not there + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0053(CachedRowSet rs) throws Exception { + int rowToInsert = 1961; + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + // Add new row + rs.moveToInsertRow(); + rs.updateInt(1, rowToInsert); + rs.updateString(2, "GOTHAM"); + rs.updateInt(3, 3450); + rs.updateInt(4, 2005); + rs.updateInt(5, 5455); + rs.insertRow(); + rs.moveToCurrentRow(); + // check that the number of rows has increased + assertTrue(rs.size() == COFFEE_HOUSES_ROWS + 1); + assertTrue(findRowByPrimaryKey(rs, rowToInsert, 1)); + rs.undoInsert(); + // Check to make sure the row is no longer there + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + assertFalse(findRowByPrimaryKey(rs, rowToInsert, 1)); + rs.close(); + } + + /* + * Insert a row, delete the row and then call undoDelete to make sure it + * is comes back + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0054(CachedRowSet rs) throws Exception { + int rowToDelete = 1961; + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + // Add new row + rs.moveToInsertRow(); + rs.updateInt(1, rowToDelete); + rs.updateString(2, "GOTHAM"); + rs.updateInt(3, 3450); + rs.updateInt(4, 2005); + rs.updateInt(5, 5455); + rs.insertRow(); + rs.moveToCurrentRow(); + // check that the number of rows has increased + assertTrue(rs.size() == COFFEE_HOUSES_ROWS + 1); + assertTrue(findRowByPrimaryKey(rs, rowToDelete, 1)); + rs.absolute(COFFEE_HOUSES_ROWS + 1); + rs.deleteRow(); + // Check to make sure the row is no longer there + //assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + assertFalse(findRowByPrimaryKey(rs, rowToDelete, 1)); + rs.setShowDeleted(true); + rs.absolute(COFFEE_HOUSES_ROWS + 1); + rs.undoDelete(); + // check that the row is back + assertTrue(rs.size() == COFFEE_HOUSES_ROWS + 1); + assertTrue(findRowByPrimaryKey(rs, rowToDelete, 1)); + rs.close(); + } + + /* + * Insert a row, modify a field and then call undoUpdate to revert the + * insert + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0055(CachedRowSet rs) throws Exception { + int rowToInsert = 1961; + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + // Add new row + rs.moveToInsertRow(); + rs.updateInt(1, rowToInsert); + rs.updateString(2, "GOTHAM"); + rs.updateInt(3, 3450); + rs.updateInt(4, 2005); + rs.updateInt(5, 5455); + rs.insertRow(); + rs.moveToCurrentRow(); + // check that the number of rows has increased + assertTrue(rs.size() == COFFEE_HOUSES_ROWS + 1); + assertTrue(findRowByPrimaryKey(rs, rowToInsert, 1)); + rs.absolute(COFFEE_HOUSES_ROWS + 1); + // Save off the original column values + String f2 = rs.getString(2); + int f3 = rs.getInt(3); + rs.updateString(2, "SMALLVILLE"); + rs.updateInt(3, 500); + // Validate the columns have been updated + assertTrue(rs.columnUpdated(2)); + assertTrue(rs.columnUpdated(3)); + // Undo the update and validate it has taken place + rs.absolute(COFFEE_HOUSES_ROWS + 1); + rs.undoUpdate(); + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + assertFalse(findRowByPrimaryKey(rs, rowToInsert, 1)); + rs.close(); + } + + /* + * Validate getOriginal returns a ResultSet which is a copy of the original + * RowSet + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void commonCachedRowSetTest0056(CachedRowSet rs) throws Exception { + String coffee = "Hazelnut"; + int sales = 100; + int id = 200; + Object[] updatedPkeys = {1, id, 3, 4, 5}; + // Change the coffee name and sales total for row 2 and save the + // previous values + rs.absolute(2); + int origId = rs.getInt(1); + String origCoffee = rs.getString(2); + int origSales = rs.getInt(5); + rs.updateInt(1, id); + rs.updateString(2, coffee); + rs.updateInt(5, sales); + // MetaData should match + try ( // Get the original original RowSet and validate that the changes + // are only made to the current, not the original + ResultSet rs1 = rs.getOriginal()) { + // MetaData should match + compareMetaData(rs.getMetaData(), rs1.getMetaData()); + assertTrue(rs1.isBeforeFirst()); + assertTrue(rs1.getConcurrency() == ResultSet.CONCUR_UPDATABLE); + assertTrue(rs1.getType() == ResultSet.TYPE_SCROLL_INSENSITIVE); + rs1.absolute(2); + // Check original rowset is not changed + assertTrue(rs1.getInt(1) == origId); + assertTrue(rs1.getString(2).equals(origCoffee)); + assertTrue(rs1.getInt(5) == origSales); + assertEquals(getPrimaryKeys(rs1), COFFEES_PRIMARY_KEYS); + // Check current rowset + assertTrue(rs.getInt(1) == id); + assertTrue(rs.getString(2).equals(coffee)); + assertTrue(rs.getInt(5) == sales); + assertEquals(getPrimaryKeys(rs), updatedPkeys); + } + rs.close(); + } + + /* + * Validate getOriginalRow returns a ResultSet which is a copy of the + * original row that was modified + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void commonCachedRowSetTest0057(CachedRowSet rs) throws Exception { + String coffee = "Hazelnut"; + int sales = 100; + int id = 200; + Object[] updatedPkeys = {1, id, 3, 4, 5}; + // Change the coffee name and sales total for row 2 and save the + // previous values + rs.absolute(2); + int origId = rs.getInt(1); + String origCoffee = rs.getString(2); + int origSales = rs.getInt(5); + rs.updateInt(1, id); + rs.updateString(2, coffee); + rs.updateInt(5, sales); + // MetaData should match + try ( // Get the original original row and validate that the changes + // are only made to the current, not the original + ResultSet rs1 = rs.getOriginalRow()) { + // MetaData should match + compareMetaData(rs.getMetaData(), rs1.getMetaData()); + assertTrue(rs1.isBeforeFirst()); + assertTrue(rs1.getConcurrency() == ResultSet.CONCUR_UPDATABLE); + assertTrue(rs1.getType() == ResultSet.TYPE_SCROLL_INSENSITIVE); + rs1.next(); + assertTrue(rs1.isFirst() && rs1.isLast()); + assertTrue(rs1.getRow() == 1); + // Check original row is not changed + assertTrue(rs1.getInt(1) == origId); + assertTrue(rs1.getString(2).equals(origCoffee)); + assertTrue(rs1.getInt(5) == origSales); + // Check current row + assertTrue(rs.getInt(1) == id); + assertTrue(rs.getString(2).equals(coffee)); + assertTrue(rs.getInt(5) == sales); + assertEquals(getPrimaryKeys(rs), updatedPkeys); + } + rs.close(); + } + + /* + * Validate that restoreOrginal will restore the RowSet to its + * state prior to the insert of a row + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0058(CachedRowSet rs) throws Exception { + int rowToInsert = 1961; + assertTrue(rs.size() == COFFEE_HOUSES_ROWS); + try ( // Add new row + CachedRowSet crs1 = rsf.createCachedRowSet()) { + rs.beforeFirst(); + crs1.populate(rs); + TestRowSetListener rsl = new TestRowSetListener(); + crs1.addRowSetListener(rsl); + crs1.moveToInsertRow(); + crs1.updateInt(1, rowToInsert); + crs1.updateString(2, "GOTHAM"); + crs1.updateInt(3, 3450); + crs1.updateInt(4, 2005); + crs1.updateInt(5, 5455); + crs1.insertRow(); + assertTrue(rsl.isNotified(TestRowSetListener.ROW_CHANGED)); + crs1.moveToCurrentRow(); + assertTrue(findRowByPrimaryKey(crs1, rowToInsert, 1)); + // Restore back to our original state and the + // previously inserted row should not be there + rsl.resetFlag(); + crs1.restoreOriginal(); + assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); + assertTrue(crs1.isBeforeFirst()); + crs1.last(); + assertFalse(crs1.rowInserted()); + assertFalse(findRowByPrimaryKey(crs1, rowToInsert, 1)); + } + rs.close(); + } + + /* + * Validate that restoreOrginal will restore the RowSet to its + * state prior to deleting a row + */ + @Test(dataProvider = "rowsetUsingCoffees", enabled = true) + public void commonCachedRowSetTest0059(CachedRowSet rs) throws Exception { + int rowToDelete = 2; + try (CachedRowSet crs1 = rsf.createCachedRowSet()) { + rs.beforeFirst(); + crs1.populate(rs); + TestRowSetListener rsl = new TestRowSetListener(); + crs1.addRowSetListener(rsl); + // Delete a row, the PK is also the absolute position as a List + // backs the RowSet + crs1.absolute(rowToDelete); + crs1.deleteRow(); + assertTrue(crs1.rowDeleted()); + assertFalse(findRowByPrimaryKey(crs1, rowToDelete, 1)); + // Restore back to our original state and the + // previously deleted row should be there + rsl.resetFlag(); + crs1.restoreOriginal(); + assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); + assertTrue(crs1.isBeforeFirst()); + crs1.absolute(rowToDelete); + assertFalse(crs1.rowDeleted()); + assertTrue(findRowByPrimaryKey(crs1, rowToDelete, 1)); + } + rs.close(); + } + + /* + * Validate that restoreOrginal will restore the RowSet to its + * state prior to updating a row + */ + @Test(dataProvider = "rowsetUsingCoffees", enabled = true) + public void commonCachedRowSetTest0060(CachedRowSet rs) throws Exception { + int rowToUpdate = 2; + String coffee = "Hazelnut"; + try (CachedRowSet crs1 = rsf.createCachedRowSet()) { + rs.beforeFirst(); + crs1.populate(rs); + TestRowSetListener rsl = new TestRowSetListener(); + crs1.addRowSetListener(rsl); + // Delete a row, the PK is also the absolute position as a List + // backs the RowSet + crs1.absolute(rowToUpdate); + String origCoffee = crs1.getString(2); + crs1.updateString(2, coffee); + assertTrue(crs1.columnUpdated(2)); + crs1.updateRow(); + assertTrue(crs1.rowUpdated()); + assertFalse(origCoffee.equals(crs1.getString(2))); + // Restore back to our original state and the + // previous value for the column within the row should be there + rsl.resetFlag(); + crs1.restoreOriginal(); + assertTrue(rsl.isNotified(TestRowSetListener.ROWSET_CHANGED)); + assertTrue(crs1.isBeforeFirst()); + // absolute() is failing for some reason so need to look at this later + crs1.next(); + crs1.next(); + assertFalse(crs1.columnUpdated(2)); + assertFalse(crs1.rowUpdated()); + assertTrue(origCoffee.equals(crs1.getString(2))); + } + rs.close(); + } + + /* + * Initialize a RowSet via the populate method. Validate it matches + * the original ResultSet + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0061(CachedRowSet rs) throws Exception { + try (CachedRowSet crs1 = rsf.createCachedRowSet()) { + rs.beforeFirst(); + crs1.populate(rs); + compareRowSets(rs, crs1); + } + rs.close(); + } + + /* + * Initialize a RowSet via the populate method specifying a starting row. + * Validate it matches the original ResultSet starting for the specofied + * offset + */ + @Test(dataProvider = "rowsetUsingCoffeeHouses") + public void commonCachedRowSetTest0062(CachedRowSet rs) throws Exception { + Object[] expectedRows = { + 32001, 10042, 10024, 10039, 10041, 33005, 33010, 10035, 10037, + 10034, 32004 + }; + int startingRow = 4; + try (CachedRowSet crs1 = rsf.createCachedRowSet()) { + rs.beforeFirst(); + crs1.populate(rs, startingRow); + assertEquals(crs1.size(), COFFEE_HOUSES_ROWS - startingRow + 1); + assertEquals(getPrimaryKeys(crs1), expectedRows); + } + rs.close(); + } + +} diff --git a/jdk/test/javax/sql/testng/test/rowset/filteredrowset/CityFilter.java b/jdk/test/javax/sql/testng/test/rowset/filteredrowset/CityFilter.java new file mode 100644 index 00000000000..2188c4eed08 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/filteredrowset/CityFilter.java @@ -0,0 +1,100 @@ +/* + * 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. + */ +package test.rowset.filteredrowset; + +import java.sql.SQLException; +import javax.sql.RowSet; +import javax.sql.rowset.Predicate; + +/* + * Simple implementation of Predicate which is used to filter rows based + * on a City. + */ +public class CityFilter implements Predicate { + + private final String[] cities; + private String colName = null; + private int colNumber = -1; + + public CityFilter(String[] cities, String colName) { + this.cities = cities; + this.colName = colName; + } + + public CityFilter(String[] cities, int colNumber) { + this.cities = cities; + this.colNumber = colNumber; + } + + public boolean evaluate(Object value, String colName) { + + if (colName.equalsIgnoreCase(this.colName)) { + for (String city : cities) { + if (city.equalsIgnoreCase((String) value)) { + return true; + } + } + } + return false; + } + + public boolean evaluate(Object value, int colNumber) { + + if (colNumber == this.colNumber) { + for (String city : this.cities) { + if (city.equalsIgnoreCase((String) value)) { + return true; + } + } + } + return false; + } + + public boolean evaluate(RowSet rs) { + + boolean result = false; + + if (rs == null) { + return false; + } + + try { + for (String city : cities) { + + String val = ""; + if (colNumber > 0) { + val = (String) rs.getObject(colNumber); + } else if (colName != null) { + val = (String) rs.getObject(colName); + } + + if (val.equalsIgnoreCase(city)) { + return true; + } + } + } catch (SQLException e) { + result = false; + } + return result; + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/filteredrowset/FilteredRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/filteredrowset/FilteredRowSetTests.java new file mode 100644 index 00000000000..263a79a68b6 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/filteredrowset/FilteredRowSetTests.java @@ -0,0 +1,140 @@ +/* + * 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. + */ +package test.rowset.filteredrowset; + +import java.sql.SQLException; +import javax.sql.RowSet; +import javax.sql.rowset.FilteredRowSet; +import javax.sql.rowset.Predicate; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import test.rowset.webrowset.CommonWebRowSetTests; + +public class FilteredRowSetTests extends CommonWebRowSetTests { + + private FilteredRowSet frs; + + @BeforeMethod + public void setUpMethod() throws Exception { + frs = createCoffeeHousesRowSet(); + } + + @AfterMethod + public void tearDownMethod() throws Exception { + frs.close(); + } + + protected FilteredRowSet newInstance() throws SQLException { + return rsf.createFilteredRowSet(); + } + + /* + * Validate getFilter returns null if setFilter has not been called + */ + @Test + public void FilteredRowSetTest0000() throws SQLException { + assertNull(frs.getFilter()); + } + + /* + * Call setFilter to set a Predicate and validate that getFilter + * returns the correct Predicate + */ + @Test + public void FilteredRowSetTest0001() throws SQLException { + Predicate p = new PrimaryKeyFilter(0, 100030, 1); + frs.setFilter(p); + assertTrue(frs.getFilter().equals(p)); + frs.setFilter(null); + assertNull(frs.getFilter()); + } + + /* + * Validate that the correct rows are returned when a Predicate using + * a column index is used + */ + @Test + public void FilteredRowSetTest0002() throws SQLException { + Object[] expectedKeys = { + 10023, 10040, 10042, 10024, 10039, 10041, 10035, 10037, 10034 + }; + frs.setFilter(new PrimaryKeyFilter(10000, 10999, 1)); + assertEquals(getPrimaryKeys(frs), expectedKeys); + } + + /* + * Validate that the correct rows are returned when a Predicate using + * a column Label is used + */ + @Test + public void FilteredRowSetTest0003() throws SQLException { + Object[] expectedKeys = { + 10023, 10040, 10042, 10024, 10039, 10041, 10035, 10037, 10034 + }; + frs.setFilter(new PrimaryKeyFilter(10000, 10999, "STORE_ID")); + assertEquals(getPrimaryKeys(frs), expectedKeys); + + } + + /* + * Validate that the correct rows are returned when a Predicate using + * a column index is used + */ + @Test + public void FilteredRowSetTest0004() throws SQLException { + Object[] expectedKeys = { + 10040, 10042, 10041, 10035, 10037 + }; + String[] cityArray = {"SF", "LA"}; + frs.setFilter(new CityFilter(cityArray, 2)); + assertEquals(getPrimaryKeys(frs), expectedKeys); + } + + /* + * Validate that the correct rows are returned when a Predicate using + * a column Label is used + */ + @Test + public void FilteredRowSetTest0005() throws SQLException { + Object[] expectedKeys = { + 10040, 10042, 10041, 10035, 10037 + }; + String[] cityArray = {"SF", "LA"}; + frs.setFilter(new CityFilter(cityArray, "CITY")); + assertEquals(getPrimaryKeys(frs), expectedKeys); + } + + + // Tests that are common but need to be disabled due to an implementation bug + + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0043(RowSet rs) throws Exception { + // Need to fix bug in FilteredRowSets + } + +} diff --git a/jdk/test/javax/sql/testng/test/rowset/filteredrowset/PrimaryKeyFilter.java b/jdk/test/javax/sql/testng/test/rowset/filteredrowset/PrimaryKeyFilter.java new file mode 100644 index 00000000000..2a748314006 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/filteredrowset/PrimaryKeyFilter.java @@ -0,0 +1,93 @@ +/* + * 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. + */ +package test.rowset.filteredrowset; + +import javax.sql.RowSet; +import javax.sql.rowset.Predicate; + +/* + * Simple implementation of Predicate which is used to filter rows based + * on the Primary Key. + */ +public class PrimaryKeyFilter implements Predicate { + + private final int lo; + private final int hi; + private String colName = null; + private int colNumber = -1; + + public PrimaryKeyFilter(int lo, int hi, int colNumber) { + this.lo = lo; + this.hi = hi; + this.colNumber = colNumber; + } + + public PrimaryKeyFilter(int lo, int hi, String colName) { + this.lo = lo; + this.hi = hi; + this.colName = colName; + } + + public boolean evaluate(Object value, String columnName) { + + boolean result = false; + if (columnName.equalsIgnoreCase(this.colName)) { + int columnValue = ((Integer) value); + result = (columnValue >= this.lo) && (columnValue <= this.hi); + } + return result; + } + + public boolean evaluate(Object value, int columnNumber) { + + boolean result = false; + if (this.colNumber == columnNumber) { + int columnValue = (Integer) value; + result = (columnValue >= this.lo) && (columnValue <= this.hi); + } + return result; + } + + public boolean evaluate(RowSet rs) { + + boolean result = false; + try { + int columnValue = -1; + + if (this.colNumber > 0) { + columnValue = rs.getInt(this.colNumber); + } else if (this.colName != null) { + columnValue = rs.getInt(this.colName); + } + if ((columnValue >= this.lo) && (columnValue <= this.hi)) { + result = true; + } + + } catch (Exception e) { + System.out.println("Error:" + e.getMessage()); + result = false; + } + return result; + } + +} diff --git a/jdk/test/javax/sql/testng/test/rowset/joinrowset/JoinRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/joinrowset/JoinRowSetTests.java new file mode 100644 index 00000000000..b84453e9a3b --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/joinrowset/JoinRowSetTests.java @@ -0,0 +1,324 @@ +/* + * 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. + */ +package test.rowset.joinrowset; + +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; +import javax.sql.RowSet; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.JoinRowSet; +import javax.sql.rowset.RowSetMetaDataImpl; +import javax.sql.rowset.WebRowSet; +import static org.testng.Assert.assertEquals; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import test.rowset.webrowset.CommonWebRowSetTests; + +public class JoinRowSetTests extends CommonWebRowSetTests { + + private final String SUPPLIERS_TABLE = "SUPPLIERS"; + // Expected COF_IDs to be found + private final Object[] EXPECTED = {4, 1}; + // SUPPLIERS Primary Key to use to validate the joins + private final int SUP_ID = 101; + // Join Column between the SUPPLIERS and COFFEES table + private final String JOIN_COLNAME = "SUP_ID"; + // Column index in COFFEES table which contains SUP_ID + private final int COFFEES_JOIN_COLUMN_INDEX = 3; + // Column index in SUPPLIERS table which contains SUP_ID + private final int SUPPLIERS_JOIN_COLUMN_INDEX = 1; + + @Override + protected JoinRowSet newInstance() throws SQLException { + return rsf.createJoinRowSet(); + } + + /* + * Initializes the SUPPLIERS metadata + */ + private void initSuppliersMetaData(CachedRowSet crs) throws SQLException { + RowSetMetaDataImpl rsmd = new RowSetMetaDataImpl(); + + /* + * CREATE TABLE SUPPLIERS ( + * SUP_ID INTEGER NOT NULL, + * SUP_NAME VARCHAR(32) NOT NULL, + * STREET VARCHAR(32) NOT NULL, + * CITY VARCHAR(32) NOT NULL, + * STATE CHAR(2) NOT NULL, + * ZIP CHAR(5) NOT NULL, + * PRIMARY KEY (SUP_ID)) + */ + rsmd.setColumnCount(6); + rsmd.setColumnName(1, "SUP_ID"); + rsmd.setColumnName(2, "SUP_NAME"); + rsmd.setColumnName(3, "STREET"); + rsmd.setColumnName(4, "CITY"); + rsmd.setColumnName(5, "STATE"); + rsmd.setColumnName(6, "ZIP"); + + rsmd.setColumnType(1, Types.INTEGER); + rsmd.setColumnType(2, Types.VARCHAR); + rsmd.setColumnType(3, Types.VARCHAR); + rsmd.setColumnType(4, Types.VARCHAR); + rsmd.setColumnType(5, Types.CHAR); + rsmd.setColumnType(6, Types.CHAR); + crs.setMetaData(rsmd); + crs.setTableName(SUPPLIERS_TABLE); + } + + /* + * Add rows to SUPPLIERS table + */ + protected void createSuppiersRows(RowSet rs) throws SQLException { + + // insert into SUPPLIERS values(49, 'Superior Coffee', '1 Party Place', + // 'Mendocino', 'CA', '95460') + rs.moveToInsertRow(); + rs.updateInt(1, 49); + rs.updateString(2, "Superior Coffee"); + rs.updateString(3, "1 Party Place"); + rs.updateString(4, "Mendocino"); + rs.updateString(5, "CA"); + rs.updateString(6, "95460"); + rs.insertRow(); + + // insert into SUPPLIERS values(101, 'Acme, Inc.', '99 Market Street', + // 'Groundsville', 'CA', '95199') + rs.moveToInsertRow(); + rs.updateInt(1, 101); + rs.updateString(2, "Acme, Inc."); + rs.updateString(3, "99 Market Street"); + rs.updateString(4, "Groundsville"); + rs.updateString(5, "CA"); + rs.updateString(6, "95199"); + rs.insertRow(); + // insert into SUPPLIERS values(150, 'The High Ground', + // '100 Coffee Lane', 'Meadows', 'CA', '93966') + rs.moveToInsertRow(); + rs.updateInt(1, 150); + rs.updateString(2, "The High Ground"); + rs.updateString(3, "100 Coffee Lane"); + rs.updateString(4, "Meadows"); + rs.updateString(5, "CA"); + rs.updateString(6, "93966"); + rs.insertRow(); + // insert into SUPPLIERS values(456," 'Restaurant Supplies, Inc.', + // '200 Magnolia Street', 'Meadows', 'CA', '93966') + rs.moveToInsertRow(); + rs.updateInt(1, 456); + rs.updateString(2, "Restaurant Supplies, Inc."); + rs.updateString(3, "200 Magnolia Stree"); + rs.updateString(4, "Meadows"); + rs.updateString(5, "CA"); + rs.updateString(6, "93966"); + rs.insertRow(); + // insert into SUPPLIERS values(927, 'Professional Kitchen', + // '300 Daisy Avenue', 'Groundsville'," 'CA', '95199') + rs.moveToInsertRow(); + rs.updateInt(1, 927); + rs.updateString(2, "Professional Kitchen"); + rs.updateString(3, "300 Daisy Avenue"); + rs.updateString(4, "Groundsville"); + rs.updateString(5, "CA"); + rs.updateString(6, "95199"); + rs.insertRow(); + } + + /* + * DataProvider used to set parameters for basic types that are supported + */ + @DataProvider(name = "createCachedRowSetsToUse") + private Object[][] createCachedRowSetsToUse() throws SQLException { + CachedRowSet crs = rsf.createCachedRowSet(); + initCoffeesMetaData(crs); + createCoffeesRows(crs); + // Make sure you are not on the insertRow + crs.moveToCurrentRow(); + CachedRowSet crs1 = rsf.createCachedRowSet(); + initSuppliersMetaData(crs1); + createSuppiersRows(crs1); + // Make sure you are not on the insertRow + crs1.moveToCurrentRow(); + return new Object[][]{ + {crs, crs1} + }; + } + + /* + * Validate that the correct coffees are returned for SUP_ID + */ + private void validateResults(final JoinRowSet jrs) throws SQLException { + List results = new ArrayList<>(); + jrs.beforeFirst(); + while (jrs.next()) { + if (jrs.getInt(JOIN_COLNAME) == SUP_ID) { + results.add(jrs.getInt("COF_ID")); + } + } + assertEquals(results.toArray(), EXPECTED); + } + + /* + * Join two CachedRowSets specifying a column name to join against + */ + @Test(dataProvider = "createCachedRowSetsToUse") + public void joinRowSetTests0000(CachedRowSet crs, CachedRowSet crs1) + throws Exception { + + try (JoinRowSet jrs = newInstance()) { + jrs.addRowSet(crs, JOIN_COLNAME); + jrs.addRowSet(crs1, JOIN_COLNAME); + validateResults(jrs); + crs.close(); + crs1.close(); + } + } + + /* + * Join two CachedRowSets specifying a column index to join against + */ + @Test(dataProvider = "createCachedRowSetsToUse") + public void joinRowSetTests0001(CachedRowSet crs, CachedRowSet crs1) + throws Exception { + + try (JoinRowSet jrs = newInstance()) { + jrs.addRowSet(crs, COFFEES_JOIN_COLUMN_INDEX); + jrs.addRowSet(crs1, SUPPLIERS_JOIN_COLUMN_INDEX); + validateResults(jrs); + crs.close(); + crs1.close(); + } + } + + /* + * Join two CachedRowSets specifying a column name to join against + */ + @Test(dataProvider = "createCachedRowSetsToUse") + public void joinRowSetTests0002(CachedRowSet crs, CachedRowSet crs1) + throws Exception { + + try (JoinRowSet jrs = newInstance()) { + RowSet[] rowsets = {crs, crs1}; + String[] joinCols = {JOIN_COLNAME, JOIN_COLNAME}; + jrs.addRowSet(rowsets, joinCols); + validateResults(jrs); + crs.close(); + crs1.close(); + } + } + + /* + * Join two CachedRowSets specifying a column index to join against + */ + @Test(dataProvider = "createCachedRowSetsToUse") + public void joinRowSetTests0003(CachedRowSet crs, CachedRowSet crs1) + throws Exception { + + try (JoinRowSet jrs = newInstance()) { + RowSet[] rowsets = {crs, crs1}; + int[] joinCols = {COFFEES_JOIN_COLUMN_INDEX, + SUPPLIERS_JOIN_COLUMN_INDEX}; + jrs.addRowSet(rowsets, joinCols); + validateResults(jrs); + crs.close(); + crs1.close(); + } + } + + /* + * Join two CachedRowSets specifying a column name to join against + */ + @Test(dataProvider = "createCachedRowSetsToUse") + public void joinRowSetTests0005(CachedRowSet crs, CachedRowSet crs1) + throws Exception { + + try (JoinRowSet jrs = newInstance()) { + crs.setMatchColumn(JOIN_COLNAME); + crs1.setMatchColumn(JOIN_COLNAME); + jrs.addRowSet(crs); + jrs.addRowSet(crs1); + validateResults(jrs); + crs.close(); + crs1.close(); + } + } + + /* + * Join two CachedRowSets specifying a column index to join against + */ + @Test(dataProvider = "createCachedRowSetsToUse") + public void joinRowSetTests0006(CachedRowSet crs, CachedRowSet crs1) + throws Exception { + + try (JoinRowSet jrs = newInstance()) { + crs.setMatchColumn(COFFEES_JOIN_COLUMN_INDEX); + crs1.setMatchColumn(SUPPLIERS_JOIN_COLUMN_INDEX); + + jrs.addRowSet(crs); + jrs.addRowSet(crs1); + validateResults(jrs); + crs.close(); + crs1.close(); + } + } + + // Disabled tests due to bugs in JoinRowSet + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0004(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0005(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0008(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0026(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0027(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0053(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0054(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType", enabled = false) + public void commonCachedRowSetTest0055(CachedRowSet rs) throws Exception { + } + + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0009(WebRowSet wrs1) throws Exception { + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/webrowset/CommonWebRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/webrowset/CommonWebRowSetTests.java new file mode 100644 index 00000000000..ce0801e0fe4 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/webrowset/CommonWebRowSetTests.java @@ -0,0 +1,400 @@ +/* + * 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. + */ +package test.rowset.webrowset; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStreamWriter; +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.util.Arrays; +import javax.sql.rowset.WebRowSet; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertEqualsNoOrder; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import test.rowset.cachedrowset.CommonCachedRowSetTests; + +public abstract class CommonWebRowSetTests extends CommonCachedRowSetTests { + + protected final String XMLFILEPATH = System.getProperty("test.src", ".") + + File.separatorChar + "xml" + File.separatorChar; + protected final String COFFEE_ROWS_XML = XMLFILEPATH + "COFFEE_ROWS.xml"; + protected final String DELETED_COFFEE_ROWS_XML + = XMLFILEPATH + "DELETED_COFFEE_ROWS.xml"; + protected final String MODFIED_DELETED_COFFEE_ROWS_XML + = XMLFILEPATH + "MODFIED_DELETED_COFFEE_ROWS.xml"; + protected final String UPDATED_COFFEE_ROWS_XML + = XMLFILEPATH + "UPDATED_COFFEE_ROWS.xml"; + protected final String INSERTED_COFFEE_ROWS_XML + = XMLFILEPATH + "INSERTED_COFFEE_ROWS.xml"; + protected final String UPDATED_INSERTED_COFFEE_ROWS_XML + = XMLFILEPATH + "UPDATED_INSERTED_COFFEE_ROWS.xml"; + + + /* + * Utility method to write a WebRowSet XML file via an OutputStream + */ + protected ByteArrayOutputStream writeWebRowSetWithOutputStream(WebRowSet rs) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + rs.writeXml(oos); + } + return baos; + } + + /* + * Utility method to write a WebRowSet XML file via an OutputStream + * and populating the WebRowSet via a ResultSet + */ + protected ByteArrayOutputStream writeWebRowSetWithOutputStream(ResultSet rs) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + WebRowSet wrs = rsf.createWebRowSet(); + wrs.writeXml(rs, oos); + } + return baos; + } + + + /* + * Utility method to popoulate a WebRowSet via a InputStream + */ + protected WebRowSet readWebRowSetWithOInputStream(ByteArrayOutputStream baos) throws Exception { + WebRowSet wrs1 = rsf.createWebRowSet(); + try (ObjectInputStream ois + = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + wrs1.readXml(ois); + } + return wrs1; + } + + /* + * Utility method to write a WebRowSet XML file via an Writer + */ + protected ByteArrayOutputStream writeWebRowSetWithOutputStreamWithWriter(WebRowSet rs) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(baos); + rs.writeXml(osw); + return baos; + } + + /* + * Utility method to write a WebRowSet XML file via an Writer and populating + * the WebRowSet via a ResultSet + */ + protected ByteArrayOutputStream writeWebRowSetWithOutputStreamWithWriter(ResultSet rs) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(baos); + WebRowSet wrs = rsf.createWebRowSet(); + wrs.writeXml(rs, osw); + return baos; + } + + /* + * Utility method to popoulate a WebRowSet via a Readar + */ + protected WebRowSet readWebRowSetWithOInputStreamWithReader(ByteArrayOutputStream baos) throws Exception { + WebRowSet wrs1 = rsf.createWebRowSet(); + InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())); + wrs1.readXml(isr); + return wrs1; + } + + /* + * Validate the expected Rows are contained within the RowSet + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void WebRowSetTest0000(WebRowSet wrs) throws Exception { + assertEquals(getPrimaryKeys(wrs), COFFEES_PRIMARY_KEYS); + assertEquals(wrs.size(), COFFEES_ROWS); + wrs.close(); + } + + /* + * Validate the expected Rows are contained within the RowSet + * populated by readXML(Reader) + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0001(WebRowSet wrs1) throws Exception { + + try (FileReader fr = new FileReader(COFFEE_ROWS_XML)) { + wrs1.readXml(fr); + } + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + assertEquals(wrs1.size(), COFFEES_ROWS); + wrs1.close(); + + } + + /* + * Validate the expected Rows are contained within the RowSet + * populated by readXML(InputStream) + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0002(WebRowSet wrs1) throws Exception { + try (FileInputStream fis = new FileInputStream(COFFEE_ROWS_XML)) { + wrs1.readXml(fis); + } + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + assertEquals(wrs1.size(), COFFEES_ROWS); + wrs1.close(); + } + + /* + * Write a WebRowSet via writeXML(OutputStream), read it + * back via readXML(InputStream) and validate the primary keys + * are the same + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void WebRowSetTest0003(WebRowSet wrs) throws Exception { + ByteArrayOutputStream baos = writeWebRowSetWithOutputStream(wrs); + try (WebRowSet wrs1 = readWebRowSetWithOInputStream(baos)) { + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + assertEquals(wrs1.size(), COFFEES_ROWS); + } + } + + /* + * Write a ResultSet via writeXML(OutputStream), read it + * back via readXML(InputStream) and validate the primary keys + * are the same + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void WebRowSetTest0004(WebRowSet wrs) throws Exception { + ResultSet rs = wrs; + rs.beforeFirst(); + ByteArrayOutputStream baos = writeWebRowSetWithOutputStream(rs); + try (WebRowSet wrs1 = readWebRowSetWithOInputStream(baos)) { + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + assertEquals(wrs1.size(), COFFEES_ROWS); + } + } + + /* + * Write a WebRowSet via writeXML(Writer), read it + * back via readXML(Reader) and validate the primary keys + * are the same + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void WebRowSetTest0005(WebRowSet wrs) throws Exception { + ByteArrayOutputStream baos = writeWebRowSetWithOutputStreamWithWriter(wrs); + try (WebRowSet wrs1 = readWebRowSetWithOInputStreamWithReader(baos)) { + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + assertEquals(wrs1.size(), COFFEES_ROWS); + } + } + + /* + * Write a WebRowSet via writeXML(Writer), read it + * back via readXML(Reader) and validate the primary keys + * are the same + */ + @Test(dataProvider = "rowsetUsingCoffees") + public void WebRowSetTest0006(WebRowSet wrs) throws Exception { + ResultSet rs = wrs; + rs.beforeFirst(); + ByteArrayOutputStream baos = writeWebRowSetWithOutputStreamWithWriter(rs); + try (WebRowSet wrs1 = readWebRowSetWithOInputStreamWithReader(baos)) { + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + assertEquals(wrs1.size(), COFFEES_ROWS); + } + } + + /* + * Validate the expected Rows are contained within the RowSet + * after deleting the specified rows + */ + @Test(dataProvider = "rowsetUsingCoffees", enabled = false) + public void WebRowSetTest0007(WebRowSet wrs) throws Exception { + assertEquals(getPrimaryKeys(wrs), COFFEES_PRIMARY_KEYS); + int[] rowsToDelete = {2, 4}; + assertEquals(getPrimaryKeys(wrs), COFFEES_PRIMARY_KEYS); + for (int row : rowsToDelete) { + assertTrue(deleteRowByPrimaryKey(wrs, row, 1)); + } + + FileInputStream fis = new FileInputStream(MODFIED_DELETED_COFFEE_ROWS_XML); + try (WebRowSet wrs1 = rsf.createWebRowSet()) { + wrs1.readXml(fis); + // With setShowDeleted(false) which is the default, + // the deleted row should not be visible + for (int row : rowsToDelete) { + assertTrue(findRowByPrimaryKey(wrs1, row, 1)); + } + assertTrue(wrs.size() == COFFEES_ROWS); + // With setShowDeleted(true), the deleted row should be visible + for (int row : rowsToDelete) { + assertTrue(findRowByPrimaryKey(wrs, row, 1)); + } + } + } + + /* + * Validate the expected Rows are contained within the RowSet + * that was populated by reading an xml file with all rows + * marked as a currentRow + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0008(WebRowSet wrs1) throws Exception { + FileInputStream fis = new FileInputStream(COFFEE_ROWS_XML); + wrs1.readXml(fis); + assertTrue(wrs1.size() == COFFEES_ROWS); + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + // Validate that the rows are not marked as deleted, inserted or updated + wrs1.beforeFirst(); + while (wrs1.next()) { + assertFalse(wrs1.rowDeleted()); + assertFalse(wrs1.rowInserted()); + assertFalse(wrs1.rowUpdated()); + } + wrs1.close(); + } + + /* + * Read an XML file to populate a WebRowSet and validate that the rows + * that are marked as deleted are marked as such in the WebRowSet + * Also validate that they are or are not visible based on the + * setShowDeleted value + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0009(WebRowSet wrs1) throws Exception { + int[] rowsToDelete = {2, 4}; + Object[] expectedRows = {1, 3, 5}; + FileInputStream fis = new FileInputStream(DELETED_COFFEE_ROWS_XML); + wrs1.readXml(fis); + assertTrue(wrs1.size() == COFFEES_ROWS); + assertEquals(getPrimaryKeys(wrs1), expectedRows); + // With setShowDeleted(false) which is the default, + // the deleted row should not be visible + for (int row : rowsToDelete) { + assertFalse(findRowByPrimaryKey(wrs1, row, 1)); + } + // With setShowDeleted(true), the deleted row should be visible + wrs1.setShowDeleted(true); + for (int row : rowsToDelete) { + assertTrue(findRowByPrimaryKey(wrs1, row, 1)); + } + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + wrs1.close(); + + } + + /* + * Validate that the correct row in the WebRowSet that had been created + * from an xml file is marked as updated and contains the correct values + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0010(WebRowSet wrs1) throws Exception { + FileInputStream fis = new FileInputStream(UPDATED_COFFEE_ROWS_XML); + wrs1.readXml(fis); + assertTrue(wrs1.size() == COFFEES_ROWS); + assertEquals(getPrimaryKeys(wrs1), COFFEES_PRIMARY_KEYS); + wrs1.beforeFirst(); + while (wrs1.next()) { + if (wrs1.getInt(1) == 3) { + assertTrue(wrs1.rowUpdated()); + assertTrue(wrs1.getInt(5) == 21 && wrs1.getInt(6) == 69); + assertFalse(wrs1.rowDeleted()); + assertFalse(wrs1.rowInserted()); + } else { + assertFalse(wrs1.rowUpdated()); + assertFalse(wrs1.rowDeleted()); + assertFalse(wrs1.rowInserted()); + } + } + wrs1.close(); + } + + /* + * Validate the correct row is marked as inserted in a WebRowSet + * that is read from an xml file + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0011(WebRowSet wrs1) throws Exception { + int expectedSize = COFFEES_ROWS + 2; + int addedRowPK = 15; + int addedRowPK2 = 20; + Object[] expected = Arrays.copyOf(COFFEES_PRIMARY_KEYS, expectedSize); + expected[expectedSize - 2] = addedRowPK; + expected[expectedSize - 1] = addedRowPK2; + FileInputStream fis = new FileInputStream(INSERTED_COFFEE_ROWS_XML); + wrs1.readXml(fis); + assertTrue(wrs1.size() == expectedSize); + assertEqualsNoOrder(getPrimaryKeys(wrs1), expected); + wrs1.beforeFirst(); + while (wrs1.next()) { + if (wrs1.getInt(1) == 15 || wrs1.getInt(1) == 20) { + assertTrue(wrs1.rowInserted()); + assertFalse(wrs1.rowDeleted()); + assertFalse(wrs1.rowUpdated()); + } else { + assertFalse(wrs1.rowInserted()); + assertFalse(wrs1.rowDeleted()); + assertFalse(wrs1.rowUpdated()); + } + } + wrs1.close(); + } + + /* + * Read an xml file which contains a row that was inserted and updated + */ + @Test(dataProvider = "rowSetType") + public void WebRowSetTest0012(WebRowSet wrs1) throws Exception { + int expectedSize = COFFEES_ROWS + 1; + int addedRowPK = 100; + Object[] expected = Arrays.copyOf(COFFEES_PRIMARY_KEYS, expectedSize); + expected[expectedSize - 1] = addedRowPK; + FileInputStream fis = new FileInputStream(UPDATED_INSERTED_COFFEE_ROWS_XML); + wrs1.readXml(fis); + assertTrue(wrs1.size() == expectedSize); + assertEquals(getPrimaryKeys(wrs1), expected); + wrs1.beforeFirst(); + while (wrs1.next()) { + if (wrs1.getInt(1) == addedRowPK) { + // Row that was inserted and updated + assertTrue(wrs1.rowUpdated()); + assertTrue( + wrs1.getBigDecimal(4).equals(BigDecimal.valueOf(12.99)) + && wrs1.getInt(6) == 125); + assertFalse(wrs1.rowDeleted()); + assertTrue(wrs1.rowInserted()); + } else { + // Remaining rows should only be inserted + assertFalse(wrs1.rowUpdated()); + assertFalse(wrs1.rowDeleted()); + assertTrue(wrs1.rowInserted()); + } + } + wrs1.close(); + } + +} diff --git a/jdk/test/javax/sql/testng/test/rowset/webrowset/WebRowSetTests.java b/jdk/test/javax/sql/testng/test/rowset/webrowset/WebRowSetTests.java new file mode 100644 index 00000000000..5f2890e0b5b --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/webrowset/WebRowSetTests.java @@ -0,0 +1,35 @@ +/* + * 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. + */ +package test.rowset.webrowset; + +import java.sql.SQLException; +import javax.sql.rowset.WebRowSet; + +public class WebRowSetTests extends CommonWebRowSetTests { + + @Override + protected WebRowSet newInstance() throws SQLException { + return rsf.createWebRowSet(); + } + +} diff --git a/jdk/test/javax/sql/testng/util/StubSyncProvider.java b/jdk/test/javax/sql/testng/util/StubSyncProvider.java index eca45798e32..8947455c701 100644 --- a/jdk/test/javax/sql/testng/util/StubSyncProvider.java +++ b/jdk/test/javax/sql/testng/util/StubSyncProvider.java @@ -1,5 +1,5 @@ /* - * 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 @@ -51,12 +51,12 @@ public class StubSyncProvider extends SyncProvider { @Override public RowSetReader getRowSetReader() { - throw new UnsupportedOperationException("Not supported yet."); + return null; } @Override public RowSetWriter getRowSetWriter() { - throw new UnsupportedOperationException("Not supported yet."); + return null; } @Override diff --git a/jdk/test/javax/sql/testng/xml/COFFEE_ROWS.xml b/jdk/test/javax/sql/testng/xml/COFFEE_ROWS.xml new file mode 100644 index 00000000000..e42eb4405b0 --- /dev/null +++ b/jdk/test/javax/sql/testng/xml/COFFEE_ROWS.xml @@ -0,0 +1,191 @@ + + + + + 1008 + + true + 1000 + 0 + 2 + + + + + 0 + 0 + 0 + true + ResultSet.TYPE_SCROLL_INSENSITIVE + false + COFFEES + + + com.sun.rowset.providers.RIOptimisticProvider + Oracle Corporation + 1.0 + 2 + 1 + + + + 6 + + 1 + false + false + false + 0 + false + false + 0 + + COF_NAME + + 0 + 0 + + + 4 + + + + 2 + false + false + false + 0 + false + false + 0 + + SUP_ID + + 0 + 0 + + + 12 + + + + 3 + false + false + false + 0 + false + false + 0 + + PRICE + + 0 + 0 + + + 4 + + + + 4 + false + false + false + 0 + false + false + 0 + + SALES + + 10 + 2 + + + 2 + + + + 5 + false + false + false + 0 + false + false + 0 + + TOTAL + + 0 + 0 + + + 4 + + + + 6 + false + false + false + 0 + false + false + 0 + + + + 0 + 0 + + + 4 + + + + + + 1 + Colombian + 101 + 7.99 + 0 + 0 + + + 2 + French_Roast + 49 + 8.99 + 0 + 0 + + + 3 + Espresso + 150 + 9.99 + 0 + 0 + + + 4 + Colombian_Decaf + 101 + 8.99 + 0 + 0 + + + 5 + French_Roast_Decaf + 49 + 9.99 + 0 + 0 + + + diff --git a/jdk/test/javax/sql/testng/xml/DELETED_COFFEE_ROWS.xml b/jdk/test/javax/sql/testng/xml/DELETED_COFFEE_ROWS.xml new file mode 100644 index 00000000000..6fd38ff4e44 --- /dev/null +++ b/jdk/test/javax/sql/testng/xml/DELETED_COFFEE_ROWS.xml @@ -0,0 +1,191 @@ + + + + SELECT * FROM COFFEES + 1008 + + true + 1000 + 0 + 2 + + + + + 0 + 0 + 0 + true + ResultSet.TYPE_SCROLL_INSENSITIVE + false + COFFEES + jdbc:derby://localhost:1527/testDB;create=true + + com.sun.rowset.providers.RIOptimisticProvider + Oracle Corporation + 1.0 + 2 + 1 + + + + 6 + + 1 + false + false + false + 0 + false + false + 0 + + COF_NAME + + 0 + 0 + + + 4 + + + + 2 + false + false + false + 0 + false + false + 0 + + SUP_ID + + 0 + 0 + + + 12 + + + + 3 + false + false + false + 0 + false + false + 0 + + PRICE + + 0 + 0 + + + 4 + + + + 4 + false + false + false + 0 + false + false + 0 + + SALES + + 10 + 2 + + + 2 + + + + 5 + false + false + false + 0 + false + false + 0 + + TOTAL + + 0 + 0 + + + 4 + + + + 6 + false + false + false + 0 + false + false + 0 + + + + 0 + 0 + + + 4 + + + + + + 1 + Colombian + 101 + 7.99 + 0 + 0 + + + 2 + French_Roast + 49 + 8.99 + 0 + 0 + + + 3 + Espresso + 150 + 9.99 + 0 + 0 + + + 4 + Colombian_Decaf + 101 + 8.99 + 0 + 0 + + + 5 + French_Roast_Decaf + 49 + 9.99 + 0 + 0 + + + diff --git a/jdk/test/javax/sql/testng/xml/INSERTED_COFFEE_ROWS.xml b/jdk/test/javax/sql/testng/xml/INSERTED_COFFEE_ROWS.xml new file mode 100644 index 00000000000..a700bab5c6c --- /dev/null +++ b/jdk/test/javax/sql/testng/xml/INSERTED_COFFEE_ROWS.xml @@ -0,0 +1,207 @@ + + + + + 1008 + + true + 1000 + 0 + 2 + + + + + 0 + 0 + 0 + true + ResultSet.TYPE_SCROLL_INSENSITIVE + false + COFFEES + + + com.sun.rowset.providers.RIOptimisticProvider + Oracle Corporation + 1.0 + 2 + 1 + + + + 6 + + 1 + false + false + false + 0 + false + false + 0 + + COF_NAME + + 0 + 0 + + + 4 + + + + 2 + false + false + false + 0 + false + false + 0 + + SUP_ID + + 0 + 0 + + + 12 + + + + 3 + false + false + false + 0 + false + false + 0 + + PRICE + + 0 + 0 + + + 4 + + + + 4 + false + false + false + 0 + false + false + 0 + + SALES + + 10 + 2 + + + 2 + + + + 5 + false + false + false + 0 + false + false + 0 + + TOTAL + + 0 + 0 + + + 4 + + + + 6 + false + false + false + 0 + false + false + 0 + + + + 0 + 0 + + + 4 + + + + + + 1 + Colombian + 101 + 7.99 + 0 + 0 + + + 2 + French_Roast + 49 + 8.99 + 0 + 0 + + + 3 + Espresso + 150 + 9.99 + 0 + 0 + + + 4 + Colombian_Decaf + 101 + 8.99 + 0 + 0 + + + 15 + Hazelnut + 101 + 8.99 + 0 + 0 + + + 20 + French Vanilla + 49 + 9.99 + 0 + 0 + + + 5 + French_Roast_Decaf + 49 + 9.99 + 0 + 0 + + + diff --git a/jdk/test/javax/sql/testng/xml/MODFIED_DELETED_COFFEE_ROWS.xml b/jdk/test/javax/sql/testng/xml/MODFIED_DELETED_COFFEE_ROWS.xml new file mode 100644 index 00000000000..2c71a5ffd3a --- /dev/null +++ b/jdk/test/javax/sql/testng/xml/MODFIED_DELETED_COFFEE_ROWS.xml @@ -0,0 +1,191 @@ + + + + + 1008 + + true + 1000 + 0 + 2 + + + + + 0 + 0 + 0 + true + ResultSet.TYPE_SCROLL_INSENSITIVE + false + COFFEES + + + com.sun.rowset.providers.RIOptimisticProvider + Oracle Corporation + 1.0 + 2 + 1 + + + + 6 + + 1 + false + false + false + 0 + false + false + 0 + + COF_NAME + + 0 + 0 + + + 4 + + + + 2 + false + false + false + 0 + false + false + 0 + + SUP_ID + + 0 + 0 + + + 12 + + + + 3 + false + false + false + 0 + false + false + 0 + + PRICE + + 0 + 0 + + + 4 + + + + 4 + false + false + false + 0 + false + false + 0 + + SALES + + 10 + 2 + + + 2 + + + + 5 + false + false + false + 0 + false + false + 0 + + TOTAL + + 0 + 0 + + + 4 + + + + 6 + false + false + false + 0 + false + false + 0 + + + + 0 + 0 + + + 4 + + + + + + 1 + Colombian + 101 + 7.99 + 0 + 0 + + + 2 + French_Roast + 49 + 8.99 + 0 + 0 + + + 3 + Espresso + 150 + 9.99 + 0 + 0 + + + 4 + Colombian_Decaf + 101 + 8.99 + 0 + 0 + + + 5 + French_Roast_Decaf + 49 + 9.99 + 0 + 0 + + + diff --git a/jdk/test/javax/sql/testng/xml/UPDATED_COFFEE_ROWS.xml b/jdk/test/javax/sql/testng/xml/UPDATED_COFFEE_ROWS.xml new file mode 100644 index 00000000000..449ba120b17 --- /dev/null +++ b/jdk/test/javax/sql/testng/xml/UPDATED_COFFEE_ROWS.xml @@ -0,0 +1,193 @@ + + + + SELECT * FROM COFFEES + 1008 + + true + 1000 + 0 + 2 + + + + + 0 + 0 + 0 + true + ResultSet.TYPE_SCROLL_INSENSITIVE + false + COFFEES + jdbc:derby://localhost:1527/testDB;create=true + + com.sun.rowset.providers.RIOptimisticProvider + Oracle Corporation + 1.0 + 2 + 1 + + + + 6 + + 1 + false + false + false + 0 + false + false + 0 + + COF_NAME + + 0 + 0 + + + 4 + + + + 2 + false + false + false + 0 + false + false + 0 + + SUP_ID + + 0 + 0 + + + 12 + + + + 3 + false + false + false + 0 + false + false + 0 + + PRICE + + 0 + 0 + + + 4 + + + + 4 + false + false + false + 0 + false + false + 0 + + SALES + + 10 + 2 + + + 2 + + + + 5 + false + false + false + 0 + false + false + 0 + + TOTAL + + 0 + 0 + + + 4 + + + + 6 + false + false + false + 0 + false + false + 0 + + + + 0 + 0 + + + 4 + + + + + + 1 + Colombian + 101 + 7.99 + 0 + 0 + + + 2 + French_Roast + 49 + 8.99 + 0 + 0 + + + 3 + Espresso + 150 + 9.99 + 0 + 21 + 0 + 69 + + + 4 + Colombian_Decaf + 101 + 8.99 + 0 + 0 + + + 5 + French_Roast_Decaf + 49 + 9.99 + 0 + 0 + + + diff --git a/jdk/test/javax/sql/testng/xml/UPDATED_INSERTED_COFFEE_ROWS.xml b/jdk/test/javax/sql/testng/xml/UPDATED_INSERTED_COFFEE_ROWS.xml new file mode 100644 index 00000000000..0cfc3c9fc73 --- /dev/null +++ b/jdk/test/javax/sql/testng/xml/UPDATED_INSERTED_COFFEE_ROWS.xml @@ -0,0 +1,201 @@ + + + + + 1008 + + true + 1000 + 0 + 2 + + + + + 0 + 0 + 0 + true + ResultSet.TYPE_SCROLL_INSENSITIVE + false + COFFEES + + + com.sun.rowset.providers.RIOptimisticProvider + Oracle Corporation + 1.0 + 2 + 1 + + + + 6 + + 1 + false + false + false + 0 + false + false + 0 + + COF_NAME + + 0 + 0 + + + 4 + + + + 2 + false + false + false + 0 + false + false + 0 + + SUP_ID + + 0 + 0 + + + 12 + + + + 3 + false + false + false + 0 + false + false + 0 + + PRICE + + 0 + 0 + + + 4 + + + + 4 + false + false + false + 0 + false + false + 0 + + SALES + + 10 + 2 + + + 2 + + + + 5 + false + false + false + 0 + false + false + 0 + + TOTAL + + 0 + 0 + + + 4 + + + + 6 + false + false + false + 0 + false + false + 0 + + + + 0 + 0 + + + 4 + + + + + + 1 + Colombian + 101 + 7.99 + 0 + 0 + + + 2 + French_Roast + 49 + 8.99 + 0 + 0 + + + 3 + Espresso + 150 + 9.99 + 0 + 0 + + + 4 + Colombian_Decaf + 101 + 8.99 + 0 + 0 + + + 5 + French_Roast_Decaf + 49 + 9.99 + 0 + 0 + + + 100 + Mocha + 49 + 9.99 + 12.99 + 20 + 35 + 125 + + + From 826e1b9739af72c8dd56ac3e4fe765cef596cd77 Mon Sep 17 00:00:00 2001 From: Kim Barrett Date: Wed, 21 Jan 2015 19:36:18 +0100 Subject: [PATCH 124/149] 8069230: Remove unused G1PostBarrierStub::byte_map_base and friends Reviewed-by: brutisso, tschatzl --- hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp | 11 +---------- hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp | 11 +---------- hotspot/src/share/vm/c1/c1_CodeStubs.hpp | 11 +---------- 3 files changed, 3 insertions(+), 30 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp index f3709eb8d05..1187443000d 100644 --- a/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, 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 @@ -483,15 +483,6 @@ void G1PreBarrierStub::emit_code(LIR_Assembler* ce) { } -jbyte* G1PostBarrierStub::_byte_map_base = NULL; - -jbyte* G1PostBarrierStub::byte_map_base_slow() { - BarrierSet* bs = Universe::heap()->barrier_set(); - assert(bs->is_a(BarrierSet::G1SATBCTLogging), - "Must be if we're using this."); - return ((G1SATBCardTableModRefBS*)bs)->byte_map_base; -} - void G1PostBarrierStub::emit_code(LIR_Assembler* ce) { __ bind(_entry); diff --git a/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp b/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp index 718c82904f0..919c2a6df9c 100644 --- a/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, 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 @@ -541,15 +541,6 @@ void G1PreBarrierStub::emit_code(LIR_Assembler* ce) { } -jbyte* G1PostBarrierStub::_byte_map_base = NULL; - -jbyte* G1PostBarrierStub::byte_map_base_slow() { - BarrierSet* bs = Universe::heap()->barrier_set(); - assert(bs->is_a(BarrierSet::G1SATBCTLogging), - "Must be if we're using this."); - return ((G1SATBCardTableModRefBS*)bs)->byte_map_base; -} - void G1PostBarrierStub::emit_code(LIR_Assembler* ce) { __ bind(_entry); assert(addr()->is_register(), "Precondition."); diff --git a/hotspot/src/share/vm/c1/c1_CodeStubs.hpp b/hotspot/src/share/vm/c1/c1_CodeStubs.hpp index e3a4f4d5680..05a8c70506f 100644 --- a/hotspot/src/share/vm/c1/c1_CodeStubs.hpp +++ b/hotspot/src/share/vm/c1/c1_CodeStubs.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, 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 @@ -601,15 +601,6 @@ class G1PostBarrierStub: public CodeStub { LIR_Opr _addr; LIR_Opr _new_val; - static jbyte* _byte_map_base; - static jbyte* byte_map_base_slow(); - static jbyte* byte_map_base() { - if (_byte_map_base == NULL) { - _byte_map_base = byte_map_base_slow(); - } - return _byte_map_base; - } - public: // addr (the address of the object head) and new_val must be registers. G1PostBarrierStub(LIR_Opr addr, LIR_Opr new_val): _addr(addr), _new_val(new_val) { } From eae923a8aedfd550ded159ae7c7dc76f789a2e0b Mon Sep 17 00:00:00 2001 From: Peter Levart Date: Wed, 21 Jan 2015 21:42:22 +0100 Subject: [PATCH 125/149] 8068427: Hashtable deserialization reconstitutes table with wrong capacity Reviewed-by: mduigou, martin, chegar, dfuchs --- .../share/classes/java/util/Hashtable.java | 35 ++++-- .../util/Hashtable/DeserializedLength.java | 110 ++++++++++++++++++ 2 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 jdk/test/java/util/Hashtable/DeserializedLength.java diff --git a/jdk/src/java.base/share/classes/java/util/Hashtable.java b/jdk/src/java.base/share/classes/java/util/Hashtable.java index 3cef9ad03e0..0f1f602f9c1 100644 --- a/jdk/src/java.base/share/classes/java/util/Hashtable.java +++ b/jdk/src/java.base/share/classes/java/util/Hashtable.java @@ -1137,10 +1137,10 @@ public class Hashtable Entry entryStack = null; synchronized (this) { - // Write out the length, threshold, loadfactor + // Write out the threshold and loadFactor s.defaultWriteObject(); - // Write out length, count of elements + // Write out the length and count of elements s.writeInt(table.length); s.writeInt(count); @@ -1169,22 +1169,33 @@ public class Hashtable private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { - // Read in the length, threshold, and loadfactor + // Read in the threshold and loadFactor s.defaultReadObject(); + // Validate loadFactor (ignore threshold - it will be re-computed) + if (loadFactor <= 0 || Float.isNaN(loadFactor)) + throw new StreamCorruptedException("Illegal Load: " + loadFactor); + // Read the original length of the array and number of elements int origlength = s.readInt(); int elements = s.readInt(); - // Compute new size with a bit of room 5% to grow but - // no larger than the original size. Make the length + // Validate # of elements + if (elements < 0) + throw new StreamCorruptedException("Illegal # of Elements: " + elements); + + // Clamp original length to be more than elements / loadFactor + // (this is the invariant enforced with auto-growth) + origlength = Math.max(origlength, (int)(elements / loadFactor) + 1); + + // Compute new length with a bit of room 5% + 3 to grow but + // no larger than the clamped original length. Make the length // odd if it's large enough, this helps distribute the entries. // Guard against the length ending up zero, that's not valid. - int length = (int)(elements * loadFactor) + (elements / 20) + 3; + int length = (int)((elements + elements / 20) / loadFactor) + 3; if (length > elements && (length & 1) == 0) length--; - if (origlength > 0 && length > origlength) - length = origlength; + length = Math.min(length, origlength); table = new Entry[length]; threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1); count = 0; @@ -1195,7 +1206,7 @@ public class Hashtable K key = (K)s.readObject(); @SuppressWarnings("unchecked") V value = (V)s.readObject(); - // synch could be eliminated for performance + // sync is eliminated for performance reconstitutionPut(table, key, value); } } @@ -1207,9 +1218,9 @@ public class Hashtable * *

This differs from the regular put method in several ways. No * checking for rehashing is necessary since the number of elements - * initially in the table is known. The modCount is not incremented - * because we are creating a new instance. Also, no return value - * is needed. + * initially in the table is known. The modCount is not incremented and + * there's no synchronization because we are creating a new instance. + * Also, no return value is needed. */ private void reconstitutionPut(Entry[] tab, K key, V value) throws StreamCorruptedException diff --git a/jdk/test/java/util/Hashtable/DeserializedLength.java b/jdk/test/java/util/Hashtable/DeserializedLength.java new file mode 100644 index 00000000000..1497eb8d00f --- /dev/null +++ b/jdk/test/java/util/Hashtable/DeserializedLength.java @@ -0,0 +1,110 @@ +/* + * 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 java.io.*; +import java.lang.reflect.Field; +import java.util.Hashtable; + +/** + * @test + * @bug 8068427 + * @summary Hashtable deserialization reconstitutes table with wrong capacity + */ +public class DeserializedLength { + + static boolean testDeserializedLength(int elements, float loadFactor) throws Exception { + + // construct Hashtable with minimal initial capacity and given loadFactor + Hashtable ht1 = new Hashtable<>(1, loadFactor); + + // add given number of unique elements + for (int i = 0; i < elements; i++) { + ht1.put(i, i); + } + + // serialize and deserialize into a deep clone + Hashtable ht2 = serialClone(ht1); + + // compare lengths of internal tables + Object[] table1 = (Object[]) hashtableTableField.get(ht1); + Object[] table2 = (Object[]) hashtableTableField.get(ht2); + assert table1 != null; + assert table2 != null; + + int minLength = (int) (ht1.size() / loadFactor) + 1; + int maxLength = minLength * 2; + + boolean ok = (table2.length >= minLength && table2.length <= maxLength); + + System.out.printf( + "%7d %5.2f %7d %7d %7d...%7d %s\n", + ht1.size(), loadFactor, + table1.length, table2.length, + minLength, maxLength, + (ok ? "OK" : "NOT-OK") + ); + + return ok; + } + + static T serialClone(T o) throws IOException, ClassNotFoundException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(bos)) { + oos.writeObject(o); + } + @SuppressWarnings("unchecked") + T clone = (T) new ObjectInputStream( + new ByteArrayInputStream(bos.toByteArray())).readObject(); + return clone; + } + + private static final Field hashtableTableField; + + static { + try { + hashtableTableField = Hashtable.class.getDeclaredField("table"); + hashtableTableField.setAccessible(true); + } catch (NoSuchFieldException e) { + throw new Error(e); + } + } + + public static void main(String[] args) throws Exception { + boolean ok = true; + + System.out.printf("Results:\n" + + " ser. deser.\n" + + " size load lentgh length valid range ok?\n" + + "------- ----- ------- ------- ----------------- ------\n" + ); + + for (int elements : new int[]{10, 50, 500, 5000}) { + for (float loadFactor : new float[]{0.15f, 0.5f, 0.75f, 1.0f, 2.5f}) { + ok &= testDeserializedLength(elements, loadFactor); + } + } + if (!ok) { + throw new AssertionError("Test failed."); + } + } +} From 25c0dd9958db58cd51003e0224e8e7001c25b0e5 Mon Sep 17 00:00:00 2001 From: Srikanth Adayapalam Date: Thu, 22 Jan 2015 09:50:03 +0100 Subject: [PATCH 126/149] 8071310: Tests missing for checkin for JDK-8046977 Reviewed-by: jlahoda --- .../lambda/MethodReferenceGenericTarget.java | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 langtools/test/tools/javac/lambda/MethodReferenceGenericTarget.java diff --git a/langtools/test/tools/javac/lambda/MethodReferenceGenericTarget.java b/langtools/test/tools/javac/lambda/MethodReferenceGenericTarget.java new file mode 100644 index 00000000000..2683d32e840 --- /dev/null +++ b/langtools/test/tools/javac/lambda/MethodReferenceGenericTarget.java @@ -0,0 +1,107 @@ +/* + * 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 8046977 8065303 + * @summary ClassCastException: typing information needed for method reference bridging not preserved + * @author Srikanth + * @run main MethodReferenceGenericTarget + */ + +public class MethodReferenceGenericTarget { + static String result = ""; + + interface ISi { int m(Short a); } + + public static void main(String[] args) { + (new MethodReferenceGenericTarget()).testUnboxObjectToNumberWiden(); + if (!result.equals("7775")) + throw new AssertionError("Incorrect result"); + MethodReferenceTestPrivateTypeConversion.main(null); + new InferenceHookTest().test(); + } + + void foo(ISi q) { + result += q.m((short)75); + } + + public void testUnboxObjectToNumberWiden() { + ISi q = (new E())::xI; + result += q.m((short)77); + // Verify poly invocation context to confirm we handle + // deferred/speculative attribution paths adequately. + foo((new E())::xI); + } + + class E { + private T xI(T t) { return t; } + } +} + +// snippet from https://bugs.openjdk.java.net/browse/JDK-8065303 +class MethodReferenceTestPrivateTypeConversion { + + class MethodReferenceTestTypeConversion_E { + private T xI(T t) { return t; } + } + + interface ISi { int m(Short a); } + + interface ICc { char m(Character a); } + + public void testUnboxObjectToNumberWiden() { + ISi q = (new MethodReferenceTestTypeConversion_E())::xI; + if ((q.m((short)77) != (short)77)) + throw new AssertionError("Incorrect result"); + } + + public void testUnboxObjectToChar() { + ICc q = (new MethodReferenceTestTypeConversion_E())::xI; + if (q.m('@') != '@') + throw new AssertionError("Incorrect result"); + } + + public static void main(String[] args) { + new MethodReferenceTestPrivateTypeConversion().testUnboxObjectToNumberWiden(); + new MethodReferenceTestPrivateTypeConversion().testUnboxObjectToChar(); + } +} + +class InferenceHookTestBase { + X m(Integer i) { return null; } +} + +class InferenceHookTest extends InferenceHookTestBase { + interface SAM1 { + R m(Integer i); + } + + Z g(SAM1 o) { return null; } + + void test() { + String s = g(super::m); + if (s != null) + throw new AssertionError("Incorrect result"); + } +} From d80497254d7bd49858e29c62980f1d7fd20648ca Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Thu, 22 Jan 2015 12:33:05 +0000 Subject: [PATCH 127/149] 8069155: The value of 'KeyStore Type' isn't 'jks' Reviewed-by: xuelei --- jdk/test/sun/security/tools/policytool/i18n.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jdk/test/sun/security/tools/policytool/i18n.sh b/jdk/test/sun/security/tools/policytool/i18n.sh index 536080b6438..ff0f32d4276 100644 --- a/jdk/test/sun/security/tools/policytool/i18n.sh +++ b/jdk/test/sun/security/tools/policytool/i18n.sh @@ -1,5 +1,5 @@ # -# 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 @@ -83,8 +83,9 @@ if [ -f $HOME/.java.policy ]; then exit 1 fi +# The keystore type is set to JKS, to match the type expected by i18n.html ${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -genkeypair -alias hello -dname CN=Hello \ - -storepass changeit -keypass changeit -keystore ks + -storepass changeit -keypass changeit -keystore ks -storetype jks echo changeit > good echo badpass > bad ${TESTJAVA}${FS}bin${FS}policytool ${TESTTOOLVMOPTS} From c692f0d9eb36462bee1c9005ea5e3aeccf06c4c1 Mon Sep 17 00:00:00 2001 From: Xueming Shen Date: Thu, 22 Jan 2015 08:51:45 -0800 Subject: [PATCH 128/149] 8069211: (zipfs) ZipFileSystem creates corrupted zip if entry output stream gets closed more than once To synchronize the write and close methods of the entry output stream Reviewed-by: alanb --- .../classes/jdk/nio/zipfs/ZipFileSystem.java | 16 ++++++++-- jdk/test/jdk/nio/zipfs/ZipFSTester.java | 29 +++++++++++++++++-- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java index b5fec0ebe1f..9480ebc86a4 100644 --- a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java +++ b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 201, 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 @@ -1533,6 +1533,7 @@ class ZipFileSystem extends FileSystem { private CRC32 crc; private Entry e; private long written; + private boolean isClosed = false; EntryOutputStream(Entry e, OutputStream os) throws IOException @@ -1545,9 +1546,14 @@ class ZipFileSystem extends FileSystem { } @Override - public void write(byte b[], int off, int len) throws IOException { + public synchronized void write(byte b[], int off, int len) + throws IOException + { if (e.type != Entry.FILECH) // only from sync ensureOpen(); + if (isClosed) { + throw new IOException("Stream closed"); + } if (off < 0 || len < 0 || off > b.length - len) { throw new IndexOutOfBoundsException(); } else if (len == 0) { @@ -1568,7 +1574,11 @@ class ZipFileSystem extends FileSystem { } @Override - public void close() throws IOException { + public synchronized void close() throws IOException { + if (isClosed) { + return; + } + isClosed = true; // TBD ensureOpen(); switch (e.method) { case METHOD_DEFLATED: diff --git a/jdk/test/jdk/nio/zipfs/ZipFSTester.java b/jdk/test/jdk/nio/zipfs/ZipFSTester.java index 3b54020bcb2..69777e3728f 100644 --- a/jdk/test/jdk/nio/zipfs/ZipFSTester.java +++ b/jdk/test/jdk/nio/zipfs/ZipFSTester.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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,6 +45,7 @@ import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; @@ -67,7 +68,7 @@ import static java.nio.file.StandardCopyOption.*; * * @test * @bug 6990846 7009092 7009085 7015391 7014948 7005986 7017840 7007596 - * 7157656 8002390 7012868 7012856 8015728 8038500 8040059 + * 7157656 8002390 7012868 7012856 8015728 8038500 8040059 8069211 * @summary Test Zip filesystem provider * @run main ZipFSTester * @run main/othervm/java.security.policy=test.policy ZipFSTester @@ -89,6 +90,7 @@ public class ZipFSTester { test2(fs); // more tests } testTime(jarFile); + test8069211(); } static void test0(FileSystem fs) @@ -416,6 +418,29 @@ public class ZipFSTester { Files.delete(fsPath); } + static void test8069211() throws Exception { + // create a new filesystem, copy this file into it + Map env = new HashMap(); + env.put("create", "true"); + Path fsPath = getTempPath(); + try (FileSystem fs = newZipFileSystem(fsPath, env);) { + OutputStream out = Files.newOutputStream(fs.getPath("/foo")); + out.write("hello".getBytes()); + out.close(); + out.close(); + } + try (FileSystem fs = newZipFileSystem(fsPath, new HashMap())) { + if (!Arrays.equals(Files.readAllBytes(fs.getPath("/foo")), + "hello".getBytes())) { + throw new RuntimeException("entry close() failed"); + } + } catch (Exception x) { + throw new RuntimeException("entry close() failed", x); + } finally { + Files.delete(fsPath); + } + } + private static FileSystem newZipFileSystem(Path path, Map env) throws Exception { From 27f201deb894b7a28d7b4e9aebec2c29471758d1 Mon Sep 17 00:00:00 2001 From: Xueming Shen Date: Thu, 22 Jan 2015 12:24:35 -0800 Subject: [PATCH 129/149] 8037394: ZipFileSystem leaks file descriptor when file is not a valid zip file To close the leaking channel as suggested Reviewed-by: alanb --- .../classes/jdk/nio/zipfs/ZipFileSystem.java | 25 +++++++++++++------ .../jdk/nio/zipfs/ZipFileSystemProvider.java | 6 ++--- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java index 9480ebc86a4..896576ebe8e 100644 --- a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java +++ b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java @@ -53,7 +53,6 @@ import java.util.zip.Deflater; import java.util.zip.InflaterInputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.ZipException; -import java.util.zip.ZipError; import static java.lang.Boolean.*; import static jdk.nio.zipfs.ZipConstants.*; import static jdk.nio.zipfs.ZipUtils.*; @@ -119,7 +118,16 @@ class ZipFileSystem extends FileSystem { this.zc = ZipCoder.get(nameEncoding); this.defaultdir = new ZipPath(this, getBytes(defaultDir)); this.ch = Files.newByteChannel(zfpath, READ); - this.cen = initCEN(); + try { + this.cen = initCEN(); + } catch (IOException x) { + try { + this.ch.close(); + } catch (IOException xx) { + x.addSuppressed(xx); + } + throw x; + } } @Override @@ -1058,12 +1066,15 @@ class ZipFileSystem extends FileSystem { int nlen = CENNAM(cen, pos); int elen = CENEXT(cen, pos); int clen = CENCOM(cen, pos); - if ((CENFLG(cen, pos) & 1) != 0) + if ((CENFLG(cen, pos) & 1) != 0) { zerror("invalid CEN header (encrypted entry)"); - if (method != METHOD_STORED && method != METHOD_DEFLATED) + } + if (method != METHOD_STORED && method != METHOD_DEFLATED) { zerror("invalid CEN header (unsupported compression method: " + method + ")"); - if (pos + CENHDR + nlen > limit) + } + if (pos + CENHDR + nlen > limit) { zerror("invalid CEN header (bad header size)"); + } byte[] name = Arrays.copyOfRange(cen, pos + CENHDR, pos + CENHDR + nlen); IndexNode inode = new IndexNode(name, pos); inodes.put(inode, inode); @@ -1609,8 +1620,8 @@ class ZipFileSystem extends FileSystem { } } - static void zerror(String msg) { - throw new ZipError(msg); + static void zerror(String msg) throws ZipException { + throw new ZipException(msg); } // Maxmum number of de/inflater we cache diff --git a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java index 2961bc90129..52063e45a78 100644 --- a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java +++ b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java @@ -36,7 +36,7 @@ import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Set; -import java.util.zip.ZipError; +import java.util.zip.ZipException; import java.util.concurrent.ExecutorService; /* @@ -100,7 +100,7 @@ public class ZipFileSystemProvider extends FileSystemProvider { ZipFileSystem zipfs = null; try { zipfs = new ZipFileSystem(this, path, env); - } catch (ZipError ze) { + } catch (ZipException ze) { String pname = path.toString(); if (pname.endsWith(".zip") || pname.endsWith(".jar")) throw ze; @@ -122,7 +122,7 @@ public class ZipFileSystemProvider extends FileSystemProvider { ensureFile(path); try { return new ZipFileSystem(this, path, env); - } catch (ZipError ze) { + } catch (ZipException ze) { String pname = path.toString(); if (pname.endsWith(".zip") || pname.endsWith(".jar")) throw ze; From b90c35c4cc91d7e90400764308771c1b640ff7e3 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Thu, 22 Jan 2015 13:40:29 -0800 Subject: [PATCH 130/149] 8069414: Rename oracle.accessbridge to jdk.accessbridge Reviewed-by: alanb, ptbrunet, erikj --- modules.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules.xml b/modules.xml index 3195fd55960..c92c3fe37a5 100644 --- a/modules.xml +++ b/modules.xml @@ -737,7 +737,7 @@ sun.awt - oracle.accessbridge + jdk.accessbridge From aca4e46572f95f6258eea8245cc97a5aa84bf41c Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Thu, 22 Jan 2015 13:49:53 -0800 Subject: [PATCH 131/149] 8069414: Rename oracle.accessbridge to jdk.accessbridge Reviewed-by: alanb, ptbrunet, erikj --- jdk/make/src/classes/build/tools/module/ext.modules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/make/src/classes/build/tools/module/ext.modules b/jdk/make/src/classes/build/tools/module/ext.modules index 93b8dd5b00a..ac6b6a2ac2f 100644 --- a/jdk/make/src/classes/build/tools/module/ext.modules +++ b/jdk/make/src/classes/build/tools/module/ext.modules @@ -6,4 +6,4 @@ jdk.localedata jdk.naming.dns jdk.scripting.nashorn jdk.zipfs -oracle.accessbridge +jdk.accessbridge From d5c853c08883147d01db6cf56a91abd504be1d54 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Fri, 23 Jan 2015 09:22:14 +0800 Subject: [PATCH 132/149] 8071313: krb5.conf not read if SCDynamicStore krb5 config is empty Reviewed-by: mullan --- .../sun/security/krb5/SCDynamicStoreConfig.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/SCDynamicStoreConfig.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/SCDynamicStoreConfig.java index f94a1372054..422e9ffbe61 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/SCDynamicStoreConfig.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/SCDynamicStoreConfig.java @@ -113,15 +113,17 @@ public class SCDynamicStoreConfig { @SuppressWarnings("unchecked") private static Hashtable convertNativeConfig( - Hashtable stanzaTable) { + Hashtable stanzaTable) throws IOException { // convert SCDynamicStore realm structure to Java realm structure Hashtable realms = (Hashtable) stanzaTable.get("realms"); - if (realms != null) { - stanzaTable.remove("realms"); - Hashtable realmsTable = convertRealmConfigs(realms); - stanzaTable.put("realms", realmsTable); + if (realms == null || realms.isEmpty()) { + throw new IOException( + "SCDynamicStore contains an empty Kerberos setting"); } + stanzaTable.remove("realms"); + Hashtable realmsTable = convertRealmConfigs(realms); + stanzaTable.put("realms", realmsTable); WrapAllStringInVector(stanzaTable); if (DEBUG) System.out.println("stanzaTable : " + stanzaTable); return stanzaTable; From 3d738985d77b4e85e9af68060d148ad151514451 Mon Sep 17 00:00:00 2001 From: Jamil Nimeh Date: Thu, 22 Jan 2015 20:19:42 -0800 Subject: [PATCH 133/149] 8044860: Vectors and fixed length fields should be verified for allowed sizes Reviewed-by: xuelei --- .../sun/security/ssl/HandshakeMessage.java | 4 +- .../classes/sun/security/ssl/SessionId.java | 17 + .../ssl/ClientHandshaker/LengthCheckTest.java | 814 ++++++++++++++++++ 3 files changed, 834 insertions(+), 1 deletion(-) create mode 100644 jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java index 972f540940c..492d112bc9d 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -243,6 +243,7 @@ static final class ClientHello extends HandshakeMessage { protocolVersion = ProtocolVersion.valueOf(s.getInt8(), s.getInt8()); clnt_random = new RandomCookie(s); sessionId = new SessionId(s.getBytes8()); + sessionId.checkLength(protocolVersion); cipherSuites = new CipherSuiteList(s); compression_methods = s.getBytes8(); if (messageLength() != messageLength) { @@ -355,6 +356,7 @@ class ServerHello extends HandshakeMessage input.getInt8()); svr_random = new RandomCookie(input); sessionId = new SessionId(input.getBytes8()); + sessionId.checkLength(protocolVersion); cipherSuite = CipherSuite.valueOf(input.getInt8(), input.getInt8()); compression_method = (byte)input.getInt8(); if (messageLength() != messageLength) { diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java b/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java index 8725e7d96b3..31a4ab9f2f8 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java @@ -27,6 +27,7 @@ package sun.security.ssl; import java.security.SecureRandom; +import javax.net.ssl.SSLProtocolException; /** * Encapsulates an SSL session ID. SSL Session IDs are not reused by @@ -41,6 +42,7 @@ import java.security.SecureRandom; final class SessionId { + static int MAX_LENGTH = 32; private byte sessionId []; // max 32 bytes /** Constructs a new session ID ... perhaps for a rejoinable session */ @@ -114,4 +116,19 @@ class SessionId } return true; } + + /** + * Checks the length of the session ID to make sure it sits within + * the range called out in the specification + */ + void checkLength(ProtocolVersion pv) throws SSLProtocolException { + // As of today all versions of TLS have a 32-byte maximum length. + // In the future we can do more here to support protocol versions + // that may have longer max lengths. + if (sessionId.length > MAX_LENGTH) { + throw new SSLProtocolException("Invalid session ID length (" + + sessionId.length + " bytes)"); + } + } + } diff --git a/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java b/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java new file mode 100644 index 00000000000..2d4940ac378 --- /dev/null +++ b/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java @@ -0,0 +1,814 @@ +/* + * 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 8044860 + * @summary Vectors and fixed length fields should be verified + * for allowed sizes. + * @run main/othervm LengthCheckTest + */ + +/** + * A SSLEngine usage example which simplifies the presentation + * by removing the I/O and multi-threading concerns. + * + * The test creates two SSLEngines, simulating a client and server. + * The "transport" layer consists two byte buffers: think of them + * as directly connected pipes. + * + * Note, this is a *very* simple example: real code will be much more + * involved. For example, different threading and I/O models could be + * used, transport mechanisms could close unexpectedly, and so on. + * + * When this application runs, notice that several messages + * (wrap/unwrap) pass before any application data is consumed or + * produced. (For more information, please see the SSL/TLS + * specifications.) There may several steps for a successful handshake, + * so it's typical to see the following series of operations: + * + * client server message + * ====== ====== ======= + * wrap() ... ClientHello + * ... unwrap() ClientHello + * ... wrap() ServerHello/Certificate + * unwrap() ... ServerHello/Certificate + * wrap() ... ClientKeyExchange + * wrap() ... ChangeCipherSpec + * wrap() ... Finished + * ... unwrap() ClientKeyExchange + * ... unwrap() ChangeCipherSpec + * ... unwrap() Finished + * ... wrap() ChangeCipherSpec + * ... wrap() Finished + * unwrap() ... ChangeCipherSpec + * unwrap() ... Finished + */ + +import javax.net.ssl.*; +import javax.net.ssl.SSLEngineResult.*; +import java.io.*; +import java.security.*; +import java.nio.*; +import java.util.List; +import java.util.ArrayList; +import sun.security.ssl.ProtocolVersion; + +public class LengthCheckTest { + + /* + * Enables logging of the SSLEngine operations. + */ + private static final boolean logging = true; + + /* + * Enables the JSSE system debugging system property: + * + * -Djavax.net.debug=all + * + * This gives a lot of low-level information about operations underway, + * including specific handshake messages, and might be best examined + * after gaining some familiarity with this application. + */ + private static final boolean debug = false; + private static final boolean dumpBufs = true; + + private final SSLContext sslc; + + private SSLEngine clientEngine; // client Engine + private ByteBuffer clientOut; // write side of clientEngine + private ByteBuffer clientIn; // read side of clientEngine + + private SSLEngine serverEngine; // server Engine + private ByteBuffer serverOut; // write side of serverEngine + private ByteBuffer serverIn; // read side of serverEngine + + private HandshakeTest handshakeTest; + + /* + * For data transport, this example uses local ByteBuffers. This + * isn't really useful, but the purpose of this example is to show + * SSLEngine concepts, not how to do network transport. + */ + private ByteBuffer cTOs; // "reliable" transport client->server + private ByteBuffer sTOc; // "reliable" transport server->client + + /* + * The following is to set up the keystores. + */ + private static final String pathToStores = "../../../../javax/net/ssl/etc"; + private static final String keyStoreFile = "keystore"; + private static final String trustStoreFile = "truststore"; + private static final String passwd = "passphrase"; + + private static final String keyFilename = + System.getProperty("test.src", ".") + "/" + pathToStores + + "/" + keyStoreFile; + private static final String trustFilename = + System.getProperty("test.src", ".") + "/" + pathToStores + + "/" + trustStoreFile; + + // Define a few basic TLS record and message types we might need + private static final int TLS_RECTYPE_CCS = 0x14; + private static final int TLS_RECTYPE_ALERT = 0x15; + private static final int TLS_RECTYPE_HANDSHAKE = 0x16; + private static final int TLS_RECTYPE_APPDATA = 0x17; + + private static final int TLS_HS_HELLO_REQUEST = 0x00; + private static final int TLS_HS_CLIENT_HELLO = 0x01; + private static final int TLS_HS_SERVER_HELLO = 0x02; + private static final int TLS_HS_CERTIFICATE = 0x0B; + private static final int TLS_HS_SERVER_KEY_EXCHG = 0x0C; + private static final int TLS_HS_CERT_REQUEST = 0x0D; + private static final int TLS_HS_SERVER_HELLO_DONE = 0x0E; + private static final int TLS_HS_CERT_VERIFY = 0x0F; + private static final int TLS_HS_CLIENT_KEY_EXCHG = 0x10; + private static final int TLS_HS_FINISHED = 0x14; + + // We're not going to define all the alert types in TLS, just + // the ones we think we'll need to reference by name. + private static final int TLS_ALERT_LVL_WARNING = 0x01; + private static final int TLS_ALERT_LVL_FATAL = 0x02; + + private static final int TLS_ALERT_UNEXPECTED_MSG = 0x0A; + private static final int TLS_ALERT_HANDSHAKE_FAILURE = 0x28; + private static final int TLS_ALERT_INTERNAL_ERROR = 0x50; + + public interface HandshakeTest { + void execTest() throws Exception; + } + + public final HandshakeTest servSendLongID = new HandshakeTest() { + @Override + public void execTest() throws Exception { + boolean gotException = false; + SSLEngineResult clientResult; // results from client's last op + SSLEngineResult serverResult; // results from server's last op + + log("\n==== Test: Client receives 64-byte session ID ===="); + + // Send Client Hello + clientResult = clientEngine.wrap(clientOut, cTOs); + log("client wrap: ", clientResult); + runDelegatedTasks(clientResult, clientEngine); + cTOs.flip(); + dumpByteBuffer("CLIENT-TO-SERVER", cTOs); + + // Server consumes Client Hello + serverResult = serverEngine.unwrap(cTOs, serverIn); + log("server unwrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + cTOs.compact(); + + // Server generates ServerHello/Cert/Done record + serverResult = serverEngine.wrap(serverOut, sTOc); + log("server wrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + sTOc.flip(); + + // Intercept the ServerHello messages and instead send + // one that has a 64-byte session ID. + if (isTlsMessage(sTOc, TLS_RECTYPE_HANDSHAKE, + TLS_HS_SERVER_HELLO)) { + ArrayList recList = splitRecord(sTOc); + + // Use the original ServerHello as a template to craft one + // with a longer-than-allowed session ID. + ByteBuffer servHelloBuf = + createEvilServerHello(recList.get(0), 64); + + recList.set(0, servHelloBuf); + + // Now send each ByteBuffer (each being a complete + // TLS record) into the client-side unwrap. + for (ByteBuffer bBuf : recList) { + dumpByteBuffer("SERVER-TO-CLIENT", bBuf); + try { + clientResult = clientEngine.unwrap(bBuf, clientIn); + } catch (SSLProtocolException e) { + log("Received expected SSLProtocolException: " + e); + gotException = true; + } + log("client unwrap: ", clientResult); + runDelegatedTasks(clientResult, clientEngine); + } + } else { + dumpByteBuffer("SERVER-TO-CLIENT", sTOc); + log("client unwrap: ", clientResult); + runDelegatedTasks(clientResult, clientEngine); + } + sTOc.compact(); + + // The Client should now send a TLS Alert + clientResult = clientEngine.wrap(clientOut, cTOs); + log("client wrap: ", clientResult); + runDelegatedTasks(clientResult, clientEngine); + cTOs.flip(); + dumpByteBuffer("CLIENT-TO-SERVER", cTOs); + + // At this point we can verify that both an exception + // was thrown and the proper action (a TLS alert) was + // sent back to the server. + if (gotException == false || + !isTlsMessage(cTOs, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL, + TLS_ALERT_INTERNAL_ERROR)) { + throw new SSLException( + "Client failed to throw Alert:fatal:internal_error"); + } + } + }; + + public final HandshakeTest clientSendLongID = new HandshakeTest() { + @Override + public void execTest() throws Exception { + boolean gotException = false; + SSLEngineResult clientResult; // results from client's last op + SSLEngineResult serverResult; // results from server's last op + + log("\n==== Test: Server receives 64-byte session ID ===="); + + // Send Client Hello + ByteBuffer evilClientHello = createEvilClientHello(64); + dumpByteBuffer("CLIENT-TO-SERVER", evilClientHello); + + try { + // Server consumes Client Hello + serverResult = serverEngine.unwrap(evilClientHello, serverIn); + log("server unwrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + evilClientHello.compact(); + + // Under normal circumstances this should be a ServerHello + // But should throw an exception instead due to the invalid + // session ID. + serverResult = serverEngine.wrap(serverOut, sTOc); + log("server wrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + sTOc.flip(); + dumpByteBuffer("SERVER-TO-CLIENT", sTOc); + } catch (SSLProtocolException ssle) { + log("Received expected SSLProtocolException: " + ssle); + gotException = true; + } + + // We expect to see the server generate an alert here + serverResult = serverEngine.wrap(serverOut, sTOc); + log("server wrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + sTOc.flip(); + dumpByteBuffer("SERVER-TO-CLIENT", sTOc); + + // At this point we can verify that both an exception + // was thrown and the proper action (a TLS alert) was + // sent back to the client. + if (gotException == false || + !isTlsMessage(sTOc, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL, + TLS_ALERT_INTERNAL_ERROR)) { + throw new SSLException( + "Server failed to throw Alert:fatal:internal_error"); + } + } + }; + + + /* + * Main entry point for this test. + */ + public static void main(String args[]) throws Exception { + List ccsTests = new ArrayList<>(); + + if (debug) { + System.setProperty("javax.net.debug", "ssl"); + } + + ccsTests.add(new LengthCheckTest("ServSendLongID")); + ccsTests.add(new LengthCheckTest("ClientSendLongID")); + + for (LengthCheckTest test : ccsTests) { + test.runTest(); + } + + System.out.println("Test Passed."); + } + + /* + * Create an initialized SSLContext to use for these tests. + */ + public LengthCheckTest(String testName) throws Exception { + + KeyStore ks = KeyStore.getInstance("JKS"); + KeyStore ts = KeyStore.getInstance("JKS"); + + char[] passphrase = "passphrase".toCharArray(); + + ks.load(new FileInputStream(keyFilename), passphrase); + ts.load(new FileInputStream(trustFilename), passphrase); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, passphrase); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ts); + + SSLContext sslCtx = SSLContext.getInstance("TLS"); + + sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + + sslc = sslCtx; + + switch (testName) { + case "ServSendLongID": + handshakeTest = servSendLongID; + break; + case "ClientSendLongID": + handshakeTest = clientSendLongID; + break; + default: + throw new IllegalArgumentException("Unknown test name: " + + testName); + } + } + + /* + * Run the test. + * + * Sit in a tight loop, both engines calling wrap/unwrap regardless + * of whether data is available or not. We do this until both engines + * report back they are closed. + * + * The main loop handles all of the I/O phases of the SSLEngine's + * lifetime: + * + * initial handshaking + * application data transfer + * engine closing + * + * One could easily separate these phases into separate + * sections of code. + */ + private void runTest() throws Exception { + boolean dataDone = false; + + createSSLEngines(); + createBuffers(); + + handshakeTest.execTest(); + } + + /* + * Using the SSLContext created during object creation, + * create/configure the SSLEngines we'll use for this test. + */ + private void createSSLEngines() throws Exception { + /* + * Configure the serverEngine to act as a server in the SSL/TLS + * handshake. Also, require SSL client authentication. + */ + serverEngine = sslc.createSSLEngine(); + serverEngine.setUseClientMode(false); + serverEngine.setNeedClientAuth(false); + + /* + * Similar to above, but using client mode instead. + */ + clientEngine = sslc.createSSLEngine("client", 80); + clientEngine.setUseClientMode(true); + + // In order to make a test that will be backwards compatible + // going back to JDK 5, force the handshake to be TLS 1.0 and + // use one of the older cipher suites. + clientEngine.setEnabledProtocols(new String[]{"TLSv1"}); + clientEngine.setEnabledCipherSuites( + new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"}); + } + + /* + * Create and size the buffers appropriately. + */ + private void createBuffers() { + + /* + * We'll assume the buffer sizes are the same + * between client and server. + */ + SSLSession session = clientEngine.getSession(); + int appBufferMax = session.getApplicationBufferSize(); + int netBufferMax = session.getPacketBufferSize(); + + /* + * We'll make the input buffers a bit bigger than the max needed + * size, so that unwrap()s following a successful data transfer + * won't generate BUFFER_OVERFLOWS. + * + * We'll use a mix of direct and indirect ByteBuffers for + * tutorial purposes only. In reality, only use direct + * ByteBuffers when they give a clear performance enhancement. + */ + clientIn = ByteBuffer.allocate(appBufferMax + 50); + serverIn = ByteBuffer.allocate(appBufferMax + 50); + + cTOs = ByteBuffer.allocateDirect(netBufferMax); + sTOc = ByteBuffer.allocateDirect(netBufferMax); + + clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); + serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); + } + + /* + * If the result indicates that we have outstanding tasks to do, + * go ahead and run them in this thread. + */ + private static void runDelegatedTasks(SSLEngineResult result, + SSLEngine engine) throws Exception { + + if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { + Runnable runnable; + while ((runnable = engine.getDelegatedTask()) != null) { + log("\trunning delegated task..."); + runnable.run(); + } + HandshakeStatus hsStatus = engine.getHandshakeStatus(); + if (hsStatus == HandshakeStatus.NEED_TASK) { + throw new Exception( + "handshake shouldn't need additional tasks"); + } + log("\tnew HandshakeStatus: " + hsStatus); + } + } + + private static boolean isEngineClosed(SSLEngine engine) { + return (engine.isOutboundDone() && engine.isInboundDone()); + } + + /* + * Simple check to make sure everything came across as expected. + */ + private static void checkTransfer(ByteBuffer a, ByteBuffer b) + throws Exception { + a.flip(); + b.flip(); + + if (!a.equals(b)) { + throw new Exception("Data didn't transfer cleanly"); + } else { + log("\tData transferred cleanly"); + } + + a.position(a.limit()); + b.position(b.limit()); + a.limit(a.capacity()); + b.limit(b.capacity()); + } + + /* + * Logging code + */ + private static boolean resultOnce = true; + + private static void log(String str, SSLEngineResult result) { + if (!logging) { + return; + } + if (resultOnce) { + resultOnce = false; + System.out.println("The format of the SSLEngineResult is: \n" + + "\t\"getStatus() / getHandshakeStatus()\" +\n" + + "\t\"bytesConsumed() / bytesProduced()\"\n"); + } + HandshakeStatus hsStatus = result.getHandshakeStatus(); + log(str + + result.getStatus() + "/" + hsStatus + ", " + + result.bytesConsumed() + "/" + result.bytesProduced() + + " bytes"); + if (hsStatus == HandshakeStatus.FINISHED) { + log("\t...ready for application data"); + } + } + + private static void log(String str) { + if (logging) { + System.out.println(str); + } + } + + /** + * Split a record consisting of multiple TLS handshake messages + * into individual TLS records, each one in a ByteBuffer of its own. + * + * @param tlsRecord A ByteBuffer containing the tls record data. + * The position of the buffer should be at the first byte + * in the TLS record data. + * + * @return An ArrayList consisting of one or more ByteBuffers. Each + * ByteBuffer will contain a single TLS record with one message. + * That message will be taken from the input record. The order + * of the messages in the ArrayList will be the same as they + * were in the input record. + */ + private ArrayList splitRecord(ByteBuffer tlsRecord) { + SSLSession session = clientEngine.getSession(); + int netBufferMax = session.getPacketBufferSize(); + ArrayList recordList = new ArrayList<>(); + + if (tlsRecord.hasRemaining()) { + int type = Byte.toUnsignedInt(tlsRecord.get()); + byte ver_major = tlsRecord.get(); + byte ver_minor = tlsRecord.get(); + int recLen = Short.toUnsignedInt(tlsRecord.getShort()); + byte[] newMsgData = null; + while (tlsRecord.hasRemaining()) { + ByteBuffer newRecord = ByteBuffer.allocateDirect(netBufferMax); + switch (type) { + case TLS_RECTYPE_CCS: + case TLS_RECTYPE_ALERT: + case TLS_RECTYPE_APPDATA: + // None of our tests have multiple non-handshake + // messages coalesced into a single record. + break; + case TLS_RECTYPE_HANDSHAKE: + newMsgData = getHandshakeMessage(tlsRecord); + break; + } + + // Put a new TLS record on the destination ByteBuffer + newRecord.put((byte)type); + newRecord.put(ver_major); + newRecord.put(ver_minor); + newRecord.putShort((short)newMsgData.length); + + // Now add the message content itself and attach to the + // returned ArrayList + newRecord.put(newMsgData); + newRecord.flip(); + recordList.add(newRecord); + } + } + + return recordList; + } + + private static ByteBuffer createEvilClientHello(int sessIdLen) { + ByteBuffer newRecord = ByteBuffer.allocateDirect(4096); + + // Lengths will initially be place holders until we determine the + // finished length of the ByteBuffer. Then we'll go back and scribble + // in the correct lengths. + + newRecord.put((byte)TLS_RECTYPE_HANDSHAKE); // Record type + newRecord.putShort((short)0x0301); // Protocol (TLS 1.0) + newRecord.putShort((short)0); // Length place holder + + newRecord.putInt(TLS_HS_CLIENT_HELLO << 24); // HS type and length + newRecord.putShort((short)0x0301); + newRecord.putInt((int)(System.currentTimeMillis() / 1000)); + SecureRandom sr = new SecureRandom(); + byte[] randBuf = new byte[28]; + sr.nextBytes(randBuf); + newRecord.put(randBuf); // Client Random + newRecord.put((byte)sessIdLen); // Session ID length + if (sessIdLen > 0) { + byte[] sessId = new byte[sessIdLen]; + sr.nextBytes(sessId); + newRecord.put(sessId); // Session ID + } + newRecord.putShort((short)2); // 2 bytes of ciphers + newRecord.putShort((short)0x002F); // TLS_RSA_AES_CBC_SHA + newRecord.putShort((short)0x0100); // only null compression + newRecord.putShort((short)5); // 5 bytes of extensions + newRecord.putShort((short)0xFF01); // Renegotiation info + newRecord.putShort((short)1); + newRecord.put((byte)0); // No reneg info exts + + // Go back and fill in the correct length values for the record + // and handshake message headers. + int recordLength = newRecord.position(); + newRecord.putShort(3, (short)(recordLength - 5)); + int newTypeAndLen = (newRecord.getInt(5) & 0xFF000000) | + ((recordLength - 9) & 0x00FFFFFF); + newRecord.putInt(5, newTypeAndLen); + + newRecord.flip(); + return newRecord; + } + + private static ByteBuffer createEvilServerHello(ByteBuffer origHello, + int newSessIdLen) { + if (newSessIdLen < 0 || newSessIdLen > Byte.MAX_VALUE) { + throw new RuntimeException("Length must be 0 <= X <= 127"); + } + + ByteBuffer newRecord = ByteBuffer.allocateDirect(4096); + // Copy the bytes from the old hello to the new up to the session ID + // field. We will go back later and fill in a new length field in + // the record header. This includes the record header (5 bytes), the + // Handshake message header (4 bytes), protocol version (2 bytes), + // and the random (32 bytes). + ByteBuffer scratchBuffer = origHello.slice(); + scratchBuffer.limit(43); + newRecord.put(scratchBuffer); + + // Advance the position in the originial hello buffer past the + // session ID. + origHello.position(43); + int origIDLen = Byte.toUnsignedInt(origHello.get()); + if (origIDLen > 0) { + // Skip over the session ID + origHello.position(origHello.position() + origIDLen); + } + + // Now add our own sessionID to the new record + SecureRandom sr = new SecureRandom(); + byte[] sessId = new byte[newSessIdLen]; + sr.nextBytes(sessId); + newRecord.put((byte)newSessIdLen); + newRecord.put(sessId); + + // Create another slice in the original buffer, based on the position + // past the session ID. Copy the remaining bytes into the new + // hello buffer. Then go back and fix up the length + newRecord.put(origHello.slice()); + + // Go back and fill in the correct length values for the record + // and handshake message headers. + int recordLength = newRecord.position(); + newRecord.putShort(3, (short)(recordLength - 5)); + int newTypeAndLen = (newRecord.getInt(5) & 0xFF000000) | + ((recordLength - 9) & 0x00FFFFFF); + newRecord.putInt(5, newTypeAndLen); + + newRecord.flip(); + return newRecord; + } + + /** + * Look at an incoming TLS record and see if it is the desired + * record type, and where appropriate the correct subtype. + * + * @param srcRecord The input TLS record to be evaluated. This + * method will only look at the leading message if multiple + * TLS handshake messages are coalesced into a single record. + * @param reqRecType The requested TLS record type + * @param recParams Zero or more integer sub type fields. For CCS + * and ApplicationData, no params are used. For handshake records, + * one value corresponding to the HandshakeType is required. + * For Alerts, two values corresponding to AlertLevel and + * AlertDescription are necessary. + * + * @return true if the proper handshake message is the first one + * in the input record, false otherwise. + */ + private boolean isTlsMessage(ByteBuffer srcRecord, int reqRecType, + int... recParams) { + boolean foundMsg = false; + + if (srcRecord.hasRemaining()) { + srcRecord.mark(); + + // Grab the fields from the TLS Record + int recordType = Byte.toUnsignedInt(srcRecord.get()); + byte ver_major = srcRecord.get(); + byte ver_minor = srcRecord.get(); + int recLen = Short.toUnsignedInt(srcRecord.getShort()); + + if (recordType == reqRecType) { + // For any zero-length recParams, making sure the requested + // type is sufficient. + if (recParams.length == 0) { + foundMsg = true; + } else { + switch (recordType) { + case TLS_RECTYPE_CCS: + case TLS_RECTYPE_APPDATA: + // We really shouldn't find ourselves here, but + // if someone asked for these types and had more + // recParams we can ignore them. + foundMsg = true; + break; + case TLS_RECTYPE_ALERT: + // Needs two params, AlertLevel and AlertDescription + if (recParams.length != 2) { + throw new RuntimeException( + "Test for Alert requires level and desc."); + } else { + int level = Byte.toUnsignedInt(srcRecord.get()); + int desc = Byte.toUnsignedInt(srcRecord.get()); + if (level == recParams[0] && + desc == recParams[1]) { + foundMsg = true; + } + } + break; + case TLS_RECTYPE_HANDSHAKE: + // Needs one parameter, HandshakeType + if (recParams.length != 1) { + throw new RuntimeException( + "Test for Handshake requires only HS type"); + } else { + // Go into the first handhshake message in the + // record and grab the handshake message header. + // All we need to do is parse out the leading + // byte. + int msgHdr = srcRecord.getInt(); + int msgType = (msgHdr >> 24) & 0x000000FF; + if (msgType == recParams[0]) { + foundMsg = true; + } + } + break; + } + } + } + + srcRecord.reset(); + } + + return foundMsg; + } + + private byte[] getHandshakeMessage(ByteBuffer srcRecord) { + // At the start of this routine, the position should be lined up + // at the first byte of a handshake message. Mark this location + // so we can return to it after reading the type and length. + srcRecord.mark(); + int msgHdr = srcRecord.getInt(); + int type = (msgHdr >> 24) & 0x000000FF; + int length = msgHdr & 0x00FFFFFF; + + // Create a byte array that has enough space for the handshake + // message header and body. + byte[] data = new byte[length + 4]; + srcRecord.reset(); + srcRecord.get(data, 0, length + 4); + + return (data); + } + + /** + * Hex-dumps a ByteBuffer to stdout. + */ + private static void dumpByteBuffer(String header, ByteBuffer bBuf) { + if (dumpBufs == false) { + return; + } + + int bufLen = bBuf.remaining(); + if (bufLen > 0) { + bBuf.mark(); + + // We expect the position of the buffer to be at the + // beginning of a TLS record. Get the type, version and length. + int type = Byte.toUnsignedInt(bBuf.get()); + int ver_major = Byte.toUnsignedInt(bBuf.get()); + int ver_minor = Byte.toUnsignedInt(bBuf.get()); + int recLen = Short.toUnsignedInt(bBuf.getShort()); + ProtocolVersion pv = ProtocolVersion.valueOf(ver_major, ver_minor); + + log("===== " + header + " (" + tlsRecType(type) + " / " + + pv + " / " + bufLen + " bytes) ====="); + bBuf.reset(); + for (int i = 0; i < bufLen; i++) { + if (i != 0 && i % 16 == 0) { + System.out.print("\n"); + } + System.out.format("%02X ", bBuf.get(i)); + } + log("\n==============================================="); + bBuf.reset(); + } + } + + private static String tlsRecType(int type) { + switch (type) { + case 20: + return "Change Cipher Spec"; + case 21: + return "Alert"; + case 22: + return "Handshake"; + case 23: + return "Application Data"; + default: + return ("Unknown (" + type + ")"); + } + } +} From af3db6d31aa50563dda37cb90acf8ff14e663692 Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Fri, 23 Jan 2015 13:57:02 +0300 Subject: [PATCH 134/149] 8067748: (process) Child is terminated when parent's console is closed [win] Reviewed-by: alanb --- .../windows/native/libjava/ProcessImpl_md.c | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/jdk/src/java.base/windows/native/libjava/ProcessImpl_md.c b/jdk/src/java.base/windows/native/libjava/ProcessImpl_md.c index 59f907cd99b..51e24a01129 100644 --- a/jdk/src/java.base/windows/native/libjava/ProcessImpl_md.c +++ b/jdk/src/java.base/windows/native/libjava/ProcessImpl_md.c @@ -283,14 +283,10 @@ static jlong processCreate( FALSE, FALSE, FALSE, FALSE, FALSE, FALSE}; - { - /* Extraction of current process standard IOE handles */ - DWORD idsIOE[3] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE}; - int i; - for (i = 0; i < 3; ++i) - /* Should not be closed by CloseHandle! */ - stdIOE[i] = GetStdHandle(idsIOE[i]); - } + /* These three should not be closed by CloseHandle! */ + stdIOE[0] = GetStdHandle(STD_INPUT_HANDLE); + stdIOE[1] = GetStdHandle(STD_OUTPUT_HANDLE); + stdIOE[2] = GetStdHandle(STD_ERROR_HANDLE); prepareIOEHandleState(stdIOE, inherit); { @@ -319,11 +315,16 @@ static jlong processCreate( if (success) { PROCESS_INFORMATION pi; - DWORD processFlag = CREATE_UNICODE_ENVIRONMENT; + DWORD processFlag = CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; - /* Suppress popping-up of a console window for non-console applications */ - if (GetConsoleWindow() == NULL) - processFlag |= CREATE_NO_WINDOW; + /* If the standard I/O is inherited, CREATE_NO_WINDOW must not be used. */ + if (GetConsoleWindow() != NULL && + (si.hStdInput == stdIOE[0] || + si.hStdOutput == stdIOE[1] || + si.hStdError == (redirectErrorStream ? stdIOE[1] : stdIOE[2]))) + { + processFlag &= ~CREATE_NO_WINDOW; + } si.dwFlags = STARTF_USESTDHANDLES; if (!CreateProcessW( From e70362babad4c2379a9cc9eaa84d62f3a1fbaad7 Mon Sep 17 00:00:00 2001 From: Konstantin Shefov Date: Fri, 23 Jan 2015 15:42:06 +0300 Subject: [PATCH 135/149] 6933879: URISyntaxException when non-alphanumeric characters are present in scope_id Reviewed-by: chegar --- jdk/src/java.base/share/classes/java/net/URI.java | 7 ++++++- jdk/test/java/net/URI/Test.java | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/net/URI.java b/jdk/src/java.base/share/classes/java/net/URI.java index e5bc8937d75..89a9d50e52a 100644 --- a/jdk/src/java.base/share/classes/java/net/URI.java +++ b/jdk/src/java.base/share/classes/java/net/URI.java @@ -2637,6 +2637,11 @@ public final class URI private static final long H_URIC_NO_SLASH = H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,"); + // scope_id = alpha | digit | "_" | "." + private static final long L_SCOPE_ID + = L_ALPHANUM | lowMask("_."); + private static final long H_SCOPE_ID + = H_ALPHANUM | highMask("_."); // -- Escaping and encoding -- @@ -3226,7 +3231,7 @@ public final class URI if (r+1 == q) { fail ("scope id expected"); } - checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM, + checkChars (r+1, q, L_SCOPE_ID, H_SCOPE_ID, "scope id"); } else { parseIPv6Reference(p, q); diff --git a/jdk/test/java/net/URI/Test.java b/jdk/test/java/net/URI/Test.java index 8e0e9247acd..fd7927b2497 100644 --- a/jdk/test/java/net/URI/Test.java +++ b/jdk/test/java/net/URI/Test.java @@ -24,7 +24,7 @@ /* @test * @summary Unit test for java.net.URI * @bug 4464135 4505046 4503239 4438319 4991359 4866303 7023363 7041800 - * 7171415 + * 7171415 6933879 * @author Mark Reinhold */ @@ -1600,6 +1600,7 @@ public class Test { static void bugs() { b6339649(); + b6933879(); b8037396(); } @@ -1614,6 +1615,18 @@ public class Test { } } + // 6933879 - check that "." and "_" characters are allowed in IPv6 scope_id. + private static void b6933879() { + final String HOST = "fe80::c00:16fe:cebe:3214%eth1.12_55"; + URI uri; + try { + uri = new URI("http", null, HOST, 10, "/", null, null); + } catch (URISyntaxException ex) { + throw new AssertionError("Should not happen", ex); + } + eq("[" + HOST + "]", uri.getHost()); + } + private static void b8037396() { // primary checks: From edc2052f33353ad3a4e01a883ba58691716cf07b Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Fri, 23 Jan 2015 15:14:53 +0100 Subject: [PATCH 136/149] 8069254: Warning issued despite @SafeVarargs annotation on constructor The Symbol created for diamond inference does not have annotations attached - need to look for @SafeVarargs on the underlying constructor's Symbol. Reviewed-by: mcimadamore --- .../com/sun/tools/javac/comp/Check.java | 4 +- .../tools/javac/varargs/warning/Warn6.java | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 langtools/test/tools/javac/varargs/warning/Warn6.java diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 4d3774fbf29..6f838f4542e 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, 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 @@ -898,7 +898,7 @@ public class Check { Type argtype = owntype.getParameterTypes().last(); if (!types.isReifiable(argtype) && (!allowSimplifiedVarargs || - sym.attribute(syms.trustMeType.tsym) == null || + sym.baseSymbol().attribute(syms.trustMeType.tsym) == null || !isTrustMeAllowedOnMethod(sym))) { warnUnchecked(env.tree.pos(), "unchecked.generic.array.creation", diff --git a/langtools/test/tools/javac/varargs/warning/Warn6.java b/langtools/test/tools/javac/varargs/warning/Warn6.java new file mode 100644 index 00000000000..1d6f525c4cf --- /dev/null +++ b/langtools/test/tools/javac/varargs/warning/Warn6.java @@ -0,0 +1,43 @@ +/* + * 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 8069254 + * @summary Ensure the generic array creation warning is not incorrectly produced for diamonds + * @compile -Xlint:unchecked -Werror Warn6.java + */ + +public class Warn6 { + @SafeVarargs + public Warn6(T... args) { + } + + public static void main(String[] args) { + Iterable i = null; + + Warn6> foo2 = new Warn6<>(i, i); + Warn6> foo3 = new Warn6>(i, i); + } +} + From 0d7e8b7cf127409f514b122539b33075e31a0a56 Mon Sep 17 00:00:00 2001 From: Sean Coffey Date: Fri, 23 Jan 2015 15:03:47 +0000 Subject: [PATCH 137/149] 8065994: HTTP Tunnel connection to NTLM proxy reauthenticates instead of using keep-alive Reviewed-by: chegar --- .../net/www/protocol/https/HttpsClient.java | 36 +++++++++---------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java index 19a2010fa0b..30e9fb0840a 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java @@ -192,22 +192,6 @@ final class HttpsClient extends HttpClient return userAgent; } - // should remove once HttpClient.newHttpProxy is putback - private static Proxy newHttpProxy(String proxyHost, int proxyPort) { - InetSocketAddress saddr = null; - final String phost = proxyHost; - final int pport = proxyPort < 0 ? httpsPortNumber : proxyPort; - try { - saddr = java.security.AccessController.doPrivileged(new - java.security.PrivilegedExceptionAction() { - public InetSocketAddress run() { - return new InetSocketAddress(phost, pport); - }}); - } catch (java.security.PrivilegedActionException pae) { - } - return new Proxy(Proxy.Type.HTTP, saddr); - } - // CONSTRUCTOR, FACTORY @@ -251,7 +235,7 @@ final class HttpsClient extends HttpClient throws IOException { this(sf, url, (proxyHost == null? null: - HttpsClient.newHttpProxy(proxyHost, proxyPort)), + HttpClient.newHttpProxy(proxyHost, proxyPort, "https")), connectTimeout); } @@ -261,6 +245,11 @@ final class HttpsClient extends HttpClient HttpsClient(SSLSocketFactory sf, URL url, Proxy proxy, int connectTimeout) throws IOException { + PlatformLogger logger = HttpURLConnection.getHttpLogger(); + if (logger.isLoggable(PlatformLogger.Level.FINEST)) { + logger.finest("Creating new HttpsClient with url:" + url + " and proxy:" + proxy + + " with connect timeout:" + connectTimeout); + } this.proxy = proxy; setSSLSocketFactory(sf); this.proxyDisabled = true; @@ -317,7 +306,7 @@ final class HttpsClient extends HttpClient return HttpsClient.New(sf, url, hv, (proxyHost == null? null : - HttpsClient.newHttpProxy(proxyHost, proxyPort)), + HttpClient.newHttpProxy(proxyHost, proxyPort, "https")), useCache, connectTimeout, httpuc); } @@ -329,6 +318,11 @@ final class HttpsClient extends HttpClient if (p == null) { p = Proxy.NO_PROXY; } + PlatformLogger logger = HttpURLConnection.getHttpLogger(); + if (logger.isLoggable(PlatformLogger.Level.FINEST)) { + logger.finest("Looking for HttpClient for URL " + url + + " and proxy value of " + p); + } HttpsClient ret = null; if (useCache) { /* see if one's already around */ @@ -342,14 +336,13 @@ final class HttpsClient extends HttpClient if (ret != null) { if ((ret.proxy != null && ret.proxy.equals(p)) || - (ret.proxy == null && p == null)) { + (ret.proxy == null && p == Proxy.NO_PROXY)) { synchronized (ret) { ret.cachedHttpClient = true; assert ret.inCache; ret.inCache = false; if (httpuc != null && ret.needsTunneling()) httpuc.setTunnelState(TUNNELING); - PlatformLogger logger = HttpURLConnection.getHttpLogger(); if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("KeepAlive stream retrieved from the cache, " + ret); } @@ -360,6 +353,9 @@ final class HttpsClient extends HttpClient // This should be fine as it is very rare that a connection // to the same host will not use the same proxy. synchronized(ret) { + if (logger.isLoggable(PlatformLogger.Level.FINEST)) { + logger.finest("Not returning this connection to cache: " + ret); + } ret.inCache = false; ret.closeServer(); } From 1059b1665d8164d7237f6dddf8380f8c8b79f702 Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Fri, 23 Jan 2015 16:16:39 +0000 Subject: [PATCH 138/149] 8069262: Doclint regression in java.nio.channels.Channels Reviewed-by: darcy --- .../share/classes/java/nio/channels/Channels.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/nio/channels/Channels.java b/jdk/src/java.base/share/classes/java/nio/channels/Channels.java index 1325374755f..20a8cdd476d 100644 --- a/jdk/src/java.base/share/classes/java/nio/channels/Channels.java +++ b/jdk/src/java.base/share/classes/java/nio/channels/Channels.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, 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 @@ -579,12 +579,13 @@ public final class Channels { * charset and writes the resulting bytes to the given channel. * *

An invocation of this method of the form - *

+ * *

 {@code
      *     Channels.newWriter(ch, csname)
      * } 
+ * * behaves in exactly the same way as the expression - *

+ * *

 {@code
      *     Channels.newWriter(ch, Charset.forName(csName).newEncoder(), -1)
      * } 
From 2a29bb3be6f9abb8ee46b547a7616a064fb3e064 Mon Sep 17 00:00:00 2001 From: Bradford Wetmore Date: Fri, 23 Jan 2015 10:31:15 -0800 Subject: [PATCH 139/149] 8069038: javax/net/ssl/TLS/TLSClientPropertyTest.java needs to be updated for JDK-8061210 Reviewed-by: xuelei, mullan --- .../net/ssl/TLS/TLSClientPropertyTest.java | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/jdk/test/javax/net/ssl/TLS/TLSClientPropertyTest.java b/jdk/test/javax/net/ssl/TLS/TLSClientPropertyTest.java index e3398ae6ee5..8d7c1b2a716 100644 --- a/jdk/test/javax/net/ssl/TLS/TLSClientPropertyTest.java +++ b/jdk/test/javax/net/ssl/TLS/TLSClientPropertyTest.java @@ -1,5 +1,5 @@ /* - * 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 @@ -29,8 +29,10 @@ import javax.net.ssl.SSLContext; /* * @test - * @bug 8049432 + * @bug 8049432 8069038 * @summary New tests for TLS property jdk.tls.client.protocols + * @summary javax/net/ssl/TLS/TLSClientPropertyTest.java needs to be + * updated for JDK-8061210 * @run main/othervm TLSClientPropertyTest NoProperty * @run main/othervm TLSClientPropertyTest SSLv3 * @run main/othervm TLSClientPropertyTest TLSv1 @@ -46,7 +48,7 @@ import javax.net.ssl.SSLContext; * protocols in the SSLContext. */ public class TLSClientPropertyTest { - private final String[] expecteSupportedProtos = new String[] { + private final String[] expectedSupportedProtos = new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }; @@ -67,31 +69,30 @@ public class TLSClientPropertyTest { } contextProtocol = null; expectedDefaultProtos = new String[] { - "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" + "TLSv1", "TLSv1.1", "TLSv1.2" }; break; case "SSLv3": contextProtocol = "SSLv3"; expectedDefaultProtos = new String[] { - "SSLv3" }; break; case "TLSv1": contextProtocol = "TLSv1"; expectedDefaultProtos = new String[] { - "SSLv3", "TLSv1" + "TLSv1" }; break; case "TLSv11": contextProtocol = "TLSv1.1"; expectedDefaultProtos = new String[] { - "SSLv3", "TLSv1", "TLSv1.1" + "TLSv1", "TLSv1.1" }; break; case "TLSv12": contextProtocol = "TLSv1.2"; expectedDefaultProtos = new String[] { - "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" + "TLSv1", "TLSv1.1", "TLSv1.2" }; break; case "WrongProperty": @@ -182,12 +183,12 @@ public class TLSClientPropertyTest { expectedProto = "Default"; } if (!context.getProtocol().equals(expectedProto)) { - error("Invalid current protocol:" + context.getProtocol() + error("Invalid current protocol: " + context.getProtocol() + ", Expected:" + expectedProto, null); } List actualDefaultProtos = Arrays.asList(context .getDefaultSSLParameters().getProtocols()); - for (String p: expectedDefaultProtos) { + for (String p : expectedDefaultProtos) { if (!actualDefaultProtos.contains(p)) { error("Default protocol " + p + "missing", null); } @@ -195,7 +196,7 @@ public class TLSClientPropertyTest { List actualSupportedProtos = Arrays.asList(context .getSupportedSSLParameters().getProtocols()); - for (String p: expecteSupportedProtos) { + for (String p : expectedSupportedProtos) { if (!actualSupportedProtos.contains(p)) { error("Expected to support protocol:" + p, null); } From 5f9dfc294a9ba12035f09efad44266368c1e49c5 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:43 -0800 Subject: [PATCH 140/149] Added tag jdk9-b47 for changeset 19cacc520105 --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 2539f7e2c81..e95f2721df1 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -289,3 +289,4 @@ f7c11da0b0481d49cc7a65a453336c108191e821 jdk9-b42 8994f5d87b3bb5e8d317d4e8ccb326da1a73684a jdk9-b44 3dd628fde2086218d548841022ee8436b6b88185 jdk9-b45 12f1e276447bcc81516e85367d53e4f08897049d jdk9-b46 +b6cca3e6175a69f39e5799b7349ddb0176630291 jdk9-b47 From 9150f5e5ccd6995dc472654242940cbbcc1b3018 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:44 -0800 Subject: [PATCH 141/149] Added tag jdk9-b47 for changeset c54bf921b2ce --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index d53cf114653..5d7b668b46c 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -449,3 +449,4 @@ c363a8b87e477ee45d6d3cb2a36cb365141bc596 jdk9-b38 43a44b56dca61a4d766a20f0528fdd8b5ceff873 jdk9-b44 5dc8184af1e2bb30b0103113d1f1a58a21a80c37 jdk9-b45 a184ee1d717297bd35b7c3e35393e137921a3ed2 jdk9-b46 +3b241fb72b8925b75941d612db762a6d5da66d02 jdk9-b47 From ed2cf041952aeb42fcd228f47e266187349ae2df Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:44 -0800 Subject: [PATCH 142/149] Added tag jdk9-b47 for changeset da1a0970667a --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index b7b87c5d34e..a6362dd4bef 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -289,3 +289,4 @@ e27c725d6c9d155667b35255f442d4ceb8c3c084 jdk9-b40 1f57bd728c9e6865ccb9d43ccd80a1c11230a32f jdk9-b44 9e3f2bed80c0e5a84a256ce41f1d10c5ade48466 jdk9-b45 326f2068b4a4c05e2fa27d6acf93eba7b54b090d jdk9-b46 +ee8447ca632e1d39180b4767c749db101bff7314 jdk9-b47 From 839ec3c2b64ed2de3a937cf974a139fa2740dbe3 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:46 -0800 Subject: [PATCH 143/149] Added tag jdk9-b47 for changeset dd8e62bad498 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index 38503a0b86f..c0eb212b48c 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -289,3 +289,4 @@ a12d347f84176200593999f4da91ae2bb86865b2 jdk9-b39 0cb0844b58924d6086d2850c22087d06679d5eef jdk9-b44 0dab3e848229127c7aca4c58b98e2d90ba70372f jdk9-b45 74eaf7ad986576c792df4dbff05eed63e5727695 jdk9-b46 +e391de88e69b59d7c618387e3cf91032f6991ce9 jdk9-b47 From 834ad6ab06d1e099cc3d66ebc9d23e32d93022b7 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:47 -0800 Subject: [PATCH 144/149] Added tag jdk9-b47 for changeset c9c4b9563018 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index c59b9b39f40..2f346d3cdf5 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -292,3 +292,4 @@ edc13d27dc871be57d7ca77eef77e6d04972fee2 jdk9-b43 2a03baa4d849818ff6d635f110c2813b12fc2326 jdk9-b44 e529374fbe526dbd668e5e98fc047b42b3bc6d33 jdk9-b45 64ca52b0bda8028636e4ccafbe1107befcdda47d jdk9-b46 +6c17d648d03e4bf4729c3645f8db55d34115e0b7 jdk9-b47 From 548150fa8a30a7f84e0c09f2ee8fbe98c15b48d2 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:48 -0800 Subject: [PATCH 145/149] Added tag jdk9-b47 for changeset 0b4c78ff36f3 --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index b3c46658a54..e5ebdf47f06 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -289,3 +289,4 @@ e336cbd8b15e959e70ed02f0f5e93fa76ebd4c07 jdk9-b41 8cc4dc300041eb70a7a40e4b2431a8f4d4965ea4 jdk9-b44 9acaa4f57b0b9e3757a7b4576ca9418a75ea8287 jdk9-b45 efedac7f44ed41cea2b1038138047271f55aacba jdk9-b46 +b641c14730ac05d9ec8b4f66e6fca3dc21adb403 jdk9-b47 From a7ecc9231b200a52221d7e772781997e42e6533b Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:51 -0800 Subject: [PATCH 146/149] Added tag jdk9-b47 for changeset 422ba63d8dda --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index 119a43b7586..db208a84159 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -289,3 +289,4 @@ f7ce2cfa4cdbec0ae0f46080484eace66be7987a jdk9-b41 de2ce70d907c9f227b802cea29285bece5194cd5 jdk9-b44 73bbdcf236b297a0c1b8875f2eeba65eaf7ade60 jdk9-b45 e272d9be5f90edb6bb6b40f7816ec85eec0f5dc2 jdk9-b46 +230c139552501e612dd0d4423ac30f94c1201c0d jdk9-b47 From 063091c9a63e0ee30b93fc546c8f98c416685fed Mon Sep 17 00:00:00 2001 From: David Katleman Date: Fri, 23 Jan 2015 18:50:52 -0800 Subject: [PATCH 147/149] Added tag jdk9-b47 for changeset 73d6633dcfd7 --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index b31c41f7e17..f754a233071 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -280,3 +280,4 @@ dd7bbdf81a537106cfa9227d1a9a57849cb26b4d jdk9-b37 50ee576062726e536d1bb9a5eadd8fd4470128fc jdk9-b44 3c2bbeda038aef7061455fec604db7d8a342fac5 jdk9-b45 2ecf0a617f0f9af1ffd278a0c70e76f1946ce773 jdk9-b46 +29046d42a95e5b9f105ab086a628bbd7f81c915d jdk9-b47 From b1b7c437259b49fef865a3b65257a0cfa74af46f Mon Sep 17 00:00:00 2001 From: "J. Duke" Date: Wed, 5 Jul 2017 20:14:13 +0200 Subject: [PATCH 148/149] Added tag jdk9-b46 for changeset 722378bc599e --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index d1af44ccacc..19a55a23eb9 100644 --- a/.hgtags +++ b/.hgtags @@ -288,3 +288,4 @@ b409bc51bc23cfd51f2bd04ea919ec83535af9d0 jdk9-b37 6494b13f88a867026ee316b444d9a4fa589dd6bd jdk9-b43 abbfccd659b91a7bb815d5e36fed635dcdd40f31 jdk9-b44 bfc24ae2b900187585079bb11e66e459d1e525fe jdk9-b45 +722378bc599e38d9a1dd484de30f10dfd7b21438 jdk9-b46 From be240f80fbc6f5031107bd498a8fec32912ff1b6 Mon Sep 17 00:00:00 2001 From: "J. Duke" Date: Wed, 5 Jul 2017 20:15:13 +0200 Subject: [PATCH 149/149] Added tag jdk9-b47 for changeset 8327024a9955 --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index 19a55a23eb9..8ad989563ae 100644 --- a/.hgtags +++ b/.hgtags @@ -289,3 +289,4 @@ b409bc51bc23cfd51f2bd04ea919ec83535af9d0 jdk9-b37 abbfccd659b91a7bb815d5e36fed635dcdd40f31 jdk9-b44 bfc24ae2b900187585079bb11e66e459d1e525fe jdk9-b45 722378bc599e38d9a1dd484de30f10dfd7b21438 jdk9-b46 +8327024a99559982b848e9c2191da9c0bf8838fd jdk9-b47