commit_id
stringlengths
40
40
project
stringclasses
90 values
commit_message
stringlengths
5
2.21k
type
stringclasses
3 values
url
stringclasses
89 values
git_diff
stringlengths
283
4.32M
a911e1da33ae86c2b30c34511b97f1a73bd681f8
drools
[JBRULES-3263] fix jitted contraints when invoking- an interface--
c
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/rule/constraint/AnalyzedCondition.java b/drools-core/src/main/java/org/drools/rule/constraint/AnalyzedCondition.java index 0163a670464..6f41150939e 100644 --- a/drools-core/src/main/java/org/drools/rule/constraint/AnalyzedCondition.java +++ b/drools-core/src/main/java/org/drools/rule/constraint/AnalyzedCondition.java @@ -472,13 +472,19 @@ public MethodInvocation(Method method) { private Method getMethodFromSuperclass(Method method) { if (method == null) return method; - Class<?> declaringSuperclass = method.getDeclaringClass().getSuperclass(); - if (declaringSuperclass == null) return method; - try { - return getMethodFromSuperclass(declaringSuperclass.getMethod(method.getName(), method.getParameterTypes())); - } catch (Exception e) { - return method; + Class<?> declaringClass = method.getDeclaringClass(); + Class<?> declaringSuperclass = declaringClass.getSuperclass(); + if (declaringSuperclass != null) { + try { + return getMethodFromSuperclass(declaringSuperclass.getMethod(method.getName(), method.getParameterTypes())); + } catch (Exception e) { } } + for (Class<?> interfaze : declaringClass.getInterfaces()) { + try { + return interfaze.getMethod(method.getName(), method.getParameterTypes()); + } catch (Exception e) { } + } + return method; } public Method getMethod() {
c1c63c500a3d0737c081b3eb5616b17767d965e6
hunterhacker$jdom
Remove duplicate TextHelper functionality. Move tests of Format to TestElement
p
https://github.com/hunterhacker/jdom
diff --git a/core/src/java/org/jdom2/util/TextHelper.java b/core/src/java/org/jdom2/util/TextHelper.java deleted file mode 100644 index 0a922b678..000000000 --- a/core/src/java/org/jdom2/util/TextHelper.java +++ /dev/null @@ -1,224 +0,0 @@ -/*-- - - Copyright (C) 2000-2004 Jason Hunter & Brett McLaughlin. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions, and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions, and the disclaimer that follows - these conditions in the documentation and/or other materials - provided with the distribution. - - 3. The name "JDOM" must not be used to endorse or promote products - derived from this software without prior written permission. For - written permission, please contact <request_AT_jdom_DOT_org>. - - 4. Products derived from this software may not be called "JDOM", nor - may "JDOM" appear in their name, without prior written permission - from the JDOM Project Management <request_AT_jdom_DOT_org>. - - In addition, we request (but do not require) that you include in the - end-user documentation provided with the redistribution and/or in the - software itself an acknowledgement equivalent to the following: - "This product includes software developed by the - JDOM Project (http://www.jdom.org/)." - Alternatively, the acknowledgment may be graphical using the logos - available at http://www.jdom.org/images/logos. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - This software consists of voluntary contributions made by many - individuals on behalf of the JDOM Project and was originally - created by Jason Hunter <jhunter_AT_jdom_DOT_org> and - Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information - on the JDOM Project, please see <http://www.jdom.org/>. - - */ - -package org.jdom2.util; - -import org.jdom2.Element; -import org.jdom2.Namespace; -import org.jdom2.output.Format; - -/** - * <p> - * This class contains static helper methods for accessing Text content of JDOM - * Elements. - * </p> - * - * @author Alex Rosen - * @author Rolf Lear - */ -public class TextHelper { - - private TextHelper() { - // make constructor inaccessible. - } - - /** - * <p> - * This convenience method returns the textual content of the first child - * element with the given name and in no Namespace, or returns an empty - * <code>String</code> ("") if the child has no textual content. However, if - * the child does not exist, <code>null</code> is returned. - * </p> - * - * @param parent - * the parent element - * @param name - * the name of the child - * @return text content for the named child, or null if no such child exists - * @see Element#getChild(String) - */ - public static String getChildText(final Element parent, final String name) { - final Element child = parent.getChild(name); - if (child == null) { - return null; - } - return child.getText(); - } - - /** - * <p> - * This convenience method returns the textual content of the first named - * child element, or returns an empty <code>String</code> ("") if the child - * has no textual content. However, if the child does not exist, - * <code>null</code> is returned. - * </p> - * - * @param parent - * the parent element - * @param name - * the name of the child - * @param ns - * the namespace of the child - * @return text content for the named child, or null if no such child exists - * @see Element#getChild(String, Namespace) - */ - public static String getChildText(final Element parent, final String name, - final Namespace ns) { - final Element child = parent.getChild(name, ns); - if (child == null) { - return null; - } - return child.getText(); - } - - /** - * <p> - * This convenience method returns the trimmed textual content of the first - * named child element, or returns null if there's no such child. See - * {@link Format#trimBoth(String)} for details of text trimming. - * </p> - * - * @param parent - * the parent element - * @param name - * the name of the child - * @return trimmed text content for the named child, or null if no such - * child exists - * @see Element#getChild(String) - */ - public static String getChildTextTrim(final Element parent, - final String name) { - final Element child = parent.getChild(name); - if (child == null) { - return null; - } - return Format.trimBoth(child.getText()); - } - - /** - * <p> - * This convenience method returns the trimmed textual content of the named - * child element, or returns null if there's no such child. See - * <code>String.trim()</code> for details of text trimming. - * </p> - * - * @param parent - * the parent element - * @param name - * the name of the child - * @param ns - * the namespace of the child - * @return trimmed text content for the named child, or null if no such - * child exists - * @see Element#getChild(String, Namespace) - */ - public static String getChildTextTrim(final Element parent, - final String name, final Namespace ns) { - final Element child = parent.getChild(name, ns); - if (child == null) { - return null; - } - return child.getText().trim(); - } - - /** - * <p> - * This convenience method returns the normalized textual content of the - * named child element, or returns null if there's no such child. See - * {@link Format#compact(String)} for details of text normalization. - * </p> - * - * @param parent - * the parent element - * @param name - * the name of the child - * @return normalized text content for the named child, or null if no such - * child exists - * @see Element#getChild(String) - */ - public static String getChildTextNormalize(final Element parent, - final String name) { - final Element child = parent.getChild(name); - if (child == null) { - return null; - } - return Format.compact(child.getText()); - } - - /** - * <p> - * This convenience method returns the normalized textual content of the - * named child element, or returns null if there's no such child. See - * {@link Format#compact(String)} for details of text normalization. - * </p> - * - * @param parent - * the parent element - * @param name - * the name of the child - * @param ns - * the namespace of the child - * @return normalized text content for the named child, or null if no such - * child exists - * @see Element#getChild(String, Namespace) - */ - public static String getChildTextNormalize(final Element parent, - final String name, final Namespace ns) { - final Element child = parent.getChild(name, ns); - if (child == null) { - return null; - } - return Format.compact(child.getText()); - } -} diff --git a/test/src/java/org/jdom2/test/cases/TestElement.java b/test/src/java/org/jdom2/test/cases/TestElement.java index 60deb0e02..7a015ca2b 100644 --- a/test/src/java/org/jdom2/test/cases/TestElement.java +++ b/test/src/java/org/jdom2/test/cases/TestElement.java @@ -101,6 +101,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT import org.jdom2.filter.ContentFilter; import org.jdom2.filter.ElementFilter; import org.jdom2.filter.Filters; +import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.test.util.UnitTestUtil; @@ -2886,4 +2887,102 @@ private void checkAttOrder(List<Attribute> attributes, Attribute...atts) { } + private String getTestString() { + return " this has space "; + } + + private String getComp() { + return Format.compact(getTestString()); + } + + private String getTrim() { + return Format.trimBoth(getTestString()); + } + + private String getPlain() { + return getTestString(); + } + + private Namespace getNamespace() { + return Namespace.getNamespace("jdomtest"); + } + + public Element getTextHelperRoot() { + final Namespace ns = getNamespace(); + + final Element root = new Element("root"); + final Element childa = new Element("child"); + final Element childb = new Element("child", ns); + final Element childc = new Element("child"); + final Element childd = new Element("child", ns); + final Element childe = new Element("kid"); + final Element childf = new Element("kid", ns); + + childa.setText(getTestString()); + childb.setText(getTestString()); + childc.setText(getTestString()); + childd.setText(getTestString()); + root.addContent(childa); + root.addContent(childb); + root.addContent(childc); + root.addContent(childd); + root.addContent(childe); + root.addContent(childf); + + return root; + } + + @Test + public void testGetChildTextElementString() { + Element root = getTextHelperRoot(); + assertEquals(getPlain(), root.getChildText("child")); + assertEquals(null, root.getChildText("dummy")); + assertEquals("", root.getChildText("kid")); + } + + @Test + public void testGetChildTextElementStringNamespace() { + Element root = getTextHelperRoot(); + Namespace ns = getNamespace(); + assertEquals(getPlain(), root.getChildText("child", ns)); + assertEquals(null, root.getChildText("dummy", ns)); + assertEquals("", root.getChildText("kid", ns)); + } + + @Test + public void testGetChildTextTrimElementString() { + Element root = getTextHelperRoot(); + assertEquals(getTrim(), root.getChildTextTrim("child")); + assertEquals(null, root.getChildTextTrim("dummy")); + assertEquals("", root.getChildTextTrim("kid")); + } + + @Test + public void testGetChildTextTrimElementStringNamespace() { + Element root = getTextHelperRoot(); + Namespace ns = getNamespace(); + assertEquals(getTrim(), root.getChildTextTrim("child", ns)); + assertEquals(null, root.getChildTextTrim("dummy", ns)); + assertEquals("", root.getChildTextTrim("kid", ns)); + } + + @Test + public void testGetChildTextNormalizeElementString() { + Element root = getTextHelperRoot(); + assertEquals(getComp(), root.getChildTextNormalize("child")); + assertEquals(null, root.getChildTextNormalize("dummy")); + assertEquals("", root.getChildTextNormalize("kid")); + } + + @Test + public void testGetChildTextNormalizeElementStringNamespace() { + Element root = getTextHelperRoot(); + Namespace ns = getNamespace(); + assertEquals(getComp(), root.getChildTextNormalize("child", ns)); + assertEquals(null, root.getChildTextNormalize("dummy", ns)); + assertEquals("", root.getChildTextNormalize("kid", ns)); + } + + + } diff --git a/test/src/java/org/jdom2/test/cases/util/TestTextHelper.java b/test/src/java/org/jdom2/test/cases/util/TestTextHelper.java deleted file mode 100644 index 036313aa1..000000000 --- a/test/src/java/org/jdom2/test/cases/util/TestTextHelper.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.jdom2.test.cases.util; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import org.jdom2.Element; -import org.jdom2.Namespace; -import org.jdom2.output.Format; -import org.jdom2.util.TextHelper; - -@SuppressWarnings("javadoc") -public class TestTextHelper { - - private final Namespace ns = Namespace.getNamespace("jdomtest"); - - private final Element root = new Element("root"); - private final Element childa = new Element("child"); - private final Element childb = new Element("child", ns); - private final Element childc = new Element("child"); - private final Element childd = new Element("child", ns); - private final Element childe = new Element("kid"); - private final Element childf = new Element("kid", ns); - private final String teststr = " this has space "; - private final String comp = Format.compact(teststr); - private final String trim = Format.trimBoth(teststr); - private final String plain = teststr; - - public TestTextHelper() { - childa.setText(teststr); - childb.setText(teststr); - childc.setText(teststr); - childd.setText(teststr); - root.addContent(childa); - root.addContent(childb); - root.addContent(childc); - root.addContent(childd); - root.addContent(childe); - root.addContent(childf); - } - - @Test - public void testGetChildTextElementString() { - assertEquals(plain, TextHelper.getChildText(root, "child")); - assertEquals(null, TextHelper.getChildText(root, "dummy")); - assertEquals("", TextHelper.getChildText(root, "kid")); - } - - @Test - public void testGetChildTextElementStringNamespace() { - assertEquals(plain, TextHelper.getChildText(root, "child", ns)); - assertEquals(null, TextHelper.getChildText(root, "dummy", ns)); - assertEquals("", TextHelper.getChildText(root, "kid", ns)); - } - - @Test - public void testGetChildTextTrimElementString() { - assertEquals(trim, TextHelper.getChildTextTrim(root, "child")); - assertEquals(null, TextHelper.getChildTextTrim(root, "dummy")); - assertEquals("", TextHelper.getChildTextTrim(root, "kid")); - } - - @Test - public void testGetChildTextTrimElementStringNamespace() { - assertEquals(trim, TextHelper.getChildTextTrim(root, "child", ns)); - assertEquals(null, TextHelper.getChildTextTrim(root, "dummy", ns)); - assertEquals("", TextHelper.getChildTextTrim(root, "kid", ns)); - } - - @Test - public void testGetChildTextNormalizeElementString() { - assertEquals(comp, TextHelper.getChildTextNormalize(root, "child")); - assertEquals(null, TextHelper.getChildTextNormalize(root, "dummy")); - assertEquals("", TextHelper.getChildTextNormalize(root, "kid")); - } - - @Test - public void testGetChildTextNormalizeElementStringNamespace() { - assertEquals(comp, TextHelper.getChildTextNormalize(root, "child", ns)); - assertEquals(null, TextHelper.getChildTextNormalize(root, "dummy", ns)); - assertEquals("", TextHelper.getChildTextNormalize(root, "kid", ns)); - } - -}
6723b2640726bd3936d4c1825412a41c2c7b5cd5
Vala
Add libusb-1.0 bindings Fixes bug 589913.
a
https://github.com/GNOME/vala/
diff --git a/vapi/Makefile.am b/vapi/Makefile.am index d02ba4517d..191b6332f9 100644 --- a/vapi/Makefile.am +++ b/vapi/Makefile.am @@ -115,6 +115,8 @@ dist_vapi_DATA = \ libsoup-2.4.deps \ libsoup-2.4.vapi \ libusb.vapi \ + libusb-1.0.deps \ + libusb-1.0.vapi \ libwnck-1.0.deps \ libwnck-1.0.vapi \ libxml-2.0.vapi \ diff --git a/vapi/libusb-1.0.deps b/vapi/libusb-1.0.deps new file mode 100644 index 0000000000..37e3098bb0 --- /dev/null +++ b/vapi/libusb-1.0.deps @@ -0,0 +1,3 @@ +glib-2.0 +posix + diff --git a/vapi/libusb-1.0.vapi b/vapi/libusb-1.0.vapi new file mode 100644 index 0000000000..f9a553f049 --- /dev/null +++ b/vapi/libusb-1.0.vapi @@ -0,0 +1,357 @@ +[CCode (cprefix = "libusb_", cheader_filename = "libusb.h")] +namespace LibUSB { + [CCode (cname = "enum libusb_class_code", cprefix = "LIBUSB_CLASS_")] + public enum ClassCode { + PER_INTERFACE, + AUDIO, + COMM, + HID, + PRINTER, + PTP, + MASS_STORAGE, + HUB, + DATA, + VENDOR_SPEC + } + + [CCode (cname = "enum libusb_descriptor_type", cprefix = "LIBUSB_DT_")] + public enum DescriptorType { + DEVICE, + CONFIG, + STRING, + INTERFACE, + ENDPOINT, + HID, + REPORT, + PHYSICAL, + HUB + } + + [CCode (cprefix = "LIBUSB_DT_")] + namespace DescriptorTypeSize { + public const int DEVICE_SIZE; + public const int CONFIG_SIZE; + public const int INTERFACE_SIZE; + public const int ENDPOINT_SIZE; + public const int ENDPOINT_AUDIO_SIZE; + public const int HUB_NONVAR_SIZE; + } + + namespace EndpointMask { + [CCode (cname = "LIBUSB_ENDPOINT_ADDRESS_MASK")] + public const int ADDRESS; + [CCode (cname = "LIBUSB_ENDPOINT_DIR_MASK")] + public const int DIR; + [CCode (cname = "LIBUSB_ENDPOINT_DIR_MASK")] + public const int DIRECTION; + } + + [CCode (cname = "enum libusb_endpoint_direction", cprefix = "LIBUSB_ENDPOINT_")] + public enum EndpointDirection { + IN, + OUT, + [CCode (cname = "LIBUSB_ENDPOINT_DIR_MASK")] + MASK + } + + [CCode (cname = "enum libusb_transfer_type", cprefix = "LIBUSB_TRANSFER_TYPE_")] + public enum TransferType { + CONTROL, + ISOCHRONOUS, + BULK, + INTERRUPT + } + + [CCode (cname = "enum libusb_standard_request", cprefix = "LIBUSB_REQUEST_")] + public enum StandardRequest { + GET_STATUS, + CLEAR_FEATURE, + SET_FEATURE, + SET_ADDRESS, + GET_DESCRIPTOR, + SET_DESCRIPTOR, + GET_CONFIGURATION, + GET_INTERFACE, + SET_INTERFACE, + SYNCH_FRAME + } + + [CCode (cname = "enum libusb_request_type", cprefix = "LIBUSB_REQUEST_TYPE_")] + public enum RequestType { + STANDARD, + CLASS, + VENDOR, + RESERVED + } + + [CCode (cname = "enum libusb_request_recipient", cprefix = "LIBUSB_RECIPIENT_")] + public enum RequestRecipient { + DEVICE, + INTERFACE, + ENDPOINT, + OTHER + } + + [CCode (cname = "enum libusb_iso_sync_type", cprefix = "LIBUSB_ISO_SYNC_TYPE_")] + public enum IsoSyncType { + NONE, + ASYNC, + ADAPTIVE, + SYNC, + MASK + } + + [CCode (cname = "enum libusb_iso_usage_type", cprefix = "LIBUSB_ISO_USAGE_TYPE_")] + public enum IsoUsageType { + DATA, + FEEDBACK, + IMPLICIT, + MASK + } + + [CCode (cname = "enum libusb_error", cprefix = "LIBUSB_ERROR_")] + public enum Error { + [CCode (cname = "LIBUSB_SUCCESS")] + SUCCESS, + IO, + INVALID_PARAM, + ACCESS, + NO_DEVICE, + NOT_FOUND, + BUSY, + TIMEOUT, + OVERFLOW, + PIPE, + INTERRUPTED, + NO_MEM, + NOT_SUPPORTED, + OTHER + } + + [CCode (cname = "struct libusb_device_descriptor")] + public struct DeviceDescriptor { + public uint8 bLength; + public uint8 bDescriptorType; + public uint16 bcdUSB; + public uint8 bDeviceClass; + public uint8 bDeviceSubClass; + public uint8 bDeviceProtocol; + public uint8 bMaxPacketSize0; + public uint16 idVendor; + public uint16 idProduct; + public uint16 bcdDevice; + public uint8 iManufacturer; + public uint8 iProduct; + public uint8 iSerialNumber; + public uint8 bNumConfigurations; + + [CCode (cname = "libusb_get_device_descriptor", instance_pos = -1)] + public DeviceDescriptor (Device device); + } + + [CCode (cname = "struct libusb_endpoint_descriptor", cprefix = "libusb_")] + public struct EndpointDescriptor { + public uint8 bLength; + public uint8 bDescriptorType; + public uint8 bEndpointAddress; + public uint8 bmAttributes; + public uint16 wMaxPacketSize; + public uint8 bInterval; + public uint8 bRefresh; + public uint8 bSynchAddress; + [CCode (array_length_cname = "extra_length")] + uchar[] extra; + } + + [CCode (cname = "struct libusb_interface_descriptor")] + public struct InterfaceDescriptor { + public uint8 bLength; + public uint8 bDescriptorType; + public uint8 bInterfaceNumber; + public uint8 bAlternateSetting; + public uint8 bNumEndpoints; + public uint8 bInterfaceClass; + public uint8 bInterfaceSubClass; + public uint8 bInterfaceProtocol; + public uint8 iInterface; + [CCode (array_length_cname = "bNumEndpoints", array_length_type = "uint8_t")] + public EndpointDescriptor[] endpoint; + [CCode (array_length_cname = "extra_length")] + uchar[] extra; + } + + [CCode (cname = "struct libusb_interface")] + public struct Interface { + [CCode (array_length_cname = "num_altsetting")] + public InterfaceDescriptor[] altsetting; + } + + [Compact, CCode (cname = "struct libusb_config_descriptor", free_function = "libusb_free_config_descriptor")] + public class ConfigDescriptor { + public uint8 bLength; + public uint8 bDescriptorType; + public uint16 wTotalLength; + public uint8 bNumInterfaces; + public uint8 bConfigurationValue; + public uint8 iConfiguration; + public uint8 bmAttributes; + public uint8 MaxPower; + [CCode (array_length_cname = "bNumInterfaces")] + public Interface[] @interface; + [CCode (array_length_cname = "extra_length")] + uchar[] extra; + } + + + [Compact, CCode (cname = "libusb_device_handle", cprefix = "libusb_", free_function = "libusb_close")] + public class DeviceHandle { + public DeviceHandle (Device device) { + DeviceHandle handle; + device.open(out handle); + } + + [CCode (cname = "libusb_open_device_with_vid_pid")] + public DeviceHandle.from_vid_pid (Context context, uint16 vendor_id, uint16 product_id); + public unowned Device get_device (); + public int get_configuration (out int config); + public int set_configuration (int configuration); + public int claim_interface (int interface_number); + public int release_interface (int interface_number); + public int set_interface_alt_setting (int interface_number, int alternate_setting); + public int clear_halt (uchar endpoint); + [CCode (cname = "libusb_reset_device")] + public int reset (); + public int kernel_driver_active (int @interface); + public int detach_kernel_driver (int @interface); + public int attach_kernel_driver (int @interface); + + public int get_string_descriptor_ascii (uint8 desc_index, uchar[] data); + public int get_descriptor (uint8 desc_type, uint8 desc_index, uchar[] data); + public int get_string_descriptor (uint desc_index, uint16 langid, uchar[] data); + + public int control_transfer (uint8 bmRequestType, uint8 bRequest, uint16 wValue, uint16 wIndex, [CCode (array_length = false)] uchar[] data, uint16 wLength, uint timeout); + public int bulk_transfer (uchar endpoint, uchar[] data, out int transferred, uint timeout); + public int interrupt_transfer (uchar endpoint, uchar[] data, out int transferred, uint timeout); + } + + [CCode (cname = "libusb_device", cprefix = "libusb_", ref_function = "libusb_ref_device", unref_function = "libusb_unref_device")] + public class Device { + public uint8 get_bus_number (); + public uint8 get_device_address (); + public int get_max_packet_size (uchar endpoint); + public int open (out DeviceHandle handle); + + public int get_active_config_descriptor (out ConfigDescriptor config); + public int get_config_descriptor (uint8 config_index, out ConfigDescriptor config); + public int get_config_descriptor_by_value (uint8 ConfigurationValue, out ConfigDescriptor config); + public int get_device_descriptor (out DeviceDescriptor desc); + } + + [Compact, CCode (cname = "libusb_context", cprefix = "libusb_", free_function = "libusb_exit")] + public class Context { + public static int init (out Context context); + public void set_debug (int level); + public ssize_t get_device_list ([CCode (array_length = false)] out Device[] list); + public DeviceHandle open_device_with_vid_pid (uint16 vendor_id, uint16 product_id); + + public int try_lock_events (); + public void lock_events (); + public void unlock_events (); + public int event_handling_ok (); + public int event_handler_active (); + public void lock_event_waiters (); + public void unlock_event_waiters (); + public int wait_for_event (GLib.TimeVal tv); + public int handle_events_timeout (GLib.TimeVal tv); + public int handle_events (); + public int handle_events_locked (GLib.TimeVal tv); + public int get_next_timeout (out Posix.timeval tv); + public void set_pollfd_notifiers (pollfd_added_cb added_cb, pollfd_removed_cb removed_cb, void* user_data); + [CCode (array_length = false)] + public unowned PollFD[] get_pollfds (); + } + + public static uint16 le16_to_cpu (uint16 n); + public static uint16 cpu_to_le16 (uint16 n); + [CCode (cname = "malloc", cheader_filename = "stdlib.h")] + private static void* malloc (ulong n_bytes); + + [Compact, CCode (cname = "struct libusb_control_setup")] + public class ControlSetup { + public uint8 bmRequestType; + public int8 bRequest; + public uint16 wValue; + public uint16 wIndex; + public uint16 wLength; + } + + [CCode (cname = "enum libusb_transfer_status", cprefix = "LIBUSB_TRANSFER_")] + public enum TransferStatus { + COMPLETED, + ERROR, + TIMED_OUT, + CANCELLED, + STALL, + NO_DEVICE, + OVERFLOW + } + + [CCode (cname = "struct libusb_iso_packet_descriptor")] + public struct IsoPacketDescriptor { + public uint length; + public uint actual_length; + public TransferStatus status; + } + + public static delegate void transfer_cb_fn (Transfer transfer); + + [Compact, CCode (cname = "struct libusb_transfer", cprefix = "libusb_", free_function = "libusb_free_transfer")] + public class Transfer { + public DeviceHandle dev_handle; + public uint8 flags; + public uchar endpoint; + public uchar type; + public uint timeout; + public TransferStatus status; + public int length; + public int actual_length; + public transfer_cb_fn @callback; + public void* user_data; + [CCode (array_length_cname = "length")] + public uchar[] buffer; + public int num_iso_packets; + [CCode (array_length = false)] + public IsoPacketDescriptor[] iso_packet_desc; + + [CCode (cname = "libusb_alloc_transfer")] + public Transfer (int iso_packets = 0); + [CCode (cname = "libusb_submit_transfer")] + public int submit (); + [CCode (cname = "libusb_cancel_transfer")] + public int cancel (); + [CCode (cname = "libusb_contrel_transfer_get_data", array_length = false)] + public unowned char[] control_get_data (); + [CCode (cname = "libusb_control_transfer_get_setup")] + public unowned ControlSetup control_get_setup (); + + public static void fill_control_setup ([CCode (array_length = false)] uchar[] buffer, uint8 bmRequestType, uint8 bRequest, uint16 wValue, uint16 wIndex, uint16 wLength); + public void fill_control_transfer (DeviceHandle dev_handle, [CCode (array_length = false)] uchar[] buffer, transfer_cb_fn @callback, void* user_data, uint timeout); + public void fill_bulk_transfer (DeviceHandle dev_handle, uchar endpoint, uchar[] buffer, transfer_cb_fn @callback, void* user_data, uint timeout); + public void fill_interrupt_transfer (DeviceHandle dev_handle, uchar endpoint, uchar[] buffer, transfer_cb_fn @callback, void* user_data, uint timeout); + public void fill_iso_transfer (DeviceHandle dev_handle, uchar endpoint, uchar[] buffer, int num_iso_packets, transfer_cb_fn @callback, void* user_data, uint timeout); + public void set_packet_lengths (uint length); + [CCode (array_length = false)] + public unowned uchar[] get_iso_packet_buffer (uint packet); + [CCode (array_length = false)] + public unowned uchar[] get_iso_packet_buffer_simple (int packet); + } + + public static delegate void pollfd_added_cb (int fd, short events, void* user_data); + public static delegate void pollfd_removed_cb (int fd, void* user_data); + + [Compact, CCode (cname = "struct libusb_pollfd")] + public class PollFD { + public int fd; + public short events; + } +}
6397f775178eedf37663c0b28e863b3b74feb277
drools
JBRULES-313: adding halt command--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@12902 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java index 832c1923745..08dd4a3e144 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java @@ -2921,6 +2921,30 @@ public void testMapAccess() throws Exception { assertTrue( list.contains( map ) ); } + + public void testHalt() throws Exception { + final PackageBuilder builder = new PackageBuilder(); + builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_halt.drl" ) ) ); + final Package pkg = builder.getPackage(); + + final RuleBase ruleBase = getRuleBase(); + ruleBase.addPackage( pkg ); + final WorkingMemory workingMemory = ruleBase.newStatefulSession(); + + final List results = new ArrayList(); + workingMemory.setGlobal( "results", + results ); + + workingMemory.insert( new Integer( 0 ) ); + workingMemory.fireAllRules(); + + assertEquals( 10, + results.size() ); + for( int i = 0; i < 10; i++ ) { + assertEquals( new Integer( i ), results.get( i ) ); + } + } + } \ No newline at end of file diff --git a/drools-compiler/src/test/resources/org/drools/integrationtests/test_halt.drl b/drools-compiler/src/test/resources/org/drools/integrationtests/test_halt.drl new file mode 100644 index 00000000000..6dc0e94ac06 --- /dev/null +++ b/drools-compiler/src/test/resources/org/drools/integrationtests/test_halt.drl @@ -0,0 +1,20 @@ +package org.drools; + +global java.util.List results; + +rule "fire" +when + $old : Number( $val : intValue ) +then + results.add( $old ); + insert( new Integer( $val + 1 ) ); + retract( $old ); +end + +rule "stop" + salience 10 +when + Number( intValue == 10 ) +then + drools.halt(); +end \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/WorkingMemory.java b/drools-core/src/main/java/org/drools/WorkingMemory.java index fadc9099c45..9887e14b991 100644 --- a/drools-core/src/main/java/org/drools/WorkingMemory.java +++ b/drools-core/src/main/java/org/drools/WorkingMemory.java @@ -311,4 +311,11 @@ public void modifyInsert(final FactHandle factHandle, * Starts a new process instance for the process with the given id. */ ProcessInstance startProcess(String processId); + + /** + * Stops rule firing after the currect rule finishes executing + * + */ + public void halt(); + } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/base/DefaultKnowledgeHelper.java b/drools-core/src/main/java/org/drools/base/DefaultKnowledgeHelper.java index ab4c095feef..c8a2cfa4a7a 100644 --- a/drools-core/src/main/java/org/drools/base/DefaultKnowledgeHelper.java +++ b/drools-core/src/main/java/org/drools/base/DefaultKnowledgeHelper.java @@ -198,4 +198,8 @@ public void setFocus(final String focus) { public Declaration getDeclaration(final String identifier) { return (Declaration) this.subrule.getOuterDeclarations().get( identifier ); } + + public void halt() { + this.workingMemory.halt(); + } } diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java index 91da739c8ac..52d6cea401e 100644 --- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java @@ -145,6 +145,8 @@ public abstract class AbstractWorkingMemory /** Flag to determine if a rule is currently being fired. */ protected boolean firing; + + protected boolean halt; // ------------------------------------------------------------ // Constructors @@ -394,6 +396,10 @@ public RuleBase getRuleBase() { return this.ruleBase; } + public void halt() { + this.halt = true; + } + /** * @see WorkingMemory */ @@ -405,7 +411,8 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa // If we're already firing a rule, then it'll pick up // the firing for any other assertObject(..) that get // nested inside, avoiding concurrent-modification - // exceptions, depending on code paths of the actions. + // exceptions, depending on code paths of the actions. + this.halt = false; if ( isSequential() ) { for ( Iterator it = this.liaPropagations.iterator(); it.hasNext(); ) { @@ -423,7 +430,7 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa try { this.firing = true; - while ( this.agenda.fireNextItem( agendaFilter ) ) { + while ( (!halt) && this.agenda.fireNextItem( agendaFilter ) ) { noneFired = false; if ( !this.actionQueue.isEmpty() ) { executeQueuedActions(); @@ -450,7 +457,7 @@ private void doOtherwise(final AgendaFilter agendaFilter) { executeQueuedActions(); } - while ( this.agenda.fireNextItem( agendaFilter ) ) { + while ( (!halt) && this.agenda.fireNextItem( agendaFilter ) ) { ; } diff --git a/drools-core/src/main/java/org/drools/common/InternalWorkingMemoryActions.java b/drools-core/src/main/java/org/drools/common/InternalWorkingMemoryActions.java index 5699f9aff65..0c124843e04 100644 --- a/drools-core/src/main/java/org/drools/common/InternalWorkingMemoryActions.java +++ b/drools-core/src/main/java/org/drools/common/InternalWorkingMemoryActions.java @@ -52,4 +52,5 @@ public void modifyInsert(final FactHandle factHandle, final Object object, final Rule rule, final Activation activation); + } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/spi/KnowledgeHelper.java b/drools-core/src/main/java/org/drools/spi/KnowledgeHelper.java index 250a8e1acb8..9b2711ed96a 100644 --- a/drools-core/src/main/java/org/drools/spi/KnowledgeHelper.java +++ b/drools-core/src/main/java/org/drools/spi/KnowledgeHelper.java @@ -17,11 +17,9 @@ */ import java.io.Serializable; -import java.util.List; import org.drools.FactException; import org.drools.FactHandle; -import org.drools.QueryResults; import org.drools.WorkingMemory; import org.drools.rule.Declaration; import org.drools.rule.Rule; @@ -134,5 +132,7 @@ public void modifyInsert(final FactHandle factHandle, // void setFocus(AgendaGroup focus); public Declaration getDeclaration(String identifier); + + public void halt(); } \ No newline at end of file
98a24828255cde13eaee893eafc9a049bb2183a7
elasticsearch
Testing: Add test rule to repeat tests on binding- exceptions--Due to the possibility of ports being already used when choosing a-random port
a
https://github.com/elastic/elasticsearch
diff --git a/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java b/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java index 5a1c882017946..95797c51396a4 100644 --- a/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java +++ b/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java @@ -33,6 +33,7 @@ import org.elasticsearch.test.cache.recycler.MockBigArrays; import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; +import org.junit.Rule; import org.junit.Test; import java.io.IOException; @@ -46,6 +47,11 @@ public class NettyTransportMultiPortTests extends ElasticsearchTestCase { + public static int MAX_RETRIES = 10; + + @Rule + public RepeatOnBindExceptionRule repeatOnBindExceptionRule = new RepeatOnBindExceptionRule(logger, MAX_RETRIES); + private NettyTransport nettyTransport; private ThreadPool threadPool; diff --git a/src/test/java/org/elasticsearch/transport/netty/RepeatOnBindExceptionRule.java b/src/test/java/org/elasticsearch/transport/netty/RepeatOnBindExceptionRule.java new file mode 100644 index 0000000000000..4db593499fb18 --- /dev/null +++ b/src/test/java/org/elasticsearch/transport/netty/RepeatOnBindExceptionRule.java @@ -0,0 +1,69 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.elasticsearch.transport.netty; + +import org.elasticsearch.common.logging.ESLogger; +import org.elasticsearch.transport.BindTransportException; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * A helper rule to catch all BindTransportExceptions + * and rerun the test for a configured number of times + */ +public class RepeatOnBindExceptionRule implements TestRule { + + private ESLogger logger; + private int retryCount; + + /** + * + * @param logger the es logger from the test class + * @param retryCount number of amounts to try a single test before failing + */ + public RepeatOnBindExceptionRule(ESLogger logger, int retryCount) { + this.logger = logger; + this.retryCount = retryCount; + } + + @Override + public Statement apply(final Statement base, Description description) { + + return new Statement() { + @Override + public void evaluate() throws Throwable { + Throwable caughtThrowable = null; + + for (int i = 0; i < retryCount; i++) { + try { + base.evaluate(); + return; + } catch (BindTransportException t) { + caughtThrowable = t; + logger.info("Bind exception occurred, rerunning the test after [{}] failures", t, i+1); + } + } + logger.error("Giving up after [{}] failures... marking test as failed", retryCount); + throw caughtThrowable; + } + }; + + } +}
ec592a45194c1a126d861514e453ac9b7de7c5be
Delta Spike
review old TODOs and remove them if not valid anymore.
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ServiceUtils.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ServiceUtils.java index a02ec3e07..0c1b994f5 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ServiceUtils.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ServiceUtils.java @@ -44,8 +44,6 @@ public static <T> List<T> loadServiceImplementations(Class<T> serviceType) if (!servicesIterator.hasNext()) { - //X TODO check if we have to do it in any case with different packaging constellations - //X and merge the result in any case ClassLoader fallbackClassLoader = ServiceUtils.class.getClassLoader(); servicesIterator = ServiceLoader.load(serviceType, fallbackClassLoader).iterator(); } diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/config/ConfigSourceTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/config/ConfigSourceTest.java index 3bbccff56..79aa6badf 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/config/ConfigSourceTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/config/ConfigSourceTest.java @@ -86,18 +86,5 @@ public void testConfigViaMetaInfPropertyFile() Assert.assertEquals(value, configuredValue); } - /* - //X TODO discuss marker - @Test - public void testConfigViaSystemPropertyAndMarker() - { - String key = "testProperty01"; - String value = "test_value"; - System.setProperty("org.apache.deltaspike." + key, value); - String configuredValue = ConfigResolver.getPropertyValue("@@deltaspike@@" + key); - - Assert.assertEquals(value, configuredValue); - } - */ }
db1d84f299ef6853256754a4afa109f1345a3104
Search_api
Issue #2100199 by drunken monkey: Merged index tabs for a cleaner look.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 5d00c434..5c279013 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,6 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #2100199 by drunken monkey: Merged index tabs for a cleaner look. - #2115127 by drunken monkey: Fixed cron indexing logic to keep the right order. - #1750144 by jsacksick, drunken monkey: Fixed missing Boost option for custom fulltext field types. diff --git a/search_api.admin.inc b/search_api.admin.inc index 90e387d9..0252f877 100644 --- a/search_api.admin.inc +++ b/search_api.admin.inc @@ -473,10 +473,17 @@ function search_api_admin_server_edit(array $form, array &$form_state, SearchApi $form['options']['#title'] = $class['name']; $form['options']['#description'] = $class['description']; - $form['submit'] = array( + $form['actions']['#type'] = 'actions'; + $form['actions']['submit'] = array( '#type' => 'submit', '#value' => t('Save settings'), ); + $form['actions']['delete'] = array( + '#type' => 'submit', + '#value' => t('Delete'), + '#submit' => array('search_api_admin_form_delete_submit'), + '#limit_validation_errors' => array(), + ); return $form; } @@ -506,6 +513,30 @@ function search_api_admin_server_edit_submit(array $form, array &$form_state) { drupal_set_message(t('The search server was successfully edited.')); } +/** + * Form submission handler for search_api_admin_server_edit(). + * + * Handles the 'Delete' button on the server and index edit forms. + * + * @see search_api_admin_server_edit() + * @see search_api_admin_index_edit() + */ +function search_api_admin_form_delete_submit($form, &$form_state) { + $destination = array(); + if (isset($_GET['destination'])) { + $destination = drupal_get_destination(); + unset($_GET['destination']); + } + if (isset($form_state['server'])) { + $server = $form_state['server']; + $form_state['redirect'] = array('admin/config/search/search_api/server/' . $server->machine_name . '/delete', array('query' => $destination)); + } + elseif (isset($form_state['index'])) { + $index = $form_state['index']; + $form_state['redirect'] = array('admin/config/search/search_api/index/' . $index->machine_name . '/delete', array('query' => $destination)); + } +} + /** * Form callback showing a form for adding an index. */ @@ -633,16 +664,15 @@ function search_api_admin_add_index_submit(array $form, array &$form_state) { } /** - * Displays an index' details. + * Page callback for displaying an index's status. * * @param SearchApiIndex $index * The index to display. + * @param string|null $action + * (optional) An action to execute for the index. Either "enable" or + * "disable". For "disable", a confirm dialog will be shown. */ -function search_api_admin_index_view(SearchApiIndex $index = NULL, $action = NULL) { - if (empty($index)) { - return MENU_NOT_FOUND; - } - +function search_api_admin_index_view(SearchApiIndex $index, $action = NULL) { if (!empty($action)) { if ($action == 'enable') { if (isset($_GET['token']) && drupal_valid_token($_GET['token'], $index->machine_name)) { @@ -666,206 +696,100 @@ function search_api_admin_index_view(SearchApiIndex $index = NULL, $action = NUL } } - $ret = array( - '#theme' => 'search_api_index', - '#id' => $index->id, - '#name' => $index->name, - '#machine_name' => $index->machine_name, - '#description' => $index->description, - '#item_type' => $index->item_type, - '#enabled' => $index->enabled, - '#server' => $index->server(), - '#options' => $index->options, - '#fields' => $index->getFields(), - '#status' => $index->status, - '#read_only' => $index->read_only, - ); - - return $ret; + return drupal_get_form('search_api_admin_index_status_form', $index); } /** - * Theme function for displaying an index. + * Form function for displaying an index status form. * - * @param array $variables - * An associative array containing: - * - id: The index's id. - * - name: The index' name. - * - machine_name: The index' machine name. - * - description: The index' description. - * - item_type: The type of items stored in this index. - * - enabled: Boolean indicating whether the index is enabled. - * - server: The server this index currently rests on, if any. - * - options: The index' options, like cron limit. - * - fields: All indexed fields of the index. - * - indexed_items: The number of items already indexed in their latest - * version on this index. - * - total_items: The total number of items that have to be indexed for this - * index. - * - status: The entity configuration status (in database, in code, etc.). - * - read_only: Boolean indicating whether this index is read only. + * @param SearchApiIndex $index + * The index whose status should be displayed. */ -function theme_search_api_index(array $variables) { - extract($variables); - - $output = ''; +function search_api_admin_index_status_form(array $form, array &$form_state, SearchApiIndex $index) { + $enabled = !empty($index->enabled); + $server = $index->server(); - $output .= '<h3>' . check_plain($name) . '</h3>' . "\n"; + $form['#attached']['css'][] = drupal_get_path('module', 'search_api') . '/search_api.admin.css'; + $form_state['index'] = $index; - $output .= '<dl>' . "\n"; + if (!empty($index->description)) { + $form['description']['#markup'] = '<p>' . nl2br(check_plain($index->description)) . '</p>'; + } - $output .= '<dt>' . t('Status') . '</dt>' . "\n"; - $output .= '<dd>'; + $form['info']['#prefix'] = '<dl>'; + $form['info']['#suffix'] = '</dl>'; if ($enabled) { - $output .= t('enabled (!disable_link)', array('!disable_link' => l(t('disable'), 'admin/config/search/search_api/index/' . $machine_name . '/disable'))); + $status_message = t('enabled (!disable_link)', array('!disable_link' => l(t('disable'), 'admin/config/search/search_api/index/' . $index->machine_name . '/disable'))); } - elseif ($server && $server->enabled) { - $output .= t('disabled (!enable_link)', array('!enable_link' => l(t('enable'), 'admin/config/search/search_api/index/' . $machine_name . '/enable', array('query' => array('token' => drupal_get_token($machine_name)))))); + elseif (!empty($server->enabled)) { + $status_message = t('disabled (!enable_link)', array('!enable_link' => l(t('enable'), 'admin/config/search/search_api/index/' . $index->machine_name . '/enable', array('query' => array('token' => drupal_get_token($index->machine_name)))))); } else { - $output .= t('disabled'); + $status_message = t('disabled'); } - $output .= '</dd>' . "\n"; - - $output .= '<dt>' . t('Machine name') . '</dt>' . "\n"; - $output .= '<dd>' . check_plain($machine_name) . '</dd>' . "\n"; + $form['info']['status']['#markup'] = '<dt>' . t('Status') . '</dt>' . "\n"; + $form['info']['status']['#markup'] .= '<dd>' . $status_message . '</dd>' . "\n"; - $output .= '<dt>' . t('Item type') . '</dt>' . "\n"; - $type = search_api_get_item_type_info($item_type); - $type = $type['name']; - $output .= '<dd>' . check_plain($type) . '</dd>' . "\n"; - - if (!empty($description)) { - $output .= '<dt>' . t('Description') . '</dt>' . "\n"; - $output .= '<dd>' . nl2br(check_plain($description)) . '</dd>' . "\n"; - } + $type = search_api_get_item_type_info($index->item_type); + $form['info']['type']['#markup'] = '<dt>' . t('Item type') . '</dt>' . "\n"; + $form['info']['type']['#markup'] .= '<dd>' . check_plain($type['name']) . '</dd>' . "\n"; if (!empty($server)) { - $output .= '<dt>' . t('Server') . '</dt>' . "\n"; - $output .= '<dd>' . l($server->name, 'admin/config/search/search_api/server/' . $server->machine_name); + $form['info']['server']['#markup'] = '<dt>' . t('Server') . '</dt>' . "\n"; + $form['info']['server']['#markup'] .= '<dd>' . l($server->name, 'admin/config/search/search_api/server/' . $server->machine_name); if (!empty($server->description)) { - $output .= '<p class="description">' . nl2br(check_plain($server->description)) . '</p>'; + $form['info']['server']['#markup'] .= '<p class="description">' . nl2br(check_plain($server->description)) . '</p>'; } - $output .= '</dd>' . "\n"; + $form['info']['server']['#markup'] .= '</dd>' . "\n"; } - if (!$read_only && !empty($options)) { - $output .= '<dt>' . t('Index options') . '</dt>' . "\n"; - $output .= '<dd><dl>' . "\n"; - $output .= '<dt>' . t('Cron batch size') . '</dt>' . "\n"; - if (empty($options['cron_limit'])) { - $output .= '<dd>' . t("Don't index during cron runs") . '</dd>' . "\n"; - } - elseif ($options['cron_limit'] < 0) { - $output .= '<dd>' . t('Unlimited') . '</dd>' . "\n"; - } - else { - $output .= '<dd>' . format_plural($options['cron_limit'], '1 item per cron batch.', '@count items per cron batch.') . '</dd>' . "\n"; - } - - if (!empty($fields)) { - $fields_list = array(); - foreach ($fields as $name => $field) { - if (search_api_is_text_type($field['type'])) { - $fields_list[] = t('@field (@boost x)', array('@field' => $field['name'], '@boost' => $field['boost'])); - } - else { - $fields_list[] = check_plain($field['name']); - } - } - if ($fields_list) { - $output .= '<dt>' . t('Indexed fields') . '</dt>' . "\n"; - $output .= '<dd>' . implode(', ', $fields_list) . '</dd>' . "\n"; - } - } - - $output .= '</dl></dd>' . "\n"; - } - elseif ($read_only) { - $output .= '<dt>' . t('Read only') . '</dt>' . "\n"; - $output .= '<dd>' . t('This index is read-only.') . '</dd>' . "\n"; - } - - $output .= '<dt>' . t('Configuration status') . '</dt>' . "\n"; - $output .= '<dd>' . "\n"; - $output .= theme('entity_status', array('status' => $status)); - $output .= '</dd>' . "\n"; - - $output .= '</dl>'; - - return $output; -} - -/** - * Form function for displaying an index status form. - * - * @param SearchApiIndex $index - * The index whose status should be displayed. - */ -function search_api_admin_index_status_form(array $form, array &$form_state, SearchApiIndex $index) { - $enabled = !empty($index->enabled); - $status = search_api_index_status($index); - $server = $index->server(); - - $form['#attached']['css'][] = drupal_get_path('module', 'search_api') . '/search_api.admin.css'; - $form_state['index'] = $index; - - $form['status_message'] = array( - '#type' => 'item', - '#title' => t('Status'), - '#description' => $enabled ? t('The index is currently enabled.') : t('The index is currently disabled.'), - ); - if (!empty($server->enabled)) { - $form['status'] = array( - '#type' => 'submit', - '#value' => $enabled ? t('Disable') : t('Enable'), - ); - } + $form['info']['config_status']['#markup'] = '<dt>' . t('Configuration status') . '</dt>' . "\n"; + $form['info']['config_status']['#markup'] .= '<dd>' . theme('entity_status', array('status' => $index->status)) . '</dd>' . "\n"; if ($index->read_only) { - $form['read_only'] = array( - '#type' => 'item', - '#title' => t('Read only'), - '#description' => t('The index is currently in read-only mode. ' . - 'No new items will be indexed, nor will old ones be deleted.'), - ); + $message = t('The index is currently in read-only mode. No new items will be indexed, nor will old ones be deleted.'); + $form['info']['read_only']['#markup'] = '<dt>' . t('Read only') . '</dt>' . "\n"; + $form['info']['read_only']['#markup'] .= '<dd>' . $message . '</dd>'; return $form; } + $status = search_api_index_status($index); + $form['index'] = array( + '#type' => 'fieldset', + '#title' => t('Indexing status'), + '#description' => t('This index is disabled. No information about the indexing status is available.'), + '#collapsible' => TRUE, + ); if ($enabled) { - $form['progress'] = array( - '#type' => 'item', - '#title' => t('Progress'), - ); $all = ($status['indexed'] == $status['total']); if ($all) { - $form['progress']['#description'] = t('All items have been indexed (@total / @total).', + $form['index']['#description'] = t('All items have been indexed (@total / @total).', array('@total' => $status['total'])); } elseif (!$status['indexed']) { - $form['progress']['#description'] = t('All items still need to be indexed (@total total).', + $form['index']['#description'] = t('All items still need to be indexed (@total total).', array('@total' => $status['total'])); } else { $percentage = (int) (100 * $status['indexed'] / $status['total']); - $form['progress']['#description'] = t('About @percentage% of all items have been indexed in their latest version (@indexed / @total).', + $form['index']['#description'] = t('About @percentage% of all items have been indexed in their latest version (@indexed / @total).', array('@indexed' => $status['indexed'], '@total' => $status['total'], '@percentage' => $percentage)); } if (!$all) { - $form['index'] = array( + $form['index']['index'] = array( '#type' => 'fieldset', '#title' => t('Index now'), '#collapsible' => TRUE, ); - $form['index']['settings'] = array( + $form['index']['index']['settings'] = array( '#type' => 'fieldset', '#title' => t('Advanced settings'), '#collapsible' => TRUE, '#collapsed' => TRUE, ); - $form['index']['settings']['limit'] = array( + $form['index']['index']['settings']['limit'] = array( '#type' => 'textfield', '#title' => t('Number of items to index'), '#default_value' => -1, @@ -874,7 +798,7 @@ function search_api_admin_index_status_form(array $form, array &$form_state, Sea '#description' => t('Number of items to index. Set to -1 for all items.'), ); $batch_size = empty($index->options['cron_limit']) ? SEARCH_API_DEFAULT_CRON_LIMIT : $index->options['cron_limit']; - $form['index']['settings']['batch_size'] = array( + $form['index']['index']['settings']['batch_size'] = array( '#type' => 'textfield', '#title' => t('Number of items per batch run'), '#default_value' => $batch_size, @@ -882,15 +806,15 @@ function search_api_admin_index_status_form(array $form, array &$form_state, Sea '#attributes' => array('class' => array('search-api-batch-size')), '#description' => t('Number of items per batch run. Set to -1 for all items at once (not recommended). Defaults to the cron batch size of the index.'), ); - $form['index']['button'] = array( + $form['index']['index']['button'] = array( '#type' => 'submit', '#value' => t('Index now'), ); - $form['index']['total'] = array( + $form['index']['index']['total'] = array( '#type' => 'value', '#value' => $status['total'], ); - $form['index']['remaining'] = array( + $form['index']['index']['remaining'] = array( '#type' => 'value', '#value' => $status['total'] - $status['indexed'], ); @@ -898,36 +822,26 @@ function search_api_admin_index_status_form(array $form, array &$form_state, Sea } if ($server) { - if ($enabled && $status['indexed'] > 0) { - $form['reindex'] = array( - '#type' => 'fieldset', - '#title' => t('Re-indexing'), - '#collapsible' => TRUE, - ); - $form['reindex']['message'] = array( - '#type' => 'item', - '#description' => t('This will add all items to the index again (overwriting the index), but existing items in the index will remain searchable.'), - ); - $form['reindex']['button'] = array( - '#type' => 'submit', - '#value' => t('Re-index content'), - ); - } - - $form['clear'] = array( + $form['index']['reindex'] = array( '#type' => 'fieldset', - '#title' => t('Clear index'), + '#title' => t('Re-indexing'), '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#tree' => TRUE, ); - $form['clear']['message'] = array( + $form['index']['reindex']['message'] = array( '#type' => 'item', - '#description' => t('All items will be deleted from the index and have to be inserted again by normally indexing them. ' . - 'Until all items are re-indexed, searches on this index will return incomplete results.<br />' . - 'Use with care, in most cases rebuilding the index might be enough.'), + '#description' => t('This will mark all items as "changed" and add them to the index again (overwriting existing data) in subsequent indexing operations.'), ); - $form['clear']['button'] = array( + $form['index']['reindex']['clear'] = array( + '#type' => 'checkbox', + '#title' => t('Also clear data on server'), + '#description' => t('If checked, indexed data on the server will be deleted, too. No results will be returned by searches for this index until items are indexed again.<br />Use with care, in most cases rebuilding the index might be enough.'), + '#default_value' => FALSE, + ); + $form['index']['reindex']['button'] = array( '#type' => 'submit', - '#value' => t('Clear index'), + '#value' => t('Re-index content'), ); } @@ -965,25 +879,26 @@ function search_api_admin_index_status_form_submit(array $form, array &$form_sta if (!_search_api_batch_indexing_create($index, $values['batch_size'], $values['limit'], $values['remaining'])) { drupal_set_message(t("Couldn't create a batch, please check the batch size and limit."), 'warning'); } - $redirect = $pre . '/status'; + $redirect = $pre; break; case t('Re-index content'): - if ($index->reindex()) { - drupal_set_message(t('The index was successfully scheduled for re-indexing.')); - } - else { - drupal_set_message(t('An error has occurred while performing the desired action. Check the logs for details.'), 'error'); - } - $redirect = $pre . '/status'; - break; - case t('Clear index'): - if ($index->clear()) { - drupal_set_message(t('The index was successfully cleared.')); + if (empty($values['reindex']['clear'])) { + if ($index->reindex()) { + drupal_set_message(t('The index was successfully scheduled for re-indexing.')); + } + else { + drupal_set_message(t('An error has occurred while performing the desired action. Check the logs for details.'), 'error'); + } } else { - drupal_set_message(t('An error has occurred while performing the desired action. Check the logs for details.'), 'error'); + if ($index->clear()) { + drupal_set_message(t('The index was successfully cleared.')); + } + else { + drupal_set_message(t('An error has occurred while performing the desired action. Check the logs for details.'), 'error'); + } } - $redirect = $pre . '/status'; + $redirect = $pre; break; default: @@ -1070,10 +985,17 @@ function search_api_admin_index_edit(array $form, array &$form_state, SearchApiI ), ); - $form['submit'] = array( + $form['actions']['#type'] = 'actions'; + $form['actions']['submit'] = array( '#type' => 'submit', '#value' => t('Save settings'), ); + $form['actions']['delete'] = array( + '#type' => 'submit', + '#value' => t('Delete'), + '#submit' => array('search_api_admin_form_delete_submit'), + '#limit_validation_errors' => array(), + ); return $form; } diff --git a/search_api.module b/search_api.module index 2c661980..3cd982b1 100644 --- a/search_api.module +++ b/search_api.module @@ -65,6 +65,7 @@ function search_api_menu() { 'file' => 'search_api.admin.inc', 'weight' => -1, 'type' => MENU_LOCAL_TASK, + 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE, ); $items[$pre . '/server/%search_api_server/delete'] = array( 'title' => 'Delete', @@ -76,7 +77,7 @@ function search_api_menu() { 'access callback' => 'search_api_access_delete_page', 'access arguments' => array(5), 'file' => 'search_api.admin.inc', - 'type' => MENU_LOCAL_TASK, + 'type' => MENU_CALLBACK, ); $items[$pre . '/index/%search_api_index'] = array( 'title' => 'View index', @@ -91,21 +92,11 @@ function search_api_menu() { $items[$pre . '/index/%search_api_index/view'] = array( 'title' => 'View', 'type' => MENU_DEFAULT_LOCAL_TASK, - 'weight' => -10, - ); - $items[$pre . '/index/%search_api_index/status'] = array( - 'title' => 'Status', - 'description' => 'Display and work on index status.', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('search_api_admin_index_status_form', 5), - 'access arguments' => array('administer search_api'), - 'file' => 'search_api.admin.inc', - 'weight' => -8, - 'type' => MENU_LOCAL_TASK, 'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE, + 'weight' => -10, ); $items[$pre . '/index/%search_api_index/edit'] = array( - 'title' => 'Settings', + 'title' => 'Edit', 'description' => 'Edit index settings.', 'page callback' => 'drupal_get_form', 'page arguments' => array('search_api_admin_index_edit', 5), @@ -147,7 +138,7 @@ function search_api_menu() { 'access callback' => 'search_api_access_delete_page', 'access arguments' => array(5), 'file' => 'search_api.admin.inc', - 'type' => MENU_LOCAL_TASK, + 'type' => MENU_CALLBACK, ); return $items; @@ -217,24 +208,6 @@ function search_api_theme() { ), 'file' => 'search_api.admin.inc', ); - $themes['search_api_index'] = array( - 'variables' => array( - 'id' => NULL, - 'name' => '', - 'machine_name' => '', - 'description' => NULL, - 'item_type' => NULL, - 'enabled' => NULL, - 'server' => NULL, - 'options' => array(), - 'fields' => array(), - 'indexed_items' => 0, - 'total_items' => 0, - 'status' => ENTITY_CUSTOM, - 'read_only' => 0, - ), - 'file' => 'search_api.admin.inc', - ); $themes['search_api_admin_item_order'] = array( 'render element' => 'element', 'file' => 'search_api.admin.inc', @@ -2673,13 +2646,11 @@ function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size, * Batch API finishing callback for the indexing functionality. * * @param boolean $success - * Result of the batch operation. + * Whether the batch finished successfully. * @param array $results - * Results. - * @param array $operations - * Remaining batch operation to process. + * Detailed informations about the result. */ -function _search_api_batch_indexing_finished($success, $results, $operations) { +function _search_api_batch_indexing_finished($success, $results) { // Check if called from drush. if (!empty($results['drush'])) { $drupal_set_message = 'drush_log'; diff --git a/search_api.test b/search_api.test index f8a506b9..a000b1aa 100644 --- a/search_api.test +++ b/search_api.test @@ -250,10 +250,7 @@ class SearchApiWebTest extends DrupalWebTestCase { $this->assertTitle('Search API test index | Drupal', 'Correct title when viewing index.'); $this->assertText('An index used for testing.', 'Description displayed.'); $this->assertText('Search API test entity', 'Item type displayed.'); - $this->assertText(format_plural(1, '1 item per cron batch.', '@count items per cron batch.'), 'Cron batch size displayed.'); - - $this->drupalGet("admin/config/search/search_api/index/$id/status"); - $this->assertText(t('The index is currently disabled.'), '"Disabled" status displayed.'); + $this->assertText(t('disabled'), '"Disabled" status displayed.'); } /** @@ -373,7 +370,6 @@ class SearchApiWebTest extends DrupalWebTestCase { */ protected function indexItems() { $this->checkIndexStatus(); - $this->assertText(t('The index is currently enabled.'), '"Enabled" status displayed.'); // Here we test the indexing + the warning message when some items // cannot be indexed. @@ -439,7 +435,7 @@ class SearchApiWebTest extends DrupalWebTestCase { * Defaults to TRUE. */ protected function checkIndexStatus($indexed = 0, $total = 10, $check_buttons = TRUE) { - $url = "admin/config/search/search_api/index/{$this->index_id}/status"; + $url = "admin/config/search/search_api/index/{$this->index_id}"; if (strpos($this->url, $url) === FALSE) { $this->drupalGet($url); } @@ -466,19 +462,13 @@ class SearchApiWebTest extends DrupalWebTestCase { return; } + $this->assertText(t('enabled'), '"Enabled" status displayed.'); if ($all) { $this->assertNoText(t('Index now'), '"Index now" form not displayed.'); } else { $this->assertText(t('Index now'), '"Index now" form displayed.'); } - if ($indexed) { - $this->assertText(t('Re-indexing'), '"Re-indexing" form displayed.'); - } - else { - $this->assertNoText(t('Re-indexing'), '"Re-indexing" form not displayed.'); - } - $this->assertText(t('Clear index'), '"Clear index" form displayed.'); } /** @@ -606,7 +596,7 @@ class SearchApiWebTest extends DrupalWebTestCase { * Tests whether clearing the index works correctly. */ protected function clearIndex() { - $this->drupalPost("admin/config/search/search_api/index/{$this->index_id}/status", array(), t('Clear index')); + $this->drupalPost("admin/config/search/search_api/index/{$this->index_id}", array('reindex[clear]' => TRUE), t('Re-index content')); $this->assertText(t('The index was successfully cleared.')); $this->assertText(t('All items still need to be indexed (@total total).', array('@total' => 14)), 'Correct index status displayed.'); } @@ -619,8 +609,9 @@ class SearchApiWebTest extends DrupalWebTestCase { protected function deleteServer() { $this->drupalPost("admin/config/search/search_api/server/{$this->server_id}/delete", array(), t('Confirm')); $this->assertNoText('test-name-foo', 'Server no longer listed.'); - $this->drupalGet("admin/config/search/search_api/index/{$this->index_id}/status"); - $this->assertText(t('The index is currently disabled.'), 'The index was disabled and removed from the server.'); + $this->drupalGet("admin/config/search/search_api/index/{$this->index_id}"); + $this->assertNoText(t('Server'), 'The index was removed from the server.'); + $this->assertText(t('disabled'), 'The index was disabled.'); } /**
882289b06e9f2adebd916cf8d02980327c6f9614
spring-framework
getAllInterfacesForClass introspects parent- interfaces as well (SPR-7247)--
c
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java b/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java index f771a5e921b1..3ce2b2b94d5f 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java @@ -22,7 +22,6 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -30,7 +29,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; -import java.util.List; import java.util.Map; import java.util.Set; @@ -971,22 +969,8 @@ public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) { * @return all interfaces that the given object implements as array */ public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) { - Assert.notNull(clazz, "Class must not be null"); - if (clazz.isInterface()) { - return new Class[] {clazz}; - } - List<Class<?>> interfaces = new ArrayList<Class<?>>(); - while (clazz != null) { - Class<?>[] ifcs = clazz.getInterfaces(); - for (Class<?> ifc : ifcs) { - if (!interfaces.contains(ifc) && - (classLoader == null || isVisible(ifc, classLoader))) { - interfaces.add(ifc); - } - } - clazz = clazz.getSuperclass(); - } - return interfaces.toArray(new Class[interfaces.size()]); + Set<Class> ifcs = getAllInterfacesForClassAsSet(clazz, classLoader); + return ifcs.toArray(new Class[ifcs.size()]); } /** @@ -1022,16 +1006,14 @@ public static Set<Class> getAllInterfacesForClassAsSet(Class clazz) { */ public static Set<Class> getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) { Assert.notNull(clazz, "Class must not be null"); - if (clazz.isInterface()) { + if (clazz.isInterface() && isVisible(clazz, classLoader)) { return Collections.singleton(clazz); } Set<Class> interfaces = new LinkedHashSet<Class>(); while (clazz != null) { - for (int i = 0; i < clazz.getInterfaces().length; i++) { - Class<?> ifc = clazz.getInterfaces()[i]; - if (classLoader == null || isVisible(ifc, classLoader)) { - interfaces.add(ifc); - } + Class<?>[] ifcs = clazz.getInterfaces(); + for (Class<?> ifc : ifcs) { + interfaces.addAll(getAllInterfacesForClassAsSet(ifc, classLoader)); } clazz = clazz.getSuperclass(); }
1d54f3f4837da65091711f7765511af1a0a7cbd5
orientdb
Fixed problem with remote connection to- distributed storage--
c
https://github.com/orientechnologies/orientdb
diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java index 0e08aa1208d..e46f23c7f3c 100755 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java @@ -1628,7 +1628,7 @@ protected void parseServerURLs() { } else { name = url.substring(url.lastIndexOf("/") + 1); for (String host : url.substring(0, dbPos).split(ADDRESS_SEPARATOR)) - host = addHost(host); + addHost(host); } if (serverURLs.size() == 1 && OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_ENABLED.getValueAsBoolean()) { @@ -1913,6 +1913,8 @@ public void updateClusterConfiguration(final byte[] obj) { if (members != null) { serverURLs.clear(); + parseServerURLs(); + for (ODocument m : members) if (m != null && !serverURLs.contains((String) m.field("id"))) { for (Map<String, Object> listener : ((Collection<Map<String, Object>>) m.field("listeners"))) {
e680208e4b24b1f5ea9522e04526ae572bb3b6e3
orientdb
Removed checks if db is open as a bug reported in- the ML by Stefan Ollinger--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java index 589f504912a..3a2ca0413bc 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java @@ -332,7 +332,6 @@ public T getUserObjectByRecord(final ORecordInternal<?> iRecord, final String iF } public T getUserObjectByRecord(final ORecordInternal<?> iRecord, final String iFetchPlan, final boolean iCreate) { - checkOpeness(); if (!(iRecord instanceof ODocument)) return null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java index 489f13de85e..3bb5ae10eb6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java @@ -76,7 +76,6 @@ public <T> T newInstance(final Class<T> iType) { * @see #registerEntityClasses(String) */ public <RET extends Object> RET newInstance(final String iClassName) { - checkOpeness(); checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_CREATE, iClassName); try { diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java b/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java index 86c25ece009..e58aa388787 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java @@ -40,14 +40,14 @@ public class OLazyObjectIterator<TYPE> implements Iterator<TYPE>, Serializable { private final ODatabasePojoAbstract<TYPE> database; private final Iterator<Object> underlying; private String fetchPlan; - final private boolean convertToRecord; + final private boolean autoConvert2Object; public OLazyObjectIterator(final ODatabasePojoAbstract<TYPE> database, final ORecord<?> iSourceRecord, final Iterator<Object> iIterator, final boolean iConvertToRecord) { this.database = database; this.sourceRecord = iSourceRecord; this.underlying = iIterator; - convertToRecord = iConvertToRecord; + autoConvert2Object = iConvertToRecord; } public TYPE next() { @@ -60,10 +60,10 @@ public TYPE next(final String iFetchPlan) { if (value == null) return null; - if (value instanceof ORID && convertToRecord) + if (value instanceof ORID && autoConvert2Object) return database.getUserObjectByRecord( (ORecordInternal<?>) ((ODatabaseRecord) database.getUnderlying()).load((ORID) value, iFetchPlan), iFetchPlan); - else if (value instanceof ODocument && convertToRecord) + else if (value instanceof ODocument && autoConvert2Object) return database.getUserObjectByRecord((ODocument) value, iFetchPlan); return (TYPE) value; diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java index 270a55248f5..de2cb6d29d6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java @@ -31,14 +31,14 @@ public class OLazyRecordIterator implements Iterator<OIdentifiable> { final private ODatabaseRecord sourceDatabase; final private ORecord<?> sourceRecord; final private Iterator<? extends OIdentifiable> underlying; - final private boolean convertToRecord; + final private boolean autoConvert2Record; public OLazyRecordIterator(final ORecord<?> iSourceRecord, final ODatabaseRecord iSourceDatabase, final byte iRecordType, final Iterator<? extends OIdentifiable> iIterator, final boolean iConvertToRecord) { this.sourceRecord = iSourceRecord; this.sourceDatabase = iSourceDatabase; this.underlying = iIterator; - this.convertToRecord = iConvertToRecord; + this.autoConvert2Record = iConvertToRecord; } public OIdentifiable next() { @@ -48,7 +48,7 @@ public OIdentifiable next() { return null; if (sourceDatabase != null) - if (value instanceof ORecordId && convertToRecord) + if (value instanceof ORecordId && autoConvert2Record) return (OIdentifiable) sourceDatabase.load((ORecordId) value); return value;
ab4b279e6a966d5410f581dc51951046a283a70c
restlet-framework-java
Fixed test case.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/src/org/restlet/test/engine/ChunkedEncodingPutTestCase.java b/modules/org.restlet.test/src/org/restlet/test/engine/ChunkedEncodingPutTestCase.java index 6380fc699b..619472cb84 100644 --- a/modules/org.restlet.test/src/org/restlet/test/engine/ChunkedEncodingPutTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/engine/ChunkedEncodingPutTestCase.java @@ -30,8 +30,6 @@ package org.restlet.test.engine; -import java.io.IOException; - import org.restlet.Application; import org.restlet.Client; import org.restlet.Component; @@ -69,13 +67,7 @@ public PutTestResource() { @Override public Representation put(Representation entity) { - String str = null; - try { - str = entity.getText(); - } catch (IOException e) { - e.printStackTrace(); - } - return new StringRepresentation(str, MediaType.TEXT_PLAIN); + return entity; } }
eacef5292eec40870a44812d0389293a21a7fc49
tapiji
Fix NPE during startup of translator application. Fixes NPE during lookup of project name for RCP translator.
c
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java index bf318882..69ba753c 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java @@ -38,569 +38,578 @@ * @author Pascal Essiembre ([email protected]) */ public class MessagesBundleGroup extends AbstractMessageModel implements - IMessagesBundleGroup { - - private String projectName; - - private static final IMessagesBundleGroupListener[] EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {}; - private static final Message[] EMPTY_MESSAGES = new Message[] {}; - - public static final String PROPERTY_MESSAGES_BUNDLE_COUNT = "messagesBundleCount"; //$NON-NLS-1$ - public static final String PROPERTY_KEY_COUNT = "keyCount"; //$NON-NLS-1$ - - /** For serialization. */ - private static final long serialVersionUID = -1977849534191384324L; - /** Bundles forming the group (key=Locale; value=MessagesBundle). */ - private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>(); - private final Set<String> keys = new TreeSet<String>(); - private final IMessagesBundleListener messagesBundleListener = new MessagesBundleListener(); - - private final IMessagesBundleGroupStrategy groupStrategy; - private static final Locale[] EMPTY_LOCALES = new Locale[] {}; - private final String name; - private final String resourceBundleId; - - /** - * Creates a new messages bundle group. - * - * @param groupStrategy - * a IMessagesBundleGroupStrategy instance - */ - public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) { - super(); - this.groupStrategy = groupStrategy; - this.name = groupStrategy.createMessagesBundleGroupName(); - this.resourceBundleId = groupStrategy.createMessagesBundleId(); - - this.projectName = groupStrategy.getProjectName(); - - MessagesBundle[] bundles = groupStrategy.loadMessagesBundles(); - if (bundles != null) { - for (int i = 0; i < bundles.length; i++) { - addMessagesBundle(bundles[i]); - } - } + IMessagesBundleGroup { - RBManager.getInstance(this.projectName) - .notifyMessagesBundleGroupCreated(this); - } + private String projectName; - /** - * Called before this object will be discarded. Disposes the underlying - * MessageBundles - */ - @Override - public void dispose() { - for (IMessagesBundle mb : getMessagesBundles()) { - try { - mb.dispose(); - } catch (Throwable t) { - // FIXME: remove debug: - System.err.println("Error disposing message-bundle " - + ((MessagesBundle) mb).getResource() - .getResourceLocationLabel()); - // disregard crashes: this is a best effort to dispose things. - } - } + private static final IMessagesBundleGroupListener[] EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {}; + private static final Message[] EMPTY_MESSAGES = new Message[] {}; - RBManager.getInstance(this.projectName) - .notifyMessagesBundleGroupDeleted(this); - } + public static final String PROPERTY_MESSAGES_BUNDLE_COUNT = "messagesBundleCount"; //$NON-NLS-1$ + public static final String PROPERTY_KEY_COUNT = "keyCount"; //$NON-NLS-1$ - /** - * Gets the messages bundle matching given locale. - * - * @param locale - * locale of bundle to retreive - * @return a bundle - */ - @Override - public IMessagesBundle getMessagesBundle(Locale locale) { - return localeBundles.get(locale); - } + /** For serialization. */ + private static final long serialVersionUID = -1977849534191384324L; + /** Bundles forming the group (key=Locale; value=MessagesBundle). */ + private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>(); + private final Set<String> keys = new TreeSet<String>(); + private final IMessagesBundleListener messagesBundleListener = new MessagesBundleListener(); - /** - * Gets the messages bundle matching given source object. A source object - * being a context-specific concrete underlying implementation of a - * <code>MessagesBundle</code> as per defined in - * <code>IMessageResource</code>. - * - * @param source - * the source object to match - * @return a messages bundle - * @see IMessagesResource - */ - public MessagesBundle getMessagesBundle(Object source) { - for (IMessagesBundle messagesBundle : getMessagesBundles()) { - if (equals(source, ((MessagesBundle) messagesBundle).getResource() - .getSource())) { - return (MessagesBundle) messagesBundle; - } - } - return null; - } + private final IMessagesBundleGroupStrategy groupStrategy; + private static final Locale[] EMPTY_LOCALES = new Locale[] {}; + private final String name; + private final String resourceBundleId; - /** - * Adds an empty <code>MessagesBundle</code> to this group for the given - * locale. - * - * @param locale - * locale for the new bundle added - */ - public void addMessagesBundle(Locale locale) { - addMessagesBundle(groupStrategy.createMessagesBundle(locale)); - } + /** + * Creates a new messages bundle group. + * + * @param groupStrategy + * a IMessagesBundleGroupStrategy instance + */ + public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) { + super(); + this.groupStrategy = groupStrategy; + this.name = groupStrategy.createMessagesBundleGroupName(); + this.resourceBundleId = groupStrategy.createMessagesBundleId(); - /** - * Gets all locales making up this messages bundle group. - */ - public Locale[] getLocales() { - return localeBundles.keySet().toArray(EMPTY_LOCALES); - } + this.projectName = groupStrategy.getProjectName(); - /** - * Gets all messages associated with the given message key. - * - * @param key - * a message key - * @return messages - */ - @Override - public IMessage[] getMessages(String key) { - List<IMessage> messages = new ArrayList<IMessage>(); - for (IMessagesBundle messagesBundle : getMessagesBundles()) { - IMessage message = messagesBundle.getMessage(key); - if (message != null) { - messages.add(message); - } - } - return messages.toArray(EMPTY_MESSAGES); + MessagesBundle[] bundles = groupStrategy.loadMessagesBundles(); + if (bundles != null) { + for (int i = 0; i < bundles.length; i++) { + addMessagesBundle(bundles[i]); + } } - /** - * Gets the message matching given key and locale. - * - * @param locale - * locale for which to retrieve the message - * @param key - * key matching entry to retrieve the message - * @return a message - */ - @Override - public IMessage getMessage(String key, Locale locale) { - IMessagesBundle messagesBundle = getMessagesBundle(locale); - if (messagesBundle != null) { - return messagesBundle.getMessage(key); - } - return null; + if (this.projectName != null) { + RBManager.getInstance(this.projectName) + .notifyMessagesBundleGroupCreated(this); } + } + + /** + * Called before this object will be discarded. Disposes the underlying + * MessageBundles + */ + @Override + public void dispose() { + for (IMessagesBundle mb : getMessagesBundles()) { + try { + mb.dispose(); + } catch (Throwable t) { + // FIXME: remove debug: + System.err.println("Error disposing message-bundle " + + ((MessagesBundle) mb).getResource() + .getResourceLocationLabel()); + // disregard crashes: this is a best effort to dispose things. + } + } + + RBManager.getInstance(this.projectName) + .notifyMessagesBundleGroupDeleted(this); + } - /** - * Adds a messages bundle to this group. - * - * @param messagesBundle - * bundle to add - * @throws MessageException - * if a messages bundle for the same locale already exists. - */ - public void addMessagesBundle(IMessagesBundle messagesBundle) { - addMessagesBundle(messagesBundle.getLocale(), messagesBundle); + /** + * Gets the messages bundle matching given locale. + * + * @param locale + * locale of bundle to retreive + * @return a bundle + */ + @Override + public IMessagesBundle getMessagesBundle(Locale locale) { + return localeBundles.get(locale); + } + + /** + * Gets the messages bundle matching given source object. A source object + * being a context-specific concrete underlying implementation of a + * <code>MessagesBundle</code> as per defined in + * <code>IMessageResource</code>. + * + * @param source + * the source object to match + * @return a messages bundle + * @see IMessagesResource + */ + public MessagesBundle getMessagesBundle(Object source) { + for (IMessagesBundle messagesBundle : getMessagesBundles()) { + if (equals(source, ((MessagesBundle) messagesBundle).getResource() + .getSource())) { + return (MessagesBundle) messagesBundle; + } } + return null; + } - /** - * Adds a messages bundle to this group. - * - * @param locale - * The locale of the bundle - * @param messagesBundle - * bundle to add - * @throws MessageException - * if a messages bundle for the same locale already exists. - */ - @Override - public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) { - MessagesBundle mb = (MessagesBundle) messagesBundle; - if (localeBundles.get(mb.getLocale()) != null) { - throw new MessageException( - "A bundle with the same locale already exists."); //$NON-NLS-1$ - } + /** + * Adds an empty <code>MessagesBundle</code> to this group for the given + * locale. + * + * @param locale + * locale for the new bundle added + */ + public void addMessagesBundle(Locale locale) { + addMessagesBundle(groupStrategy.createMessagesBundle(locale)); + } - int oldBundleCount = localeBundles.size(); - localeBundles.put(mb.getLocale(), mb); - - firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount, - localeBundles.size()); - fireMessagesBundleAdded(mb); - - String[] bundleKeys = mb.getKeys(); - for (int i = 0; i < bundleKeys.length; i++) { - String key = bundleKeys[i]; - if (!keys.contains(key)) { - int oldKeyCount = keys.size(); - keys.add(key); - firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size()); - fireKeyAdded(key); - } - } - mb.addMessagesBundleListener(messagesBundleListener); + /** + * Gets all locales making up this messages bundle group. + */ + public Locale[] getLocales() { + return localeBundles.keySet().toArray(EMPTY_LOCALES); + } + /** + * Gets all messages associated with the given message key. + * + * @param key + * a message key + * @return messages + */ + @Override + public IMessage[] getMessages(String key) { + List<IMessage> messages = new ArrayList<IMessage>(); + for (IMessagesBundle messagesBundle : getMessagesBundles()) { + IMessage message = messagesBundle.getMessage(key); + if (message != null) { + messages.add(message); + } + } + return messages.toArray(EMPTY_MESSAGES); + } + + /** + * Gets the message matching given key and locale. + * + * @param locale + * locale for which to retrieve the message + * @param key + * key matching entry to retrieve the message + * @return a message + */ + @Override + public IMessage getMessage(String key, Locale locale) { + IMessagesBundle messagesBundle = getMessagesBundle(locale); + if (messagesBundle != null) { + return messagesBundle.getMessage(key); } + return null; + } - /** - * Removes the {@link IMessagesBundle} from the group. - * @param messagesBundle The bundle to remove. - */ - @Override - public void removeMessagesBundle(IMessagesBundle messagesBundle) { - Locale locale = messagesBundle.getLocale(); + /** + * Adds a messages bundle to this group. + * + * @param messagesBundle + * bundle to add + * @throws MessageException + * if a messages bundle for the same locale already exists. + */ + public void addMessagesBundle(IMessagesBundle messagesBundle) { + addMessagesBundle(messagesBundle.getLocale(), messagesBundle); + } - if (localeBundles.containsKey(locale)) { - localeBundles.remove(locale); - } + /** + * Adds a messages bundle to this group. + * + * @param locale + * The locale of the bundle + * @param messagesBundle + * bundle to add + * @throws MessageException + * if a messages bundle for the same locale already exists. + */ + @Override + public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) { + MessagesBundle mb = (MessagesBundle) messagesBundle; + if (localeBundles.get(mb.getLocale()) != null) { + throw new MessageException( + "A bundle with the same locale already exists."); //$NON-NLS-1$ + } - // which keys should I not remove? - Set<String> keysNotToRemove = new TreeSet<String>(); + int oldBundleCount = localeBundles.size(); + localeBundles.put(mb.getLocale(), mb); - for (String key : messagesBundle.getKeys()) { - for (IMessagesBundle bundle : localeBundles.values()) { - if (bundle.getMessage(key) != null) { - keysNotToRemove.add(key); - } - } - } + firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount, + localeBundles.size()); + fireMessagesBundleAdded(mb); - // remove keys - for (String keyToRemove : messagesBundle.getKeys()) { - if (!keysNotToRemove.contains(keyToRemove)) { // we can remove - keys.remove(keyToRemove); - } - } + String[] bundleKeys = mb.getKeys(); + for (int i = 0; i < bundleKeys.length; i++) { + String key = bundleKeys[i]; + if (!keys.contains(key)) { + int oldKeyCount = keys.size(); + keys.add(key); + firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size()); + fireKeyAdded(key); + } } + mb.addMessagesBundleListener(messagesBundleListener); + + } /** - * Gets this messages bundle group name. That is the name, which is used - * for the tab of the MultiPageEditorPart - * @return bundle group name + * Removes the {@link IMessagesBundle} from the group. + * + * @param messagesBundle + * The bundle to remove. */ - @Override - public String getName() { - return name; - } + @Override + public void removeMessagesBundle(IMessagesBundle messagesBundle) { + Locale locale = messagesBundle.getLocale(); - /** - * Adds an empty message to every messages bundle of this group with the - * given. - * - * @param key - * message key - */ - @Override - public void addMessages(String key) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - ((MessagesBundle) msgBundle).addMessage(key); - } + if (localeBundles.containsKey(locale)) { + localeBundles.remove(locale); } - /** - * Renames a key in all messages bundles forming this group. - * - * @param sourceKey - * the message key to rename - * @param targetKey - * the new message name - */ - public void renameMessageKeys(String sourceKey, String targetKey) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.renameMessageKey(sourceKey, targetKey); - } - } + // which keys should I not remove? + Set<String> keysNotToRemove = new TreeSet<String>(); - /** - * Removes messages matching the given key from all messages bundle. - * - * @param key - * key of messages to remove - */ - @Override - public void removeMessages(String key) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.removeMessage(key); + for (String key : messagesBundle.getKeys()) { + for (IMessagesBundle bundle : localeBundles.values()) { + if (bundle.getMessage(key) != null) { + keysNotToRemove.add(key); } + } } - /** - * Removes messages matching the given key from all messages bundle and add - * it's parent key to bundles. - * - * @param key - * key of messages to remove - */ - @Override - public void removeMessagesAddParentKey(String key) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.removeMessageAddParentKey(key); - } + // remove keys + for (String keyToRemove : messagesBundle.getKeys()) { + if (!keysNotToRemove.contains(keyToRemove)) { // we can remove + keys.remove(keyToRemove); + } } + } - /** - * Sets whether messages matching the <code>key</code> are active or not. - * - * @param key - * key of messages - */ - public void setMessagesActive(String key, boolean active) { - for (IMessagesBundle msgBundle : localeBundles.values()) { - IMessage entry = msgBundle.getMessage(key); - if (entry != null) { - entry.setActive(active); - } - } - } + /** + * Gets this messages bundle group name. That is the name, which is used for + * the tab of the MultiPageEditorPart + * + * @return bundle group name + */ + @Override + public String getName() { + return name; + } - /** - * Duplicates each messages matching the <code>sourceKey</code> to the - * <code>newKey</code>. - * - * @param sourceKey - * original key - * @param targetKey - * new key - * @throws MessageException - * if a target key already exists - */ - public void duplicateMessages(String sourceKey, String targetKey) { - if (sourceKey.equals(targetKey)) { - return; - } - for (IMessagesBundle msgBundle : localeBundles.values()) { - msgBundle.duplicateMessage(sourceKey, targetKey); - } + /** + * Adds an empty message to every messages bundle of this group with the + * given. + * + * @param key + * message key + */ + @Override + public void addMessages(String key) { + for (IMessagesBundle msgBundle : localeBundles.values()) { + ((MessagesBundle) msgBundle).addMessage(key); } + } - /** - * Returns a collection of all bundles in this group. - * - * @return the bundles in this group - */ - @Override - public Collection<IMessagesBundle> getMessagesBundles() { - return localeBundles.values(); + /** + * Renames a key in all messages bundles forming this group. + * + * @param sourceKey + * the message key to rename + * @param targetKey + * the new message name + */ + public void renameMessageKeys(String sourceKey, String targetKey) { + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.renameMessageKey(sourceKey, targetKey); } + } - /** - * Gets all keys from all messages bundles. - * - * @return all keys from all messages bundles - */ - @Override - public String[] getMessageKeys() { - return keys.toArray(BabelUtils.EMPTY_STRINGS); + /** + * Removes messages matching the given key from all messages bundle. + * + * @param key + * key of messages to remove + */ + @Override + public void removeMessages(String key) { + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.removeMessage(key); } + } - /** - * Whether the given key is found in this messages bundle group. - * - * @param key - * the key to find - * @return <code>true</code> if the key exists in this bundle group. - */ - @Override - public boolean isMessageKey(String key) { - return keys.contains(key); + /** + * Removes messages matching the given key from all messages bundle and add + * it's parent key to bundles. + * + * @param key + * key of messages to remove + */ + @Override + public void removeMessagesAddParentKey(String key) { + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.removeMessageAddParentKey(key); } + } - /** - * Gets the number of messages bundles in this group. - * - * @return the number of messages bundles in this group - */ - @Override - public int getMessagesBundleCount() { - return localeBundles.size(); + /** + * Sets whether messages matching the <code>key</code> are active or not. + * + * @param key + * key of messages + */ + public void setMessagesActive(String key, boolean active) { + for (IMessagesBundle msgBundle : localeBundles.values()) { + IMessage entry = msgBundle.getMessage(key); + if (entry != null) { + entry.setActive(active); + } } + } - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!(obj instanceof MessagesBundleGroup)) { - return false; - } - MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj; - return equals(localeBundles, messagesBundleGroup.localeBundles); + /** + * Duplicates each messages matching the <code>sourceKey</code> to the + * <code>newKey</code>. + * + * @param sourceKey + * original key + * @param targetKey + * new key + * @throws MessageException + * if a target key already exists + */ + public void duplicateMessages(String sourceKey, String targetKey) { + if (sourceKey.equals(targetKey)) { + return; } - - public final synchronized void addMessagesBundleGroupListener( - final IMessagesBundleGroupListener listener) { - addPropertyChangeListener(listener); + for (IMessagesBundle msgBundle : localeBundles.values()) { + msgBundle.duplicateMessage(sourceKey, targetKey); } + } - public final synchronized void removeMessagesBundleGroupListener( - final IMessagesBundleGroupListener listener) { - removePropertyChangeListener(listener); - } + /** + * Returns a collection of all bundles in this group. + * + * @return the bundles in this group + */ + @Override + public Collection<IMessagesBundle> getMessagesBundles() { + return localeBundles.values(); + } - public final synchronized IMessagesBundleGroupListener[] getMessagesBundleGroupListeners() { - // TODO find more efficient way to avoid class cast. - return Arrays.asList(getPropertyChangeListeners()).toArray( - EMPTY_GROUP_LISTENERS); - } + /** + * Gets all keys from all messages bundles. + * + * @return all keys from all messages bundles + */ + @Override + public String[] getMessageKeys() { + return keys.toArray(BabelUtils.EMPTY_STRINGS); + } - private void fireKeyAdded(String key) { - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.keyAdded(key); - } - } + /** + * Whether the given key is found in this messages bundle group. + * + * @param key + * the key to find + * @return <code>true</code> if the key exists in this bundle group. + */ + @Override + public boolean isMessageKey(String key) { + return keys.contains(key); + } - private void fireKeyRemoved(String key) { - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.keyRemoved(key); - } - } + /** + * Gets the number of messages bundles in this group. + * + * @return the number of messages bundles in this group + */ + @Override + public int getMessagesBundleCount() { + return localeBundles.size(); + } - private void fireMessagesBundleAdded(MessagesBundle messagesBundle) { - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.messagesBundleAdded(messagesBundle); - } - } + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof MessagesBundleGroup)) { + return false; + } + MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj; + return equals(localeBundles, messagesBundleGroup.localeBundles); + } + + public final synchronized void addMessagesBundleGroupListener( + final IMessagesBundleGroupListener listener) { + addPropertyChangeListener(listener); + } + + public final synchronized void removeMessagesBundleGroupListener( + final IMessagesBundleGroupListener listener) { + removePropertyChangeListener(listener); + } + + public final synchronized IMessagesBundleGroupListener[] getMessagesBundleGroupListeners() { + // TODO find more efficient way to avoid class cast. + return Arrays.asList(getPropertyChangeListeners()).toArray( + EMPTY_GROUP_LISTENERS); + } + + private void fireKeyAdded(String key) { + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.keyAdded(key); + } + } + + private void fireKeyRemoved(String key) { + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.keyRemoved(key); + } + } + + private void fireMessagesBundleAdded(MessagesBundle messagesBundle) { + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messagesBundleAdded(messagesBundle); + } + } + + private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) { + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messagesBundleRemoved(messagesBundle); + } + } - private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) { - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.messagesBundleRemoved(messagesBundle); + /** + * Returns true if the supplied key is already existing in this group. + * + * @param key + * The key that shall be tested. + * + * @return true <=> The key is already existing. + */ + @Override + public boolean containsKey(String key) { + for (Locale locale : localeBundles.keySet()) { + IMessagesBundle messagesBundle = localeBundles.get(locale); + for (String k : messagesBundle.getKeys()) { + if (k.equals(key)) { + return true; + } else { + continue; } + } } + return false; + } + + /** + * Is the given key found in this bundle group. + * + * @param key + * the key to find + * @return <code>true</code> if the key exists in this bundle group. + */ + @Override + public boolean isKey(String key) { + return keys.contains(key); + } + + /** + * Gets the unique id of the bundle group. That is usually: + * <directory>"."<default-filename>. The default filename is without the + * suffix (e.g. _en, or _en_GB). + * + * @return The unique identifier for the resource bundle group + */ + @Override + public String getResourceBundleId() { + return resourceBundleId; + } + + /** + * Gets the name of the project, the resource bundle group is in. + * + * @return The project name + */ + @Override + public String getProjectName() { + return this.projectName; + } - /** - * Returns true if the supplied key is already existing in this group. - * - * @param key - * The key that shall be tested. - * - * @return true <=> The key is already existing. - */ + /** + * Class listening for changes in underlying messages bundle and relays them + * to the listeners for MessagesBundleGroup. + */ + private class MessagesBundleListener implements IMessagesBundleListener { @Override - public boolean containsKey(String key) { - for (Locale locale : localeBundles.keySet()) { - IMessagesBundle messagesBundle = localeBundles.get(locale); - for (String k : messagesBundle.getKeys()) { - if (k.equals(key)) { - return true; - } else { - continue; - } - } + public void messageAdded(MessagesBundle messagesBundle, Message message) { + int oldCount = keys.size(); + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messageAdded(messagesBundle, message); + if (getMessages(message.getKey()).length == 1) { + keys.add(message.getKey()); + firePropertyChange(PROPERTY_KEY_COUNT, oldCount, + keys.size()); + fireKeyAdded(message.getKey()); } - return false; + } } - /** - * Is the given key found in this bundle group. - * - * @param key - * the key to find - * @return <code>true</code> if the key exists in this bundle group. - */ @Override - public boolean isKey(String key) { - return keys.contains(key); + public void messageRemoved(MessagesBundle messagesBundle, + Message message) { + int oldCount = keys.size(); + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messageRemoved(messagesBundle, message); + int keyMessagesCount = getMessages(message.getKey()).length; + if (keyMessagesCount == 0 && keys.contains(message.getKey())) { + keys.remove(message.getKey()); + firePropertyChange(PROPERTY_KEY_COUNT, oldCount, + keys.size()); + fireKeyRemoved(message.getKey()); + } + } } - /** - * Gets the unique id of the bundle group. That is usually: <directory>"."<default-filename>. - * The default filename is without the suffix (e.g. _en, or _en_GB). - * @return The unique identifier for the resource bundle group - */ @Override - public String getResourceBundleId() { - return resourceBundleId; + public void messageChanged(MessagesBundle messagesBundle, + PropertyChangeEvent changeEvent) { + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messageChanged(messagesBundle, changeEvent); + } } - /** - * Gets the name of the project, the resource bundle group is in. - * @return The project name - */ + // MessagesBundle property changes: @Override - public String getProjectName() { - return this.projectName; - } - - /** - * Class listening for changes in underlying messages bundle and relays them - * to the listeners for MessagesBundleGroup. - */ - private class MessagesBundleListener implements IMessagesBundleListener { - @Override - public void messageAdded(MessagesBundle messagesBundle, Message message) { - int oldCount = keys.size(); - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.messageAdded(messagesBundle, message); - if (getMessages(message.getKey()).length == 1) { - keys.add(message.getKey()); - firePropertyChange(PROPERTY_KEY_COUNT, oldCount, - keys.size()); - fireKeyAdded(message.getKey()); - } - } - } - - @Override - public void messageRemoved(MessagesBundle messagesBundle, - Message message) { - int oldCount = keys.size(); - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.messageRemoved(messagesBundle, message); - int keyMessagesCount = getMessages(message.getKey()).length; - if (keyMessagesCount == 0 && keys.contains(message.getKey())) { - keys.remove(message.getKey()); - firePropertyChange(PROPERTY_KEY_COUNT, oldCount, - keys.size()); - fireKeyRemoved(message.getKey()); - } - } - } - - @Override - public void messageChanged(MessagesBundle messagesBundle, - PropertyChangeEvent changeEvent) { - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.messageChanged(messagesBundle, changeEvent); - } - } - - // MessagesBundle property changes: - @Override - public void propertyChange(PropertyChangeEvent evt) { - MessagesBundle bundle = (MessagesBundle) evt.getSource(); - IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); - for (int i = 0; i < listeners.length; i++) { - IMessagesBundleGroupListener listener = listeners[i]; - listener.messagesBundleChanged(bundle, evt); - } - } + public void propertyChange(PropertyChangeEvent evt) { + MessagesBundle bundle = (MessagesBundle) evt.getSource(); + IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners(); + for (int i = 0; i < listeners.length; i++) { + IMessagesBundleGroupListener listener = listeners[i]; + listener.messagesBundleChanged(bundle, evt); + } } + } - /** - * @return <code>true</code> if the bundle group has {@link PropertiesFileGroupStrategy} as strategy, - * else <code>false</code>. This is the case, when only TapiJI edits the resource bundles and no - * have been opened. - */ - @Override - public boolean hasPropertiesFileGroupStrategy() { - return groupStrategy instanceof PropertiesFileGroupStrategy; - } + /** + * @return <code>true</code> if the bundle group has + * {@link PropertiesFileGroupStrategy} as strategy, else + * <code>false</code>. This is the case, when only TapiJI edits the + * resource bundles and no have been opened. + */ + @Override + public boolean hasPropertiesFileGroupStrategy() { + return groupStrategy instanceof PropertiesFileGroupStrategy; + } } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java index d1c760c6..892b8aa8 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java @@ -12,6 +12,7 @@ package org.eclipse.babel.core.message.manager; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; @@ -94,7 +95,11 @@ private boolean isResourceBundleFile(IResource file) { private List<CheckItem> getBlacklistItems() { IConfiguration configuration = ConfigurationManager.getInstance() .getConfiguration(); - return convertStringToList(configuration.getNonRbPattern()); + if (configuration != null) { + return convertStringToList(configuration.getNonRbPattern()); + } else { + return new ArrayList<CheckItem>(); + } } private static final String DELIMITER = ";"; diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java index 2a2f8db4..c8c5b147 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java @@ -31,20 +31,19 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; - /** * MessagesBundleGroup strategy for standard Java properties file structure. * That is, all *.properties files of the same base name within the same - * directory. This implementation works on files outside the Eclipse - * workspace. + * directory. This implementation works on files outside the Eclipse workspace. + * * @author Pascal Essiembre */ -public class PropertiesFileGroupStrategy implements IMessagesBundleGroupStrategy { +public class PropertiesFileGroupStrategy implements + IMessagesBundleGroupStrategy { /** Empty bundle array. */ - private static final MessagesBundle[] EMPTY_MESSAGES = - new MessagesBundle[] {}; - + private static final MessagesBundle[] EMPTY_MESSAGES = new MessagesBundle[] {}; + /** File being open, triggering the creation of a bundle group. */ private File file; /** MessagesBundle group base name. */ @@ -57,153 +56,153 @@ public class PropertiesFileGroupStrategy implements IMessagesBundleGroupStrategy private final IPropertiesSerializerConfig serializerConfig; /** Properties file deserializer configuration. */ private final IPropertiesDeserializerConfig deserializerConfig; - - + /** * Constructor. - * @param file file from which to derive the group + * + * @param file + * file from which to derive the group */ - public PropertiesFileGroupStrategy( - File file, - IPropertiesSerializerConfig serializerConfig, - IPropertiesDeserializerConfig deserializerConfig) { - super(); - this.serializerConfig = serializerConfig; - this.deserializerConfig = deserializerConfig; - this.file = file; - this.fileExtension = file.getName().replaceFirst( - "(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$ - - String patternCore = - "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ - + fileExtension + ")$"; //$NON-NLS-1$ - - // Compute and cache name - String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$ - this.baseName = file.getName().replaceFirst( - namePattern, "$1"); //$NON-NLS-1$ - - // File matching pattern - this.fileMatchPattern = - "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$ + public PropertiesFileGroupStrategy(File file, + IPropertiesSerializerConfig serializerConfig, + IPropertiesDeserializerConfig deserializerConfig) { + super(); + this.serializerConfig = serializerConfig; + this.deserializerConfig = deserializerConfig; + this.file = file; + this.fileExtension = file.getName().replaceFirst("(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$ + + String patternCore = "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ + + fileExtension + ")$"; //$NON-NLS-1$ + + // Compute and cache name + String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$ + this.baseName = file.getName().replaceFirst(namePattern, "$1"); //$NON-NLS-1$ + + // File matching pattern + this.fileMatchPattern = "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$ } /** * @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy - * #getMessagesBundleGroupName() + * #getMessagesBundleGroupName() */ public String createMessagesBundleGroupName() { - return baseName + "[...]." + fileExtension; //$NON-NLS-1$ + return baseName + "[...]." + fileExtension; //$NON-NLS-1$ } /** * @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy - * #loadMessagesBundles() + * #loadMessagesBundles() */ public MessagesBundle[] loadMessagesBundles() throws MessageException { - File[] resources = null; - File parentDir = file.getParentFile(); - if (parentDir != null) { - resources = parentDir.listFiles(); - } - Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>(); - if (resources != null) { - for (int i = 0; i < resources.length; i++) { - File resource = resources[i]; - String resourceName = resource.getName(); - if (resource.isFile() - && resourceName.matches(fileMatchPattern)) { - // Build local title - String localeText = resourceName.replaceFirst( - fileMatchPattern, "$2"); //$NON-NLS-1$ - Locale locale = BabelUtils.parseLocale(localeText); - bundles.add(createBundle(locale, resource)); - } - } - } - return bundles.toArray(EMPTY_MESSAGES); + File[] resources = null; + File parentDir = file.getParentFile(); + if (parentDir != null) { + resources = parentDir.listFiles(); + } + Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>(); + if (resources != null) { + for (int i = 0; i < resources.length; i++) { + File resource = resources[i]; + String resourceName = resource.getName(); + if (resource.isFile() && resourceName.matches(fileMatchPattern)) { + // Build local title + String localeText = resourceName.replaceFirst( + fileMatchPattern, "$2"); //$NON-NLS-1$ + Locale locale = BabelUtils.parseLocale(localeText); + bundles.add(createBundle(locale, resource)); + } + } + } + return bundles.toArray(EMPTY_MESSAGES); } /** * @see org.eclipse.babel.core.bundle.IBundleGroupStrategy - * #createBundle(java.util.Locale) + * #createBundle(java.util.Locale) */ public MessagesBundle createMessagesBundle(Locale locale) { - // TODO Implement me (code exists in SourceForge version) - return null; + // TODO Implement me (code exists in SourceForge version) + return null; } - + /** * Creates a resource bundle for an existing resource. - * @param locale locale for which to create a bundle - * @param resource resource used to create bundle + * + * @param locale + * locale for which to create a bundle + * @param resource + * resource used to create bundle * @return an initialized bundle */ protected MessagesBundle createBundle(Locale locale, File resource) - throws MessageException { - try { - //TODO have the text de/serializer tied to Eclipse preferences, - //singleton per project, and listening for changes - return new MessagesBundle(new PropertiesFileResource( - locale, - new PropertiesSerializer(serializerConfig), - new PropertiesDeserializer(deserializerConfig), - resource)); - } catch (FileNotFoundException e) { - throw new MessageException( - "Cannot create bundle for locale " //$NON-NLS-1$ - + locale + " and resource " + resource, e); //$NON-NLS-1$ - } + throws MessageException { + try { + // TODO have the text de/serializer tied to Eclipse preferences, + // singleton per project, and listening for changes + return new MessagesBundle(new PropertiesFileResource(locale, + new PropertiesSerializer(serializerConfig), + new PropertiesDeserializer(deserializerConfig), resource)); + } catch (FileNotFoundException e) { + throw new MessageException("Cannot create bundle for locale " //$NON-NLS-1$ + + locale + " and resource " + resource, e); //$NON-NLS-1$ + } } - + public String createMessagesBundleId() { - String path = file.getAbsolutePath(); - int index = path.indexOf("src"); - String pathBeforeSrc = path.substring(0, index - 1); - int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar); - String projectName = path.substring(lastIndexOf + 1, index - 1); - String relativeFilePath = path.substring(index, path.length()); - - IFile f = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(relativeFilePath); - - return NameUtils.getResourceBundleId(f); + String path = file.getAbsolutePath(); + int index = path.indexOf("src"); + String pathBeforeSrc = path.substring(0, index - 1); + int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar); + String projectName = path.substring(lastIndexOf + 1, index - 1); + String relativeFilePath = path.substring(index, path.length()); + + IFile f = ResourcesPlugin.getWorkspace().getRoot() + .getProject(projectName).getFile(relativeFilePath); + + return NameUtils.getResourceBundleId(f); } - + public String getProjectName() { - IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation(); - IPath fullPath = null; - if (this.file.getAbsolutePath().contains(path.toOSString())) { - fullPath = new Path(this.file.getAbsolutePath()); - } else { - fullPath = new Path(path.toOSString() + this.file.getAbsolutePath()); - } - - IFile file = ResourcesPlugin - .getWorkspace() - .getRoot() - .getFileForLocation(fullPath); - - return ResourcesPlugin.getWorkspace().getRoot().getProject(file.getFullPath().segments()[0]).getName(); + IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation(); + IPath fullPath = null; + if (this.file.getAbsolutePath().contains(path.toOSString())) { + fullPath = new Path(this.file.getAbsolutePath()); + } else { + fullPath = new Path(path.toOSString() + this.file.getAbsolutePath()); + } + + IFile file = ResourcesPlugin.getWorkspace().getRoot() + .getFileForLocation(fullPath); + + if (file != null) { + return ResourcesPlugin.getWorkspace().getRoot() + .getProject(file.getFullPath().segments()[0]).getName(); + } else { + return null; + } + } - -// public static String getResourceBundleId (IResource resource) { -// String packageFragment = ""; -// -// IJavaElement propertyFile = JavaCore.create(resource.getParent()); -// if (propertyFile != null && propertyFile instanceof IPackageFragment) -// packageFragment = ((IPackageFragment) propertyFile).getElementName(); -// -// return (packageFragment.length() > 0 ? packageFragment + "." : "") + -// getResourceBundleName(resource); -// } -// -// public static String getResourceBundleName(IResource res) { -// String name = res.getName(); -// String regex = "^(.*?)" //$NON-NLS-1$ -// + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ -// + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ -// + res.getFileExtension() + ")$"; //$NON-NLS-1$ -// return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ -// } + + // public static String getResourceBundleId (IResource resource) { + // String packageFragment = ""; + // + // IJavaElement propertyFile = JavaCore.create(resource.getParent()); + // if (propertyFile != null && propertyFile instanceof IPackageFragment) + // packageFragment = ((IPackageFragment) propertyFile).getElementName(); + // + // return (packageFragment.length() > 0 ? packageFragment + "." : "") + + // getResourceBundleName(resource); + // } + // + // public static String getResourceBundleName(IResource res) { + // String name = res.getName(); + // String regex = "^(.*?)" //$NON-NLS-1$ + // + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ + // + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ + // + res.getFileExtension() + ")$"; //$NON-NLS-1$ + // return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ + // } } diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java index 887626f7..cd4a9d88 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java @@ -1,290 +1,245 @@ -/* - * Copyright (C) 2007 Uwe Voigt +/******************************************************************************* + * Copyright (c) 2012 Stefan Reiterer. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html * - * This file is part of Essiembre ResourceBundle Editor. - * - * Essiembre ResourceBundle Editor is free software; you can redistribute it - * and/or modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * Essiembre ResourceBundle Editor 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Essiembre ResourceBundle Editor; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307 USA - */ + * Contributors: + * Stefan Reiterer - initial API and implementation + ******************************************************************************/ + package org.eclipse.babel.core.util; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; -import java.util.StringTokenizer; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.osgi.framework.Constants; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.osgi.service.resolver.BundleDescription; +import org.eclipse.osgi.service.resolver.HostSpecification; +import org.eclipse.pde.core.plugin.IFragmentModel; +import org.eclipse.pde.core.plugin.IPluginBase; +import org.eclipse.pde.core.plugin.IPluginModelBase; +import org.eclipse.pde.core.plugin.PluginRegistry; -/** - * A class that helps to find fragment and plugin projects. - * - * @author Uwe Voigt (http://sourceforge.net/users/uwe_ewald/) - */ public class PDEUtils { - - /** Bundle manifest name */ - public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$ - /** Plugin manifest name */ - public static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$ - /** Fragment manifest name */ - public static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$ - /** - * Returns the plugin-id of the project if it is a plugin project. Else - * null is returned. + // The same as PDE.PLUGIN_NATURE, because the PDE provided constant is not accessible (internal class) + private static final String PLUGIN_NATURE = "org.eclipse.pde.PluginNature"; + + /** + * Get the project's plug-in Id if the given project is an eclipse plug-in. * - * @param project the project - * @return the plugin-id or null + * @param project the workspace project. + * @return the project's plug-in Id. Null if the project is no plug-in project. */ public static String getPluginId(IProject project) { - if (project == null) + + if (project == null || !isPluginProject(project)) { + return null; + } + + IPluginModelBase pluginModelBase = PluginRegistry.findModel(project); + + if (pluginModelBase == null) { + // plugin not found in registry return null; - IResource manifest = project.findMember(OSGI_BUNDLE_MANIFEST); - String id = getManifestEntryValue(manifest, Constants.BUNDLE_SYMBOLICNAME); - if (id != null) - return id; - manifest = project.findMember(PLUGIN_MANIFEST); - if (manifest == null) - manifest = project.findMember(FRAGMENT_MANIFEST); - if (manifest instanceof IFile) { - InputStream in = null; - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - in = ((IFile) manifest).getContents(); - Document document = builder.parse(in); - Node node = getXMLElement(document, "plugin"); //$NON-NLS-1$ - if (node == null) - node = getXMLElement(document, "fragment"); //$NON-NLS-1$ - if (node != null) - node = node.getAttributes().getNamedItem("id"); //$NON-NLS-1$ - if (node != null) - return node.getNodeValue(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (in != null) - in.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return null; + } + + IPluginBase pluginBase = pluginModelBase.getPluginBase(); + + return pluginBase.getId(); } /** - * Returns all project containing plugin/fragment of the specified - * project. If the specified project itself is a fragment, then only this is returned. - * - * @param pluginProject the plugin project - * @return the all project containing a fragment or null if none - */ - public static IProject[] lookupFragment(IProject pluginProject) { - List<IProject> fragmentIds = new ArrayList<IProject>(); - - String pluginId = PDEUtils.getPluginId(pluginProject); - if (pluginId == null) + * Returns all project containing plugin/fragment of the specified project. + * If the specified project itself is a fragment, then only this is + * returned. + * + * @param pluginProject + * the plugin project + * @return the all project containing a fragment or null if none + */ + public static IProject[] lookupFragment(IProject pluginProject) { + if (isFragment(pluginProject) && pluginProject.isOpen()) { + return new IProject[] {pluginProject}; + } + + IProject[] workspaceProjects = pluginProject.getWorkspace().getRoot().getProjects(); + String hostPluginId = getPluginId(pluginProject); + + if (hostPluginId == null) { + // project is not a plugin project return null; - String fragmentId = getFragmentId(pluginProject, getPluginId(getFragmentHost(pluginProject))); - if (fragmentId != null){ - fragmentIds.add(pluginProject); - return fragmentIds.toArray(new IProject[0]); } - IProject[] projects = pluginProject.getWorkspace().getRoot().getProjects(); - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - if (!project.isOpen()) + List<IProject> fragmentProjects = new ArrayList<IProject>(); + for (IProject project : workspaceProjects) { + if (!project.isOpen() || getFragmentId(project, hostPluginId) == null) { + // project is not open or it is no fragment where given project is the host project. continue; - if (getFragmentId(project, pluginId) == null) - continue; - fragmentIds.add(project); + } + fragmentProjects.add(project); } - - if (fragmentIds.size() > 0) return fragmentIds.toArray(new IProject[0]); - else return null; - } - public static boolean isFragment(IProject pluginProject){ - String pluginId = PDEUtils.getPluginId(pluginProject); - if (pluginId == null) + if (fragmentProjects.isEmpty()) { + return null; + } + + return fragmentProjects.toArray(new IProject[0]); + } + + /** + * Check if the given plug-in project is a fragment. + * + * @param pluginProject the plug-in project in the workspace. + * @return true if it is a fragment, otherwise false. + */ + public static boolean isFragment(IProject pluginProject) { + if (pluginProject == null) { return false; - String fragmentId = getFragmentId(pluginProject, getPluginId(getFragmentHost(pluginProject))); - if (fragmentId != null) - return true; - else + } + + IPluginModelBase pModel = PluginRegistry.findModel(pluginProject); + + if (pModel == null) { + // this project is not a plugin/fragment return false; - } - - public static List<IProject> getFragments(IProject hostProject){ - List<IProject> fragmentIds = new ArrayList<IProject>(); - - String pluginId = PDEUtils.getPluginId(hostProject); - IProject[] projects = hostProject.getWorkspace().getRoot().getProjects(); - - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - if (!project.isOpen()) - continue; - if (getFragmentId(project, pluginId) == null) - continue; - fragmentIds.add(project); } - - return fragmentIds; - } - - /** + + return pModel.isFragmentModel(); + } + + /** + * Get all fragments for the given host project. + * + * @param hostProject the host plug-in project in the workspace. + * @return a list of all fragment projects for the given host project which are in the same workspace as the host project. + */ + public static List<IProject> getFragments(IProject hostProject) { + // Check preconditions + String hostId = getPluginId(hostProject); + if (hostProject == null || hostId == null) { + // no valid host project given. + return Collections.emptyList(); + } + + // Get the fragments of the host project + IPluginModelBase pModelBase = PluginRegistry.findModel(hostProject); + BundleDescription desc = pModelBase.getBundleDescription(); + + ArrayList<IPluginModelBase> fragmentModels = new ArrayList<IPluginModelBase>(); + if (desc == null) { + // There is no bundle description for the host project + return Collections.emptyList(); + } + + BundleDescription[] f = desc.getFragments(); + for (BundleDescription candidateDesc : f) { + IPluginModelBase candidate = PluginRegistry.findModel(candidateDesc); + if (candidate instanceof IFragmentModel) { + fragmentModels.add(candidate); + } + } + + // Get the fragment project which is in the current workspace + ArrayList<IProject> fragments = getFragmentsAsWorkspaceProjects(hostProject, fragmentModels); + + return fragments; + } + + /** * Returns the fragment-id of the project if it is a fragment project with * the specified host plugin id as host. Else null is returned. * - * @param project the project - * @param hostPluginId the host plugin id + * @param project + * the project + * @param hostPluginId + * the host plugin id * @return the plugin-id or null */ - public static String getFragmentId(IProject project, String hostPluginId) { - IResource manifest = project.findMember(FRAGMENT_MANIFEST); - Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$ - if (fragmentNode != null) { - Node hostNode = fragmentNode.getAttributes().getNamedItem("plugin-id"); //$NON-NLS-1$ - if (hostNode != null && hostNode.getNodeValue().equals(hostPluginId)) { - Node idNode = fragmentNode.getAttributes().getNamedItem("id"); //$NON-NLS-1$ - if (idNode != null) - return idNode.getNodeValue(); - } + public static String getFragmentId(IProject project, String hostPluginId) { + if (!isFragment(project) || hostPluginId == null) { + return null; } - manifest = project.findMember(OSGI_BUNDLE_MANIFEST); - String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST); - if (hostId != null && hostId.equals(hostPluginId)) - return getManifestEntryValue(manifest, Constants.BUNDLE_SYMBOLICNAME); - return null; - } - - /** - * Returns the host plugin project of the specified project if it contains a fragment. - * - * @param fragment the fragment project - * @return the host plugin project or null - */ - public static IProject getFragmentHost(IProject fragment) { - IResource manifest = fragment.findMember(FRAGMENT_MANIFEST); - Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$ - if (fragmentNode != null) { - Node hostNode = fragmentNode.getAttributes().getNamedItem("plugin-id"); //$NON-NLS-1$ - if (hostNode != null) - return fragment.getWorkspace().getRoot().getProject(hostNode.getNodeValue()); + + IPluginModelBase pluginModelBase = PluginRegistry.findModel(project); + if (pluginModelBase instanceof IFragmentModel) { + IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase; + BundleDescription description = fragmentModel.getBundleDescription(); + HostSpecification hostSpecification = description.getHost(); + + if (hostPluginId.equals(hostSpecification.getName())) { + return getPluginId(project); + } } - manifest = fragment.findMember(OSGI_BUNDLE_MANIFEST); - String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST); - if (hostId != null) - return fragment.getWorkspace().getRoot().getProject(hostId); return null; } /** - * Returns the file content as UTF8 string. + * Returns the host plugin project of the specified project if it contains a + * fragment. * - * @param file - * @param charset - * @return + * @param fragment + * the fragment project + * @return the host plugin project or null */ - public static String getFileContent(IFile file, String charset) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - InputStream in = null; - try { - in = file.getContents(true); - byte[] buf = new byte[8000]; - for (int count; (count = in.read(buf)) != -1;) - outputStream.write(buf, 0, count); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ignore) { - } - } - } - try { - return outputStream.toString(charset); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return outputStream.toString(); + public static IProject getFragmentHost(IProject fragment) { + if (!isFragment(fragment)) { + return null; + } + + IPluginModelBase pluginModelBase = PluginRegistry.findModel(fragment); + if (pluginModelBase instanceof IFragmentModel) { + IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase; + BundleDescription description = fragmentModel.getBundleDescription(); + HostSpecification hostSpecification = description.getHost(); + + IPluginModelBase hostProject = PluginRegistry.findModel(hostSpecification.getName()); + IProject[] projects = fragment.getWorkspace().getRoot().getProjects(); + ArrayList<IProject> hostProjects = getPluginProjects(Arrays.asList(hostProject), projects); + + if (hostProjects.size() != 1) { + // hostproject not in workspace + return null; + } else { + return hostProjects.get(0); + } } + + return null; } - private static String getManifestEntryValue(IResource manifest, String entryKey) { - if (manifest instanceof IFile) { - String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$ - int index = content.indexOf(entryKey); - if (index != -1) { - StringTokenizer st = new StringTokenizer(content.substring(index - + entryKey.length()), ";:\r\n"); //$NON-NLS-1$ - return st.nextToken().trim(); - } - } - return null; - } + private static ArrayList<IProject> getFragmentsAsWorkspaceProjects(IProject hostProject, ArrayList<IPluginModelBase> fragmentModels) { + IProject[] projects = hostProject.getWorkspace().getRoot().getProjects(); + + ArrayList<IProject> fragments = getPluginProjects(fragmentModels, projects); + + return fragments; + } - private static Document getXMLDocument(IResource resource) { - if (!(resource instanceof IFile)) - return null; - InputStream in = null; - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - in = ((IFile) resource).getContents(); - return builder.parse(in); - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - try { - if (in != null) - in.close(); - } catch (Exception e) { - e.printStackTrace(); + private static ArrayList<IProject> getPluginProjects(List<IPluginModelBase> fragmentModels, IProject[] projects) { + ArrayList<IProject> fragments = new ArrayList<IProject>(); + for (IProject project : projects) { + IPluginModelBase pModel = PluginRegistry.findModel(project); + + if (fragmentModels.contains(pModel)) { + fragments.add(project); } } - } - - private static Node getXMLElement(Document document, String name) { - if (document == null) - return null; - NodeList list = document.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - Node node = list.item(i); - if (node.getNodeType() != Node.ELEMENT_NODE) - continue; - if (name.equals(node.getNodeName())) - return node; + + return fragments; + } + + private static boolean isPluginProject(IProject project) { + try { + return project.hasNature(PLUGIN_NATURE); + } catch (CoreException ce) { + //Logger.logError(ce); } - return null; - } - -} + return false; + } +} \ No newline at end of file diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java index b0ead893..f0710190 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java @@ -10,10 +10,11 @@ ******************************************************************************/ package org.eclipse.babel.editor.api; +import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer; import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer; /** - * Provides the {@link ILevenshteinDistanceAnalyzer} + * Provides the {@link IProximityAnalyzer} * <br><br> * * @author Alexej Strelzow @@ -23,7 +24,7 @@ public class AnalyzerFactory { /** * @return An instance of the {@link LevenshteinDistanceAnalyzer} */ - public static ILevenshteinDistanceAnalyzer getLevenshteinDistanceAnalyzer () { - return (ILevenshteinDistanceAnalyzer) LevenshteinDistanceAnalyzer.getInstance(); + public static IProximityAnalyzer getLevenshteinDistanceAnalyzer () { + return (IProximityAnalyzer) LevenshteinDistanceAnalyzer.getInstance(); } } diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java deleted file mode 100644 index fcf0ff6c..00000000 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Martin Reiterer. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.editor.api; - -public interface ILevenshteinDistanceAnalyzer { - - double analyse(Object value, Object pattern); - -} diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java index 41af9dce..aee3c114 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java @@ -12,15 +12,15 @@ import java.util.Locale; +import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer; import org.eclipse.babel.editor.api.AnalyzerFactory; -import org.eclipse.babel.editor.api.ILevenshteinDistanceAnalyzer; import org.eclipse.babel.editor.api.IValuedKeyTreeNode; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; public class FuzzyMatcher extends ExactMatcher { - protected ILevenshteinDistanceAnalyzer lvda; + protected IProximityAnalyzer lvda; protected float minimumSimilarity = 0.75f; public FuzzyMatcher(StructuredViewer viewer) { diff --git a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF index 3f1023cd..d9209fe7 100644 --- a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF @@ -12,7 +12,7 @@ Require-Bundle: org.eclipse.core.runtime, org.eclipse.ui.ide;bundle-version="3.7.0", org.eclipse.ui;bundle-version="3.7.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: org.apache.commons.io, +Import-Package: org.eclipse.core.filebuffers, org.eclipse.core.resources, org.eclipse.jdt.core, diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java index 733b4f78..8bfd10a5 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java @@ -15,30 +15,30 @@ public class Logger { - public static void logInfo(String message) { - log(IStatus.INFO, IStatus.OK, message, null); - } - - public static void logError(Throwable exception) { - logError("Unexpected Exception", exception); - } - - public static void logError(String message, Throwable exception) { - log(IStatus.ERROR, IStatus.OK, message, exception); - } - - public static void log(int severity, int code, String message, - Throwable exception) { - log(createStatus(severity, code, message, exception)); - } - - public static IStatus createStatus(int severity, int code, String message, - Throwable exception) { - return new Status(severity, Activator.PLUGIN_ID, code, message, - exception); - } - - public static void log(IStatus status) { - Activator.getDefault().getLog().log(status); - } + public static void logInfo(String message) { + log(IStatus.INFO, IStatus.OK, message, null); + } + + public static void logError(Throwable exception) { + logError("Unexpected Exception", exception); + } + + public static void logError(String message, Throwable exception) { + log(IStatus.ERROR, IStatus.OK, message, exception); + } + + public static void log(int severity, int code, String message, + Throwable exception) { + log(createStatus(severity, code, message, exception)); + } + + public static IStatus createStatus(int severity, int code, String message, + Throwable exception) { + return new Status(severity, Activator.PLUGIN_ID, code, message, + exception); + } + + public static void log(IStatus status) { + Activator.getDefault().getLog().log(status); + } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java index 208bd033..491d0872 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java @@ -11,13 +11,13 @@ ******************************************************************************/ package org.eclipse.babel.tapiji.tools.core.util; +import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; -import java.io.IOException; +import java.io.FileReader; import org.eclipse.babel.tapiji.tools.core.Activator; import org.eclipse.babel.tapiji.tools.core.Logger; -import org.eclipse.core.internal.resources.ResourceException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; @@ -25,46 +25,57 @@ public class FileUtils { - public static String readFile(IResource resource) { - return readFileAsString(resource.getRawLocation().toFile()); - } + public static String readFile(IResource resource) { + return readFileAsString(resource.getRawLocation().toFile()); + } - protected static String readFileAsString(File filePath) { - String content = ""; + protected static String readFileAsString(File filePath) { + String content = ""; - try { - content = org.apache.commons.io.FileUtils - .readFileToString(filePath); - } catch (IOException e) { - Logger.logError(e); - } + if (!filePath.exists()) + return content; + try { + BufferedReader fileReader = new BufferedReader(new FileReader( + filePath)); + String line = ""; - return content; - } + while ((line = fileReader.readLine()) != null) { + content += line + "\n"; + } - public static File getRBManagerStateFile() { - return Activator.getDefault().getStateLocation() - .append("internationalization.xml").toFile(); + // close filereader + fileReader.close(); + } catch (Exception e) { + // TODO log error output + Logger.logError(e); } - /** - * Don't use that -> causes {@link ResourceException} -> because File out of - * sync - * - * @param file - * @param editorContent - * @throws CoreException - * @throws OperationCanceledException - */ - public synchronized void saveTextFile(IFile file, String editorContent) - throws CoreException, OperationCanceledException { - try { - file.setContents( - new ByteArrayInputStream(editorContent.getBytes()), false, - true, null); - } catch (Exception e) { - e.printStackTrace(); - } + return content; + } + + public static File getRBManagerStateFile() { + return Activator.getDefault().getStateLocation() + .append("internationalization.xml").toFile(); + } + + /** + * Don't use that -> causes {@link ResourceException} -> because File out of + * sync + * + * @param file + * @param editorContent + * @throws CoreException + * @throws OperationCanceledException + */ + public synchronized void saveTextFile(IFile file, String editorContent) + throws CoreException, OperationCanceledException { + try { + file.setContents( + new ByteArrayInputStream(editorContent.getBytes()), false, + true, null); + } catch (Exception e) { + e.printStackTrace(); } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java index 3e7e03d8..fcb60328 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java @@ -10,8 +10,8 @@ ******************************************************************************/ package org.eclipselabs.tapiji.translator.views.widgets.filter; +import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer; import org.eclipse.babel.editor.api.AnalyzerFactory; -import org.eclipse.babel.editor.api.ILevenshteinDistanceAnalyzer; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipselabs.tapiji.translator.model.Term; @@ -19,7 +19,7 @@ public class FuzzyMatcher extends ExactMatcher { - protected ILevenshteinDistanceAnalyzer lvda; + protected IProximityAnalyzer lvda; protected float minimumSimilarity = 0.75f; public FuzzyMatcher(StructuredViewer viewer) {
a7a3653b7006297958e79146aa46011d6060099f
hadoop
HADOOP-7341. Fix options parsing in CommandFormat.- Contributed by Daryn Sharp.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1132505 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index 16152a6c9f688..cabe26cebf230 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -278,6 +278,8 @@ Trunk (unreleased changes) HADOOP-7284 Trash and shell's rm does not work for viewfs (Sanjay Radia) + HADOOP-7341. Fix options parsing in CommandFormat (Daryn Sharp via todd) + Release 0.22.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/fs/FsShellPermissions.java b/src/java/org/apache/hadoop/fs/FsShellPermissions.java index 839f954f92dc2..41c9f4b367027 100644 --- a/src/java/org/apache/hadoop/fs/FsShellPermissions.java +++ b/src/java/org/apache/hadoop/fs/FsShellPermissions.java @@ -80,7 +80,7 @@ public static class Chmod extends FsShellPermissions { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 2, Integer.MAX_VALUE, "R", null); + CommandFormat cf = new CommandFormat(2, Integer.MAX_VALUE, "R", null); cf.parse(args); setRecursive(cf.getOpt("R")); @@ -143,7 +143,7 @@ public static class Chown extends FsShellPermissions { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 2, Integer.MAX_VALUE, "R"); + CommandFormat cf = new CommandFormat(2, Integer.MAX_VALUE, "R"); cf.parse(args); setRecursive(cf.getOpt("R")); parseOwnerGroup(args.removeFirst()); diff --git a/src/java/org/apache/hadoop/fs/shell/CommandFormat.java b/src/java/org/apache/hadoop/fs/shell/CommandFormat.java index e72e553d72be3..eea429a97e5f1 100644 --- a/src/java/org/apache/hadoop/fs/shell/CommandFormat.java +++ b/src/java/org/apache/hadoop/fs/shell/CommandFormat.java @@ -29,14 +29,30 @@ * Parse the args of a command and check the format of args. */ public class CommandFormat { - final String name; final int minPar, maxPar; final Map<String, Boolean> options = new HashMap<String, Boolean>(); boolean ignoreUnknownOpts = false; - /** constructor */ + /** + * @deprecated use replacement since name is an unused parameter + * @param name of command, but never used + * @param min see replacement + * @param max see replacement + * @param possibleOpt see replacement + * @see #CommandFormat(int, int, String...) + */ + @Deprecated public CommandFormat(String n, int min, int max, String ... possibleOpt) { - name = n; + this(min, max, possibleOpt); + } + + /** + * Simple parsing of command line arguments + * @param min minimum arguments required + * @param max maximum arguments permitted + * @param possibleOpt list of the allowed switches + */ + public CommandFormat(int min, int max, String ... possibleOpt) { minPar = min; maxPar = max; for (String opt : possibleOpt) { @@ -71,16 +87,23 @@ public void parse(List<String> args) { int pos = 0; while (pos < args.size()) { String arg = args.get(pos); - if (arg.startsWith("-") && arg.length() > 1) { - String opt = arg.substring(1); - if (options.containsKey(opt)) { - args.remove(pos); - options.put(opt, Boolean.TRUE); - continue; - } - if (!ignoreUnknownOpts) throw new UnknownOptionException(arg); + // stop if not an opt, or the stdin arg "-" is found + if (!arg.startsWith("-") || arg.equals("-")) { + break; + } else if (arg.equals("--")) { // force end of option processing + args.remove(pos); + break; + } + + String opt = arg.substring(1); + if (options.containsKey(opt)) { + args.remove(pos); + options.put(opt, Boolean.TRUE); + } else if (ignoreUnknownOpts) { + pos++; + } else { + throw new UnknownOptionException(arg); } - pos++; } int psize = args.size(); if (psize < minPar) { diff --git a/src/java/org/apache/hadoop/fs/shell/CopyCommands.java b/src/java/org/apache/hadoop/fs/shell/CopyCommands.java index a10d303a8287a..32c71c32b1b67 100644 --- a/src/java/org/apache/hadoop/fs/shell/CopyCommands.java +++ b/src/java/org/apache/hadoop/fs/shell/CopyCommands.java @@ -64,7 +64,7 @@ public static class Merge extends FsCommand { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 2, 3); + CommandFormat cf = new CommandFormat(2, 3); cf.parse(args); // TODO: this really should be a -nl option @@ -94,7 +94,7 @@ static class Cp extends CommandWithDestination { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 2, Integer.MAX_VALUE); + CommandFormat cf = new CommandFormat(2, Integer.MAX_VALUE); cf.parse(args); getRemoteDestination(args); } @@ -137,7 +137,7 @@ protected void processOptions(LinkedList<String> args) throws IOException { localFs = FileSystem.getLocal(getConf()); CommandFormat cf = new CommandFormat( - null, 1, Integer.MAX_VALUE, "crc", "ignoreCrc"); + 1, Integer.MAX_VALUE, "crc", "ignoreCrc"); cf.parse(args); copyCrc = cf.getOpt("crc"); verifyChecksum = !cf.getOpt("ignoreCrc"); @@ -216,7 +216,7 @@ public static class Put extends CommandWithDestination { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 1, Integer.MAX_VALUE); + CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE); cf.parse(args); getRemoteDestination(args); } diff --git a/src/java/org/apache/hadoop/fs/shell/Count.java b/src/java/org/apache/hadoop/fs/shell/Count.java index 6d945196babf4..891e68a4bf928 100644 --- a/src/java/org/apache/hadoop/fs/shell/Count.java +++ b/src/java/org/apache/hadoop/fs/shell/Count.java @@ -73,7 +73,7 @@ public Count(String[] cmd, int pos, Configuration conf) { @Override protected void processOptions(LinkedList<String> args) { - CommandFormat cf = new CommandFormat(NAME, 1, Integer.MAX_VALUE, "q"); + CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, "q"); cf.parse(args); if (args.isEmpty()) { // default path is the current working directory args.add("."); diff --git a/src/java/org/apache/hadoop/fs/shell/Delete.java b/src/java/org/apache/hadoop/fs/shell/Delete.java index 7f17619d220c8..8b34afecdf0ca 100644 --- a/src/java/org/apache/hadoop/fs/shell/Delete.java +++ b/src/java/org/apache/hadoop/fs/shell/Delete.java @@ -57,7 +57,7 @@ public static class Rm extends FsCommand { @Override protected void processOptions(LinkedList<String> args) throws IOException { CommandFormat cf = new CommandFormat( - null, 1, Integer.MAX_VALUE, "r", "R", "skipTrash"); + 1, Integer.MAX_VALUE, "r", "R", "skipTrash"); cf.parse(args); deleteDirs = cf.getOpt("r") || cf.getOpt("R"); skipTrash = cf.getOpt("skipTrash"); @@ -115,7 +115,7 @@ static class Expunge extends FsCommand { // TODO: should probably allow path arguments for the filesystems @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 0, 0); + CommandFormat cf = new CommandFormat(0, 0); cf.parse(args); } diff --git a/src/java/org/apache/hadoop/fs/shell/Display.java b/src/java/org/apache/hadoop/fs/shell/Display.java index 312527b98e3d0..e650b711bc108 100644 --- a/src/java/org/apache/hadoop/fs/shell/Display.java +++ b/src/java/org/apache/hadoop/fs/shell/Display.java @@ -66,7 +66,7 @@ public static class Cat extends Display { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 1, Integer.MAX_VALUE, "ignoreCrc"); + CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, "ignoreCrc"); cf.parse(args); verifyChecksum = !cf.getOpt("ignoreCrc"); } diff --git a/src/java/org/apache/hadoop/fs/shell/FsUsage.java b/src/java/org/apache/hadoop/fs/shell/FsUsage.java index cf95f6a98a107..0d73f76e6669e 100644 --- a/src/java/org/apache/hadoop/fs/shell/FsUsage.java +++ b/src/java/org/apache/hadoop/fs/shell/FsUsage.java @@ -67,7 +67,7 @@ public static class Df extends FsUsage { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 0, Integer.MAX_VALUE, "h"); + CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE, "h"); cf.parse(args); humanReadable = cf.getOpt("h"); if (args.isEmpty()) args.add(Path.SEPARATOR); @@ -123,7 +123,7 @@ public static class Du extends FsUsage { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 0, Integer.MAX_VALUE, "h", "s"); + CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE, "h", "s"); cf.parse(args); humanReadable = cf.getOpt("h"); summary = cf.getOpt("s"); diff --git a/src/java/org/apache/hadoop/fs/shell/Ls.java b/src/java/org/apache/hadoop/fs/shell/Ls.java index 7bd8ba4b82ac0..36c01a63297dd 100644 --- a/src/java/org/apache/hadoop/fs/shell/Ls.java +++ b/src/java/org/apache/hadoop/fs/shell/Ls.java @@ -62,7 +62,7 @@ public static void registerCommands(CommandFactory factory) { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 0, Integer.MAX_VALUE, "R"); + CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE, "R"); cf.parse(args); setRecursive(cf.getOpt("R")); if (args.isEmpty()) args.add(Path.CUR_DIR); diff --git a/src/java/org/apache/hadoop/fs/shell/Mkdir.java b/src/java/org/apache/hadoop/fs/shell/Mkdir.java index effbbfebb0303..30ce5ed4dfddf 100644 --- a/src/java/org/apache/hadoop/fs/shell/Mkdir.java +++ b/src/java/org/apache/hadoop/fs/shell/Mkdir.java @@ -45,7 +45,7 @@ public static void registerCommands(CommandFactory factory) { @Override protected void processOptions(LinkedList<String> args) { - CommandFormat cf = new CommandFormat(null, 1, Integer.MAX_VALUE); + CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE); cf.parse(args); } diff --git a/src/java/org/apache/hadoop/fs/shell/MoveCommands.java b/src/java/org/apache/hadoop/fs/shell/MoveCommands.java index 32089303b9855..5f7d474fbc104 100644 --- a/src/java/org/apache/hadoop/fs/shell/MoveCommands.java +++ b/src/java/org/apache/hadoop/fs/shell/MoveCommands.java @@ -78,7 +78,7 @@ public static class Rename extends CommandWithDestination { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 2, Integer.MAX_VALUE); + CommandFormat cf = new CommandFormat(2, Integer.MAX_VALUE); cf.parse(args); getRemoteDestination(args); } diff --git a/src/java/org/apache/hadoop/fs/shell/SetReplication.java b/src/java/org/apache/hadoop/fs/shell/SetReplication.java index a7097170cae5d..3266bd2b4081e 100644 --- a/src/java/org/apache/hadoop/fs/shell/SetReplication.java +++ b/src/java/org/apache/hadoop/fs/shell/SetReplication.java @@ -33,7 +33,7 @@ @InterfaceAudience.Private @InterfaceStability.Unstable -public class SetReplication extends FsCommand { +class SetReplication extends FsCommand { public static void registerCommands(CommandFactory factory) { factory.addClass(SetReplication.class, "-setrep"); } @@ -51,7 +51,7 @@ public static void registerCommands(CommandFactory factory) { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 2, Integer.MAX_VALUE, "R", "w"); + CommandFormat cf = new CommandFormat(2, Integer.MAX_VALUE, "R", "w"); cf.parse(args); waitOpt = cf.getOpt("w"); setRecursive(cf.getOpt("R")); diff --git a/src/java/org/apache/hadoop/fs/shell/Stat.java b/src/java/org/apache/hadoop/fs/shell/Stat.java index 6bd57cf5a134d..e8a731a3351ed 100644 --- a/src/java/org/apache/hadoop/fs/shell/Stat.java +++ b/src/java/org/apache/hadoop/fs/shell/Stat.java @@ -64,7 +64,7 @@ public static void registerCommands(CommandFactory factory) { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 1, Integer.MAX_VALUE, "R"); + CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, "R"); cf.parse(args); setRecursive(cf.getOpt("R")); if (args.getFirst().contains("%")) format = args.removeFirst(); diff --git a/src/java/org/apache/hadoop/fs/shell/Tail.java b/src/java/org/apache/hadoop/fs/shell/Tail.java index fda7b99c52256..e95d4d1cec830 100644 --- a/src/java/org/apache/hadoop/fs/shell/Tail.java +++ b/src/java/org/apache/hadoop/fs/shell/Tail.java @@ -51,7 +51,7 @@ public static void registerCommands(CommandFactory factory) { @Override protected void processOptions(LinkedList<String> args) throws IOException { - CommandFormat cf = new CommandFormat(null, 1, 1, "f"); + CommandFormat cf = new CommandFormat(1, 1, "f"); cf.parse(args); follow = cf.getOpt("f"); } diff --git a/src/java/org/apache/hadoop/fs/shell/Test.java b/src/java/org/apache/hadoop/fs/shell/Test.java index 309ad053aa175..9780698b3a8be 100644 --- a/src/java/org/apache/hadoop/fs/shell/Test.java +++ b/src/java/org/apache/hadoop/fs/shell/Test.java @@ -46,7 +46,7 @@ public static void registerCommands(CommandFactory factory) { @Override protected void processOptions(LinkedList<String> args) { - CommandFormat cf = new CommandFormat(null, 1, 1, "e", "d", "z"); + CommandFormat cf = new CommandFormat(1, 1, "e", "d", "z"); cf.parse(args); String[] opts = cf.getOpts().toArray(new String[0]); diff --git a/src/java/org/apache/hadoop/fs/shell/Touchz.java b/src/java/org/apache/hadoop/fs/shell/Touchz.java index f384ab51df9a2..18c9aa74c29c9 100644 --- a/src/java/org/apache/hadoop/fs/shell/Touchz.java +++ b/src/java/org/apache/hadoop/fs/shell/Touchz.java @@ -52,7 +52,7 @@ public static class Touchz extends Touch { @Override protected void processOptions(LinkedList<String> args) { - CommandFormat cf = new CommandFormat(null, 1, Integer.MAX_VALUE); + CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE); cf.parse(args); } diff --git a/src/test/core/org/apache/hadoop/fs/TestCommandFormat.java b/src/test/core/org/apache/hadoop/fs/TestCommandFormat.java index 3fdc253c16484..4b855c4940440 100644 --- a/src/test/core/org/apache/hadoop/fs/TestCommandFormat.java +++ b/src/test/core/org/apache/hadoop/fs/TestCommandFormat.java @@ -119,63 +119,59 @@ public void testOptArg() { @Test public void testArgOpt() { args = listOf("b", "-a"); - expectedOpts = setOf("a"); - expectedArgs = listOf("b"); + expectedArgs = listOf("b", "-a"); - checkArgLimits(UnknownOptionException.class, 0, 0); checkArgLimits(TooManyArgumentsException.class, 0, 0, "a", "b"); - checkArgLimits(null, 0, 1, "a", "b"); - checkArgLimits(null, 1, 1, "a", "b"); checkArgLimits(null, 1, 2, "a", "b"); - checkArgLimits(NotEnoughArgumentsException.class, 2, 2, "a", "b"); + checkArgLimits(null, 2, 2, "a", "b"); + checkArgLimits(NotEnoughArgumentsException.class, 3, 4, "a", "b"); } @Test - public void testOptArgOpt() { - args = listOf("a", "-b", "c"); - expectedOpts = setOf("b"); - expectedArgs = listOf("a", "c"); + public void testOptStopOptArg() { + args = listOf("-a", "--", "-b", "c"); + expectedOpts = setOf("a"); + expectedArgs = listOf("-b", "c"); checkArgLimits(UnknownOptionException.class, 0, 0); - checkArgLimits(TooManyArgumentsException.class, 0, 0, "b"); - checkArgLimits(TooManyArgumentsException.class, 1, 1, "b"); - checkArgLimits(null, 0, 2, "b"); - checkArgLimits(NotEnoughArgumentsException.class, 3, 3, "b"); + checkArgLimits(TooManyArgumentsException.class, 0, 1, "a", "b"); + checkArgLimits(null, 2, 2, "a", "b"); + checkArgLimits(NotEnoughArgumentsException.class, 3, 4, "a", "b"); } @Test public void testOptDashArg() { - args = listOf("-b", "-", "c"); + args = listOf("-b", "-", "-c"); expectedOpts = setOf("b"); - expectedArgs = listOf("-", "c"); + expectedArgs = listOf("-", "-c"); checkArgLimits(UnknownOptionException.class, 0, 0); - checkArgLimits(TooManyArgumentsException.class, 0, 0, "b"); - checkArgLimits(TooManyArgumentsException.class, 1, 1, "b"); - checkArgLimits(null, 2, 2, "b"); - checkArgLimits(NotEnoughArgumentsException.class, 3, 4, "b"); + checkArgLimits(TooManyArgumentsException.class, 0, 0, "b", "c"); + checkArgLimits(TooManyArgumentsException.class, 1, 1, "b", "c"); + checkArgLimits(null, 2, 2, "b", "c"); + checkArgLimits(NotEnoughArgumentsException.class, 3, 4, "b", "c"); } @Test public void testOldArgsWithIndex() { String[] arrayArgs = new String[]{"ignore", "-a", "b", "-c"}; { - CommandFormat cf = new CommandFormat("", 0, 9, "a", "c"); + CommandFormat cf = new CommandFormat(0, 9, "a", "c"); List<String> parsedArgs = cf.parse(arrayArgs, 0); - assertEquals(setOf("a", "c"), cf.getOpts()); - assertEquals(listOf("ignore", "b"), parsedArgs); + assertEquals(setOf(), cf.getOpts()); + assertEquals(listOf("ignore", "-a", "b", "-c"), parsedArgs); } { - CommandFormat cf = new CommandFormat("", 0, 9, "a", "c"); + CommandFormat cf = new CommandFormat(0, 9, "a", "c"); List<String> parsedArgs = cf.parse(arrayArgs, 1); - assertEquals(setOf("a", "c"), cf.getOpts()); - assertEquals(listOf("b"), parsedArgs); + assertEquals(setOf("a"), cf.getOpts()); + assertEquals(listOf("b", "-c"), parsedArgs); } { - CommandFormat cf = new CommandFormat("", 0, 9, "a", "c"); + CommandFormat cf = new CommandFormat(0, 9, "a", "c"); List<String> parsedArgs = cf.parse(arrayArgs, 2); - assertEquals(setOf("c"), cf.getOpts()); - assertEquals(listOf("b"), parsedArgs); + assertEquals(setOf(), cf.getOpts()); + assertEquals(listOf("b", "-c"), parsedArgs); } } @@ -183,7 +179,7 @@ private static <T> CommandFormat checkArgLimits( Class<? extends IllegalArgumentException> expectedErr, int min, int max, String ... opts) { - CommandFormat cf = new CommandFormat("", min, max, opts); + CommandFormat cf = new CommandFormat(min, max, opts); List<String> parsedArgs = new ArrayList<String>(args); Class<?> cfError = null; @@ -202,11 +198,13 @@ private static <T> CommandFormat checkArgLimits( return cf; } - private static <T> List<T> listOf(T ... objects) { + // Don't use generics to avoid warning: + // unchecked generic array creation of type T[] for varargs parameter + private static List<String> listOf(String ... objects) { return Arrays.asList(objects); } - private static <T> Set<T> setOf(T ... objects) { - return new HashSet<T>(listOf(objects)); + private static Set<String> setOf(String ... objects) { + return new HashSet<String>(listOf(objects)); } }
72385b4f18bd2646ee7aa3b627a40f1326eb9c1f
isa-tools$isacreator
Added remote folder field in the AppManager, added functionality to save to same remote folder, fixed method to get file metadata in GSDataManager
p
https://github.com/isa-tools/isacreator
diff --git a/src/main/java/org/isatools/isacreator/gs/GSDataManager.java b/src/main/java/org/isatools/isacreator/gs/GSDataManager.java index c844b3a5..7ae6f124 100644 --- a/src/main/java/org/isatools/isacreator/gs/GSDataManager.java +++ b/src/main/java/org/isatools/isacreator/gs/GSDataManager.java @@ -101,9 +101,14 @@ public void lsHome(String username){ } - public GSFileMetadata getFileMetadata(String filePath){ + public GSFileMetadata getFileMetadata(String url){ + //System.out.println("at getFileMetadata -> url="+url); + //System.out.println("is logged in?="+gsSession.isLoggedIn()); + String filePath = transformURLtoFilePath(url) ; + //System.out.println("filePath="+filePath); DataManagerClient dmClient = gsSession.getDataManagerClient(); GSFileMetadata fileMetadata = dmClient.getMetadata(filePath); + //System.out.println("fileMetadata="+fileMetadata); return fileMetadata; } diff --git a/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java b/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java index 948a47a1..829da015 100644 --- a/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java +++ b/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java @@ -44,6 +44,7 @@ public static List<ErrorMessage> downloadFiles(Authentication gsAuthentication) if (!errors.isEmpty()){ return errors; } + ApplicationManager.setCurrentRemoteISATABFolder(ISAcreatorCLArgs.isatabDir()); }//isatabDir not null @@ -56,7 +57,8 @@ public static List<ErrorMessage> downloadFiles(Authentication gsAuthentication) }//if ISAcreatorCLArgs.isatabDir(localTmpDirectory); - ApplicationManager.setCurrentISATABFolder(localTmpDirectory); + ApplicationManager.setCurrentLocalISATABFolder(localTmpDirectory); + }// if return errors; diff --git a/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java b/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java index f1c56602..dda5caf2 100644 --- a/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java +++ b/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java @@ -70,8 +70,12 @@ public void actionPerformed(ActionEvent actionEvent) { File folder = new File(localISATABFolder); File[] files = folder.listFiles(); + + String folderPath = ApplicationManager.getCurrentRemoteISAtabFolder(); + GSFileMetadata folderMetadata = gsDataManager.getFileMetadata(folderPath); + for(File file: files){ - // gsDataManager.saveFile(file, fileMetadata); + gsDataManager.saveFile(file, folderMetadata); } diff --git a/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java b/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java index 8f57feda..4fc867e0 100644 --- a/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java +++ b/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java @@ -329,7 +329,7 @@ public void propertyChange(PropertyChangeEvent event) { gsDataManager.downloadAllFilesFromDirectory(fileMetadata.getPath(),localTmpDirectory, pattern); System.out.println("Importing file..."); - ApplicationManager.setCurrentISATABFolder(localTmpDirectory); + ApplicationManager.setCurrentLocalISATABFolder(localTmpDirectory); loadFile(localTmpDirectory); diff --git a/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java b/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java index ac42cd6f..3b5ce296 100644 --- a/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java +++ b/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java @@ -32,15 +32,24 @@ public class ApplicationManager { private static String currentlySelectedFieldName; private static String currentLocalISAtabFolder; + private static String currentRemoteISAtabFolder; public static String getCurrentLocalISAtabFolder(){ return currentLocalISAtabFolder; } - public static void setCurrentISATABFolder(String folder){ + public static void setCurrentLocalISATABFolder(String folder){ currentLocalISAtabFolder = folder; } + public static String getCurrentRemoteISAtabFolder(){ + return currentRemoteISAtabFolder; + } + + public static void setCurrentRemoteISATABFolder(String folder){ + currentRemoteISAtabFolder = folder; + } + public static void setCurrentApplicationInstance(ISAcreator isacreatorEnvironment) { ApplicationManager.currentApplicationInstance = isacreatorEnvironment;
0fa50b7ec172424f1e4d34ccd5698533748e0a3a
dustin$java-memcached-client
Add visibility into operations (status). This commit allows the functionality for users to issue requests and then check to see whether or not they succeeded. They can also now access the error message that the server sends back to them so they can see why the server rejected their request. Operation status's also take into account operation timeouts and exceptions so if an operation times out the operation says so. Also if an exception is thrown while processing the operation the operation status reports the message from that exception. Change-Id: I62af7450cf6cd1c9d1bf171e5063b3d8a1c919ce Reviewed-on: http://review.couchbase.org/7044 Reviewed-by: Michael Wiederhold <[email protected]> Tested-by: Michael Wiederhold <[email protected]>
p
https://github.com/dustin/java-memcached-client
diff --git a/src/main/java/net/spy/memcached/MemcachedClient.java b/src/main/java/net/spy/memcached/MemcachedClient.java index 1b425526e..bf6542bbf 100644 --- a/src/main/java/net/spy/memcached/MemcachedClient.java +++ b/src/main/java/net/spy/memcached/MemcachedClient.java @@ -429,7 +429,7 @@ private CountDownLatch broadcastOp(BroadcastOpFactory of, return conn.broadcastOperation(of, nodes); } - private <T> Future<Boolean> asyncStore(StoreType storeType, String key, + private <T> OperationFuture<Boolean> asyncStore(StoreType storeType, String key, int exp, T value, Transcoder<T> tc) { CachedData co=tc.encode(value); final CountDownLatch latch=new CountDownLatch(1); @@ -438,7 +438,7 @@ private <T> Future<Boolean> asyncStore(StoreType storeType, String key, Operation op=opFact.store(storeType, key, co.getFlags(), exp, co.getData(), new OperationCallback() { public void receivedStatus(OperationStatus val) { - rv.set(val.isSuccess()); + rv.set(val.isSuccess(), val); } public void complete() { latch.countDown(); @@ -448,12 +448,12 @@ public void complete() { return rv; } - private Future<Boolean> asyncStore(StoreType storeType, + private OperationFuture<Boolean> asyncStore(StoreType storeType, String key, int exp, Object value) { return asyncStore(storeType, key, exp, value, transcoder); } - private <T> Future<Boolean> asyncCat( + private <T> OperationFuture<Boolean> asyncCat( ConcatenationType catType, long cas, String key, T value, Transcoder<T> tc) { CachedData co=tc.encode(value); @@ -463,7 +463,7 @@ private <T> Future<Boolean> asyncCat( Operation op=opFact.cat(catType, cas, key, co.getData(), new OperationCallback() { public void receivedStatus(OperationStatus val) { - rv.set(val.isSuccess()); + rv.set(val.isSuccess(), val); } public void complete() { latch.countDown(); @@ -484,7 +484,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> touch(final String key, final int exp) { + public <T> OperationFuture<Boolean> touch(final String key, final int exp) { return touch(key, exp, transcoder); } @@ -499,7 +499,7 @@ public <T> Future<Boolean> touch(final String key, final int exp) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> touch(final String key, final int exp, + public <T> OperationFuture<Boolean> touch(final String key, final int exp, final Transcoder<T> tc) { final CountDownLatch latch=new CountDownLatch(1); final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(latch, @@ -507,7 +507,7 @@ public <T> Future<Boolean> touch(final String key, final int exp, Operation op=opFact.touch(key, exp, new OperationCallback() { public void receivedStatus(OperationStatus status) { - rv.set(status.isSuccess()); + rv.set(status.isSuccess(), status); } public void complete() { latch.countDown(); @@ -531,7 +531,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> append(long cas, String key, Object val) { + public OperationFuture<Boolean> append(long cas, String key, Object val) { return append(cas, key, val, transcoder); } @@ -550,7 +550,7 @@ public Future<Boolean> append(long cas, String key, Object val) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> append(long cas, String key, T val, + public <T> OperationFuture<Boolean> append(long cas, String key, T val, Transcoder<T> tc) { return asyncCat(ConcatenationType.append, cas, key, val, tc); } @@ -568,7 +568,7 @@ public <T> Future<Boolean> append(long cas, String key, T val, * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> prepend(long cas, String key, Object val) { + public OperationFuture<Boolean> prepend(long cas, String key, Object val) { return prepend(cas, key, val, transcoder); } @@ -587,7 +587,7 @@ public Future<Boolean> prepend(long cas, String key, Object val) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> prepend(long cas, String key, T val, + public <T> OperationFuture<Boolean> prepend(long cas, String key, T val, Transcoder<T> tc) { return asyncCat(ConcatenationType.prepend, cas, key, val, tc); } @@ -632,7 +632,7 @@ public <T> Future<CASResponse> asyncCAS(String key, long casId, int exp, T value co.getData(), new OperationCallback() { public void receivedStatus(OperationStatus val) { if(val instanceof CASOperationStatus) { - rv.set(((CASOperationStatus)val).getCASResponse()); + rv.set(((CASOperationStatus)val).getCASResponse(), val); } else if(val instanceof CancelledOperationStatus) { // Cancelled, ignore and let it float up } else { @@ -758,7 +758,7 @@ public CASResponse cas(String key, long casId, Object value) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> add(String key, int exp, T o, Transcoder<T> tc) { + public <T> OperationFuture<Boolean> add(String key, int exp, T o, Transcoder<T> tc) { return asyncStore(StoreType.add, key, exp, o, tc); } @@ -793,7 +793,7 @@ public <T> Future<Boolean> add(String key, int exp, T o, Transcoder<T> tc) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> add(String key, int exp, Object o) { + public OperationFuture<Boolean> add(String key, int exp, Object o) { return asyncStore(StoreType.add, key, exp, o, transcoder); } @@ -829,7 +829,7 @@ public Future<Boolean> add(String key, int exp, Object o) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> set(String key, int exp, T o, Transcoder<T> tc) { + public <T> OperationFuture<Boolean> set(String key, int exp, T o, Transcoder<T> tc) { return asyncStore(StoreType.set, key, exp, o, tc); } @@ -864,7 +864,7 @@ public <T> Future<Boolean> set(String key, int exp, T o, Transcoder<T> tc) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> set(String key, int exp, Object o) { + public OperationFuture<Boolean> set(String key, int exp, Object o) { return asyncStore(StoreType.set, key, exp, o, transcoder); } @@ -901,7 +901,7 @@ public Future<Boolean> set(String key, int exp, Object o) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<Boolean> replace(String key, int exp, T o, + public <T> OperationFuture<Boolean> replace(String key, int exp, T o, Transcoder<T> tc) { return asyncStore(StoreType.replace, key, exp, o, tc); } @@ -937,7 +937,7 @@ public <T> Future<Boolean> replace(String key, int exp, T o, * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> replace(String key, int exp, Object o) { + public OperationFuture<Boolean> replace(String key, int exp, Object o) { return asyncStore(StoreType.replace, key, exp, o, transcoder); } @@ -951,7 +951,7 @@ public Future<Boolean> replace(String key, int exp, Object o) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<T> asyncGet(final String key, final Transcoder<T> tc) { + public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) { final CountDownLatch latch=new CountDownLatch(1); final GetFuture<T> rv=new GetFuture<T>(latch, operationTimeout); @@ -960,7 +960,7 @@ public <T> Future<T> asyncGet(final String key, final Transcoder<T> tc) { new GetOperation.Callback() { private Future<T> val=null; public void receivedStatus(OperationStatus status) { - rv.set(val); + rv.set(val, status); } public void gotData(String k, int flags, byte[] data) { assert key.equals(k) : "Wrong key returned"; @@ -984,7 +984,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Object> asyncGet(final String key) { + public GetFuture<Object> asyncGet(final String key) { return asyncGet(key, transcoder); } @@ -998,7 +998,7 @@ public Future<Object> asyncGet(final String key) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<CASValue<T>> asyncGets(final String key, + public <T> OperationFuture<CASValue<T>> asyncGets(final String key, final Transcoder<T> tc) { final CountDownLatch latch=new CountDownLatch(1); @@ -1009,7 +1009,7 @@ public <T> Future<CASValue<T>> asyncGets(final String key, new GetsOperation.Callback() { private CASValue<T> val=null; public void receivedStatus(OperationStatus status) { - rv.set(val); + rv.set(val, status); } public void gotData(String k, int flags, long cas, byte[] data) { assert key.equals(k) : "Wrong key returned"; @@ -1034,7 +1034,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<CASValue<Object>> asyncGets(final String key) { + public OperationFuture<CASValue<Object>> asyncGets(final String key) { return asyncGets(key, transcoder); } @@ -1168,7 +1168,7 @@ public Object get(String key) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<CASValue<T>> asyncGetAndLock(final String key, int exp, + public <T> OperationFuture<CASValue<T>> asyncGetAndLock(final String key, int exp, final Transcoder<T> tc) { final CountDownLatch latch=new CountDownLatch(1); final OperationFuture<CASValue<T>> rv= @@ -1178,7 +1178,7 @@ public <T> Future<CASValue<T>> asyncGetAndLock(final String key, int exp, new GetlOperation.Callback() { private CASValue<T> val=null; public void receivedStatus(OperationStatus status) { - rv.set(val); + rv.set(val, status); } public void gotData(String k, int flags, long cas, byte[] data) { assert key.equals(k) : "Wrong key returned"; @@ -1205,7 +1205,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<CASValue<Object>> asyncGetAndLock(final String key, int exp) { + public OperationFuture<CASValue<Object>> asyncGetAndLock(final String key, int exp) { return asyncGetAndLock(key, exp, transcoder); } @@ -1268,10 +1268,12 @@ public <T> BulkFuture<Map<String, T>> asyncGetBulk(Collection<String> keys, final CountDownLatch latch=new CountDownLatch(chunks.size()); final Collection<Operation> ops=new ArrayList<Operation>(chunks.size()); + final BulkGetFuture<T> rv = new BulkGetFuture<T>(m, ops, latch); GetOperation.Callback cb=new GetOperation.Callback() { @SuppressWarnings("synthetic-access") public void receivedStatus(OperationStatus status) { + rv.setStatus(status); if(!status.isSuccess()) { getLogger().warn("Unsuccessful get: %s", status); } @@ -1300,7 +1302,7 @@ public void complete() { assert mops.size() == chunks.size(); checkState(); conn.addOperations(mops); - return new BulkGetFuture<T>(m, ops, latch); + return rv; } /** @@ -1367,7 +1369,7 @@ public BulkFuture<Map<String, Object>> asyncGetBulk(String... keys) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<CASValue<Object>> asyncGetAndTouch(final String key, final int exp) { + public OperationFuture<CASValue<Object>> asyncGetAndTouch(final String key, final int exp) { return asyncGetAndTouch(key, exp, transcoder); } @@ -1381,7 +1383,7 @@ public Future<CASValue<Object>> asyncGetAndTouch(final String key, final int exp * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public <T> Future<CASValue<T>> asyncGetAndTouch(final String key, final int exp, + public <T> OperationFuture<CASValue<T>> asyncGetAndTouch(final String key, final int exp, final Transcoder<T> tc) { final CountDownLatch latch=new CountDownLatch(1); final OperationFuture<CASValue<T>> rv=new OperationFuture<CASValue<T>>(latch, @@ -1390,7 +1392,7 @@ public <T> Future<CASValue<T>> asyncGetAndTouch(final String key, final int exp, Operation op=opFact.getAndTouch(key, exp, new GetAndTouchOperation.Callback() { private CASValue<T> val=null; public void receivedStatus(OperationStatus status) { - rv.set(val); + rv.set(val, status); } public void complete() { latch.countDown(); @@ -1739,7 +1741,7 @@ private long mutateWithDefault(Mutator t, String key, return rv; } - private Future<Long> asyncMutate(Mutator m, String key, int by, long def, + private OperationFuture<Long> asyncMutate(Mutator m, String key, int by, long def, int exp) { final CountDownLatch latch = new CountDownLatch(1); final OperationFuture<Long> rv = new OperationFuture<Long>( @@ -1747,7 +1749,7 @@ private Future<Long> asyncMutate(Mutator m, String key, int by, long def, Operation op = addOp(key, opFact.mutate(m, key, by, def, exp, new OperationCallback() { public void receivedStatus(OperationStatus s) { - rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1")); + rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1"), s); } public void complete() { latch.countDown(); @@ -1767,7 +1769,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Long> asyncIncr(String key, int by) { + public OperationFuture<Long> asyncIncr(String key, int by) { return asyncMutate(Mutator.incr, key, by, 0, -1); } @@ -1781,7 +1783,7 @@ public Future<Long> asyncIncr(String key, int by) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Long> asyncDecr(String key, int by) { + public OperationFuture<Long> asyncDecr(String key, int by) { return asyncMutate(Mutator.decr, key, by, 0, -1); } @@ -1837,7 +1839,7 @@ public long decr(String key, int by, long def) { * @deprecated Hold values are no longer honored. */ @Deprecated - public Future<Boolean> delete(String key, int hold) { + public OperationFuture<Boolean> delete(String key, int hold) { return delete(key); } @@ -1849,14 +1851,14 @@ public Future<Boolean> delete(String key, int hold) { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> delete(String key) { + public OperationFuture<Boolean> delete(String key) { final CountDownLatch latch=new CountDownLatch(1); final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(latch, operationTimeout); DeleteOperation op=opFact.delete(key, new OperationCallback() { public void receivedStatus(OperationStatus s) { - rv.set(s.isSuccess()); + rv.set(s.isSuccess(), s); } public void complete() { latch.countDown(); @@ -1873,7 +1875,7 @@ public void complete() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> flush(final int delay) { + public OperationFuture<Boolean> flush(final int delay) { final AtomicReference<Boolean> flushResult= new AtomicReference<Boolean>(null); final ConcurrentLinkedQueue<Operation> ops= @@ -1891,6 +1893,7 @@ public void complete() { ops.add(op); return op; }}); + return new OperationFuture<Boolean>(blatch, flushResult, operationTimeout) { @Override @@ -1903,6 +1906,12 @@ public boolean cancel(boolean ign) { return rv; } @Override + public Boolean get(long duration, TimeUnit units) throws InterruptedException, + TimeoutException, ExecutionException { + status = new OperationStatus(true, "OK"); + return super.get(duration, units); + } + @Override public boolean isCancelled() { boolean rv=false; for(Operation op : ops) { @@ -1927,7 +1936,7 @@ public boolean isDone() { * @throws IllegalStateException in the rare circumstance where queue * is too full to accept any more requests */ - public Future<Boolean> flush() { + public OperationFuture<Boolean> flush() { return flush(-1); } diff --git a/src/main/java/net/spy/memcached/internal/BulkFuture.java b/src/main/java/net/spy/memcached/internal/BulkFuture.java index b1c1e1232..d5c647192 100644 --- a/src/main/java/net/spy/memcached/internal/BulkFuture.java +++ b/src/main/java/net/spy/memcached/internal/BulkFuture.java @@ -4,6 +4,8 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import net.spy.memcached.ops.OperationStatus; + /** * Additional flexibility for asyncGetBulk * @@ -44,4 +46,11 @@ public interface BulkFuture<V> extends Future<V> { public V getSome(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException; + /** + * Gets the status of the operation upon completion. + * + * @return the operation status. + */ + public OperationStatus getStatus(); + } diff --git a/src/main/java/net/spy/memcached/internal/BulkGetFuture.java b/src/main/java/net/spy/memcached/internal/BulkGetFuture.java index 3bcc4ee73..d7c46160a 100644 --- a/src/main/java/net/spy/memcached/internal/BulkGetFuture.java +++ b/src/main/java/net/spy/memcached/internal/BulkGetFuture.java @@ -14,6 +14,7 @@ import net.spy.memcached.compat.log.LoggerFactory; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationState; +import net.spy.memcached.ops.OperationStatus; /** * Future for handling results from bulk gets. @@ -26,6 +27,7 @@ public class BulkGetFuture<T> implements BulkFuture<Map<String, T>> { private final Map<String, Future<T>> rvMap; private final Collection<Operation> ops; private final CountDownLatch latch; + private OperationStatus status; private boolean cancelled=false; private boolean timeout = false; @@ -35,6 +37,7 @@ public BulkGetFuture(Map<String, Future<T>> m, rvMap = m; ops = getOps; latch=l; + status = null; } public boolean cancel(boolean ign) { @@ -47,6 +50,7 @@ public boolean cancel(boolean ign) { v.cancel(ign); } cancelled=true; + status = new OperationStatus(false, "Cancelled"); return rv; } @@ -89,6 +93,7 @@ public Map<String, T> get(long to, TimeUnit unit) Map<String, T> ret = internalGet(to, unit, timedoutOps); if (timedoutOps.size() > 0) { this.timeout = true; + status = new OperationStatus(false, "Timed out"); throw new CheckedOperationTimeoutException("Operation timed out.", timedoutOps); } @@ -121,9 +126,11 @@ private Map<String, T> internalGet(long to, TimeUnit unit, } for (Operation op : ops) { if (op.isCancelled()) { + status = new OperationStatus(false, "Cancelled"); throw new ExecutionException(new RuntimeException("Cancelled")); } if (op.hasErrored()) { + status = new OperationStatus(false, op.getException().getMessage()); throw new ExecutionException(op.getException()); } } @@ -134,6 +141,24 @@ private Map<String, T> internalGet(long to, TimeUnit unit, return m; } + public OperationStatus getStatus() { + if (status == null) { + try { + get(); + } catch (InterruptedException e) { + status = new OperationStatus(false, "Interrupted"); + Thread.currentThread().interrupt(); + } catch (ExecutionException e) { + return status; + } + } + return status; + } + + public void setStatus(OperationStatus s) { + status = s; + } + public boolean isCancelled() { return cancelled; } diff --git a/src/main/java/net/spy/memcached/internal/GetFuture.java b/src/main/java/net/spy/memcached/internal/GetFuture.java index de750544a..8cab34b00 100644 --- a/src/main/java/net/spy/memcached/internal/GetFuture.java +++ b/src/main/java/net/spy/memcached/internal/GetFuture.java @@ -7,6 +7,7 @@ import java.util.concurrent.TimeoutException; import net.spy.memcached.ops.Operation; +import net.spy.memcached.ops.OperationStatus; /** * Future returned for GET operations. @@ -38,8 +39,12 @@ public T get(long duration, TimeUnit units) return v == null ? null : v.get(); } - public void set(Future<T> d) { - rv.set(d); + public OperationStatus getStatus() { + return rv.getStatus(); + } + + public void set(Future<T> d, OperationStatus s) { + rv.set(d, s); } public void setOperation(Operation to) { diff --git a/src/main/java/net/spy/memcached/internal/OperationFuture.java b/src/main/java/net/spy/memcached/internal/OperationFuture.java index e2c8c5efd..5075f49ee 100644 --- a/src/main/java/net/spy/memcached/internal/OperationFuture.java +++ b/src/main/java/net/spy/memcached/internal/OperationFuture.java @@ -10,6 +10,7 @@ import net.spy.memcached.MemcachedConnection; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationState; +import net.spy.memcached.ops.OperationStatus; /** * Managed future for operations. @@ -22,6 +23,7 @@ public class OperationFuture<T> implements Future<T> { private final CountDownLatch latch; private final AtomicReference<T> objRef; + protected OperationStatus status; private final long timeout; private Operation op; @@ -34,6 +36,7 @@ public OperationFuture(CountDownLatch l, AtomicReference<T> oref, super(); latch=l; objRef=oref; + status = null; timeout = opTimeout; } @@ -49,6 +52,7 @@ public T get() throws InterruptedException, ExecutionException { try { return get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { + status = new OperationStatus(false, "Timed out"); throw new RuntimeException( "Timed out waiting for operation", e); } @@ -62,6 +66,7 @@ public T get(long duration, TimeUnit units) if (op != null) { // op can be null on a flush op.timeOut(); } + status = new OperationStatus(false, "Timed out"); throw new CheckedOperationTimeoutException( "Timed out waiting for operation", op); } else { @@ -69,20 +74,37 @@ public T get(long duration, TimeUnit units) MemcachedConnection.opSucceeded(op); } if(op != null && op.hasErrored()) { + status = new OperationStatus(false, op.getException().getMessage()); throw new ExecutionException(op.getException()); } if(isCancelled()) { throw new ExecutionException(new RuntimeException("Cancelled")); } if(op != null && op.isTimedOut()) { + status = new OperationStatus(false, "Timed out"); throw new ExecutionException(new CheckedOperationTimeoutException("Operation timed out.", op)); } return objRef.get(); } - public void set(T o) { + public OperationStatus getStatus() { + if (status == null) { + try { + get(); + } catch (InterruptedException e) { + status = new OperationStatus(false, "Interrupted"); + Thread.currentThread().isInterrupted(); + } catch (ExecutionException e) { + + } + } + return status; + } + + public void set(T o, OperationStatus s) { objRef.set(o); + status = s; } public void setOperation(Operation to) { diff --git a/src/test/java/net/spy/memcached/ProtocolBaseCase.java b/src/test/java/net/spy/memcached/ProtocolBaseCase.java index d885f9572..983404a83 100644 --- a/src/test/java/net/spy/memcached/ProtocolBaseCase.java +++ b/src/test/java/net/spy/memcached/ProtocolBaseCase.java @@ -15,6 +15,9 @@ import java.util.concurrent.TimeUnit; import net.spy.memcached.compat.SyncThread; +import net.spy.memcached.internal.BulkFuture; +import net.spy.memcached.internal.GetFuture; +import net.spy.memcached.internal.OperationFuture; import net.spy.memcached.ops.OperationErrorType; import net.spy.memcached.ops.OperationException; import net.spy.memcached.transcoders.SerializingTranscoder; @@ -91,14 +94,16 @@ public void testGetStatsCacheDump() throws Exception { public void testDelayedFlush() throws Exception { assertNull(client.get("test1")); - client.set("test1", 5, "test1value"); - client.set("test2", 5, "test2value"); + assert client.set("test1", 5, "test1value").getStatus().isSuccess(); + assert client.set("test2", 5, "test2value").getStatus().isSuccess(); assertEquals("test1value", client.get("test1")); assertEquals("test2value", client.get("test2")); - client.flush(2); + assert client.flush(2).getStatus().isSuccess(); Thread.sleep(2100); assertNull(client.get("test1")); assertNull(client.get("test2")); + assert !client.asyncGet("test1").getStatus().isSuccess(); + assert !client.asyncGet("test2").getStatus().isSuccess(); } public void testNoop() { @@ -118,7 +123,7 @@ public void testSimpleGet() throws Exception { public void testSimpleCASGets() throws Exception { assertNull(client.gets("test1")); - client.set("test1", 5, "test1value"); + assert client.set("test1", 5, "test1value").getStatus().isSuccess(); assertEquals("test1value", client.gets("test1").getValue()); } @@ -165,7 +170,7 @@ public void testReallyLongCASId() throws Exception { public void testExtendedUTF8Key() throws Exception { String key="\u2013\u00ba\u2013\u220f\u2014\u00c4"; assertNull(client.get(key)); - client.set(key, 5, "test1value"); + assert client.set(key, 5, "test1value").getStatus().isSuccess(); assertEquals("test1value", client.get(key)); } @@ -240,7 +245,7 @@ public void testParallelSetGet() throws Throwable { int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){ public Boolean call() throws Exception { for(int i=0; i<10; i++) { - client.set("test" + i, 5, "value" + i); + assert client.set("test" + i, 5, "value" + i).getStatus().isSuccess(); assertEquals("value" + i, client.get("test" + i)); } for(int i=0; i<10; i++) { @@ -255,7 +260,7 @@ public void testParallelSetMultiGet() throws Throwable { int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){ public Boolean call() throws Exception { for(int i=0; i<10; i++) { - client.set("test" + i, 5, "value" + i); + assert client.set("test" + i, 5, "value" + i).getStatus().isSuccess(); assertEquals("value" + i, client.get("test" + i)); } Map<String, Object> m=client.getBulk("test0", "test1", "test2", @@ -272,7 +277,7 @@ public Boolean call() throws Exception { public void testParallelSetAutoMultiGet() throws Throwable { int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){ public Boolean call() throws Exception { - client.set("testparallel", 5, "parallelvalue"); + assert client.set("testparallel", 5, "parallelvalue").getStatus().isSuccess(); for(int i=0; i<10; i++) { assertEquals("parallelvalue", client.get("testparallel")); } @@ -283,9 +288,12 @@ public Boolean call() throws Exception { public void testAdd() throws Exception { assertNull(client.get("test1")); + assert !client.asyncGet("test1").getStatus().isSuccess(); assertTrue(client.set("test1", 5, "test1value").get()); assertEquals("test1value", client.get("test1")); + assert client.asyncGet("test1").getStatus().isSuccess(); assertFalse(client.add("test1", 5, "ignoredvalue").get()); + assert !client.add("test1", 5, "ignoredvalue").getStatus().isSuccess(); // Should return the original value assertEquals("test1value", client.get("test1")); } @@ -293,9 +301,11 @@ public void testAdd() throws Exception { public void testAddWithTranscoder() throws Exception { Transcoder<String> t=new TestTranscoder(); assertNull(client.get("test1", t)); + assert !client.asyncGet("test1", t).getStatus().isSuccess(); assertTrue(client.set("test1", 5, "test1value", t).get()); assertEquals("test1value", client.get("test1", t)); assertFalse(client.add("test1", 5, "ignoredvalue", t).get()); + assert !client.add("test1", 5, "ignoredvalue", t).getStatus().isSuccess(); // Should return the original value assertEquals("test1value", client.get("test1", t)); } @@ -330,6 +340,7 @@ public void testReplaceNotSerializable() throws Exception { public void testUpdate() throws Exception { assertNull(client.get("test1")); client.replace("test1", 5, "test1value"); + assert !client.replace("test1", 5, "test1value").getStatus().isSuccess(); assertNull(client.get("test1")); } @@ -337,6 +348,7 @@ public void testUpdateWithTranscoder() throws Exception { Transcoder<String> t=new TestTranscoder(); assertNull(client.get("test1", t)); client.replace("test1", 5, "test1value", t); + assert !client.replace("test1", 5, "test1value", t).getStatus().isSuccess(); assertNull(client.get("test1", t)); } @@ -367,6 +379,7 @@ public void testGetBulk() throws Exception { client.set("test1", 5, "val1"); client.set("test2", 5, "val2"); Map<String, Object> vals=client.getBulk(keys); + assert client.asyncGetBulk(keys).getStatus().isSuccess(); assertEquals(2, vals.size()); assertEquals("val1", vals.get("test1")); assertEquals("val2", vals.get("test2")); @@ -377,6 +390,7 @@ public void testGetBulkVararg() throws Exception { client.set("test1", 5, "val1"); client.set("test2", 5, "val2"); Map<String, Object> vals=client.getBulk("test1", "test2", "test3"); + assert client.asyncGetBulk("test1", "test2", "test3").getStatus().isSuccess(); assertEquals(2, vals.size()); assertEquals("val1", vals.get("test1")); assertEquals("val2", vals.get("test2")); @@ -388,6 +402,7 @@ public void testGetBulkVarargWithTranscoder() throws Exception { client.set("test1", 5, "val1", t); client.set("test2", 5, "val2", t); Map<String, String> vals=client.getBulk(t, "test1", "test2", "test3"); + assert client.asyncGetBulk(t, "test1", "test2", "test3").getStatus().isSuccess(); assertEquals(2, vals.size()); assertEquals("val1", vals.get("test1")); assertEquals("val2", vals.get("test2")); @@ -398,8 +413,9 @@ public void testAsyncGetBulkVarargWithTranscoder() throws Exception { assertEquals(0, client.getBulk(t, "test1", "test2", "test3").size()); client.set("test1", 5, "val1", t); client.set("test2", 5, "val2", t); - Future<Map<String, String>> vals=client.asyncGetBulk(t, + BulkFuture<Map<String, String>> vals=client.asyncGetBulk(t, "test1", "test2", "test3"); + assert vals.getStatus().isSuccess(); assertEquals(2, vals.get().size()); assertEquals("val1", vals.get().get("test1")); assertEquals("val2", vals.get().get("test2")); @@ -471,7 +487,9 @@ public void testGetVersions() throws Exception { public void testNonexistentMutate() throws Exception { assertEquals(-1, client.incr("nonexistent", 1)); + assert !client.asyncIncr("nonexistent", 1).getStatus().isSuccess(); assertEquals(-1, client.decr("nonexistent", 1)); + assert !client.asyncDecr("nonexistent", 1).getStatus().isSuccess(); } public void testMutateWithDefault() throws Exception { @@ -488,6 +506,7 @@ public void testMutateWithDefaultAndExp() throws Exception { assertEquals(9, client.decr("mtest2", 1, 9, 1)); Thread.sleep(2000); assertNull(client.get("mtest")); + assert ! client.asyncGet("mtest").getStatus().isSuccess(); } public void testAsyncIncrement() throws Exception { @@ -528,7 +547,7 @@ public void testImmediateDelete() throws Exception { assertNull(client.get("test1")); client.set("test1", 5, "test1value"); assertEquals("test1value", client.get("test1")); - client.delete("test1"); + assert client.delete("test1").getStatus().isSuccess(); assertNull(client.get("test1")); } @@ -593,12 +612,15 @@ public int getTimeoutExceptionThreshold() { assert set == true; int i = 0; + GetFuture<Object> g = null; try { for(i = 0; i < 1000000; i++) { - client.get(key); + g = client.asyncGet(key); + g.get(); } throw new Exception("Didn't get a timeout."); - } catch(RuntimeException e) { + } catch(Exception e) { + assert !g.getStatus().isSuccess(); System.out.println("Got a timeout at iteration " + i + "."); } Thread.sleep(100); // let whatever caused the timeout to pass @@ -741,13 +763,15 @@ public void testABunchOfCancelledOperations() throws Exception { futures.add(client.set(k, 5, "xval")); futures.add(client.asyncGet(k)); } - Future<Boolean> sf=client.set(k, 5, "myxval"); - Future<Object> gf=client.asyncGet(k); + OperationFuture<Boolean> sf=client.set(k, 5, "myxval"); + GetFuture<Object> gf=client.asyncGet(k); for(Future<?> f : futures) { f.cancel(true); } assertTrue(sf.get()); + assert sf.getStatus().isSuccess(); assertEquals("myxval", gf.get()); + assert gf.getStatus().isSuccess(); } public void testUTF8Key() throws Exception { @@ -801,14 +825,18 @@ public void testUTF8Value() throws Exception { public void testAppend() throws Exception { final String key="append.key"; assertTrue(client.set(key, 5, "test").get()); - assertTrue(client.append(0, key, "es").get()); + OperationFuture<Boolean> op = client.append(0, key, "es"); + assertTrue(op.get()); + assert op.getStatus().isSuccess(); assertEquals("testes", client.get(key)); } public void testPrepend() throws Exception { final String key="prepend.key"; assertTrue(client.set(key, 5, "test").get()); - assertTrue(client.prepend(0, key, "es").get()); + OperationFuture<Boolean> op = client.prepend(0, key, "es"); + assertTrue(op.get()); + assert op.getStatus().isSuccess(); assertEquals("estest", client.get(key)); }
bd5a2f972f8c896a896f291d644f4f31b0c2395e
hbase
HBASE-7307 MetaReader.tableExists should not- return false if the specified table regions has been split (Rajesh)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1419998 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java index ebf60d5b0ccf..ea9da0c4ee2e 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java @@ -322,7 +322,6 @@ public boolean visit(Result r) throws IOException { return true; } if (!isInsideTable(this.current, tableNameBytes)) return false; - if (this.current.isSplitParent()) return true; // Else call super and add this Result to the collection. super.visit(r); // Stop collecting regions from table after we get one. diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java index fcfb76478292..2780b93a4417 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java @@ -46,6 +46,7 @@ import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.UnknownRegionException; import org.apache.hadoop.hbase.ZooKeeperConnectionException; +import org.apache.hadoop.hbase.catalog.MetaReader; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; @@ -626,7 +627,48 @@ public void run() { } } } - + + @Test(timeout = 20000) + public void testTableExistsIfTheSpecifiedTableRegionIsSplitParent() throws Exception { + final byte[] tableName = + Bytes.toBytes("testTableExistsIfTheSpecifiedTableRegionIsSplitParent"); + HRegionServer regionServer = null; + List<HRegion> regions = null; + HBaseAdmin admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); + try { + // Create table then get the single region for our new table. + HTableDescriptor htd = new HTableDescriptor(tableName); + htd.addFamily(new HColumnDescriptor("cf")); + admin.createTable(htd); + HTable t = new HTable(cluster.getConfiguration(), tableName); + regions = cluster.getRegions(tableName); + int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionName()); + regionServer = cluster.getRegionServer(regionServerIndex); + insertData(tableName, admin, t); + // Turn off balancer so it doesn't cut in and mess up our placements. + admin.setBalancerRunning(false, false); + // Turn off the meta scanner so it don't remove parent on us. + cluster.getMaster().setCatalogJanitorEnabled(false); + boolean tableExists = MetaReader.tableExists(regionServer.getCatalogTracker(), + Bytes.toString(tableName)); + assertEquals("The specified table should present.", true, tableExists); + SplitTransaction st = new SplitTransaction(regions.get(0), Bytes.toBytes("row2")); + try { + st.prepare(); + st.createDaughters(regionServer, regionServer); + } catch (IOException e) { + + } + tableExists = MetaReader.tableExists(regionServer.getCatalogTracker(), + Bytes.toString(tableName)); + assertEquals("The specified table should present.", true, tableExists); + } finally { + admin.setBalancerRunning(true, false); + cluster.getMaster().setCatalogJanitorEnabled(true); + admin.close(); + } + } + private void insertData(final byte[] tableName, HBaseAdmin admin, HTable t) throws IOException, InterruptedException { Put p = new Put(Bytes.toBytes("row1"));
4a9f2fb05a3163e11ed35d85a33a6b8e216dde77
ReactiveX-RxJava
TakeWhile protect calls to predicate--
c
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java b/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java index f45efabc92..1bad2d36e5 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java +++ b/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java @@ -123,7 +123,15 @@ public void onError(Exception e) { @Override public void onNext(T args) { - if (predicate.call(args, counter.getAndIncrement())) { + Boolean isSelected; + try { + isSelected = predicate.call(args, counter.getAndIncrement()); + } + catch (Exception e) { + observer.onError(e); + return; + } + if (isSelected) { observer.onNext(args); } else { observer.onCompleted(); @@ -238,6 +246,35 @@ public Boolean call(String s) })).last(); } + @Test + public void testTakeWhileProtectsPredicateCall() { + TestObservable source = new TestObservable(mock(Subscription.class), "one"); + final RuntimeException testException = new RuntimeException("test exception"); + + @SuppressWarnings("unchecked") + Observer<String> aObserver = mock(Observer.class); + Observable<String> take = Observable.create(takeWhile(source, new Func1<String, Boolean>() + { + @Override + public Boolean call(String s) + { + throw testException; + } + })); + take.subscribe(aObserver); + + // wait for the Observable to complete + try { + source.t.join(); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + + verify(aObserver, never()).onNext(any(String.class)); + verify(aObserver, times(1)).onError(testException); + } + @Test public void testUnsubscribeAfterTake() { Subscription s = mock(Subscription.class);
64cb8af5792432c71315a95b72cdb48219a170a3
restlet-framework-java
Fixed issue -649
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/src/org/restlet/test/engine/HeaderTestCase.java b/modules/org.restlet.test/src/org/restlet/test/engine/HeaderTestCase.java index 08aec9e758..4b66087dc5 100644 --- a/modules/org.restlet.test/src/org/restlet/test/engine/HeaderTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/engine/HeaderTestCase.java @@ -41,10 +41,15 @@ import org.restlet.data.Encoding; import org.restlet.data.MediaType; import org.restlet.engine.header.EncodingReader; +import org.restlet.engine.header.Header; +import org.restlet.engine.header.HeaderConstants; import org.restlet.engine.header.HeaderReader; +import org.restlet.engine.header.HeaderUtils; import org.restlet.engine.header.PreferenceReader; import org.restlet.engine.header.TokenReader; +import org.restlet.engine.util.Base64; import org.restlet.engine.util.DateUtils; +import org.restlet.representation.Representation; import org.restlet.test.RestletTestCase; /** @@ -99,6 +104,33 @@ public void testAddValues() { assertEquals(l.size(), 1); } + public void testExtracting() { + ArrayList<Header> headers = new ArrayList<Header>(); + String md5hash = "aaaaaaaaaaaaaaaa"; + // encodes to "YWFhYWFhYWFhYWFhYWFhYQ==", the "==" at the end is padding + String encodedWithPadding = Base64.encode(md5hash.getBytes(), false); + String encodedNoPadding = encodedWithPadding.substring(0, 22); + + Header header = new Header(HeaderConstants.HEADER_CONTENT_MD5, + encodedWithPadding); + headers.add(header); + + // extract Content-MD5 header with padded Base64 encoding, make sure it + // decodes to original hash + Representation rep = HeaderUtils.extractEntityHeaders(headers, null); + assertEquals(rep.getDigest().getAlgorithm(), + org.restlet.data.Digest.ALGORITHM_MD5); + assertEquals(new String(rep.getDigest().getValue()), md5hash); + + // extract header with UNpadded encoding, make sure it also decodes to + // original hash + header.setValue(encodedNoPadding); + rep = HeaderUtils.extractEntityHeaders(headers, null); + assertEquals(rep.getDigest().getAlgorithm(), + org.restlet.data.Digest.ALGORITHM_MD5); + assertEquals(new String(rep.getDigest().getValue()), md5hash); + } + public void testInvalidDate() { final String headerValue = "-1"; final Date date = DateUtils.parse(headerValue, diff --git a/modules/org.restlet/src/org/restlet/engine/header/HeaderUtils.java b/modules/org.restlet/src/org/restlet/engine/header/HeaderUtils.java index ebcc35fc30..8016d77aea 100644 --- a/modules/org.restlet/src/org/restlet/engine/header/HeaderUtils.java +++ b/modules/org.restlet/src/org/restlet/engine/header/HeaderUtils.java @@ -122,6 +122,7 @@ public class HeaderUtils { HeaderConstants.HEADER_VARY, HeaderConstants.HEADER_VIA, HeaderConstants.HEADER_WARNING, HeaderConstants.HEADER_WWW_AUTHENTICATE))); + /** * Set of unsupported headers that will be covered in future versions. */ @@ -631,7 +632,8 @@ public static void copyExtensionHeaders(Series<Header> headers, // [ifndef gwt] instruction extensionHeaders = new Series<Header>(Header.class); // [ifdef gwt] instruction uncomment - // extensionHeaders = new org.restlet.engine.util.HeaderSeries(); + // extensionHeaders = new + // org.restlet.engine.util.HeaderSeries(); response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, extensionHeaders); } @@ -852,10 +854,19 @@ public static Representation extractEntityHeaders(Iterable<Header> headers, } else if (header.getName().equalsIgnoreCase( HeaderConstants.HEADER_CONTENT_MD5)) { // [ifndef gwt] + // Since an MD5 hash is 128 bits long, its base64 encoding + // is 22 bytes if unpadded, or 24 bytes if padded. If the + // header value is unpadded, append two base64 padding + // characters ("==") before passing the value to + // Base64.decode(), which requires its input argument's + // length to be a multiple of four. + String base64hash = header.getValue(); + if (base64hash.length() == 22) { + base64hash += "=="; + } result.setDigest(new org.restlet.data.Digest( org.restlet.data.Digest.ALGORITHM_MD5, - org.restlet.engine.util.Base64.decode(header - .getValue()))); + org.restlet.engine.util.Base64.decode(base64hash))); entityHeaderFound = true; // [enddef] }
0beaf21a12326edae32f256a2ff57c4684c2ad43
Vala
Fix bindings to use the new syntax for fixed-length arrays Fixes bug 590477.
a
https://github.com/GNOME/vala/
diff --git a/vapi/fuse.vapi b/vapi/fuse.vapi index 8232b20f70..054bcd60e1 100644 --- a/vapi/fuse.vapi +++ b/vapi/fuse.vapi @@ -51,9 +51,9 @@ namespace Fuse { } [CCode (cname = "fuse_fill_dir_t")] - public static delegate int FillDir (void* buf, string name, stat? st, off_t offset); + public static delegate int FillDir (void* buf, string name, Stat? st, off_t offset); - public static delegate int GetAttr (string path, stat* st); + public static delegate int GetAttr (string path, Stat* st); public static delegate int Access (string path, int mask); public static delegate int ReadLink (string path, char* buf, size_t size); public static delegate int ReadDir (string path, void* buf, FillDir filler, off_t offset, FileInfo fi); @@ -67,7 +67,7 @@ namespace Fuse { public static delegate int Chmod (string path, mode_t mode); public static delegate int Chown (string path, uid_t uid, gid_t gid); public static delegate int Truncate (string path, off_t size); - public static delegate int Utimens (string path, timespec[2] ts); + public static delegate int Utimens (string path, timespec[] ts); public static delegate int Open (string path, FileInfo fi); public static delegate int Read (string path, char* buf, size_t size, off_t offset, FileInfo fi); public static delegate int Write (string path, char* buf, size_t size, off_t offset, FileInfo fi); diff --git a/vapi/gsl.vapi b/vapi/gsl.vapi index 7529e5d7ad..4ad89b1580 100644 --- a/vapi/gsl.vapi +++ b/vapi/gsl.vapi @@ -2331,8 +2331,8 @@ namespace Gsl { public size_t n; public size_t nf; - public size_t[64] factor; - public Complex[64] twiddle; + public size_t factor[64]; + public Complex twiddle[64]; public Complex trig; [CCode (cname="gsl_fft_complex_wavetable_alloc")] @@ -2376,8 +2376,8 @@ namespace Gsl { public size_t n; public size_t nf; - public size_t[64] factor; - public Complex[64] twiddle; + public size_t factor[64]; + public Complex twiddle[64]; public Complex trig; [CCode (cname="gsl_fft_real_wavetable_alloc")] @@ -2410,8 +2410,8 @@ namespace Gsl { public size_t n; public size_t nf; - public size_t[64] factor; - public Complex[64] twiddle; + public size_t factor[64]; + public Complex twiddle[64]; public Complex trig; [CCode (cname="gsl_fft_halfcomplex_wavetable_alloc")] @@ -2481,10 +2481,10 @@ namespace Gsl public double beta; public int mu; public int nu; - public double[25] ri; - public double[25] rj; - public double[25] rg; - public double[25] rh; + public double ri[25]; + public double rj[25]; + public double rg[25]; + public double rh[25]; [CCode (cname="gsl_integration_qaws_table_alloc")] public IntegrationQAWSTable (double alpha, double beta, int mu, int nu); diff --git a/vapi/v4l2.vapi b/vapi/v4l2.vapi index 25f4988b2e..4b1a8498bd 100644 --- a/vapi/v4l2.vapi +++ b/vapi/v4l2.vapi @@ -314,7 +314,7 @@ namespace V4l2 public uint8 seconds; public uint8 minutes; public uint8 hours; - public uint8[4] userbits; + public uint8 userbits[4]; } [CCode (cprefix="V4L2_TC_TYPE_")] @@ -349,9 +349,9 @@ namespace V4l2 public int quality; public int APPn; public int APP_len; - public char[60] APP_data; + public char APP_data[60]; public int COM_len; - public char[60] COM_data; + public char COM_data[60]; public uint32 jpeg_markers; } @@ -1135,7 +1135,7 @@ namespace V4l2 { public uint32 entries; public uint32 entries_cap; - public EncIdxEntry[V4L2_ENC_IDX_ENTRIES] entry; + public EncIdxEntry[] entry; } [CCode (cprefix="V4L2_ENC_CMD_")] @@ -1151,7 +1151,7 @@ namespace V4l2 [CCode (cname="struct raw")] public struct Raw { - public uint32[8] data; + public uint32 data[8]; } [CCode (cname="struct v4l2_encoder_cmd")] @@ -1169,8 +1169,8 @@ namespace V4l2 public uint32 offset; public uint32 samples_per_line; public uint32 sample_format; - public int32[2] start; - public uint32[2] count; + public int32 start[2]; + public uint32 count[2]; public uint32 flags; } @@ -1185,7 +1185,7 @@ namespace V4l2 public struct SlicedVbiFormat { public uint16 service_set; - public uint16[2, 24] service_lines; + public uint16[] service_lines; public uint32 io_size; public uint32[] reserved; } @@ -1206,7 +1206,7 @@ namespace V4l2 public struct SlicedVbiCap { public uint16 service_set; - public uint16[2, 24] service_lines; + public uint16[] service_lines; public BufferType type; } @@ -1216,7 +1216,7 @@ namespace V4l2 public uint32 id; public uint32 field; public uint32 line; - public uint8[48] data; + public uint8 data[48]; } public struct Fmt @@ -1225,7 +1225,7 @@ namespace V4l2 public Window win; public VbiFormat vbi; public SlicedVbiFormat sliced; - public uint8[200] raw_data; + public uint8 raw_data[200]; } [CCode (cname="struct v4l2_format")] @@ -1239,7 +1239,7 @@ namespace V4l2 { public CaptureParm capture; public OutputParm output; - public uint8[200] raw_data; + public uint8 raw_data[200]; } [CCode (cname="struct v4l2_streamparm")]
ed8f32bd6696291a1bc49597b70c30335ec2917d
Vala
Support chain up to constructv functions.
a
https://github.com/GNOME/vala/
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala index e42c5785ee..5cdd816cd2 100644 --- a/codegen/valaccodebasemodule.vala +++ b/codegen/valaccodebasemodule.vala @@ -6205,6 +6205,18 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator { return get_ccode_attribute(sym).real_name; } + public static string get_ccode_constructv_name (CreationMethod m) { + const string infix = "constructv"; + + var parent = m.parent_symbol as Class; + + if (m.name == ".new") { + return "%s%s".printf (get_ccode_lower_case_prefix (parent), infix); + } else { + return "%s%s_%s".printf (get_ccode_lower_case_prefix (parent), infix, m.name); + } + } + public static string get_ccode_vfunc_name (Method m) { return get_ccode_attribute(m).vfunc_name; } diff --git a/codegen/valaccodemethodcallmodule.vala b/codegen/valaccodemethodcallmodule.vala index 0bd462a134..728dccdd49 100644 --- a/codegen/valaccodemethodcallmodule.vala +++ b/codegen/valaccodemethodcallmodule.vala @@ -48,6 +48,8 @@ public class Vala.CCodeMethodCallModule : CCodeAssignmentModule { // Enum.VALUE.to_string() var en = (Enum) ma.inner.value_type.data_type; ccall.call = new CCodeIdentifier (generate_enum_tostring_function (en)); + } else if (expr.is_constructv_chainup) { + ccall.call = new CCodeIdentifier (get_ccode_constructv_name ((CreationMethod) m)); } } else if (itype is SignalType) { var sig_type = (SignalType) itype; @@ -61,7 +63,11 @@ public class Vala.CCodeMethodCallModule : CCodeAssignmentModule { var cl = (Class) ((ObjectType) itype).type_symbol; m = cl.default_construction_method; generate_method_declaration (m, cfile); - ccall = new CCodeFunctionCall (new CCodeIdentifier (get_ccode_real_name (m))); + var real_name = get_ccode_real_name (m); + if (expr.is_constructv_chainup) { + real_name = get_ccode_constructv_name ((CreationMethod) m); + } + ccall = new CCodeFunctionCall (new CCodeIdentifier (real_name)); } else if (itype is StructValueType) { // constructor var st = (Struct) ((StructValueType) itype).type_symbol; @@ -598,7 +604,7 @@ public class Vala.CCodeMethodCallModule : CCodeAssignmentModule { * except when using printf-style arguments */ if (m == null) { in_arg_map.set (get_param_pos (-1, true), new CCodeConstant ("NULL")); - } else if (!m.printf_format && !m.scanf_format && get_ccode_sentinel (m) != "") { + } else if (!m.printf_format && !m.scanf_format && get_ccode_sentinel (m) != "" && !expr.is_constructv_chainup) { in_arg_map.set (get_param_pos (-1, true), new CCodeConstant (get_ccode_sentinel (m))); } } diff --git a/codegen/valaccodemethodmodule.vala b/codegen/valaccodemethodmodule.vala index f0cddaec11..c7c7818f72 100644 --- a/codegen/valaccodemethodmodule.vala +++ b/codegen/valaccodemethodmodule.vala @@ -204,7 +204,7 @@ public abstract class Vala.CCodeMethodModule : CCodeStructModule { if (m.is_variadic ()) { // _constructv function - function = new CCodeFunction (get_constructv_name ((CreationMethod) m)); + function = new CCodeFunction (get_ccode_constructv_name ((CreationMethod) m)); cparam_map = new HashMap<int,CCodeParameter> (direct_hash, direct_equal); generate_cparameters (m, decl_space, cparam_map, function); @@ -214,18 +214,6 @@ public abstract class Vala.CCodeMethodModule : CCodeStructModule { } } - private string get_constructv_name (CreationMethod m) { - const string infix = "constructv"; - - var parent = m.parent_symbol as Class; - - if (m.name == ".new") { - return "%s%s".printf (CCodeBaseModule.get_ccode_lower_case_prefix (parent), infix); - } else { - return "%s%s_%s".printf (CCodeBaseModule.get_ccode_lower_case_prefix (parent), infix, m.name); - } - } - void register_plugin_types (Symbol sym, Set<Symbol> registered_types) { var ns = sym as Namespace; var cl = sym as Class; @@ -289,7 +277,7 @@ public abstract class Vala.CCodeMethodModule : CCodeStructModule { public override void visit_method (Method m) { string real_name = get_ccode_real_name (m); if (m is CreationMethod && m.is_variadic ()) { - real_name = get_constructv_name ((CreationMethod) m); + real_name = get_ccode_constructv_name ((CreationMethod) m); } push_context (new EmitContext (m)); @@ -1182,7 +1170,7 @@ public abstract class Vala.CCodeMethodModule : CCodeStructModule { push_function (vfunc); - string constructor = (m.is_variadic ()) ? get_constructv_name (m) : get_ccode_real_name (m); + string constructor = (m.is_variadic ()) ? get_ccode_constructv_name (m) : get_ccode_real_name (m); var vcall = new CCodeFunctionCall (new CCodeIdentifier (constructor)); if (self_as_first_parameter) { diff --git a/tests/Makefile.am b/tests/Makefile.am index b84ee0411a..b84d433ebd 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -100,6 +100,7 @@ TESTS = \ delegates/bug638415.vala \ delegates/bug639751.vala \ delegates/bug703804.vala \ + objects/chainup.vala \ objects/classes.vala \ objects/fields.vala \ objects/interfaces.vala \ diff --git a/tests/objects/chainup.vala b/tests/objects/chainup.vala new file mode 100644 index 0000000000..fdca08d671 --- /dev/null +++ b/tests/objects/chainup.vala @@ -0,0 +1,39 @@ +class FooBase { + public int bar; + + public FooBase (int _, ...) { + va_list v = va_list (); + bar = v.arg (); + } + + public FooBase.baz (int _, ...) { + va_list v = va_list (); + this (_, v); + } +} + +class Foo : FooBase { + public Foo (int _, ...) { + va_list v = va_list (); + base (_, v); + } + + public Foo.baz (int _, ...) { + va_list v = va_list (); + base.baz (_, v); + } + + public Foo.qux (int _, ...) { + va_list v = va_list (); + this.baz (_, v); + } +} + +void main () { + var foo = new Foo (0, 10); + assert (foo.bar == 10); + foo = new Foo.baz (0, 20); + assert (foo.bar == 20); + foo = new Foo.qux (0, 30); + assert (foo.bar == 30); +} diff --git a/vala/valaclass.vala b/vala/valaclass.vala index 5110a7aa63..ba23a508fb 100644 --- a/vala/valaclass.vala +++ b/vala/valaclass.vala @@ -151,7 +151,7 @@ public class Vala.Class : ObjectTypeSymbol { /** * Specifies the default construction method. */ - public Method default_construction_method { get; set; } + public CreationMethod default_construction_method { get; set; } /** * Specifies the instance constructor. @@ -303,7 +303,7 @@ public class Vala.Class : ObjectTypeSymbol { } if (m is CreationMethod) { if (m.name == null) { - default_construction_method = m; + default_construction_method = (CreationMethod) m; m.name = ".new"; } diff --git a/vala/valamethodcall.vala b/vala/valamethodcall.vala index 5b0ba8a1de..89d2ba5cc0 100644 --- a/vala/valamethodcall.vala +++ b/vala/valamethodcall.vala @@ -41,6 +41,11 @@ public class Vala.MethodCall : Expression { public bool is_assert { get; private set; } + /** + * Whether this chain up uses the constructv function with va_list. + */ + public bool is_constructv_chainup { get; private set; } + public Expression _call; private List<Expression> argument_list = new ArrayList<Expression> (); @@ -213,6 +218,8 @@ public class Vala.MethodCall : Expression { var mtype = call.value_type; + CreationMethod base_cm = null; + if (mtype is ObjectType || call.symbol_reference == context.analyzer.object_type) { // constructor chain-up var cm = context.analyzer.find_current_method () as CreationMethod; @@ -230,7 +237,7 @@ public class Vala.MethodCall : Expression { if (mtype is ObjectType) { var otype = (ObjectType) mtype; var cl = (Class) otype.type_symbol; - var base_cm = cl.default_construction_method; + base_cm = cl.default_construction_method; if (base_cm == null) { error = true; Report.error (source_reference, "chain up to `%s' not supported".printf (cl.get_full_name ())); @@ -301,7 +308,7 @@ public class Vala.MethodCall : Expression { } cm.chain_up = true; - var base_cm = (CreationMethod) call.symbol_reference; + base_cm = (CreationMethod) call.symbol_reference; if (!base_cm.has_construct_function) { error = true; Report.error (source_reference, "chain up to `%s' not supported".printf (base_cm.get_full_name ())); @@ -720,6 +727,14 @@ public class Vala.MethodCall : Expression { return false; } + /* Check for constructv chain up */ + if (base_cm != null && base_cm.is_variadic () && args.size == base_cm.get_parameters ().size) { + var this_last_arg = args[args.size-1]; + if (this_last_arg.value_type is StructValueType && this_last_arg.value_type.data_type == context.analyzer.va_list_type.data_type) { + is_constructv_chainup = true; + } + } + if (may_throw) { if (parent_node is LocalVariable || parent_node is ExpressionStatement) { // simple statements, no side effects after method call diff --git a/vala/valasemanticanalyzer.vala b/vala/valasemanticanalyzer.vala index 90923ac2c5..8244896d00 100644 --- a/vala/valasemanticanalyzer.vala +++ b/vala/valasemanticanalyzer.vala @@ -150,6 +150,7 @@ public class Vala.SemanticAnalyzer : CodeVisitor { public DataType unichar_type; public DataType double_type; public DataType type_type; + public DataType va_list_type; public Class object_type; public StructValueType gvalue_type; public ObjectType gvariant_type; @@ -196,6 +197,7 @@ public class Vala.SemanticAnalyzer : CodeVisitor { size_t_type = new IntegerType ((Struct) root_symbol.scope.lookup ("size_t")); ssize_t_type = new IntegerType ((Struct) root_symbol.scope.lookup ("ssize_t")); double_type = new FloatingType ((Struct) root_symbol.scope.lookup ("double")); + va_list_type = new StructValueType ((Struct) root_symbol.scope.lookup ("va_list")); var unichar_struct = (Struct) root_symbol.scope.lookup ("unichar"); if (unichar_struct != null) {
a307fbcc9de63945fea3d0dc298ea14eaf59cf5b
tapiji
Deletes branch master.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF index cfbfc3ac..f0a5731d 100644 --- a/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.translator.rap.supplemental/META-INF/MANIFEST.MF @@ -20,7 +20,7 @@ Export-Package: org.eclipse.jdt.core, org.eclipse.ui.texteditor, org.eclipselabs.tapiji.translator.rap.supplemental Require-Bundle: org.eclipse.core.filesystem;bundle-version="1.3.100", - org.eclipse.core.runtime;bundle-version="3.8.0", + org.eclipse.core.runtime, org.eclipse.core.resources;bundle-version="3.7.101", org.eclipse.rap.ui;bundle-version="1.5.0", org.eclipse.rap.ui.workbench,
fbe88fe1a56907fae90cdf3ebf8c9fb1e12c7d09
intellij-community
form scope provider & dom lookups implemented--
a
https://github.com/JetBrains/intellij-community
diff --git a/codeInsight/impl/com/intellij/codeInsight/lookup/LookupValueFactory.java b/codeInsight/impl/com/intellij/codeInsight/lookup/LookupValueFactory.java new file mode 100644 index 0000000000000..b0a5173f0c3a7 --- /dev/null +++ b/codeInsight/impl/com/intellij/codeInsight/lookup/LookupValueFactory.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved. + */ + +package com.intellij.codeInsight.lookup; + +import com.intellij.openapi.util.Iconable; + +import javax.swing.*; + +/** + * @author Dmitry Avdeev + */ +public class LookupValueFactory { + + private LookupValueFactory() { + } + + public static Object createLookupValue(String name, Icon icon) { + return new LookupValueWithIcon(name, icon); + } + + public static class LookupValueWithIcon implements PresentableLookupValue, Iconable { + private final String myName; + private final Icon myIcon; + + protected LookupValueWithIcon(String name, Icon icon) { + + myName = name; + myIcon = icon; + } + public String getPresentation() { + return myName; + } + + public Icon getIcon(int flags) { + return myIcon; + } + } +} diff --git a/dom/impl/src/com/intellij/util/xml/impl/GenericDomValueReference.java b/dom/impl/src/com/intellij/util/xml/impl/GenericDomValueReference.java index 36fed9058e15f..a25ddc29270d7 100644 --- a/dom/impl/src/com/intellij/util/xml/impl/GenericDomValueReference.java +++ b/dom/impl/src/com/intellij/util/xml/impl/GenericDomValueReference.java @@ -4,7 +4,6 @@ package com.intellij.util.xml.impl; import com.intellij.javaee.J2EEBundle; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; @@ -14,13 +13,14 @@ import com.intellij.psi.impl.source.resolve.reference.impl.GenericReference; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlTag; -import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.*; +import com.intellij.codeInsight.lookup.LookupValueFactory; +import javax.swing.*; import java.util.Collection; import java.util.List; +import java.util.ArrayList; /** * author: lesya @@ -151,21 +151,18 @@ public Object[] getVariants() { final ResolvingConverter<T> resolvingConverter = (ResolvingConverter<T>)converter; final ConvertContext convertContext = new ConvertContextImpl(DomManagerImpl.getDomInvocationHandler(myGenericValue)); final Collection<T> variants = resolvingConverter.getVariants(convertContext); - if (!variants.isEmpty()) { - final Collection<String> strings = ContainerUtil.findAll(ContainerUtil.map(variants, new Function<T, String>() { - public String fun(final T s) { - return converter.toString(s, convertContext); - } - }), new Condition<String>() { - public boolean value(final String object) { - return object != null; - } - }); - if (!strings.isEmpty()) { - return strings.toArray(new String[strings.size()]); + ArrayList<Object> result = new ArrayList<Object>(variants.size()); + for (T variant: variants) { + String name = converter.toString(variant, convertContext); + if (name != null) { + Icon icon = ElementPresentationManager.getIcon(variant); + Object value = LookupValueFactory.createLookupValue(name, icon); + result.add(value); } } + return result.toArray(); } return super.getVariants(); } + } diff --git a/dom/openapi/src/com/intellij/util/xml/ResolvingConverter.java b/dom/openapi/src/com/intellij/util/xml/ResolvingConverter.java index 8122a7d58ce33..38f510059b21d 100644 --- a/dom/openapi/src/com/intellij/util/xml/ResolvingConverter.java +++ b/dom/openapi/src/com/intellij/util/xml/ResolvingConverter.java @@ -16,6 +16,8 @@ */ package com.intellij.util.xml; +import org.jetbrains.annotations.NotNull; + import java.util.Collection; import java.util.Arrays; import java.util.Collections; @@ -53,10 +55,12 @@ public String toString(final Boolean t, final ConvertContext context) { return t == null? null:t.toString(); } + @NotNull public Collection<Boolean> getVariants(final ConvertContext context) { return Arrays.asList(Boolean.FALSE, Boolean.TRUE); } }; + @NotNull Collection<T> getVariants(final ConvertContext context); } diff --git a/dom/openapi/src/com/intellij/util/xml/Scope.java b/dom/openapi/src/com/intellij/util/xml/Scope.java index 0b98d6282ac6f..65abd61e1c20c 100644 --- a/dom/openapi/src/com/intellij/util/xml/Scope.java +++ b/dom/openapi/src/com/intellij/util/xml/Scope.java @@ -3,9 +3,13 @@ */ package com.intellij.util.xml; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + /** * @author peter */ +@Retention(RetentionPolicy.RUNTIME) public @interface Scope { Class<? extends ScopeProvider> value(); } diff --git a/dom/openapi/src/com/intellij/util/xml/ScopeProvider.java b/dom/openapi/src/com/intellij/util/xml/ScopeProvider.java index f5bd88fd38551..6880c6b46cdbe 100644 --- a/dom/openapi/src/com/intellij/util/xml/ScopeProvider.java +++ b/dom/openapi/src/com/intellij/util/xml/ScopeProvider.java @@ -17,6 +17,7 @@ package com.intellij.util.xml; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * Should be stateless, since its instances are cached. @@ -29,6 +30,6 @@ public interface ScopeProvider { * For uniqueness checking should return element, whose direct children names will be compared. Basically it's parameter element's parent: ParentScopeProvider. * For resolving should return element, whose all children will be searched */ - @NotNull DomElement getScope(@NotNull DomElement element); + @Nullable DomElement getScope(@NotNull DomElement element); }
089b6d52e485ac587753db5343e9bb2104ed1c84
camel
Fixed unit test. Doh what a mistake--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@887104 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java index d8fe3adb3802d..f2c01618cef64 100644 --- a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java @@ -44,12 +44,10 @@ public void setUp() throws Exception { @Test public void testPollingConsumer() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); - result.expectedBodiesReceived(5); + result.expectedMessageCount(3); result.expectedFileExists(FTP_ROOT_DIR + "polling/done/1.txt"); result.expectedFileExists(FTP_ROOT_DIR + "polling/done/2.txt"); result.expectedFileExists(FTP_ROOT_DIR + "polling/done/3.txt"); - result.expectedFileExists(FTP_ROOT_DIR + "polling/done/4.txt"); - result.expectedFileExists(FTP_ROOT_DIR + "polling/done/5.txt"); PollingConsumer consumer = context.getEndpoint(getFtpUrl()).createPollingConsumer(); consumer.start(); @@ -82,8 +80,6 @@ private void prepareFtpServer() throws Exception { sendFile(getFtpUrl(), "Message 1", "1.txt"); sendFile(getFtpUrl(), "Message 2", "2.txt"); sendFile(getFtpUrl(), "Message 3", "3.txt"); - sendFile(getFtpUrl(), "Message 4", "4.txt"); - sendFile(getFtpUrl(), "Message 5", "5.txt"); } } \ No newline at end of file
69c6e80acd16d0073400d78bd0e52caf44ef8f40
ReactiveX-RxJava
added variance to Action*
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java index a688d03792..c24a7143f8 100644 --- a/rxjava-core/src/main/java/rx/Observable.java +++ b/rxjava-core/src/main/java/rx/Observable.java @@ -247,7 +247,7 @@ private Subscription protectivelyWrapAndSubscribe(Observer<T> o) { return subscription.wrap(subscribe(new SafeObserver<T>(subscription, o))); } - public Subscription subscribe(final Action1<T> onNext) { + public Subscription subscribe(final Action1<? super T> onNext) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } @@ -278,11 +278,11 @@ public void onNext(T args) { }); } - public Subscription subscribe(final Action1<T> onNext, Scheduler scheduler) { + public Subscription subscribe(final Action1<? super T> onNext, Scheduler scheduler) { return subscribeOn(scheduler).subscribe(onNext); } - public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError) { + public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } @@ -316,11 +316,11 @@ public void onNext(T args) { }); } - public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError, Scheduler scheduler) { + public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError, Scheduler scheduler) { return subscribeOn(scheduler).subscribe(onNext, onError); } - public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError, final Action0 onComplete) { + public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError, final Action0 onComplete) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } @@ -357,7 +357,7 @@ public void onNext(T args) { }); } - public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError, final Action0 onComplete, Scheduler scheduler) { + public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError, final Action0 onComplete, Scheduler scheduler) { return subscribeOn(scheduler).subscribe(onNext, onError, onComplete); } diff --git a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java index 299c2fdc17..fa502843a4 100644 --- a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java +++ b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java @@ -355,7 +355,7 @@ private Subscription protectivelyWrapAndSubscribe(Observer<T> o) { * @throws RuntimeException * if an error occurs */ - public void forEach(final Action1<T> onNext) { + public void forEach(final Action1<? super T> onNext) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> exceptionFromOnError = new AtomicReference<Throwable>(); diff --git a/rxjava-core/src/main/java/rx/util/functions/Functions.java b/rxjava-core/src/main/java/rx/util/functions/Functions.java index 867b47d114..7809b3240d 100644 --- a/rxjava-core/src/main/java/rx/util/functions/Functions.java +++ b/rxjava-core/src/main/java/rx/util/functions/Functions.java @@ -253,7 +253,7 @@ public Void call(Object... args) { * @param f * @return {@link FuncN} */ - public static <T0> FuncN<Void> fromAction(final Action1<T0> f) { + public static <T0> FuncN<Void> fromAction(final Action1<? super T0> f) { return new FuncN<Void>() { @SuppressWarnings("unchecked") @@ -275,7 +275,7 @@ public Void call(Object... args) { * @param f * @return {@link FuncN} */ - public static <T0, T1> FuncN<Void> fromAction(final Action2<T0, T1> f) { + public static <T0, T1> FuncN<Void> fromAction(final Action2<? super T0, ? super T1> f) { return new FuncN<Void>() { @SuppressWarnings("unchecked") @@ -297,7 +297,7 @@ public Void call(Object... args) { * @param f * @return {@link FuncN} */ - public static <T0, T1, T2> FuncN<Void> fromAction(final Action3<T0, T1, T2> f) { + public static <T0, T1, T2> FuncN<Void> fromAction(final Action3<? super T0, ? super T1, ? super T2> f) { return new FuncN<Void>() { @SuppressWarnings("unchecked")
64a2fde80a9f3aa71ac5c0e0b479c242bcecb561
kotlin
Extract Function: Fix signature update on dialog- opening--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java b/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java index e5df89c5e737c..26b599ac49db5 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java @@ -63,7 +63,7 @@ public KotlinExtractFunctionDialog(Project project, ExtractionDescriptorWithConf setModal(true); setTitle(JetRefactoringBundle.message("extract.function")); init(); - update(false); + update(); } private void createUIComponents() { @@ -94,10 +94,8 @@ private boolean checkNames() { return true; } - private void update(boolean recreateDescriptor) { - if (recreateDescriptor) { - this.currentDescriptor = createDescriptor(); - } + private void update() { + this.currentDescriptor = createDescriptor(); setOKActionEnabled(checkNames()); signaturePreviewField.setText( @@ -116,7 +114,7 @@ protected void init() { new DocumentAdapter() { @Override public void documentChanged(DocumentEvent event) { - update(true); + update(); } } ); @@ -130,7 +128,7 @@ public void documentChanged(DocumentEvent event) { new ItemListener() { @Override public void itemStateChanged(@NotNull ItemEvent e) { - update(true); + update(); } } ); @@ -138,7 +136,7 @@ public void itemStateChanged(@NotNull ItemEvent e) { parameterTablePanel = new KotlinParameterTablePanel() { @Override protected void updateSignature() { - KotlinExtractFunctionDialog.this.update(true); + KotlinExtractFunctionDialog.this.update(); } @Override
1bf160a0415dc5838b0eeee9ef92faf152c8c04c
Delta Spike
upgrade to more recent weld-arquillian version
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml index 98801253f..38bb6c33b 100644 --- a/deltaspike/parent/pom.xml +++ b/deltaspike/parent/pom.xml @@ -168,7 +168,7 @@ <jacoco.version>0.5.7.201204190339</jacoco.version> <arquillian-openwebbeans.version>1.0.0.CR2</arquillian-openwebbeans.version> - <arquillian-weld.version>1.0.0.CR3</arquillian-weld.version> + <arquillian-weld.version>1.0.0.CR4</arquillian-weld.version> <!-- OSGi bundles properties --> <deltaspike.osgi.import.deltaspike.version>version="[$(version;==;${deltaspike.osgi.version.clean}),$(version;=+;${deltaspike.osgi.version.clean}))"</deltaspike.osgi.import.deltaspike.version>
1ab51a08aae827b179dc7d2089f0905acf3d1fcd
kotlin
Optimize search of package part files for- JetPositionManager--
p
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/PositionManagerLibraryClassFileSearcher.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/PositionManagerLibraryClassFileSearcher.kt index cdecca370887d..b3a55233c9056 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/PositionManagerLibraryClassFileSearcher.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/PositionManagerLibraryClassFileSearcher.kt @@ -38,6 +38,7 @@ import org.jetbrains.kotlin.psi.JetPsiUtil import org.jetbrains.kotlin.resolve.jvm.JvmClassName import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptor +import com.intellij.util.indexing.FileBasedIndex private val LOG = Logger.getInstance("org.jetbrains.kotlin.idea.debugger") @@ -115,9 +116,11 @@ private fun findPackagePartFileNamesForElement(elementAt: JetElement): List<Stri JdkScope(project, libraryEntry as JdkOrderEntry) } - val packagePartFiles = FilenameIndex.getAllFilesByExt(project, "class", scope) - .filter { it.getName().startsWith(packagePartNameWoHash) } - .map { + val packagePartFiles = FilenameIndex.getAllFilenames(project).stream().filter { + it.startsWith(packagePartNameWoHash) && it.endsWith(".class") + }.flatMap { + FilenameIndex.getVirtualFilesByName(project, it, scope).stream() + }.map { val packageFqName = file.getPackageFqName() if (packageFqName.isRoot()) { it.getNameWithoutExtension() @@ -125,7 +128,7 @@ private fun findPackagePartFileNamesForElement(elementAt: JetElement): List<Stri "${packageFqName.asString()}.${it.getNameWithoutExtension()}" } } - return packagePartFiles + return packagePartFiles.toList() } private fun render(desc: DeclarationDescriptor) = DescriptorRenderer.FQ_NAMES_IN_TYPES.render(desc) diff --git a/idea/src/org/jetbrains/kotlin/idea/util/DebuggerUtils.java b/idea/src/org/jetbrains/kotlin/idea/util/DebuggerUtils.java index 748ed8b245c3d..07ad78368becc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/DebuggerUtils.java +++ b/idea/src/org/jetbrains/kotlin/idea/util/DebuggerUtils.java @@ -28,6 +28,7 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils; import org.jetbrains.kotlin.idea.debugger.DebuggerPackage; +import org.jetbrains.kotlin.load.kotlin.PackageClassUtils; import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils; import org.jetbrains.kotlin.psi.JetElement; import org.jetbrains.kotlin.psi.JetFile; @@ -63,12 +64,16 @@ public boolean apply(@Nullable JetFile file) { return filesWithExactName.iterator().next(); } + if (!isPackagePartClassName(className)) { + return filesWithExactName.iterator().next(); + } + JetFile file = getFileForPackagePartPrefixedName(filesWithExactName, className.getInternalName()); if (file != null) { return file; } - boolean isInLibrary = KotlinPackage.any(filesWithExactName, new Function1<JetFile, Boolean>() { + boolean isInLibrary = KotlinPackage.all(filesWithExactName, new Function1<JetFile, Boolean>() { @Override public Boolean invoke(JetFile file) { return LibraryUtil.findLibraryEntry(file.getVirtualFile(), file.getProject()) != null; @@ -91,6 +96,11 @@ public Boolean invoke(JetFile file) { return null; } + private static boolean isPackagePartClassName(JvmClassName className) { + String packageName = className.getPackageFqName().asString().replaceAll("\\.", "/"); + return className.getInternalName().startsWith(packageName + "/" + PackageClassUtils.getPackageClassName(className.getPackageFqName())); + } + @Nullable private static JetFile getFileForPackagePartPrefixedName( @NotNull Collection<JetFile> allPackageFiles,
2136542f1bbca3cfcad3107365015c103f5b42ae
hadoop
YARN-632. Changed ContainerManager api to throw- IOException and YarnRemoteException. Contributed by Xuan Gong. svn merge- --ignore-ancestry -c 1479740 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1479741 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 22876e4f070e5..a83cc29faaae7 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -37,6 +37,9 @@ Release 2.0.5-beta - UNRELEASED YARN-633. Changed RMAdminProtocol api to throw IOException and YarnRemoteException. (Xuan Gong via vinodkv) + YARN-632. Changed ContainerManager api to throw IOException and + YarnRemoteException. (Xuan Gong via vinodkv) + NEW FEATURES YARN-482. FS: Extend SchedulingMode to intermediate queues. diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ContainerManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ContainerManager.java index 0bb559a9fc557..0961ac4e4d766 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ContainerManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ContainerManager.java @@ -18,6 +18,8 @@ package org.apache.hadoop.yarn.api; +import java.io.IOException; + import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Stable; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusRequest; @@ -68,11 +70,12 @@ public interface ContainerManager { * @return empty response to indicate acceptance of the request * or an exception * @throws YarnRemoteException + * @throws IOException */ @Public @Stable StartContainerResponse startContainer(StartContainerRequest request) - throws YarnRemoteException; + throws YarnRemoteException, IOException; /** * <p>The <code>ApplicationMaster</code> requests a <code>NodeManager</code> @@ -94,11 +97,12 @@ StartContainerResponse startContainer(StartContainerRequest request) * @return empty response to indicate acceptance of the request * or an exception * @throws YarnRemoteException + * @throws IOException */ @Public @Stable StopContainerResponse stopContainer(StopContainerRequest request) - throws YarnRemoteException; + throws YarnRemoteException, IOException; /** * <p>The api used by the <code>ApplicationMaster</code> to request for @@ -118,9 +122,11 @@ StopContainerResponse stopContainer(StopContainerRequest request) * @return response containing the <code>ContainerStatus</code> of the * container * @throws YarnRemoteException + * @throws IOException */ @Public @Stable GetContainerStatusResponse getContainerStatus( - GetContainerStatusRequest request) throws YarnRemoteException; + GetContainerStatusRequest request) throws YarnRemoteException, + IOException; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java index d46be9760900c..c311a34a33b9b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java @@ -759,6 +759,10 @@ public void run() { + container.getId()); e.printStackTrace(); // TODO do we need to release this container? + } catch (IOException e) { + LOG.info("Start container failed for :" + ", containerId=" + + container.getId()); + e.printStackTrace(); } // Get container status? diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/impl/pb/service/ContainerManagerPBServiceImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/impl/pb/service/ContainerManagerPBServiceImpl.java index 4b0af8156d2c2..19eefff1a997c 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/impl/pb/service/ContainerManagerPBServiceImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/impl/pb/service/ContainerManagerPBServiceImpl.java @@ -18,6 +18,8 @@ package org.apache.hadoop.yarn.api.impl.pb.service; +import java.io.IOException; + import org.apache.hadoop.yarn.api.ContainerManager; import org.apache.hadoop.yarn.api.ContainerManagerPB; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusResponse; @@ -57,6 +59,8 @@ public GetContainerStatusResponseProto getContainerStatus(RpcController arg0, return ((GetContainerStatusResponsePBImpl)response).getProto(); } catch (YarnRemoteException e) { throw new ServiceException(e); + } catch (IOException e) { + throw new ServiceException(e); } } @@ -69,6 +73,8 @@ public StartContainerResponseProto startContainer(RpcController arg0, return ((StartContainerResponsePBImpl)response).getProto(); } catch (YarnRemoteException e) { throw new ServiceException(e); + } catch (IOException e) { + throw new ServiceException(e); } } @@ -81,6 +87,8 @@ public StopContainerResponseProto stopContainer(RpcController arg0, return ((StopContainerResponsePBImpl)response).getProto(); } catch (YarnRemoteException e) { throw new ServiceException(e); + } catch (IOException e) { + throw new ServiceException(e); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java index 8e3ef455f9b67..68891103ed8a7 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java @@ -396,7 +396,7 @@ private void authorizeRequest(String containerIDStr, @SuppressWarnings("unchecked") @Override public StartContainerResponse startContainer(StartContainerRequest request) - throws YarnRemoteException { + throws YarnRemoteException, IOException { if (blockNewContainerRequests.get()) { throw RPCUtil.getRemoteException(new NMNotYetReadyException( @@ -503,7 +503,7 @@ public StartContainerResponse startContainer(StartContainerRequest request) @Override @SuppressWarnings("unchecked") public StopContainerResponse stopContainer(StopContainerRequest request) - throws YarnRemoteException { + throws YarnRemoteException, IOException { ContainerId containerID = request.getContainerId(); String containerIDStr = containerID.toString(); @@ -545,7 +545,8 @@ public StopContainerResponse stopContainer(StopContainerRequest request) @Override public GetContainerStatusResponse getContainerStatus( - GetContainerStatusRequest request) throws YarnRemoteException { + GetContainerStatusRequest request) throws YarnRemoteException, + IOException { ContainerId containerID = request.getContainerId(); String containerIDStr = containerID.toString(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java index c1b9ef378472c..5f73d2d105313 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeManagerResync.java @@ -299,6 +299,8 @@ public void run() { // class name after YARN-142 Assert.assertTrue(e.getRemoteTrace().contains( NMNotYetReadyException.class.getName())); + } catch (IOException e) { + assertionFailedInThread.set(true); } } // no. of containers to be launched should equal to no. of diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java index 7da531ece5670..102c77d223094 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java @@ -185,13 +185,13 @@ public void tearDown() throws IOException, InterruptedException { public static void waitForContainerState(ContainerManager containerManager, ContainerId containerID, ContainerState finalState) - throws InterruptedException, YarnRemoteException { + throws InterruptedException, YarnRemoteException, IOException { waitForContainerState(containerManager, containerID, finalState, 20); } public static void waitForContainerState(ContainerManager containerManager, ContainerId containerID, ContainerState finalState, int timeOutMax) - throws InterruptedException, YarnRemoteException { + throws InterruptedException, YarnRemoteException, IOException { GetContainerStatusRequest request = recordFactory.newRecordInstance(GetContainerStatusRequest.class); request.setContainerId(containerID); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java index a4081130da2cf..e0a35eb2f5b3c 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java @@ -531,6 +531,9 @@ void callWithIllegalContainerID(ContainerManager client, "Unauthorized request to start container. " + "\nExpected containerId: " + tokenId.getContainerID() + " Found: " + newContainerId.toString())); + } catch (IOException e) { + LOG.info("Got IOException: ",e); + fail("IOException is not expected."); } } @@ -557,6 +560,9 @@ void callWithIllegalResource(ContainerManager client, Assert.assertTrue(e.getMessage().contains( "\nExpected resource " + tokenId.getResource().toString() + " but found " + container.getResource().toString())); + } catch (IOException e) { + LOG.info("Got IOException: ",e); + fail("IOException is not expected."); } } @@ -585,6 +591,9 @@ void callWithIllegalUserName(ContainerManager client, Assert.assertTrue(e.getMessage().contains( "Expected user-name " + tokenId.getApplicationSubmitter() + " but found " + context.getUser())); + } catch (IOException e) { + LOG.info("Got IOException: ",e); + fail("IOException is not expected."); } }
7140c07477a6e894c02fb5df2fb14d177cb3c40e
Valadoc
libvaladoc: gir-reader: Unescape %, @, (, ), &, #
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentscanner.vala b/src/libvaladoc/documentation/gtkdoccommentscanner.vala index 62b102a945..4f32494253 100644 --- a/src/libvaladoc/documentation/gtkdoccommentscanner.vala +++ b/src/libvaladoc/documentation/gtkdoccommentscanner.vala @@ -147,6 +147,36 @@ public class Valadoc.Gtkdoc.Scanner { start = (string) ((char*) pos + 9); pos = (string) ((char*) pos + 8); builder.append_unichar ('⁄'); + } else if (pos.has_prefix ("&percnt;")) { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + start = (string) ((char*) pos + 8); + pos = (string) ((char*) pos + 7); + builder.append_c ('%'); + } else if (pos.has_prefix ("&commat;")) { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + start = (string) ((char*) pos + 8); + pos = (string) ((char*) pos + 7); + builder.append_c ('@'); + } else if (pos.has_prefix ("&lpar;")) { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + start = (string) ((char*) pos + 6); + pos = (string) ((char*) pos + 5); + builder.append_c ('('); + } else if (pos.has_prefix ("&rpar;")) { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + start = (string) ((char*) pos + 6); + pos = (string) ((char*) pos + 5); + builder.append_c (')'); + } else if (pos.has_prefix ("&num;")) { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + start = (string) ((char*) pos + 5); + pos = (string) ((char*) pos + 4); + builder.append_c ('#'); + } else if (pos.has_prefix ("&amp;")) { + builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); + start = (string) ((char*) pos + 5); + pos = (string) ((char*) pos + 4); + builder.append_c ('&'); } else if (pos.has_prefix ("&ast;")) { builder.append_len (start, (ssize_t) ((char*) pos - (char*) start)); start = (string) ((char*) pos + 5);
68302d9b31f48a7ae68109a651054bbd64546956
Mylyn Reviews
Refactoring - splitted several classes in smaller parts to improve testability - added some javadoc and tests Change-Id: Ic403f614c1a6ebdc2c89994e22ae01becca10e62
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF index 095129ff..36491e2f 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF @@ -14,7 +14,15 @@ Require-Bundle: org.eclipse.mylyn.tasks.core;bundle-version="3.8.0", org.apache.lucene.core;bundle-version="2.9.1", org.eclipse.team.core;bundle-version="3.6.0" Export-Package: org.eclipse.mylyn.versions.tasks.mapper.generic;x-internal:=true, - org.eclipse.mylyn.versions.tasks.mapper.internal + org.eclipse.mylyn.versions.tasks.mapper.internal; + uses:="org.eclipse.mylyn.tasks.core, + org.eclipse.mylyn.versions.tasks.mapper.generic, + org.eclipse.core.runtime, + org.eclipse.mylyn.versions.core, + org.eclipse.mylyn.versions.tasks.core, + org.eclipse.team.core.history, + org.eclipse.core.resources, + org.osgi.framework" Bundle-Vendor: %Bundle-Vendor Bundle-ActivationPolicy: lazy Bundle-Activator: org.eclipse.mylyn.versions.tasks.mapper.internal.RepositoryIndexerPlugin diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java index 3cbe23b9..3a4b6b97 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java @@ -10,42 +10,32 @@ *******************************************************************************/ package org.eclipse.mylyn.versions.tasks.mapper.generic; -import java.io.File; -import java.io.NotSerializableException; -import java.net.URI; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.core.ITask; -import org.eclipse.mylyn.versions.core.ChangeSet; import org.eclipse.mylyn.versions.core.ScmCore; import org.eclipse.mylyn.versions.core.ScmRepository; import org.eclipse.mylyn.versions.core.spi.ScmConnector; import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping; -import org.eclipse.mylyn.versions.tasks.mapper.internal.ChangeSetIndexer; +import org.eclipse.mylyn.versions.tasks.mapper.internal.ChangeSetProvider; +import org.eclipse.mylyn.versions.tasks.mapper.internal.EclipsePluginConfiguration; +import org.eclipse.mylyn.versions.tasks.mapper.internal.MappingChangeSetCollector; import org.eclipse.mylyn.versions.tasks.mapper.internal.RepositoryIndexerPlugin; import org.eclipse.mylyn.versions.tasks.ui.AbstractChangesetMappingProvider; -import org.eclipse.team.core.history.IFileRevision; -import org.eclipse.team.core.history.ITag; -import org.eclipse.team.core.history.provider.FileRevision; /** * * @author Kilian Matt - * + * */ -public class GenericTaskChangesetMapper extends - AbstractChangesetMappingProvider { +public class GenericTaskChangesetMapper extends AbstractChangesetMappingProvider { private IConfiguration configuration; private IChangeSetIndexSearcher indexSearch; @@ -55,8 +45,9 @@ public GenericTaskChangesetMapper() { this.indexSearch = RepositoryIndexerPlugin.getDefault().getIndexer(); } - public GenericTaskChangesetMapper(IConfiguration configuration) { + public GenericTaskChangesetMapper(IConfiguration configuration, IChangeSetIndexSearcher indexSearch) { this.configuration = configuration; + this.indexSearch=indexSearch; } public void getChangesetsForTask(final IChangeSetMapping mapping, @@ -65,77 +56,12 @@ public void getChangesetsForTask(final IChangeSetMapping mapping, if (task == null) throw new IllegalArgumentException("task must not be null"); - List<ScmRepository> repos = getRepositoriesFor(task); for (final ScmRepository repo : repos) { - indexSearch.search(task, repo.getUrl(), 10, new IChangeSetCollector() { - - public void collect(String revision, String repositoryUrl) throws CoreException { - mapping.addChangeSet(getChangeset(revision, repo,monitor)); - } - }); - } - } - - class FileRevision implements IFileRevision{ - private String contentIdentifier; - - public FileRevision(String contentIdentifier){ - this.contentIdentifier=contentIdentifier; - } - - public IStorage getStorage(IProgressMonitor monitor) - throws CoreException { - throw new UnsupportedOperationException(); + ChangeSetProvider provider = new ChangeSetProvider(repo); + indexSearch.search(task, repo.getUrl(), 10, + new MappingChangeSetCollector(monitor, mapping, provider)); } - - public String getName() { - throw new UnsupportedOperationException(); - } - - public URI getURI() { - throw new UnsupportedOperationException(); - } - - public long getTimestamp() { - throw new UnsupportedOperationException(); - } - - public boolean exists() { - throw new UnsupportedOperationException(); - } - - public String getContentIdentifier() { - return contentIdentifier; - } - - public String getAuthor() { - throw new UnsupportedOperationException(); - } - - public String getComment() { - throw new UnsupportedOperationException(); - } - - public ITag[] getBranches() { - throw new UnsupportedOperationException(); - } - - public ITag[] getTags() { - throw new UnsupportedOperationException(); - } - - public boolean isPropertyMissing() { - throw new UnsupportedOperationException(); - } - - public IFileRevision withAllProperties(IProgressMonitor monitor) - throws CoreException { - throw new UnsupportedOperationException(); - }} - - protected ChangeSet getChangeset(String revision, ScmRepository repo,IProgressMonitor monitor) throws CoreException { - return repo.getConnector().getChangeSet(repo, new FileRevision(revision), monitor); } private List<ScmRepository> getRepositoriesFor(ITask task) diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java index 394c83d6..bcb2bb5c 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java @@ -11,8 +11,9 @@ package org.eclipse.mylyn.versions.tasks.mapper.generic; import org.eclipse.core.runtime.CoreException; + /** - * + * Collects the changes of a search. * @author Kilian Matt * */ diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java index 24e7ed98..d7460e44 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java @@ -53,7 +53,6 @@ /** * * @author Kilian Matt - * */ public class ChangeSetIndexer implements IChangeSetIndexSearcher { diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetProvider.java new file mode 100644 index 00000000..d375a305 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetProvider.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.mylyn.versions.core.ChangeSet; +import org.eclipse.mylyn.versions.core.ScmRepository; + +/** + * + * @author Kilian Matt + */ +public final class ChangeSetProvider{ + private ScmRepository repo; + + public ChangeSetProvider(ScmRepository repo) { + this.repo=repo; + } + + public ChangeSet getChangeset(String revision, + IProgressMonitor monitor) throws CoreException { + return repo.getConnector().getChangeSet(repo, + new FileRevision(revision), monitor); + } +} \ No newline at end of file diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseIndexLocationProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseIndexLocationProvider.java new file mode 100644 index 00000000..6e915695 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseIndexLocationProvider.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import java.io.File; + +import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; + +/** + * Eclipse-based implementation of {@link IIndexLocationProvider}, which uses a user-defineable Location stored in the preferences. + * + * @author Kilian Matt + */ +public class EclipseIndexLocationProvider implements IIndexLocationProvider{ + + public File getIndexLocation(){ + return new File(TasksUiPlugin.getDefault().getDataDirectory(),".changeSetIndex"); + } + +} diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/EclipsePluginConfiguration.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipsePluginConfiguration.java similarity index 92% rename from tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/EclipsePluginConfiguration.java rename to tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipsePluginConfiguration.java index cd278871..6b0219ec 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/EclipsePluginConfiguration.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipsePluginConfiguration.java @@ -8,7 +8,7 @@ * Contributors: * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.versions.tasks.mapper.generic; +package org.eclipse.mylyn.versions.tasks.mapper.internal; import java.util.ArrayList; import java.util.List; @@ -17,6 +17,7 @@ import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.core.TaskRepository; +import org.eclipse.mylyn.versions.tasks.mapper.generic.IConfiguration; /** * diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java index 5a05735e..1ea07839 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java @@ -24,10 +24,11 @@ import org.eclipse.mylyn.versions.core.spi.ScmConnector; import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexer; import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetSource; + /** + * ChangeSet Source, which provides the changesets of all (shared) projects in the Eclipse workspace. * * @author Kilian Matt - * */ public class EclipseWorkspaceRepositorySource implements IChangeSetSource { public void fetchAllChangesets(IProgressMonitor monitor, diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/FileRevision.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/FileRevision.java new file mode 100644 index 00000000..84bd3b77 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/FileRevision.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import java.net.URI; + +import org.eclipse.core.resources.IStorage; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.team.core.history.IFileRevision; +import org.eclipse.team.core.history.ITag; + +/** + * + * @author Kilian Matt + * + */ +public class FileRevision implements IFileRevision { + private String contentIdentifier; + + public FileRevision(String contentIdentifier) { + this.contentIdentifier = contentIdentifier; + } + + public IStorage getStorage(IProgressMonitor monitor) throws CoreException { + throw new UnsupportedOperationException(); + } + + public String getName() { + throw new UnsupportedOperationException(); + } + + public URI getURI() { + throw new UnsupportedOperationException(); + } + + public long getTimestamp() { + throw new UnsupportedOperationException(); + } + + public boolean exists() { + throw new UnsupportedOperationException(); + } + + public String getContentIdentifier() { + return contentIdentifier; + } + + public String getAuthor() { + throw new UnsupportedOperationException(); + } + + public String getComment() { + throw new UnsupportedOperationException(); + } + + public ITag[] getBranches() { + throw new UnsupportedOperationException(); + } + + public ITag[] getTags() { + throw new UnsupportedOperationException(); + } + + public boolean isPropertyMissing() { + throw new UnsupportedOperationException(); + } + + public IFileRevision withAllProperties(IProgressMonitor monitor) + throws CoreException { + throw new UnsupportedOperationException(); + } +} \ No newline at end of file diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IIndexLocationProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IIndexLocationProvider.java new file mode 100644 index 00000000..b42a1e19 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IIndexLocationProvider.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import java.io.File; + +/** + * + * @author Kilian Matt + */ +public interface IIndexLocationProvider { + public File getIndexLocation(); +} diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java index 82f38d72..0a760298 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java @@ -12,7 +12,7 @@ import org.eclipse.core.runtime.Assert; /** - * + * Enumeration of fields, which are indexed * @author Kilian Matt * */ diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/MappingChangeSetCollector.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/MappingChangeSetCollector.java new file mode 100644 index 00000000..dd2797d3 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/MappingChangeSetCollector.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping; +import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetCollector; + +/** + * Implementation of an {@link IChangeSetCollector}, which maps the found matches to changesets + * @author Kilian Matt + */ +public class MappingChangeSetCollector implements IChangeSetCollector { + private final IProgressMonitor monitor; + private final IChangeSetMapping mapping; + private final ChangeSetProvider changeSetProvider; + + public MappingChangeSetCollector(IProgressMonitor monitor, + IChangeSetMapping mapping, ChangeSetProvider changeSetProvider) { + this.monitor = monitor; + this.mapping = mapping; + this.changeSetProvider=changeSetProvider; + } + + public void collect(String revision, String repositoryUrl) throws CoreException { + mapping.addChangeSet(changeSetProvider.getChangeset(revision, monitor)); + } + +} diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java index ecea2908..02610a85 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java @@ -15,6 +15,7 @@ import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexSearcher; + /** * * @author Kilian Matt @@ -22,12 +23,19 @@ */ public class RepositoryIndexer { + private static final int STARTUP_DELAY_MILLIS = 10000; private IndexRepositoryJob repoSyncJob; public RepositoryIndexer() { - repoSyncJob = new IndexRepositoryJob(); - repoSyncJob.schedule(10000); + } + + public void start() { + repoSyncJob.schedule(STARTUP_DELAY_MILLIS); + } + + public void stop() { + repoSyncJob.cancel(); } private static class IndexRepositoryJob extends Job { diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java index 72872649..f9273172 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java @@ -16,39 +16,52 @@ import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexSearcher; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; + + /** * * @author Kilian Matt - * + * */ -public class RepositoryIndexerPlugin implements BundleActivator { +public class RepositoryIndexerPlugin implements BundleActivator { + public static final String PLUGIN_ID = "org.eclipse.mylyn.versions.tasks.mapper"; private static RepositoryIndexerPlugin instance; - public static final String PLUGIN_ID="org.eclipse.mylyn.versions.tasks.mapper"; - + private RepositoryIndexer synchronizer; private IChangeSetIndexSearcher indexSearch; - + public RepositoryIndexerPlugin() { - instance = this; } public static RepositoryIndexerPlugin getDefault() { return instance; } - + public void start(BundleContext context) throws Exception { - synchronizer= new RepositoryIndexer(); - - File file = new File(TasksUiPlugin.getDefault().getDataDirectory(),".changeSetIndex"); - indexSearch=new ChangeSetIndexer(file,new EclipseWorkspaceRepositorySource()); - } - public IChangeSetIndexSearcher getIndexer(){ - return indexSearch; + RepositoryIndexerPlugin.instance = this; + synchronizer = new RepositoryIndexer(); + synchronizer.start(); } public void stop(BundleContext context) throws Exception { - this.instance=null; - + RepositoryIndexerPlugin.instance = null; + synchronizer.stop(); + } + + public IChangeSetIndexSearcher getIndexer() { + if (indexSearch == null) { + initIndexer(); + } + return indexSearch; } + protected synchronized void initIndexer() { + if (indexSearch == null) { + File file = new EclipseIndexLocationProvider().getIndexLocation(); + indexSearch = new ChangeSetIndexer(file, + new EclipseWorkspaceRepositorySource()); + } + } + + } diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF index 209af050..e28de0ea 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF @@ -1,12 +1,16 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Task Mapper Tests -Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.mapper.tests +Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.mapper.tests;singleton:=true Bundle-Version: 1.1.0.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Fragment-Host: org.eclipse.mylyn.versions.tasks.mapper.generic Require-Bundle: org.junit;bundle-version="4.8.2", - org.eclipse.mylyn.versions.tasks.mapper.generic;bundle-version="0.1.0", org.eclipse.mylyn.versions.core;bundle-version="1.0.0", org.eclipse.core.runtime;bundle-version="3.7.0", org.eclipse.mylyn.tasks.core;bundle-version="3.8.0", - org.eclipse.mylyn.tasks.tests;bundle-version="3.8.0" + org.eclipse.mylyn.tasks.tests;bundle-version="3.8.0", + org.eclipse.mylyn.versions.tasks.core;bundle-version="1.1.0", + org.mockito;bundle-version="1.8.4", + org.eclipse.mylyn.versions.tasks.ui;bundle-version="1.1.0" +Export-Package: org.eclipse.mylyn.versions.tasks.mapper.generic diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties index 34d2e4d2..128ccd14 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties @@ -2,3 +2,4 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ . +additional.bundles = org.objenesis diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml index 26aed9a3..5f5ffc73 100644 --- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml @@ -10,7 +10,7 @@ <groupId>org.eclipse.mylyn.reviews</groupId> <artifactId>org.eclipse.mylyn.versions.tasks.mapper.tests</artifactId> <version>1.1.0-SNAPSHOT</version> - <packaging>eclipse-plugin</packaging> + <packaging>eclipse-test-plugin</packaging> <build> <plugins> <plugin> diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java new file mode 100644 index 00000000..18c1d070 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java @@ -0,0 +1,87 @@ +package org.eclipse.mylyn.versions.tasks.mapper.generic; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.mylyn.tasks.core.ITask; +import org.eclipse.mylyn.versions.core.ChangeSet; +import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +public class GenericTaskChangesetMapperTest { + + private GenericTaskChangesetMapper mapper; + private IChangeSetIndexSearcher indexSearcher; + + @Before + public void setUp() throws Exception { + IConfiguration config = mock(IConfiguration.class); + indexSearcher = mock(IChangeSetIndexSearcher.class); + mapper = new GenericTaskChangesetMapper(config, indexSearcher); + } + + @Test + public void testGetChangesetsForTask_TaskNullNotAllowed() + throws CoreException { + IChangeSetMapping mapping = new TestChangeSetMapping(null); + try { + mapper.getChangesetsForTask(mapping, new NullProgressMonitor()); + fail(); + } catch (IllegalArgumentException ex) { + + } + } + + @Test + public void testGetChangesetsForTask_() throws CoreException { + ITask task = mock(ITask.class); + TestChangeSetMapping mapping = new TestChangeSetMapping(task); + doAnswer(new Answer<Object>() { + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + ((IChangeSetCollector) invocation.getArguments()[3]).collect( + "123", (String) invocation.getArguments()[1]); + return null; + } + + }).when(indexSearcher).search(eq(task), anyString(), anyInt(), + any(IChangeSetCollector.class)); + mapper.getChangesetsForTask(mapping, new NullProgressMonitor()); + assertEquals(1, mapping.getChangeSets().size()); + } + + private static class TestChangeSetMapping implements IChangeSetMapping { + private List<ChangeSet> changes = new ArrayList<ChangeSet>(); + private ITask task; + + TestChangeSetMapping(ITask task) { + this.task = task; + } + + @Override + public ITask getTask() { + return task; + } + + @Override + public void addChangeSet(ChangeSet changeset) { + changes.add(changeset); + } + + public List<ChangeSet> getChangeSets() { + return changes; + } + + } + +} diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPluginTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPluginTest.java new file mode 100644 index 00000000..93a67243 --- /dev/null +++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPluginTest.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.mapper.internal; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +//import org.mockito.Mockito; +import org.osgi.framework.BundleContext; + +/** + * + * @author Kilian Matt + */ +public class RepositoryIndexerPluginTest { + + private RepositoryIndexerPlugin plugin; + private BundleContext context; + + @Before + public void prepare() { + plugin = new RepositoryIndexerPlugin(); + context =null; +// Mockito.mock(BundleContext.class); + } + + @Test + public void startsSavesObjectAsDefault() throws Exception { + plugin.start(context); + Assert.assertSame(plugin, RepositoryIndexerPlugin.getDefault()); + } + + @Test + public void lastStartedObjectIsSavedAsDefault() throws Exception { + plugin.start(context); + + RepositoryIndexerPlugin other = new RepositoryIndexerPlugin(); + other.start(context); + + Assert.assertSame(other, RepositoryIndexerPlugin.getDefault()); + Assert.assertNotSame(plugin, RepositoryIndexerPlugin.getDefault()); + } + +}
448f8dbb9fd9bf2e0ef72dda7bb235915deca94f
hadoop
HADOOP-7110. Implement chmod with JNI. Contributed- by Todd Lipcon--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1063090 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index eba3b6f39cce9..74d4265a974f6 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -266,6 +266,8 @@ Release 0.22.0 - Unreleased HADOOP-6056. Use java.net.preferIPv4Stack to force IPv4. (Michele Catasta via shv) + HADOOP-7110. Implement chmod with JNI. (todd) + OPTIMIZATIONS HADOOP-6884. Add LOG.isDebugEnabled() guard for each LOG.debug(..). diff --git a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java index 053fd392defb8..0ecdd6241e015 100644 --- a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java +++ b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java @@ -36,6 +36,7 @@ import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.permission.FsPermission; +import org.apache.hadoop.io.nativeio.NativeIO; import org.apache.hadoop.util.Progressable; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.StringUtils; @@ -554,8 +555,13 @@ public void setOwner(Path p, String username, String groupname) @Override public void setPermission(Path p, FsPermission permission) throws IOException { - execCommand(pathToFile(p), Shell.SET_PERMISSION_COMMAND, - String.format("%05o", permission.toShort())); + if (NativeIO.isAvailable()) { + NativeIO.chmod(pathToFile(p).getCanonicalPath(), + permission.toShort()); + } else { + execCommand(pathToFile(p), Shell.SET_PERMISSION_COMMAND, + String.format("%05o", permission.toShort())); + } } private static String execCommand(File f, String... cmd) throws IOException { diff --git a/src/java/org/apache/hadoop/io/nativeio/NativeIO.java b/src/java/org/apache/hadoop/io/nativeio/NativeIO.java index 6e16c73fb93c0..db4512562f885 100644 --- a/src/java/org/apache/hadoop/io/nativeio/NativeIO.java +++ b/src/java/org/apache/hadoop/io/nativeio/NativeIO.java @@ -74,6 +74,9 @@ public static boolean isAvailable() { public static native FileDescriptor open(String path, int flags, int mode) throws IOException; /** Wrapper around fstat(2) */ public static native Stat fstat(FileDescriptor fd) throws IOException; + /** Wrapper around chmod(2) */ + public static native void chmod(String path, int mode) throws IOException; + /** Initialize the JNI method ID and class ID cache */ private static native void initNative(); diff --git a/src/native/config.h.in b/src/native/config.h.in index 26f8b0fcfb243..18f5da8462bef 100644 --- a/src/native/config.h.in +++ b/src/native/config.h.in @@ -82,6 +82,9 @@ /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME +/* Define to the home page for this package. */ +#undef PACKAGE_URL + /* Define to the version of this package. */ #undef PACKAGE_VERSION diff --git a/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c b/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c index 1c1a9896274c0..d55072099db4e 100644 --- a/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c +++ b/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c @@ -221,6 +221,25 @@ Java_org_apache_hadoop_io_nativeio_NativeIO_open( return ret; } +/** + * public static native void chmod(String path, int mode) throws IOException; + */ +JNIEXPORT void JNICALL +Java_org_apache_hadoop_io_nativeio_NativeIO_chmod( + JNIEnv *env, jclass clazz, jstring j_path, + jint mode) +{ + const char *path = (*env)->GetStringUTFChars(env, j_path, NULL); + if (path == NULL) return; // JVM throws Exception for us + + if (chmod(path, mode) != 0) { + throw_ioe(env, errno); + } + + (*env)->ReleaseStringUTFChars(env, j_path, path); +} + + /* * Throw a java.IO.IOException, generating the message from errno. */ diff --git a/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java b/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java index 972c9fc25c85a..06e02294f698a 100644 --- a/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java +++ b/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java @@ -28,7 +28,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileUtil; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.NativeCodeLoader; public class TestNativeIO { @@ -134,4 +138,34 @@ public void testFDDoesntLeak() throws IOException { } } + /** + * Test basic chmod operation + */ + @Test + public void testChmod() throws Exception { + try { + NativeIO.chmod("/this/file/doesnt/exist", 777); + fail("Chmod of non-existent file didn't fail"); + } catch (NativeIOException nioe) { + assertEquals(Errno.ENOENT, nioe.getErrno()); + } + + File toChmod = new File(TEST_DIR, "testChmod"); + assertTrue("Create test subject", + toChmod.exists() || toChmod.mkdir()); + NativeIO.chmod(toChmod.getAbsolutePath(), 0777); + assertPermissions(toChmod, 0777); + NativeIO.chmod(toChmod.getAbsolutePath(), 0000); + assertPermissions(toChmod, 0000); + NativeIO.chmod(toChmod.getAbsolutePath(), 0644); + assertPermissions(toChmod, 0644); + } + + private void assertPermissions(File f, int expected) throws IOException { + FileSystem localfs = FileSystem.getLocal(new Configuration()); + FsPermission perms = localfs.getFileStatus( + new Path(f.getAbsolutePath())).getPermission(); + assertEquals(expected, perms.toShort()); + } + }
cce874510408305fed6e01ab5b70ab753f9ac693
ReactiveX-RxJava
Beef up UnsubscribeTester--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java b/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java index 1d0eb6f145..7ab3a9e2c7 100644 --- a/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java +++ b/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java @@ -2,10 +2,13 @@ import org.junit.Test; import org.mockito.Mockito; +import rx.Observable; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions; import rx.testing.UnsubscribeTester; +import rx.util.functions.Action1; +import rx.util.functions.Func0; import rx.util.functions.Func1; import java.util.ArrayList; @@ -266,43 +269,38 @@ private void assertObservedUntilTwo(Observer<String> aObserver) } @Test - public void testUnsubscribeFromOnNext() { - RepeatSubject<Object> subject = RepeatSubject.create(); - - UnsubscribeTester test1 = UnsubscribeTester.createOnNext(subject); - UnsubscribeTester test2 = UnsubscribeTester.createOnNext(subject); - - subject.onNext("one"); - - test1.assertPassed(); - test2.assertPassed(); - } - - @Test - public void testUnsubscribeFromOnCompleted() { - RepeatSubject<Object> subject = RepeatSubject.create(); - - UnsubscribeTester test1 = UnsubscribeTester.createOnCompleted(subject); - UnsubscribeTester test2 = UnsubscribeTester.createOnCompleted(subject); - - subject.onCompleted(); - - test1.assertPassed(); - test2.assertPassed(); - } - - @Test - public void testUnsubscribeFromOnError() { - RepeatSubject<Object> subject = RepeatSubject.create(); - - UnsubscribeTester test1 = UnsubscribeTester.createOnError(subject); - UnsubscribeTester test2 = UnsubscribeTester.createOnError(subject); - - subject.onError(new Exception()); - - test1.assertPassed(); - test2.assertPassed(); + public void testUnsubscribe() + { + UnsubscribeTester.test(new Func0<RepeatSubject<Object>>() + { + @Override + public RepeatSubject<Object> call() + { + return RepeatSubject.create(); + } + }, new Action1<RepeatSubject<Object>>() + { + @Override + public void call(RepeatSubject<Object> repeatSubject) + { + repeatSubject.onCompleted(); + } + }, new Action1<RepeatSubject<Object>>() + { + @Override + public void call(RepeatSubject<Object> repeatSubject) + { + repeatSubject.onError(new Exception()); + } + }, new Action1<RepeatSubject<Object>>() + { + @Override + public void call(RepeatSubject<Object> repeatSubject) + { + repeatSubject.onNext("one"); + } + } + ); } - } } diff --git a/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java b/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java index e1988c9093..08607f2734 100644 --- a/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java +++ b/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java @@ -3,6 +3,8 @@ import rx.Observable; import rx.Observer; import rx.Subscription; +import rx.util.functions.Action1; +import rx.util.functions.Func0; import static org.junit.Assert.assertTrue; @@ -12,7 +14,44 @@ public class UnsubscribeTester public UnsubscribeTester() {} - public static <T> UnsubscribeTester createOnNext(Observable<T> observable) + /** + * Tests the unsubscription semantics of an observable. + * + * @param provider Function that when called provides an instance of the observable being tested + * @param generateOnCompleted Causes an observer generated by @param provider to generate an onCompleted event. Null to not test onCompleted. + * @param generateOnError Causes an observer generated by @param provider to generate an onError event. Null to not test onError. + * @param generateOnNext Causes an observer generated by @param provider to generate an onNext event. Null to not test onNext. + * @param <T> The type of object passed by the Observable + */ + public static <T, O extends Observable<T>> void test(Func0<O> provider, Action1<? super O> generateOnCompleted, Action1<? super O> generateOnError, Action1<? super O> generateOnNext) + { + if (generateOnCompleted != null) { + O observable = provider.call(); + UnsubscribeTester tester1 = createOnCompleted(observable); + UnsubscribeTester tester2 = createOnCompleted(observable); + generateOnCompleted.call(observable); + tester1.assertPassed(); + tester2.assertPassed(); + } + if (generateOnError != null) { + O observable = provider.call(); + UnsubscribeTester tester1 = createOnError(observable); + UnsubscribeTester tester2 = createOnError(observable); + generateOnError.call(observable); + tester1.assertPassed(); + tester2.assertPassed(); + } + if (generateOnNext != null) { + O observable = provider.call(); + UnsubscribeTester tester1 = createOnNext(observable); + UnsubscribeTester tester2 = createOnNext(observable); + generateOnNext.call(observable); + tester1.assertPassed(); + tester2.assertPassed(); + } + } + + private static <T> UnsubscribeTester createOnCompleted(Observable<T> observable) { final UnsubscribeTester test = new UnsubscribeTester(); test.setSubscription(observable.subscribe(new Observer<T>() @@ -20,6 +59,7 @@ public static <T> UnsubscribeTester createOnNext(Observable<T> observable) @Override public void onCompleted() { + test.doUnsubscribe(); } @Override @@ -30,13 +70,12 @@ public void onError(Exception e) @Override public void onNext(T args) { - test.doUnsubscribe(); } })); return test; } - public static <T> UnsubscribeTester createOnCompleted(Observable<T> observable) + private static <T> UnsubscribeTester createOnError(Observable<T> observable) { final UnsubscribeTester test = new UnsubscribeTester(); test.setSubscription(observable.subscribe(new Observer<T>() @@ -44,12 +83,12 @@ public static <T> UnsubscribeTester createOnCompleted(Observable<T> observable) @Override public void onCompleted() { - test.doUnsubscribe(); } @Override public void onError(Exception e) { + test.doUnsubscribe(); } @Override @@ -60,7 +99,7 @@ public void onNext(T args) return test; } - public static <T> UnsubscribeTester createOnError(Observable<T> observable) + private static <T> UnsubscribeTester createOnNext(Observable<T> observable) { final UnsubscribeTester test = new UnsubscribeTester(); test.setSubscription(observable.subscribe(new Observer<T>() @@ -73,12 +112,12 @@ public void onCompleted() @Override public void onError(Exception e) { - test.doUnsubscribe(); } @Override public void onNext(T args) { + test.doUnsubscribe(); } })); return test; @@ -96,7 +135,7 @@ private void doUnsubscribe() subscription.unsubscribe(); } - public void assertPassed() + private void assertPassed() { assertTrue("expected notification was received", subscription == null); }
86f43189eb607c39694441af9799f93f3bf5fc4f
camel
CAMEL-2180: Do not use copy of exchange when- processing in doCatch.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@881175 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java index 8cfdae8c3dc9f..594eba6c227a6 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java @@ -72,7 +72,7 @@ public void process(Exchange exchange) throws Exception { exchange.setException(e); } - // handle any exception occured during the try processor + // handle any exception occurred during the try processor try { if (e != null) { handleException(exchange, e); @@ -104,17 +104,14 @@ protected void handleException(Exchange exchange, Throwable e) throws Exception LOG.trace("This TryProcessor catches the exception: " + caught.getClass().getName() + " caused by: " + e.getMessage()); } - // TODO: No need to make a copy - // lets attach the exception to the exchange - Exchange localExchange = exchange.copy(); - - localExchange.setProperty(Exchange.EXCEPTION_CAUGHT, caught); // give the rest of the pipeline another chance - localExchange.setException(null); + exchange.setProperty(Exchange.EXCEPTION_CAUGHT, caught); + exchange.setException(null); // do not catch any exception here, let it propagate up - catchClause.process(localExchange); + catchClause.process(exchange); + // is the exception handled by the catch clause boolean handled = catchClause.handles(exchange); if (LOG.isDebugEnabled()) { @@ -124,13 +121,11 @@ protected void handleException(Exchange exchange, Throwable e) throws Exception if (!handled) { // put exception back as it was not handled - if (localExchange.getException() == null) { - localExchange.setException(localExchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)); + if (exchange.getException() == null) { + exchange.setException(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)); } } - // copy result back to the original exchange - ExchangeHelper.copyResults(exchange, localExchange); return; } }
1e31fa5f695e2f3f99fec2488197e99985f36376
camel
CAMEL-1461: JMSProducer only sets JMSReplyTo if- exchange is out capable. Fixed a NPE.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@757693 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java index 3ad34041fb779..8fe911ecd594b 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java @@ -88,8 +88,8 @@ public void onMessage(final Message message) { cause = exchange.getException(); sendReply = true; } else { - // only throw exception if endpoint is not configured to transfer exceptions - // back to caller + // only throw exception if endpoint is not configured to transfer exceptions back to caller + // do not send a reply but wrap and rethrow the exception rce = wrapRuntimeCamelException(exchange.getException()); } } else if (exchange.getFault().getBody() != null) { @@ -97,14 +97,14 @@ public void onMessage(final Message message) { body = exchange.getFault(); sendReply = true; } - } else { + } else if (exchange.getOut(false) != null) { // process OK so get the reply body = exchange.getOut(false); sendReply = true; } // send the reply if we got a response and the exchange is out capable - if (sendReply && !disableReplyTo && exchange.getPattern().isOutCapable()) { + if (rce == null && sendReply && !disableReplyTo && exchange.getPattern().isOutCapable()) { sendReply(replyDestination, message, exchange, body, cause); } diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java index 7736755481505..64dca42bf983f 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java @@ -47,6 +47,7 @@ import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.ExchangeHelper; +import org.apache.camel.util.ObjectHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -215,6 +216,7 @@ public Message makeJmsMessage(Exchange exchange, org.apache.camel.Message camelM // create jms message containg the caused exception answer = createJmsMessage(cause, session); } else { + ObjectHelper.notNull(camelMessage, "message body"); // create regular jms message using the camel message body answer = createJmsMessage(exchange, camelMessage.getBody(), camelMessage.getHeaders(), session, exchange.getContext()); appendJmsProperties(answer, exchange, camelMessage); @@ -249,7 +251,14 @@ public void appendJmsProperty(Message jmsMessage, Exchange exchange, org.apache. if (headerName.equals("JMSCorrelationID")) { jmsMessage.setJMSCorrelationID(ExchangeHelper.convertToType(exchange, String.class, headerValue)); } else if (headerName.equals("JMSReplyTo") && headerValue != null) { - jmsMessage.setJMSReplyTo(ExchangeHelper.convertToType(exchange, Destination.class, headerValue)); + if (exchange.getPattern().isOutCapable()) { + // only set the JMSReply if the Exchange supports Out + jmsMessage.setJMSReplyTo(ExchangeHelper.convertToType(exchange, Destination.class, headerValue)); + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("Exchange is not out capable, Ignoring JMSReplyTo: " + headerValue); + } + } } else if (headerName.equals("JMSType")) { jmsMessage.setJMSType(ExchangeHelper.convertToType(exchange, String.class, headerValue)); } else if (LOG.isDebugEnabled()) { diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteWithInOnlyTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteWithInOnlyTest.java new file mode 100644 index 0000000000000..2b7adad192f50 --- /dev/null +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteWithInOnlyTest.java @@ -0,0 +1,95 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.jms; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.ExchangePattern; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.JndiRegistry; +import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; + +/** + * Unit test inspired by user forum + * + * @version $Revision$ + */ +public class JmsRouteWithInOnlyTest extends ContextTestSupport { + + protected String componentName = "activemq"; + + public void testSendOrder() throws Exception { + MockEndpoint inbox = getMockEndpoint("mock:inbox"); + inbox.expectedBodiesReceived("Camel in Action"); + + MockEndpoint order = getMockEndpoint("mock:topic"); + order.expectedBodiesReceived("Camel in Action"); + + Object out = template.requestBody("activemq:queue:inbox", "Camel in Action"); + assertEquals("OK: Camel in Action", out); + + assertMockEndpointsSatisfied(); + + // assert MEP + assertEquals(ExchangePattern.InOut, inbox.getReceivedExchanges().get(0).getPattern()); + assertEquals(ExchangePattern.InOnly, order.getReceivedExchanges().get(0).getPattern()); + } + + @Override + protected JndiRegistry createRegistry() throws Exception { + JndiRegistry jndi = super.createRegistry(); + jndi.bind("orderService", new MyOrderServiceBean()); + return jndi; + } + + protected CamelContext createCamelContext() throws Exception { + CamelContext camelContext = super.createCamelContext(); + + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + camelContext.addComponent(componentName, jmsComponentClientAcknowledge(connectionFactory)); + + return camelContext; + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("activemq:queue:inbox") + .to("mock:inbox") + .inOnly("activemq:topic:order") + .beanRef("orderService", "handleOrder"); + + from("activemq:topic:order") + .to("mock:topic"); + } + }; + } + + public static class MyOrderServiceBean { + + public String handleOrder(String body) { + return "OK: " + body; + } + + } +}
f0bae099e625f74dac8cb391811188fadffb07bf
drools
JBRULES-2375: fixing deadlock on queued actions--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@33500 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
c
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java index b28c673ce7f..0795aa1188c 100644 --- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java @@ -31,6 +31,7 @@ import java.util.Queue; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @@ -174,7 +175,7 @@ public abstract class AbstractWorkingMemory protected Queue<WorkingMemoryAction> actionQueue; - protected volatile boolean evaluatingActionQueue; + protected AtomicBoolean evaluatingActionQueue; protected ReentrantLock lock; @@ -353,7 +354,8 @@ public AbstractWorkingMemory(final int id, this.initialFactHandle = initialFactHandle; } - this.actionQueue = new LinkedList<WorkingMemoryAction>(); + this.actionQueue = new ConcurrentLinkedQueue<WorkingMemoryAction>(); + this.evaluatingActionQueue = new AtomicBoolean( false ); this.addRemovePropertyChangeListenerArgs = new Object[]{this}; this.workingMemoryEventSupport = workingMemoryEventSupport; @@ -1459,9 +1461,8 @@ public void update(org.drools.FactHandle factHandle, public void executeQueuedActions() { try { startOperation(); - synchronized ( this.actionQueue ) { - if ( !this.actionQueue.isEmpty() && !evaluatingActionQueue ) { - evaluatingActionQueue = true; + if( evaluatingActionQueue.compareAndSet( false, true ) ) { + if ( !this.actionQueue.isEmpty() ) { WorkingMemoryAction action = null; while ( (action = actionQueue.poll()) != null ) { @@ -1472,10 +1473,10 @@ public void executeQueuedActions() { e ); } } - evaluatingActionQueue = false; } } } finally { + evaluatingActionQueue.compareAndSet( true, false ); endOperation(); } } @@ -1485,14 +1486,12 @@ public Queue<WorkingMemoryAction> getActionQueue() { } public void queueWorkingMemoryAction(final WorkingMemoryAction action) { - synchronized ( this.actionQueue ) { - try { - startOperation(); - this.actionQueue.add( action ); - this.agenda.notifyHalt(); - } finally { - endOperation(); - } + try { + startOperation(); + this.actionQueue.add( action ); + this.agenda.notifyHalt(); + } finally { + endOperation(); } } diff --git a/drools-core/src/main/java/org/drools/process/instance/event/DefaultSignalManager.java b/drools-core/src/main/java/org/drools/process/instance/event/DefaultSignalManager.java index 6af11ad39d2..c3371f6d039 100644 --- a/drools-core/src/main/java/org/drools/process/instance/event/DefaultSignalManager.java +++ b/drools-core/src/main/java/org/drools/process/instance/event/DefaultSignalManager.java @@ -52,7 +52,6 @@ public void removeEventListener(String type, EventListener eventListener) { public void signalEvent(String type, Object event) { ((InternalWorkingMemory) workingMemory).queueWorkingMemoryAction(new SignalAction(type, event)); - workingMemory.fireAllRules(); } public void internalSignalEvent(String type, Object event) { diff --git a/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java b/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java index 6fa79a49202..f48a5080b95 100644 --- a/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java +++ b/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java @@ -78,6 +78,7 @@ public void testRuleFlowGroup() { public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) { + System.out.println( knowledgeHelper.getRule() ); list.add( knowledgeHelper.getRule() ); }
9b945a0d6290280b0ce7e4535fb0f305144cc5b3
Vala
gnutls: fix a couple cnames, and change a char* to a string
c
https://github.com/GNOME/vala/
diff --git a/vapi/gnutls.vapi b/vapi/gnutls.vapi index bd302fdf16..a0bcf88358 100644 --- a/vapi/gnutls.vapi +++ b/vapi/gnutls.vapi @@ -563,7 +563,7 @@ namespace GnuTLS [CCode (cname = "gnutls_priority_set")] public int set_priority (Priority priority); [CCode (cname = "gnutls_priority_set_direct")] - public int set_priority_from_string (string priority, out char* err_pos = null); + public int set_priority_from_string (string priority, out unowned string err_pos = null); [CCode (cname = "gnutls_set_default_priority")] public int set_default_priority (); [CCode (cname = "gnutls_set_default_export_priority")] @@ -1888,7 +1888,9 @@ namespace GnuTLS APPLICATION_ERROR_MAX, // -65000 APPLICATION_ERROR_MIN; // -65500 + [CCode (cname = "gnutls_error_is_fatal")] public bool is_fatal (); + [CCode (cname = "gnutls_error_to_alert")] public AlertDescription to_alert (out AlertLevel level); [CCode (cname = "gnutls_perror")] public void print ();
170647869b279e735cefa4541d45510071989ac4
Delta Spike
DELTASPIKE-401 change GlobalAlternativeTest to work w Weld and OWB
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java index 60ca097f9..044484e4a 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java @@ -68,13 +68,31 @@ public class GlobalAlternativeTest @Deployment public static WebArchive deploy() { - Asset beansXml = new StringAsset( - "<beans><alternatives>" + - "<class>" + BaseInterface1AlternativeImplementation.class.getName() + "</class>" + - "<class>" + SubBaseBean2.class.getName() + "</class>" + - "<class>" + AlternativeBaseBeanB.class.getName() + "</class>" + - "</alternatives></beans>" - ); + + Asset beansXml = EmptyAsset.INSTANCE; + + try + { + // if this doesn't throw a ClassNotFoundException, then we have OpenWebBeans on the ClassPath. + Class.forName("org.apache.webbeans.spi.ContainerLifecycle"); + + // Older OWB versions had an error with @Alternatives pickup from AnnotatedType. + // But as OWB has global-alternatives behaviour by default, we can simply add them + // via beans.xml. From OWB-1.2.1 on we would not need this anymore, but it's still needed + // for 1.0.x, 1.1.x and 1.2.0 series + beansXml = new StringAsset( + "<beans><alternatives>" + + "<class>" + BaseInterface1AlternativeImplementation.class.getName() + "</class>" + + "<class>" + SubBaseBean2.class.getName() + "</class>" + + "<class>" + AlternativeBaseBeanB.class.getName() + "</class>" + + "</alternatives></beans>" + ); + } + catch (ClassNotFoundException cnfe) + { + // all fine, no OWB here -> Weld handling + } + JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "excludeIntegrationTest.jar") .addPackage(GlobalAlternativeTest.class.getPackage())
da1f992b70bd0ae022625624c9c54b57721f4633
hector-client$hector
SlicePredicate: Added support for 'default' ranges When using SlicePredicate for range queries, Hector expects both start and finish values to be set. This is not the best behavior. For example, Cassandra allows to query for the 'first N columns' simply by setting start and finish values to empty string and setting count to N. Although this query can be performed with String/StringSerializer, with UUID/UUIDSerializer it can't be done. To get 'first N columns' of type UUID, one has to generate min/max UUID's and use these as range values. Cherrypicked from http://github.com/abelaska/hector/commit/48186610cf9275bd4fbd0b14271f94437ce838d4 Author: tyruk Note: the actual functionality of default ranges was already enabled, but this commit makes it prettier code-wise
p
https://github.com/hector-client/hector
diff --git a/src/main/java/me/prettyprint/cassandra/model/HSlicePredicate.java b/src/main/java/me/prettyprint/cassandra/model/HSlicePredicate.java index 60bb37931..1c77a08f8 100644 --- a/src/main/java/me/prettyprint/cassandra/model/HSlicePredicate.java +++ b/src/main/java/me/prettyprint/cassandra/model/HSlicePredicate.java @@ -8,6 +8,7 @@ import me.prettyprint.cassandra.utils.Assert; import me.prettyprint.hector.api.Serializer; +import me.prettyprint.hector.api.exceptions.HectorException; import org.apache.cassandra.thrift.SlicePredicate; import org.apache.cassandra.thrift.SliceRange; @@ -20,8 +21,6 @@ */ public final class HSlicePredicate<N> { - /** Use column names or start/finish? */ - protected boolean useColumnNames; protected Collection<N> columnNames; protected N start; protected N finish; @@ -30,6 +29,8 @@ public final class HSlicePredicate<N> { /** Is count already set? */ private boolean countSet = false; protected final Serializer<N> columnNameSerializer; + protected enum PredicateType {Unknown, ColumnNames, Range}; + protected PredicateType predicateType = PredicateType.Unknown; public HSlicePredicate(Serializer<N> columnNameSerializer) { Assert.notNull(columnNameSerializer, "columnNameSerializer can't be null"); @@ -44,7 +45,7 @@ public HSlicePredicate(Serializer<N> columnNameSerializer) { */ public HSlicePredicate<N> setColumnNames(N... columnNames) { this.columnNames = Arrays.asList(columnNames); - useColumnNames = true; + predicateType = PredicateType.ColumnNames; return this; } @@ -55,7 +56,7 @@ public HSlicePredicate<N> setColumnNames(N... columnNames) { */ public HSlicePredicate<N> setKeysOnlyPredicate() { this.columnNames = new ArrayList<N>(); - useColumnNames = true; + predicateType = PredicateType.ColumnNames; return this; } @@ -77,7 +78,7 @@ public HSlicePredicate<N> setRange(N start, N finish, boolean reversed, int coun this.reversed = reversed; this.count = count; countSet = true; - useColumnNames = false; + predicateType = PredicateType.Range; return this; } @@ -91,15 +92,23 @@ public Collection<N> getColumnNames() { */ public SlicePredicate toThrift() { SlicePredicate pred = new SlicePredicate(); - if (useColumnNames) { - if (columnNames == null) { + + switch (predicateType) { + case ColumnNames: + if (columnNames == null || columnNames.isEmpty()) { return null; } pred.setColumn_names(toThriftColumnNames(columnNames)); - } else { + break; + case Range: Assert.isTrue(countSet, "Count was not set, neither were column-names set, can't execute"); - pred.setSlice_range(new SliceRange(findBytes(start),findBytes(finish), - reversed, count)); + SliceRange range = new SliceRange(findBytes(start), findBytes(finish), reversed, count); + pred.setSlice_range(range); + break; + case Unknown: + default: + throw new HectorException( + "Neither column names nor range were set, this is an invalid slice predicate"); } return pred; } @@ -125,6 +134,7 @@ private List<byte[]> toThriftColumnNames(Collection<N> clms) { @Override public String toString() { return "HSlicePredicate(" - + (useColumnNames ? columnNames : "cStart:" + start + ",cFinish:" + finish) + ")"; + + (predicateType == PredicateType.ColumnNames ? columnNames : + "cStart:" + start + ",cFinish:" + finish) + ")"; } }
fe164471124f357d20acb18f6a6059eb5f91be07
spring-framework
more work on enabling non-namespace extensions of- xml parsing--
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java index b0719aa07db9..eb86869264ee 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java @@ -1417,4 +1417,14 @@ public String getNamespaceURI(Node node) { public boolean nodeNameEquals(Node node, String desiredName) { return DomUtils.nodeNameEquals(node, desiredName); } + + /** + * Gets the local name for the supplied {@link Node}. The default implementation calls {@link Node#getLocalName}. + * Subclasses may override the default implementation to provide a different mechanism for getting the local name. + * @param node the <code>Node</code> + * @return the local name of the supplied <code>Node</code>. + */ + public String getLocalName(Node node) { + return node.getLocalName(); + } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java index ae1e28e3d176..ee996402b83a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java @@ -77,10 +77,11 @@ public final BeanDefinition parse(Element element, ParserContext parserContext) * the local name of the supplied {@link Element}. */ private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) { - BeanDefinitionParser parser = this.parsers.get(element.getLocalName()); + String localName = parserContext.getDelegate().getLocalName(element); + BeanDefinitionParser parser = this.parsers.get(localName); if (parser == null) { parserContext.getReaderContext().fatal( - "Cannot locate BeanDefinitionParser for element [" + element.getLocalName() + "]", element); + "Cannot locate BeanDefinitionParser for element [" + localName + "]", element); } return parser; } @@ -102,11 +103,12 @@ public final BeanDefinitionHolder decorate( */ private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) { BeanDefinitionDecorator decorator = null; + String localName = parserContext.getDelegate().getLocalName(node); if (node instanceof Element) { - decorator = this.decorators.get(node.getLocalName()); + decorator = this.decorators.get(localName); } else if (node instanceof Attr) { - decorator = this.attributeDecorators.get(node.getLocalName()); + decorator = this.attributeDecorators.get(localName); } else { parserContext.getReaderContext().fatal( @@ -114,7 +116,7 @@ else if (node instanceof Attr) { } if (decorator == null) { parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionDecorator for " + - (node instanceof Element ? "element" : "attribute") + " [" + node.getLocalName() + "]", node); + (node instanceof Element ? "element" : "attribute") + " [" + localName + "]", node); } return decorator; }
6ceadd85dc54ab7e5a58cf51d50289055f3d6bb9
hbase
HBASE-3387 Pair does not deep check arrays for- equality--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1053484 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index afe42f6b85f0..fa3639e56a35 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -40,6 +40,8 @@ Release 0.91.0 - Unreleased function HBASE-3260 Coprocessors: Add explicit lifecycle management HBASE-3377 Upgrade Jetty to 6.1.26 + HBASE-3387 Pair does not deep check arrays for equality + (Jesse Yates via Stack) NEW FEATURES diff --git a/src/main/java/org/apache/hadoop/hbase/util/Pair.java b/src/main/java/org/apache/hadoop/hbase/util/Pair.java index ff296b6bda2b..a8779ce56bff 100644 --- a/src/main/java/org/apache/hadoop/hbase/util/Pair.java +++ b/src/main/java/org/apache/hadoop/hbase/util/Pair.java @@ -21,6 +21,7 @@ package org.apache.hadoop.hbase.util; import java.io.Serializable; +import java.lang.reflect.Array; /** * A generic class for pairs. @@ -87,9 +88,35 @@ public T2 getSecond() return second; } - private static boolean equals(Object x, Object y) - { - return (x == null && y == null) || (x != null && x.equals(y)); + private static boolean equals(Object x, Object y) { + if (x == null && y == null) + return true; + + if (x != null && y != null) { + if (x.getClass().equals(y.getClass())) { + if (x.getClass().isArray() && y.getClass().isArray()) { + + int len = Array.getLength(x) == Array.getLength(y) ? Array + .getLength(x) : -1; + if (len < 0) + return false; + + for (int i = 0; i < len; i++) { + + Object xi = Array.get(x, i); + Object yi = Array.get(y, i); + + if (!xi.equals(yi)) + return false; + } + return true; + } else { + return x.equals(y); + } + } + } + return false; + } @Override diff --git a/src/test/java/org/apache/hadoop/hbase/util/TestPairEquals.java b/src/test/java/org/apache/hadoop/hbase/util/TestPairEquals.java new file mode 100644 index 000000000000..d546cf589939 --- /dev/null +++ b/src/test/java/org/apache/hadoop/hbase/util/TestPairEquals.java @@ -0,0 +1,79 @@ +/** + * Copyright 2010 The Apache Software Foundation + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.hbase.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Testing Testing {@link Pair#equals(Object)} for deep checking of arrays + */ +public class TestPairEquals { + + /** + * Testing {@link Pair#equals(Object)} for deep checking of arrays + */ + @Test + public void testEquals() { + Pair<String, String> p1 = new Pair<String, String>("Hello", "World"); + Pair<String, String> p1a = new Pair<String, String>("Hello", "World"); + assertTrue(p1.equals(p1a)); + + Pair<String, byte[]> p2 = new Pair<String, byte[]>("Hello", new byte[] { 1, + 0, 5 }); + Pair<String, byte[]> p2a = new Pair<String, byte[]>("Hello", new byte[] { + 1, 0, 5 }); + // Previously this test would fail as they are two different pointers to + // arrays that inherently the same. + assertTrue(p2.equals(p2a)); + + Pair<char[], String> p3 = new Pair<char[], String>(new char[] { 'h', 'e' }, + "world"); + assertTrue(p3.equals(p3)); + + // These kinds of tests will still fail as they have fundamentally different + // elements + Pair<Character[], String> p4 = new Pair<Character[], String>( + new Character[] { new Character('h'), new Character('e') }, "world"); + // checking for autoboxing non-equality to the original class + assertFalse(p3.equals(p4)); + + // still fail for a different autoboxing situation (just to prove that it + // is not just chars) + Pair<String, Integer[]> p5 = new Pair<String, Integer[]>("hello", + new Integer[] { new Integer(1), new Integer(982) }); + Pair<String, int[]> p5a = new Pair<String, int[]>("hello", new int[] { 1, + 982 }); + assertFalse(p5.equals(p5a)); + + // will still fail for that different things + Pair<String, byte[]> p6 = new Pair<String, byte[]>("Hello", new byte[] { 1, + 0, 4 }); + assertFalse(p2.equals(p6)); + + // will still fail for the other predicate being different + Pair<String, byte[]> p7 = new Pair<String, byte[]>("World", new byte[] { 1, + 0, 5 }); + assertFalse(p2.equals(p7)); + } +}
6bc9677bbe919cd5bcadd8af2f5b0c838757a4ce
drools
[DROOLS-293] fix ObjectTypeNode id creation and- comparison--
c
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java b/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java index 8a8f37d9cea..9756ad1485a 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java @@ -133,7 +133,7 @@ public ObjectTypeNode(final int id, source, context.getRuleBase().getConfiguration().getAlphaNodeHashingThreshold() ); this.objectType = objectType; - idGenerator = new IdGenerator(objectType); + idGenerator = new IdGenerator(id); setObjectMemoryEnabled( context.isObjectTypeNodeMemoryEnabled() ); @@ -145,15 +145,15 @@ public ObjectTypeNode(final int id, } private static class IdGenerator { - private final Class<?> otnClass; + private final int otnId; private int otnIdCounter; - private IdGenerator(ObjectType objectType) { - otnClass = objectType instanceof ClassObjectType ? ((ClassObjectType)objectType).getClassType() : Object.class; + private IdGenerator(int otnId) { + this.otnId = otnId; } private Id nextId() { - return new Id(otnClass, otnIdCounter++); + return new Id(otnId, otnIdCounter++); } private void reset() { @@ -161,21 +161,21 @@ private void reset() { } } - public static Id DEFAULT_ID = new Id(Object.class, 0); + public static Id DEFAULT_ID = new Id(-1, 0); public static class Id { - private final Class<?> clazz; + private final int otnId; private final int id; - public Id(Class<?> clazz, int id) { - this.clazz = clazz; + public Id(int otnId, int id) { + this.otnId = otnId; this.id = id; } @Override public String toString() { - return "ObjectTypeNode.Id[" + clazz.getName() + "#" + id + "]"; + return "ObjectTypeNode.Id[" + otnId + "#" + id + "]"; } @Override @@ -184,22 +184,16 @@ public boolean equals(Object o) { if (o == null || !(o instanceof Id)) return false; Id otherId = (Id) o; - return id == otherId.id && clazz == otherId.clazz; + return id == otherId.id && otnId == otherId.otnId; } @Override public int hashCode() { - int result = clazz.hashCode(); - result = 31 * result + id; - return result; + return 31 * otnId + 37 * id; } public boolean before(Id otherId) { - return otherId != null && clazz == otherId.clazz && this.id < otherId.id; - } - - public Class<?> getTypeNodeClass() { - return clazz; + return otherId != null && ( otnId < otherId.otnId || ( otnId == otherId.otnId && id < otherId.id ) ); } public int getId() { @@ -217,12 +211,12 @@ public void readExternal(ObjectInput in) throws IOException, if ( objectType instanceof ClassObjectType ) { objectType = ((ReteooRuleBase) ((DroolsObjectInputStream) in).getRuleBase()).getClassFieldAccessorCache().getClassObjectType( (ClassObjectType) objectType ); } - idGenerator = new IdGenerator(objectType); objectMemoryEnabled = in.readBoolean(); expirationOffset = in.readLong(); queryNode = in.readBoolean(); dirty = true; + idGenerator = new IdGenerator(id); } public void writeExternal(ObjectOutput out) throws IOException {
ad97977bc5310342aead2139c86637098d1e2e94
tapiji
Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*.
p
https://github.com/tapiji/tapiji
diff --git a/at.ac.tuwien.inso.eclipse.rbe/.project b/at.ac.tuwien.inso.eclipse.rbe/.project index ee34232d..c504135a 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/.project +++ b/at.ac.tuwien.inso.eclipse.rbe/.project @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> - <name>at.ac.tuwien.inso.eclipse.rbe</name> + <name>org.eclipselabs.tapiji.translator.rbe</name> <comment></comment> <projects> </projects> diff --git a/at.ac.tuwien.inso.eclipse.rbe/META-INF/MANIFEST.MF b/at.ac.tuwien.inso.eclipse.rbe/META-INF/MANIFEST.MF index 206b4a36..e462b490 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/META-INF/MANIFEST.MF +++ b/at.ac.tuwien.inso.eclipse.rbe/META-INF/MANIFEST.MF @@ -1,11 +1,11 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: ResourceBundleEditorAPI -Bundle-SymbolicName: at.ac.tuwien.inso.eclipse.rbe +Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rbe Bundle-Version: 0.0.1.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Export-Package: at.ac.tuwien.inso.eclipse.rbe.model.analyze, - at.ac.tuwien.inso.eclipse.rbe.model.bundle, - at.ac.tuwien.inso.eclipse.rbe.model.tree, - at.ac.tuwien.inso.eclipse.rbe.model.tree.updater, - at.ac.tuwien.inso.eclipse.rbe.ui.wizards +Export-Package: org.eclipselabs.tapiji.translator.rbe.model.analyze, + org.eclipselabs.tapiji.translator.rbe.model.bundle, + org.eclipselabs.tapiji.translator.rbe.model.tree, + org.eclipselabs.tapiji.translator.rbe.model.tree.updater, + org.eclipselabs.tapiji.translator.rbe.ui.wizards diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/updater/IKeyTreeUpdater.java b/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/updater/IKeyTreeUpdater.java deleted file mode 100644 index b9c520ca..00000000 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/updater/IKeyTreeUpdater.java +++ /dev/null @@ -1,11 +0,0 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.tree.updater; - -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; - -public interface IKeyTreeUpdater { - - void addKey(IKeyTree keyTree, String key); - - void removeKey(IKeyTree keyTree, String key); - -} diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java similarity index 59% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java index 2a864e24..f4a7c1fc 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.analyze; +package org.eclipselabs.tapiji.translator.rbe.model.analyze; public interface ILevenshteinDistanceAnalyzer { diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundle.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundle.java similarity index 80% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundle.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundle.java index 5ae271cb..500fbdf5 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundle.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundle.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.bundle; +package org.eclipselabs.tapiji.translator.rbe.model.bundle; import java.util.Iterator; import java.util.Locale; diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundleEntry.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundleEntry.java similarity index 74% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundleEntry.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundleEntry.java index 6d795bcf..598d93d5 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundleEntry.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundleEntry.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.bundle; +package org.eclipselabs.tapiji.translator.rbe.model.bundle; import java.util.Locale; diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundleGroup.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundleGroup.java similarity index 88% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundleGroup.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundleGroup.java index 845944d0..88bf14f1 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/bundle/IBundleGroup.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/bundle/IBundleGroup.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.bundle; +package org.eclipselabs.tapiji.translator.rbe.model.bundle; import java.util.Collection; import java.util.Iterator; diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IKeyTree.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IKeyTree.java similarity index 58% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IKeyTree.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IKeyTree.java index 7e7d6fa1..40748966 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IKeyTree.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IKeyTree.java @@ -1,10 +1,11 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.tree; +package org.eclipselabs.tapiji.translator.rbe.model.tree; import java.util.Map; import java.util.Set; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.updater.IKeyTreeUpdater; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.tree.updater.IKeyTreeUpdater; + public interface IKeyTree { diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IKeyTreeItem.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IKeyTreeItem.java similarity index 79% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IKeyTreeItem.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IKeyTreeItem.java index ee3edb15..0f396c14 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IKeyTreeItem.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IKeyTreeItem.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.tree; +package org.eclipselabs.tapiji.translator.rbe.model.tree; import java.util.Collection; import java.util.Set; diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IValuedKeyTreeItem.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IValuedKeyTreeItem.java similarity index 84% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IValuedKeyTreeItem.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IValuedKeyTreeItem.java index ee19cab0..f56670b5 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/model/tree/IValuedKeyTreeItem.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/IValuedKeyTreeItem.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.model.tree; +package org.eclipselabs.tapiji.translator.rbe.model.tree; import java.util.Collection; import java.util.Locale; diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/updater/IKeyTreeUpdater.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/updater/IKeyTreeUpdater.java new file mode 100644 index 00000000..f6efa2c6 --- /dev/null +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/model/tree/updater/IKeyTreeUpdater.java @@ -0,0 +1,11 @@ +package org.eclipselabs.tapiji.translator.rbe.model.tree.updater; + +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; + +public interface IKeyTreeUpdater { + + void addKey(IKeyTree keyTree, String key); + + void removeKey(IKeyTree keyTree, String key); + +} diff --git a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/ui/wizards/IResourceBundleWizard.java b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java similarity index 64% rename from at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/ui/wizards/IResourceBundleWizard.java rename to at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java index bd1ee446..afb12509 100644 --- a/at.ac.tuwien.inso.eclipse.rbe/src/at/ac/tuwien/inso/eclipse/rbe/ui/wizards/IResourceBundleWizard.java +++ b/at.ac.tuwien.inso.eclipse.rbe/src/org/eclipselabs/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java @@ -1,4 +1,4 @@ -package at.ac.tuwien.inso.eclipse.rbe.ui.wizards; +package org.eclipselabs.tapiji.translator.rbe.ui.wizards; public interface IResourceBundleWizard {
95c114f2692ca7fdc187d2f167b76f90975e1ead
Mylyn Reviews
Fixed bundle names and license information
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF b/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF index 2782c9a4..b93a9fc9 100644 --- a/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF +++ b/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 -Bundle-Name: Mylyn Reviews Core +Bundle-Name: Mylyn Reviews Core (Incubation) Bundle-SymbolicName: org.eclipse.mylyn.reviews.core;singleton:=true Bundle-Version: 0.0.1 Bundle-Activator: org.eclipse.mylyn.reviews.core.Activator diff --git a/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF b/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF index e02bd3c9..9309a535 100644 --- a/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF +++ b/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 -Bundle-Name: Mylyn Reviews UI +Bundle-Name: Mylyn Reviews UI (Incubation) Bundle-SymbolicName: org.eclipse.mylyn.reviews.ui;singleton:=true Bundle-Version: 0.0.1 Bundle-Activator: org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin diff --git a/org.eclipse.mylyn.reviews/feature.xml b/org.eclipse.mylyn.reviews/feature.xml index d389273f..1bcecf9a 100644 --- a/org.eclipse.mylyn.reviews/feature.xml +++ b/org.eclipse.mylyn.reviews/feature.xml @@ -1,20 +1,70 @@ <?xml version="1.0" encoding="UTF-8"?> <feature id="org.eclipse.mylyn.reviews" - label="Mylyn Reviews" + label="Mylyn Reviews (Incubation)" version="0.0.1" provider-name="Mylyn Reviews Team"> - <description url="http://www.example.com/description"> - [Enter Feature Description here.] + <description url="http://www.eclipse.org/reviews"> + Provides Review functionality for Mylyn </description> - <copyright url="http://www.example.com/copyright"> - [Enter Copyright Description here.] + <copyright> + Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology and others. All rights reserved. </copyright> - <license url="http://www.example.com/license"> - [Enter License Description here.] + <license url="http://www.eclipse.org/legal/epl/notice.php"> + Eclipse Foundation Software User Agreement + +April 14, 2010 +Usage Of Content + +THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY &quot;CONTENT&quot;). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT. +Applicable Licenses + +Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, &quot;Program&quot; will mean the Content. + +Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code repository (&quot;Repository&quot;) in software modules (&quot;Modules&quot;) and made available as downloadable archives (&quot;Downloads&quot;). + + * Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins (&quot;Plug-ins&quot;), plug-in fragments (&quot;Fragments&quot;), and features (&quot;Features&quot;). + * Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named &quot;plugins&quot;. + * A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named &quot;features&quot;. Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of the Plug-ins and/or Fragments associated with that Feature. + * Features may also include other Features (&quot;Included Features&quot;). Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of Included Features. + +The terms and conditions governing Plug-ins and Fragments should be contained in files named &quot;about.html&quot; (&quot;Abouts&quot;). The terms and conditions governing Features and Included Features should be contained in files named &quot;license.html&quot; (&quot;Feature Licenses&quot;). Abouts and Feature Licenses may be located in any directory of a Download or Module including, but not limited to the following locations: + + * The top-level (root) directory + * Plug-in and Fragment directories + * Inside Plug-ins and Fragments packaged as JARs + * Sub-directories of the directory named &quot;src&quot; of certain Plug-ins + * Feature directories + +Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license (&quot;Feature Update License&quot;) during the installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or inform you where you can locate them. Feature Update Licenses may be found in the &quot;license&quot; property of files named &quot;feature.properties&quot; found within a Feature. Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in that directory. + +THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO): + + * Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html) + * Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE) + * Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0) + * Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html) + * Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html) + +IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please contact the Eclipse Foundation to determine what terms and conditions govern that particular Content. +Use of Provisioning Technology + +The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse Update Manager (&quot;Provisioning Technology&quot;) for the purpose of allowing users to install software, documentation, information and/or other materials (collectively &quot;Installable Software&quot;). This capability is provided with the intent of allowing such users to install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html (&quot;Specification&quot;). + +You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following: + + 1. A series of actions may occur (&quot;Provisioning Process&quot;) in which a user may execute the Provisioning Technology on a machine (&quot;Target Machine&quot;) with the intent of installing, extending or updating the functionality of an Eclipse-based product. + 2. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be accessed and copied to the Target Machine. + 3. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable Software (&quot;Installable Software Agreement&quot;) and such Installable Software Agreement shall be accessed from the Target Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software. + +Cryptography + +Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check the country&apos;s laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. + +Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both. </license> <plugin
afaa34702725d63d7a6cd89c0e5b2eb35a5be19e
Vala
Make all Literal constructors accept null SourceReferences
a
https://github.com/GNOME/vala/
diff --git a/vala/valabooleanliteral.vala b/vala/valabooleanliteral.vala index db05f0afde..bf0842fba0 100644 --- a/vala/valabooleanliteral.vala +++ b/vala/valabooleanliteral.vala @@ -38,7 +38,7 @@ public class Vala.BooleanLiteral : Literal { * @param source reference to source code * @return newly created boolean literal */ - public BooleanLiteral (bool b, SourceReference source) { + public BooleanLiteral (bool b, SourceReference? source = null) { value = b; source_reference = source; } diff --git a/vala/valacharacterliteral.vala b/vala/valacharacterliteral.vala index 9ab7a8c03a..3d858b4ecc 100644 --- a/vala/valacharacterliteral.vala +++ b/vala/valacharacterliteral.vala @@ -52,7 +52,7 @@ public class Vala.CharacterLiteral : Literal { * @param source reference to source code * @return newly created character literal */ - public CharacterLiteral (string c, SourceReference source) { + public CharacterLiteral (string c, SourceReference? source = null) { value = c; source_reference = source; diff --git a/vala/valarealliteral.vala b/vala/valarealliteral.vala index cbfca7c05d..6f327d461d 100644 --- a/vala/valarealliteral.vala +++ b/vala/valarealliteral.vala @@ -38,7 +38,7 @@ public class Vala.RealLiteral : Literal { * @param source reference to source code * @return newly created real literal */ - public RealLiteral (string r, SourceReference source) { + public RealLiteral (string r, SourceReference? source = null) { value = r; source_reference = source; }
7c7e4a2e255eff4ee29992330b352a7665050834
camel
CAMEL-5906: Added new camel-servletlistener- component for bootstrapping Camel in web app without using spring etc. Work- in progress.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1428278 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextLifecycle.java b/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextLifecycle.java index 733c7b07d69fb..762c8f22c04a1 100644 --- a/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextLifecycle.java +++ b/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextLifecycle.java @@ -24,12 +24,40 @@ */ public interface CamelContextLifecycle { + /** + * Callback before starting {@link ServletCamelContext}. + * + * @param camelContext the Camel context + * @param jndi the JNDI context. + * @throws Exception is thrown if any error. + */ void beforeStart(ServletCamelContext camelContext, JndiContext jndi) throws Exception; + /** + * Callback after {@link ServletCamelContext} has been started. + * + * @param camelContext the Camel context + * @param jndi the JNDI context. + * @throws Exception is thrown if any error. + */ void afterStart(ServletCamelContext camelContext, JndiContext jndi) throws Exception; + /** + * Callback before stopping {@link ServletCamelContext}. + * + * @param camelContext the Camel context + * @param jndi the JNDI context. + * @throws Exception is thrown if any error. + */ void beforeStop(ServletCamelContext camelContext, JndiContext jndi) throws Exception; + /** + * Callback after {@link ServletCamelContext} has been stopped. + * + * @param camelContext the Camel context + * @param jndi the JNDI context. + * @throws Exception is thrown if any error. + */ void afterStop(ServletCamelContext camelContext, JndiContext jndi) throws Exception; } diff --git a/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextServletListener.java b/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextServletListener.java index 190662310c700..ab95c1e5f95bf 100644 --- a/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextServletListener.java +++ b/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/CamelContextServletListener.java @@ -60,7 +60,6 @@ public class CamelContextServletListener implements ServletContextListener { private boolean test; @Override - @SuppressWarnings("unchecked") public void contextInitialized(ServletContextEvent sce) { LOG.info("CamelContextServletListener initializing ..."); @@ -128,7 +127,7 @@ public void contextInitialized(ServletContextEvent sce) { } // any custom CamelContextLifecycle - String lifecycle = (String) map.remove(CamelContextLifecycle.class.getName()); + String lifecycle = (String) map.remove("CamelContextLifecycle"); if (lifecycle != null) { try { Class<CamelContextLifecycle> clazz = camelContext.getClassResolver().resolveMandatoryClass(lifecycle, CamelContextLifecycle.class); @@ -164,6 +163,55 @@ public void contextInitialized(ServletContextEvent sce) { LOG.info("CamelContextServletListener initialized"); } + @Override + public void contextDestroyed(ServletContextEvent sce) { + LOG.info("CamelContextServletListener destroying ..."); + if (camelContext != null) { + try { + if (camelContextLifecycle != null) { + camelContextLifecycle.beforeStop(camelContext, jndiContext); + } + camelContext.stop(); + if (camelContextLifecycle != null) { + camelContextLifecycle.afterStop(camelContext, jndiContext); + } + } catch (Exception e) { + LOG.warn("Error stopping CamelContext. This exception will be ignored.", e); + } + } + camelContext = null; + jndiContext = null; + instance = null; + LOG.info("CamelContextServletListener destroyed"); + } + + private Map<String, Object> extractInitParameters(ServletContextEvent sce) { + // configure CamelContext with the init parameter + Map<String, Object> map = new LinkedHashMap<String, Object>(); + Enumeration names = sce.getServletContext().getInitParameterNames(); + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + String value = sce.getServletContext().getInitParameter(name); + + if (ObjectHelper.isNotEmpty(value)) { + Object target = value; + if (value.startsWith("#")) { + // a reference lookup in jndi + value = value.substring(1); + target = lookupJndi(jndiContext, value); + } + map.put(name, target); + } + } + return map; + } + + /** + * Extract the routes from the parameters. + * + * @param map parameters + * @return a list of routes, which can be of different types. See source code for more details. + */ private List<Object> extractRoutes(Map<String, Object> map) { List<Object> answer = new ArrayList<Object>(); List<String> names = new ArrayList<String>(); @@ -237,27 +285,6 @@ private List<Object> extractRoutes(Map<String, Object> map) { return answer; } - private Map<String, Object> extractInitParameters(ServletContextEvent sce) { - // configure CamelContext with the init parameter - Map<String, Object> map = new LinkedHashMap<String, Object>(); - Enumeration names = sce.getServletContext().getInitParameterNames(); - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - String value = sce.getServletContext().getInitParameter(name); - - if (ObjectHelper.isNotEmpty(value)) { - Object target = value; - if (value.startsWith("#")) { - // a reference lookup in jndi - value = value.substring(1); - target = lookupJndi(jndiContext, value); - } - map.put(name, target); - } - } - return map; - } - private static Object lookupJndi(JndiContext jndiContext, String name) { try { return jndiContext.lookup(name); @@ -266,26 +293,4 @@ private static Object lookupJndi(JndiContext jndiContext, String name) { } } - @Override - public void contextDestroyed(ServletContextEvent sce) { - LOG.info("CamelContextServletListener destroying ..."); - if (camelContext != null) { - try { - if (camelContextLifecycle != null) { - camelContextLifecycle.beforeStop(camelContext, jndiContext); - } - camelContext.stop(); - if (camelContextLifecycle != null) { - camelContextLifecycle.afterStop(camelContext, jndiContext); - } - } catch (Exception e) { - LOG.warn("Error stopping CamelContext. This exception will be ignored.", e); - } - } - camelContext = null; - jndiContext = null; - instance = null; - LOG.info("CamelContextServletListener destroyed"); - } - } diff --git a/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/ServletCamelContext.java b/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/ServletCamelContext.java index ad7e95e1321a5..bb053086436f5 100644 --- a/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/ServletCamelContext.java +++ b/components/camel-servletlistener/src/main/java/org/apache/camel/component/servletlistener/ServletCamelContext.java @@ -26,10 +26,20 @@ */ public class ServletCamelContext extends DefaultCamelContext { + private final Context jndiContext; private final ServletContext servletContext; public ServletCamelContext(Context jndiContext, ServletContext servletContext) { super(jndiContext); + this.jndiContext = jndiContext; this.servletContext = servletContext; } + + public Context getJndiContext() { + return jndiContext; + } + + public ServletContext getServletContext() { + return servletContext; + } } diff --git a/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/HelloBean.java b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/HelloBean.java new file mode 100644 index 0000000000000..ef1ad32ce1780 --- /dev/null +++ b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/HelloBean.java @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.servletlistener; + +/** + * + */ +public class HelloBean { + + public String hello(String name) { + return "Hello " + name; + } +} diff --git a/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/LifecycleTest.java b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/LifecycleTest.java new file mode 100644 index 0000000000000..6d547bf9520da --- /dev/null +++ b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/LifecycleTest.java @@ -0,0 +1,51 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.servletlistener; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; + +/** + * + */ +public class LifecycleTest extends ServletCamelTestSupport { + + protected String getConfiguration() { + return "/myweb5.xml"; + } + + @Test + public void testCamelContext() throws Exception { + CamelContext context = getCamelContext(); + assertNotNull(context); + + assertEquals("MyCamel", context.getName()); + + ProducerTemplate template = context.createProducerTemplate(); + + MockEndpoint mock = context.getEndpoint("mock:foo", MockEndpoint.class); + mock.expectedBodiesReceived("Hello World"); + + template.sendBody("seda:foo", "World"); + + mock.assertIsSatisfied(); + template.stop(); + } + +} diff --git a/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/MyBeanRoute.java b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/MyBeanRoute.java new file mode 100644 index 0000000000000..2a91209a3602b --- /dev/null +++ b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/MyBeanRoute.java @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.servletlistener; + +import org.apache.camel.builder.RouteBuilder; + +/** + * + */ +public class MyBeanRoute extends RouteBuilder { + + @Override + public void configure() throws Exception { + from("seda:foo").routeId("foo") + .to("bean:myBean") + .to("mock:foo"); + } +} diff --git a/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/MyLifecycle.java b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/MyLifecycle.java new file mode 100644 index 0000000000000..386b5f1a6a118 --- /dev/null +++ b/components/camel-servletlistener/src/test/java/org/apache/camel/component/servletlistener/MyLifecycle.java @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.servletlistener; + +import org.apache.camel.util.jndi.JndiContext; + +/** + * + */ +// START SNIPPET: e1 +public class MyLifecycle extends CamelContextLifecycleSupport { + + @Override + public void beforeStart(ServletCamelContext camelContext, JndiContext jndi) throws Exception { + // enlist our bean(s) in the registry + jndi.bind("myBean", new HelloBean()); + } +} +// END SNIPPET: e1 diff --git a/components/camel-servletlistener/src/test/resources/myweb5.xml b/components/camel-servletlistener/src/test/resources/myweb5.xml new file mode 100644 index 0000000000000..004effb519af9 --- /dev/null +++ b/components/camel-servletlistener/src/test/resources/myweb5.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> + +<!DOCTYPE web-app + PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" + "http://java.sun.com/dtd/web-app_2_3.dtd"> + +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> +<!-- START SNIPPET: web --> +<web-app> + + <!-- the test parameter is only to be used for unit testing --> + <context-param> + <param-name>test</param-name> + <param-value>true</param-value> + </context-param> + + <!-- you can configure any of the properties on CamelContext, eg setName will be configured as below --> + <context-param> + <param-name>name</param-name> + <param-value>MyCamel</param-value> + </context-param> + + <!-- configure a route builder to use --> + <!-- Camel will pickup any parameter names that start with routeBuilder (case ignored) --> + <context-param> + <param-name>routeBuilder-MyRoute</param-name> + <param-value>org.apache.camel.component.servletlistener.MyBeanRoute</param-value> + </context-param> + <!-- configure our lifecycle class, which allows us to do custom logic before/after starting CamelContext --> + <context-param> + <param-name>CamelContextLifecycle</param-name> + <param-value>org.apache.camel.component.servletlistener.MyLifecycle</param-value> + </context-param> + + <listener> + <listener-class>org.apache.camel.component.servletlistener.CamelContextServletListener</listener-class> + </listener> + +</web-app> +<!-- END SNIPPET: web --> \ No newline at end of file
daab3db062b9b8cddbb653fedca91288cf5a0684
kotlin
Add WITH_RUNTIME and WITH_REFLECT directives to- box tests--Currently all tests in boxWithStdlib/ run with both runtime and reflection-included; eventually they'll be merged into box/ using these directives-
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt b/compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt similarity index 99% rename from compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt rename to compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt index b8e2bbdcfe356..45aae6043855e 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt +++ b/compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt @@ -41,4 +41,4 @@ fun box(): String { val test2: X<String, B<String>> = J.test2() as X<String, B<String>> return test2.p1 + test2.p2.value -} \ No newline at end of file +} diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt similarity index 97% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt index f120be87f6224..5ef83125dcb5a 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt similarity index 96% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt index 87a17ca3bd09c..b620b9318936a 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.KCallable import kotlin.test.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt similarity index 95% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt index cb99eb8129d0c..7046257bca3e8 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.KClass import kotlin.test.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt similarity index 95% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt index a21e54b428757..22d1afefa3ac3 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.assertEquals diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt similarity index 94% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt index 2f989b02118d8..f485e0554fe10 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt similarity index 98% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt index c9133e2ec241f..bbd34af42b9a5 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.* import kotlin.test.assertTrue diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt similarity index 95% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt index 3f5912a3ab310..806258b30482f 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.assertEquals diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt similarity index 91% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt index 48a845d11bd7e..a082834ed029d 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.assertNotNull diff --git a/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt b/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt index 14960a71ce7fc..f68dda4d4b18e 100644 --- a/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt +++ b/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt import test.A diff --git a/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt b/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt index 07b1bd2799a87..2915070b4c557 100644 --- a/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt +++ b/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: box.kt package test diff --git a/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt b/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt index f89f5ec7516d0..7f782c4f080cd 100644 --- a/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt +++ b/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt import a.* diff --git a/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt b/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt index adaa0963a20d1..369756176b40d 100644 --- a/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt +++ b/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt import a.OK diff --git a/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt b/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt index 8bc0417184e4a..efdebe900ac5e 100644 --- a/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt +++ b/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: box.kt package test diff --git a/compiler/testData/codegen/boxMultiFile/kt1515.kt b/compiler/testData/codegen/boxMultiFile/kt1515.kt index 7cd77d0374c90..90dfc5624f775 100644 --- a/compiler/testData/codegen/boxMultiFile/kt1515.kt +++ b/compiler/testData/codegen/boxMultiFile/kt1515.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package thispackage diff --git a/compiler/testData/codegen/boxMultiFile/kt5445.kt b/compiler/testData/codegen/boxMultiFile/kt5445.kt index 7b342adab2eaf..b8eb1bd4a7813 100644 --- a/compiler/testData/codegen/boxMultiFile/kt5445.kt +++ b/compiler/testData/codegen/boxMultiFile/kt5445.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package test2 diff --git a/compiler/testData/codegen/boxMultiFile/kt5445_2.kt b/compiler/testData/codegen/boxMultiFile/kt5445_2.kt index 62def12b07f13..6d0bf0391a746 100644 --- a/compiler/testData/codegen/boxMultiFile/kt5445_2.kt +++ b/compiler/testData/codegen/boxMultiFile/kt5445_2.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package test2 diff --git a/compiler/testData/codegen/boxMultiFile/mainInFiles.kt b/compiler/testData/codegen/boxMultiFile/mainInFiles.kt index c488f31116fec..229de1362cfa1 100644 --- a/compiler/testData/codegen/boxMultiFile/mainInFiles.kt +++ b/compiler/testData/codegen/boxMultiFile/mainInFiles.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package test diff --git a/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt b/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt index 9030317f1a5d7..33b98e5aaf5e8 100644 --- a/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt +++ b/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: box.kt import a.* diff --git a/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt b/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt index 74bca491a4c8b..461b35bccb485 100644 --- a/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt +++ b/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1/wrapped.kt fun getWrapped1(): Runnable { diff --git a/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt b/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt index f149e6819887b..0ce5c61c0b59e 100644 --- a/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt +++ b/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1/part.kt @file:JvmName("Foo") diff --git a/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt b/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt index 93f3efb978844..2d0bc40ed34c8 100644 --- a/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt +++ b/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaClass.java public class JavaClass { diff --git a/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt b/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt index 032a68a65a157..21514c2a694a8 100644 --- a/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt +++ b/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt b/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt index 8dbebfd91bad3..9566ff0d9ec15 100644 --- a/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt +++ b/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt index 38ceb8c790201..ada2a274c2fd7 100644 --- a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt +++ b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class O {} @@ -16,7 +17,7 @@ annotation class Ann(val args: Array<KClass<*>>) fun box(): String { val args = Test::class.java.getAnnotation(Ann::class.java).args - val argName1 = args[0].simpleName ?: "fail 1" - val argName2 = args[1].simpleName ?: "fail 2" + val argName1 = args[0].java.simpleName ?: "fail 1" + val argName2 = args[1].java.simpleName ?: "fail 2" return argName1 + argName2 } diff --git a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt index ba5d272def412..e8bbfe3c99a0a 100644 --- a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt +++ b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class OK {} @@ -14,6 +15,6 @@ import kotlin.reflect.KClass annotation class Ann(val arg: KClass<*>) fun box(): String { - val argName = Test::class.java.getAnnotation(Ann::class.java).arg.simpleName ?: "fail 1" + val argName = Test::class.java.getAnnotation(Ann::class.java).arg.java.simpleName ?: "fail 1" return argName } diff --git a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt index e12a7817fcf81..15d218db5c0f6 100644 --- a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt +++ b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class O {} @@ -16,7 +17,7 @@ annotation class Ann(vararg val args: KClass<*>) fun box(): String { val args = Test::class.java.getAnnotation(Ann::class.java).args - val argName1 = args[0].simpleName ?: "fail 1" - val argName2 = args[1].simpleName ?: "fail 2" + val argName1 = args[0].java.simpleName ?: "fail 1" + val argName2 = args[1].java.simpleName ?: "fail 2" return argName1 + argName2 } diff --git a/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt b/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt index f7ccb51249c63..a05f02ea645ed 100644 --- a/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt +++ b/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: A.java public class A extends AImpl implements java.util.List<String> { diff --git a/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt b/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt index fac871fb05d5a..69f8ff0a32fb4 100644 --- a/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt +++ b/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaClass.java public class JavaClass { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt b/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt index 887a1af5cc5ac..e1bd46360aa44 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt b/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt index d4db0df8d6039..f13f8a93d6b90 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: StringHolder.java import java.lang.annotation.ElementType; diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt index fc240cd9899ee..240fccccd5656 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt index 0a2e8bd496dd8..4186b62d558c3 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt index 3227619a9cc10..bc2c3db2f558a 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt b/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt index fd2feb7393abc..66b6bd3328602 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Bar.java public class Bar { diff --git a/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt b/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt index b2b9353b3df41..58bdad5fe98be 100644 --- a/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt +++ b/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: CompanionInitialization.java public class CompanionInitialization { diff --git a/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt b/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt index ea0ed56d7268f..250f764b41fe7 100644 --- a/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt +++ b/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmField/simple.kt b/compiler/testData/codegen/boxWithJava/jvmField/simple.kt index 4112b0f189b81..f89b81c2fc20e 100644 --- a/compiler/testData/codegen/boxWithJava/jvmField/simple.kt +++ b/compiler/testData/codegen/boxWithJava/jvmField/simple.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt b/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt index b63fe927dcd82..498a8b306de43 100644 --- a/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt +++ b/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt b/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt index a03031975129a..9fff7ca10bb1a 100644 --- a/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt +++ b/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt index dfbfe6702310c..dd1d45bb97d48 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java import java.lang.annotation.Annotation; diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt index 13d937d9b4bbd..e6aa00a607e8f 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt index b25091ee2ed2a..b11acbd3d0f24 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt index b4b84c3e15cc3..97d071d557de5 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt b/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt index 12e90aca638ce..b1f09f9ea9547 100644 --- a/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt +++ b/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaClass.java import java.lang.annotation.Retention; diff --git a/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt b/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt index 385f8a0896f51..035da13ca8032 100644 --- a/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt +++ b/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt b/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt index c6c0a16780a8a..a8cc18a55ff74 100644 --- a/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt +++ b/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaBaseClass.java public class JavaBaseClass { diff --git a/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt b/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt index 99d6f8e15f3aa..6aff71b3d79e4 100644 --- a/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt +++ b/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaBaseClass.java public class JavaBaseClass { diff --git a/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt b/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt index 4947956755a46..1ea9f687be462 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java @Anno("J") diff --git a/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt b/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt index b02cf4892eb27..35f527ffa0255 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt b/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt index 5ce51bff71a9d..4a28a0f9aa9dc 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt b/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt index 9121ae15c5057..13de918f62822 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt index 2260351e564f2..f1c2d8bdf424e 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt index 1a21b4b0cd9af..c1880a4c91843 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt b/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt index d7096212f8616..2843bacbab651 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java import kotlin.jvm.functions.Function2; diff --git a/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt b/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt index 8b06ce6459e7f..7dffd907ee142 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt b/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt index 1f40ab18c87e4..d1ef881b8782d 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt b/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt index 8a08b664ab5e2..f71764acfc390 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J extends K { diff --git a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt index 16030d194a530..8cbbf6c6cf6c2 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt index 3d853c18d6a92..9887e442c792a 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt b/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt index 4ccd0f612ec39..21a31878f02a2 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt b/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt index ffd0b270986bd..7bde34e271db1 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt b/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt index 930dde99cb30c..6defc2359f771 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt b/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt index 8980cd4d7abfd..2699bf83e0f6a 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt b/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt index 89a5ab0403cea..f43a98c50f442 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java import java.util.List; diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java b/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java index b3c7b2f0cef61..1857c048e69d8 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java @@ -51,6 +51,9 @@ import static org.jetbrains.kotlin.test.KotlinTestUtils.getAnnotationsJar; public abstract class AbstractBlackBoxCodegenTest extends CodegenTestCase { + private boolean addRuntime = false; + private boolean addReflect = false; + @Override protected void doMultiFileTest(@NotNull File wholeFile, @NotNull List<TestFile> files, @Nullable File javaFilesDir) throws Exception { TestJdkKind jdkKind = TestJdkKind.MOCK_JDK; @@ -59,18 +62,26 @@ protected void doMultiFileTest(@NotNull File wholeFile, @NotNull List<TestFile> if (InTextDirectivesUtils.isDirectiveDefined(file.content, "FULL_JDK")) { jdkKind = TestJdkKind.FULL_JDK; } - if (InTextDirectivesUtils.isDirectiveDefined(file.content, "NO_KOTLIN_REFLECT")) { - configurationKind = ConfigurationKind.NO_KOTLIN_REFLECT; + if (InTextDirectivesUtils.isDirectiveDefined(file.content, "WITH_RUNTIME")) { + addRuntime = true; + } + if (InTextDirectivesUtils.isDirectiveDefined(file.content, "WITH_REFLECT")) { + addReflect = true; } javacOptions.addAll(InTextDirectivesUtils.findListWithPrefixes(file.content, "// JAVAC_OPTIONS:")); } + configurationKind = + addReflect ? ConfigurationKind.ALL : + addRuntime ? ConfigurationKind.NO_KOTLIN_REFLECT : + ConfigurationKind.JDK_ONLY; + compileAndRun(files, javaFilesDir, jdkKind, javacOptions); } protected void doTestWithStdlib(@NotNull String filename) throws Exception { - configurationKind = ConfigurationKind.ALL; + addReflect = true; doTest(filename); } diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java index 076092aadccb6..4d1fc5d639290 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java @@ -7030,11 +7030,83 @@ public void testAllFilesPresentInReflection() throws Exception { KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/box/reflection"), Pattern.compile("^(.+)\\.kt$"), true); } + @TestMetadata("defaultImplsGenericSignature.kt") + public void testDefaultImplsGenericSignature() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt"); + doTest(fileName); + } + @TestMetadata("functionLiteralGenericSignature.kt") public void testFunctionLiteralGenericSignature() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/functionLiteralGenericSignature.kt"); doTest(fileName); } + + @TestMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect") + @TestDataPath("$PROJECT_ROOT") + @RunWith(JUnit3RunnerWithInners.class) + public static class NoKotlinReflect extends AbstractBlackBoxCodegenTest { + public void testAllFilesPresentInNoKotlinReflect() throws Exception { + KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/box/reflection/noKotlinReflect"), Pattern.compile("^(.+)\\.kt$"), true); + } + + @TestMetadata("javaClass.kt") + public void testJavaClass() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt"); + doTest(fileName); + } + + @TestMetadata("primitiveJavaClass.kt") + public void testPrimitiveJavaClass() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt"); + doTest(fileName); + } + + @TestMetadata("propertyGetSetName.kt") + public void testPropertyGetSetName() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt"); + doTest(fileName); + } + + @TestMetadata("propertyInstanceof.kt") + public void testPropertyInstanceof() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt"); + doTest(fileName); + } + + @TestMetadata("reifiedTypeJavaClass.kt") + public void testReifiedTypeJavaClass() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt"); + doTest(fileName); + } + + @TestMetadata("simpleClassLiterals.kt") + public void testSimpleClassLiterals() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt"); + doTest(fileName); + } + + @TestMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny") + @TestDataPath("$PROJECT_ROOT") + @RunWith(JUnit3RunnerWithInners.class) + public static class MethodsFromAny extends AbstractBlackBoxCodegenTest { + public void testAllFilesPresentInMethodsFromAny() throws Exception { + KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny"), Pattern.compile("^(.+)\\.kt$"), true); + } + + @TestMetadata("callableReferences.kt") + public void testCallableReferences() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt"); + doTest(fileName); + } + + @TestMetadata("classReference.kt") + public void testClassReference() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt"); + doTest(fileName); + } + } + } } @TestMetadata("compiler/testData/codegen/box/regressions") diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java index caf303962cc31..e9d7fa1f6a1d5 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java @@ -601,12 +601,6 @@ public void testDeclaredVsInheritedProperties() throws Exception { doTest(fileName); } - @TestMetadata("defaultImplsGenericSignature.kt") - public void testDefaultImplsGenericSignature() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt"); - doTest(fileName); - } - @TestMetadata("functionReferenceErasedToKFunction.kt") public void testFunctionReferenceErasedToKFunction() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt"); diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java index 27b99123016ef..9aaca3605e245 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java @@ -3786,12 +3786,6 @@ public void testCovariantOverride() throws Exception { doTestWithStdlib(fileName); } - @TestMetadata("kt11121.kt") - public void testKt11121() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/kt11121.kt"); - doTestWithStdlib(fileName); - } - @TestMetadata("genericBackingFieldSignature.kt") public void testGenericBackingFieldSignature() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/genericBackingFieldSignature.kt"); @@ -3804,6 +3798,12 @@ public void testGenericMethodSignature() throws Exception { doTestWithStdlib(fileName); } + @TestMetadata("kt11121.kt") + public void testKt11121() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/kt11121.kt"); + doTestWithStdlib(fileName); + } + @TestMetadata("kt5112.kt") public void testKt5112() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/kt5112.kt"); @@ -4153,72 +4153,6 @@ public void testTypeToString() throws Exception { } } - @TestMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class NoKotlinReflect extends AbstractBlackBoxCodegenTest { - public void testAllFilesPresentInNoKotlinReflect() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect"), Pattern.compile("^(.+)\\.kt$"), true); - } - - @TestMetadata("javaClass.kt") - public void testJavaClass() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("primitiveJavaClass.kt") - public void testPrimitiveJavaClass() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("propertyGetSetName.kt") - public void testPropertyGetSetName() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("propertyInstanceof.kt") - public void testPropertyInstanceof() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("reifiedTypeJavaClass.kt") - public void testReifiedTypeJavaClass() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("simpleClassLiterals.kt") - public void testSimpleClassLiterals() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class MethodsFromAny extends AbstractBlackBoxCodegenTest { - public void testAllFilesPresentInMethodsFromAny() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny"), Pattern.compile("^(.+)\\.kt$"), true); - } - - @TestMetadata("callableReferences.kt") - public void testCallableReferences() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt"); - doTestWithStdlib(fileName); - } - - @TestMetadata("classReference.kt") - public void testClassReference() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt"); - doTestWithStdlib(fileName); - } - } - } - @TestMetadata("compiler/testData/codegen/boxWithStdlib/reflection/parameters") @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class)
8cd014851fb7a6e488abe13f495bd02b9c80e003
tapiji
Fixes bug in I18nBuilder. If a full build is triggered, then only errors from the last parsed file were reported. This change fixes that problem.
c
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java index f767964a..20c3942b 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java @@ -60,5 +60,10 @@ public String getContextId() { public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { return null; } + + @Override + public void reset() { + // there is nothing todo + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java index 3ba57eeb..7daa03a7 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java @@ -153,6 +153,12 @@ private void auditResources(List<IResource> resources, monitor.beginTask( "Audit resource file for Internationalization problems", work); + + for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) { + if (ra instanceof I18nResourceAuditor) { + ((I18nResourceAuditor)ra).reset(); + } + } for (IResource resource : resources) { monitor.subTask("'" + resource.getFullPath().toOSString() + "'"); diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java index 04bb77a7..c89f7ac8 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java @@ -67,6 +67,11 @@ public abstract class I18nResourceAuditor extends I18nAuditor { * resources */ public abstract List<ILocation> getBrokenBundleReferences(); + + /** + * Resets the auditor and clears collected Internationalization errors + */ + public abstract void reset(); /** * Returns a characterizing identifier of the implemented auditing diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java index f201c427..dea2c537 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java @@ -37,10 +37,14 @@ public class JavaResourceAuditor extends I18nResourceAuditor { - protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>(); - protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>(); - protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>(); + protected List<SLLocation> constantLiterals; + protected List<SLLocation> brokenResourceReferences; + protected List<SLLocation> brokenBundleReferences; + public JavaResourceAuditor() { + this.reset(); + } + @Override public String[] getFileEndings() { return new String[] { "java" }; @@ -63,13 +67,13 @@ public void audit(IResource resource) { cu.accept(csav); // Report all constant string literals - constantLiterals = csav.getConstantStringLiterals(); + constantLiterals.addAll(csav.getConstantStringLiterals()); // Report all broken Resource-Bundle references - brokenResourceReferences = csav.getBrokenResourceReferences(); + brokenResourceReferences.addAll(csav.getBrokenResourceReferences()); // Report all broken definitions to Resource-Bundle references - brokenBundleReferences = csav.getBrokenRBReferences(); + brokenBundleReferences.addAll(csav.getBrokenRBReferences()); } @Override @@ -162,4 +166,10 @@ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { return resolutions; } + @Override + public void reset() { + constantLiterals = new ArrayList<SLLocation>(); + brokenResourceReferences = new ArrayList<SLLocation>(); + brokenBundleReferences = new ArrayList<SLLocation>(); + } }
ea89ac5dd42a7d3564ca6955b93f8356e1b04fd3
Valadoc
libvaladoc/html: Add style for {{{source}}}
a
https://github.com/GNOME/vala/
diff --git a/icons/devhelpstyle.css b/icons/devhelpstyle.css index d6c94432b1..966c9929c6 100644 --- a/icons/devhelpstyle.css +++ b/icons/devhelpstyle.css @@ -41,7 +41,7 @@ ul.external_link { margin-left:auto; } -.main_sourcesample { +.main_source, .main_sourcesample { padding-right: 10px; padding-left: 5px; padding-bottom: 5px; diff --git a/icons/style.css b/icons/style.css index 919fba6a9e..8987ccd36f 100644 --- a/icons/style.css +++ b/icons/style.css @@ -44,7 +44,7 @@ ul.external_link { margin-left:auto; } -.main_sourcesample { +.main_source, .main_sourcesample { padding-right: 10px; padding-left: 5px; padding-bottom: 5px; diff --git a/icons/wikistyle.css b/icons/wikistyle.css index d9aab37db4..7dc8497e59 100644 --- a/icons/wikistyle.css +++ b/icons/wikistyle.css @@ -57,7 +57,7 @@ div.main_block_content { margin-left:15px; } -.main_sourcesample { +.main_source, .main_sourcesample { padding-right: 10px; padding-left: 5px; padding-bottom: 5px; diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala index 5a3d44f9c1..153e844b96 100755 --- a/src/libvaladoc/html/htmlrenderer.vala +++ b/src/libvaladoc/html/htmlrenderer.vala @@ -450,7 +450,7 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer { } public override void visit_source_code (SourceCode element) { - writer.start_tag ("pre"); + writer.start_tag ("pre", {"class", "main_source"}); writer.set_wrap (false); write_string (element.code); writer.set_wrap (true);
146f645e74abb525754d3b4043803a5d1f7c0bee
getrailo$railo
improved "update jars" functionality
p
https://github.com/getrailo/railo
diff --git a/railo-java/railo-core/src/railo/commons/net/HTTPUtil.java b/railo-java/railo-core/src/railo/commons/net/HTTPUtil.java index 4aed796e5e..190ec21ee5 100755 --- a/railo-java/railo-core/src/railo/commons/net/HTTPUtil.java +++ b/railo-java/railo-core/src/railo/commons/net/HTTPUtil.java @@ -45,6 +45,8 @@ import railo.runtime.net.http.HTTPServletRequestWrap; import railo.runtime.net.http.HttpClientUtil; import railo.runtime.net.http.HttpServletResponseWrap; +import railo.runtime.net.proxy.ProxyData; +import railo.runtime.net.proxy.ProxyDataImpl; import railo.runtime.op.Caster; import railo.runtime.op.Decision; import railo.runtime.type.List; @@ -843,6 +845,42 @@ public static int getPort(URL url) { return 443; return 80; } + + + /** + * return the length of a file defined by a url. + * @param dataUrl + * @return + */ + public static long length(URL url) { + long length=0; + + // check response header "content-length" + ProxyData pd=ProxyDataImpl.NO_PROXY; + try { + HttpMethod http = HTTPUtil.head(url, null, null, -1,null, "Railo", pd.getServer(), pd.getPort(),pd.getUsername(), pd.getPassword(),null); + Header cl = http.getResponseHeader("content-length"); + if(cl!=null) { + length=Caster.toIntValue(cl.getValue(),-1); + if(length!=-1) return length; + } + } + catch (IOException e) {} + + // get it for size + try { + HttpMethod http = HTTPUtil.invoke(url, null, null, -1,null, "Railo", pd.getServer(), pd.getPort(),pd.getUsername(), pd.getPassword(),null); + InputStream is = http.getResponseBodyAsStream(); + byte[] buffer = new byte[1024]; + int len; + length=0; + while((len = is.read(buffer)) !=-1){ + length+=len; + } + } + catch (IOException e) {} + return length; + } } \ No newline at end of file diff --git a/railo-java/railo-core/src/railo/commons/net/JarLoader.java b/railo-java/railo-core/src/railo/commons/net/JarLoader.java index db586b7464..a7919d391f 100644 --- a/railo-java/railo-core/src/railo/commons/net/JarLoader.java +++ b/railo-java/railo-core/src/railo/commons/net/JarLoader.java @@ -3,12 +3,15 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; +import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; +import railo.print; import railo.commons.io.IOUtil; import railo.commons.io.res.Resource; +import railo.commons.io.res.type.http.HTTPResource; import railo.commons.io.res.util.ResourceClassLoader; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.SystemOut; @@ -18,6 +21,7 @@ import railo.runtime.PageContext; import railo.runtime.config.ConfigWeb; import railo.runtime.config.ConfigWebImpl; +import railo.runtime.exp.PageException; public class JarLoader { @@ -44,8 +48,9 @@ public static ClassLoader loadJars(PageContext pc, String[] jars,ClassLoader par public static Resource[] download(PageContext pc, String[] jars) throws IOException { List<Resource> list=new ArrayList<Resource>(); Resource jar; + lastCheck=-1; for(int i=0;i<jars.length;i++){ - jar=download(pc, jars[i], WHEN_EXISTS_RETURN_NULL); + jar=download(pc, jars[i], WHEN_EXISTS_UPDATE); if(jar!=null) list.add(jar); } return list.toArray(new Resource[list.size()]); @@ -57,61 +62,112 @@ private static Resource download(PageContext pc,String jarName, short whenExists ConfigWebImpl config=(ConfigWebImpl) pc.getConfig(); CFMLEngine engine=config.getCFMLEngineImpl(); PrintWriter out = pc.getConfig().getOutWriter(); + + URL dataUrl=toURL(engine,jarName); // destination file ClassLoader mainClassLoader = new TP().getClass().getClassLoader(); Resource lib = ResourceUtil.toResourceNotExisting(pc,CFMLEngineFactory.getClassLoaderRoot(mainClassLoader).getCanonicalPath(),false); Resource jar=lib.getRealResource(jarName); - if(jar.exists()){ + SystemOut.printDate(out,"Check for jar at "+dataUrl); + if(jar.exists()){ if(whenExists==WHEN_EXISTS_RETURN_JAR) return jar; else if(whenExists==WHEN_EXISTS_RETURN_NULL) return null; else if(whenExists==WHEN_EXISTS_UPDATE) { - if(!jar.delete()) throw new IOException("cannot update jar ["+jar+"], jar is locked or write protected"); + // compare local and remote + long localLen=jar.length(); + long remoteLengh=HTTPUtil.length(dataUrl); + // only update when size change more than 10 + if(localLen==remoteLengh){ + SystemOut.printDate(out,"jar "+jar+" is up to date"); + return jar; + } + if(!jar.delete()) throw new IOException("cannot update jar ["+jar+"], jar is locked or write protected, stop the servlet engine and delete this jar manually."); } else throw new IOException("jar ["+jar+"] already exists"); } - URL hostUrl=engine.getUpdateLocation(); - if(hostUrl==null)hostUrl=new URL("http://www.getrailo.org"); - URL dataUrl=new URL(hostUrl,"/railo/remote/jars/"+jarName); - - SystemOut.printDate(out,"Check for jar at "+hostUrl); - - + + //long len=HTTPUtil.length(); InputStream is = (InputStream)dataUrl.getContent(); // copy input stream to lib directory IOUtil.copy(is, jar,true); - SystemOut.printDate(out,"created jar "+jar); + SystemOut.printDate(out,"created/updated jar "+jar); return jar; } - + + private static URL toURL(CFMLEngine engine, String jarName) throws MalformedURLException { + URL hostUrl=engine.getUpdateLocation(); + if(hostUrl==null)hostUrl=new URL("http://www.getrailo.org"); + return new URL(hostUrl,"/railo/remote/jars/"+jarName); + } + + public static boolean exists(ConfigWeb config,String[] jarNames) { for(int i=0;i<jarNames.length;i++){ if(!exists(config, jarNames[i])) return false; } return true; - + } + + /** + * check if one of given jar has changed or not exist + * @param config + * @param jarNames + * @return + */ + private static boolean changed=false; + private static long lastCheck=-1; + public static boolean changed(ConfigWeb config,String[] jarNames) { + if((lastCheck+300000)<System.currentTimeMillis()) { + changed=false; + for(int i=0;i<jarNames.length;i++){ + if(changed(config, jarNames[i])) { + changed=true; + break; + } + } + lastCheck=System.currentTimeMillis(); + } + return changed; } private static boolean exists(ConfigWeb config,String jarName) { - // some variables nned later - ConfigWebImpl configImpl=(ConfigWebImpl) config; - CFMLEngine engine=configImpl.getCFMLEngineImpl(); - PrintWriter out = config.getOutWriter(); - - // destination file + Resource res = _toResource(config, jarName); + if(res==null) return false; + return res.exists(); + } + + private static boolean changed(ConfigWeb config,String jarName) { + Resource res = _toResource(config, jarName); + if(res==null) { + print.o("missing:"+jarName); + return true; + } + + CFMLEngine engine=((ConfigWebImpl)config).getCFMLEngineImpl(); + try { + URL dataUrl = toURL(engine,jarName); + boolean changed=res.length()!=HTTPUtil.length(dataUrl); + if(changed)print.o("diff:"+jarName); + + return changed; + } catch (MalformedURLException e) { + return false; + } + } + + private static Resource _toResource(ConfigWeb config,String jarName) { + // destination file ClassLoader mainClassLoader = new TP().getClass().getClassLoader(); try { Resource lib = ResourceUtil.toResourceNotExisting(config,CFMLEngineFactory.getClassLoaderRoot(mainClassLoader).getCanonicalPath()); - Resource jar=lib.getRealResource(jarName); - return jar.exists(); + return lib.getRealResource(jarName); } catch (IOException e) { - return false; + return null; } - - } } diff --git a/railo-java/railo-core/src/railo/runtime/cache/CacheConnectionImpl.java b/railo-java/railo-core/src/railo/runtime/cache/CacheConnectionImpl.java index 4a4774467b..da515b6780 100755 --- a/railo-java/railo-core/src/railo/runtime/cache/CacheConnectionImpl.java +++ b/railo-java/railo-core/src/railo/runtime/cache/CacheConnectionImpl.java @@ -51,7 +51,7 @@ public Cache getInstance(Config config) throws IOException { } catch(NoClassDefFoundError e){ if(!(config instanceof ConfigWeb)) throw e; - if(!JarLoader.exists((ConfigWeb)config, Admin.UPDATE_JARS)) + if(JarLoader.changed((ConfigWeb)config, Admin.CACHE_JARS)) throw new IOException( "cannot initilaize Cache ["+clazz.getName()+"], make sure you have added all the required jars files. "+ "GO to the Railo Server Administrator and on the page Services/Update, click on \"Update JAR's\"."); diff --git a/railo-java/railo-core/src/railo/runtime/config/ConfigImpl.java b/railo-java/railo-core/src/railo/runtime/config/ConfigImpl.java index 48b89b9b78..58e94f3002 100755 --- a/railo-java/railo-core/src/railo/runtime/config/ConfigImpl.java +++ b/railo-java/railo-core/src/railo/runtime/config/ConfigImpl.java @@ -3026,7 +3026,7 @@ public ORMEngine getORMEngine(PageContext pc) throws PageException { t.printStackTrace();; } }*/ - if(!JarLoader.exists(pc.getConfig(), Admin.UPDATE_JARS)) + if(JarLoader.changed(pc.getConfig(), Admin.ORM_JARS)) throw new ORMException( "cannot initilaize ORM Engine ["+ormEngineClass.getName()+"], make sure you have added all the required jars files", "GO to the Railo Server Administrator and on the page Services/Update, click on \"Update JAR's\""); diff --git a/railo-java/railo-core/src/railo/runtime/tag/Admin.java b/railo-java/railo-core/src/railo/runtime/tag/Admin.java index ef30b997e9..8b8a44cb4b 100755 --- a/railo-java/railo-core/src/railo/runtime/tag/Admin.java +++ b/railo-java/railo-core/src/railo/runtime/tag/Admin.java @@ -142,6 +142,9 @@ public final class Admin extends TagImpl implements DynamicAttributes { private static final Collection.Key KEY = KeyImpl.getInstance("key"); private static final Collection.Key VALUE = KeyImpl.getInstance("value"); private static final Collection.Key TIME = KeyImpl.getInstance("time"); + public static final String[] ORM_JARS = new String[]{"antlr.jar","dom4j.jar","hibernate.jar","javassist.jar","jta.jar","slf4j-api.jar","railo-sl4j.jar"}; + public static final String[] CACHE_JARS = new String[]{"ehcache.jar"}; + public static final String[] CFX_JARS = new String[]{"com.naryx.tagfusion.cfx.jar"}; public static final String[] UPDATE_JARS = new String[]{"ehcache.jar","antlr.jar","dom4j.jar","hibernate.jar","javassist.jar","jta.jar","slf4j-api.jar","railo-sl4j.jar","metadata-extractor.jar","icepdf-core.jar","com.naryx.tagfusion.cfx.jar"}; /* @@ -1878,13 +1881,12 @@ private void listPatches() throws PageException { throw Caster.toPageException(e); } } - + private void needNewJars() throws PageException { - - boolean exists = JarLoader.exists(pageContext.getConfig(), UPDATE_JARS); - + boolean needNewJars = JarLoader.changed(pageContext.getConfig(), UPDATE_JARS); + try { - pageContext.setVariable(getString("admin",action,"returnVariable"),!Caster.toBoolean(exists)); + pageContext.setVariable(getString("admin",action,"returnVariable"),needNewJars); } catch (Exception e) { throw Caster.toPageException(e);
1677de7862935244adfcd039bd1f0bd3a93e7009
restlet-framework-java
Fixed regression. Reported by Guido Schmidt--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectedRequest.java b/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectedRequest.java index 5b2807de35..25ab1bc4fc 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectedRequest.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectedRequest.java @@ -664,11 +664,13 @@ public List<Range> getRanges() { public List<RecipientInfo> getRecipientsInfo() { List<RecipientInfo> result = super.getRecipientsInfo(); if (!recipientsInfoAdded) { - for (String header : getHeaders().getValuesArray( - HeaderConstants.HEADER_VIA)) { - new RecipientInfoReader(header).addValues(result); + if (getHeaders() != null) { + for (String header : getHeaders().getValuesArray( + HeaderConstants.HEADER_VIA)) { + new RecipientInfoReader(header).addValues(result); + } } - setRecipientsInfo(result); + this.recipientsInfoAdded = true; } return result; }
207f8e7c475fb8f4ac45baed88daa5d80c2a72b6
kotlin
Cleanup--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/KotlinLightClassForPackageProvider.java b/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/KotlinLightClassForPackageProvider.java index db0ae9954084f..7ba8103cf9b0e 100644 --- a/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/KotlinLightClassForPackageProvider.java +++ b/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/KotlinLightClassForPackageProvider.java @@ -58,15 +58,6 @@ public KotlinLightClassForPackageProvider(@NotNull Project project, @NotNull FqN public Result<PsiClass> compute() { checkForBuiltIns(); - PsiJavaFileStubImpl javaFileStub = new PsiJavaFileStubImpl(fqName.getFqName(), true); - - Stack<StubElement> stubStack = new Stack<StubElement>(); - - ClassBuilderFactory builderFactory = new KotlinLightClassBuilderFactory(stubStack); - - // The context must reflect _all files in the module_. not only the current file - // Otherwise, the analyzer gets confused and can't, for example, tell which files come as sources and which - // must be loaded from .class files LightClassConstructionContext context = LightClassGenerationSupport.getInstance(project).analyzeRelevantCode(files); Throwable error = context.getError(); @@ -74,7 +65,12 @@ public Result<PsiClass> compute() { throw new IllegalStateException("failed to analyze: " + error, error); } + PsiJavaFileStubImpl javaFileStub = new PsiJavaFileStubImpl(fqName.getFqName(), true); + try { + Stack<StubElement> stubStack = new Stack<StubElement>(); + ClassBuilderFactory builderFactory = new KotlinLightClassBuilderFactory(stubStack); + GenerationState state = new GenerationState( project, builderFactory,
c93e1d8deccb1d508e50a890e96cb4dc929ee044
Valadoc
driver-0.13.x: Add basic gir support
a
https://github.com/GNOME/vala/
diff --git a/src/driver/0.13.x/treebuilder.vala b/src/driver/0.13.x/treebuilder.vala index 74f42c5e69..efb8d44a0a 100644 --- a/src/driver/0.13.x/treebuilder.vala +++ b/src/driver/0.13.x/treebuilder.vala @@ -698,9 +698,9 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { } context.add_source_file (source_file); - } else if (source.has_suffix (".vapi")) { + } else if (source.has_suffix (".vapi") || source.has_suffix (".gir")) { string file_name = Path.get_basename (source); - file_name = file_name.substring (0, file_name.length - ".vapi".length); + file_name = file_name.substring (0, file_name.last_index_of_char ('.')); var vfile = new Vala.SourceFile (context, Vala.SourceFileType.PACKAGE, rpath); context.add_source_file (vfile); @@ -711,7 +711,6 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { register_source_file (source_package, vfile); - add_deps (context, Path.build_filename (Path.get_dirname (source), "%s.deps".printf (file_name)), file_name); } else if (source.has_suffix (".c")) { context.add_c_source_file (rpath); @@ -809,6 +808,15 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { return context; } + // parse gir: + Vala.GirParser gir_parser = new Vala.GirParser (); + + gir_parser.parse (context); + if (context.report.get_errors () > 0) { + return context; + } + + // check context: context.check ();
a71d8de130a2bf90941566fcf2bc8b1804b96dee
Vala
gtk+-2.0, gtk+-3.0: fix return value of Gtk.AccelGroup.find Fixes bug 617963.
c
https://github.com/GNOME/vala/
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi index fed1382747..0cfefc0a37 100644 --- a/vapi/gtk+-2.0.vapi +++ b/vapi/gtk+-2.0.vapi @@ -66,7 +66,7 @@ namespace Gtk { public void connect_by_path (string accel_path, GLib.Closure closure); public bool disconnect (GLib.Closure closure); public bool disconnect_key (uint accel_key, Gdk.ModifierType accel_mods); - public Gtk.AccelKey find (Gtk.AccelGroupFindFunc find_func, void* data); + public Gtk.AccelKey* find (Gtk.AccelGroupFindFunc find_func); public static unowned Gtk.AccelGroup from_accel_closure (GLib.Closure closure); public bool get_is_locked (); public Gdk.ModifierType get_modifier_mask (); diff --git a/vapi/gtk+-3.0.vapi b/vapi/gtk+-3.0.vapi index a00981a800..1c3388cdce 100644 --- a/vapi/gtk+-3.0.vapi +++ b/vapi/gtk+-3.0.vapi @@ -63,7 +63,7 @@ namespace Gtk { public void connect_by_path (string accel_path, GLib.Closure closure); public bool disconnect (GLib.Closure closure); public bool disconnect_key (uint accel_key, Gdk.ModifierType accel_mods); - public Gtk.AccelKey find (Gtk.AccelGroupFindFunc find_func, void* data); + public Gtk.AccelKey* find (Gtk.AccelGroupFindFunc find_func); public static unowned Gtk.AccelGroup from_accel_closure (GLib.Closure closure); public bool get_is_locked (); public Gdk.ModifierType get_modifier_mask (); diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala b/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala index 8e2d3085be..fc803003eb 100644 --- a/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala +++ b/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala @@ -21,6 +21,10 @@ */ namespace Gtk { + public class AccelGroup { + public Gtk.AccelKey* find (Gtk.AccelGroupFindFunc find_func); + } + public struct Allocation { public int x; public int y; diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata index 7b04c710c0..c1a37f4c0f 100644 --- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata +++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata @@ -11,6 +11,7 @@ gtk_about_dialog_set_url_hook.data hidden="1" gtk_about_dialog_set_url_hook.destroy hidden="1" gtk_about_dialog_set_url_hook type_name="void" gtk_accel_groups_from_object type_arguments="AccelGroup" +gtk_accel_group_find hidden="1" GtkAccelKey is_value_type="1" gtk_accel_map_lookup_entry.key is_out="1" gtk_accelerator_parse.accelerator_key is_out="1" diff --git a/vapi/packages/gtk+-3.0/gtk+-3.0-custom.vala b/vapi/packages/gtk+-3.0/gtk+-3.0-custom.vala index c30718c1be..feabb3491e 100644 --- a/vapi/packages/gtk+-3.0/gtk+-3.0-custom.vala +++ b/vapi/packages/gtk+-3.0/gtk+-3.0-custom.vala @@ -21,6 +21,10 @@ */ namespace Gtk { + public class AccelGroup { + public Gtk.AccelKey* find (Gtk.AccelGroupFindFunc find_func); + } + public struct Allocation { public int x; public int y; diff --git a/vapi/packages/gtk+-3.0/gtk+-3.0.metadata b/vapi/packages/gtk+-3.0/gtk+-3.0.metadata index 2dc8e435f3..6c34f0bb1f 100644 --- a/vapi/packages/gtk+-3.0/gtk+-3.0.metadata +++ b/vapi/packages/gtk+-3.0/gtk+-3.0.metadata @@ -11,6 +11,7 @@ gtk_about_dialog_set_url_hook.data hidden="1" gtk_about_dialog_set_url_hook.destroy hidden="1" gtk_about_dialog_set_url_hook type_name="void" gtk_accel_groups_from_object type_arguments="AccelGroup" +gtk_accel_group_find hidden="1" GtkAccelKey is_value_type="1" gtk_accel_map_lookup_entry.key is_out="1" gtk_accelerator_parse.accelerator_key is_out="1"
6626b44286943b4721df3345479cf5cf3ec8e2b2
internetarchive$heritrix3
generics warnings fixes This commit does not change any functionality, just alters generics to reduce warnings in Eclipse.
p
https://github.com/internetarchive/heritrix3
diff --git a/commons/src/main/java/org/apache/commons/httpclient/Cookie.java b/commons/src/main/java/org/apache/commons/httpclient/Cookie.java index 5f0650984..1db473a85 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/Cookie.java +++ b/commons/src/main/java/org/apache/commons/httpclient/Cookie.java @@ -61,8 +61,8 @@ * * @version $Revision$ $Date$ */ -@SuppressWarnings({"serial","unchecked"}) // <- HERITRIX CHANGE -public class Cookie extends NameValuePair implements Serializable, Comparator { +@SuppressWarnings({"serial"}) // <- HERITRIX CHANGE +public class Cookie extends NameValuePair implements Serializable, Comparator<Cookie> { // ----------------------------------------------------------- Constructors @@ -415,6 +415,7 @@ public int hashCode() { * @param obj The object to compare against. * @return true if the two objects are equal. */ + @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; @@ -454,7 +455,8 @@ public String toExternalForm() { * @param o2 The second object to be compared * @return See {@link java.util.Comparator#compare(Object,Object)} */ - public int compare(Object o1, Object o2) { + @Override + public int compare(Cookie o1, Cookie o2) { LOG.trace("enter Cookie.compare(Object, Object)"); if (!(o1 instanceof Cookie)) { diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java b/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java index c9e86a615..d9c2cf134 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java +++ b/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java @@ -91,7 +91,6 @@ * * @version $Revision$ $Date$ */ -@SuppressWarnings("unchecked") // <- HERITRIX CHANGE public class HttpConnection { // ----------------------------------------------------------- Constructors @@ -1162,7 +1161,7 @@ public void shutdownOutput() { // Socket.shutdownOutput is a JDK 1.3 // method. We'll use reflection in case // we're running in an older VM - Class[] paramsClasses = new Class[0]; + Class<?>[] paramsClasses = new Class[0]; Method shutdownOutput = socket.getClass().getMethod("shutdownOutput", paramsClasses); Object[] params = new Object[0]; diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java b/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java index fe8be4b01..cda1b9d20 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java +++ b/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java @@ -94,7 +94,7 @@ * * @version $Revision$ $Date$ */ -@SuppressWarnings({"deprecation","unchecked"}) // <- // IA/HERITRIX change +@SuppressWarnings({"deprecation"}) // <- // IA/HERITRIX change public abstract class HttpMethodBase implements HttpMethod { // -------------------------------------------------------------- Constants @@ -1145,8 +1145,9 @@ private CookieSpec getCookieSpec(final HttpState state) { } else { this.cookiespec = CookiePolicy.getSpecByPolicy(i); } - this.cookiespec.setValidDateFormats( - (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS)); + @SuppressWarnings("unchecked") + Collection<String> val = (Collection<String>)this.params.getParameter(HttpMethodParams.DATE_PATTERNS); + this.cookiespec.setValidDateFormats(val); } return this.cookiespec; } diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java b/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java index 7ae07c974..a67636552 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java +++ b/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java @@ -47,7 +47,6 @@ * * @since 2.0beta1 */ -@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE public class HttpParser { /** Log object for this class. */ @@ -159,7 +158,7 @@ public static String readLine(InputStream inputStream) throws IOException { public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException { LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); - ArrayList headers = new ArrayList(); + ArrayList<Header> headers = new ArrayList<Header>(); String name = null; StringBuffer value = null; for (; ;) { diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpState.java b/commons/src/main/java/org/apache/commons/httpclient/HttpState.java index 031ac5f14..5b95cb26f 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/HttpState.java +++ b/commons/src/main/java/org/apache/commons/httpclient/HttpState.java @@ -30,23 +30,21 @@ package org.apache.commons.httpclient; import java.util.ArrayList; -import java.util.Collection; // <- IA/HERITRIX CHANGE +import java.util.Collection; import java.util.Date; import java.util.HashMap; -import java.util.Map; -import java.util.List; import java.util.Iterator; -import java.util.SortedMap; // <- IA/HERITRIX CHANGE -import java.util.TreeMap; // <- IA/HERITRIX CHANGE +import java.util.Map; +import java.util.SortedMap; import java.util.concurrent.ConcurrentSkipListMap; -import org.apache.commons.httpclient.cookie.CookieSpec; +import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import com.sleepycat.collections.StoredIterator; // <- IA/HERITRIX CHANGE +import com.sleepycat.collections.StoredIterator; /** * <p> @@ -67,7 +65,6 @@ * @version $Revision$ $Date$ * */ -@SuppressWarnings({"unchecked","unused"}) // <- IA/HERITRIX CHANGE public class HttpState { // ----------------------------------------------------- Instance Variables @@ -76,13 +73,13 @@ public class HttpState { * Map of {@link Credentials credentials} by realm that this * HTTP state contains. */ - private HashMap credMap = new HashMap(); + private HashMap<AuthScope, Credentials> credMap = new HashMap<AuthScope, Credentials>(); /** * Map of {@link Credentials proxy credentials} by realm that this * HTTP state contains */ - private HashMap proxyCred = new HashMap(); + private HashMap<AuthScope, Credentials> proxyCred = new HashMap<AuthScope, Credentials>(); // BEGIN IA/HERITRIX CHANGES // /** @@ -92,7 +89,7 @@ public class HttpState { /** * SortedMap of {@link Cookie cookies} that this HTTP state contains. */ - private SortedMap cookiesMap = new ConcurrentSkipListMap(); + private SortedMap<String, Cookie> cookiesMap = new ConcurrentSkipListMap<String, Cookie>(); // END IA/HERITRIX CHANGES private boolean preemptive = false; @@ -200,8 +197,8 @@ public synchronized Cookie[] getCookies() { // BEGIN IA/HERITRIX CHANGES // PRIOR IMPL & COMPARISON HARNESS LEFT COMMENTED OUT FOR TEMPORARY REFERENCE // Cookie[] arrayListAnswer = (Cookie[]) (cookiesArrayList.toArray(new Cookie[cookiesArrayList.size()])); - ArrayList arrayableCookies = new ArrayList(); - Iterator iter = cookiesMap.values().iterator(); + ArrayList<Cookie> arrayableCookies = new ArrayList<Cookie>(); + Iterator<Cookie> iter = cookiesMap.values().iterator(); while(iter.hasNext()) { arrayableCookies.add(iter.next()); } @@ -226,7 +223,7 @@ public synchronized Cookie[] getCookies() { * * @return sorter map of {@link Cookie cookies} */ - public SortedMap getCookiesMap() { + public SortedMap<String, Cookie> getCookiesMap() { return cookiesMap; } @@ -236,7 +233,7 @@ public SortedMap getCookiesMap() { * * @param map alternate sorted map to use to store cookies */ - public void setCookiesMap(SortedMap map) { + public void setCookiesMap(SortedMap<String, Cookie> map) { this.cookiesMap = map; } // END IA/HERITRIX ADDITIONS @@ -321,9 +318,9 @@ public synchronized boolean purgeExpiredCookies(Date date) { // } // } boolean removed = false; - Iterator it = cookiesMap.values().iterator(); + Iterator<Cookie> it = cookiesMap.values().iterator(); while (it.hasNext()) { - if (((Cookie) (it.next())).isExpired(date)) { + if (it.next().isExpired(date)) { it.remove(); removed = true; } @@ -457,15 +454,15 @@ public synchronized void setCredentials(final AuthScope authscope, final Credent * @return the credentials * */ - private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) { + private static Credentials matchCredentials(final HashMap<AuthScope, Credentials> map, final AuthScope authscope) { // see if we get a direct hit - Credentials creds = (Credentials)map.get(authscope); + Credentials creds = map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; - Iterator items = map.keySet().iterator(); + Iterator<AuthScope> items = map.keySet().iterator(); while (items.hasNext()) { AuthScope current = (AuthScope)items.next(); int factor = authscope.match(current); @@ -649,12 +646,12 @@ public synchronized String toString() { * @param credMap The credentials. * @return The string representation. */ - private static String getCredentialsStringRepresentation(final Map credMap) { + private static String getCredentialsStringRepresentation(final Map<AuthScope, Credentials> credMap) { StringBuffer sbResult = new StringBuffer(); - Iterator iter = credMap.keySet().iterator(); + Iterator<AuthScope> iter = credMap.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); - Credentials cred = (Credentials) credMap.get(key); + Credentials cred = credMap.get(key); if (sbResult.length() > 0) { sbResult.append(", "); } @@ -670,11 +667,11 @@ private static String getCredentialsStringRepresentation(final Map credMap) { * @param cookies The cookies * @return The string representation. */ - private static String getCookiesStringRepresentation(final Collection cookies) { // <- IA/HERITRIX CHANGE + private static String getCookiesStringRepresentation(final Collection<Cookie> cookies) { // <- IA/HERITRIX CHANGE StringBuffer sbResult = new StringBuffer(); - Iterator iter = cookies.iterator(); + Iterator<Cookie> iter = cookies.iterator(); while (iter.hasNext()) { - Cookie ck = (Cookie) iter.next(); + Cookie ck = iter.next(); if (sbResult.length() > 0) { sbResult.append("#"); } diff --git a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java index 5b14bff4e..46be9ff8c 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java +++ b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java @@ -51,7 +51,6 @@ * * @since 2.0 */ -@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE public interface CookieSpec { /** Path delimiter */ @@ -140,7 +139,7 @@ void validate(String host, int port, String path, boolean secure, * * @param datepatterns collection of date patterns */ - void setValidDateFormats(Collection datepatterns); + void setValidDateFormats(Collection<String> datepatterns); /** * Returns the {@link Collection} of date patterns used for parsing. The String patterns are compatible @@ -148,7 +147,7 @@ void validate(String host, int port, String path, boolean secure, * * @return collection of date patterns */ - Collection getValidDateFormats(); + Collection<String> getValidDateFormats(); /** * Determines if a Cookie matches a location. @@ -195,7 +194,7 @@ Cookie[] match(String host, int port, String path, boolean secure, * * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted - * (currenlty ignored) + * (currently ignored) * @param path the path to which the request is being submitted * @param secure <tt>true</tt> if the request is using a secure protocol * @param cookies SortedMap of <tt>Cookie</tt>s to be matched @@ -203,7 +202,7 @@ Cookie[] match(String host, int port, String path, boolean secure, * @return <tt>true</tt> if the cookie should be submitted with a request * with given attributes, <tt>false</tt> otherwise. */ - Cookie[] match(String domain, int port, String path, boolean secure, SortedMap cookiesMap); + Cookie[] match(String domain, int port, String path, boolean secure, SortedMap<String, Cookie> cookiesMap); // END IA/HERITRIX CHANGES /** diff --git a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java index 406e8ed34..170ab06f0 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java +++ b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java @@ -65,14 +65,13 @@ * * @since 2.0 */ -@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE public class CookieSpecBase implements CookieSpec { /** Log object */ protected static final Log LOG = LogFactory.getLog(CookieSpec.class); /** Valid date patterns */ - private Collection datepatterns = null; + private Collection<String> datepatterns = null; /** Default constructor */ public CookieSpecBase() { @@ -346,11 +345,13 @@ public void parseAttribute( } - public Collection getValidDateFormats() { + @Override + public Collection<String> getValidDateFormats() { return this.datepatterns; } - public void setValidDateFormats(final Collection datepatterns) { + @Override + public void setValidDateFormats(final Collection<String> datepatterns) { this.datepatterns = datepatterns; } @@ -580,7 +581,7 @@ public Cookie[] match(String host, int port, String path, if (cookies == null) { return null; } - List matching = new LinkedList(); + List<Cookie> matching = new LinkedList<Cookie>(); for (int i = 0; i < cookies.length; i++) { if (match(host, port, path, secure, cookies[i])) { addInPathOrder(matching, cookies[i]); @@ -606,9 +607,9 @@ public Cookie[] match(String host, int port, String path, * @param cookies SortedMap of <tt>Cookie</tt>s to be matched * @return an array of <tt>Cookie</tt>s matching the criterium */ - + @Override public Cookie[] match(String host, int port, String path, - boolean secure, final SortedMap cookies) { + boolean secure, final SortedMap<String, Cookie> cookies) { LOG.trace("enter CookieSpecBase.match(" + "String, int, String, boolean, SortedMap)"); @@ -616,7 +617,7 @@ public Cookie[] match(String host, int port, String path, if (cookies == null) { return null; } - List matching = new LinkedList(); + List<Cookie> matching = new LinkedList<Cookie>(); InternetDomainName domain; try { domain = InternetDomainName.fromLenient(host); @@ -626,7 +627,7 @@ public Cookie[] match(String host, int port, String path, String candidate = (domain!=null) ? domain.name() : host; while(candidate!=null) { - Iterator iter = cookies.subMap(candidate, + Iterator<Cookie> iter = cookies.subMap(candidate, candidate + Cookie.DOMAIN_OVERBOUNDS).values().iterator(); while (iter.hasNext()) { Cookie cookie = (Cookie) (iter.next()); @@ -656,7 +657,7 @@ public Cookie[] match(String host, int port, String path, * @param list - the list to add the cookie to * @param addCookie - the Cookie to add to list */ - private static void addInPathOrder(List list, Cookie addCookie) { + private static void addInPathOrder(List<Cookie> list, Cookie addCookie) { int i = 0; for (i = 0; i < list.size(); i++) { diff --git a/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java b/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java index 82e1a105b..8da6f6f92 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java +++ b/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java @@ -42,7 +42,6 @@ * * @since 3.0 */ -@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE public class IgnoreCookiesSpec implements CookieSpec { /** @@ -63,14 +62,16 @@ public Cookie[] parse(String host, int port, String path, boolean secure, String /** * @return <code>null</code> */ - public Collection getValidDateFormats() { + @Override + public Collection<String> getValidDateFormats() { return null; } /** * Does nothing. */ - public void setValidDateFormats(Collection datepatterns) { + @Override + public void setValidDateFormats(Collection<String> datepatterns) { } /** @@ -152,8 +153,9 @@ public boolean pathMatch(final String path, final String topmostPath) { } // BEGIN IA/HERITRIX ADDITION + @Override public Cookie[] match(String domain, int port, String path, boolean secure, - SortedMap cookiesMap) { + SortedMap<String, Cookie> cookiesMap) { return new Cookie[0]; } // END IA/HERITRIX CHANGE diff --git a/commons/src/main/java/org/archive/bdb/AutoKryo.java b/commons/src/main/java/org/archive/bdb/AutoKryo.java index 1306beec8..f12879601 100644 --- a/commons/src/main/java/org/archive/bdb/AutoKryo.java +++ b/commons/src/main/java/org/archive/bdb/AutoKryo.java @@ -26,15 +26,15 @@ */ @SuppressWarnings("unchecked") public class AutoKryo extends Kryo { - protected ArrayList<Class> registeredClasses = new ArrayList<Class>(); + protected ArrayList<Class<?>> registeredClasses = new ArrayList<Class<?>>(); @Override - protected void handleUnregisteredClass(Class type) { + protected void handleUnregisteredClass(@SuppressWarnings("rawtypes") Class type) { System.err.println("UNREGISTERED FOR KRYO "+type+" in "+registeredClasses.get(0)); super.handleUnregisteredClass(type); } - public void autoregister(Class type) { + public void autoregister(Class<?> type) { if (registeredClasses.contains(type)) { return; } @@ -43,7 +43,7 @@ public void autoregister(Class type) { invokeStatic( "autoregisterTo", type, - new Class[]{ ((Class)AutoKryo.class), }, + new Class[]{ ((Class<?>)AutoKryo.class), }, new Object[] { this, }); } catch (Exception e) { register(type); @@ -88,7 +88,7 @@ public <T> T newInstance(Class<T> type) { throw ex; } - protected Object invokeStatic(String method, Class clazz, Class[] types, Object[] args) throws Exception { + protected Object invokeStatic(String method, Class<?> clazz, Class<?>[] types, Object[] args) throws Exception { return clazz.getMethod(method, types).invoke(null, args); } } diff --git a/commons/src/main/java/org/archive/bdb/KryoBinding.java b/commons/src/main/java/org/archive/bdb/KryoBinding.java index 70002973a..51e547a7d 100644 --- a/commons/src/main/java/org/archive/bdb/KryoBinding.java +++ b/commons/src/main/java/org/archive/bdb/KryoBinding.java @@ -51,8 +51,7 @@ protected WeakReference<ObjectBuffer> initialValue() { * @param baseClass is the base class for serialized objects stored using * this binding */ - @SuppressWarnings("unchecked") - public KryoBinding(Class baseClass) { + public KryoBinding(Class<K> baseClass) { this.baseClass = baseClass; kryo.autoregister(baseClass); // TODO: reevaluate if explicit registration should be required diff --git a/commons/src/main/java/org/archive/io/Arc2Warc.java b/commons/src/main/java/org/archive/io/Arc2Warc.java index 5cd99c959..eedd848f3 100644 --- a/commons/src/main/java/org/archive/io/Arc2Warc.java +++ b/commons/src/main/java/org/archive/io/Arc2Warc.java @@ -199,7 +199,7 @@ public static void main(String [] args) "Force overwrite of target file.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); - List cmdlineArgs = cmdline.getArgList(); + List<String> cmdlineArgs = cmdline.getArgList(); Option [] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); @@ -230,7 +230,7 @@ public static void main(String [] args) if (cmdlineArgs.size() != 2) { usage(formatter, options, 0); } - (new Arc2Warc()).transform(new File(cmdlineArgs.get(0).toString()), - new File(cmdlineArgs.get(1).toString()), force); + (new Arc2Warc()).transform(new File(cmdlineArgs.get(0)), + new File(cmdlineArgs.get(1)), force); } } diff --git a/commons/src/main/java/org/archive/io/Warc2Arc.java b/commons/src/main/java/org/archive/io/Warc2Arc.java index eb611ceaa..3cd1142f7 100644 --- a/commons/src/main/java/org/archive/io/Warc2Arc.java +++ b/commons/src/main/java/org/archive/io/Warc2Arc.java @@ -173,7 +173,6 @@ protected boolean isARCType(final String mimetype) { * @throws IOException * @throws java.text.ParseException */ - @SuppressWarnings("unchecked") public static void main(String [] args) throws ParseException, IOException, java.text.ParseException { Options options = new Options(); @@ -187,7 +186,8 @@ public static void main(String [] args) "Suffix to use on created ARC files, else uses default.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); - List cmdlineArgs = cmdline.getArgList(); + @SuppressWarnings("unchecked") + List<String> cmdlineArgs = cmdline.getArgList(); Option [] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); diff --git a/commons/src/main/java/org/archive/io/arc/ARCReader.java b/commons/src/main/java/org/archive/io/arc/ARCReader.java index fcb6c15ba..7f85cc2a8 100644 --- a/commons/src/main/java/org/archive/io/arc/ARCReader.java +++ b/commons/src/main/java/org/archive/io/arc/ARCReader.java @@ -453,7 +453,7 @@ public static void main(String [] args) options.addOption(new Option("p","parse", false, "Parse headers.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); - List cmdlineArgs = cmdline.getArgList(); + List<String> cmdlineArgs = cmdline.getArgList(); Option [] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); @@ -529,8 +529,7 @@ public static void main(String [] args) arc.setParseHttpHeaders(parse); outputRecord(arc, format); } else { - for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { - String urlOrPath = (String)i.next(); + for (String urlOrPath : cmdlineArgs) { try { ARCReader r = ARCReaderFactory.get(urlOrPath); r.setStrict(strict); diff --git a/commons/src/main/java/org/archive/io/warc/WARCReader.java b/commons/src/main/java/org/archive/io/warc/WARCReader.java index 3794a23d8..98a7e0248 100644 --- a/commons/src/main/java/org/archive/io/warc/WARCReader.java +++ b/commons/src/main/java/org/archive/io/warc/WARCReader.java @@ -192,13 +192,13 @@ public static void createCDXIndexFile(String urlOrPath) * @throws IOException * @throws java.text.ParseException */ - @SuppressWarnings("unchecked") public static void main(String [] args) throws ParseException, IOException, java.text.ParseException { Options options = getOptions(); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); - List cmdlineArgs = cmdline.getArgList(); + @SuppressWarnings("unchecked") + List<String> cmdlineArgs = cmdline.getArgList(); Option [] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); @@ -264,7 +264,7 @@ public static void main(String [] args) r.setStrict(strict); outputRecord(r, format); } else { - for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { + for (Iterator<String> i = cmdlineArgs.iterator(); i.hasNext();) { String urlOrPath = (String)i.next(); try { WARCReader r = WARCReaderFactory.get(urlOrPath); diff --git a/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java b/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java index 7e5301410..11c5faf7f 100644 --- a/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java +++ b/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java @@ -63,8 +63,7 @@ public BeanFieldsPatternValidator(Class<?> clazz, String ... fieldsPatterns) { } } - @SuppressWarnings("unchecked") - public boolean supports(Class cls) { + public boolean supports(Class<?> cls) { return this.clazz.isAssignableFrom(cls); } diff --git a/commons/src/main/java/org/archive/spring/ConfigFileEditor.java b/commons/src/main/java/org/archive/spring/ConfigFileEditor.java index 7bb897bab..c55daa792 100644 --- a/commons/src/main/java/org/archive/spring/ConfigFileEditor.java +++ b/commons/src/main/java/org/archive/spring/ConfigFileEditor.java @@ -23,8 +23,9 @@ * PropertyEditor allowing Strings to become ConfigFile instances. * */ -public class ConfigFileEditor<T> extends ConfigPathEditor { +public class ConfigFileEditor extends ConfigPathEditor { + @Override public Object getValue() { ConfigFile c = new ConfigFile(null,value.toString()); return c; diff --git a/commons/src/main/java/org/archive/spring/ConfigPathEditor.java b/commons/src/main/java/org/archive/spring/ConfigPathEditor.java index 03b63ca1a..531b3adce 100644 --- a/commons/src/main/java/org/archive/spring/ConfigPathEditor.java +++ b/commons/src/main/java/org/archive/spring/ConfigPathEditor.java @@ -29,63 +29,75 @@ * PropertyEditor allowing Strings to become ConfigPath instances. * */ -public class ConfigPathEditor<T> implements PropertyEditor { +public class ConfigPathEditor implements PropertyEditor { protected Object value; + @Override public void addPropertyChangeListener(PropertyChangeListener listener) { // TODO Auto-generated method stub } + @Override public String getAsText() { // TODO Auto-generated method stub return null; } + @Override public Component getCustomEditor() { // TODO Auto-generated method stub return null; } + @Override public String getJavaInitializationString() { // TODO Auto-generated method stub return null; } + @Override public String[] getTags() { // TODO Auto-generated method stub return null; } + @Override public Object getValue() { ConfigPath c = new ConfigPath(null,value.toString()); //c.put(value); return c; } + @Override public boolean isPaintable() { // TODO Auto-generated method stub return false; } + @Override public void paintValue(Graphics gfx, Rectangle box) { // TODO Auto-generated method stub } + @Override public void removePropertyChangeListener(PropertyChangeListener listener) { // TODO Auto-generated method stub } + @Override public void setAsText(String text) throws IllegalArgumentException { setValue(text); } + @Override public void setValue(Object value) { this.value = value; } + @Override public boolean supportsCustomEditor() { // TODO Auto-generated method stub return false; diff --git a/commons/src/main/java/org/archive/util/ArchiveUtils.java b/commons/src/main/java/org/archive/util/ArchiveUtils.java index 614cae76b..fce854d1f 100644 --- a/commons/src/main/java/org/archive/util/ArchiveUtils.java +++ b/commons/src/main/java/org/archive/util/ArchiveUtils.java @@ -749,13 +749,12 @@ public static String shortReportLine(Reporter rep) { * @param obj Object to prettify * @return prettified String */ - @SuppressWarnings("unchecked") public static String prettyString(Object obj) { // these things have to checked and casted unfortunately if (obj instanceof Object[]) { return prettyString((Object[]) obj); } else if (obj instanceof Map) { - return prettyString((Map) obj); + return prettyString((Map<?, ?>) obj); } else { return "<"+obj+">"; } @@ -767,8 +766,7 @@ public static String prettyString(Object obj) { * @param Map * @return prettified (in curly brackets) string of Map contents */ - @SuppressWarnings("unchecked") - public static String prettyString(Map map) { + public static String prettyString(Map<?, ?> map) { StringBuilder builder = new StringBuilder(); builder.append("{ "); boolean needsComma = false; diff --git a/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java b/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java index 0a6d1099d..a4fc257fc 100644 --- a/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java +++ b/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java @@ -151,7 +151,6 @@ public ObjectIdentityBdbCache() { * @param classCatalog * @throws DatabaseException */ - @SuppressWarnings("unchecked") public void initialize(final Environment env, String dbName, final Class valueClass, final StoredClassCatalog classCatalog) throws DatabaseException { @@ -523,10 +522,9 @@ final public V doctoredGet() { private static class SoftEntry<V> extends SoftReference<V> { PhantomEntry<V> phantom; - @SuppressWarnings("unchecked") public SoftEntry(String key, V referent, ReferenceQueue<V> q) { super(referent, q); - this.phantom = new PhantomEntry(key, referent); // unchecked cast + this.phantom = new PhantomEntry<V>(key, referent); } public V get() { diff --git a/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java b/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java index 70cd213c9..84504e79d 100644 --- a/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java +++ b/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java @@ -124,7 +124,6 @@ public ObjectIdentityBdbManualCache() { * @param classCatalog * @throws DatabaseException */ - @SuppressWarnings("unchecked") public void initialize(final Environment env, String dbName, final Class valueClass, final StoredClassCatalog classCatalog) throws DatabaseException { diff --git a/commons/src/main/java/org/archive/util/PrefixFinder.java b/commons/src/main/java/org/archive/util/PrefixFinder.java index 098a8b5b7..9d22b4c1f 100644 --- a/commons/src/main/java/org/archive/util/PrefixFinder.java +++ b/commons/src/main/java/org/archive/util/PrefixFinder.java @@ -76,18 +76,17 @@ public static List<String> find(SortedSet<String> set, String input) { } - @SuppressWarnings("unchecked") protected static SortedSet<String> headSetInclusive(SortedSet<String> set, String input) { // use NavigableSet inclusive version if available if(set instanceof NavigableSet) { - return ((NavigableSet)set).headSet(input, true); + return ((NavigableSet<String>)set).headSet(input, true); } // use Stored*Set inclusive version if available if(set instanceof StoredSortedKeySet) { - return ((StoredSortedKeySet)set).headSet(input, true); + return ((StoredSortedKeySet<String>)set).headSet(input, true); } if(set instanceof StoredSortedValueSet) { - return ((StoredSortedValueSet)set).headSet(input, true); + return ((StoredSortedValueSet<String>)set).headSet(input, true); } // Use synthetic "one above" trick // NOTE: because '\0' sorts in the middle in "java modified UTF-8", @@ -125,15 +124,14 @@ public static List<String> findKeys(SortedMap<String,?> map, String input) { } - @SuppressWarnings("unchecked") private static SortedMap<String, ?> headMapInclusive(SortedMap<String, ?> map, String input) { // use NavigableMap inclusive version if available if(map instanceof NavigableMap) { - return ((NavigableMap)map).headMap(input, true); + return ((NavigableMap<String, ?>)map).headMap(input, true); } // use StoredSortedMap inclusive version if available if(map instanceof StoredSortedMap) { - return ((StoredSortedMap)map).headMap(input, true); + return ((StoredSortedMap<String, ?>)map).headMap(input, true); } // Use synthetic "one above" trick // NOTE: because '\0' sorts in the middle in "java modified UTF-8", diff --git a/commons/src/main/java/st/ata/util/FPGenerator.java b/commons/src/main/java/st/ata/util/FPGenerator.java index e742e4c38..20a8702d3 100644 --- a/commons/src/main/java/st/ata/util/FPGenerator.java +++ b/commons/src/main/java/st/ata/util/FPGenerator.java @@ -42,9 +42,7 @@ and use <code>reduce</code> to reduce to a fingerprint after the loop. */ - // Tested by: TestFPGenerator -@SuppressWarnings("unchecked") public final class FPGenerator { /** Return a fingerprint generator. The fingerprints generated @@ -64,7 +62,7 @@ public static FPGenerator make(long polynomial, int degree) { } return fpgen; } - private static final Hashtable generators = new Hashtable(10); + private static final Hashtable<Long, FPGenerator> generators = new Hashtable<Long, FPGenerator>(10); private static final long zero = 0; private static final long one = 0x8000000000000000L; diff --git a/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java b/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java index e8563b695..035149fb6 100644 --- a/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java +++ b/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java @@ -74,7 +74,6 @@ public void testSortedMap() { testUrlsNoMatch(map); } - @SuppressWarnings("unchecked") public void testStoredSortedMap() throws Exception { EnvironmentConfig config = new EnvironmentConfig(); config.setAllowCreate(true); @@ -89,7 +88,7 @@ public void testStoredSortedMap() throws Exception { dbConfig.setDeferredWrite(true); Database db = bdbEnvironment.openDatabase(null, "test", dbConfig); - StoredSortedMap ssm = new StoredSortedMap(db, new StringBinding(), new StringBinding(), true); + StoredSortedMap<String, String> ssm = new StoredSortedMap<String, String>(db, new StringBinding(), new StringBinding(), true); testUrlsNoMatch(ssm); db.close(); bdbEnvironment.close(); diff --git a/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java b/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java index 765b7bb55..7c258d39b 100644 --- a/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java +++ b/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java @@ -25,8 +25,7 @@ public class CheckpointValidator implements Validator { @Override - @SuppressWarnings("unchecked") - public boolean supports(Class cls) { + public boolean supports(Class<?> cls) { return Checkpoint.class.isAssignableFrom(cls); } diff --git a/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java b/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java index 0c8901452..fc6f249b1 100644 --- a/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java +++ b/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java @@ -33,7 +33,7 @@ * * @contributor gojomo */ -public class CrawlLimitEnforcer implements ApplicationListener { +public class CrawlLimitEnforcer implements ApplicationListener<ApplicationEvent> { /** * Maximum number of bytes to download. Once this number is exceeded @@ -80,6 +80,7 @@ public void setCrawlController(CrawlController controller) { this.controller = controller; } + @Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof StatSnapshotEvent) { CrawlStatSnapshot snapshot = ((StatSnapshotEvent)event).getSnapshot(); diff --git a/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java b/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java index c9df326ed..3b1cba657 100644 --- a/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java +++ b/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java @@ -88,7 +88,7 @@ public abstract class AbstractFrontier HasKeyedProperties, ExtractorParameters, CrawlUriReceiver, - ApplicationListener { + ApplicationListener<ApplicationEvent> { private static final long serialVersionUID = 555881755284996860L; private static final Logger logger = Logger .getLogger(AbstractFrontier.class.getName()); @@ -1130,6 +1130,7 @@ public String shortReportLine() { return ArchiveUtils.shortReportLine(this); } + @Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof CrawlStateEvent) { CrawlStateEvent event1 = (CrawlStateEvent)event; diff --git a/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java b/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java index 7031b99e9..b54ea9ed7 100644 --- a/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java +++ b/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java @@ -96,7 +96,6 @@ public static void main(String[] args) throws DatabaseException, IOException { * @throws UnsupportedEncodingException * @throws IOException */ - @SuppressWarnings("unchecked") private static void main2args(String[] args) throws DatabaseException, FileNotFoundException, UnsupportedEncodingException, IOException { File source = new File(args[0]); @@ -110,16 +109,16 @@ private static void main2args(String[] args) throws DatabaseException, null, PersistProcessor.URI_HISTORY_DBNAME, PersistProcessor.HISTORY_DB_CONFIG.toDatabaseConfig()); - StoredSortedMap historyMap = new StoredSortedMap(historyDB, - new StringBinding(), new SerialBinding(classCatalog, - Map.class), true); + @SuppressWarnings({ "rawtypes", "unchecked" }) + StoredSortedMap<String, Object> historyMap = new StoredSortedMap<String, Object>(historyDB, + new StringBinding(), new SerialBinding(classCatalog, Map.class), true); int count = 0; if(source.isFile()) { // scan log, writing to database BufferedReader br = ArchiveUtils.getBufferedReader(source); - Iterator iter = new LineReadingIterator(br); + Iterator<String> iter = new LineReadingIterator(br); while(iter.hasNext()) { String line = (String) iter.next(); String[] splits = line.split("\\s"); @@ -130,9 +129,10 @@ private static void main2args(String[] args) throws DatabaseException, } String key = PersistProcessor.persistKeyFor(uri); int precedence = Integer.parseInt(splits[1]); - Map<String,Object> map = (Map<String,Object>)historyMap.get(key); + @SuppressWarnings("unchecked") + Map<String, Object> map = (Map<String, Object>)historyMap.get(key); if (map==null) { - map = new HashMap<String,Object>(); + map = new HashMap<String, Object>(); } map.put(A_PRECALC_PRECEDENCE, precedence); historyMap.put(key,map); diff --git a/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java b/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java index f4362eada..3dc107678 100644 --- a/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java +++ b/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java @@ -66,29 +66,27 @@ public void setBdbModule(BdbModule bdb) { this.bdb = bdb; } - @SuppressWarnings("unchecked") - protected StoredSortedMap store; + protected StoredSortedMap<String, ?> store; protected Database historyDb; - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) public void start() { if(isRunning()) { return; - } + } + store = null; String dbName = PersistProcessor.URI_HISTORY_DBNAME; - StoredSortedMap historyMap; try { StoredClassCatalog classCatalog = bdb.getClassCatalog(); BdbModule.BdbConfig dbConfig = PersistProcessor.HISTORY_DB_CONFIG; - historyDb = bdb.openDatabase(dbName, dbConfig, true); - historyMap = new StoredSortedMap(historyDb, - new StringBinding(), new SerialBinding(classCatalog, - Map.class), true); + historyDb = bdb.openDatabase(dbName, dbConfig, true); + SerialBinding sb = new SerialBinding(classCatalog, Map.class); + StoredSortedMap historyMap = new StoredSortedMap(historyDb, new StringBinding(), sb, true); + store = historyMap; } catch (DatabaseException e) { throw new RuntimeException(e); } - store = historyMap; } public boolean isRunning() { @@ -141,11 +139,10 @@ protected int calculatePrecedence(CrawlURI curi) { * double-loading * @param curi CrawlURI to receive prior state data */ - @SuppressWarnings("unchecked") protected void mergePrior(CrawlURI curi) { - Map<String, Map> prior = null; String key = PersistProcessor.persistKeyFor(curi); - prior = (Map<String,Map>) store.get(key); + @SuppressWarnings({ "rawtypes", "unchecked" }) + Map<String,Map> prior = (Map<String, Map>) store.get(key); if(prior!=null) { // merge in keys curi.getData().putAll(prior); diff --git a/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java b/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java index 7afa3e129..ec13f78d5 100644 --- a/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java +++ b/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java @@ -31,7 +31,7 @@ * * @contributor Kristinn Sigur&eth;sson */ -public class DiskSpaceMonitor implements ApplicationListener { +public class DiskSpaceMonitor implements ApplicationListener<ApplicationEvent> { private static final Logger logger = Logger.getLogger(DiskSpaceMonitor.class.getName()); protected List<String> monitorPaths = new ArrayList<String>(); diff --git a/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java b/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java index aa1bab8c2..c5d9efcc8 100644 --- a/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java +++ b/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java @@ -23,7 +23,6 @@ import java.beans.PropertyDescriptor; import java.io.File; import java.io.PrintWriter; -import java.net.URLEncoder; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -177,7 +176,7 @@ protected void writeNestedNames(PrintWriter pw, Object obj, String prefix, Set<O } } if(obj instanceof Iterable) { - for (Object next : (Iterable)obj) { + for (Object next : (Iterable<Object>)obj) { writeNestedNames(pw, next, prefix, alreadyWritten); } } @@ -411,7 +410,6 @@ private IdentityHashMap<Object, String> getBeanToNameMap() { * @param alreadyWritten Set of objects to not redundantly write * @param beanPathPrefix beanPath prefix to apply to sub fields browse links */ - @SuppressWarnings("unchecked") protected void writeObject(PrintWriter pw, String field, Object object, HashSet<Object> alreadyWritten, String beanPathPrefix) { String key = getBeanToNameMap().get(object); String close = ""; @@ -497,14 +495,15 @@ protected void writeObject(PrintWriter pw, String field, Object object, HashSet< writeObject(pw, i+"", list.get(i), alreadyWritten, beanPathPrefix); } } else if(object instanceof Iterable) { - for (Object next : (Iterable)object) { + @SuppressWarnings("unchecked") + Iterable<Object> itbl = (Iterable<Object>)object; + for (Object next : itbl) { writeObject(pw, "#", next, alreadyWritten, null); } } if(object instanceof Map) { - for (Object next : ((Map)object).entrySet()) { + for (Map.Entry<?, ?> entry : ((Map<?, ?>)object).entrySet()) { // TODO: protect against giant maps? - Map.Entry<?, ?> entry = (Map.Entry<?, ?>)next; if(beanPath!=null) { beanPathPrefix = beanPath+"["; } diff --git a/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java b/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java index 80775e19a..c25bfaeb7 100644 --- a/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java +++ b/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java @@ -53,7 +53,7 @@ * @contributor gojomo */ public class SheetOverlaysManager implements -BeanFactoryAware, OverlayMapsSource, ApplicationListener { +BeanFactoryAware, OverlayMapsSource, ApplicationListener<ApplicationEvent> { private static final Logger logger = Logger.getLogger(SheetOverlaysManager.class.getName()); @@ -186,6 +186,7 @@ public Map<String, Object> getOverlayMap(String name) { * properties. * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent) */ + @Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof ContextRefreshedEvent) { for(Sheet s: sheetsByName.values()) { diff --git a/modules/src/main/java/org/archive/modules/CrawlURI.java b/modules/src/main/java/org/archive/modules/CrawlURI.java index cfc01bf49..c923195cb 100644 --- a/modules/src/main/java/org/archive/modules/CrawlURI.java +++ b/modules/src/main/java/org/archive/modules/CrawlURI.java @@ -891,7 +891,7 @@ public Map<String,Object> getPersistentDataMap() { */ public Set<Credential> getCredentials() { @SuppressWarnings("unchecked") - Set<Credential> r = (Set)getData().get(A_CREDENTIALS_KEY); + Set<Credential> r = (Set<Credential>)getData().get(A_CREDENTIALS_KEY); if (r == null) { r = new HashSet<Credential>(); getData().put(A_CREDENTIALS_KEY, r); @@ -1250,7 +1250,7 @@ public FetchType getFetchType() { public Collection<Throwable> getNonFatalFailures() { @SuppressWarnings("unchecked") - List<Throwable> list = (List)getData().get(A_NONFATAL_ERRORS); + List<Throwable> list = (List<Throwable>)getData().get(A_NONFATAL_ERRORS); if (list == null) { list = new ArrayList<Throwable>(); getData().put(A_NONFATAL_ERRORS, list); @@ -1505,7 +1505,7 @@ public void makeHeritable(String key) { */ public void makeNonHeritable(String key) { @SuppressWarnings("unchecked") - HashSet heritableKeys = (HashSet)data.get(A_HERITABLE_KEYS); + HashSet<String> heritableKeys = (HashSet<String>)data.get(A_HERITABLE_KEYS); if(heritableKeys == null) { return; } diff --git a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java index 529e8a62b..c3332dc3d 100644 --- a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java +++ b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java @@ -18,7 +18,6 @@ */ package org.archive.modules.canonicalize; -import java.util.regex.Pattern; /** * Strip cold fusion session ids. diff --git a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java index ec3ad1193..692759993 100644 --- a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java +++ b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java @@ -18,8 +18,6 @@ */ package org.archive.modules.canonicalize; -import java.util.regex.Pattern; - /** * Strip known session ids. * @author stack diff --git a/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java b/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java index b0f61ada5..987a23edc 100644 --- a/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java +++ b/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java @@ -34,7 +34,6 @@ * * @author Igor Ranitovic */ -@SuppressWarnings("unchecked") public class CustomSWFTags extends SWFTagTypesImpl { protected SWFActions actions; @@ -43,18 +42,21 @@ public CustomSWFTags(SWFActions a) { actions = a; } - public SWFActions tagDefineButton(int id, Vector buttonRecords) + @Override + public SWFActions tagDefineButton(int id, @SuppressWarnings("rawtypes") Vector buttonRecords) throws IOException { return actions; } + @Override public SWFActions tagDefineButton2(int id, boolean trackAsMenu, - Vector buttonRecord2s) throws IOException { + @SuppressWarnings("rawtypes") Vector buttonRecord2s) throws IOException { return actions; } + @Override public SWFActions tagDoAction() throws IOException { return actions; } @@ -63,10 +65,12 @@ public SWFActions tagDoInActions(int spriteId) throws IOException { return actions; } + @Override public SWFTagTypes tagDefineSprite(int id) throws IOException { return this; } + @Override public SWFActions tagPlaceObject2(boolean isMove, int clipDepth, int depth, int charId, Matrix matrix, AlphaTransform cxform, int ratio, String name, int clipActionFlags) throws IOException { diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java index 994b0a1d6..133b152e7 100644 --- a/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java +++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java @@ -58,7 +58,6 @@ public class ExtractorJS extends ContentExtractor { private static final long serialVersionUID = 2L; - @SuppressWarnings("unused") private static Logger LOGGER = Logger.getLogger("org.archive.crawler.extractor.ExtractorJS"); diff --git a/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java index 3fcbed636..5b782da32 100644 --- a/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java +++ b/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java @@ -49,7 +49,6 @@ import au.id.jericho.lib.html.FormControl; import au.id.jericho.lib.html.FormControlType; import au.id.jericho.lib.html.FormField; -import au.id.jericho.lib.html.FormFields; import au.id.jericho.lib.html.HTMLElementName; import au.id.jericho.lib.html.Source; import au.id.jericho.lib.html.StartTagType; @@ -94,7 +93,7 @@ public JerichoExtractorHTML(String name) { "parser, the Jericho HTML Parser, reads the whole " + "document into memory for " + "parsing - thus this extractor has an inherent OOME risk. " + - "This OOME risk can be reduced/eleminated by limiting the " + + "This OOME risk can be reduced/eliminated by limiting the " + "size of documents to be parsed (i.e. using " + "NotExceedsDocumentLengthTresholdDecideRule). "); }*/ @@ -105,8 +104,7 @@ public JerichoExtractorHTML() { private static List<Attribute> findOnAttributes(Attributes attributes) { List<Attribute> result = new LinkedList<Attribute>(); - for (Iterator attrIter = attributes.iterator(); attrIter.hasNext();) { - Attribute attr = (Attribute) attrIter.next(); + for (Attribute attr : (Iterable<Attribute>)attributes) { if (attr.getKey().startsWith("on")) result.add(attr); } @@ -118,7 +116,7 @@ protected void processGeneralTag(CrawlURI curi, Element element, Attributes attributes) { Attribute attr; String attrValue; - List attrList; + List<Attribute> attrList; String elementName = element.getName(); // Just in case it's an OBJECT or APPLET tag @@ -163,7 +161,7 @@ protected void processGeneralTag(CrawlURI curi, Element element, } // ON_ if ((attrList = findOnAttributes(attributes)).size() != 0) { - for (Iterator attrIter = attrList.iterator(); attrIter.hasNext();) { + for (Iterator<Attribute> attrIter = attrList.iterator(); attrIter.hasNext();) { attr = (Attribute) attrIter.next(); CharSequence valueSegment = attr.getValueSegment(); if (valueSegment != null) @@ -370,21 +368,14 @@ protected void processForm(CrawlURI curi, Element element) { numberOfFormsProcessed.incrementAndGet(); // get all form fields - FormFields formFields = element.findFormFields(); - for (Iterator fieldsIter = formFields.iterator(); fieldsIter.hasNext();) { - // for each form field - FormField formField = (FormField) fieldsIter.next(); - + for (FormField formField : (Iterable<FormField>)element.findFormFields()) { // for each form control - for (Iterator controlIter = formField.getFormControls().iterator(); - controlIter.hasNext();) { - FormControl formControl = (FormControl) controlIter.next(); - + for (FormControl formControl : (Iterable<FormControl>)formField.getFormControls()) { // get name of control element (and URLEncode it) String controlName = formControl.getName(); // retrieve list of values - submit needs special handling - Collection controlValues; + Collection<String> controlValues; if (!(formControl.getFormControlType() == FormControlType.SUBMIT)) { controlValues = formControl.getValues(); @@ -394,9 +385,7 @@ protected void processForm(CrawlURI curi, Element element) { if (controlValues.size() > 0) { // for each value set - for (Iterator valueIter = controlValues.iterator(); - valueIter.hasNext();) { - String value = (String) valueIter.next(); + for (String value : controlValues) { queryURL += "&" + controlName + "=" + value; } } else { @@ -430,10 +419,8 @@ protected void processForm(CrawlURI curi, Element element) { */ protected void extract(CrawlURI curi, CharSequence cs) { Source source = new Source(cs); - List elements = source.findAllElements(StartTagType.NORMAL); - for (Iterator elementIter = elements.iterator(); - elementIter.hasNext();) { - Element element = (Element) elementIter.next(); + List<Element> elements = source.findAllElements(StartTagType.NORMAL); + for (Element element : elements) { String elementName = element.getName(); Attributes attributes; if (elementName.equals(HTMLElementName.META)) { diff --git a/modules/src/main/java/org/archive/modules/extractor/PDFParser.java b/modules/src/main/java/org/archive/modules/extractor/PDFParser.java index 9a44d59b8..8aa07cde0 100644 --- a/modules/src/main/java/org/archive/modules/extractor/PDFParser.java +++ b/modules/src/main/java/org/archive/modules/extractor/PDFParser.java @@ -199,7 +199,6 @@ protected void extractURIs(PdfObject entity){ PdfDictionary dictionary= (PdfDictionary)entity; - @SuppressWarnings("unchecked") Set<PdfName> allkeys = dictionary.getKeys(); for (PdfName key: allkeys) { PdfObject value = dictionary.get(key); @@ -219,11 +218,8 @@ protected void extractURIs(PdfObject entity){ }else if(entity.isArray()){ PdfArray array = (PdfArray)entity; - ArrayList arrayObjects = array.getArrayList(); - Iterator objectList = arrayObjects.iterator(); - - while(objectList.hasNext()){ - this.extractURIs( (PdfObject)objectList.next()); + for (PdfObject pdfObject : (Iterable<PdfObject>)array.getArrayList()) { + this.extractURIs(pdfObject); } // deal with indirect references diff --git a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java index c339b0f44..a92fe1ea9 100644 --- a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java +++ b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java @@ -743,14 +743,14 @@ protected void readResponseBody(HttpState state, * @param curi CrawlURI * @param rec HttpRecorder */ - @SuppressWarnings("unchecked") protected void setSizes(CrawlURI curi, Recorder rec) { // set reporting size curi.setContentSize(rec.getRecordedInput().getSize()); // special handling for 304-not modified if (curi.getFetchStatus() == HttpStatus.SC_NOT_MODIFIED && curi.containsDataKey(A_FETCH_HISTORY)) { - Map history[] = (Map[])curi.getData().get(A_FETCH_HISTORY); + @SuppressWarnings("unchecked") + Map<String, ?> history[] = (Map[])curi.getData().get(A_FETCH_HISTORY); if (history[0] != null && history[0] .containsKey(A_REFERENCE_LENGTH)) { @@ -1024,12 +1024,12 @@ protected HostConfiguration configureMethod(CrawlURI curi, * @param sourceHeader header to consult in URI history * @param targetHeader header to set if possible */ - @SuppressWarnings("unchecked") protected void setConditionalGetHeader(CrawlURI curi, HttpMethod method, boolean conditional, String sourceHeader, String targetHeader) { if (conditional) { try { - Map[] history = (Map[])curi.getData().get(A_FETCH_HISTORY); + @SuppressWarnings("unchecked") + Map<String, ?>[] history = (Map[])curi.getData().get(A_FETCH_HISTORY); int previousStatus = (Integer) history[0].get(A_STATUS); if(previousStatus<=0) { // do not reuse headers from any broken fetch @@ -1261,7 +1261,6 @@ protected void handle401(final HttpMethod method, final CrawlURI curi) { * CrawlURI that got a 401. * @return Returns first wholesome authscheme found else null. */ - @SuppressWarnings("unchecked") protected AuthScheme getAuthScheme(final HttpMethod method, final CrawlURI curi) { Header[] headers = method.getResponseHeaders("WWW-Authenticate"); @@ -1271,9 +1270,11 @@ protected AuthScheme getAuthScheme(final HttpMethod method, return null; } - Map authschemes = null; + Map<String, String> authschemes = null; try { - authschemes = AuthChallengeParser.parseChallenges(headers); + @SuppressWarnings("unchecked") + Map<String, String> parsedChallenges = AuthChallengeParser.parseChallenges(headers); + authschemes = parsedChallenges; } catch (MalformedChallengeException e) { logger.fine("Failed challenge parse: " + e.getMessage()); } @@ -1285,7 +1286,7 @@ protected AuthScheme getAuthScheme(final HttpMethod method, AuthScheme result = null; // Use the first auth found. - for (Iterator i = authschemes.keySet().iterator(); result == null + for (Iterator<String> i = authschemes.keySet().iterator(); result == null && i.hasNext();) { String key = (String) i.next(); String challenge = (String) authschemes.get(key); @@ -1377,7 +1378,6 @@ public void stop() { super.stop(); // At the end save cookies to the file specified in the order file. if (cookieStorage != null) { - @SuppressWarnings("unchecked") Map<String, Cookie> map = http.getState().getCookiesMap(); cookieStorage.saveCookiesMap(map); cookieStorage.stop(); diff --git a/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java b/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java index c3282b0cf..24bb50743 100644 --- a/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java +++ b/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java @@ -57,7 +57,6 @@ public void setHistoryLength(int length) { public FetchHistoryProcessor() { } - @SuppressWarnings("unchecked") @Override protected void innerProcess(CrawlURI puri) throws InterruptedException { CrawlURI curi = (CrawlURI) puri; @@ -92,12 +91,14 @@ protected void innerProcess(CrawlURI puri) throws InterruptedException { // get or create proper-sized history array int targetHistoryLength = getHistoryLength(); - HashMap[] history = - (HashMap[]) (curi.containsDataKey(A_FETCH_HISTORY) + @SuppressWarnings("unchecked") + HashMap<String, ?>[] history = + (HashMap<String, ?>[]) (curi.containsDataKey(A_FETCH_HISTORY) ? curi.getData().get(A_FETCH_HISTORY) : new HashMap[targetHistoryLength]); if(history.length != targetHistoryLength) { - HashMap[] newHistory = new HashMap[targetHistoryLength]; + @SuppressWarnings("unchecked") + HashMap<String, ?>[] newHistory = new HashMap[targetHistoryLength]; System.arraycopy( history,0, newHistory,0, diff --git a/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java b/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java index b9220fcd1..2dc2f8c4e 100644 --- a/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java +++ b/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java @@ -80,10 +80,10 @@ public void setPreloadSourceUrl(String preloadSourceUrl) { this.preloadSourceUrl = preloadSourceUrl; } - @SuppressWarnings("unchecked") @Override protected void innerProcess(CrawlURI curi) throws InterruptedException { String pkey = persistKeyFor(curi); + @SuppressWarnings("unchecked") Map<String, Object> prior = (Map<String,Object>) store.get(pkey); if(prior!=null) { diff --git a/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java b/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java index 0ae482e24..5080fad10 100644 --- a/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java +++ b/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java @@ -85,7 +85,6 @@ @author Howard Lee Gayle */ -@SuppressWarnings("unchecked") public class MirrorWriterProcessor extends Processor { private static final long serialVersionUID = 3L; private static final Logger logger = @@ -462,7 +461,7 @@ private URIToFileReturn dirPath(String baseDir, String host, int port, If not, the last element is removed. @param list the list */ - private void ensurePairs(List list) { + private void ensurePairs(List<?> list) { if (1 == (list.size() % 2)) { list.remove(list.size() - 1); } @@ -513,7 +512,7 @@ private URIToFileReturn uriToFile(String baseDir, CrawlURI curi) if ((null != ctm) && (ctm.size() > 1)) { ensurePairs(ctm); String contentType = curi.getContentType().toLowerCase(); - Iterator i = ctm.iterator(); + Iterator<String> i = ctm.iterator(); for (boolean more = true; more && i.hasNext();) { String ct = (String) i.next(); String suf = (String) i.next(); @@ -542,7 +541,7 @@ private URIToFileReturn uriToFile(String baseDir, CrawlURI curi) ensurePairs(cm); characterMap = new HashMap<String,String>(cm.size()); // Above will be half full. - for (Iterator i = cm.iterator(); i.hasNext();) { + for (Iterator<String> i = cm.iterator(); i.hasNext();) { String s1 = (String) i.next(); String s2 = (String) i.next(); if ((null != s1) && (1 == s1.length()) && (null != s2) @@ -628,15 +627,15 @@ file system path segment (component) @throws IOException if a needed directory could not be created @throws IOException - if a needed directory is not writeable + if a needed directory is not writable @throws IOException if a non-directory file exists with the same path as a needed directory */ private URIToFileReturn uriToFile(CrawlURI curi, String host, int port, String uriPath, String query, String suffix, String baseDir, int maxSegLen, int maxPathLen, boolean caseSensitive, - String dirFile, Map characterMap, String dotBegin, String dotEnd, - String tooLongDir, boolean suffixAtEnd, Set underscoreSet) + String dirFile, Map<String, String> characterMap, String dotBegin, String dotEnd, + String tooLongDir, boolean suffixAtEnd, Set<String> underscoreSet) throws IOException { assert (null == host) || (0 != host.length()); assert 0 != uriPath.length(); @@ -904,7 +903,7 @@ This class represents one directory segment (component) of a URI path. */ class DirSegment extends PathSegment { /** If a segment name is in this set, prepend an underscore.*/ - private Set underscoreSet; + private Set<String> underscoreSet; /** Creates a DirSegment. @@ -937,8 +936,8 @@ file system path segment (component) maxSegLen is too small. */ DirSegment(String uriPath, int beginIndex, int endIndex, int maxSegLen, - boolean caseSensitive, CrawlURI curi, Map characterMap, - String dotBegin, String dotEnd, Set underscoreSet) { + boolean caseSensitive, CrawlURI curi, Map<String, String> characterMap, + String dotBegin, String dotEnd, Set<String> underscoreSet) { super(maxSegLen, caseSensitive, curi); mainPart = new LumpyString(uriPath, beginIndex, endIndex, (null == dotEnd) ? 0 : dotEnd.length(), @@ -1126,7 +1125,7 @@ file system path segment (component) maxSegLen is too small. */ EndSegment(String uriPath, int beginIndex, int endIndex, int maxSegLen, - boolean caseSensitive, CrawlURI curi, Map characterMap, + boolean caseSensitive, CrawlURI curi, Map<String, String> characterMap, String dotBegin, String query, String suffix, int maxPathLen, boolean suffixAtEnd) { super(maxSegLen - 1, caseSensitive, curi); @@ -1413,7 +1412,7 @@ class LumpyString { dotBegin is non-null but empty. */ LumpyString(String str, int beginIndex, int endIndex, int padding, - int maxLen, Map characterMap, String dotBegin) { + int maxLen, Map<String, String> characterMap, String dotBegin) { if (beginIndex < 0) { throw new IllegalArgumentException("beginIndex < 0: " + beginIndex); diff --git a/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java b/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java index 09dd6d1d1..dcd5d4fca 100644 --- a/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java +++ b/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java @@ -62,7 +62,6 @@ public abstract class WriterPoolProcessor extends Processor implements Lifecycle, Checkpointable, WriterPoolSettings { private static final long serialVersionUID = 1L; - @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(WriterPoolProcessor.class.getName());
5924e74d550b3ac5e5d65c2fc80275095de1c0e1
hadoop
YARN-2768 Improved Yarn Registry service record- structure (stevel)--
p
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 8335d2b1c4f12..6689d894772e1 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -710,6 +710,8 @@ Release 2.6.0 - UNRELEASED YARN-2677 registry punycoding of usernames doesn't fix all usernames to be DNS-valid (stevel) + YARN-2768 Improved Yarn Registry service record structure (stevel) + --- YARN-2598 GHS should show N/A instead of null for the inaccessible information diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/cli/RegistryCli.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/cli/RegistryCli.java index 863039e2e8b8e..bf2b5e5a54d34 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/cli/RegistryCli.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/cli/RegistryCli.java @@ -24,6 +24,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.List; +import java.util.Map; import com.google.common.base.Preconditions; import org.apache.commons.cli.CommandLine; @@ -174,24 +175,22 @@ public int resolve(String [] args) { ServiceRecord record = registry.resolve(argsList.get(1)); for (Endpoint endpoint : record.external) { - if ((endpoint.protocolType.equals(ProtocolTypes.PROTOCOL_WEBUI)) - || (endpoint.protocolType.equals(ProtocolTypes.PROTOCOL_REST))) { - sysout.print(" Endpoint(ProtocolType=" - + endpoint.protocolType + ", Api=" - + endpoint.api + "); Uris are: "); - } else { - sysout.print(" Endpoint(ProtocolType=" + sysout.println(" Endpoint(ProtocolType=" + endpoint.protocolType + ", Api=" + endpoint.api + ");" + " Addresses(AddressType=" + endpoint.addressType + ") are: "); - } - for (List<String> a : endpoint.addresses) { - sysout.print(a + " "); - } - sysout.println(); - } + for (Map<String, String> address : endpoint.addresses) { + sysout.println(" [ "); + for (Map.Entry<String, String> entry : address.entrySet()) { + sysout.println(" " + entry.getKey() + + ": \"" + entry.getValue() + "\""); + } + sysout.println(" ]"); + } + sysout.println(); + } return 0; } catch (Exception e) { syserr.println(analyzeException("resolve", e, argsList)); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/JsonSerDeser.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/JsonSerDeser.java index e086e3694f6e8..af4e4f409c0c0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/JsonSerDeser.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/JsonSerDeser.java @@ -19,6 +19,7 @@ package org.apache.hadoop.registry.client.binding; import com.google.common.base.Preconditions; +import org.apache.commons.lang.StringUtils; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.fs.FSDataInputStream; @@ -45,8 +46,6 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.Arrays; /** * Support for marshalling objects to and from JSON. @@ -62,30 +61,30 @@ public class JsonSerDeser<T> { private static final Logger LOG = LoggerFactory.getLogger(JsonSerDeser.class); private static final String UTF_8 = "UTF-8"; - public static final String E_NO_SERVICE_RECORD = "No service record at path"; + public static final String E_NO_DATA = "No data at path"; + public static final String E_DATA_TOO_SHORT = "Data at path too short"; + public static final String E_MISSING_MARKER_STRING = + "Missing marker string: "; private final Class<T> classType; private final ObjectMapper mapper; - private final byte[] header; /** * Create an instance bound to a specific type * @param classType class to marshall - * @param header byte array to use as header */ - public JsonSerDeser(Class<T> classType, byte[] header) { + public JsonSerDeser(Class<T> classType) { Preconditions.checkArgument(classType != null, "null classType"); - Preconditions.checkArgument(header != null, "null header"); this.classType = classType; this.mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // make an immutable copy to keep findbugs happy. - byte[] h = new byte[header.length]; - System.arraycopy(header, 0, h, 0, header.length); - this.header = h; } + /** + * Get the simple name of the class type to be marshalled + * @return the name of the class being marshalled + */ public String getName() { return classType.getSimpleName(); } @@ -183,7 +182,7 @@ public T load(FileSystem fs, Path path) if (count != len) { throw new EOFException(path.toString() + ": read finished prematurely"); } - return fromBytes(path.toString(), b, 0); + return fromBytes(path.toString(), b); } /** @@ -206,8 +205,7 @@ public void save(FileSystem fs, Path path, T instance, * @throws IOException on any failure */ private void writeJsonAsBytes(T instance, - DataOutputStream dataOutputStream) throws - IOException { + DataOutputStream dataOutputStream) throws IOException { try { byte[] b = toBytes(instance); dataOutputStream.write(b); @@ -228,36 +226,50 @@ public byte[] toBytes(T instance) throws IOException { } /** - * Convert JSON To bytes, inserting the header - * @param instance instance to convert - * @return a byte array - * @throws IOException + * Deserialize from a byte array + * @param path path the data came from + * @param bytes byte array + * @throws IOException all problems + * @throws EOFException not enough data + * @throws InvalidRecordException if the parsing failed -the record is invalid */ - public byte[] toByteswithHeader(T instance) throws IOException { - byte[] body = toBytes(instance); - - ByteBuffer buffer = ByteBuffer.allocate(body.length + header.length); - buffer.put(header); - buffer.put(body); - return buffer.array(); + public T fromBytes(String path, byte[] bytes) throws IOException, + InvalidRecordException { + return fromBytes(path, bytes, ""); } /** - * Deserialize from a byte array + * Deserialize from a byte array, optionally checking for a marker string. + * <p> + * If the marker parameter is supplied (and not empty), then its presence + * will be verified before the JSON parsing takes place; it is a fast-fail + * check. If not found, an {@link InvalidRecordException} exception will be + * raised * @param path path the data came from * @param bytes byte array - * @return offset in the array to read from + * @param marker an optional string which, if set, MUST be present in the + * UTF-8 parsed payload. + * @return The parsed record * @throws IOException all problems * @throws EOFException not enough data - * @throws InvalidRecordException if the parsing failed -the record is invalid + * @throws InvalidRecordException if the JSON parsing failed. + * @throws NoRecordException if the data is not considered a record: either + * it is too short or it did not contain the marker string. */ - public T fromBytes(String path, byte[] bytes, int offset) throws IOException, - InvalidRecordException { - int data = bytes.length - offset; - if (data <= 0) { - throw new EOFException("No data at " + path); + public T fromBytes(String path, byte[] bytes, String marker) + throws IOException, NoRecordException, InvalidRecordException { + int len = bytes.length; + if (len == 0 ) { + throw new NoRecordException(path, E_NO_DATA); + } + if (StringUtils.isNotEmpty(marker) && len < marker.length()) { + throw new NoRecordException(path, E_DATA_TOO_SHORT); + } + String json = new String(bytes, 0, len, UTF_8); + if (StringUtils.isNotEmpty(marker) + && !json.contains(marker)) { + throw new NoRecordException(path, E_MISSING_MARKER_STRING + marker); } - String json = new String(bytes, offset, data, UTF_8); try { return fromJson(json); } catch (JsonProcessingException e) { @@ -266,52 +278,7 @@ public T fromBytes(String path, byte[] bytes, int offset) throws IOException, } /** - * Read from a byte array to a type, checking the header first - * @param path source of data - * @param buffer buffer - * @return the parsed structure - * Null if the record was too short or the header did not match - * @throws IOException on a failure - * @throws NoRecordException if header checks implied there was no record - * @throws InvalidRecordException if record parsing failed - */ - @SuppressWarnings("unchecked") - public T fromBytesWithHeader(String path, byte[] buffer) throws IOException { - int hlen = header.length; - int blen = buffer.length; - if (hlen > 0) { - if (blen < hlen) { - throw new NoRecordException(path, E_NO_SERVICE_RECORD); - } - byte[] magic = Arrays.copyOfRange(buffer, 0, hlen); - if (!Arrays.equals(header, magic)) { - LOG.debug("start of entry does not match service record header at {}", - path); - throw new NoRecordException(path, E_NO_SERVICE_RECORD); - } - } - return fromBytes(path, buffer, hlen); - } - - /** - * Check if a buffer has a header which matches this record type - * @param buffer buffer - * @return true if there is a match - * @throws IOException - */ - public boolean headerMatches(byte[] buffer) throws IOException { - int hlen = header.length; - int blen = buffer.length; - boolean matches = false; - if (blen > hlen) { - byte[] magic = Arrays.copyOfRange(buffer, 0, hlen); - matches = Arrays.equals(header, magic); - } - return matches; - } - - /** - * Convert an object to a JSON string + * Convert an instance to a JSON string * @param instance instance to convert * @return a JSON string description * @throws JsonParseException parse problems @@ -324,4 +291,19 @@ public synchronized String toJson(T instance) throws IOException, return mapper.writeValueAsString(instance); } + /** + * Convert an instance to a string form for output. This is a robust + * operation which will convert any JSON-generating exceptions into + * error text. + * @param instance non-null instance + * @return a JSON string + */ + public String toString(T instance) { + Preconditions.checkArgument(instance != null, "Null instance argument"); + try { + return toJson(instance); + } catch (IOException e) { + return "Failed to convert to a string: " + e; + } + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryTypeUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryTypeUtils.java index b4254a3beba9e..ec59d5985a044 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryTypeUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryTypeUtils.java @@ -22,17 +22,19 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.registry.client.exceptions.InvalidRecordException; -import org.apache.hadoop.registry.client.types.AddressTypes; +import static org.apache.hadoop.registry.client.types.AddressTypes.*; import org.apache.hadoop.registry.client.types.Endpoint; import org.apache.hadoop.registry.client.types.ProtocolTypes; +import org.apache.hadoop.registry.client.types.ServiceRecord; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; -import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Static methods to work with registry types —primarily endpoints and the @@ -94,79 +96,66 @@ public static Endpoint inetAddrEndpoint(String api, Preconditions.checkArgument(protocolType != null, "null protocolType"); Preconditions.checkArgument(hostname != null, "null hostname"); return new Endpoint(api, - AddressTypes.ADDRESS_HOSTNAME_AND_PORT, + ADDRESS_HOSTNAME_AND_PORT, protocolType, - tuplelist(hostname, Integer.toString(port))); + hostnamePortPair(hostname, port)); } /** * Create an IPC endpoint * @param api API - * @param protobuf flag to indicate whether or not the IPC uses protocol - * buffers * @param address the address as a tuple of (hostname, port) * @return the new endpoint */ - public static Endpoint ipcEndpoint(String api, - boolean protobuf, List<String> address) { - ArrayList<List<String>> addressList = new ArrayList<List<String>>(); - if (address != null) { - addressList.add(address); - } + public static Endpoint ipcEndpoint(String api, InetSocketAddress address) { return new Endpoint(api, - AddressTypes.ADDRESS_HOSTNAME_AND_PORT, - protobuf ? ProtocolTypes.PROTOCOL_HADOOP_IPC_PROTOBUF - : ProtocolTypes.PROTOCOL_HADOOP_IPC, - addressList); + ADDRESS_HOSTNAME_AND_PORT, + ProtocolTypes.PROTOCOL_HADOOP_IPC, + address== null ? null: hostnamePortPair(address)); } /** - * Create a single-element list of tuples from the input. - * that is, an input ("a","b","c") is converted into a list - * in the form [["a","b","c"]] - * @param t1 tuple elements - * @return a list containing a single tuple + * Create a single entry map + * @param key map entry key + * @param val map entry value + * @return a 1 entry map. */ - public static List<List<String>> tuplelist(String... t1) { - List<List<String>> outer = new ArrayList<List<String>>(); - outer.add(tuple(t1)); - return outer; + public static Map<String, String> map(String key, String val) { + Map<String, String> map = new HashMap<String, String>(1); + map.put(key, val); + return map; } /** - * Create a tuples from the input. - * that is, an input ("a","b","c") is converted into a list - * in the form ["a","b","c"] - * @param t1 tuple elements - * @return a single tuple as a list + * Create a URI + * @param uri value + * @return a 1 entry map. */ - public static List<String> tuple(String... t1) { - return Arrays.asList(t1); + public static Map<String, String> uri(String uri) { + return map(ADDRESS_URI, uri); } /** - * Create a tuples from the input, converting all to Strings in the process - * that is, an input ("a", 7, true) is converted into a list - * in the form ["a","7,"true"] - * @param t1 tuple elements - * @return a single tuple as a list + * Create a (hostname, port) address pair + * @param hostname hostname + * @param port port + * @return a 1 entry map. */ - public static List<String> tuple(Object... t1) { - List<String> l = new ArrayList<String>(t1.length); - for (Object t : t1) { - l.add(t.toString()); - } - return l; + public static Map<String, String> hostnamePortPair(String hostname, int port) { + Map<String, String> map = + map(ADDRESS_HOSTNAME_FIELD, hostname); + map.put(ADDRESS_PORT_FIELD, Integer.toString(port)); + return map; } /** - * Convert a socket address pair into a string tuple, (host, port). - * TODO JDK7: move to InetAddress.getHostString() to avoid DNS lookups. - * @param address an address - * @return an element for the address list + * Create a (hostname, port) address pair + * @param address socket address whose hostname and port are used for the + * generated address. + * @return a 1 entry map. */ - public static List<String> marshall(InetSocketAddress address) { - return tuple(address.getHostName(), address.getPort()); + public static Map<String, String> hostnamePortPair(InetSocketAddress address) { + return hostnamePortPair(address.getHostName(), address.getPort()); } /** @@ -199,24 +188,36 @@ public static List<String> retrieveAddressesUriType(Endpoint epr) if (epr == null) { return null; } - requireAddressType(AddressTypes.ADDRESS_URI, epr); - List<List<String>> addresses = epr.addresses; + requireAddressType(ADDRESS_URI, epr); + List<Map<String, String>> addresses = epr.addresses; if (addresses.size() < 1) { throw new InvalidRecordException(epr.toString(), "No addresses in endpoint"); } List<String> results = new ArrayList<String>(addresses.size()); - for (List<String> address : addresses) { - if (address.size() != 1) { - throw new InvalidRecordException(epr.toString(), - "Address payload invalid: wrong element count: " + - address.size()); - } - results.add(address.get(0)); + for (Map<String, String> address : addresses) { + results.add(getAddressField(address, ADDRESS_URI)); } return results; } + /** + * Get a specific field from an address -raising an exception if + * the field is not present + * @param address address to query + * @param field field to resolve + * @return the resolved value. Guaranteed to be non-null. + * @throws InvalidRecordException if the field did not resolve + */ + public static String getAddressField(Map<String, String> address, + String field) throws InvalidRecordException { + String val = address.get(field); + if (val == null) { + throw new InvalidRecordException("", "Missing address field: " + field); + } + return val; + } + /** * Get the address URLs. Guranteed to return at least one address. * @param epr endpoint @@ -237,4 +238,53 @@ public static List<URL> retrieveAddressURLs(Endpoint epr) } return results; } + + /** + * Validate the record by checking for null fields and other invalid + * conditions + * @param path path for exceptions + * @param record record to validate. May be null + * @throws InvalidRecordException on invalid entries + */ + public static void validateServiceRecord(String path, ServiceRecord record) + throws InvalidRecordException { + if (record == null) { + throw new InvalidRecordException(path, "Null record"); + } + if (!ServiceRecord.RECORD_TYPE.equals(record.type)) { + throw new InvalidRecordException(path, + "invalid record type field: \"" + record.type + "\""); + } + + if (record.external != null) { + for (Endpoint endpoint : record.external) { + validateEndpoint(path, endpoint); + } + } + if (record.internal != null) { + for (Endpoint endpoint : record.internal) { + validateEndpoint(path, endpoint); + } + } + } + + /** + * Validate the endpoint by checking for null fields and other invalid + * conditions + * @param path path for exceptions + * @param endpoint endpoint to validate. May be null + * @throws InvalidRecordException on invalid entries + */ + public static void validateEndpoint(String path, Endpoint endpoint) + throws InvalidRecordException { + if (endpoint == null) { + throw new InvalidRecordException(path, "Null endpoint"); + } + try { + endpoint.validate(); + } catch (RuntimeException e) { + throw new InvalidRecordException(path, e.toString()); + } + } + } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryUtils.java index 8caf4002feebf..68dc84e7bf749 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryUtils.java @@ -33,7 +33,6 @@ import org.apache.hadoop.registry.client.impl.zk.RegistryInternalConstants; import org.apache.hadoop.registry.client.types.RegistryPathStatus; import org.apache.hadoop.registry.client.types.ServiceRecord; -import org.apache.hadoop.registry.client.types.ServiceRecordHeader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -314,7 +313,7 @@ public static Map<String, ServiceRecord> extractServiceRecords( Collection<RegistryPathStatus> stats) throws IOException { Map<String, ServiceRecord> results = new HashMap<String, ServiceRecord>(stats.size()); for (RegistryPathStatus stat : stats) { - if (stat.size > ServiceRecordHeader.getLength()) { + if (stat.size > ServiceRecord.RECORD_TYPE.length()) { // maybe has data String path = join(parentpath, stat.path); try { @@ -344,7 +343,6 @@ public static Map<String, ServiceRecord> extractServiceRecords( * <p> * @param operations operation support for fetches * @param parentpath path of the parent of all the entries - * @param stats a map of name:value mappings. * @return a possibly empty map of fullpath:record. * @throws IOException for any IO Operation that wasn't ignored. */ @@ -362,7 +360,6 @@ public static Map<String, ServiceRecord> extractServiceRecords( * <p> * @param operations operation support for fetches * @param parentpath path of the parent of all the entries - * @param stats a map of name:value mappings. * @return a possibly empty map of fullpath:record. * @throws IOException for any IO Operation that wasn't ignored. */ @@ -382,7 +379,7 @@ public static Map<String, ServiceRecord> extractServiceRecords( */ public static class ServiceRecordMarshal extends JsonSerDeser<ServiceRecord> { public ServiceRecordMarshal() { - super(ServiceRecord.class, ServiceRecordHeader.getData()); + super(ServiceRecord.class); } } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/exceptions/NoRecordException.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/exceptions/NoRecordException.java index 160433f081410..b81b9d4134131 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/exceptions/NoRecordException.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/exceptions/NoRecordException.java @@ -21,17 +21,11 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.registry.client.types.ServiceRecord; -import org.apache.hadoop.registry.client.types.ServiceRecordHeader; /** * Raised if there is no {@link ServiceRecord} resolved at the end - * of the specified path, for reasons such as: - * <ul> - * <li>There wasn't enough data to contain a Service Record.</li> - * <li>The start of the data did not match the {@link ServiceRecordHeader} - * header.</li> - * </ul> - * + * of the specified path. + * <p> * There may be valid data of some form at the end of the path, but it does * not appear to be a Service Record. */ diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/impl/zk/RegistryOperationsService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/impl/zk/RegistryOperationsService.java index 7c01bdf433e0c..271ab25463335 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/impl/zk/RegistryOperationsService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/impl/zk/RegistryOperationsService.java @@ -24,9 +24,11 @@ import org.apache.hadoop.registry.client.api.BindFlags; import org.apache.hadoop.registry.client.api.RegistryOperations; +import org.apache.hadoop.registry.client.binding.RegistryTypeUtils; import org.apache.hadoop.registry.client.binding.RegistryUtils; import org.apache.hadoop.registry.client.binding.RegistryPathUtils; import org.apache.hadoop.registry.client.exceptions.InvalidPathnameException; +import org.apache.hadoop.registry.client.exceptions.NoRecordException; import org.apache.hadoop.registry.client.types.RegistryPathStatus; import org.apache.hadoop.registry.client.types.ServiceRecord; import org.apache.zookeeper.CreateMode; @@ -103,10 +105,12 @@ public void bind(String path, int flags) throws IOException { Preconditions.checkArgument(record != null, "null record"); validatePath(path); + // validate the record before putting it + RegistryTypeUtils.validateServiceRecord(path, record); LOG.info("Bound at {} : {}", path, record); CreateMode mode = CreateMode.PERSISTENT; - byte[] bytes = serviceRecordMarshal.toByteswithHeader(record); + byte[] bytes = serviceRecordMarshal.toBytes(record); zkSet(path, mode, bytes, getClientAcls(), ((flags & BindFlags.OVERWRITE) != 0)); } @@ -114,7 +118,11 @@ public void bind(String path, @Override public ServiceRecord resolve(String path) throws IOException { byte[] bytes = zkRead(path); - return serviceRecordMarshal.fromBytesWithHeader(path, bytes); + + ServiceRecord record = serviceRecordMarshal.fromBytes(path, + bytes, ServiceRecord.RECORD_TYPE); + RegistryTypeUtils.validateServiceRecord(path, record); + return record; } @Override diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/AddressTypes.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/AddressTypes.java index 192819c8d7dc6..36dbf0ce66e1d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/AddressTypes.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/AddressTypes.java @@ -38,6 +38,8 @@ public interface AddressTypes { * </pre> */ public static final String ADDRESS_HOSTNAME_AND_PORT = "host/port"; + public static final String ADDRESS_HOSTNAME_FIELD = "host"; + public static final String ADDRESS_PORT_FIELD = "port"; /** diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/Endpoint.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/Endpoint.java index 51418d9c9e5f6..e4effb42c8664 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/Endpoint.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/Endpoint.java @@ -21,14 +21,16 @@ import com.google.common.base.Preconditions; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.registry.client.binding.JsonSerDeser; import org.apache.hadoop.registry.client.binding.RegistryTypeUtils; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.net.URI; import java.util.ArrayList; -import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Description of a single service/component endpoint. @@ -67,7 +69,7 @@ public final class Endpoint implements Cloneable { /** * a list of address tuples —tuples whose format depends on the address type */ - public List<List<String>> addresses; + public List<Map<String, String>> addresses; /** * Create an empty instance. @@ -84,10 +86,11 @@ public Endpoint(Endpoint that) { this.api = that.api; this.addressType = that.addressType; this.protocolType = that.protocolType; - this.addresses = new ArrayList<List<String>>(that.addresses.size()); - for (List<String> address : addresses) { - List<String> addr2 = new ArrayList<String>(address.size()); - Collections.copy(address, addr2); + this.addresses = newAddresses(that.addresses.size()); + for (Map<String, String> address : that.addresses) { + Map<String, String> addr2 = new HashMap<String, String>(address.size()); + addr2.putAll(address); + addresses.add(addr2); } } @@ -101,16 +104,82 @@ public Endpoint(Endpoint that) { public Endpoint(String api, String addressType, String protocolType, - List<List<String>> addrs) { + List<Map<String, String>> addrs) { this.api = api; this.addressType = addressType; this.protocolType = protocolType; - this.addresses = new ArrayList<List<String>>(); + this.addresses = newAddresses(0); if (addrs != null) { addresses.addAll(addrs); } } + /** + * Build an endpoint with an empty address list + * @param api API name + * @param addressType address type + * @param protocolType protocol type + */ + public Endpoint(String api, + String addressType, + String protocolType) { + this.api = api; + this.addressType = addressType; + this.protocolType = protocolType; + this.addresses = newAddresses(0); + } + + /** + * Build an endpoint with a single address entry. + * <p> + * This constructor is superfluous given the varags constructor is equivalent + * for a single element argument. However, type-erasure in java generics + * causes javac to warn about unchecked generic array creation. This + * constructor, which represents the common "one address" case, does + * not generate compile-time warnings. + * @param api API name + * @param addressType address type + * @param protocolType protocol type + * @param addr address. May be null —in which case it is not added + */ + public Endpoint(String api, + String addressType, + String protocolType, + Map<String, String> addr) { + this(api, addressType, protocolType); + if (addr != null) { + addresses.add(addr); + } + } + + /** + * Build an endpoint with a list of addresses + * @param api API name + * @param addressType address type + * @param protocolType protocol type + * @param addrs addresses. Null elements will be skipped + */ + public Endpoint(String api, + String addressType, + String protocolType, + Map<String, String>...addrs) { + this(api, addressType, protocolType); + for (Map<String, String> addr : addrs) { + if (addr!=null) { + addresses.add(addr); + } + } + } + + /** + * Create a new address structure of the requested size + * @param size size to create + * @return the new list + */ + private List<Map<String, String>> newAddresses(int size) { + return new ArrayList<Map<String, String>>(size); + } + /** * Build an endpoint from a list of URIs; each URI * is ASCII-encoded and added to the list of addresses. @@ -125,40 +194,16 @@ public Endpoint(String api, this.addressType = AddressTypes.ADDRESS_URI; this.protocolType = protocolType; - List<List<String>> addrs = new ArrayList<List<String>>(uris.length); + List<Map<String, String>> addrs = newAddresses(uris.length); for (URI uri : uris) { - addrs.add(RegistryTypeUtils.tuple(uri.toString())); + addrs.add(RegistryTypeUtils.uri(uri.toString())); } this.addresses = addrs; } @Override public String toString() { - final StringBuilder sb = new StringBuilder("Endpoint{"); - sb.append("api='").append(api).append('\''); - sb.append(", addressType='").append(addressType).append('\''); - sb.append(", protocolType='").append(protocolType).append('\''); - - sb.append(", addresses="); - if (addresses != null) { - sb.append("[ "); - for (List<String> address : addresses) { - sb.append("[ "); - if (address == null) { - sb.append("NULL entry in address list"); - } else { - for (String elt : address) { - sb.append('"').append(elt).append("\" "); - } - } - sb.append("] "); - }; - sb.append("] "); - } else { - sb.append("(null) "); - } - sb.append('}'); - return sb.toString(); + return marshalToString.toString(this); } /** @@ -173,7 +218,7 @@ public void validate() { Preconditions.checkNotNull(addressType, "null addressType field"); Preconditions.checkNotNull(protocolType, "null protocolType field"); Preconditions.checkNotNull(addresses, "null addresses field"); - for (List<String> address : addresses) { + for (Map<String, String> address : addresses) { Preconditions.checkNotNull(address, "null element in address"); } } @@ -184,7 +229,19 @@ public void validate() { * @throws CloneNotSupportedException */ @Override - protected Object clone() throws CloneNotSupportedException { + public Object clone() throws CloneNotSupportedException { return super.clone(); } + + + /** + * Static instance of service record marshalling + */ + private static class Marshal extends JsonSerDeser<Endpoint> { + private Marshal() { + super(Endpoint.class); + } + } + + private static final Marshal marshalToString = new Marshal(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ProtocolTypes.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ProtocolTypes.java index f225cf087753b..b836b0003c7dc 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ProtocolTypes.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ProtocolTypes.java @@ -34,15 +34,10 @@ public interface ProtocolTypes { String PROTOCOL_FILESYSTEM = "hadoop/filesystem"; /** - * Classic Hadoop IPC : {@value}. + * Hadoop IPC, "classic" or protobuf : {@value}. */ String PROTOCOL_HADOOP_IPC = "hadoop/IPC"; - /** - * Hadoop protocol buffers IPC: {@value}. - */ - String PROTOCOL_HADOOP_IPC_PROTOBUF = "hadoop/protobuf"; - /** * Corba IIOP: {@value}. */ diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecord.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecord.java index 378127fc026c2..9403d3168e2d5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecord.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecord.java @@ -21,6 +21,7 @@ import com.google.common.base.Preconditions; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.registry.client.exceptions.InvalidRecordException; import org.codehaus.jackson.annotate.JsonAnyGetter; import org.codehaus.jackson.annotate.JsonAnySetter; import org.codehaus.jackson.map.annotate.JsonSerialize; @@ -40,6 +41,17 @@ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class ServiceRecord implements Cloneable { + /** + * A type string which MUST be in the serialized json. This permits + * fast discarding of invalid entries + */ + public static final String RECORD_TYPE = "JSONServiceRecord"; + + /** + * The type field. This must be the string {@link #RECORD_TYPE} + */ + public String type = RECORD_TYPE; + /** * Description string */ @@ -233,17 +245,5 @@ protected Object clone() throws CloneNotSupportedException { return super.clone(); } - /** - * Validate the record by checking for null fields and other invalid - * conditions - * @throws NullPointerException if a field is null when it - * MUST be set. - * @throws RuntimeException on invalid entries - */ - public void validate() { - for (Endpoint endpoint : external) { - Preconditions.checkNotNull("null endpoint", endpoint); - endpoint.validate(); - } - } + } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecordHeader.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecordHeader.java deleted file mode 100644 index 2f75dba5a3357..0000000000000 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/ServiceRecordHeader.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.registry.client.types; - -import org.apache.hadoop.classification.InterfaceAudience; -import org.apache.hadoop.classification.InterfaceStability; - -/** - * Service record header; access to the byte array kept private - * to avoid findbugs warnings of mutability - */ [email protected] [email protected] -public class ServiceRecordHeader { - /** - * Header of a service record: "jsonservicerec" - * By making this over 12 bytes long, we can auto-determine which entries - * in a listing are too short to contain a record without getting their data - */ - private static final byte[] RECORD_HEADER = { - 'j', 's', 'o', 'n', - 's', 'e', 'r', 'v', 'i', 'c', 'e', - 'r', 'e', 'c' - }; - - /** - * Get the length of the record header - * @return the header length - */ - public static int getLength() { - return RECORD_HEADER.length; - } - - /** - * Get a clone of the record header - * @return the new record header. - */ - public static byte[] getData() { - byte[] h = new byte[RECORD_HEADER.length]; - System.arraycopy(RECORD_HEADER, 0, h, 0, RECORD_HEADER.length); - return h; - } -} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/tla/yarnregistry.tla b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/tla/yarnregistry.tla index 1c19adead446c..a950475f402e5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/tla/yarnregistry.tla +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/tla/yarnregistry.tla @@ -4,6 +4,7 @@ EXTENDS FiniteSets, Sequences, Naturals, TLC (* +============================================================================ * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -19,6 +20,7 @@ EXTENDS FiniteSets, Sequences, Naturals, TLC * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. +============================================================================ *) (* @@ -71,13 +73,22 @@ CONSTANTS MknodeActions \* all possible mkdir actions +ASSUME PathChars \in STRING +ASSUME Paths \in STRING + +(* Data in records is JSON, hence a string *) +ASSUME Data \in STRING + +---------------------------------------------------------------------------------------- (* the registry*) VARIABLE registry + (* Sequence of actions to apply to the registry *) VARIABLE actions + ---------------------------------------------------------------------------------------- (* Tuple of all variables. *) @@ -92,7 +103,6 @@ vars == << registry, actions >> (* Persistence policy *) PersistPolicySet == { - "", \* Undefined; field not present. PERMANENT is implied. "permanent", \* persists until explicitly removed "application", \* persists until the application finishes "application-attempt", \* persists until the application attempt finishes @@ -104,7 +114,6 @@ TypeInvariant == /\ \A p \in PersistPolicies: p \in PersistPolicySet - ---------------------------------------------------------------------------------------- @@ -129,6 +138,14 @@ RegistryEntry == [ ] +(* Define the set of all string to string mappings *) + +StringMap == [ + STRING |-> STRING +] + + + (* An endpoint in a service record *) @@ -140,21 +157,14 @@ Endpoint == [ addresses: Addresses ] -(* Attributes are the set of all string to string mappings *) - -Attributes == [ -STRING |-> STRING -] - (* A service record *) ServiceRecord == [ - \* ID -used when applying the persistence policy - yarn_id: STRING, - \* the persistence policy - yarn_persistence: PersistPolicySet, + \* This MUST be present: if it is not then the data is not a service record + \* This permits shortcut scan & reject of byte arrays without parsing + type: "JSONServiceRecord", \*A description description: STRING, @@ -166,9 +176,34 @@ ServiceRecord == [ internal: Endpoints, \* Attributes are a function - attributes: Attributes + attributes: StringMap ] +---------------------------------------------------------------------------------------- + +(* + There is an operation serialize whose internals are not defined, + Which converts the service records to JSON + *) + +CONSTANT serialize(_) + +(* A function which returns true iff the byte stream is considered a valid service record. *) +CONSTANT containsServiceRecord(_) + +(* A function to deserialize a string to JSON *) +CONSTANT deserialize(_) + +ASSUME \A json \in STRING: containsServiceRecord(json) \in BOOLEAN + +(* Records can be serialized *) +ASSUME \A r \in ServiceRecord : serialize(r) \in STRING /\ containsServiceRecord(serialize(r)) + +(* All strings for which containsServiceRecord() holds can be deserialized *) +ASSUME \A json \in STRING: containsServiceRecord(json) => deserialize(json) \in ServiceRecord + + + ---------------------------------------------------------------------------------------- @@ -304,8 +339,8 @@ validRegistry(R) == \* an entry must be the root entry or have a parent entry /\ \A e \in R: isRootEntry(e) \/ exists(R, parent(e.path)) - \* If the entry has data, it must be a service record - /\ \A e \in R: (e.data = << >> \/ e.data \in ServiceRecords) + \* If the entry has data, it must contain a service record + /\ \A e \in R: (e.data = << >> \/ containsServiceRecord(e.data)) ---------------------------------------------------------------------------------------- @@ -336,13 +371,13 @@ mknode() adds a new empty entry where there was none before, iff *) mknodeSimple(R, path) == - LET record == [ path |-> path, data |-> <<>> ] + LET entry == [ path |-> path, data |-> <<>> ] IN \/ exists(R, path) - \/ (exists(R, parent(path)) /\ canBind(R, record) /\ (R' = R \union {record} )) + \/ (exists(R, parent(path)) /\ canBind(R, entry) /\ (R' = R \union {entry} )) (* -For all parents, the mknodeSimpl() criteria must apply. +For all parents, the mknodeSimple() criteria must apply. This could be defined recursively, though as TLA+ does not support recursion, an alternative is required @@ -350,7 +385,8 @@ an alternative is required Because this specification is declaring the final state of a operation, not the implemental, all that is needed is to describe those parents. -It declares that the mkdirSimple state applies to the path and all its parents in the set R' +It declares that the mknodeSimple() state applies to the path and all +its parents in the set R' *) mknodeWithParents(R, path) == @@ -402,7 +438,7 @@ purge(R, path, id, persistence) == => recursiveDelete(R, p2.path) (* -resolveRecord() resolves the record at a path or fails. +resolveEntry() resolves the record entry at a path or fails. It relies on the fact that if the cardinality of a set is 1, then the CHOOSE operator is guaranteed to return the single entry of that set, iff the choice predicate holds. @@ -411,19 +447,28 @@ Using a predicate of TRUE, it always succeeds, so this function selects the sole entry of the resolve operation. *) -resolveRecord(R, path) == +resolveEntry(R, path) == LET l == resolve(R, path) IN /\ Cardinality(l) = 1 /\ CHOOSE e \in l : TRUE +(* + Resolve a record by resolving the entry and deserializing the result + *) +resolveRecord(R, path) == + deserialize(resolveEntry(R, path)) + + (* The specific action of putting an entry into a record includes validating the record *) validRecordToBind(path, record) == \* The root entry must have permanent persistence - isRootPath(path) => (record.attributes["yarn:persistence"] = "permanent" - \/ record.attributes["yarn:persistence"] = "") + isRootPath(path) => ( + record.attributes["yarn:persistence"] = "permanent" + \/ record.attributes["yarn:persistence"] + \/ record.attributes["yarn:persistence"] = {}) (* @@ -432,13 +477,12 @@ marshalled as the data in the entry *) bindRecord(R, path, record) == /\ validRecordToBind(path, record) - /\ bind(R, [path |-> path, data |-> record]) + /\ bind(R, [path |-> path, data |-> serialize(record)]) ---------------------------------------------------------------------------------------- - (* The action queue can only contain one of the sets of action types, and by giving each a unique name, those sets are guaranteed to be disjoint diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/RegistryTestHelper.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/RegistryTestHelper.java index 460ecad876a1f..91602e1d3b3e2 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/RegistryTestHelper.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/RegistryTestHelper.java @@ -20,7 +20,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.hadoop.security.UserGroupInformation; -import org.apache.hadoop.util.Shell; import org.apache.hadoop.registry.client.api.RegistryConstants; import org.apache.hadoop.registry.client.binding.RegistryUtils; import org.apache.hadoop.registry.client.binding.RegistryTypeUtils; @@ -46,11 +45,7 @@ import java.util.List; import java.util.Map; -import static org.apache.hadoop.registry.client.binding.RegistryTypeUtils.inetAddrEndpoint; -import static org.apache.hadoop.registry.client.binding.RegistryTypeUtils.ipcEndpoint; -import static org.apache.hadoop.registry.client.binding.RegistryTypeUtils.restEndpoint; -import static org.apache.hadoop.registry.client.binding.RegistryTypeUtils.tuple; -import static org.apache.hadoop.registry.client.binding.RegistryTypeUtils.webEndpoint; +import static org.apache.hadoop.registry.client.binding.RegistryTypeUtils.*; /** * This is a set of static methods to aid testing the registry operations. @@ -61,18 +56,18 @@ public class RegistryTestHelper extends Assert { public static final String SC_HADOOP = "org-apache-hadoop"; public static final String USER = "devteam/"; public static final String NAME = "hdfs"; - public static final String API_WEBHDFS = "org_apache_hadoop_namenode_webhdfs"; - public static final String API_HDFS = "org_apache_hadoop_namenode_dfs"; + public static final String API_WEBHDFS = "classpath:org.apache.hadoop.namenode.webhdfs"; + public static final String API_HDFS = "classpath:org.apache.hadoop.namenode.dfs"; public static final String USERPATH = RegistryConstants.PATH_USERS + USER; public static final String PARENT_PATH = USERPATH + SC_HADOOP + "/"; public static final String ENTRY_PATH = PARENT_PATH + NAME; - public static final String NNIPC = "nnipc"; - public static final String IPC2 = "IPC2"; + public static final String NNIPC = "uuid:423C2B93-C927-4050-AEC6-6540E6646437"; + public static final String IPC2 = "uuid:0663501D-5AD3-4F7E-9419-52F5D6636FCF"; private static final Logger LOG = LoggerFactory.getLogger(RegistryTestHelper.class); - public static final String KTUTIL = "ktutil"; private static final RegistryUtils.ServiceRecordMarshal recordMarshal = new RegistryUtils.ServiceRecordMarshal(); + public static final String HTTP_API = "http://"; /** * Assert the path is valid by ZK rules @@ -148,9 +143,9 @@ public static void validateEntry(ServiceRecord record) { assertEquals(API_WEBHDFS, webhdfs.api); assertEquals(AddressTypes.ADDRESS_URI, webhdfs.addressType); assertEquals(ProtocolTypes.PROTOCOL_REST, webhdfs.protocolType); - List<List<String>> addressList = webhdfs.addresses; - List<String> url = addressList.get(0); - String addr = url.get(0); + List<Map<String, String>> addressList = webhdfs.addresses; + Map<String, String> url = addressList.get(0); + String addr = url.get("uri"); assertTrue(addr.contains("http")); assertTrue(addr.contains(":8020")); @@ -159,8 +154,9 @@ public static void validateEntry(ServiceRecord record) { nnipc.protocolType); Endpoint ipc2 = findEndpoint(record, IPC2, false, 1,2); + assertNotNull(ipc2); - Endpoint web = findEndpoint(record, "web", true, 1, 1); + Endpoint web = findEndpoint(record, HTTP_API, true, 1, 1); assertEquals(1, web.addresses.size()); assertEquals(1, web.addresses.get(0).size()); } @@ -275,14 +271,14 @@ public static ServiceRecord buildExampleServiceEntry(String persistence) throws public static void addSampleEndpoints(ServiceRecord entry, String hostname) throws URISyntaxException { assertNotNull(hostname); - entry.addExternalEndpoint(webEndpoint("web", + entry.addExternalEndpoint(webEndpoint(HTTP_API, new URI("http", hostname + ":80", "/"))); entry.addExternalEndpoint( restEndpoint(API_WEBHDFS, new URI("http", hostname + ":8020", "/"))); - Endpoint endpoint = ipcEndpoint(API_HDFS, true, null); - endpoint.addresses.add(tuple(hostname, "8030")); + Endpoint endpoint = ipcEndpoint(API_HDFS, null); + endpoint.addresses.add(RegistryTypeUtils.hostnamePortPair(hostname, 8030)); entry.addInternalEndpoint(endpoint); InetSocketAddress localhost = new InetSocketAddress("localhost", 8050); entry.addInternalEndpoint( @@ -290,9 +286,7 @@ public static void addSampleEndpoints(ServiceRecord entry, String hostname) 8050)); entry.addInternalEndpoint( RegistryTypeUtils.ipcEndpoint( - IPC2, - true, - RegistryTypeUtils.marshall(localhost))); + IPC2, localhost)); } /** diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/client/binding/TestMarshalling.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/client/binding/TestMarshalling.java index 14e3b1fa631ea..f1814d30707c0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/client/binding/TestMarshalling.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/client/binding/TestMarshalling.java @@ -19,9 +19,9 @@ package org.apache.hadoop.registry.client.binding; import org.apache.hadoop.registry.RegistryTestHelper; +import org.apache.hadoop.registry.client.exceptions.InvalidRecordException; import org.apache.hadoop.registry.client.exceptions.NoRecordException; import org.apache.hadoop.registry.client.types.ServiceRecord; -import org.apache.hadoop.registry.client.types.ServiceRecordHeader; import org.apache.hadoop.registry.client.types.yarn.PersistencePolicies; import org.junit.BeforeClass; import org.junit.Rule; @@ -31,8 +31,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.EOFException; - /** * Test record marshalling */ @@ -44,6 +42,7 @@ public class TestMarshalling extends RegistryTestHelper { public final Timeout testTimeout = new Timeout(10000); @Rule public TestName methodName = new TestName(); + private static RegistryUtils.ServiceRecordMarshal marshal; @BeforeClass @@ -55,42 +54,65 @@ public static void setupClass() { public void testRoundTrip() throws Throwable { String persistence = PersistencePolicies.PERMANENT; ServiceRecord record = createRecord(persistence); - record.set("customkey","customvalue"); - record.set("customkey2","customvalue2"); + record.set("customkey", "customvalue"); + record.set("customkey2", "customvalue2"); + RegistryTypeUtils.validateServiceRecord("", record); LOG.info(marshal.toJson(record)); byte[] bytes = marshal.toBytes(record); - ServiceRecord r2 = marshal.fromBytes("", bytes, 0); + ServiceRecord r2 = marshal.fromBytes("", bytes); assertMatches(record, r2); + RegistryTypeUtils.validateServiceRecord("", r2); } - @Test - public void testRoundTripHeaders() throws Throwable { - ServiceRecord record = createRecord(PersistencePolicies.CONTAINER); - byte[] bytes = marshal.toByteswithHeader(record); - ServiceRecord r2 = marshal.fromBytesWithHeader("", bytes); - assertMatches(record, r2); + @Test(expected = NoRecordException.class) + public void testUnmarshallNoData() throws Throwable { + marshal.fromBytes("src", new byte[]{}); } @Test(expected = NoRecordException.class) - public void testRoundTripBadHeaders() throws Throwable { - ServiceRecord record = createRecord(PersistencePolicies.APPLICATION); - byte[] bytes = marshal.toByteswithHeader(record); - bytes[1] = 0x01; - marshal.fromBytesWithHeader("src", bytes); + public void testUnmarshallNotEnoughData() throws Throwable { + // this is nominally JSON -but without the service record header + marshal.fromBytes("src", new byte[]{'{','}'}, ServiceRecord.RECORD_TYPE); + } + + @Test(expected = InvalidRecordException.class) + public void testUnmarshallNoBody() throws Throwable { + byte[] bytes = "this is not valid JSON at all and should fail".getBytes(); + marshal.fromBytes("src", bytes); + } + + @Test(expected = InvalidRecordException.class) + public void testUnmarshallWrongType() throws Throwable { + byte[] bytes = "{'type':''}".getBytes(); + ServiceRecord serviceRecord = marshal.fromBytes("marshalling", bytes); + RegistryTypeUtils.validateServiceRecord("validating", serviceRecord); } @Test(expected = NoRecordException.class) - public void testUnmarshallHeaderTooShort() throws Throwable { - marshal.fromBytesWithHeader("src", new byte[]{'a'}); + public void testUnmarshallWrongLongType() throws Throwable { + ServiceRecord record = new ServiceRecord(); + record.type = "ThisRecordHasALongButNonMatchingType"; + byte[] bytes = marshal.toBytes(record); + ServiceRecord serviceRecord = marshal.fromBytes("marshalling", + bytes, ServiceRecord.RECORD_TYPE); } - @Test(expected = EOFException.class) - public void testUnmarshallNoBody() throws Throwable { - byte[] bytes = ServiceRecordHeader.getData(); - marshal.fromBytesWithHeader("src", bytes); + @Test(expected = NoRecordException.class) + public void testUnmarshallNoType() throws Throwable { + ServiceRecord record = new ServiceRecord(); + record.type = "NoRecord"; + byte[] bytes = marshal.toBytes(record); + ServiceRecord serviceRecord = marshal.fromBytes("marshalling", + bytes, ServiceRecord.RECORD_TYPE); } + @Test(expected = InvalidRecordException.class) + public void testRecordValidationWrongType() throws Throwable { + ServiceRecord record = new ServiceRecord(); + record.type = "NotAServiceRecordType"; + RegistryTypeUtils.validateServiceRecord("validating", record); + } @Test public void testUnknownFieldsRoundTrip() throws Throwable { @@ -102,8 +124,8 @@ public void testUnknownFieldsRoundTrip() throws Throwable { assertEquals("2", record.get("intval")); assertNull(record.get("null")); assertEquals("defval", record.get("null", "defval")); - byte[] bytes = marshal.toByteswithHeader(record); - ServiceRecord r2 = marshal.fromBytesWithHeader("", bytes); + byte[] bytes = marshal.toBytes(record); + ServiceRecord r2 = marshal.fromBytes("", bytes); assertEquals("value", r2.get("key")); assertEquals("2", r2.get("intval")); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/operations/TestRegistryOperations.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/operations/TestRegistryOperations.java index 7a7f88cd51cb3..853d7f179095f 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/operations/TestRegistryOperations.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/test/java/org/apache/hadoop/registry/operations/TestRegistryOperations.java @@ -23,6 +23,7 @@ import org.apache.hadoop.fs.PathNotFoundException; import org.apache.hadoop.registry.AbstractRegistryTest; import org.apache.hadoop.registry.client.api.BindFlags; +import org.apache.hadoop.registry.client.binding.RegistryTypeUtils; import org.apache.hadoop.registry.client.binding.RegistryUtils; import org.apache.hadoop.registry.client.binding.RegistryPathUtils; import org.apache.hadoop.registry.client.exceptions.NoRecordException; @@ -91,10 +92,8 @@ public void testLsParent() throws Throwable { childStats.values()); assertEquals(1, records.size()); ServiceRecord record = records.get(ENTRY_PATH); - assertNotNull(record); - record.validate(); + RegistryTypeUtils.validateServiceRecord(ENTRY_PATH, record); assertMatches(written, record); - } @Test diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/registry/yarn-registry.md b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/registry/yarn-registry.md index a2a5009660fe6..b38d9fba5ba25 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/registry/yarn-registry.md +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/registry/yarn-registry.md @@ -352,6 +352,10 @@ application. <td>Name</td> <td>Description</td> </tr> + <tr> + <td>type: String</td> + <td>Always: "JSONServiceRecord"</td> + </tr> <tr> <td>description: String</td> <td>Human-readable description.</td> @@ -366,6 +370,8 @@ application. </tr> </table> +The type field MUST be `"JSONServiceRecord"`. Mandating this string allows future record types *and* permits rapid rejection of byte arrays that lack this string before attempting JSON parsing. + ### YARN Persistence policies The YARN Resource Manager integration integrates cleanup of service records @@ -379,7 +385,6 @@ any use of the registry without the RM's participation. The attributes, `yarn:id` and `yarn:persistence` specify which records *and any child entries* may be deleted as the associated YARN components complete. - The `yarn:id` field defines the application, attempt or container ID to match; the `yarn:persistence` attribute defines the trigger for record cleanup, and implicitly the type of the contents of the `yarn:id` field. @@ -432,31 +437,32 @@ up according the lifecycle of that application. <td>Description</td> </tr> <tr> - <td>addresses: List[List[String]]</td> - <td>a list of address tuples whose format depends on the address type</td> - </tr> - <tr> - <td>addressType: String</td> - <td>format of the binding</td> - </tr> + <td>api: URI as String</td> + <td>API implemented at the end of the binding</td> <tr> <td>protocol: String</td> <td>Protocol. Examples: `http`, `https`, `hadoop-rpc`, `zookeeper`, `web`, `REST`, `SOAP`, ...</td> </tr> <tr> - <td>api: String</td> - <td>API implemented at the end of the binding</td> + <td>addressType: String</td> + <td>format of the binding</td> </tr> + </tr> + <tr> + <td>addresses: List[Map[String, String]]</td> + <td>a list of address maps</td> + </tr> + </table> All string fields have a limit on size, to dissuade services from hiding complex JSON structures in the text description. -### Field: Address Type +#### Field `addressType`: Address Type -The addressType field defines the string format of entries. +The `addressType` field defines the string format of entries. Having separate types is that tools (such as a web viewer) can process binding strings without having to recognize the protocol. @@ -467,43 +473,58 @@ strings without having to recognize the protocol. <td>binding format</td> </tr> <tr> - <td>`url`</td> - <td>`[URL]`</td> + <td>uri</td> + <td>uri:URI of endpoint</td> </tr> <tr> - <td>`hostname`</td> - <td>`[hostname]`</td> + <td>hostname</td> + <td>hostname: service host</td> </tr> <tr> - <td>`inetaddress`</td> - <td>`[hostname, port]`</td> + <td>inetaddress</td> + <td>hostname: service host, port: service port</td> </tr> <tr> - <td>`path`</td> - <td>`[/path/to/something]`</td> + <td>path</td> + <td>path: generic unix filesystem path</td> </tr> <tr> - <td>`zookeeper`</td> - <td>`[quorum-entry, path]`</td> + <td>zookeeper</td> + <td>hostname: service host, port: service port, path: ZK path</td> </tr> </table> -An actual zookeeper binding consists of a list of `hostname:port` bindings –the -quorum— and the path within. In the proposed schema, every quorum entry will be -listed as a triple of `[hostname, port, path]`. Client applications do not -expect the path to de be different across the quorum. The first entry in the -list of quorum hosts MUST define the path to be used by all clients. Later -entries SHOULD list the same path, though clients MUST ignore these. +In the zookeeper binding, every entry represents a single node in quorum, +the `hostname` and `port` fields defining the hostname of the ZK instance +and the port on which it is listening. The `path` field lists zookeeper path +for applications to use. For example, for HBase this would refer to the znode +containing information about the HBase cluster. + +The path MUST be identical across all address elements in the `addresses` list. +This ensures that any single address contains enough information to connect +to the quorum and connect to the relevant znode. New Address types may be defined; if not standard please prefix with the character sequence `"x-"`. -#### **Field: API** +### Field `api`: API identifier + +The API field MUST contain a URI that identifies the specific API of an endpoint. +These MUST be unique to an API to avoid confusion. + +The following strategies are suggested to provide unique URIs for an API + +1. The SOAP/WS-* convention of using the URL to where the WSDL defining the service +2. A URL to the svn/git hosted document defining a REST API +3. the `classpath` schema followed by a path to a class or package in an application. +4. The `uuid` schema with a generated UUID. + +It is hoped that standard API URIs will be defined for common APIs. Two such non-normative APIs are used in this document + +* `http://` : A web site for humans +* `classpath:javax.management.jmx`: and endpoint supporting the JMX management protocol (RMI-based) -APIs may be unique to a service class, or may be common across by service -classes. They MUST be given unique names. These MAY be based on service -packages but MAY be derived from other naming schemes: ### Examples of Service Entries @@ -524,12 +545,14 @@ overall application. It exports the URL to a load balancer. { "description" : "tomcat-based web application", - "registrationTime" : 1408638082444, "external" : [ { - "api" : "www", + "api" : "http://internal.example.org/restapis/scheduler/20141026v1", "addressType" : "uri", - "protocolType" : "REST", - "addresses" : [ [ "http://loadbalancer/" ] [ "http://loadbalancer2/" ] ] + "protocol" : "REST", + "addresses" : [ + { "uri" : "http://loadbalancer/" }, + { "uri" : "http://loadbalancer2/" } + ] } ], "internal" : [ ] } @@ -545,21 +568,23 @@ will trigger the deletion of this entry /users/devteam/org-apache-tomcat/test1/components/container-1408631738011-0001-01-000001 { - "registrationTime" : 1408638082445, "yarn:id" : "container_1408631738011_0001_01_000001", - "yarn:persistence" : "3", - "description" : null, + "yarn:persistence" : "container", + "description" : "", "external" : [ { - "api" : "www", + "api" : "http://internal.example.org/restapis/scheduler/20141026v1", "addressType" : "uri", - "protocolType" : "REST", - "addresses" : [ [ "http://rack4server3:43572" ] ] + "protocol" : "REST", + "addresses" : [{ "uri" : "rack4server3:43572" } ] } ], "internal" : [ { - "api" : "jmx", + "api" : "classpath:javax.management.jmx", "addressType" : "host/port", - "protocolType" : "JMX", - "addresses" : [ [ "rack4server3", "43573" ] ] + "protocol" : "rmi", + "addresses" : [ { + "host" : "rack4server3", + "port" : "48551" + } ] } ] } @@ -571,19 +596,22 @@ external endpoint, the JMX addresses as internal. { "registrationTime" : 1408638082445, "yarn:id" : "container_1408631738011_0001_01_000002", - "yarn:persistence" : "3", + "yarn:persistence" : "container", "description" : null, "external" : [ { - "api" : "www", + "api" : "http://internal.example.org/restapis/scheduler/20141026v1", "addressType" : "uri", - "protocolType" : "REST", + "protocol" : "REST", "addresses" : [ [ "http://rack1server28:35881" ] ] } ], "internal" : [ { - "api" : "jmx", + "api" : "classpath:javax.management.jmx", "addressType" : "host/port", - "protocolType" : "JMX", - "addresses" : [ [ "rack1server28", "35882" ] ] + "protocol" : "rmi", + "addresses" : [ { + "host" : "rack1server28", + "port" : "48551" + } ] } ] } @@ -887,3 +915,106 @@ Implementations may throttle update operations. **Rate of Polling** Clients which poll the registry may be throttled. + +# Complete service record example + +Below is a (non-normative) example of a service record retrieved +from a YARN application. + + + { + "type" : "JSONServiceRecord", + "description" : "Slider Application Master", + "yarn:persistence" : "application", + "yarn:id" : "application_1414052463672_0028", + "external" : [ { + "api" : "classpath:org.apache.slider.appmaster", + "addressType" : "host/port", + "protocol" : "hadoop/IPC", + "addresses" : [ { + "port" : "48551", + "host" : "nn.example.com" + } ] + }, { + "api" : "http://", + "addressType" : "uri", + "protocol" : "web", + "addresses" : [ { + "uri" : "http://nn.example.com:40743" + } ] + }, { + "api" : "classpath:org.apache.slider.management", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "http://nn.example.com:40743/ws/v1/slider/mgmt" + } ] + }, { + "api" : "classpath:org.apache.slider.publisher", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "http://nn.example.com:40743/ws/v1/slider/publisher" + } ] + }, { + "api" : "classpath:org.apache.slider.registry", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "http://nn.example.com:40743/ws/v1/slider/registry" + } ] + }, { + "api" : "classpath:org.apache.slider.publisher.configurations", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "http://nn.example.com:40743/ws/v1/slider/publisher/slider" + } ] + }, { + "api" : "classpath:org.apache.slider.publisher.exports", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "http://nn.example.com:40743/ws/v1/slider/publisher/exports" + } ] + } ], + "internal" : [ { + "api" : "classpath:org.apache.slider.agents.secure", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "https://nn.example.com:52705/ws/v1/slider/agents" + } ] + }, { + "api" : "classpath:org.apache.slider.agents.oneway", + "addressType" : "uri", + "protocol" : "REST", + "addresses" : [ { + "uri" : "https://nn.example.com:33425/ws/v1/slider/agents" + } ] + } ] + } + +It publishes a number of endpoints, both internal and external. + +External: + +1. The IPC hostname and port for client-AM communications +1. URL to the AM's web UI +1. A series of REST URLs under the web UI for specific application services. +The details are irrelevant —note that they use an application-specific API +value to ensure uniqueness. + +Internal: +1. Two URLS to REST APIs offered by the AM for containers deployed by + the application itself. + +Python agents running in the containers retrieve the internal endpoint +URLs to communicate with their AM. The record is resolved on container startup +and cached until communications problems occur. At that point the registry is +queried for the current record, then an attempt is made to reconnect to the AM. + +Here "connectivity" problems means both "low level socket/IO errors" and +"failures in HTTPS authentication". The agents use two-way HTTPS authentication +—if the AM fails and another application starts listening on the same ports +it will trigger an authentication failure and hence service record reread.
15de1f5c92d90b583cce13d0bd7bda05d396adea
Delta Spike
DELTASPIKE-367 upgrade to final owb-arquillian-1.2.0
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml index 24ea1da9a..8437f796c 100644 --- a/deltaspike/parent/code/pom.xml +++ b/deltaspike/parent/code/pom.xml @@ -186,7 +186,7 @@ <dependency> <groupId>org.apache.openwebbeans.arquillian</groupId> <artifactId>owb-arquillian-standalone</artifactId> - <version>1.2.0-SNAPSHOT</version> + <version>1.2.0</version> <scope>test</scope> </dependency> </dependencies>
61401651a988791c5cd106f517ceb42ab2ef13e7
restlet-framework-java
- Improved exception handling on createResource().--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/Finder.java b/modules/org.restlet/src/org/restlet/Finder.java index bdf8e0d8e8..28ce55dca3 100644 --- a/modules/org.restlet/src/org/restlet/Finder.java +++ b/modules/org.restlet/src/org/restlet/Finder.java @@ -125,7 +125,9 @@ private boolean allowMethod(Method method, Resource target) { /** * Creates a new instance of the resource class designated by the - * "targetClass" property. + * "targetClass" property. Note that Error and RuntimeException thrown by + * Resource constructors are rethrown by this method. Other exception are + * caught and logged. * * @param request * The request to handle. @@ -158,6 +160,8 @@ public Resource createResource(Request request, Response response) { } catch (InvocationTargetException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); + } else if (e.getCause() instanceof RuntimeException) { + throw (RuntimeException) e.getCause(); } else { getLogger() .log(
7be3d247f90c23bbb11bc735276d51008243a7f6
kotlin
fix tests after recent refactoring--
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironment.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironment.java index 7d4c7ea5f85c2..1d1445118ddd3 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironment.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileEnvironment.java @@ -85,7 +85,7 @@ public CompileEnvironment(MessageRenderer messageRenderer, boolean verbose, Comp public void dispose() { } }; - environment = new JetCoreEnvironment(rootDisposable, mode == CompilerSpecialMode.REGULAR); + environment = new JetCoreEnvironment(rootDisposable, mode.includeJdkHeaders()); this.messageRenderer = messageRenderer; } @@ -282,7 +282,7 @@ private List<Module> runDefineModules(String moduleFile, ClassFileFactory factor public ClassFileFactory compileModule(Module moduleBuilder, String directory) { CompileSession moduleCompileSession = newCompileSession(); - moduleCompileSession.setStubs(mode != CompilerSpecialMode.REGULAR); + moduleCompileSession.setStubs(mode.isStubs()); if (moduleBuilder.getSourceFiles().isEmpty()) { throw new CompileEnvironmentException("No source files where defined"); @@ -403,7 +403,7 @@ public ClassLoader compileText(String code) { public boolean compileBunchOfSources(String sourceFileOrDir, String jar, String outputDir, boolean includeRuntime) { CompileSession session = newCompileSession(); - session.setStubs(mode != CompilerSpecialMode.REGULAR); + session.setStubs(mode.isStubs()); session.addSources(sourceFileOrDir); @@ -412,7 +412,7 @@ public boolean compileBunchOfSources(String sourceFileOrDir, String jar, String public boolean compileBunchOfSourceDirectories(List<String> sources, String jar, String outputDir, boolean includeRuntime) { CompileSession session = newCompileSession(); - session.setStubs(mode != CompilerSpecialMode.REGULAR); + session.setStubs(mode.isStubs()); for (String source : sources) { session.addSources(source); diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerSpecialMode.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerSpecialMode.java index 91535c783ed51..4fa7a42372cef 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerSpecialMode.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/CompilerSpecialMode.java @@ -29,4 +29,8 @@ public enum CompilerSpecialMode { public boolean includeJdkHeaders() { return this == REGULAR || this == STDLIB; } + + public boolean isStubs() { + return this == BUILTINS || this == JDK_HEADERS; + } }
37d68385670d60a4bb73d2947e9da1eef0173c6b
tapiji
Cleans up build stragegy.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html new file mode 100644 index 00000000..84ec2511 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html @@ -0,0 +1,261 @@ +<?xml version="1.0" encoding="ISO-8859-1" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> + +<head> +<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> +<title>Eclipse Public License - Version 1.0</title> +<style type="text/css"> + body { + size: 8.5in 11.0in; + margin: 0.25in 0.5in 0.25in 0.5in; + tab-interval: 0.5in; + } + p { + margin-left: auto; + margin-top: 0.5em; + margin-bottom: 0.5em; + } + p.list { + margin-left: 0.5in; + margin-top: 0.05em; + margin-bottom: 0.05em; + } + </style> + +</head> + +<body lang="EN-US"> + +<p align=center><b>Eclipse Public License - v 1.0</b></p> + +<p>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE +PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR +DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS +AGREEMENT.</p> + +<p><b>1. DEFINITIONS</b></p> + +<p>&quot;Contribution&quot; means:</p> + +<p class="list">a) in the case of the initial Contributor, the initial +code and documentation distributed under this Agreement, and</p> +<p class="list">b) in the case of each subsequent Contributor:</p> +<p class="list">i) changes to the Program, and</p> +<p class="list">ii) additions to the Program;</p> +<p class="list">where such changes and/or additions to the Program +originate from and are distributed by that particular Contributor. A +Contribution 'originates' from a Contributor if it was added to the +Program by such Contributor itself or anyone acting on such +Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in +conjunction with the Program under their own license agreement, and (ii) +are not derivative works of the Program.</p> + +<p>&quot;Contributor&quot; means any person or entity that distributes +the Program.</p> + +<p>&quot;Licensed Patents&quot; mean patent claims licensable by a +Contributor which are necessarily infringed by the use or sale of its +Contribution alone or when combined with the Program.</p> + +<p>&quot;Program&quot; means the Contributions distributed in accordance +with this Agreement.</p> + +<p>&quot;Recipient&quot; means anyone who receives the Program under +this Agreement, including all Contributors.</p> + +<p><b>2. GRANT OF RIGHTS</b></p> + +<p class="list">a) Subject to the terms of this Agreement, each +Contributor hereby grants Recipient a non-exclusive, worldwide, +royalty-free copyright license to reproduce, prepare derivative works +of, publicly display, publicly perform, distribute and sublicense the +Contribution of such Contributor, if any, and such derivative works, in +source code and object code form.</p> + +<p class="list">b) Subject to the terms of this Agreement, each +Contributor hereby grants Recipient a non-exclusive, worldwide, +royalty-free patent license under Licensed Patents to make, use, sell, +offer to sell, import and otherwise transfer the Contribution of such +Contributor, if any, in source code and object code form. This patent +license shall apply to the combination of the Contribution and the +Program if, at the time the Contribution is added by the Contributor, +such addition of the Contribution causes such combination to be covered +by the Licensed Patents. The patent license shall not apply to any other +combinations which include the Contribution. No hardware per se is +licensed hereunder.</p> + +<p class="list">c) Recipient understands that although each Contributor +grants the licenses to its Contributions set forth herein, no assurances +are provided by any Contributor that the Program does not infringe the +patent or other intellectual property rights of any other entity. Each +Contributor disclaims any liability to Recipient for claims brought by +any other entity based on infringement of intellectual property rights +or otherwise. As a condition to exercising the rights and licenses +granted hereunder, each Recipient hereby assumes sole responsibility to +secure any other intellectual property rights needed, if any. For +example, if a third party patent license is required to allow Recipient +to distribute the Program, it is Recipient's responsibility to acquire +that license before distributing the Program.</p> + +<p class="list">d) Each Contributor represents that to its knowledge it +has sufficient copyright rights in its Contribution, if any, to grant +the copyright license set forth in this Agreement.</p> + +<p><b>3. REQUIREMENTS</b></p> + +<p>A Contributor may choose to distribute the Program in object code +form under its own license agreement, provided that:</p> + +<p class="list">a) it complies with the terms and conditions of this +Agreement; and</p> + +<p class="list">b) its license agreement:</p> + +<p class="list">i) effectively disclaims on behalf of all Contributors +all warranties and conditions, express and implied, including warranties +or conditions of title and non-infringement, and implied warranties or +conditions of merchantability and fitness for a particular purpose;</p> + +<p class="list">ii) effectively excludes on behalf of all Contributors +all liability for damages, including direct, indirect, special, +incidental and consequential damages, such as lost profits;</p> + +<p class="list">iii) states that any provisions which differ from this +Agreement are offered by that Contributor alone and not by any other +party; and</p> + +<p class="list">iv) states that source code for the Program is available +from such Contributor, and informs licensees how to obtain it in a +reasonable manner on or through a medium customarily used for software +exchange.</p> + +<p>When the Program is made available in source code form:</p> + +<p class="list">a) it must be made available under this Agreement; and</p> + +<p class="list">b) a copy of this Agreement must be included with each +copy of the Program.</p> + +<p>Contributors may not remove or alter any copyright notices contained +within the Program.</p> + +<p>Each Contributor must identify itself as the originator of its +Contribution, if any, in a manner that reasonably allows subsequent +Recipients to identify the originator of the Contribution.</p> + +<p><b>4. COMMERCIAL DISTRIBUTION</b></p> + +<p>Commercial distributors of software may accept certain +responsibilities with respect to end users, business partners and the +like. While this license is intended to facilitate the commercial use of +the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create +potential liability for other Contributors. Therefore, if a Contributor +includes the Program in a commercial product offering, such Contributor +(&quot;Commercial Contributor&quot;) hereby agrees to defend and +indemnify every other Contributor (&quot;Indemnified Contributor&quot;) +against any losses, damages and costs (collectively &quot;Losses&quot;) +arising from claims, lawsuits and other legal actions brought by a third +party against the Indemnified Contributor to the extent caused by the +acts or omissions of such Commercial Contributor in connection with its +distribution of the Program in a commercial product offering. The +obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In +order to qualify, an Indemnified Contributor must: a) promptly notify +the Commercial Contributor in writing of such claim, and b) allow the +Commercial Contributor to control, and cooperate with the Commercial +Contributor in, the defense and any related settlement negotiations. The +Indemnified Contributor may participate in any such claim at its own +expense.</p> + +<p>For example, a Contributor might include the Program in a commercial +product offering, Product X. That Contributor is then a Commercial +Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance +claims and warranties are such Commercial Contributor's responsibility +alone. Under this section, the Commercial Contributor would have to +defend claims against the other Contributors related to those +performance claims and warranties, and if a court requires any other +Contributor to pay any damages as a result, the Commercial Contributor +must pay those damages.</p> + +<p><b>5. NO WARRANTY</b></p> + +<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS +PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, +ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY +OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and +distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement , including but not limited to +the risks and costs of program errors, compliance with applicable laws, +damage to or loss of data, programs or equipment, and unavailability or +interruption of operations.</p> + +<p><b>6. DISCLAIMER OF LIABILITY</b></p> + +<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT +NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR +DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> + +<p><b>7. GENERAL</b></p> + +<p>If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this Agreement, and without further action +by the parties hereto, such provision shall be reformed to the minimum +extent necessary to make such provision valid and enforceable.</p> + +<p>If Recipient institutes patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that the +Program itself (excluding combinations of the Program with other +software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the +date such litigation is filed.</p> + +<p>All Recipient's rights under this Agreement shall terminate if it +fails to comply with any of the material terms or conditions of this +Agreement and does not cure such failure in a reasonable period of time +after becoming aware of such noncompliance. If all Recipient's rights +under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive.</p> + +<p>Everyone is permitted to copy and distribute copies of this +Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The +Agreement Steward reserves the right to publish new versions (including +revisions) of this Agreement from time to time. No one other than the +Agreement Steward has the right to modify this Agreement. The Eclipse +Foundation is the initial Agreement Steward. The Eclipse Foundation may +assign the responsibility to serve as the Agreement Steward to a +suitable separate entity. Each new version of the Agreement will be +given a distinguishing version number. The Program (including +Contributions) may always be distributed subject to the version of the +Agreement under which it was received. In addition, after a new version +of the Agreement is published, Contributor may elect to distribute the +Program (including its Contributions) under the new version. Except as +expressly stated in Sections 2(a) and 2(b) above, Recipient receives no +rights or licenses to the intellectual property of any Contributor under +this Agreement, whether expressly, by implication, estoppel or +otherwise. All rights in the Program not expressly granted under this +Agreement are reserved.</p> + +<p>This Agreement is governed by the laws of the State of New York and +the intellectual property laws of the United States of America. No party +to this Agreement will bring a legal action under this Agreement more +than one year after the cause of action arose. Each party waives its +rights to a jury trial in any resulting litigation.</p> + +</body> + +</html> diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java index 604783c9..7f147a53 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java @@ -19,6 +19,7 @@ import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.dialogs.InputDialog; @@ -29,71 +30,73 @@ public class CreateResourceBundleEntry implements IMarkerResolution2 { - private String key; - private String bundleId; + private String key; + private String bundleId; - public CreateResourceBundleEntry(String key, String bundleId) { - this.key = key; - this.bundleId = bundleId; - } + public CreateResourceBundleEntry(String key, String bundleId) { + this.key = key; + this.bundleId = bundleId; + } + + @Override + public String getDescription() { + return "Creates a new Resource-Bundle entry for the property-key '" + + key + "'"; + } - @Override - public String getDescription() { - return "Creates a new Resource-Bundle entry for the property-key '" - + key + "'"; - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getLabel() { + return "Create Resource-Bundle entry for '" + key + "'"; + } - @Override - public String getLabel() { - return "Create Resource-Bundle entry for '" + key + "'"; - } + @Override + public void run(IMarker marker) { + int startPos = marker.getAttribute(IMarker.CHAR_START, 0); + int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; + IResource resource = marker.getResource(); - @Override - public void run(IMarker marker) { - int startPos = marker.getAttribute(IMarker.CHAR_START, 0); - int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; - IResource resource = marker.getResource(); + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(key != null ? key : ""); + config.setPreselectedMessage(""); + config.setPreselectedBundle(bundleId); + config.setPreselectedLocale(""); + config.setProjectName(resource.getProject().getName()); - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(key != null ? key : ""); - config.setPreselectedMessage(""); - config.setPreselectedBundle(bundleId); - config.setPreselectedLocale(""); - config.setProjectName(resource.getProject().getName()); + dialog.setDialogConfiguration(config); - dialog.setDialogConfiguration(config); + if (dialog.open() != InputDialog.OK) { + return; + } + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + } - if (dialog.open() != InputDialog.OK) - return; - } catch (Exception e) { - Logger.logError(e); - } finally { - try { - (new I18nBuilder()).buildResource(resource, null); - bufferManager.disconnect(path, null); - } catch (CoreException e) { - Logger.logError(e); - } } - } - } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java index 45762ea2..ecb947b4 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java @@ -20,6 +20,7 @@ import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IJavaProject; @@ -37,158 +38,164 @@ public class CreateResourceBundle implements IMarkerResolution2 { - private IResource resource; - private int start; - private int end; - private String key; - private boolean jsfContext; - private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; - - public CreateResourceBundle(String key, IResource resource, int start, - int end) { - this.key = ResourceUtils.deriveNonExistingRBName(key, - ResourceBundleManager.getManager(resource.getProject())); - this.resource = resource; - this.start = start; - this.end = end; - this.jsfContext = jsfContext; - } - - @Override - public String getDescription() { - return "Creates a new Resource-Bundle with the id '" + key + "'"; - } - - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getLabel() { - return "Create Resource-Bundle '" + key + "'"; - } - - @Override - public void run(IMarker marker) { - runAction(); - } - - protected void runAction() { - // First see if this is a "new wizard". - IWizardDescriptor descriptor = PlatformUI.getWorkbench() - .getNewWizardRegistry().findWizard(newBunldeWizard); - // If not check if it is an "import wizard". - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() - .findWizard(newBunldeWizard); + private IResource resource; + private int start; + private int end; + private String key; + private boolean jsfContext; + private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; + + public CreateResourceBundle(String key, IResource resource, int start, + int end) { + this.key = ResourceUtils.deriveNonExistingRBName(key, + ResourceBundleManager.getManager(resource.getProject())); + this.resource = resource; + this.start = start; + this.end = end; + this.jsfContext = jsfContext; } - // Or maybe an export wizard - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() - .findWizard(newBunldeWizard); + + @Override + public String getDescription() { + return "Creates a new Resource-Bundle with the id '" + key + "'"; } - try { - // Then if we have a wizard, open it. - if (descriptor != null) { - IWizard wizard = descriptor.createWizard(); - if (!(wizard instanceof IResourceBundleWizard)) - return; - - IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; - String[] keySilbings = key.split("\\."); - String rbName = keySilbings[keySilbings.length - 1]; - String packageName = ""; - - rbw.setBundleId(rbName); - - // Set the default path according to the specified package name - String pathName = ""; - if (keySilbings.length > 1) { - try { - IJavaProject jp = JavaCore - .create(resource.getProject()); - packageName = key.substring(0, key.lastIndexOf(".")); - - for (IPackageFragmentRoot fr : jp - .getAllPackageFragmentRoots()) { - IPackageFragment pf = fr - .getPackageFragment(packageName); - if (pf.exists()) { - pathName = pf.getResource().getFullPath() - .removeFirstSegments(0).toOSString(); - break; - } - } - } catch (Exception e) { - pathName = ""; - } - } - try { - IJavaProject jp = JavaCore.create(resource.getProject()); - if (pathName.trim().equals("")) { - for (IPackageFragmentRoot fr : jp - .getAllPackageFragmentRoots()) { - if (!fr.isReadOnly()) { - pathName = fr.getResource().getFullPath() - .removeFirstSegments(0).toOSString(); - break; - } - } - } - } catch (Exception e) { - pathName = ""; - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } - rbw.setDefaultPath(pathName); - - WizardDialog wd = new WizardDialog(Display.getDefault() - .getActiveShell(), wizard); - wd.setTitle(wizard.getWindowTitle()); - if (wd.open() == WizardDialog.OK) { - (new I18nBuilder()).buildProject(null, - resource.getProject()); - (new I18nBuilder()).buildResource(resource, null); - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); - - if (document.get().charAt(start - 1) == '"' - && document.get().charAt(start) != '"') { - start--; - end++; - } - if (document.get().charAt(end + 1) == '"' - && document.get().charAt(end) != '"') - end++; + @Override + public String getLabel() { + return "Create Resource-Bundle '" + key + "'"; + } - document.replace(start, end - start, "\"" - + (packageName.equals("") ? "" : packageName - + ".") + rbName + "\""); + @Override + public void run(IMarker marker) { + runAction(); + } - textFileBuffer.commit(null, false); - } catch (Exception e) { - Logger.logError(e); - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - Logger.logError(e); + protected void runAction() { + // First see if this is a "new wizard". + IWizardDescriptor descriptor = PlatformUI.getWorkbench() + .getNewWizardRegistry().findWizard(newBunldeWizard); + // If not check if it is an "import wizard". + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() + .findWizard(newBunldeWizard); + } + // Or maybe an export wizard + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() + .findWizard(newBunldeWizard); + } + try { + // Then if we have a wizard, open it. + if (descriptor != null) { + IWizard wizard = descriptor.createWizard(); + if (!(wizard instanceof IResourceBundleWizard)) { + return; + } + + IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; + String[] keySilbings = key.split("\\."); + String rbName = keySilbings[keySilbings.length - 1]; + String packageName = ""; + + rbw.setBundleId(rbName); + + // Set the default path according to the specified package name + String pathName = ""; + if (keySilbings.length > 1) { + try { + IJavaProject jp = JavaCore + .create(resource.getProject()); + packageName = key.substring(0, key.lastIndexOf(".")); + + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + IPackageFragment pf = fr + .getPackageFragment(packageName); + if (pf.exists()) { + pathName = pf.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } + } + } catch (Exception e) { + pathName = ""; + } + } + + try { + IJavaProject jp = JavaCore.create(resource.getProject()); + if (pathName.trim().equals("")) { + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + if (!fr.isReadOnly()) { + pathName = fr.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } + } + } + } catch (Exception e) { + pathName = ""; + } + + rbw.setDefaultPath(pathName); + + WizardDialog wd = new WizardDialog(Display.getDefault() + .getActiveShell(), wizard); + wd.setTitle(wizard.getWindowTitle()); + if (wd.open() == WizardDialog.OK) { + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); + + if (document.get().charAt(start - 1) == '"' + && document.get().charAt(start) != '"') { + start--; + end++; + } + if (document.get().charAt(end + 1) == '"' + && document.get().charAt(end) != '"') { + end++; + } + + document.replace(start, end - start, "\"" + + (packageName.equals("") ? "" : packageName + + ".") + rbName + "\""); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + Logger.logError(e); + } + } + } } - } + } catch (CoreException e) { + Logger.logError(e); } - } - } catch (CoreException e) { - Logger.logError(e); } - } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java index b41328e0..578d190c 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java @@ -48,6 +48,7 @@ import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; @@ -60,753 +61,786 @@ public class ResourceBundleManager { - public static String defaultLocaleTag = "[default]"; // TODO externalize + public static String defaultLocaleTag = "[default]"; // TODO externalize - /*** CONFIG SECTION ***/ - private static boolean checkResourceExclusionRoot = false; + /*** CONFIG SECTION ***/ + private static boolean checkResourceExclusionRoot = false; - /*** MEMBER SECTION ***/ - private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>(); + /*** MEMBER SECTION ***/ + private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>(); - public static final String RESOURCE_BUNDLE_EXTENSION = ".properties"; + public static final String RESOURCE_BUNDLE_EXTENSION = ".properties"; - // project-specific - private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>(); - - private Map<String, String> bundleNames = new HashMap<String, String>(); - - private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>(); - - private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>(); - - // global - private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>(); - - private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>(); - - private static IResourceChangeListener changelistener; - - /* Host project */ - private IProject project = null; - - /** State-Serialization Information **/ - private static boolean state_loaded = false; - private static final String TAG_INTERNATIONALIZATION = "Internationalization"; - private static final String TAG_EXCLUDED = "Excluded"; - private static final String TAG_RES_DESC = "ResourceDescription"; - private static final String TAG_RES_DESC_ABS = "AbsolutePath"; - private static final String TAG_RES_DESC_REL = "RelativePath"; - private static final String TAB_RES_DESC_PRO = "ProjectName"; - private static final String TAB_RES_DESC_BID = "BundleId"; - - // Define private constructor - private ResourceBundleManager() { - } - - public static ResourceBundleManager getManager(IProject project) { - // check if persistant state has been loaded - if (!state_loaded) - loadManagerState(); - - // set host-project - if (FragmentProjectUtils.isFragment(project)) - project = FragmentProjectUtils.getFragmentHost(project); - - ResourceBundleManager manager = rbmanager.get(project); - if (manager == null) { - manager = new ResourceBundleManager(); - manager.project = project; - rbmanager.put(project, manager); - manager.detectResourceBundles(); - - } - return manager; - } - - public Set<Locale> getProvidedLocales(String bundleName) { - RBManager instance = RBManager.getInstance(project); - - Set<Locale> locales = new HashSet<Locale>(); - IMessagesBundleGroup group = instance - .getMessagesBundleGroup(bundleName); - if (group == null) - return locales; - - for (IMessagesBundle bundle : group.getMessagesBundles()) { - locales.add(bundle.getLocale()); - } - return locales; - } - - public static String getResourceBundleName(IResource res) { - String name = res.getName(); - String regex = "^(.*?)" //$NON-NLS-1$ - + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ - + res.getFileExtension() + ")$"; //$NON-NLS-1$ - return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ - } - - protected boolean isResourceBundleLoaded(String bundleName) { - return RBManager.getInstance(project).containsMessagesBundleGroup( - bundleName); - } - - protected Locale getLocaleByName(String bundleName, String localeID) { - // Check locale - Locale locale = null; - bundleName = bundleNames.get(bundleName); - localeID = localeID.substring(0, - localeID.length() - "properties".length() - 1); - if (localeID.length() == bundleName.length()) { - // default locale - return null; - } else { - localeID = localeID.substring(bundleName.length() + 1); - String[] localeTokens = localeID.split("_"); - - switch (localeTokens.length) { - case 1: - locale = new Locale(localeTokens[0]); - break; - case 2: - locale = new Locale(localeTokens[0], localeTokens[1]); - break; - case 3: - locale = new Locale(localeTokens[0], localeTokens[1], - localeTokens[2]); - break; - default: - locale = null; - break; - } - } - - return locale; - } - - protected void unloadResource(String bundleName, IResource resource) { - // TODO implement more efficient - unloadResourceBundle(bundleName); - // loadResourceBundle(bundleName); - } - - public static String getResourceBundleId(IResource resource) { - String packageFragment = ""; - - IJavaElement propertyFile = JavaCore.create(resource.getParent()); - if (propertyFile != null && propertyFile instanceof IPackageFragment) - packageFragment = ((IPackageFragment) propertyFile) - .getElementName(); - - return (packageFragment.length() > 0 ? packageFragment + "." : "") - + getResourceBundleName(resource); - } - - public void addBundleResource(IResource resource) { - if (resource.isDerived()) - return; - - String bundleName = getResourceBundleId(resource); - Set<IResource> res; - - if (!resources.containsKey(bundleName)) - res = new HashSet<IResource>(); - else - res = resources.get(bundleName); - - res.add(resource); - resources.put(bundleName, res); - allBundles.put(bundleName, new HashSet<IResource>(res)); - bundleNames.put(bundleName, getResourceBundleName(resource)); - - // Fire resource changed event - ResourceBundleChangedEvent event = new ResourceBundleChangedEvent( - ResourceBundleChangedEvent.ADDED, bundleName, - resource.getProject()); - this.fireResourceBundleChangedEvent(bundleName, event); - } - - protected void removeAllBundleResources(String bundleName) { - unloadResourceBundle(bundleName); - resources.remove(bundleName); - // allBundles.remove(bundleName); - listeners.remove(bundleName); - } - - public void unloadResourceBundle(String name) { - RBManager instance = RBManager.getInstance(project); - instance.deleteMessagesBundleGroup(name); - } - - public IMessagesBundleGroup getResourceBundle(String name) { - RBManager instance = RBManager.getInstance(project); - return instance.getMessagesBundleGroup(name); - } - - public Collection<IResource> getResourceBundles(String bundleName) { - return resources.get(bundleName); - } - - public List<String> getResourceBundleNames() { - List<String> returnList = new ArrayList<String>(); - - Iterator<String> it = resources.keySet().iterator(); - while (it.hasNext()) { - returnList.add(it.next()); - } - return returnList; - } - - public IResource getResourceFile(String file) { - String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$"; - String bundleName = file.replaceFirst(regex, "$1"); - IResource resource = null; - - for (IResource res : resources.get(bundleName)) { - if (res.getName().equalsIgnoreCase(file)) { - resource = res; - break; - } - } - - return resource; - } - - public void fireResourceBundleChangedEvent(String bundleName, - ResourceBundleChangedEvent event) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); - - if (l == null) - return; - - for (IResourceBundleChangedListener listener : l) { - listener.resourceBundleChanged(event); - } - } - - public void registerResourceBundleChangeListener(String bundleName, - IResourceBundleChangedListener listener) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); - if (l == null) - l = new ArrayList<IResourceBundleChangedListener>(); - l.add(listener); - listeners.put(bundleName, l); - } - - public void unregisterResourceBundleChangeListener(String bundleName, - IResourceBundleChangedListener listener) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); - if (l == null) - return; - l.remove(listener); - listeners.put(bundleName, l); - } - - protected void detectResourceBundles() { - try { - project.accept(new ResourceBundleDetectionVisitor(getProject())); - - IProject[] fragments = FragmentProjectUtils.lookupFragment(project); - if (fragments != null) { - for (IProject p : fragments) { - p.accept(new ResourceBundleDetectionVisitor(getProject())); - } - } - } catch (CoreException e) { - } - } - - public IProject getProject() { - return project; - } - - public List<String> getResourceBundleIdentifiers() { - List<String> returnList = new ArrayList<String>(); - - // TODO check other resource bundles that are available on the curren - // class path - Iterator<String> it = this.resources.keySet().iterator(); - while (it.hasNext()) { - returnList.add(it.next()); - } + // project-specific + private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>(); - return returnList; - } - - public static List<String> getAllResourceBundleNames() { - List<String> returnList = new ArrayList<String>(); + private Map<String, String> bundleNames = new HashMap<String, String>(); - for (IProject p : getAllSupportedProjects()) { - if (!FragmentProjectUtils.isFragment(p)) { - Iterator<String> it = getManager(p).resources.keySet() - .iterator(); + private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>(); + + private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>(); + + // global + private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>(); + + private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>(); + + private static IResourceChangeListener changelistener; + + /* Host project */ + private IProject project = null; + + /** State-Serialization Information **/ + private static boolean state_loaded = false; + private static final String TAG_INTERNATIONALIZATION = "Internationalization"; + private static final String TAG_EXCLUDED = "Excluded"; + private static final String TAG_RES_DESC = "ResourceDescription"; + private static final String TAG_RES_DESC_ABS = "AbsolutePath"; + private static final String TAG_RES_DESC_REL = "RelativePath"; + private static final String TAB_RES_DESC_PRO = "ProjectName"; + private static final String TAB_RES_DESC_BID = "BundleId"; + + // Define private constructor + private ResourceBundleManager() { + } + + public static ResourceBundleManager getManager(IProject project) { + // check if persistant state has been loaded + if (!state_loaded) { + loadManagerState(); + } + + // set host-project + if (FragmentProjectUtils.isFragment(project)) { + project = FragmentProjectUtils.getFragmentHost(project); + } + + ResourceBundleManager manager = rbmanager.get(project); + if (manager == null) { + manager = new ResourceBundleManager(); + manager.project = project; + rbmanager.put(project, manager); + manager.detectResourceBundles(); + + } + return manager; + } + + public Set<Locale> getProvidedLocales(String bundleName) { + RBManager instance = RBManager.getInstance(project); + + Set<Locale> locales = new HashSet<Locale>(); + IMessagesBundleGroup group = instance + .getMessagesBundleGroup(bundleName); + if (group == null) { + return locales; + } + + for (IMessagesBundle bundle : group.getMessagesBundles()) { + locales.add(bundle.getLocale()); + } + return locales; + } + + public static String getResourceBundleName(IResource res) { + String name = res.getName(); + String regex = "^(.*?)" //$NON-NLS-1$ + + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ + + res.getFileExtension() + ")$"; //$NON-NLS-1$ + return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ + } + + protected boolean isResourceBundleLoaded(String bundleName) { + return RBManager.getInstance(project).containsMessagesBundleGroup( + bundleName); + } + + protected Locale getLocaleByName(String bundleName, String localeID) { + // Check locale + Locale locale = null; + bundleName = bundleNames.get(bundleName); + localeID = localeID.substring(0, + localeID.length() - "properties".length() - 1); + if (localeID.length() == bundleName.length()) { + // default locale + return null; + } else { + localeID = localeID.substring(bundleName.length() + 1); + String[] localeTokens = localeID.split("_"); + + switch (localeTokens.length) { + case 1: + locale = new Locale(localeTokens[0]); + break; + case 2: + locale = new Locale(localeTokens[0], localeTokens[1]); + break; + case 3: + locale = new Locale(localeTokens[0], localeTokens[1], + localeTokens[2]); + break; + default: + locale = null; + break; + } + } + + return locale; + } + + protected void unloadResource(String bundleName, IResource resource) { + // TODO implement more efficient + unloadResourceBundle(bundleName); + // loadResourceBundle(bundleName); + } + + public static String getResourceBundleId(IResource resource) { + String packageFragment = ""; + + IJavaElement propertyFile = JavaCore.create(resource.getParent()); + if (propertyFile != null && propertyFile instanceof IPackageFragment) { + packageFragment = ((IPackageFragment) propertyFile) + .getElementName(); + } + + return (packageFragment.length() > 0 ? packageFragment + "." : "") + + getResourceBundleName(resource); + } + + public void addBundleResource(IResource resource) { + if (resource.isDerived()) { + return; + } + + String bundleName = getResourceBundleId(resource); + Set<IResource> res; + + if (!resources.containsKey(bundleName)) { + res = new HashSet<IResource>(); + } else { + res = resources.get(bundleName); + } + + res.add(resource); + resources.put(bundleName, res); + allBundles.put(bundleName, new HashSet<IResource>(res)); + bundleNames.put(bundleName, getResourceBundleName(resource)); + + // Fire resource changed event + ResourceBundleChangedEvent event = new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.ADDED, bundleName, + resource.getProject()); + this.fireResourceBundleChangedEvent(bundleName, event); + } + + protected void removeAllBundleResources(String bundleName) { + unloadResourceBundle(bundleName); + resources.remove(bundleName); + // allBundles.remove(bundleName); + listeners.remove(bundleName); + } + + public void unloadResourceBundle(String name) { + RBManager instance = RBManager.getInstance(project); + instance.deleteMessagesBundleGroup(name); + } + + public IMessagesBundleGroup getResourceBundle(String name) { + RBManager instance = RBManager.getInstance(project); + return instance.getMessagesBundleGroup(name); + } + + public Collection<IResource> getResourceBundles(String bundleName) { + return resources.get(bundleName); + } + + public List<String> getResourceBundleNames() { + List<String> returnList = new ArrayList<String>(); + + Iterator<String> it = resources.keySet().iterator(); while (it.hasNext()) { - returnList.add(p.getName() + "/" + it.next()); + returnList.add(it.next()); } - } + return returnList; } - return returnList; - } - public static Set<IProject> getAllSupportedProjects() { - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() - .getProjects(); - Set<IProject> projs = new HashSet<IProject>(); + public IResource getResourceFile(String file) { + String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$"; + String bundleName = file.replaceFirst(regex, "$1"); + IResource resource = null; + + for (IResource res : resources.get(bundleName)) { + if (res.getName().equalsIgnoreCase(file)) { + resource = res; + break; + } + } - for (IProject p : projects) { - if (InternationalizationNature.hasNature(p)) - projs.add(p); + return resource; } - return projs; - } - public String getKeyHoverString(String rbName, String key) { - try { - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup bundleGroup = instance - .getMessagesBundleGroup(rbName); - if (!bundleGroup.containsKey(key)) - return null; + public void fireResourceBundleChangedEvent(String bundleName, + ResourceBundleChangedEvent event) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + + if (l == null) { + return; + } + + for (IResourceBundleChangedListener listener : l) { + listener.resourceBundleChanged(event); + } + } + + public void registerResourceBundleChangeListener(String bundleName, + IResourceBundleChangedListener listener) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + if (l == null) { + l = new ArrayList<IResourceBundleChangedListener>(); + } + l.add(listener); + listeners.put(bundleName, l); + } + + public void unregisterResourceBundleChangeListener(String bundleName, + IResourceBundleChangedListener listener) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + if (l == null) { + return; + } + l.remove(listener); + listeners.put(bundleName, l); + } + + protected void detectResourceBundles() { + try { + project.accept(new ResourceBundleDetectionVisitor(getProject())); + + IProject[] fragments = FragmentProjectUtils.lookupFragment(project); + if (fragments != null) { + for (IProject p : fragments) { + p.accept(new ResourceBundleDetectionVisitor(getProject())); + } + } + } catch (CoreException e) { + } + } + + public IProject getProject() { + return project; + } + + public List<String> getResourceBundleIdentifiers() { + List<String> returnList = new ArrayList<String>(); + + // TODO check other resource bundles that are available on the curren + // class path + Iterator<String> it = this.resources.keySet().iterator(); + while (it.hasNext()) { + returnList.add(it.next()); + } + + return returnList; + } + + public static List<String> getAllResourceBundleNames() { + List<String> returnList = new ArrayList<String>(); + + for (IProject p : getAllSupportedProjects()) { + if (!FragmentProjectUtils.isFragment(p)) { + Iterator<String> it = getManager(p).resources.keySet() + .iterator(); + while (it.hasNext()) { + returnList.add(p.getName() + "/" + it.next()); + } + } + } + return returnList; + } + + public static Set<IProject> getAllSupportedProjects() { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() + .getProjects(); + Set<IProject> projs = new HashSet<IProject>(); + + for (IProject p : projects) { + if (InternationalizationNature.hasNature(p)) { + projs.add(p); + } + } + return projs; + } - String hoverText = "<html><head></head><body>"; - - for (IMessage message : bundleGroup.getMessages(key)) { - String displayName = message.getLocale() == null ? "Default" - : message.getLocale().getDisplayName(); - String value = message.getValue(); - hoverText += "<b><i>" + displayName + "</i></b><br/>" - + value.replace("\n", "<br/>") + "<br/><br/>"; - } - return hoverText + "</body></html>"; - } catch (Exception e) { - // silent catch - return ""; - } - } - - public boolean isKeyBroken(String rbName, String key) { - IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( - project).getMessagesBundleGroup(rbName); - if (messagesBundleGroup == null) { - return true; - } else { - return !messagesBundleGroup.containsKey(key); - } - - // if (!resourceBundles.containsKey(rbName)) - // return true; - // return !this.isResourceExisting(rbName, key); - } - - protected void excludeSingleResource(IResource res) { - IResourceDescriptor rd = new ResourceDescriptor(res); - EditorUtils.deleteAuditMarkersForResource(res); - - // exclude resource - excludedResources.add(rd); - Collection<Object> changedExclusoins = new HashSet<Object>(); - changedExclusoins.add(res); - fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins)); - - // Check if the excluded resource represents a resource-bundle - if (RBFileUtils.isResourceBundleFile(res)) { - String bundleName = getResourceBundleId(res); - Set<IResource> resSet = resources.remove(bundleName); - if (resSet != null) { - resSet.remove(res); - - if (!resSet.isEmpty()) { - resources.put(bundleName, resSet); - unloadResource(bundleName, res); + public String getKeyHoverString(String rbName, String key) { + try { + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance + .getMessagesBundleGroup(rbName); + if (!bundleGroup.containsKey(key)) { + return null; + } + + String hoverText = "<html><head></head><body>"; + + for (IMessage message : bundleGroup.getMessages(key)) { + String displayName = message.getLocale() == null ? "Default" + : message.getLocale().getDisplayName(); + String value = message.getValue(); + hoverText += "<b><i>" + displayName + "</i></b><br/>" + + value.replace("\n", "<br/>") + "<br/><br/>"; + } + return hoverText + "</body></html>"; + } catch (Exception e) { + // silent catch + return ""; + } + } + + public boolean isKeyBroken(String rbName, String key) { + IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( + project).getMessagesBundleGroup(rbName); + if (messagesBundleGroup == null) { + return true; } else { - rd.setBundleId(bundleName); - unloadResourceBundle(bundleName); - (new I18nBuilder()).buildProject(null, res.getProject()); - } - - fireResourceBundleChangedEvent(getResourceBundleId(res), - new ResourceBundleChangedEvent( - ResourceBundleChangedEvent.EXCLUDED, - bundleName, res.getProject())); - } - } - } - - public void excludeResource(IResource res, IProgressMonitor monitor) { - try { - if (monitor == null) - monitor = new NullProgressMonitor(); - - final List<IResource> resourceSubTree = new ArrayList<IResource>(); - res.accept(new IResourceVisitor() { - - @Override - public boolean visit(IResource resource) throws CoreException { - Logger.logInfo("Excluding resource '" - + resource.getFullPath().toOSString() + "'"); - resourceSubTree.add(resource); - return true; - } - - }); - - // Iterate previously retrieved resource and exclude them from - // Internationalization - monitor.beginTask( - "Exclude resources from Internationalization context", - resourceSubTree.size()); - try { - for (IResource resource : resourceSubTree) { - excludeSingleResource(resource); - EditorUtils.deleteAuditMarkersForResource(resource); - monitor.worked(1); - } - } catch (Exception e) { - Logger.logError(e); - } finally { - monitor.done(); - } - } catch (CoreException e) { - Logger.logError(e); - } - } - - public void includeResource(IResource res, IProgressMonitor monitor) { - if (monitor == null) - monitor = new NullProgressMonitor(); - - final Collection<Object> changedResources = new HashSet<Object>(); - IResource resource = res; - - if (!excludedResources.contains(new ResourceDescriptor(res))) { - while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) { - if (excludedResources - .contains(new ResourceDescriptor(resource))) { - excludeResource(resource, monitor); - changedResources.add(resource); - break; - } else - resource = resource.getParent(); - } - } - - try { - res.accept(new IResourceVisitor() { - - @Override - public boolean visit(IResource resource) throws CoreException { - changedResources.add(resource); - return true; - } - }); - - monitor.beginTask("Add resources to Internationalization context", - changedResources.size()); - try { - for (Object r : changedResources) { - excludedResources.remove(new ResourceDescriptor( - (IResource) r)); - monitor.worked(1); - } - - } catch (Exception e) { - Logger.logError(e); - } finally { - monitor.done(); - } - } catch (Exception e) { - Logger.logError(e); - } - - (new I18nBuilder()).buildResource(res, null); - - // Check if the included resource represents a resource-bundle - if (RBFileUtils.isResourceBundleFile(res)) { - String bundleName = getResourceBundleId(res); - boolean newRB = resources.containsKey(bundleName); - - this.addBundleResource(res); - this.unloadResourceBundle(bundleName); - // this.loadResourceBundle(bundleName); - - if (newRB) - (new I18nBuilder()).buildProject(null, res.getProject()); - fireResourceBundleChangedEvent(getResourceBundleId(res), - new ResourceBundleChangedEvent( - ResourceBundleChangedEvent.INCLUDED, bundleName, - res.getProject())); - } - - fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources)); - } - - protected void fireResourceExclusionEvent(ResourceExclusionEvent event) { - for (IResourceExclusionListener listener : exclusionListeners) - listener.exclusionChanged(event); - } - - public static boolean isResourceExcluded(IResource res) { - IResource resource = res; - - if (!state_loaded) - loadManagerState(); - - boolean isExcluded = false; - - do { - if (excludedResources.contains(new ResourceDescriptor(resource))) { - if (RBFileUtils.isResourceBundleFile(resource)) { - Set<IResource> resources = allBundles - .remove(getResourceBundleName(resource)); - if (resources == null) - resources = new HashSet<IResource>(); - resources.add(resource); - allBundles.put(getResourceBundleName(resource), resources); - } - - isExcluded = true; - break; - } - resource = resource.getParent(); - } while (resource != null - && !(resource instanceof IProject || resource instanceof IWorkspaceRoot) - && checkResourceExclusionRoot); - - return isExcluded; // excludedResources.contains(new - // ResourceDescriptor(res)); - } - - public IFile getRandomFile(String bundleName) { - try { - IResource res = (resources.get(bundleName)).iterator().next(); - return res.getProject().getFile(res.getProjectRelativePath()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - private static void loadManagerState() { - excludedResources = new HashSet<IResourceDescriptor>(); - FileReader reader = null; - try { - reader = new FileReader(FileUtils.getRBManagerStateFile()); - loadManagerState(XMLMemento.createReadRoot(reader)); - state_loaded = true; - } catch (Exception e) { - // do nothing - } - - changelistener = new RBChangeListner(); - ResourcesPlugin.getWorkspace().addResourceChangeListener( - changelistener, - IResourceChangeEvent.PRE_DELETE - | IResourceChangeEvent.POST_CHANGE); - } - - private static void loadManagerState(XMLMemento memento) { - IMemento excludedChild = memento.getChild(TAG_EXCLUDED); - for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) { - IResourceDescriptor descriptor = new ResourceDescriptor(); - descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS)); - descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL)); - descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO)); - descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID)); - excludedResources.add(descriptor); - } - } - - public static void saveManagerState() { - if (excludedResources == null) - return; - XMLMemento memento = XMLMemento - .createWriteRoot(TAG_INTERNATIONALIZATION); - IMemento exclChild = memento.createChild(TAG_EXCLUDED); - - Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); - while (itExcl.hasNext()) { - IResourceDescriptor desc = itExcl.next(); - IMemento resDesc = exclChild.createChild(TAG_RES_DESC); - resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName()); - resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath()); - resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath()); - resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId()); - } - FileWriter writer = null; - try { - writer = new FileWriter(FileUtils.getRBManagerStateFile()); - memento.save(writer); - } catch (Exception e) { - // do nothing - } finally { - try { - if (writer != null) - writer.close(); - } catch (Exception e) { - // do nothing - } - } - } - - @Deprecated - protected static boolean isResourceExcluded(IProject project, String bname) { - Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); - while (itExcl.hasNext()) { - IResourceDescriptor rd = itExcl.next(); - if (project.getName().equals(rd.getProjectName()) - && bname.equals(rd.getBundleId())) - return true; - } - return false; - } - - public static ResourceBundleManager getManager(String projectName) { - for (IProject p : getAllSupportedProjects()) { - if (p.getName().equalsIgnoreCase(projectName)) { - // check if the projectName is a fragment and return the manager - // for the host - if (FragmentProjectUtils.isFragment(p)) - return getManager(FragmentProjectUtils.getFragmentHost(p)); - else - return getManager(p); - } - } - return null; - } - - public IFile getResourceBundleFile(String resourceBundle, Locale l) { - IFile res = null; - Set<IResource> resSet = resources.get(resourceBundle); - - if (resSet != null) { - for (IResource resource : resSet) { - Locale refLoc = getLocaleByName(resourceBundle, - resource.getName()); - if (refLoc == null - && l == null - || (refLoc != null && refLoc.equals(l) || l != null - && l.equals(refLoc))) { - res = resource.getProject().getFile( - resource.getProjectRelativePath()); - break; - } - } - } - - return res; - } - - public Set<IResource> getAllResourceBundleResources(String resourceBundle) { - return allBundles.get(resourceBundle); - } - - public void registerResourceExclusionListener( - IResourceExclusionListener listener) { - exclusionListeners.add(listener); - } - - public void unregisterResourceExclusionListener( - IResourceExclusionListener listener) { - exclusionListeners.remove(listener); - } - - public boolean isResourceExclusionListenerRegistered( - IResourceExclusionListener listener) { - return exclusionListeners.contains(listener); - } - - public static void unregisterResourceExclusionListenerFromAllManagers( - IResourceExclusionListener excludedResource) { - for (ResourceBundleManager mgr : rbmanager.values()) { - mgr.unregisterResourceExclusionListener(excludedResource); - } - } - - public void addResourceBundleEntry(String resourceBundleId, String key, - Locale locale, String message) throws ResourceBundleException { - - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup bundleGroup = instance - .getMessagesBundleGroup(resourceBundleId); - IMessage entry = bundleGroup.getMessage(key, locale); + return !messagesBundleGroup.containsKey(key); + } + + // if (!resourceBundles.containsKey(rbName)) + // return true; + // return !this.isResourceExisting(rbName, key); + } + + protected void excludeSingleResource(IResource res) { + IResourceDescriptor rd = new ResourceDescriptor(res); + EditorUtils.deleteAuditMarkersForResource(res); + + // exclude resource + excludedResources.add(rd); + Collection<Object> changedExclusoins = new HashSet<Object>(); + changedExclusoins.add(res); + fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins)); + + // Check if the excluded resource represents a resource-bundle + if (RBFileUtils.isResourceBundleFile(res)) { + String bundleName = getResourceBundleId(res); + Set<IResource> resSet = resources.remove(bundleName); + if (resSet != null) { + resSet.remove(res); + + if (!resSet.isEmpty()) { + resources.put(bundleName, resSet); + unloadResource(bundleName, res); + } else { + rd.setBundleId(bundleName); + unloadResourceBundle(bundleName); + try { + res.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + } + + fireResourceBundleChangedEvent(getResourceBundleId(res), + new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.EXCLUDED, + bundleName, res.getProject())); + } + } + } + + public void excludeResource(IResource res, IProgressMonitor monitor) { + try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + final List<IResource> resourceSubTree = new ArrayList<IResource>(); + res.accept(new IResourceVisitor() { + + @Override + public boolean visit(IResource resource) throws CoreException { + Logger.logInfo("Excluding resource '" + + resource.getFullPath().toOSString() + "'"); + resourceSubTree.add(resource); + return true; + } + + }); + + // Iterate previously retrieved resource and exclude them from + // Internationalization + monitor.beginTask( + "Exclude resources from Internationalization context", + resourceSubTree.size()); + try { + for (IResource resource : resourceSubTree) { + excludeSingleResource(resource); + EditorUtils.deleteAuditMarkersForResource(resource); + monitor.worked(1); + } + } catch (Exception e) { + Logger.logError(e); + } finally { + monitor.done(); + } + } catch (CoreException e) { + Logger.logError(e); + } + } + + public void includeResource(IResource res, IProgressMonitor monitor) { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + final Collection<Object> changedResources = new HashSet<Object>(); + IResource resource = res; + + if (!excludedResources.contains(new ResourceDescriptor(res))) { + while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) { + if (excludedResources + .contains(new ResourceDescriptor(resource))) { + excludeResource(resource, monitor); + changedResources.add(resource); + break; + } else { + resource = resource.getParent(); + } + } + } - if (entry == null) { - DirtyHack.setFireEnabled(false); + try { + res.accept(new IResourceVisitor() { + + @Override + public boolean visit(IResource resource) throws CoreException { + changedResources.add(resource); + return true; + } + }); + + monitor.beginTask("Add resources to Internationalization context", + changedResources.size()); + try { + for (Object r : changedResources) { + excludedResources.remove(new ResourceDescriptor( + (IResource) r)); + monitor.worked(1); + } + + } catch (Exception e) { + Logger.logError(e); + } finally { + monitor.done(); + } + } catch (Exception e) { + Logger.logError(e); + } + + (new I18nBuilder()).buildResource(res, null); - IMessagesBundle messagesBundle = bundleGroup - .getMessagesBundle(locale); - IMessage m = MessageFactory.createMessage(key, locale); - m.setText(message); - messagesBundle.addMessage(m); + // Check if the included resource represents a resource-bundle + if (RBFileUtils.isResourceBundleFile(res)) { + String bundleName = getResourceBundleId(res); + boolean newRB = resources.containsKey(bundleName); - instance.writeToFile(messagesBundle); + this.addBundleResource(res); + this.unloadResourceBundle(bundleName); + // this.loadResourceBundle(bundleName); - DirtyHack.setFireEnabled(true); + if (newRB) { + (new I18nBuilder()).buildProject(null, res.getProject()); + } + fireResourceBundleChangedEvent(getResourceBundleId(res), + new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.INCLUDED, bundleName, + res.getProject())); + } - // notify the PropertyKeySelectionTree - instance.fireEditorChanged(); + fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources)); } - } - public void saveResourceBundle(String resourceBundleId, - IMessagesBundleGroup newBundleGroup) throws ResourceBundleException { + protected void fireResourceExclusionEvent(ResourceExclusionEvent event) { + for (IResourceExclusionListener listener : exclusionListeners) { + listener.exclusionChanged(event); + } + } - // RBManager.getInstance(). - } + public static boolean isResourceExcluded(IResource res) { + IResource resource = res; - public void removeResourceBundleEntry(String resourceBundleId, - List<String> keys) throws ResourceBundleException { + if (!state_loaded) { + loadManagerState(); + } - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup messagesBundleGroup = instance - .getMessagesBundleGroup(resourceBundleId); + boolean isExcluded = false; + + do { + if (excludedResources.contains(new ResourceDescriptor(resource))) { + if (RBFileUtils.isResourceBundleFile(resource)) { + Set<IResource> resources = allBundles + .remove(getResourceBundleName(resource)); + if (resources == null) { + resources = new HashSet<IResource>(); + } + resources.add(resource); + allBundles.put(getResourceBundleName(resource), resources); + } + + isExcluded = true; + break; + } + resource = resource.getParent(); + } while (resource != null + && !(resource instanceof IProject || resource instanceof IWorkspaceRoot) + && checkResourceExclusionRoot); + + return isExcluded; // excludedResources.contains(new + // ResourceDescriptor(res)); + } - DirtyHack.setFireEnabled(false); + public IFile getRandomFile(String bundleName) { + try { + IResource res = (resources.get(bundleName)).iterator().next(); + return res.getProject().getFile(res.getProjectRelativePath()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - for (String key : keys) { - messagesBundleGroup.removeMessages(key); + private static void loadManagerState() { + excludedResources = new HashSet<IResourceDescriptor>(); + FileReader reader = null; + try { + reader = new FileReader(FileUtils.getRBManagerStateFile()); + loadManagerState(XMLMemento.createReadRoot(reader)); + state_loaded = true; + } catch (Exception e) { + // do nothing + } + + changelistener = new RBChangeListner(); + ResourcesPlugin.getWorkspace().addResourceChangeListener( + changelistener, + IResourceChangeEvent.PRE_DELETE + | IResourceChangeEvent.POST_CHANGE); } - instance.writeToFile(messagesBundleGroup); + private static void loadManagerState(XMLMemento memento) { + IMemento excludedChild = memento.getChild(TAG_EXCLUDED); + for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) { + IResourceDescriptor descriptor = new ResourceDescriptor(); + descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS)); + descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL)); + descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO)); + descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID)); + excludedResources.add(descriptor); + } + } - DirtyHack.setFireEnabled(true); + public static void saveManagerState() { + if (excludedResources == null) { + return; + } + XMLMemento memento = XMLMemento + .createWriteRoot(TAG_INTERNATIONALIZATION); + IMemento exclChild = memento.createChild(TAG_EXCLUDED); + + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor desc = itExcl.next(); + IMemento resDesc = exclChild.createChild(TAG_RES_DESC); + resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName()); + resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath()); + resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath()); + resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId()); + } + FileWriter writer = null; + try { + writer = new FileWriter(FileUtils.getRBManagerStateFile()); + memento.save(writer); + } catch (Exception e) { + // do nothing + } finally { + try { + if (writer != null) { + writer.close(); + } + } catch (Exception e) { + // do nothing + } + } + } - // notify the PropertyKeySelectionTree - instance.fireEditorChanged(); - } + @Deprecated + protected static boolean isResourceExcluded(IProject project, String bname) { + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor rd = itExcl.next(); + if (project.getName().equals(rd.getProjectName()) + && bname.equals(rd.getBundleId())) { + return true; + } + } + return false; + } - public boolean isResourceExisting(String bundleId, String key) { - boolean keyExists = false; - IMessagesBundleGroup bGroup = getResourceBundle(bundleId); + public static ResourceBundleManager getManager(String projectName) { + for (IProject p : getAllSupportedProjects()) { + if (p.getName().equalsIgnoreCase(projectName)) { + // check if the projectName is a fragment and return the manager + // for the host + if (FragmentProjectUtils.isFragment(p)) { + return getManager(FragmentProjectUtils.getFragmentHost(p)); + } else { + return getManager(p); + } + } + } + return null; + } + + public IFile getResourceBundleFile(String resourceBundle, Locale l) { + IFile res = null; + Set<IResource> resSet = resources.get(resourceBundle); + + if (resSet != null) { + for (IResource resource : resSet) { + Locale refLoc = getLocaleByName(resourceBundle, + resource.getName()); + if (refLoc == null + && l == null + || (refLoc != null && refLoc.equals(l) || l != null + && l.equals(refLoc))) { + res = resource.getProject().getFile( + resource.getProjectRelativePath()); + break; + } + } + } - if (bGroup != null) { - keyExists = bGroup.isKey(key); + return res; } - return keyExists; - } + public Set<IResource> getAllResourceBundleResources(String resourceBundle) { + return allBundles.get(resourceBundle); + } - public static void refreshResource(IResource resource) { - (new I18nBuilder()).buildProject(null, resource.getProject()); - (new I18nBuilder()).buildResource(resource, null); - } + public void registerResourceExclusionListener( + IResourceExclusionListener listener) { + exclusionListeners.add(listener); + } - public Set<Locale> getProjectProvidedLocales() { - Set<Locale> locales = new HashSet<Locale>(); + public void unregisterResourceExclusionListener( + IResourceExclusionListener listener) { + exclusionListeners.remove(listener); + } + + public boolean isResourceExclusionListenerRegistered( + IResourceExclusionListener listener) { + return exclusionListeners.contains(listener); + } + + public static void unregisterResourceExclusionListenerFromAllManagers( + IResourceExclusionListener excludedResource) { + for (ResourceBundleManager mgr : rbmanager.values()) { + mgr.unregisterResourceExclusionListener(excludedResource); + } + } + + public void addResourceBundleEntry(String resourceBundleId, String key, + Locale locale, String message) throws ResourceBundleException { + + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance + .getMessagesBundleGroup(resourceBundleId); + IMessage entry = bundleGroup.getMessage(key, locale); + + if (entry == null) { + DirtyHack.setFireEnabled(false); + + IMessagesBundle messagesBundle = bundleGroup + .getMessagesBundle(locale); + IMessage m = MessageFactory.createMessage(key, locale); + m.setText(message); + messagesBundle.addMessage(m); + + instance.writeToFile(messagesBundle); + + DirtyHack.setFireEnabled(true); + + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); + } + } + + public void saveResourceBundle(String resourceBundleId, + IMessagesBundleGroup newBundleGroup) throws ResourceBundleException { + + // RBManager.getInstance(). + } + + public void removeResourceBundleEntry(String resourceBundleId, + List<String> keys) throws ResourceBundleException { + + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup messagesBundleGroup = instance + .getMessagesBundleGroup(resourceBundleId); + + DirtyHack.setFireEnabled(false); + + for (String key : keys) { + messagesBundleGroup.removeMessages(key); + } + + instance.writeToFile(messagesBundleGroup); + + DirtyHack.setFireEnabled(true); + + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); + } + + public boolean isResourceExisting(String bundleId, String key) { + boolean keyExists = false; + IMessagesBundleGroup bGroup = getResourceBundle(bundleId); + + if (bGroup != null) { + keyExists = bGroup.isKey(key); + } + + return keyExists; + } + + public static void refreshResource(IResource resource) { + try { + resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + } - for (String bundleId : getResourceBundleNames()) { - Set<Locale> rb_l = getProvidedLocales(bundleId); - if (!rb_l.isEmpty()) { - Object[] bundlelocales = rb_l.toArray(); - for (Object l : bundlelocales) { - /* TODO check if useful to add the default */ - if (!locales.contains(l)) - locales.add((Locale) l); + public Set<Locale> getProjectProvidedLocales() { + Set<Locale> locales = new HashSet<Locale>(); + + for (String bundleId : getResourceBundleNames()) { + Set<Locale> rb_l = getProvidedLocales(bundleId); + if (!rb_l.isEmpty()) { + Object[] bundlelocales = rb_l.toArray(); + for (Object l : bundlelocales) { + /* TODO check if useful to add the default */ + if (!locales.contains(l)) { + locales.add((Locale) l); + } + } + } } - } + return locales; } - return locales; - } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java index 7f39b6b7..14bbbc7d 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java @@ -7,6 +7,7 @@ ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; +import org.eclipse.babel.tapiji.tools.core.Logger; import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder; import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager; import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils; @@ -16,6 +17,7 @@ import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.filebuffers.LocationKind; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IJavaProject; @@ -136,9 +138,13 @@ protected void runAction() { wd.setTitle(wizard.getWindowTitle()); if (wd.open() == WizardDialog.OK) { - (new I18nBuilder()).buildProject(null, - resource.getProject()); - (new I18nBuilder()).buildResource(resource, null); + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } ITextFileBufferManager bufferManager = FileBuffers .getTextFileBufferManager();
32151ae7ab34f9df07340ad150b2920f128186e2
Delta Spike
DELTASPIKE-312 introduce openejb.owb.version This allows to fix the OWB version used for the cdictrl-openejb build using -Dopenejb.owb.version=1.1.7
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml index 599eb7289..b4676ace5 100644 --- a/deltaspike/cdictrl/impl-openejb/pom.xml +++ b/deltaspike/cdictrl/impl-openejb/pom.xml @@ -34,6 +34,7 @@ <properties> <openejb.version>4.5.0</openejb.version> + <openejb.owb.version>${owb.version}</openejb.owb.version> </properties> <dependencies> @@ -63,25 +64,25 @@ <dependency> <groupId>org.apache.openwebbeans</groupId> <artifactId>openwebbeans-impl</artifactId> - <version>${owb.version}</version> + <version>${openejb.owb.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.openwebbeans</groupId> <artifactId>openwebbeans-ejb</artifactId> - <version>${owb.version}</version> + <version>${openejb.owb.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.openwebbeans</groupId> <artifactId>openwebbeans-ee</artifactId> - <version>${owb.version}</version> + <version>${openejb.owb.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.openwebbeans</groupId> <artifactId>openwebbeans-ee-common</artifactId> - <version>${owb.version}</version> + <version>${openejb.owb.version}</version> <scope>provided</scope> </dependency> </dependencies>
c8fdea3a62ecf92c159ca8811b7d4a1039edd546
orientdb
Fixed issue -2472 about null values in Lists--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java index 60cce8473b2..8157ec110d5 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java @@ -79,7 +79,9 @@ public boolean addAll(Collection<? extends OIdentifiable> c) { while (it.hasNext()) { Object o = it.next(); - if (o instanceof OIdentifiable) + if (o == null) + add(null); + else if (o instanceof OIdentifiable) add((OIdentifiable) o); else OMultiValue.add(this, o); @@ -407,9 +409,9 @@ public boolean lazyLoad(final boolean iInvalidateStream) { for (String item : items) { if (item.length() == 0) - continue; - - super.add(new ORecordId(item)); + super.add(new ORecordId()); + else + super.add(new ORecordId(item)); } modCount = currentModCount; diff --git a/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java b/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java index 021e97ea0cc..ab800be333d 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java +++ b/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java @@ -298,6 +298,9 @@ private static void processRecord(final ODocument record, final Object iUserObje final String iFieldPathFromRoot, final OFetchListener iListener, final OFetchContext iContext, final String iFormat) throws IOException { + if (record == null) + return; + Object fieldValue; iContext.onBeforeFetch(record); @@ -363,7 +366,6 @@ private static void processRecord(final ODocument record, final Object iUserObje } } catch (Exception e) { - e.printStackTrace(); OLogManager.instance().error(null, "Fetching error on record %s", e, record.getIdentity()); } } @@ -531,7 +533,9 @@ else if (fieldValue instanceof Iterable<?> || fieldValue instanceof ORidBag) { removeParsedFromMap(parsedRecords, d); d = d.getRecord(); - if (!(d instanceof ODocument)) { + if (d == null) + iListener.processStandardField(null, d, null, iContext, iUserObject, ""); + else if (!(d instanceof ODocument)) { iListener.processStandardField(null, d, fieldName, iContext, iUserObject, ""); } else { iContext.onBeforeDocument(iRootRecord, (ODocument) d, fieldName, iUserObject); diff --git a/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java b/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java index c5773e46570..3178cc3eeb5 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java +++ b/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java @@ -16,12 +16,6 @@ */ package com.orientechnologies.orient.core.fetch.json; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Date; -import java.util.Set; -import java.util.Stack; - import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.db.record.ridbag.ORidBag; @@ -35,6 +29,12 @@ import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerJSON.FormatSettings; import com.orientechnologies.orient.core.version.ODistributedVersion; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Date; +import java.util.Set; +import java.util.Stack; + /** * @author luca.molino * @@ -174,6 +174,11 @@ private void appendType(final StringBuilder iBuffer, final String iFieldName, fi } public void writeSignature(final OJSONWriter json, final ORecordInternal<?> record) throws IOException { + if( record == null ) { + json.write("null"); + return; + } + boolean firstAttribute = true; if (settings.includeType) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java index fd34670cf43..067310a12dc 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java @@ -85,8 +85,13 @@ else if (iValue instanceof OIdentifiable) { } else { if (iFormat != null && iFormat.contains("shallow")) buffer.append("{}"); - else - buffer.append(linked.getRecord().toJSON(iFormat)); + else { + final ORecord<?> rec = linked.getRecord(); + if (rec != null) + buffer.append(rec.toJSON(iFormat)); + else + buffer.append("null"); + } } } else if (iValue.getClass().isArray()) { @@ -374,8 +379,10 @@ public OJSONWriter writeAttribute(final int iIdentLevel, final boolean iNewLine, format(iIdentLevel, iNewLine); - out.append(writeValue(iName, iFormat)); - out.append(":"); + if (iName != null) { + out.append(writeValue(iName, iFormat)); + out.append(":"); + } if (iFormat.contains("graph") && (iValue == null || iValue instanceof OIdentifiable) && (iName.startsWith("in_") || iName.startsWith("out_"))) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java index e7d5cd862a7..8d21461f7f7 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java @@ -15,13 +15,6 @@ */ package com.orientechnologies.orient.core.serialization.serializer.record.string; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - import com.orientechnologies.common.collection.OLazyIterator; import com.orientechnologies.common.collection.OMultiCollectionIterator; import com.orientechnologies.common.collection.OMultiValue; @@ -61,6 +54,13 @@ import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerEmbedded; import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + @SuppressWarnings({ "unchecked", "serial" }) public abstract class ORecordSerializerCSVAbstract extends ORecordSerializerStringAbstract { public static final char FIELD_VALUE_SEPARATOR = ':'; @@ -689,7 +689,7 @@ else if (item.length() > 2 && item.charAt(0) == OStringSerializerHelper.EMBEDDED } } else { if (linkedType == null) { - final char begin = item.charAt(0); + final char begin = item.length() > 0 ? item.charAt(0) : OStringSerializerHelper.LINK; // AUTO-DETERMINE LINKED TYPE if (begin == OStringSerializerHelper.LINK)
b701a84d372be5cdc2fa1382e7755407700620cf
hadoop
Merge r1580077 from trunk. YARN-1849. Fixed NPE in- ResourceTrackerService-registerNodeManager for UAM. Contributed by Karthik- Kambatla--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1580078 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index ec57c127fb78f..198d002c7ec03 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -524,6 +524,9 @@ Release 2.4.0 - UNRELEASED YARN-1670. Fixed a bug in log-aggregation that can cause the writer to write more log-data than the log-length that it records. (Mit Desai via vinodk) + YARN-1849. Fixed NPE in ResourceTrackerService#registerNodeManager for UAM + (Karthik Kambatla via jianhe ) + Release 2.3.1 - UNRELEASED INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java index 8a2c53958cba7..1d4032048e468 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java @@ -31,6 +31,7 @@ import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.util.VersionUtil; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; @@ -187,12 +188,51 @@ protected void serviceStop() throws Exception { super.serviceStop(); } + /** + * Helper method to handle received ContainerStatus. If this corresponds to + * the completion of a master-container of a managed AM, + * we call the handler for RMAppAttemptContainerFinishedEvent. + */ + @SuppressWarnings("unchecked") + @VisibleForTesting + void handleContainerStatus(ContainerStatus containerStatus) { + ApplicationAttemptId appAttemptId = + containerStatus.getContainerId().getApplicationAttemptId(); + RMApp rmApp = + rmContext.getRMApps().get(appAttemptId.getApplicationId()); + if (rmApp == null) { + LOG.error("Received finished container : " + + containerStatus.getContainerId() + + "for unknown application " + appAttemptId.getApplicationId() + + " Skipping."); + return; + } + + if (rmApp.getApplicationSubmissionContext().getUnmanagedAM()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Ignoring container completion status for unmanaged AM" + + rmApp.getApplicationId()); + } + return; + } + + RMAppAttempt rmAppAttempt = rmApp.getRMAppAttempt(appAttemptId); + Container masterContainer = rmAppAttempt.getMasterContainer(); + if (masterContainer.getId().equals(containerStatus.getContainerId()) + && containerStatus.getState() == ContainerState.COMPLETE) { + // sending master container finished event. + RMAppAttemptContainerFinishedEvent evt = + new RMAppAttemptContainerFinishedEvent(appAttemptId, + containerStatus); + rmContext.getDispatcher().getEventHandler().handle(evt); + } + } + @SuppressWarnings("unchecked") @Override public RegisterNodeManagerResponse registerNodeManager( RegisterNodeManagerRequest request) throws YarnException, IOException { - NodeId nodeId = request.getNodeId(); String host = nodeId.getHost(); int cmPort = nodeId.getPort(); @@ -204,29 +244,7 @@ public RegisterNodeManagerResponse registerNodeManager( LOG.info("received container statuses on node manager register :" + request.getContainerStatuses()); for (ContainerStatus containerStatus : request.getContainerStatuses()) { - ApplicationAttemptId appAttemptId = - containerStatus.getContainerId().getApplicationAttemptId(); - RMApp rmApp = - rmContext.getRMApps().get(appAttemptId.getApplicationId()); - if (rmApp != null) { - RMAppAttempt rmAppAttempt = rmApp.getRMAppAttempt(appAttemptId); - if (rmAppAttempt != null) { - if (rmAppAttempt.getMasterContainer().getId() - .equals(containerStatus.getContainerId()) - && containerStatus.getState() == ContainerState.COMPLETE) { - // sending master container finished event. - RMAppAttemptContainerFinishedEvent evt = - new RMAppAttemptContainerFinishedEvent(appAttemptId, - containerStatus); - rmContext.getDispatcher().getEventHandler().handle(evt); - } - } - } else { - LOG.error("Received finished container :" - + containerStatus.getContainerId() - + " for non existing application :" - + appAttemptId.getApplicationId()); - } + handleContainerStatus(containerStatus); } } RegisterNodeManagerResponse response = recordFactory diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java index 697a18099b339..3e90ec8ec1d5a 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java @@ -35,9 +35,11 @@ import javax.crypto.SecretKey; +import com.google.common.annotations.VisibleForTesting; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; @@ -629,7 +631,9 @@ public Container getMasterContainer() { } } - private void setMasterContainer(Container container) { + @InterfaceAudience.Private + @VisibleForTesting + public void setMasterContainer(Container container) { masterContainer = container; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java index 303e0fb56e549..2f16b85699d37 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java @@ -26,8 +26,6 @@ import java.util.HashMap; import java.util.List; -import org.junit.Assert; - import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.metrics2.MetricsSystem; @@ -45,21 +43,29 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.DrainDispatcher; +import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse; import org.apache.hadoop.yarn.server.api.records.NodeAction; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; +import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.YarnVersionInfo; + import org.junit.After; +import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; public class TestResourceTrackerService { @@ -468,26 +474,64 @@ private void checkUnealthyNMCount(MockRM rm, MockNM nm1, boolean health, ClusterMetrics.getMetrics().getUnhealthyNMs()); } + @SuppressWarnings("unchecked") @Test - public void testNodeRegistrationWithContainers() throws Exception { - rm = new MockRM(); - rm.init(new YarnConfiguration()); + public void testHandleContainerStatusInvalidCompletions() throws Exception { + rm = new MockRM(new YarnConfiguration()); rm.start(); - RMApp app = rm.submitApp(1024); - MockNM nm = rm.registerNode("host1:1234", 8192); - nm.nodeHeartbeat(true); + EventHandler handler = + spy(rm.getRMContext().getDispatcher().getEventHandler()); - // Register node with some container statuses + // Case 1: Unmanaged AM + RMApp app = rm.submitApp(1024, true); + + // Case 1.1: AppAttemptId is null ContainerStatus status = ContainerStatus.newInstance( ContainerId.newInstance(ApplicationAttemptId.newInstance( app.getApplicationId(), 2), 1), ContainerState.COMPLETE, "Dummy Completed", 0); + rm.getResourceTrackerService().handleContainerStatus(status); + verify(handler, never()).handle((Event) any()); + + // Case 1.2: Master container is null + RMAppAttemptImpl currentAttempt = + (RMAppAttemptImpl) app.getCurrentAppAttempt(); + currentAttempt.setMasterContainer(null); + status = ContainerStatus.newInstance( + ContainerId.newInstance(currentAttempt.getAppAttemptId(), 0), + ContainerState.COMPLETE, "Dummy Completed", 0); + rm.getResourceTrackerService().handleContainerStatus(status); + verify(handler, never()).handle((Event)any()); - // The following shouldn't throw NPE - nm.registerNode(Collections.singletonList(status)); - assertEquals("Incorrect number of nodes", 1, - rm.getRMContext().getRMNodes().size()); + // Case 2: Managed AM + app = rm.submitApp(1024); + + // Case 2.1: AppAttemptId is null + status = ContainerStatus.newInstance( + ContainerId.newInstance(ApplicationAttemptId.newInstance( + app.getApplicationId(), 2), 1), + ContainerState.COMPLETE, "Dummy Completed", 0); + try { + rm.getResourceTrackerService().handleContainerStatus(status); + } catch (Exception e) { + // expected - ignore + } + verify(handler, never()).handle((Event)any()); + + // Case 2.2: Master container is null + currentAttempt = + (RMAppAttemptImpl) app.getCurrentAppAttempt(); + currentAttempt.setMasterContainer(null); + status = ContainerStatus.newInstance( + ContainerId.newInstance(currentAttempt.getAppAttemptId(), 0), + ContainerState.COMPLETE, "Dummy Completed", 0); + try { + rm.getResourceTrackerService().handleContainerStatus(status); + } catch (Exception e) { + // expected - ignore + } + verify(handler, never()).handle((Event)any()); } @Test
d6f8a7f7ee7c689abdaa85b0c4d546e562f4e838
hadoop
YARN-539. Addressed memory leak of LocalResource- objects NM when a resource localization fails. Contributed by Omkar Vinit- Joshi. svn merge --ignore-ancestry -c 1466756 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1466757 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index a60b06ea032c9..c72ab75ab0265 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -159,6 +159,9 @@ Release 2.0.5-beta - UNRELEASED YARN-534. Change RM restart recovery to also account for AM max-attempts configuration after the restart. (Jian He via vinodkv) + YARN-539. Addressed memory leak of LocalResource objects NM when a resource + localization fails. (Omkar Vinit Joshi via vinodkv) + Release 2.0.4-alpha - UNRELEASED INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml b/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml index 247406434e703..4ba2d72289e71 100644 --- a/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml +++ b/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml @@ -270,4 +270,11 @@ <Bug pattern="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE" /> </Match> + <!-- This type cast problem will never occur. --> + <Match> + <Class name="org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.LocalResourcesTrackerImpl" /> + <Method name="handle" /> + <Bug pattern="BC_UNCONFIRMED_CAST" /> + </Match> + </FindBugsFilter> diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTracker.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTracker.java index 2e795e54a10e7..98ec471abf0db 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTracker.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTracker.java @@ -40,8 +40,5 @@ interface LocalResourcesTracker String getUser(); - // TODO: Remove this in favour of EventHandler.handle - void localizationCompleted(LocalResourceRequest req, boolean success); - long nextUniqueNumber(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTrackerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTrackerImpl.java index 53ca9013da8d5..786b58ca5d01f 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTrackerImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalResourcesTrackerImpl.java @@ -33,6 +33,7 @@ import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceEvent; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceReleaseEvent; /** @@ -96,13 +97,22 @@ public LocalResourcesTrackerImpl(String user, Dispatcher dispatcher, this.conf = conf; } + /* + * Synchronizing this method for avoiding races due to multiple ResourceEvent's + * coming to LocalResourcesTracker from Public/Private localizer and + * Resource Localization Service. + */ @Override - public void handle(ResourceEvent event) { + public synchronized void handle(ResourceEvent event) { LocalResourceRequest req = event.getLocalResourceRequest(); LocalizedResource rsrc = localrsrc.get(req); switch (event.getType()) { - case REQUEST: case LOCALIZED: + if (useLocalCacheDirectoryManager) { + inProgressLocalResourcesMap.remove(req); + } + break; + case REQUEST: if (rsrc != null && (!isResourcePresent(rsrc))) { LOG.info("Resource " + rsrc.getLocalPath() + " is missing, localizing it again"); @@ -117,10 +127,24 @@ public void handle(ResourceEvent event) { break; case RELEASE: if (null == rsrc) { - LOG.info("Release unknown rsrc null (discard)"); + // The container sent a release event on a resource which + // 1) Failed + // 2) Removed for some reason (ex. disk is no longer accessible) + ResourceReleaseEvent relEvent = (ResourceReleaseEvent) event; + LOG.info("Container " + relEvent.getContainer() + + " sent RELEASE event on a resource request " + req + + " not present in cache."); return; } break; + case LOCALIZATION_FAILED: + decrementFileCountForLocalCacheDirectory(req, null); + /* + * If resource localization fails then Localized resource will be + * removed from local cache. + */ + localrsrc.remove(req); + break; } rsrc.handle(event); } @@ -279,18 +303,6 @@ public Iterator<LocalizedResource> iterator() { } } - @Override - public void localizationCompleted(LocalResourceRequest req, - boolean success) { - if (useLocalCacheDirectoryManager) { - if (!success) { - decrementFileCountForLocalCacheDirectory(req, null); - } else { - inProgressLocalResourcesMap.remove(req); - } - } - } - @Override public long nextUniqueNumber() { return uniqueNumberGenerator.incrementAndGet(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalizedResource.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalizedResource.java index 00709fd91c290..f0cd87b573a41 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalizedResource.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalizedResource.java @@ -32,10 +32,12 @@ import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerResourceFailedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerResourceLocalizedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerResourceRequestEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceEventType; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceFailedLocalizationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceLocalizedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceReleaseEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceRequestEvent; @@ -89,6 +91,8 @@ ResourceEventType.LOCALIZED, new FetchSuccessTransition()) .addTransition(ResourceState.DOWNLOADING, EnumSet.of(ResourceState.DOWNLOADING, ResourceState.INIT), ResourceEventType.RELEASE, new ReleasePendingTransition()) + .addTransition(ResourceState.DOWNLOADING, ResourceState.FAILED, + ResourceEventType.LOCALIZATION_FAILED, new FetchFailedTransition()) // From LOCALIZED (ref >= 0, on disk) .addTransition(ResourceState.LOCALIZED, ResourceState.LOCALIZED, @@ -126,12 +130,14 @@ public String toString() { } private void release(ContainerId container) { - if (!ref.remove(container)) { - LOG.info("Attempt to release claim on " + this + - " from unregistered container " + container); - assert false; // TODO: FIX + if (ref.remove(container)) { + // updating the timestamp only in case of success. + timestamp.set(currentTime()); + } else { + LOG.info("Container " + container + + " doesn't exist in the container list of the Resource " + this + + " to which it sent RELEASE event"); } - timestamp.set(currentTime()); } private long currentTime() { @@ -250,6 +256,25 @@ public void transition(LocalizedResource rsrc, ResourceEvent event) { } } + /** + * Resource localization failed, notify waiting containers. + */ + @SuppressWarnings("unchecked") + private static class FetchFailedTransition extends ResourceTransition { + @Override + public void transition(LocalizedResource rsrc, ResourceEvent event) { + ResourceFailedLocalizationEvent failedEvent = + (ResourceFailedLocalizationEvent) event; + Queue<ContainerId> containers = rsrc.ref; + Throwable failureCause = failedEvent.getCause(); + for (ContainerId container : containers) { + rsrc.dispatcher.getEventHandler().handle( + new ContainerResourceFailedEvent(container, failedEvent + .getLocalResourceRequest(), failureCause)); + } + } + } + /** * Resource already localized, notify immediately. */ diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java index 5058cb2cad9ea..7b9873a1f4578 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java @@ -84,7 +84,6 @@ import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerAction; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse; import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus; -import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.ResourceStatusType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType; @@ -101,6 +100,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerResourceRequestEvent; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceFailedLocalizationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceLocalizedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceReleaseEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceRequestEvent; @@ -683,7 +683,6 @@ public void addResource(LocalizerResourceRequestEvent request) { } @Override - @SuppressWarnings("unchecked") // dispatcher not typed public void run() { try { // TODO shutdown, better error handling esp. DU @@ -699,10 +698,8 @@ public void run() { return; } LocalResourceRequest key = assoc.getResource().getRequest(); - assoc.getResource().handle( - new ResourceLocalizedEvent(key, - local, FileUtil.getDU(new File(local.toUri())))); - publicRsrc.localizationCompleted(key, true); + publicRsrc.handle(new ResourceLocalizedEvent(key, local, FileUtil + .getDU(new File(local.toUri())))); synchronized (attempts) { attempts.remove(key); } @@ -710,13 +707,10 @@ public void run() { LOG.info("Failed to download rsrc " + assoc.getResource(), e.getCause()); LocalResourceRequest req = assoc.getResource().getRequest(); - dispatcher.getEventHandler().handle( - new ContainerResourceFailedEvent( - assoc.getContext().getContainerId(), - req, e.getCause())); - publicRsrc.localizationCompleted(req, false); - List<LocalizerResourceRequestEvent> reqs; + publicRsrc.handle(new ResourceFailedLocalizationEvent(req, e + .getCause())); synchronized (attempts) { + List<LocalizerResourceRequestEvent> reqs; reqs = attempts.get(req); if (null == reqs) { LOG.error("Missing pending list for " + req); @@ -724,13 +718,6 @@ public void run() { } attempts.remove(req); } - // let the other containers know about the localization failure - for (LocalizerResourceRequestEvent reqEvent : reqs) { - dispatcher.getEventHandler().handle( - new ContainerResourceFailedEvent( - reqEvent.getContext().getContainerId(), - reqEvent.getResource().getRequest(), e.getCause())); - } } catch (CancellationException e) { // ignore; shutting down } @@ -810,13 +797,14 @@ private LocalResource findNextResource() { return null; } - // TODO this sucks. Fix it later - @SuppressWarnings("unchecked") // dispatcher not typed LocalizerHeartbeatResponse update( List<LocalResourceStatus> remoteResourceStatuses) { LocalizerHeartbeatResponse response = recordFactory.newRecordInstance(LocalizerHeartbeatResponse.class); + String user = context.getUser(); + ApplicationId applicationId = + context.getContainerId().getApplicationAttemptId().getApplicationId(); // The localizer has just spawned. Start giving it resources for // remote-fetching. if (remoteResourceStatuses.isEmpty()) { @@ -847,6 +835,11 @@ LocalizerHeartbeatResponse update( } ArrayList<ResourceLocalizationSpec> rsrcs = new ArrayList<ResourceLocalizationSpec>(); + /* + * TODO : It doesn't support multiple downloads per ContainerLocalizer + * at the same time. We need to think whether we should support this. + */ + for (LocalResourceStatus stat : remoteResourceStatuses) { LocalResource rsrc = stat.getResource(); LocalResourceRequest req = null; @@ -865,11 +858,10 @@ LocalizerHeartbeatResponse update( case FETCH_SUCCESS: // notify resource try { - assoc.getResource().handle( - new ResourceLocalizedEvent(req, - ConverterUtils.getPathFromYarnURL(stat.getLocalPath()), - stat.getLocalSize())); - localizationCompleted(stat); + getLocalResourcesTracker(req.getVisibility(), user, applicationId) + .handle( + new ResourceLocalizedEvent(req, ConverterUtils + .getPathFromYarnURL(stat.getLocalPath()), stat.getLocalSize())); } catch (URISyntaxException e) { } if (pending.isEmpty()) { // TODO: Synchronization @@ -899,19 +891,16 @@ LocalizerHeartbeatResponse update( LOG.info("DEBUG: FAILED " + req, stat.getException()); assoc.getResource().unlock(); response.setLocalizerAction(LocalizerAction.DIE); - localizationCompleted(stat); - // TODO: Why is this event going directly to the container. Why not - // the resource itself? What happens to the resource? Is it removed? - dispatcher.getEventHandler().handle( - new ContainerResourceFailedEvent(context.getContainerId(), - req, stat.getException())); + getLocalResourcesTracker(req.getVisibility(), user, applicationId) + .handle( + new ResourceFailedLocalizationEvent(req, stat.getException())); break; default: LOG.info("Unknown status: " + stat.getStatus()); response.setLocalizerAction(LocalizerAction.DIE); - dispatcher.getEventHandler().handle( - new ContainerResourceFailedEvent(context.getContainerId(), - req, stat.getException())); + getLocalResourcesTracker(req.getVisibility(), user, applicationId) + .handle( + new ResourceFailedLocalizationEvent(req, stat.getException())); break; } } @@ -919,27 +908,6 @@ LocalizerHeartbeatResponse update( return response; } - private void localizationCompleted(LocalResourceStatus stat) { - try { - LocalResource rsrc = stat.getResource(); - LocalResourceRequest key = new LocalResourceRequest(rsrc); - String user = context.getUser(); - ApplicationId appId = - context.getContainerId().getApplicationAttemptId() - .getApplicationId(); - LocalResourceVisibility vis = rsrc.getVisibility(); - LocalResourcesTracker tracker = - getLocalResourcesTracker(vis, user, appId); - if (stat.getStatus() == ResourceStatusType.FETCH_SUCCESS) { - tracker.localizationCompleted(key, true); - } else { - tracker.localizationCompleted(key, false); - } - } catch (URISyntaxException e) { - LOG.error("Invalid resource URL specified", e); - } - } - private Path getPathForLocalization(LocalResource rsrc) throws IOException, URISyntaxException { String user = context.getUser(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceState.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceState.java index 751f60e0af172..75c8ad7663cf3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceState.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceState.java @@ -20,5 +20,6 @@ enum ResourceState { INIT, DOWNLOADING, - LOCALIZED + LOCALIZED, + FAILED } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceEventType.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceEventType.java index d68a1b6d39134..e657c0acf3c62 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceEventType.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceEventType.java @@ -29,5 +29,7 @@ public enum ResourceEventType { /** See {@link ResourceLocalizedEvent} */ LOCALIZED, /** See {@link ResourceReleaseEvent} */ - RELEASE + RELEASE, + /** See {@link ResourceFailedLocalizationEvent} */ + LOCALIZATION_FAILED } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceFailedLocalizationEvent.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceFailedLocalizationEvent.java new file mode 100644 index 0000000000000..79b28bac9088b --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceFailedLocalizationEvent.java @@ -0,0 +1,39 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event; + +import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.LocalResourceRequest; + +/** + * This event is sent by the localizer in case resource localization fails for + * the requested resource. + */ +public class ResourceFailedLocalizationEvent extends ResourceEvent { + + private Throwable cause; + + public ResourceFailedLocalizationEvent(LocalResourceRequest rsrc, + Throwable cause) { + super(rsrc, ResourceEventType.LOCALIZATION_FAILED); + this.cause = cause; + } + + public Throwable getCause() { + return cause; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalResourcesTrackerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalResourcesTrackerImpl.java index a8bbdb035211f..b2caba02e81ca 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalResourcesTrackerImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalResourcesTrackerImpl.java @@ -19,6 +19,7 @@ package org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer; import static org.mockito.Mockito.any; +import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -41,11 +42,15 @@ import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEventType; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerResourceFailedEvent; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerResourceLocalizedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerResourceRequestEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceEvent; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceFailedLocalizationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceLocalizedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceReleaseEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceRequestEvent; @@ -224,6 +229,142 @@ public void testConsistency() { } } + @Test(timeout = 1000) + @SuppressWarnings("unchecked") + public void testLocalResourceCache() { + String user = "testuser"; + DrainDispatcher dispatcher = null; + try { + Configuration conf = new Configuration(); + dispatcher = createDispatcher(conf); + + EventHandler<LocalizerEvent> localizerEventHandler = + mock(EventHandler.class); + EventHandler<ContainerEvent> containerEventHandler = + mock(EventHandler.class); + + // Registering event handlers. + dispatcher.register(LocalizerEventType.class, localizerEventHandler); + dispatcher.register(ContainerEventType.class, containerEventHandler); + + ConcurrentMap<LocalResourceRequest, LocalizedResource> localrsrc = + new ConcurrentHashMap<LocalResourceRequest, LocalizedResource>(); + LocalResourcesTracker tracker = + new LocalResourcesTrackerImpl(user, dispatcher, localrsrc, true, conf); + + LocalResourceRequest lr = + createLocalResourceRequest(user, 1, 1, LocalResourceVisibility.PUBLIC); + + // Creating 2 containers for same application which will be requesting + // same local resource. + // Container 1 requesting local resource. + ContainerId cId1 = BuilderUtils.newContainerId(1, 1, 1, 1); + LocalizerContext lc1 = new LocalizerContext(user, cId1, null); + ResourceEvent reqEvent1 = + new ResourceRequestEvent(lr, LocalResourceVisibility.PRIVATE, lc1); + + // No resource request is initially present in local cache + Assert.assertEquals(0, localrsrc.size()); + + // Container-1 requesting local resource. + tracker.handle(reqEvent1); + + // New localized Resource should have been added to local resource map + // and the requesting container will be added to its waiting queue. + Assert.assertEquals(1, localrsrc.size()); + Assert.assertTrue(localrsrc.containsKey(lr)); + Assert.assertEquals(1, localrsrc.get(lr).getRefCount()); + Assert.assertTrue(localrsrc.get(lr).ref.contains(cId1)); + Assert.assertEquals(ResourceState.DOWNLOADING, localrsrc.get(lr) + .getState()); + + // Container 2 requesting the resource + ContainerId cId2 = BuilderUtils.newContainerId(1, 1, 1, 2); + LocalizerContext lc2 = new LocalizerContext(user, cId2, null); + ResourceEvent reqEvent2 = + new ResourceRequestEvent(lr, LocalResourceVisibility.PRIVATE, lc2); + tracker.handle(reqEvent2); + + // Container 2 should have been added to the waiting queue of the local + // resource + Assert.assertEquals(2, localrsrc.get(lr).getRefCount()); + Assert.assertTrue(localrsrc.get(lr).ref.contains(cId2)); + + // Failing resource localization + ResourceEvent resourceFailedEvent = + new ResourceFailedLocalizationEvent(lr, new Exception("test")); + + // Backing up the resource to track its state change as it will be + // removed after the failed event. + LocalizedResource localizedResource = localrsrc.get(lr); + + tracker.handle(resourceFailedEvent); + + // After receiving failed resource event; all waiting containers will be + // notified with Container Resource Failed Event. + Assert.assertEquals(0, localrsrc.size()); + verify(containerEventHandler, times(2)).handle( + isA(ContainerResourceFailedEvent.class)); + Assert.assertEquals(ResourceState.FAILED, localizedResource.getState()); + + // Container 1 trying to release the resource (This resource is already + // deleted from the cache. This call should return silently without + // exception. + ResourceReleaseEvent relEvent1 = new ResourceReleaseEvent(lr, cId1); + tracker.handle(relEvent1); + + // Container-3 now requests for the same resource. This request call + // is coming prior to Container-2's release call. + ContainerId cId3 = BuilderUtils.newContainerId(1, 1, 1, 3); + LocalizerContext lc3 = new LocalizerContext(user, cId3, null); + ResourceEvent reqEvent3 = + new ResourceRequestEvent(lr, LocalResourceVisibility.PRIVATE, lc3); + tracker.handle(reqEvent3); + + // Local resource cache now should have the requested resource and the + // number of waiting containers should be 1. + Assert.assertEquals(1, localrsrc.size()); + Assert.assertTrue(localrsrc.containsKey(lr)); + Assert.assertEquals(1, localrsrc.get(lr).getRefCount()); + Assert.assertTrue(localrsrc.get(lr).ref.contains(cId3)); + + // Container-2 Releases the resource + ResourceReleaseEvent relEvent2 = new ResourceReleaseEvent(lr, cId2); + tracker.handle(relEvent2); + + // Making sure that there is no change in the cache after the release. + Assert.assertEquals(1, localrsrc.size()); + Assert.assertTrue(localrsrc.containsKey(lr)); + Assert.assertEquals(1, localrsrc.get(lr).getRefCount()); + Assert.assertTrue(localrsrc.get(lr).ref.contains(cId3)); + + // Sending ResourceLocalizedEvent to tracker. In turn resource should + // send Container Resource Localized Event to waiting containers. + Path localizedPath = new Path("/tmp/file1"); + ResourceLocalizedEvent localizedEvent = + new ResourceLocalizedEvent(lr, localizedPath, 123L); + tracker.handle(localizedEvent); + + // Verifying ContainerResourceLocalizedEvent . + verify(containerEventHandler, times(1)).handle( + isA(ContainerResourceLocalizedEvent.class)); + Assert.assertEquals(ResourceState.LOCALIZED, localrsrc.get(lr) + .getState()); + Assert.assertEquals(1, localrsrc.get(lr).getRefCount()); + + // Container-3 releasing the resource. + ResourceReleaseEvent relEvent3 = new ResourceReleaseEvent(lr, cId3); + tracker.handle(relEvent3); + + Assert.assertEquals(0, localrsrc.get(lr).getRefCount()); + + } finally { + if (dispatcher != null) { + dispatcher.stop(); + } + } + } + @Test(timeout = 100000) @SuppressWarnings("unchecked") public void testHierarchicalLocalCacheDirectories() { @@ -266,19 +407,25 @@ public void testHierarchicalLocalCacheDirectories() { // Simulate the process of localization of lr1 Path hierarchicalPath1 = tracker.getPathForLocalization(lr1, localDir); // Simulate lr1 getting localized - ResourceLocalizedEvent rle = + ResourceLocalizedEvent rle1 = new ResourceLocalizedEvent(lr1, new Path(hierarchicalPath1.toUri().toString() + Path.SEPARATOR + "file1"), 120); - tracker.handle(rle); + tracker.handle(rle1); // Localization successful. - tracker.localizationCompleted(lr1, true); LocalResourceRequest lr2 = createLocalResourceRequest(user, 3, 3, LocalResourceVisibility.PUBLIC); + // Container 1 requests lr2 to be localized. + ResourceEvent reqEvent2 = + new ResourceRequestEvent(lr2, LocalResourceVisibility.PUBLIC, lc1); + tracker.handle(reqEvent2); + Path hierarchicalPath2 = tracker.getPathForLocalization(lr2, localDir); // localization failed. - tracker.localizationCompleted(lr2, false); + ResourceFailedLocalizationEvent rfe2 = + new ResourceFailedLocalizationEvent(lr2, new Exception("Test")); + tracker.handle(rfe2); /* * The path returned for two localization should be different because we @@ -292,7 +439,11 @@ public void testHierarchicalLocalCacheDirectories() { LocalResourceVisibility.PUBLIC, lc1); tracker.handle(reqEvent3); Path hierarchicalPath3 = tracker.getPathForLocalization(lr3, localDir); - tracker.localizationCompleted(lr3, true); + // localization successful + ResourceLocalizedEvent rle3 = + new ResourceLocalizedEvent(lr3, new Path(hierarchicalPath3.toUri() + .toString() + Path.SEPARATOR + "file3"), 120); + tracker.handle(rle3); // Verifying that path created is inside the subdirectory Assert.assertEquals(hierarchicalPath3.toUri().toString(),
a4873a43416cb322957863fd3c34795a3808f7ac
hadoop
HDFS-3167. CLI-based driver for MiniDFSCluster.- Contributed by Henry Robinson.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1308160 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt index 62e45162a1ec0..c85adc18b1e01 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt +++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt @@ -68,6 +68,8 @@ Release 2.0.0 - UNRELEASED DistributedFileSystem to @InterfaceAudience.LimitedPrivate. (harsh via szetszwo) + HDFS-3167. CLI-based driver for MiniDFSCluster. (Henry Robinson via atm) + IMPROVEMENTS HDFS-2018. Move all journal stream management code into one place. diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java index 709a5012bfb2b..cdcf618c80dd5 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java @@ -36,7 +36,9 @@ public HdfsTestDriver(ProgramDriver pgd) { this.pgd = pgd; try { pgd.addClass("dfsthroughput", BenchmarkThroughput.class, - "measure hdfs throughput"); + "measure hdfs throughput"); + pgd.addClass("minidfscluster", MiniDFSClusterManager.class, + "Run a single-process mini DFS cluster"); } catch(Throwable e) { e.printStackTrace(); } diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/MiniDFSClusterManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/MiniDFSClusterManager.java new file mode 100644 index 0000000000000..4622b4cd5c53c --- /dev/null +++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/MiniDFSClusterManager.java @@ -0,0 +1,259 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.test; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.OptionBuilder; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.hdfs.HdfsConfiguration; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hdfs.MiniDFSCluster; +import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption; +import org.mortbay.util.ajax.JSON; + +/** + * This class drives the creation of a mini-cluster on the local machine. By + * default, a MiniDFSCluster is spawned on the first available ports that are + * found. + * + * A series of command line flags controls the startup cluster options. + * + * This class can dump a Hadoop configuration and some basic metadata (in JSON) + * into a textfile. + * + * To shutdown the cluster, kill the process. + * + * To run this from the command line, do the following (replacing the jar + * version as appropriate): + * + * $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/share/hadoop/hdfs/hadoop-hdfs-0.24.0-SNAPSHOT-tests.jar org.apache.hadoop.test.MiniDFSClusterManager -options... + */ +public class MiniDFSClusterManager { + private static final Log LOG = + LogFactory.getLog(MiniDFSClusterManager.class); + + private MiniDFSCluster dfs; + private String writeDetails; + private int numDataNodes; + private int nameNodePort; + private StartupOption dfsOpts; + private String writeConfig; + private Configuration conf; + + private static final long SLEEP_INTERVAL_MS = 1000 * 60; + + /** + * Creates configuration options object. + */ + @SuppressWarnings("static-access") + private Options makeOptions() { + Options options = new Options(); + options + .addOption("datanodes", true, "How many datanodes to start (default 1)") + .addOption("format", false, "Format the DFS (default false)") + .addOption("cmdport", true, + "Which port to listen on for commands (default 0--we choose)") + .addOption("nnport", true, "NameNode port (default 0--we choose)") + .addOption("namenode", true, "URL of the namenode (default " + + "is either the DFS cluster or a temporary dir)") + .addOption(OptionBuilder + .hasArgs() + .withArgName("property=value") + .withDescription("Options to pass into configuration object") + .create("D")) + .addOption(OptionBuilder + .hasArg() + .withArgName("path") + .withDescription("Save configuration to this XML file.") + .create("writeConfig")) + .addOption(OptionBuilder + .hasArg() + .withArgName("path") + .withDescription("Write basic information to this JSON file.") + .create("writeDetails")) + .addOption(OptionBuilder.withDescription("Prints option help.") + .create("help")); + return options; + } + + /** + * Main entry-point. + */ + public void run(String[] args) throws IOException { + if (!parseArguments(args)) { + return; + } + start(); + sleepForever(); + } + + private void sleepForever() { + while (true) { + try { + Thread.sleep(SLEEP_INTERVAL_MS); + if (!dfs.isClusterUp()) { + LOG.info("Cluster is no longer up, exiting"); + return; + } + } catch (InterruptedException _) { + // nothing + } + } + } + + /** + * Starts DFS as specified in member-variable options. Also writes out + * configuration and details, if requested. + */ + public void start() throws IOException, FileNotFoundException { + dfs = new MiniDFSCluster.Builder(conf).nameNodePort(nameNodePort) + .numDataNodes(numDataNodes) + .startupOption(dfsOpts) + .build(); + dfs.waitActive(); + + LOG.info("Started MiniDFSCluster -- namenode on port " + + dfs.getNameNodePort()); + + if (writeConfig != null) { + FileOutputStream fos = new FileOutputStream(new File(writeConfig)); + conf.writeXml(fos); + fos.close(); + } + + if (writeDetails != null) { + Map<String, Object> map = new TreeMap<String, Object>(); + if (dfs != null) { + map.put("namenode_port", dfs.getNameNodePort()); + } + + FileWriter fw = new FileWriter(new File(writeDetails)); + fw.write(new JSON().toJSON(map)); + fw.close(); + } + } + + /** + * Parses arguments and fills out the member variables. + * @param args Command-line arguments. + * @return true on successful parse; false to indicate that the + * program should exit. + */ + private boolean parseArguments(String[] args) { + Options options = makeOptions(); + CommandLine cli; + try { + CommandLineParser parser = new GnuParser(); + cli = parser.parse(options, args); + } catch(ParseException e) { + LOG.warn("options parsing failed: "+e.getMessage()); + new HelpFormatter().printHelp("...", options); + return false; + } + + if (cli.hasOption("help")) { + new HelpFormatter().printHelp("...", options); + return false; + } + + if (cli.getArgs().length > 0) { + for (String arg : cli.getArgs()) { + LOG.error("Unrecognized option: " + arg); + new HelpFormatter().printHelp("...", options); + return false; + } + } + + // HDFS + numDataNodes = intArgument(cli, "datanodes", 1); + nameNodePort = intArgument(cli, "nnport", 0); + dfsOpts = cli.hasOption("format") ? + StartupOption.FORMAT : StartupOption.REGULAR; + + // Runner + writeDetails = cli.getOptionValue("writeDetails"); + writeConfig = cli.getOptionValue("writeConfig"); + + // General + conf = new HdfsConfiguration(); + updateConfiguration(conf, cli.getOptionValues("D")); + + return true; + } + + /** + * Updates configuration based on what's given on the command line. + * + * @param conf2 The configuration object + * @param keyvalues An array of interleaved key value pairs. + */ + private void updateConfiguration(Configuration conf2, String[] keyvalues) { + int num_confs_updated = 0; + if (keyvalues != null) { + for (String prop : keyvalues) { + String[] keyval = prop.split("=", 2); + if (keyval.length == 2) { + conf2.set(keyval[0], keyval[1]); + num_confs_updated++; + } else { + LOG.warn("Ignoring -D option " + prop); + } + } + } + LOG.info("Updated " + num_confs_updated + + " configuration settings from command line."); + } + + /** + * Extracts an integer argument with specified default value. + */ + private int intArgument(CommandLine cli, String argName, int defaultValue) { + String o = cli.getOptionValue(argName); + try { + if (o != null) { + return Integer.parseInt(o); + } + } catch (NumberFormatException ex) { + LOG.error("Couldn't parse value (" + o + ") for option " + + argName + ". Using default: " + defaultValue); + } + + return defaultValue; + } + + /** + * Starts a MiniDFSClusterManager with parameters drawn from the command line. + */ + public static void main(String[] args) throws IOException { + new MiniDFSClusterManager().run(args); + } +}
5787e2af06a377732f81cccb57b29a324875bb71
orientdb
Support for not-logget Transactions by setting- OTransaction.setUsingLog(false). Default is true
a
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java index 82285da83b5..3be98a9318d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java @@ -118,7 +118,7 @@ public byte[] toStream() { public ORecordAbstract<T> fromStream(final byte[] iRecordBuffer) { _dirty = false; _source = iRecordBuffer; - _size = iRecordBuffer.length; + _size = iRecordBuffer != null ? iRecordBuffer.length : 0; _status = STATUS.LOADED; invokeListenerEvent(ORecordListener.EVENT.UNMARSHALL); diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java index 10146e58d4b..7997b3acecf 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java @@ -174,7 +174,7 @@ protected void commitAllPendingRecords(final int iRequesterId, final OTransactio if (tmpEntries.size() > 0) { for (OTransactionEntry txEntry : tmpEntries) // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE - commitEntry(iRequesterId, iTx, txEntry); + commitEntry(iRequesterId, iTx, txEntry, iTx.isUsingLog()); allEntries.addAll(tmpEntries); tmpEntries.clear(); @@ -194,7 +194,8 @@ protected void rollback() { // TODO } - private void commitEntry(final int iRequesterId, final OTransaction iTx, final OTransactionEntry txEntry) throws IOException { + private void commitEntry(final int iRequesterId, final OTransaction iTx, final OTransactionEntry txEntry, final boolean iUseLog) + throws IOException { if (txEntry.status != OTransactionEntry.DELETED && !txEntry.getRecord().isDirty()) return; @@ -215,46 +216,53 @@ private void commitEntry(final int iRequesterId, final OTransaction iTx, final O case OTransactionEntry.LOADED: break; - case OTransactionEntry.CREATED: + case OTransactionEntry.CREATED: { // CHECK 2 TIMES TO ASSURE THAT IT'S A CREATE OR AN UPDATE BASED ON RECURSIVE TO-STREAM METHOD byte[] stream = txEntry.getRecord().toStream(); - if (rid.isNew()) { - if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord())) - // RECORD CHANGED: RE-STREAM IT - stream = txEntry.getRecord().toStream(); - - rid.clusterPosition = createRecord(iRequesterId, iTx.getId(), cluster, stream, txEntry.getRecord().getRecordType()); - rid.clusterId = cluster.getId(); - - iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord()); + if (iUseLog) { + if (rid.isNew()) { + if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord())) + // RECORD CHANGED: RE-STREAM IT + stream = txEntry.getRecord().toStream(); + + rid.clusterPosition = createRecord(iRequesterId, iTx.getId(), cluster, stream, txEntry.getRecord().getRecordType()); + rid.clusterId = cluster.getId(); + + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord()); + } else { + txEntry.getRecord().setVersion( + updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), + txEntry.getRecord().getRecordType())); + } } else { - txEntry.getRecord().setVersion( - updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry - .getRecord().getRecordType())); + iTx.getDatabase().getStorage().createRecord(cluster.getId(), stream, txEntry.getRecord().getRecordType()); } break; + } + + case OTransactionEntry.UPDATED: { + byte[] stream = txEntry.getRecord().toStream(); - case OTransactionEntry.UPDATED: if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_UPDATE, txEntry.getRecord())) // RECORD CHANGED: RE-STREAM IT stream = txEntry.getRecord().toStream(); txEntry.getRecord().setVersion( - updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().toStream(), txEntry.getRecord() - .getVersion(), txEntry.getRecord().getRecordType())); + updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry + .getRecord().getRecordType())); iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_UPDATE, txEntry.getRecord()); break; + } - case OTransactionEntry.DELETED: - if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord())) - // RECORD CHANGED: RE-STREAM IT - stream = txEntry.getRecord().toStream(); + case OTransactionEntry.DELETED: { + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord()); deleteRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().getVersion()); iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_DELETE, txEntry.getRecord()); + } break; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java index 25f498c6fe4..0aa11089fe0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java @@ -46,6 +46,10 @@ public enum TXSTATUS { public int getId(); + public boolean isUsingLog(); + + public void setUsingLog(boolean useLog); + public Iterable<? extends OTransactionEntry> getEntries(); public List<OTransactionEntry> getEntriesByClass(String iClassName); diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java index 42203006e44..6a71398719e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java @@ -80,4 +80,11 @@ public int size() { public ORecordInternal<?> getEntry(ORecordId rid) { return null; } + + public boolean isUsingLog() { + return false; + } + + public void setUsingLog(final boolean useLog) { + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java index baeba5b507b..90fbe801888 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java @@ -21,6 +21,8 @@ import com.orientechnologies.orient.core.storage.OStorageEmbedded; public class OTransactionOptimistic extends OTransactionRealAbstract { + private boolean usingLog = true; + public OTransactionOptimistic(final ODatabaseRecordTx iDatabase, final int iId) { super(iDatabase, iId); } @@ -101,12 +103,12 @@ private void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, fin final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (!rid.isValid()) { - // TODO: NEED IT FOR REAL? - // NEW RECORD: CHECK IF IT'S ALREADY IN - for (OTransactionEntry entry : entries.values()) { - if (entry.getRecord() == iRecord) - return; - } +// // TODO: NEED IT FOR REAL? +// // NEW RECORD: CHECK IF IT'S ALREADY IN +// for (OTransactionEntry entry : entries.values()) { +// if (entry.getRecord() == iRecord) +// return; +// } iRecord.onBeforeIdentityChanged(rid); @@ -165,4 +167,12 @@ private void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, fin public String toString() { return "OTransactionOptimistic [id=" + id + ", status=" + status + ", entries=" + entries.size() + "]"; } + + public boolean isUsingLog() { + return usingLog; + } + + public void setUsingLog(final boolean useLog) { + this.usingLog = useLog; + } }
d79c2322e801524146441b1f61739ea079a9a15a
restlet-framework-java
- Initial code for new default HTTP connector.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/HttpServerHelper.java b/modules/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/HttpServerHelper.java index 215e65cad1..91ab71ce9a 100644 --- a/modules/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/HttpServerHelper.java +++ b/modules/org.restlet.ext.grizzly/src/org/restlet/ext/grizzly/HttpServerHelper.java @@ -64,7 +64,8 @@ public HttpServerHelper(Server server) { @Override protected void configure(Controller controller) throws Exception { // Get the TCP select handler of the controller - final TCPSelectorHandler selectorHandler = getSelectorHandler(); + TCPSelectorHandler selectorHandler = getSelectorHandler(); + // Configure it selectorHandler.setPort(getHelped().getPort()); if (getHelped().getAddress() != null) { diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java index ab8fa996c8..a53be36333 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java @@ -37,8 +37,6 @@ import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; @@ -47,8 +45,6 @@ import javax.net.ssl.SSLSocket; import org.restlet.Connector; -import org.restlet.Request; -import org.restlet.Response; import org.restlet.data.Parameter; import org.restlet.engine.ConnectorHelper; import org.restlet.engine.http.header.HeaderConstants; @@ -88,20 +84,12 @@ public static boolean isBroken(Exception exception) { return result; } - private volatile boolean persistent; - - private volatile boolean pipelining; - - private final Queue<Request> requests; - - private final Queue<Response> responses; - - private volatile ConnectionState state; - private volatile boolean inboundBusy; private volatile boolean outboundBusy; + private volatile ConnectionState state; + /** The connecting user */ private final Socket socket; @@ -117,10 +105,6 @@ public static boolean isBroken(Exception exception) { public Connection(ConnectorHelper<T> helper, Socket socket) throws IOException { this.helper = helper; - this.persistent = false; - this.pipelining = false; - this.requests = new ConcurrentLinkedQueue<Request>(); - this.responses = new ConcurrentLinkedQueue<Response>(); this.state = ConnectionState.CLOSED; this.socket = socket; this.inboundBusy = false; @@ -265,10 +249,10 @@ public void addAdditionalHeaders(Series<Parameter> existingHeaders, /** * Closes the connection. By default, set the state to - * {@link ConnectionState#CLOSING}. + * {@link ConnectionState#CLOSED}. */ public void close() { - setState(ConnectionState.CLOSING); + setState(ConnectionState.CLOSED); } public String getAddress() { @@ -322,14 +306,6 @@ protected Representation getRepresentation( null); } - public Queue<Request> getRequests() { - return requests; - } - - public Queue<Response> getResponses() { - return responses; - } - public Socket getSocket() { return socket; } @@ -395,20 +371,12 @@ public boolean isOutboundBusy() { return outboundBusy; } - public boolean isPersistent() { - return persistent; - } - - public boolean isPipelining() { - return pipelining; - } - /** * Opens the connection. By default, set the state to - * {@link ConnectionState#OPENING}. + * {@link ConnectionState#OPEN}. */ public void open() { - setState(ConnectionState.OPENING); + setState(ConnectionState.OPEN); } public void setInboundBusy(boolean inboundBusy) { @@ -419,14 +387,6 @@ public void setOutboundBusy(boolean outboundBusy) { this.outboundBusy = outboundBusy; } - public void setPersistent(boolean persistent) { - this.persistent = persistent; - } - - public void setPipelining(boolean pipelining) { - this.pipelining = pipelining; - } - public void setState(ConnectionState state) { this.state = state; } diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java b/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java index baef77acf0..a0388a3b8b 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java @@ -41,7 +41,7 @@ public enum ConnectionState { OPENING, /** The network connection has been successfully opened. */ - OPENED, + OPEN, /** The network connection is being closed. */ CLOSING, diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/DefaultServerConnection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/DefaultServerConnection.java index 44471cc41d..436a7a3579 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/DefaultServerConnection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/DefaultServerConnection.java @@ -38,9 +38,14 @@ import java.net.Socket; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.logging.Level; +import org.restlet.Request; +import org.restlet.Response; + /** * An internal HTTP server connection. * @@ -54,6 +59,14 @@ public class DefaultServerConnection extends ServerConnection { /** The outbound stream. */ private final OutputStream outboundStream; + private volatile boolean persistent; + + private volatile boolean pipelining; + + private final Queue<Request> requests; + + private final Queue<Response> responses; + /** * Constructor. * @@ -66,23 +79,10 @@ public DefaultServerConnection(DefaultServerHelper helper, Socket socket) super(helper, socket); this.inboundStream = new BufferedInputStream(socket.getInputStream()); this.outboundStream = new BufferedOutputStream(socket.getOutputStream()); - } - - @Override - public void open() { - super.open(); - - if (!getHelper().getHandlerService().isShutdown()) { - try { - getHelper().handle(null, null); - } catch (Exception e) { - getLogger().log(Level.WARNING, - "Error while handling an HTTP server call: ", - e.getMessage()); - getLogger().log(Level.INFO, - "Error while handling an HTTP server call", e); - } - } + this.persistent = false; + this.pipelining = false; + this.requests = new ConcurrentLinkedQueue<Request>(); + this.responses = new ConcurrentLinkedQueue<Response>(); } @Override @@ -134,6 +134,10 @@ public InputStream getRequestHeadStream() { return getInboundStream(); } + public Queue<Request> getRequests() { + return requests; + } + @Override public WritableByteChannel getResponseEntityChannel() { return null; @@ -144,4 +148,42 @@ public OutputStream getResponseEntityStream() { return null; } + public Queue<Response> getResponses() { + return responses; + } + + public boolean isPersistent() { + return persistent; + } + + public boolean isPipelining() { + return pipelining; + } + + @Override + public void open() { + super.open(); + + if (!getHelper().getHandlerService().isShutdown()) { + try { + + getHelper().handle(null, null); + } catch (Exception e) { + getLogger().log(Level.WARNING, + "Error while handling an HTTP server call: ", + e.getMessage()); + getLogger().log(Level.INFO, + "Error while handling an HTTP server call", e); + } + } + } + + public void setPersistent(boolean persistent) { + this.persistent = persistent; + } + + public void setPipelining(boolean pipelining) { + this.pipelining = pipelining; + } + }
a0670a90454c44cfb1bcf30dee2b097ea7dfdec1
agorava$agorava-core
AGOVA-68 Add PicketLink Support Add picketlink lib in dependency management Switch from @GenericBean to @Generic annotation Improve Generic support for bean other than OAuthService
a
https://github.com/agorava/agorava-core
diff --git a/agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java b/agorava-core-api/src/main/java/org/agorava/api/atinject/Generic.java similarity index 92% rename from agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java rename to agorava-core-api/src/main/java/org/agorava/api/atinject/Generic.java index d6644e3..b12de2a 100644 --- a/agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java +++ b/agorava-core-api/src/main/java/org/agorava/api/atinject/Generic.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 Agorava + * Copyright 2014 Agorava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,19 @@ package org.agorava.api.atinject; -import javax.inject.Qualifier; -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + /** - * This qualifier is used to mark Class to indicate that it should be used to generate differrent beans for each {@link + * This qualifier is used to mark Class to indicate that it should be used to generate different beans for each {@link * ProviderRelated} Qualifier. * <p/> * Provider services (i.e. Social Media) are dynamically discovered when Agorava is bootstrapped thanks to Provider services @@ -46,8 +46,8 @@ * @see InjectWithQualifier */ @Qualifier -@Target({TYPE, METHOD, PARAMETER, FIELD}) +@Target({ TYPE, METHOD, PARAMETER, FIELD }) @Retention(RUNTIME) @Documented -public @interface GenericBean { +public @interface Generic { } diff --git a/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java b/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java index eba3b3c..b6e6d62 100644 --- a/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java +++ b/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 Agorava + * Copyright 2014 Agorava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,21 @@ package org.agorava.api.atinject; -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + /** * Annotation used in Generic Bean to mark injection point that should be modified by * framework bootstrap to bear the same {@link ProviderRelated} qualifier than the containing bean. * <p>For example: * <pre> - * &#064;org.agorava.api.atinject.GenericBean + * &#064;org.agorava.api.atinject.Generic * public OAuthServiceImpl extends OAuthService { * * &#064;InjectWithQualifier @@ -40,9 +40,9 @@ * * @author Antoine Sabot-Durand * @see ProviderRelated - * @see GenericBean + * @see Generic */ -@Target({METHOD, FIELD, PARAMETER}) +@Target({ METHOD, FIELD, PARAMETER }) @Retention(RUNTIME) @Documented public @interface InjectWithQualifier { diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java index ef9def0..d8b88e2 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java @@ -19,6 +19,7 @@ import org.agorava.AgoravaConstants; import org.agorava.AgoravaContext; import org.agorava.api.atinject.Current; +import org.agorava.api.atinject.Generic; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.atinject.ProviderRelated; import org.agorava.api.exception.AgoravaException; @@ -88,6 +89,7 @@ public class AgoravaExtension extends AgoravaContext implements Extension, Seria private Map<OAuth.OAuthVersion, Class<? extends OAuthService>> version2ServiceClass = new HashMap<OAuth.OAuthVersion, Class<? extends OAuthService>>(); private Map<Annotation, OAuth.OAuthVersion> providerQualifiers2Version = new HashMap<Annotation, OAuth.OAuthVersion>(); + private Set<Class<?>> genericClasses = new HashSet<Class<?>>(); /** * @return the set of all service's qualifiers present in the application @@ -153,6 +155,19 @@ public void processOauthService(@Observes ProcessAnnotatedType<? extends OAuthSe version2ServiceClass.put(qualOauth.value(), clazz); } + public void vetoOauthSession(@Observes ProcessAnnotatedType<OAuthSession> pat) { + pat.veto(); + } + + public void processGenericBeanAnnotated(@Observes ProcessAnnotatedType<?> pat) { + + AnnotatedType<?> at = pat.getAnnotatedType(); + if (at.isAnnotationPresent(Generic.class) && !(at.isAnnotationPresent(OAuth.class))) { + genericClasses.add(at.getJavaClass()); + pat.veto(); + } + } + //----------------- Process Producer Phase ---------------------------------- /** @@ -239,12 +254,6 @@ public void processRemoteServiceRoot(@Observes ProcessBean<? extends ProviderCon CommonsProcessOAuthTier(pb); } - private void captureGenericOAuthService(@Observes ProcessBean<? extends OAuthService> pb) { - Bean<? extends OAuthService> bean = pb.getBean(); - if (bean.getQualifiers().contains(GenericBeanLiteral.INSTANCE)) { - log.info("here"); - } - } private void captureOauthSessionProducer(@Observes ProcessProducerMethod<OAuthSession, ?> pb) { Annotated at = pb.getAnnotated(); @@ -295,10 +304,12 @@ private <T> void beanRegisterer(Class<T> clazz, Annotation qual, Class<? extends BeanBuilder<T> providerBuilder = new BeanBuilder<T>(beanManager) .readFromType(atb.create()) - .scope(scope) .passivationCapable(true) .addTypes(types); + if (scope != null) { + providerBuilder.scope(scope); + } Bean<T> newBean = providerBuilder.create(); abd.addBean(newBean); } @@ -314,6 +325,11 @@ private <T> void beanRegisterer(Class<T> clazz, Annotation qual, Class<? extends public void registerGenericBeans(@Observes AfterBeanDiscovery abd, BeanManager beanManager) { for (Annotation qual : providerQualifiersConfigured) { + for (Class<?> aClass : genericClasses) { + beanRegisterer(aClass, qual, Dependent.class, abd, beanManager); + + } + OAuth.OAuthVersion version = providerQualifiers2Version.get(qual); if (version == null) { abd.addDefinitionError(new AgoravaException("There is no OAuth version associated to provider related " + diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/GenericBeanLiteral.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/GenericLiteral.java similarity index 74% rename from agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/GenericBeanLiteral.java rename to agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/GenericLiteral.java index 6559937..7813601 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/GenericBeanLiteral.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/GenericLiteral.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 Agorava + * Copyright 2014 Agorava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,13 @@ package org.agorava.cdi.extensions; -import org.agorava.api.atinject.GenericBean; +import org.agorava.api.atinject.Generic; import javax.enterprise.util.AnnotationLiteral; /** * @author Antoine Sabot-Durand */ -class GenericBeanLiteral extends AnnotationLiteral<GenericBean> implements GenericBean { - public static GenericBeanLiteral INSTANCE = new GenericBeanLiteral(); +class GenericLiteral extends AnnotationLiteral<Generic> implements Generic { + public static GenericLiteral INSTANCE = new GenericLiteral(); } diff --git a/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/GenericService.java b/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/GenericService.java new file mode 100644 index 0000000..855af71 --- /dev/null +++ b/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/GenericService.java @@ -0,0 +1,39 @@ +/* + * Copyright 2014 Agorava + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.agorava.cdi.test; + +import org.agorava.api.atinject.Generic; +import org.agorava.api.atinject.InjectWithQualifier; +import org.agorava.api.oauth.application.OAuthAppSettings; + +/** + * @author Antoine Sabot-Durand + */ + +@Generic +public class GenericService { + + + @InjectWithQualifier + OAuthAppSettings settings; + + public OAuthAppSettings getSettings() { + return settings; + } + + +} diff --git a/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/ProvidersAndSettingsBeanGenerationTest.java b/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/ProvidersAndSettingsBeanGenerationTest.java index e30e1a0..7fc77e7 100644 --- a/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/ProvidersAndSettingsBeanGenerationTest.java +++ b/agorava-core-impl-cdi/src/test/java/org/agorava/cdi/test/ProvidersAndSettingsBeanGenerationTest.java @@ -63,6 +63,10 @@ public class ProvidersAndSettingsBeanGenerationTest extends AgoravaArquillianCom @Any Instance<OAuthSession> sessions; + @Inject + @Any + Instance<GenericService> genericServices; + @Deployment public static Archive<?> createTestArchive() throws FileNotFoundException { @@ -73,16 +77,12 @@ public static Archive<?> createTestArchive() throws FileNotFoundException { FakeService.class, FakeService2.class, FakeServiceLiteral.class, - FakeService2Literal.class) + FakeService2Literal.class, + GenericService.class) .addAsResource("agorava-request-resolver.properties", "agorava.properties"); return ret; } - /*@BeforeClass - public static void before() { - getenv().put("agorava.bundle", "agorava-request-resolver"); - }*/ - @Test public void providersShouldHaveRightOauthVersion() { @@ -96,7 +96,15 @@ public void settingsShouldHaveRightQualifier() { Assert.assertEquals("Bad qualifier for settings2", FakeService2Literal.INSTANCE, settings2.getQualifier()); } - + @Test + public void genericServiceShouldBeTwo() { + int i = 0; + for (GenericService g : genericServices) { + i++; + Assert.assertNotNull(g.getSettings()); + } + Assert.assertEquals(i, 2); + } /*@Test(expected = NullPointerException.class) public void testServiceWithCurrentSession() { diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java index fb891f0..346c681 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java @@ -17,7 +17,7 @@ package org.agorava.oauth; import org.agorava.AgoravaConstants; -import org.agorava.api.atinject.GenericBean; +import org.agorava.api.atinject.Generic; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.oauth.OAuth; import org.agorava.api.oauth.OAuthRequest; @@ -42,7 +42,7 @@ * @author Pablo Fernandez */ -@GenericBean +@Generic @OAuth(ONE) public class OAuth10aServiceImpl extends OAuthServiceBase { private static Logger LOGGER = Logger.getLogger(OAuth10aServiceImpl.class.getName()); diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java index 003a221..5cd8666 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20FinalServiceImpl.java @@ -17,7 +17,7 @@ package org.agorava.oauth; import org.agorava.AgoravaConstants; -import org.agorava.api.atinject.GenericBean; +import org.agorava.api.atinject.Generic; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.oauth.OAuth; import org.agorava.api.oauth.OAuthRequest; @@ -33,7 +33,7 @@ /** * @author Antoine Sabot-Durand */ -@GenericBean +@Generic @OAuth(TWO_FINAL) public class OAuth20FinalServiceImpl extends OAuth20ServiceImpl { diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java index a5d2d3b..0c67d44 100644 --- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java +++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth20ServiceImpl.java @@ -18,7 +18,7 @@ import org.agorava.AgoravaConstants; -import org.agorava.api.atinject.GenericBean; +import org.agorava.api.atinject.Generic; import org.agorava.api.atinject.InjectWithQualifier; import org.agorava.api.oauth.OAuth; import org.agorava.api.oauth.OAuthRequest; @@ -30,7 +30,7 @@ import org.agorava.spi.ProviderConfigOauth20; import static org.agorava.api.oauth.OAuth.OAuthVersion.TWO_DRAFT_11; -@GenericBean +@Generic @OAuth(TWO_DRAFT_11) public class OAuth20ServiceImpl extends OAuthServiceBase {
e62058be691ad452be79c96d0738207d34d55ea3
Delta Spike
DELTASPIKE-462 don't close the EM if we didn't open it This happens when we use BeanManagedUserTransactionStrategy and have a Stateless EJB call our transactional CDI beans.
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java index c363d7286..b7bd1fada 100644 --- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java +++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java @@ -79,6 +79,7 @@ public Object execute(InvocationContext invocationContext) throws Exception TransactionBeanStorage transactionBeanStorage = TransactionBeanStorage.getInstance(); boolean isOutermostInterceptor = transactionBeanStorage.isEmpty(); + boolean outermostTransactionAlreadyExisted = false; if (isOutermostInterceptor) { @@ -107,6 +108,10 @@ public Object execute(InvocationContext invocationContext) throws Exception { transaction.begin(); } + else if (isOutermostInterceptor) + { + outermostTransactionAlreadyExisted = true; + } //don't move it before EntityTransaction#begin() and invoke it in any case beforeProceed(entityManagerEntry); @@ -125,25 +130,15 @@ public Object execute(InvocationContext invocationContext) throws Exception Set<EntityManagerEntry> entityManagerEntryList = transactionBeanStorage.getUsedEntityManagerEntries(); - for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) + if (!outermostTransactionAlreadyExisted) { - EntityTransaction transaction = getTransaction(currentEntityManagerEntry); - if (transaction != null && transaction.isActive()) - { - try - { - transaction.rollback(); - } - catch (Exception eRollback) - { - if (LOGGER.isLoggable(Level.SEVERE)) - { - LOGGER.log(Level.SEVERE, - "Got additional Exception while subsequently " + - "rolling back other SQL transactions", eRollback); - } - } - } + // We only commit transactions we opened ourselfs. + // If the transaction got opened outside of our interceptor chain + // we must not handle it. + // This e.g. happens if a Stateless EJB invokes a Transactional CDI bean + // which uses the BeanManagedUserTransactionStrategy. + + rollbackAllTransactions(entityManagerEntryList); } // drop all EntityManagers from the request-context cache @@ -163,73 +158,85 @@ public Object execute(InvocationContext invocationContext) throws Exception boolean commitFailed = false; // commit all open transactions in the outermost interceptor! - // this is a 'JTA for poor men' only, and will not guaranty + // For Resource-local this is a 'JTA for poor men' only, and will not guaranty // commit stability over various databases! + // In case of JTA we will just commit the UserTransaction. if (isOutermostInterceptor) { - // only commit all transactions if we didn't rollback - // them already - if (firstException == null) + if (!outermostTransactionAlreadyExisted) { - Set<EntityManagerEntry> entityManagerEntryList = - transactionBeanStorage.getUsedEntityManagerEntries(); + // We only commit transactions we opened ourselfs. + // If the transaction got opened outside of our interceptor chain + // we must not handle it. + // This e.g. happens if a Stateless EJB invokes a Transactional CDI bean + // which uses the BeanManagedUserTransactionStrategy. - boolean rollbackOnly = false; - // but first try to flush all the transactions and write the updates to the database - for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) + if (firstException == null) { - EntityTransaction transaction = getTransaction(currentEntityManagerEntry); - if (transaction != null && transaction.isActive()) + // only commit all transactions if we didn't rollback + // them already + Set<EntityManagerEntry> entityManagerEntryList = + transactionBeanStorage.getUsedEntityManagerEntries(); + + boolean rollbackOnly = false; + // but first try to flush all the transactions and write the updates to the database + for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) { - try + EntityTransaction transaction = getTransaction(currentEntityManagerEntry); + if (transaction != null && transaction.isActive()) { - if (!commitFailed) + try { - currentEntityManagerEntry.getEntityManager().flush(); - - if (!rollbackOnly && transaction.getRollbackOnly()) + if (!commitFailed) { - //don't set commitFailed to true directly - //(the order of the entity-managers isn't deterministic -> tests would break) - rollbackOnly = true; + currentEntityManagerEntry.getEntityManager().flush(); + + if (!rollbackOnly && transaction.getRollbackOnly()) + { + // don't set commitFailed to true directly + // (the order of the entity-managers isn't deterministic + // -> tests would break) + rollbackOnly = true; + } } } - } - catch (Exception e) - { - firstException = e; - commitFailed = true; - break; + catch (Exception e) + { + firstException = e; + commitFailed = true; + break; + } } } - } - if (rollbackOnly) - { - commitFailed = true; - } + if (rollbackOnly) + { + commitFailed = true; + } - // and now either commit or rollback all transactions - for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) - { - EntityTransaction transaction = getTransaction(currentEntityManagerEntry); - if (transaction != null && transaction.isActive()) + // and now either commit or rollback all transactions + for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) { - try + EntityTransaction transaction = getTransaction(currentEntityManagerEntry); + if (transaction != null && transaction.isActive()) { - if (commitFailed || transaction.getRollbackOnly() /*last chance to check it (again)*/) + try { - transaction.rollback(); + // last chance to check it (again) + if (commitFailed || transaction.getRollbackOnly()) + { + transaction.rollback(); + } + else + { + transaction.commit(); + } } - else + catch (Exception e) { - transaction.commit(); + firstException = e; + commitFailed = true; } } - catch (Exception e) - { - firstException = e; - commitFailed = true; - } } } } @@ -248,6 +255,30 @@ public Object execute(InvocationContext invocationContext) throws Exception } } + private void rollbackAllTransactions(Set<EntityManagerEntry> entityManagerEntryList) + { + for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList) + { + EntityTransaction transaction = getTransaction(currentEntityManagerEntry); + if (transaction != null && transaction.isActive()) + { + try + { + transaction.rollback(); + } + catch (Exception eRollback) + { + if (LOGGER.isLoggable(Level.SEVERE)) + { + LOGGER.log(Level.SEVERE, + "Got additional Exception while subsequently " + + "rolling back other SQL transactions", eRollback); + } + } + } + } + } + protected EntityManagerEntry createEntityManagerEntry( EntityManager entityManager, Class<? extends Annotation> qualifier) { diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java index 811bf619d..c37dc7224 100644 --- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java +++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java @@ -24,7 +24,6 @@ /** * Stores a {@link EntityManager} and the qualifier - * @deprecated we shall rather introduce an own QualifierMap or a ComparableQualifier which checks Nonbinding */ @Typed() public class EntityManagerEntry
04f1e7a41874bb93434c91c80544eda24afbb215
hadoop
HADOOP-7001. Configuration changes can occur via- the Reconfigurable interface. (Patrick Kline via dhruba)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1038480 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index fb24c361eaac0..3ac3baf1d920b 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -14,6 +14,9 @@ Trunk (unreleased changes) HADOOP-7042. Updates to test-patch.sh to include failed test names and improve other messaging. (nigel) + HADOOP-7001. Configuration changes can occur via the Reconfigurable + interface. (Patrick Kline via dhruba) + OPTIMIZATIONS BUG FIXES diff --git a/src/java/org/apache/hadoop/conf/Configuration.java b/src/java/org/apache/hadoop/conf/Configuration.java index ac242d6282769..7f265f3e6b480 100644 --- a/src/java/org/apache/hadoop/conf/Configuration.java +++ b/src/java/org/apache/hadoop/conf/Configuration.java @@ -587,12 +587,22 @@ public void set(String name, String value) { } } + /** + * Unset a previously set property. + */ + public synchronized void unset(String name) { + name = handleDeprecation(name); + + getOverlay().remove(name); + getProps().remove(name); + } + /** * Sets a property if it is currently unset. * @param name the property name * @param value the new value */ - public void setIfUnset(String name, String value) { + public synchronized void setIfUnset(String name, String value) { if (get(name) == null) { set(name, value); } diff --git a/src/java/org/apache/hadoop/conf/ReconfigurableBase.java b/src/java/org/apache/hadoop/conf/ReconfigurableBase.java new file mode 100644 index 0000000000000..b872e77225914 --- /dev/null +++ b/src/java/org/apache/hadoop/conf/ReconfigurableBase.java @@ -0,0 +1,114 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.conf; + +import org.apache.commons.logging.*; + +import java.util.Collection; + +/** + * Utility base class for implementing the Reconfigurable interface. + * + * Subclasses should override reconfigurePropertyImpl to change individual + * properties and getReconfigurableProperties to get all properties that + * can be changed at run time. + */ +public abstract class ReconfigurableBase + extends Configured implements Reconfigurable { + + private static final Log LOG = + LogFactory.getLog(ReconfigurableBase.class); + + /** + * Construct a ReconfigurableBase. + */ + public ReconfigurableBase() { + super(new Configuration()); + } + + /** + * Construct a ReconfigurableBase with the {@link Configuration} + * conf. + */ + public ReconfigurableBase(Configuration conf) { + super((conf == null) ? new Configuration() : conf); + } + + /** + * {@inheritDoc} + * + * This method makes the change to this objects {@link Configuration} + * and calls reconfigurePropertyImpl to update internal data structures. + * This method cannot be overridden, subclasses should instead override + * reconfigureProperty. + */ + @Override + public final String reconfigureProperty(String property, String newVal) + throws ReconfigurationException { + if (isPropertyReconfigurable(property)) { + LOG.info("changing property " + property + " to " + newVal); + String oldVal; + synchronized(getConf()) { + oldVal = getConf().get(property); + reconfigurePropertyImpl(property, newVal); + if (newVal != null) { + getConf().set(property, newVal); + } else { + getConf().unset(property); + } + } + return oldVal; + } else { + throw new ReconfigurationException(property, newVal, + getConf().get(property)); + } + } + + /** + * {@inheritDoc} + * + * Subclasses must override this. + */ + @Override + public abstract Collection<String> getReconfigurableProperties(); + + + /** + * {@inheritDoc} + * + * Subclasses may wish to override this with a more efficient implementation. + */ + @Override + public boolean isPropertyReconfigurable(String property) { + return getReconfigurableProperties().contains(property); + } + + /** + * Change a configuration property. + * + * Subclasses must override this. This method applies the change to + * all internal data structures derived from the configuration property + * that is being changed. If this object owns other Reconfigurable objects + * reconfigureProperty should be called recursively to make sure that + * to make sure that the configuration of these objects is updated. + */ + protected abstract void reconfigurePropertyImpl(String property, String newVal) + throws ReconfigurationException; + +} diff --git a/src/java/org/apache/hadoop/conf/ReconfigurationException.java b/src/java/org/apache/hadoop/conf/ReconfigurationException.java new file mode 100644 index 0000000000000..0935bf025fd30 --- /dev/null +++ b/src/java/org/apache/hadoop/conf/ReconfigurationException.java @@ -0,0 +1,104 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.conf; + + +/** + * Exception indicating that configuration property cannot be changed + * at run time. + */ +public class ReconfigurationException extends Exception { + + private static final long serialVersionUID = 1L; + + private String property; + private String newVal; + private String oldVal; + + /** + * Construct the exception message. + */ + private static String constructMessage(String property, + String newVal, String oldVal) { + String message = "Could not change property " + property; + if (oldVal != null) { + message += " from \'" + oldVal; + } + if (newVal != null) { + message += "\' to \'" + newVal + "\'"; + } + return message; + } + + + /** + * Create a new instance of {@link ReconfigurationException}. + */ + public ReconfigurationException() { + super("Could not change configuration."); + this.property = null; + this.newVal = null; + this.oldVal = null; + } + + /** + * Create a new instance of {@link ReconfigurationException}. + */ + public ReconfigurationException(String property, + String newVal, String oldVal, + Throwable cause) { + super(constructMessage(property, newVal, oldVal), cause); + this.property = property; + this.newVal = newVal; + this.oldVal = oldVal; + } + + /** + * Create a new instance of {@link ReconfigurationException}. + */ + public ReconfigurationException(String property, + String newVal, String oldVal) { + super(constructMessage(property, newVal, oldVal)); + this.property = property; + this.newVal = newVal; + this.oldVal = oldVal; + } + + /** + * Get property that cannot be changed. + */ + public String getProperty() { + return property; + } + + /** + * Get value to which property was supposed to be changed. + */ + public String getNewValue() { + return newVal; + } + + /** + * Get old value of property that cannot be changed. + */ + public String getOldValue() { + return oldVal; + } + +} diff --git a/src/java/org/apache/hadoop/conf/ReconfigurationServlet.java b/src/java/org/apache/hadoop/conf/ReconfigurationServlet.java new file mode 100644 index 0000000000000..041b263edd92d --- /dev/null +++ b/src/java/org/apache/hadoop/conf/ReconfigurationServlet.java @@ -0,0 +1,248 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.conf; + +import org.apache.commons.logging.*; + +import org.apache.commons.lang.StringEscapeUtils; + +import java.util.Collection; +import java.util.Map; +import java.util.Enumeration; +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.hadoop.util.StringUtils; + +/** + * A servlet for changing a node's configuration. + * + * Reloads the configuration file, verifies whether changes are + * possible and asks the admin to approve the change. + * + */ +public class ReconfigurationServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Log LOG = + LogFactory.getLog(ReconfigurationServlet.class); + + // the prefix used to fing the attribute holding the reconfigurable + // for a given request + // + // we get the attribute prefix + servlet path + public static final String CONF_SERVLET_RECONFIGURABLE_PREFIX = + "conf.servlet.reconfigurable."; + + /** + * {@inheritDoc} + */ + @Override + public void init() throws ServletException { + super.init(); + } + + private Reconfigurable getReconfigurable(HttpServletRequest req) { + LOG.info("servlet path: " + req.getServletPath()); + LOG.info("getting attribute: " + CONF_SERVLET_RECONFIGURABLE_PREFIX + + req.getServletPath()); + return (Reconfigurable) + this.getServletContext().getAttribute(CONF_SERVLET_RECONFIGURABLE_PREFIX + + req.getServletPath()); + } + + private void printHeader(PrintWriter out, String nodeName) { + out.print("<html><head>"); + out.printf("<title>%s Reconfiguration Utility</title>\n", + StringEscapeUtils.escapeHtml(nodeName)); + out.print("</head><body>\n"); + out.printf("<h1>%s Reconfiguration Utility</h1>\n", + StringEscapeUtils.escapeHtml(nodeName)); + } + + private void printFooter(PrintWriter out) { + out.print("</body></html>\n"); + } + + /** + * Print configuration options that can be changed. + */ + private void printConf(PrintWriter out, Reconfigurable reconf) { + Configuration oldConf = reconf.getConf(); + Configuration newConf = new Configuration(); + + Collection<ReconfigurationUtil.PropertyChange> changes = + ReconfigurationUtil.getChangedProperties(newConf, + oldConf); + + boolean changeOK = true; + + out.println("<form action=\"\" method=\"post\">"); + out.println("<table border=\"1\">"); + out.println("<tr><th>Property</th><th>Old value</th>"); + out.println("<th>New value </th><th></th></tr>"); + for (ReconfigurationUtil.PropertyChange c: changes) { + out.print("<tr><td>"); + if (!reconf.isPropertyReconfigurable(c.prop)) { + out.print("<font color=\"red\">" + + StringEscapeUtils.escapeHtml(c.prop) + "</font>"); + changeOK = false; + } else { + out.print(StringEscapeUtils.escapeHtml(c.prop)); + out.print("<input type=\"hidden\" name=\"" + + StringEscapeUtils.escapeHtml(c.prop) + "\" value=\"" + + StringEscapeUtils.escapeHtml(c.newVal) + "\"/>"); + } + out.print("</td><td>" + + (c.oldVal == null ? "<it>default</it>" : + StringEscapeUtils.escapeHtml(c.oldVal)) + + "</td><td>" + + (c.newVal == null ? "<it>default</it>" : + StringEscapeUtils.escapeHtml(c.newVal)) + + "</td>"); + out.print("</tr>\n"); + } + out.println("</table>"); + if (!changeOK) { + out.println("<p><font color=\"red\">WARNING: properties marked red" + + " will not be changed until the next restart.</font></p>"); + } + out.println("<input type=\"submit\" value=\"Apply\" />"); + out.println("</form>"); + } + + @SuppressWarnings("unchecked") + private Enumeration<String> getParams(HttpServletRequest req) { + return (Enumeration<String>) req.getParameterNames(); + } + + /** + * Apply configuratio changes after admin has approved them. + */ + private void applyChanges(PrintWriter out, Reconfigurable reconf, + HttpServletRequest req) + throws IOException, ReconfigurationException { + Configuration oldConf = reconf.getConf(); + Configuration newConf = new Configuration(); + + Enumeration<String> params = getParams(req); + + synchronized(oldConf) { + while (params.hasMoreElements()) { + String rawParam = params.nextElement(); + String param = StringEscapeUtils.unescapeHtml(rawParam); + String value = + StringEscapeUtils.unescapeHtml(req.getParameter(rawParam)); + if (value != null) { + if (value.equals(newConf.getRaw(param)) || value.equals("default") || + value.equals("null") || value.equals("")) { + if ((value.equals("default") || value.equals("null") || + value.equals("")) && + oldConf.getRaw(param) != null) { + out.println("<p>Changed \"" + + StringEscapeUtils.escapeHtml(param) + "\" from \"" + + StringEscapeUtils.escapeHtml(oldConf.getRaw(param)) + + "\" to default</p>"); + reconf.reconfigureProperty(param, null); + } else if (!value.equals("default") && !value.equals("null") && + !value.equals("") && + (oldConf.getRaw(param) == null || + !oldConf.getRaw(param).equals(value))) { + // change from default or value to different value + if (oldConf.getRaw(param) == null) { + out.println("<p>Changed \"" + + StringEscapeUtils.escapeHtml(param) + + "\" from default to \"" + + StringEscapeUtils.escapeHtml(value) + "\"</p>"); + } else { + out.println("<p>Changed \"" + + StringEscapeUtils.escapeHtml(param) + "\" from \"" + + StringEscapeUtils.escapeHtml(oldConf. + getRaw(param)) + + "\" to \"" + + StringEscapeUtils.escapeHtml(value) + "\"</p>"); + } + reconf.reconfigureProperty(param, value); + } else { + LOG.info("property " + param + " unchanged"); + } + } else { + // parameter value != newConf value + out.println("<p>\"" + StringEscapeUtils.escapeHtml(param) + + "\" not changed because value has changed from \"" + + StringEscapeUtils.escapeHtml(value) + "\" to \"" + + StringEscapeUtils.escapeHtml(newConf.getRaw(param)) + + "\" since approval</p>"); + } + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + LOG.info("GET"); + PrintWriter out = resp.getWriter(); + + Reconfigurable reconf = getReconfigurable(req); + String nodeName = reconf.getClass().getCanonicalName(); + + printHeader(out, nodeName); + printConf(out, reconf); + printFooter(out); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + LOG.info("POST"); + PrintWriter out = resp.getWriter(); + + Reconfigurable reconf = getReconfigurable(req); + String nodeName = reconf.getClass().getCanonicalName(); + + printHeader(out, nodeName); + + try { + applyChanges(out, reconf, req); + } catch (ReconfigurationException e) { + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + StringUtils.stringifyException(e)); + return; + } + + out.println("<p><a href=\"" + req.getServletPath() + "\">back</a></p>"); + printFooter(out); + } + +} \ No newline at end of file diff --git a/src/java/org/apache/hadoop/conf/ReconfigurationUtil.java b/src/java/org/apache/hadoop/conf/ReconfigurationUtil.java new file mode 100644 index 0000000000000..ca685f4058491 --- /dev/null +++ b/src/java/org/apache/hadoop/conf/ReconfigurationUtil.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.conf; + +import java.util.Map; +import java.util.Collection; +import java.util.HashMap; + +public class ReconfigurationUtil { + + public static class PropertyChange { + public String prop; + public String oldVal; + public String newVal; + + public PropertyChange(String prop, String newVal, String oldVal) { + this.prop = prop; + this.newVal = newVal; + this.oldVal = oldVal; + } + } + + public static Collection<PropertyChange> + getChangedProperties(Configuration newConf, Configuration oldConf) { + Map<String, PropertyChange> changes = new HashMap<String, PropertyChange>(); + + // iterate over old configuration + for (Map.Entry<String, String> oldEntry: oldConf) { + String prop = oldEntry.getKey(); + String oldVal = oldEntry.getValue(); + String newVal = newConf.getRaw(prop); + + if (newVal == null || !newVal.equals(oldVal)) { + changes.put(prop, new PropertyChange(prop, newVal, oldVal)); + } + } + + // now iterate over new configuration + // (to look for properties not present in old conf) + for (Map.Entry<String, String> newEntry: newConf) { + String prop = newEntry.getKey(); + String newVal = newEntry.getValue(); + if (oldConf.get(prop) == null) { + changes.put(prop, new PropertyChange(prop, newVal, null)); + } + } + + return changes.values(); + } +} \ No newline at end of file diff --git a/src/test/core/org/apache/hadoop/conf/TestReconfiguration.java b/src/test/core/org/apache/hadoop/conf/TestReconfiguration.java new file mode 100644 index 0000000000000..d3e93a5f793af --- /dev/null +++ b/src/test/core/org/apache/hadoop/conf/TestReconfiguration.java @@ -0,0 +1,293 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.conf; + +import junit.framework.TestCase; + +import org.junit.Test; +import org.junit.Before; + +import java.util.Collection; +import java.util.Arrays; + +public class TestReconfiguration extends TestCase { + private Configuration conf1; + private Configuration conf2; + + private static final String PROP1 = "test.prop.one"; + private static final String PROP2 = "test.prop.two"; + private static final String PROP3 = "test.prop.three"; + private static final String PROP4 = "test.prop.four"; + private static final String PROP5 = "test.prop.five"; + + private static final String VAL1 = "val1"; + private static final String VAL2 = "val2"; + + @Before + public void setUp () { + conf1 = new Configuration(); + conf2 = new Configuration(); + + // set some test properties + conf1.set(PROP1, VAL1); + conf1.set(PROP2, VAL1); + conf1.set(PROP3, VAL1); + + conf2.set(PROP1, VAL1); // same as conf1 + conf2.set(PROP2, VAL2); // different value as conf1 + // PROP3 not set in conf2 + conf2.set(PROP4, VAL1); // not set in conf1 + + } + + /** + * Test ReconfigurationUtil.getChangedProperties. + */ + @Test + public void testGetChangedProperties() { + Collection<ReconfigurationUtil.PropertyChange> changes = + ReconfigurationUtil.getChangedProperties(conf2, conf1); + + assertTrue(changes.size() == 3); + + boolean changeFound = false; + boolean unsetFound = false; + boolean setFound = false; + + for (ReconfigurationUtil.PropertyChange c: changes) { + if (c.prop.equals(PROP2) && c.oldVal != null && c.oldVal.equals(VAL1) && + c.newVal != null && c.newVal.equals(VAL2)) { + changeFound = true; + } else if (c.prop.equals(PROP3) && c.oldVal != null && c.oldVal.equals(VAL1) && + c.newVal == null) { + unsetFound = true; + } else if (c.prop.equals(PROP4) && c.oldVal == null && + c.newVal != null && c.newVal.equals(VAL1)) { + setFound = true; + } + } + + assertTrue(changeFound && unsetFound && setFound); + } + + /** + * a simple reconfigurable class + */ + public static class ReconfigurableDummy extends ReconfigurableBase + implements Runnable { + public volatile boolean running = true; + + public ReconfigurableDummy(Configuration conf) { + super(conf); + } + + /** + * {@inheritDoc} + */ + @Override + public Collection<String> getReconfigurableProperties() { + return Arrays.asList(PROP1, PROP2, PROP4); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized void reconfigurePropertyImpl(String property, + String newVal) { + // do nothing + } + + /** + * Run until PROP1 is no longer VAL1. + */ + @Override + public void run() { + while (running && getConf().get(PROP1).equals(VAL1)) { + try { + Thread.sleep(1); + } catch (InterruptedException ignore) { + // do nothing + } + } + } + + } + + /** + * Test reconfiguring a Reconfigurable. + */ + @Test + public void testReconfigure() { + ReconfigurableDummy dummy = new ReconfigurableDummy(conf1); + + assertTrue(dummy.getConf().get(PROP1).equals(VAL1)); + assertTrue(dummy.getConf().get(PROP2).equals(VAL1)); + assertTrue(dummy.getConf().get(PROP3).equals(VAL1)); + assertTrue(dummy.getConf().get(PROP4) == null); + assertTrue(dummy.getConf().get(PROP5) == null); + + assertTrue(dummy.isPropertyReconfigurable(PROP1)); + assertTrue(dummy.isPropertyReconfigurable(PROP2)); + assertFalse(dummy.isPropertyReconfigurable(PROP3)); + assertTrue(dummy.isPropertyReconfigurable(PROP4)); + assertFalse(dummy.isPropertyReconfigurable(PROP5)); + + // change something to the same value as before + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP1, VAL1); + assertTrue(dummy.getConf().get(PROP1).equals(VAL1)); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertFalse(exceptionCaught); + } + + // change something to null + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP1, null); + assertTrue(dummy.getConf().get(PROP1) == null); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertFalse(exceptionCaught); + } + + // change something to a different value than before + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP1, VAL2); + assertTrue(dummy.getConf().get(PROP1).equals(VAL2)); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertFalse(exceptionCaught); + } + + // set unset property to null + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP4, null); + assertTrue(dummy.getConf().get(PROP4) == null); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertFalse(exceptionCaught); + } + + // set unset property + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP4, VAL1); + assertTrue(dummy.getConf().get(PROP4).equals(VAL1)); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertFalse(exceptionCaught); + } + + // try to set unset property to null (not reconfigurable) + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP5, null); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertTrue(exceptionCaught); + } + + // try to set unset property to value (not reconfigurable) + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP5, VAL1); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertTrue(exceptionCaught); + } + + // try to change property to value (not reconfigurable) + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP3, VAL2); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertTrue(exceptionCaught); + } + + // try to change property to null (not reconfigurable) + { + boolean exceptionCaught = false; + try { + dummy.reconfigureProperty(PROP3, null); + } catch (ReconfigurationException e) { + exceptionCaught = true; + } + assertTrue(exceptionCaught); + } + } + + /** + * Test whether configuration changes are visible in another thread. + */ + @Test + public void testThread() throws ReconfigurationException { + ReconfigurableDummy dummy = new ReconfigurableDummy(conf1); + assertTrue(dummy.getConf().get(PROP1).equals(VAL1)); + Thread dummyThread = new Thread(dummy); + dummyThread.start(); + try { + Thread.sleep(500); + } catch (InterruptedException ignore) { + // do nothing + } + dummy.reconfigureProperty(PROP1, VAL2); + + long endWait = System.currentTimeMillis() + 2000; + while (dummyThread.isAlive() && System.currentTimeMillis() < endWait) { + try { + Thread.sleep(50); + } catch (InterruptedException ignore) { + // do nothing + } + } + + assertFalse(dummyThread.isAlive()); + dummy.running = false; + try { + dummyThread.join(); + } catch (InterruptedException ignore) { + // do nothing + } + assertTrue(dummy.getConf().get(PROP1).equals(VAL2)); + + } + +} \ No newline at end of file
a2c979388250683f8dc91c18db45d3a0a5b3b3e3
Vala
Add support for [Deprecated] attribute Fixes bug 614712.
a
https://github.com/GNOME/vala/
diff --git a/vala/valaclass.vala b/vala/valaclass.vala index eef5075b29..54916c592a 100644 --- a/vala/valaclass.vala +++ b/vala/valaclass.vala @@ -673,6 +673,8 @@ public class Vala.Class : ObjectTypeSymbol { is_compact = true; } else if (a.name == "Immutable") { is_immutable = true; + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } @@ -1115,6 +1117,7 @@ public class Vala.Class : ObjectTypeSymbol { } if (sym is Method) { // method is used as interface implementation, so it is not unused + sym.check_deprecated (source_reference); sym.used = true; } else { error = true; @@ -1134,6 +1137,7 @@ public class Vala.Class : ObjectTypeSymbol { } if (sym is Property) { // property is used as interface implementation, so it is not unused + sym.check_deprecated (source_reference); sym.used = true; } else { error = true; diff --git a/vala/valacodewriter.vala b/vala/valacodewriter.vala index a2bb0f9912..2fc5f8261d 100644 --- a/vala/valacodewriter.vala +++ b/vala/valacodewriter.vala @@ -160,6 +160,30 @@ public class Vala.CodeWriter : CodeVisitor { return cheaders; } + private void emit_deprecated_attribute (Symbol symbol) { + if (symbol.deprecated) { + write_indent (); + write_string ("[Deprecated"); + var since = symbol.deprecated_since; + var replacement = symbol.replacement; + + if (since != null || replacement != null) { + write_string (" ("); + if (since != null) { + write_string ("since = \"%s\"".printf (since)); + } + if (since != null && replacement != null) { + write_string (", "); + } + if (replacement != null) { + write_string ("replacement = \"%s\"".printf (since)); + } + write_string (")"); + } + write_string ("]"); + } + } + public override void visit_class (Class cl) { if (cl.external_package) { return; @@ -181,6 +205,8 @@ public class Vala.CodeWriter : CodeVisitor { write_newline (); } + emit_deprecated_attribute (cl); + write_indent (); write_string ("[CCode ("); @@ -330,6 +356,8 @@ public class Vala.CodeWriter : CodeVisitor { write_newline (); } + emit_deprecated_attribute (st); + write_indent (); write_string ("[CCode ("); @@ -411,6 +439,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (iface); + write_indent (); write_string ("[CCode (cheader_filename = \"%s\"".printf (get_cheaders(iface))); @@ -485,6 +515,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (en); + write_indent (); write_string ("[CCode (cprefix = \"%s\", ".printf (en.get_cprefix ())); @@ -554,6 +586,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (edomain); + write_indent (); write_string ("[CCode (cprefix = \"%s\", cheader_filename = \"%s\")]".printf (edomain.get_cprefix (), get_cheaders(edomain))); @@ -588,6 +622,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (c); + bool custom_cname = (c.get_cname () != c.get_default_cname ()); bool custom_cheaders = (c.parent_symbol is Namespace); if (custom_cname || custom_cheaders) { @@ -630,6 +666,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (f); + bool custom_cname = (f.get_cname () != f.get_default_cname ()); bool custom_ctype = (f.get_ctype () != null); bool custom_cheaders = (f.parent_symbol is Namespace); @@ -826,6 +864,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (cb); + write_indent (); write_string ("[CCode (cheader_filename = \"%s\"".printf (get_cheaders(cb))); @@ -897,6 +937,8 @@ public class Vala.CodeWriter : CodeVisitor { write_string ("[ScanfFormat]"); } + emit_deprecated_attribute (m); + var ccode_params = new StringBuilder (); var separator = ""; @@ -1022,6 +1064,8 @@ public class Vala.CodeWriter : CodeVisitor { return; } + emit_deprecated_attribute (prop); + if (prop.no_accessor_method) { write_indent (); write_string ("[NoAccessorMethod]"); @@ -1089,6 +1133,8 @@ public class Vala.CodeWriter : CodeVisitor { write_indent (); write_string ("[HasEmitter]"); } + + emit_deprecated_attribute (sig); write_indent (); write_accessibility (sig); diff --git a/vala/valaconstant.vala b/vala/valaconstant.vala index 6c0ee9e26f..b9d29a2b98 100644 --- a/vala/valaconstant.vala +++ b/vala/valaconstant.vala @@ -153,6 +153,8 @@ public class Vala.Constant : Member, Lockable { foreach (Attribute a in attributes) { if (a.name == "CCode") { process_ccode_attribute (a); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valadelegate.vala b/vala/valadelegate.vala index 09538e98a8..6952409953 100644 --- a/vala/valadelegate.vala +++ b/vala/valadelegate.vala @@ -276,6 +276,8 @@ public class Vala.Delegate : TypeSymbol { foreach (Attribute a in attributes) { if (a.name == "CCode") { process_ccode_attribute (a); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valaenum.vala b/vala/valaenum.vala index ef8a07792f..85bd3b4d18 100644 --- a/vala/valaenum.vala +++ b/vala/valaenum.vala @@ -244,6 +244,8 @@ public class Vala.Enum : TypeSymbol { process_ccode_attribute (a); } else if (a.name == "Flags") { is_flags = true; + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valaenumvalue.vala b/vala/valaenumvalue.vala index eaade92c15..47f11ee197 100644 --- a/vala/valaenumvalue.vala +++ b/vala/valaenumvalue.vala @@ -102,6 +102,8 @@ public class Vala.EnumValue : Symbol { foreach (Attribute a in attributes) { if (a.name == "CCode" && a.has_argument("cname")) { cname = a.get_string ("cname"); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valaerrordomain.vala b/vala/valaerrordomain.vala index dbc6b4567a..24b8072147 100644 --- a/vala/valaerrordomain.vala +++ b/vala/valaerrordomain.vala @@ -189,6 +189,8 @@ public class Vala.ErrorDomain : TypeSymbol { foreach (Attribute a in attributes) { if (a.name == "CCode") { process_ccode_attribute (a); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valafield.vala b/vala/valafield.vala index b038c729f0..ed7e091bf3 100644 --- a/vala/valafield.vala +++ b/vala/valafield.vala @@ -249,6 +249,8 @@ public class Vala.Field : Member, Lockable { foreach (Attribute a in attributes) { if (a.name == "CCode") { process_ccode_attribute (a); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valainterface.vala b/vala/valainterface.vala index e88d44fc66..02c63a8460 100644 --- a/vala/valainterface.vala +++ b/vala/valainterface.vala @@ -482,6 +482,8 @@ public class Vala.Interface : ObjectTypeSymbol { foreach (Attribute a in attributes) { if (a.name == "CCode") { process_ccode_attribute (a); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valalambdaexpression.vala b/vala/valalambdaexpression.vala index 25e54b0f6b..4bc618ff13 100644 --- a/vala/valalambdaexpression.vala +++ b/vala/valalambdaexpression.vala @@ -136,6 +136,7 @@ public class Vala.LambdaExpression : Expression { method = new Method (get_lambda_name (analyzer), cb.return_type, source_reference); // track usage for flow analyzer method.used = true; + method.check_deprecated (source_reference); if (!cb.has_target || !analyzer.is_in_instance_method ()) { method.binding = MemberBinding.STATIC; diff --git a/vala/valamemberaccess.vala b/vala/valamemberaccess.vala index c566995acc..6d12220252 100644 --- a/vala/valamemberaccess.vala +++ b/vala/valamemberaccess.vala @@ -640,6 +640,7 @@ public class Vala.MemberAccess : Expression { } member.used = true; + member.check_deprecated (source_reference); if (access == SymbolAccessibility.PROTECTED) { var target_type = (TypeSymbol) member.parent_symbol; diff --git a/vala/valamethod.vala b/vala/valamethod.vala index 61a5aa1689..60995c81e9 100644 --- a/vala/valamethod.vala +++ b/vala/valamethod.vala @@ -498,6 +498,8 @@ public class Vala.Method : Member { } else if (a.name == "NoArrayLength") { Report.warning (source_reference, "NoArrayLength attribute is deprecated, use [CCode (array_length = false)] instead."); no_array_length = true; + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valaobjectcreationexpression.vala b/vala/valaobjectcreationexpression.vala index 2c8ad17b3a..ab726e79fa 100644 --- a/vala/valaobjectcreationexpression.vala +++ b/vala/valaobjectcreationexpression.vala @@ -261,6 +261,7 @@ public class Vala.ObjectCreationExpression : Expression { // track usage for flow analyzer symbol_reference.used = true; + symbol_reference.check_deprecated (source_reference); } if (symbol_reference != null && symbol_reference.access == SymbolAccessibility.PRIVATE) { diff --git a/vala/valaproperty.vala b/vala/valaproperty.vala index ac15b8e854..ea9d2e1231 100644 --- a/vala/valaproperty.vala +++ b/vala/valaproperty.vala @@ -294,6 +294,8 @@ public class Vala.Property : Member, Lockable { if (a.has_argument ("blurb")) { blurb = a.get_string ("blurb"); } + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valasignal.vala b/vala/valasignal.vala index f4859d5cb5..89bca45c97 100644 --- a/vala/valasignal.vala +++ b/vala/valasignal.vala @@ -246,9 +246,10 @@ public class Vala.Signal : Member, Lockable { foreach (Attribute a in attributes) { if (a.name == "HasEmitter") { has_emitter = true; - } - if (a.name == "Signal") { + } else if (a.name == "Signal") { process_signal_attribute (a); + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valastruct.vala b/vala/valastruct.vala index b7af767fc9..bcfa13e186 100644 --- a/vala/valastruct.vala +++ b/vala/valastruct.vala @@ -497,6 +497,8 @@ public class Vala.Struct : TypeSymbol { process_floating_type_attribute (a); } else if (a.name == "Immutable") { is_immutable = true; + } else if (a.name == "Deprecated") { + process_deprecated_attribute (a); } } } diff --git a/vala/valasymbol.vala b/vala/valasymbol.vala index 231eacea67..8cb6e43486 100644 --- a/vala/valasymbol.vala +++ b/vala/valasymbol.vala @@ -67,6 +67,21 @@ public abstract class Vala.Symbol : CodeNode { */ public bool active { get; set; default = true; } + /** + * Specifies whether this symbol has been deprecated. + */ + public bool deprecated { get; set; default = false; } + + /** + * Specifies what version this symbol has been deprecated since. + */ + public string? deprecated_since { get; set; default = null; } + + /** + * Specifies the replacement if this symbol has been deprecated. + */ + public string? replacement { get; set; default = null; } + /** * Specifies whether this symbol has been accessed. */ @@ -365,6 +380,39 @@ public abstract class Vala.Symbol : CodeNode { return isclass; } + + /** + * Process a [Deprecated] attribute + */ + public virtual void process_deprecated_attribute (Attribute attr) { + if (attr.name != "Deprecated") { + return; + } + + deprecated = true; + + if (attr.has_argument ("since")) { + deprecated_since = attr.get_string ("since"); + } + if (attr.has_argument ("replacement")) { + replacement = attr.get_string ("replacement"); + } + } + + /** + * Check to see if the symbol has been deprecated, and emit a warning + * if it has. + */ + public bool check_deprecated (SourceReference? source_ref = null) { + if (deprecated) { + if (!CodeContext.get ().deprecated) { + Report.warning (source_ref, "%s %s%s".printf (get_full_name (), (deprecated_since == null) ? "is deprecated" : "has been deprecated since %s".printf (deprecated_since), (replacement == null) ? "" : ". Use %s".printf (replacement))); + } + return true; + } else { + return false; + } + } } public enum Vala.SymbolAccessibility {
f21a1c54157482d6b8758d8daee5b55a1d410cd0
evllabs$jgaap
Made following UI changes: - Added notes functionality - Added tabbed results window - Added distance function capibilities - Added review panel (still work in progress) - Added double click on item windows to add and remove items git-svn-id: https://www.evllabs.com/svn/jgaap/trunk@160 bcaee279-2e94-4b2e-be96-a1d7c6f3fc26
p
https://github.com/evllabs/jgaap
diff --git a/src/com/jgaap/classifiers/FrequencyCentroidDriver.java b/src/com/jgaap/classifiers/FrequencyCentroidDriver.java index b23dece2d..efb0ba9e8 100644 --- a/src/com/jgaap/classifiers/FrequencyCentroidDriver.java +++ b/src/com/jgaap/classifiers/FrequencyCentroidDriver.java @@ -32,7 +32,7 @@ public String tooltipText() { } public boolean showInGUI() { - return false; + return true; } @SuppressWarnings("unchecked") diff --git a/src/com/jgaap/classifiers/NearestNeighborDriver.java b/src/com/jgaap/classifiers/NearestNeighborDriver.java index cdf3677c2..24aadeaf9 100644 --- a/src/com/jgaap/classifiers/NearestNeighborDriver.java +++ b/src/com/jgaap/classifiers/NearestNeighborDriver.java @@ -28,7 +28,7 @@ public String tooltipText() { } public boolean showInGUI() { - return false; + return true; } @Override diff --git a/src/com/jgaap/ui/JGAAP_UI_MainForm.form b/src/com/jgaap/ui/JGAAP_UI_MainForm.form index fffcd0437..019d1e8eb 100644 --- a/src/com/jgaap/ui/JGAAP_UI_MainForm.form +++ b/src/com/jgaap/ui/JGAAP_UI_MainForm.form @@ -198,6 +198,78 @@ </MenuItem> </SubComponents> </Menu> + <Menu class="javax.swing.JMenu" name="jMenu2"> + <Properties> + <Property name="text" type="java.lang.String" value="AAAC Problems"/> + </Properties> + <SubComponents> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem1"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem A"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem2"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem B"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem3"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem C"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem4"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem D"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem5"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem E"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem6"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem F"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem7"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem G"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem8"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem H"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem9"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem I"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem10"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem J"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem11"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem K"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem12"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem L"/> + </Properties> + </MenuItem> + <MenuItem class="javax.swing.JMenuItem" name="jMenuItem13"> + <Properties> + <Property name="text" type="java.lang.String" value="Problem M"/> + </Properties> + </MenuItem> + </SubComponents> + </Menu> <Menu class="javax.swing.JMenu" name="jMenu3"> <Properties> <Property name="text" type="java.lang.String" value="Options"/> @@ -264,28 +336,31 @@ <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> - <Group type="102" max="-2" attributes="0"> - <Group type="103" groupAlignment="0" max="-2" attributes="0"> - <Group type="102" attributes="0"> - <EmptySpace min="-2" pref="386" max="-2" attributes="0"/> - <Component id="Process_Button" min="-2" max="-2" attributes="0"/> - </Group> - <Group type="102" alignment="0" attributes="0"> - <EmptySpace min="-2" max="-2" attributes="0"/> - <Component id="JGAAP_TabbedPane" min="-2" pref="849" max="-2" attributes="0"/> + <Group type="102" alignment="1" attributes="0"> + <EmptySpace max="-2" attributes="0"/> + <Group type="103" groupAlignment="1" attributes="0"> + <Component id="JGAAP_TabbedPane" alignment="1" pref="849" max="32767" attributes="0"/> + <Group type="102" alignment="1" attributes="0"> + <Component id="Review_Button" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="Next_Button" min="-2" max="-2" attributes="0"/> </Group> </Group> - <EmptySpace min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> - <Group type="102" alignment="1" attributes="0"> - <Component id="JGAAP_TabbedPane" pref="575" max="32767" attributes="0"/> + <Group type="102" alignment="0" attributes="0"> + <EmptySpace max="-2" attributes="0"/> + <Component id="JGAAP_TabbedPane" min="-2" pref="529" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> - <Component id="Process_Button" min="-2" max="-2" attributes="0"/> - <EmptySpace min="-2" max="-2" attributes="0"/> + <Group type="103" groupAlignment="3" attributes="0"> + <Component id="Next_Button" alignment="3" min="-2" max="-2" attributes="0"/> + <Component id="Review_Button" alignment="3" min="-2" max="-2" attributes="0"/> + </Group> + <EmptySpace max="32767" attributes="0"/> </Group> </Group> </DimensionLayout> @@ -371,7 +446,7 @@ <EmptySpace type="unrelated" max="-2" attributes="0"/> <Component id="jLabel2" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> - <Component id="jScrollPane2" pref="237" max="32767" attributes="0"/> + <Component id="jScrollPane2" pref="191" max="32767" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="DocumentsPanel_RemoveAuthorButton" alignment="3" min="-2" max="-2" attributes="0"/> @@ -485,6 +560,9 @@ <Properties> <Property name="label" type="java.lang.String" value="Notes"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="DocumentsPanel_NotesButtonActionPerformed"/> + </Events> </Component> <Component class="javax.swing.JLabel" name="jLabel10"> <Properties> @@ -590,7 +668,7 @@ </Group> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> - <Component id="jScrollPane20" pref="350" max="32767" attributes="0"/> + <Component id="jScrollPane20" pref="304" max="32767" attributes="0"/> <Group type="102" attributes="0"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" attributes="0"> @@ -604,8 +682,8 @@ </Group> <Group type="102" alignment="1" attributes="0"> <Group type="103" groupAlignment="1" attributes="0"> - <Component id="jScrollPane13" pref="263" max="32767" attributes="1"/> - <Component id="jScrollPane12" alignment="1" pref="263" max="32767" attributes="1"/> + <Component id="jScrollPane13" pref="217" max="32767" attributes="1"/> + <Component id="jScrollPane12" alignment="1" pref="217" max="32767" attributes="1"/> </Group> <EmptySpace max="-2" attributes="0"/> <Component id="CanonicizersPanel_SetToDocumentButton" min="-2" max="-2" attributes="0"/> @@ -645,7 +723,7 @@ <SubComponents> <Component class="javax.swing.JButton" name="CanonicizersPanel_RemoveCanonicizerButton"> <Properties> - <Property name="text" type="java.lang.String" value="-"/> + <Property name="text" type="java.lang.String" value="&lt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="CanonicizersPanel_RemoveCanonicizerButtonActionPerformed"/> @@ -663,6 +741,9 @@ <Properties> <Property name="label" type="java.lang.String" value="Notes"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="CanonicizersPanel_NotesButtonActionPerformed"/> + </Events> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane11"> <AuxValues> @@ -683,7 +764,7 @@ </Container> <Component class="javax.swing.JButton" name="CanonicizersPanel_AddCanonicizerButton"> <Properties> - <Property name="text" type="java.lang.String" value="+"/> + <Property name="text" type="java.lang.String" value="&gt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="CanonicizersPanel_AddCanonicizerButtonActionPerformed"/> @@ -823,7 +904,7 @@ <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Microsoft Sans Serif" size="24" style="0"/> </Property> - <Property name="text" type="java.lang.String" value="Selected C"/> + <Property name="text" type="java.lang.String" value="Selected"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel30"> @@ -920,8 +1001,8 @@ <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> <Component id="EventSetsPanel_ParametersPanel" alignment="0" max="32767" attributes="0"/> - <Component id="jScrollPane10" pref="350" max="32767" attributes="0"/> - <Component id="jScrollPane9" alignment="0" pref="350" max="32767" attributes="0"/> + <Component id="jScrollPane10" pref="304" max="32767" attributes="0"/> + <Component id="jScrollPane9" alignment="0" pref="304" max="32767" attributes="0"/> <Group type="102" alignment="0" attributes="0"> <Component id="EventSetsPanel_AddEventSetButton" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> @@ -946,6 +1027,9 @@ <Properties> <Property name="label" type="java.lang.String" value="Notes"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="EventSetsPanel_NotesButtonActionPerformed"/> + </Events> </Component> <Component class="javax.swing.JLabel" name="jLabel6"> <Properties> @@ -976,7 +1060,7 @@ <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Microsoft Sans Serif" size="24" style="0"/> </Property> - <Property name="text" type="java.lang.String" value="Selected ED"/> + <Property name="text" type="java.lang.String" value="Selected"/> </Properties> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane9"> @@ -1038,7 +1122,7 @@ </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> - <EmptySpace min="0" pref="346" max="32767" attributes="0"/> + <EmptySpace min="0" pref="300" max="32767" attributes="0"/> </Group> </DimensionLayout> </Layout> @@ -1062,7 +1146,7 @@ </Container> <Component class="javax.swing.JButton" name="EventSetsPanel_AddEventSetButton"> <Properties> - <Property name="label" type="java.lang.String" value="+"/> + <Property name="text" type="java.lang.String" value="&gt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="EventSetsPanel_AddEventSetButtonActionPerformed"/> @@ -1070,7 +1154,7 @@ </Component> <Component class="javax.swing.JButton" name="EventSetsPanel_RemoveEventSetButton"> <Properties> - <Property name="label" type="java.lang.String" value="-"/> + <Property name="text" type="java.lang.String" value="&lt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="EventSetsPanel_RemoveEventSetButtonActionPerformed"/> @@ -1157,9 +1241,9 @@ </Group> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> - <Component id="jScrollPane14" pref="350" max="32767" attributes="0"/> + <Component id="jScrollPane14" pref="304" max="32767" attributes="0"/> <Component id="EventCullingPanel_ParametersPanel" max="32767" attributes="1"/> - <Component id="jScrollPane15" alignment="0" pref="350" max="32767" attributes="0"/> + <Component id="jScrollPane15" alignment="0" pref="304" max="32767" attributes="0"/> <Group type="102" alignment="0" attributes="0"> <Component id="EventCullingPanel_AddEventCullingButton" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> @@ -1202,13 +1286,16 @@ <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Microsoft Sans Serif" size="24" style="0"/> </Property> - <Property name="text" type="java.lang.String" value="Selected EC"/> + <Property name="text" type="java.lang.String" value="Selected"/> </Properties> </Component> <Component class="javax.swing.JButton" name="EventCullingPanel_NotesButton"> <Properties> <Property name="label" type="java.lang.String" value="Notes"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="EventCullingPanel_NotesButtonActionPerformed"/> + </Events> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane14"> <AuxValues> @@ -1233,7 +1320,7 @@ </Container> <Component class="javax.swing.JButton" name="EventCullingPanel_AddEventCullingButton"> <Properties> - <Property name="label" type="java.lang.String" value="+"/> + <Property name="text" type="java.lang.String" value="&gt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="EventCullingPanel_AddEventCullingButtonActionPerformed"/> @@ -1241,7 +1328,7 @@ </Component> <Component class="javax.swing.JButton" name="EventCullingPanel_RemoveEventCullingButton"> <Properties> - <Property name="label" type="java.lang.String" value="-"/> + <Property name="text" type="java.lang.String" value="&lt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="EventCullingPanel_RemoveEventCullingButtonActionPerformed"/> @@ -1280,7 +1367,7 @@ </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> - <EmptySpace min="0" pref="346" max="32767" attributes="0"/> + <EmptySpace min="0" pref="300" max="32767" attributes="0"/> </Group> </DimensionLayout> </Layout> @@ -1348,19 +1435,23 @@ <Group type="102" alignment="1" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="1" attributes="0"> - <Component id="jScrollPane19" alignment="0" pref="824" max="32767" attributes="0"/> - <Component id="jLabel28" alignment="0" min="-2" max="-2" attributes="0"/> <Group type="102" alignment="1" attributes="0"> - <Group type="103" groupAlignment="0" max="-2" attributes="0"> - <Component id="jScrollPane18" min="0" pref="0" max="32767" attributes="1"/> - <Component id="jLabel20" alignment="0" max="32767" attributes="1"/> - </Group> - <EmptySpace max="-2" attributes="0"/> - <Group type="103" groupAlignment="1" max="-2" attributes="0"> - <Component id="AnalysisMethodPanel_RemoveAnalysisMethodsButton" alignment="0" max="32767" attributes="1"/> - <Component id="AnalysisMethodPanel_AddAllAnalysisMethodsButton" alignment="0" max="32767" attributes="1"/> - <Component id="AnalysisMethodPanel_AddAnalysisMethodButton" alignment="0" max="32767" attributes="1"/> - <Component id="AnalysisMethodPanel_RemoveAllAnalysisMethodsButton" alignment="1" min="-2" pref="64" max="-2" attributes="1"/> + <Group type="103" groupAlignment="0" attributes="0"> + <Component id="jLabel35" alignment="0" pref="257" max="32767" attributes="1"/> + <Group type="102" alignment="1" attributes="0"> + <Group type="103" groupAlignment="1" attributes="0"> + <Component id="jScrollPane22" alignment="0" pref="187" max="32767" attributes="1"/> + <Component id="jScrollPane18" alignment="0" min="0" pref="0" max="32767" attributes="1"/> + <Component id="jLabel20" alignment="0" max="32767" attributes="1"/> + </Group> + <EmptySpace max="-2" attributes="0"/> + <Group type="103" groupAlignment="1" max="-2" attributes="0"> + <Component id="AnalysisMethodPanel_RemoveAnalysisMethodsButton" alignment="0" max="32767" attributes="1"/> + <Component id="AnalysisMethodPanel_AddAllAnalysisMethodsButton" alignment="0" max="32767" attributes="1"/> + <Component id="AnalysisMethodPanel_AddAnalysisMethodButton" alignment="0" max="32767" attributes="1"/> + <Component id="AnalysisMethodPanel_RemoveAllAnalysisMethodsButton" alignment="1" min="-2" pref="64" max="-2" attributes="1"/> + </Group> + </Group> </Group> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> @@ -1369,12 +1460,25 @@ </Group> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> + <Component id="AnalysisMethodPanel_DFParametersPanel" max="32767" attributes="0"/> + <Component id="AnalysisMethodPanel_AMParametersPanel" max="32767" attributes="0"/> <Group type="102" attributes="0"> <Component id="jLabel21" min="-2" max="-2" attributes="0"/> - <EmptySpace pref="174" max="32767" attributes="0"/> + <EmptySpace pref="133" max="32767" attributes="0"/> <Component id="AnalysisMethodPanel_NotesButton" min="-2" max="-2" attributes="0"/> </Group> - <Component id="AnalysisMethodPanel_ParametersPanel" max="32767" attributes="0"/> + <Component id="jLabel37" alignment="0" min="-2" max="-2" attributes="0"/> + </Group> + </Group> + <Group type="102" alignment="0" attributes="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <Component id="jScrollPane19" min="-2" pref="405" max="-2" attributes="0"/> + <Component id="jLabel36" alignment="0" min="-2" max="-2" attributes="0"/> + </Group> + <EmptySpace max="-2" attributes="0"/> + <Group type="103" groupAlignment="0" attributes="0"> + <Component id="jLabel28" alignment="0" min="-2" max="-2" attributes="0"/> + <Component id="jScrollPane23" alignment="0" pref="413" max="32767" attributes="0"/> </Group> </Group> </Group> @@ -1394,24 +1498,43 @@ </Group> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> - <Component id="jScrollPane17" pref="347" max="32767" attributes="0"/> - <Component id="AnalysisMethodPanel_ParametersPanel" max="32767" attributes="0"/> - <Component id="jScrollPane18" pref="347" max="32767" attributes="0"/> + <Component id="jScrollPane17" pref="301" max="32767" attributes="0"/> <Group type="102" alignment="0" attributes="0"> - <Component id="AnalysisMethodPanel_AddAnalysisMethodButton" min="-2" max="-2" attributes="0"/> + <Component id="AnalysisMethodPanel_AMParametersPanel" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="jLabel37" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> - <Component id="AnalysisMethodPanel_RemoveAnalysisMethodsButton" min="-2" max="-2" attributes="0"/> + <Component id="AnalysisMethodPanel_DFParametersPanel" max="32767" attributes="0"/> + </Group> + <Group type="102" attributes="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" attributes="0"> + <Component id="AnalysisMethodPanel_AddAnalysisMethodButton" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="AnalysisMethodPanel_RemoveAnalysisMethodsButton" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="AnalysisMethodPanel_AddAllAnalysisMethodsButton" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="AnalysisMethodPanel_RemoveAllAnalysisMethodsButton" min="-2" max="-2" attributes="0"/> + </Group> + <Component id="jScrollPane18" min="-2" pref="129" max="-2" attributes="0"/> + </Group> <EmptySpace max="-2" attributes="0"/> - <Component id="AnalysisMethodPanel_AddAllAnalysisMethodsButton" min="-2" max="-2" attributes="0"/> + <Component id="jLabel35" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> - <Component id="AnalysisMethodPanel_RemoveAllAnalysisMethodsButton" min="-2" max="-2" attributes="0"/> - <EmptySpace min="156" pref="156" max="156" attributes="0"/> + <Component id="jScrollPane22" pref="132" max="32767" attributes="0"/> </Group> </Group> <EmptySpace max="-2" attributes="0"/> - <Component id="jLabel28" min="-2" max="-2" attributes="0"/> + <Group type="103" groupAlignment="3" attributes="0"> + <Component id="jLabel28" alignment="3" min="-2" max="-2" attributes="0"/> + <Component id="jLabel36" alignment="3" min="-2" max="-2" attributes="0"/> + </Group> <EmptySpace max="-2" attributes="0"/> - <Component id="jScrollPane19" min="-2" pref="101" max="-2" attributes="0"/> + <Group type="103" groupAlignment="1" attributes="0"> + <Component id="jScrollPane19" min="-2" pref="101" max="-2" attributes="0"/> + <Component id="jScrollPane23" min="-2" pref="101" max="-2" attributes="0"/> + </Group> <EmptySpace max="-2" attributes="0"/> </Group> </Group> @@ -1431,7 +1554,7 @@ <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Microsoft Sans Serif" size="24" style="0"/> </Property> - <Property name="text" type="java.lang.String" value="Parameters"/> + <Property name="text" type="java.lang.String" value="AM Parameters"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel22"> @@ -1439,13 +1562,16 @@ <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Microsoft Sans Serif" size="24" style="0"/> </Property> - <Property name="text" type="java.lang.String" value="Selected AM"/> + <Property name="text" type="java.lang.String" value="Selected"/> </Properties> </Component> <Component class="javax.swing.JButton" name="AnalysisMethodPanel_NotesButton"> <Properties> <Property name="label" type="java.lang.String" value="Notes"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="AnalysisMethodPanel_NotesButtonActionPerformed"/> + </Events> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane17"> <AuxValues> @@ -1470,7 +1596,7 @@ </Container> <Component class="javax.swing.JButton" name="AnalysisMethodPanel_AddAnalysisMethodButton"> <Properties> - <Property name="label" type="java.lang.String" value="+"/> + <Property name="text" type="java.lang.String" value="&gt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed"/> @@ -1478,7 +1604,7 @@ </Component> <Component class="javax.swing.JButton" name="AnalysisMethodPanel_RemoveAnalysisMethodsButton"> <Properties> - <Property name="label" type="java.lang.String" value="-"/> + <Property name="text" type="java.lang.String" value="&lt;"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed"/> @@ -1500,7 +1626,7 @@ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed"/> </Events> </Component> - <Container class="javax.swing.JPanel" name="AnalysisMethodPanel_ParametersPanel"> + <Container class="javax.swing.JPanel" name="AnalysisMethodPanel_AMParametersPanel"> <Properties> <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> <Border info="org.netbeans.modules.form.compat2.border.EtchedBorderInfo"> @@ -1517,7 +1643,7 @@ </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> - <EmptySpace min="0" pref="343" max="32767" attributes="0"/> + <EmptySpace min="0" pref="125" max="32767" attributes="0"/> </Group> </DimensionLayout> </Layout> @@ -1548,7 +1674,7 @@ <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Microsoft Sans Serif" size="24" style="0"/> </Property> - <Property name="text" type="java.lang.String" value="Analysis Method Description"/> + <Property name="text" type="java.lang.String" value="Distance Function Description"/> </Properties> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane19"> @@ -1568,16 +1694,148 @@ </Component> </SubComponents> </Container> + <Container class="javax.swing.JScrollPane" name="jScrollPane22"> + <AuxValues> + <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> + <SubComponents> + <Component class="javax.swing.JList" name="AnalysisMethodPanel_DistanceFunctionsListBox"> + <Properties> + <Property name="model" type="javax.swing.ListModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor"> + <Connection code="DistanceFunctionsListBox_Model" type="code"/> + </Property> + <Property name="selectionMode" type="int" value="0"/> + </Properties> + <Events> + <EventHandler event="mouseClicked" listener="java.awt.event.MouseListener" parameters="java.awt.event.MouseEvent" handler="AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked"/> + <EventHandler event="mouseMoved" listener="java.awt.event.MouseMotionListener" parameters="java.awt.event.MouseEvent" handler="AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved"/> + </Events> + </Component> + </SubComponents> + </Container> + <Component class="javax.swing.JLabel" name="jLabel35"> + <Properties> + <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> + <Font name="Microsoft Sans Serif" size="24" style="0"/> + </Property> + <Property name="text" type="java.lang.String" value="Distance Functions"/> + </Properties> + </Component> + <Container class="javax.swing.JScrollPane" name="jScrollPane23"> + <AuxValues> + <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/> + </AuxValues> + + <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> + <SubComponents> + <Component class="javax.swing.JTextArea" name="AnalysisMethodPanel_DistanceFunctionDescriptionTextBox"> + <Properties> + <Property name="columns" type="int" value="20"/> + <Property name="lineWrap" type="boolean" value="true"/> + <Property name="rows" type="int" value="5"/> + <Property name="wrapStyleWord" type="boolean" value="true"/> + </Properties> + </Component> + </SubComponents> + </Container> + <Component class="javax.swing.JLabel" name="jLabel36"> + <Properties> + <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> + <Font name="Microsoft Sans Serif" size="24" style="0"/> + </Property> + <Property name="text" type="java.lang.String" value="Analysis Method Description"/> + </Properties> + </Component> + <Container class="javax.swing.JPanel" name="AnalysisMethodPanel_DFParametersPanel"> + <Properties> + <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> + <Border info="org.netbeans.modules.form.compat2.border.EtchedBorderInfo"> + <EtchetBorder/> + </Border> + </Property> + </Properties> + + <Layout> + <DimensionLayout dim="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <EmptySpace min="0" pref="355" max="32767" attributes="0"/> + </Group> + </DimensionLayout> + <DimensionLayout dim="1"> + <Group type="103" groupAlignment="0" attributes="0"> + <EmptySpace min="0" pref="128" max="32767" attributes="0"/> + </Group> + </DimensionLayout> + </Layout> + </Container> + <Component class="javax.swing.JLabel" name="jLabel37"> + <Properties> + <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> + <Font name="Microsoft Sans Serif" size="24" style="0"/> + </Property> + <Property name="text" type="java.lang.String" value="DF Parameters"/> + </Properties> + </Component> + </SubComponents> + </Container> + <Container class="javax.swing.JPanel" name="JGAAP_ReviewPanel"> + <Constraints> + <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout$JTabbedPaneConstraintsDescription"> + <JTabbedPaneConstraints tabName="Review &amp; Process"> + <Property name="tabTitle" type="java.lang.String" value="Review &amp; Process"/> + </JTabbedPaneConstraints> + </Constraint> + </Constraints> + + <Layout> + <DimensionLayout dim="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="0" attributes="0"> + <EmptySpace min="-2" pref="368" max="-2" attributes="0"/> + <Component id="Process_Button" min="-2" max="-2" attributes="0"/> + <EmptySpace pref="407" max="32767" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + <DimensionLayout dim="1"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="1" attributes="0"> + <EmptySpace pref="467" max="32767" attributes="0"/> + <Component id="Process_Button" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + </Layout> + <SubComponents> + <Component class="javax.swing.JButton" name="Process_Button"> + <Properties> + <Property name="label" type="java.lang.String" value="Process"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="Process_ButtonActionPerformed"/> + </Events> + </Component> </SubComponents> </Container> </SubComponents> </Container> - <Component class="javax.swing.JButton" name="Process_Button"> + <Component class="javax.swing.JButton" name="Next_Button"> + <Properties> + <Property name="text" type="java.lang.String" value="Next &gt;"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="Next_ButtonActionPerformed"/> + </Events> + </Component> + <Component class="javax.swing.JButton" name="Review_Button"> <Properties> - <Property name="label" type="java.lang.String" value="Process"/> + <Property name="text" type="java.lang.String" value="Finish &amp; Review"/> </Properties> <Events> - <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="Process_ButtonActionPerformed"/> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="Review_ButtonActionPerformed"/> </Events> </Component> </SubComponents> diff --git a/src/com/jgaap/ui/JGAAP_UI_MainForm.java b/src/com/jgaap/ui/JGAAP_UI_MainForm.java index e235d679a..4b8250bb9 100644 --- a/src/com/jgaap/ui/JGAAP_UI_MainForm.java +++ b/src/com/jgaap/ui/JGAAP_UI_MainForm.java @@ -42,6 +42,11 @@ public class JGAAP_UI_MainForm extends javax.swing.JFrame { private static final long serialVersionUID = 1L; + JGAAP_UI_NotesDialog NotesPage = new JGAAP_UI_NotesDialog(JGAAP_UI_MainForm.this, true); + JGAAP_UI_ResultsDialog ResultsPage = new JGAAP_UI_ResultsDialog(JGAAP_UI_MainForm.this, false); + String[] Notes = new String [5]; + + DefaultListModel AnalysisMethodListBox_Model = new DefaultListModel(); DefaultListModel SelectedAnalysisMethodListBox_Model = new DefaultListModel(); DefaultListModel CanonicizerListBox_Model = new DefaultListModel(); @@ -50,6 +55,7 @@ public class JGAAP_UI_MainForm extends javax.swing.JFrame { DefaultListModel SelectedEventCullingListBox_Model = new DefaultListModel(); DefaultListModel EventSetsListBox_Model = new DefaultListModel(); DefaultListModel SelectedEventSetsListBox_Model = new DefaultListModel(); + DefaultListModel DistanceFunctionsListBox_Model = new DefaultListModel(); DefaultComboBoxModel LanguageComboBox_Model = new DefaultComboBoxModel(); @@ -103,6 +109,7 @@ public JGAAP_UI_MainForm() { initComponents(); SanatizeMasterLists(); SetAnalysisMethodList(); + SetDistanceFunctionList(); SetCanonicizerList(); SetEventSetList(); SetEventCullingList(); @@ -221,13 +228,24 @@ private void initComponents() { AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton(); - AnalysisMethodPanel_ParametersPanel = new javax.swing.JPanel(); + AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel(); jScrollPane18 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList(); jLabel28 = new javax.swing.JLabel(); jScrollPane19 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea(); + jScrollPane22 = new javax.swing.JScrollPane(); + AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList(); + jLabel35 = new javax.swing.JLabel(); + jScrollPane23 = new javax.swing.JScrollPane(); + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea(); + jLabel36 = new javax.swing.JLabel(); + AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel(); + jLabel37 = new javax.swing.JLabel(); + JGAAP_ReviewPanel = new javax.swing.JPanel(); Process_Button = new javax.swing.JButton(); + Next_Button = new javax.swing.JButton(); + Review_Button = new javax.swing.JButton(); JGAAP_MenuBar = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); SaveProblemMenuItem = new javax.swing.JMenuItem(); @@ -235,6 +253,20 @@ private void initComponents() { jMenu4 = new javax.swing.JMenu(); BatchSaveMenuItem = new javax.swing.JMenuItem(); BatchLoadMenuItem = new javax.swing.JMenuItem(); + jMenu2 = new javax.swing.JMenu(); + jMenuItem1 = new javax.swing.JMenuItem(); + jMenuItem2 = new javax.swing.JMenuItem(); + jMenuItem3 = new javax.swing.JMenuItem(); + jMenuItem4 = new javax.swing.JMenuItem(); + jMenuItem5 = new javax.swing.JMenuItem(); + jMenuItem6 = new javax.swing.JMenuItem(); + jMenuItem7 = new javax.swing.JMenuItem(); + jMenuItem8 = new javax.swing.JMenuItem(); + jMenuItem9 = new javax.swing.JMenuItem(); + jMenuItem10 = new javax.swing.JMenuItem(); + jMenuItem11 = new javax.swing.JMenuItem(); + jMenuItem12 = new javax.swing.JMenuItem(); + jMenuItem13 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenu5 = new javax.swing.JMenu(); exitMenuItem = new javax.swing.JMenuItem(); @@ -394,6 +426,11 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { }); DocumentsPanel_NotesButton.setLabel("Notes"); + DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + DocumentsPanel_NotesButtonActionPerformed(evt); + } + }); jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel10.setText("Language"); @@ -458,7 +495,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE) + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveAuthorButton) @@ -469,7 +506,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel); - CanonicizersPanel_RemoveCanonicizerButton.setText("-"); + CanonicizersPanel_RemoveCanonicizerButton.setText("<"); CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt); @@ -480,6 +517,11 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { jLabel27.setText("Documents"); CanonicizersPanel_NotesButton.setLabel("Notes"); + CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CanonicizersPanel_NotesButtonActionPerformed(evt); + } + }); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true); @@ -487,7 +529,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true); jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox); - CanonicizersPanel_AddCanonicizerButton.setText("+"); + CanonicizersPanel_AddCanonicizerButton.setText(">"); CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt); @@ -570,7 +612,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { }); jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); - jLabel29.setText("Selected C"); + jLabel29.setText("Selected"); jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel30.setText("Canonicizers"); @@ -641,7 +683,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { .addComponent(CanonicizersPanel_NotesButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE) + .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() @@ -654,8 +696,8 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE) - .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)) + .addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE) + .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_SetToDocumentButton))) .addGap(6, 6, 6) @@ -683,6 +725,11 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel); EventSetsPanel_NotesButton.setLabel("Notes"); + EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + EventSetsPanel_NotesButtonActionPerformed(evt); + } + }); jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel6.setText("Event Driver"); @@ -694,7 +741,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { jLabel8.setText("Event Driver Description"); jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); - jLabel9.setText("Selected ED"); + jLabel9.setText("Selected"); EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model); EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); @@ -734,7 +781,7 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { ); EventSetsPanel_ParametersPanelLayout.setVerticalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGap(0, 346, Short.MAX_VALUE) + .addGap(0, 300, Short.MAX_VALUE) ); EventSetsPanel_EventSetDescriptionTextBox.setColumns(20); @@ -743,14 +790,14 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true); jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox); - EventSetsPanel_AddEventSetButton.setLabel("+"); + EventSetsPanel_AddEventSetButton.setText(">"); EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddEventSetButtonActionPerformed(evt); } }); - EventSetsPanel_RemoveEventSetButton.setLabel("-"); + EventSetsPanel_RemoveEventSetButton.setText("<"); EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveEventSetButtonActionPerformed(evt); @@ -817,8 +864,8 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE) - .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE) + .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) + .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(EventSetsPanel_AddEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) @@ -843,9 +890,14 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { jLabel16.setText("Parameters"); jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); - jLabel17.setText("Selected EC"); + jLabel17.setText("Selected"); EventCullingPanel_NotesButton.setLabel("Notes"); + EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + EventCullingPanel_NotesButtonActionPerformed(evt); + } + }); EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); @@ -861,14 +913,14 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { }); jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox); - EventCullingPanel_AddEventCullingButton.setLabel("+"); + EventCullingPanel_AddEventCullingButton.setText(">"); EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddEventCullingButtonActionPerformed(evt); } }); - EventCullingPanel_RemoveEventCullingButton.setLabel("-"); + EventCullingPanel_RemoveEventCullingButton.setText("<"); EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt); @@ -899,7 +951,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { ); EventCullingPanel_ParametersPanelLayout.setVerticalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGap(0, 346, Short.MAX_VALUE) + .addGap(0, 300, Short.MAX_VALUE) ); EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model); @@ -969,9 +1021,9 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { .addComponent(EventCullingPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE) + .addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE) + .addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(EventCullingPanel_AddEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) @@ -990,16 +1042,21 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel); - jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); + jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel20.setText("Analysis Methods"); jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); - jLabel21.setText("Parameters"); + jLabel21.setText("AM Parameters"); jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); - jLabel22.setText("Selected AM"); + jLabel22.setText("Selected"); AnalysisMethodPanel_NotesButton.setLabel("Notes"); + AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + AnalysisMethodPanel_NotesButtonActionPerformed(evt); + } + }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); @@ -1015,14 +1072,14 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { }); jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox); - AnalysisMethodPanel_AddAnalysisMethodButton.setLabel("+"); + AnalysisMethodPanel_AddAnalysisMethodButton.setText(">"); AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt); } }); - AnalysisMethodPanel_RemoveAnalysisMethodsButton.setLabel("-"); + AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("<"); AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt); @@ -1043,17 +1100,17 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { } }); - AnalysisMethodPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); + AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); - javax.swing.GroupLayout AnalysisMethodPanel_ParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_ParametersPanel); - AnalysisMethodPanel_ParametersPanel.setLayout(AnalysisMethodPanel_ParametersPanelLayout); - AnalysisMethodPanel_ParametersPanelLayout.setHorizontalGroup( - AnalysisMethodPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel); + AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout); + AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup( + AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); - AnalysisMethodPanel_ParametersPanelLayout.setVerticalGroup( - AnalysisMethodPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGap(0, 343, Short.MAX_VALUE) + AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup( + AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 125, Short.MAX_VALUE) ); AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model); @@ -1070,8 +1127,8 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { }); jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox); - jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); - jLabel28.setText("Analysis Method Description"); + jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N + jLabel28.setText("Distance Function Description"); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true); @@ -1079,6 +1136,48 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true); jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox); + AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model); + AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); + AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt); + } + }); + AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { + public void mouseMoved(java.awt.event.MouseEvent evt) { + AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt); + } + }); + jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox); + + jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N + jLabel35.setText("Distance Functions"); + + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20); + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true); + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5); + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true); + jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox); + + jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N + jLabel36.setText("Analysis Method Description"); + + AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); + + javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel); + AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout); + AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup( + AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 355, Short.MAX_VALUE) + ); + AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup( + AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 128, Short.MAX_VALUE) + ); + + jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); + jLabel37.setText("DF Parameters"); + javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel); JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout); JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup( @@ -1086,29 +1185,41 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(jScrollPane19, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) - .addComponent(jLabel28, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() - .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) - .addComponent(jScrollPane18, 0, 0, Short.MAX_VALUE) - .addComponent(jLabel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) - .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE) + .addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE) + .addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel22) .addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(jLabel21) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 174, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_NotesButton)) - .addComponent(AnalysisMethodPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addComponent(jLabel37))) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel36)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel28) + .addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_AnalysisMethodPanelLayout.setVerticalGroup( @@ -1122,22 +1233,36 @@ public void mouseMoved(java.awt.event.MouseEvent evt) { .addComponent(AnalysisMethodPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE) - .addComponent(AnalysisMethodPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(jScrollPane18, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE) + .addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() - .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton) + .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton) + .addComponent(jLabel37) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton) + .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() + .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton)) + .addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel35) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton) - .addGap(156, 156, 156))) + .addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(jLabel28) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel28) + .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); @@ -1150,6 +1275,39 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { } }); + javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel); + JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout); + JGAAP_ReviewPanelLayout.setHorizontalGroup( + JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup() + .addGap(368, 368, 368) + .addComponent(Process_Button) + .addContainerGap(407, Short.MAX_VALUE)) + ); + JGAAP_ReviewPanelLayout.setVerticalGroup( + JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup() + .addContainerGap(467, Short.MAX_VALUE) + .addComponent(Process_Button) + .addContainerGap()) + ); + + JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel); + + Next_Button.setText("Next >"); + Next_Button.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + Next_ButtonActionPerformed(evt); + } + }); + + Review_Button.setText("Finish & Review"); + Review_Button.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + Review_ButtonActionPerformed(evt); + } + }); + jMenu1.setText("File"); SaveProblemMenuItem.setText("Save Problem"); @@ -1190,6 +1348,49 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu1.add(jMenu4); + jMenu2.setText("AAAC Problems"); + + jMenuItem1.setText("Problem A"); + jMenu2.add(jMenuItem1); + + jMenuItem2.setText("Problem B"); + jMenu2.add(jMenuItem2); + + jMenuItem3.setText("Problem C"); + jMenu2.add(jMenuItem3); + + jMenuItem4.setText("Problem D"); + jMenu2.add(jMenuItem4); + + jMenuItem5.setText("Problem E"); + jMenu2.add(jMenuItem5); + + jMenuItem6.setText("Problem F"); + jMenu2.add(jMenuItem6); + + jMenuItem7.setText("Problem G"); + jMenu2.add(jMenuItem7); + + jMenuItem8.setText("Problem H"); + jMenu2.add(jMenuItem8); + + jMenuItem9.setText("Problem I"); + jMenu2.add(jMenuItem9); + + jMenuItem10.setText("Problem J"); + jMenu2.add(jMenuItem10); + + jMenuItem11.setText("Problem K"); + jMenu2.add(jMenuItem11); + + jMenuItem12.setText("Problem L"); + jMenu2.add(jMenuItem12); + + jMenuItem13.setText("Problem M"); + jMenu2.add(jMenuItem13); + + jMenu1.add(jMenu2); + jMenu3.setText("Options"); jMenu5.setText("Default Language"); @@ -1226,23 +1427,26 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) - .addGroup(layout.createSequentialGroup() - .addGap(386, 386, 386) - .addComponent(Process_Button)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() - .addContainerGap() - .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 849, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addComponent(Review_Button) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(Next_Button))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(Process_Button) - .addContainerGap()) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(Next_Button) + .addComponent(Review_Button)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); @@ -1257,8 +1461,8 @@ private void Process_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GE for (Document unknown : unknowns) { buffer.append(unknown.getResult()); } - JGAAP_UI_ResultsDialog ResultsPage = new JGAAP_UI_ResultsDialog(JGAAP_UI_MainForm.this, false); - ResultsPage.DisplayResults(buffer.toString()); + //ResultsPage.DisplayResults(buffer.toString()); + ResultsPage.AddResults(buffer.toString()); ResultsPage.setVisible(true); } catch (Exception e){ } @@ -1355,19 +1559,20 @@ private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN private void AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); - if (index > -1) { - if (index < AnalysisDriverMasterList.size()) { - String text = AnalysisDriverMasterList.get(index).tooltipText(); - theList.setToolTipText(text); - } else { - String text = DistanceFunctionsMasterList.get(index - AnalysisDriverMasterList.size()).tooltipText(); - theList.setToolTipText(text); - } - } + if (index > -1) + { + String text = AnalysisDriverMasterList.get(index).tooltipText(); + theList.setToolTipText(text); + } }//GEN-LAST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved private void AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(AnalysisDriverMasterList.get(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedIndex()).longDescription()); + + if (evt.getClickCount() == 2) + { + AddAnalysisMethodSelection(); + } }//GEN-LAST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked private void AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed @@ -1387,19 +1592,31 @@ private void AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(java }//GEN-LAST:event_AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed private void AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed + RemoveAnalysisMethodSelection(); +}//GEN-LAST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed + + private void RemoveAnalysisMethodSelection() { SelectedAnalysisDriverList = JGAAP_API.getAnalysisDrivers(); JGAAP_API.removeAnalysisDriver(SelectedAnalysisDriverList.get(AnalysisMethodPanel_SelectedAnalysisMethodsListBox.getSelectedIndex())); UpdateSelectedAnalysisMethodListBox(); -}//GEN-LAST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed + } private void AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed + AddAnalysisMethodSelection(); +}//GEN-LAST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed + + private void AddAnalysisMethodSelection() { try{ - JGAAP_API.addAnalysisDriver(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedValue().toString()); + AnalysisDriver temp = JGAAP_API.addAnalysisDriver(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedValue().toString()); + if (temp instanceof NeighborAnalysisDriver) + { + JGAAP_API.addDistanceFunction(AnalysisMethodPanel_DistanceFunctionsListBox.getSelectedValue().toString(), temp); + } UpdateSelectedAnalysisMethodListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } -}//GEN-LAST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed + } private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved JList theList = (JList) evt.getSource(); @@ -1412,6 +1629,11 @@ private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(java.a private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(SelectedAnalysisDriverList.get(AnalysisMethodPanel_SelectedAnalysisMethodsListBox.getSelectedIndex()).longDescription()); + + if (evt.getClickCount() == 2) + { + RemoveAnalysisMethodSelection(); + } }//GEN-LAST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked private void EventCullingPanel_EventCullingListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_EventCullingListBoxMouseMoved @@ -1425,6 +1647,11 @@ private void EventCullingPanel_EventCullingListBoxMouseMoved(java.awt.event.Mous private void EventCullingPanel_EventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_EventCullingListBoxMouseClicked EventCullingPanel_EventCullingDescriptionTextbox.setText(EventCullersMasterList.get(EventCullingPanel_EventCullingListBox.getSelectedIndex()).longDescription()); + + if (evt.getClickCount() == 2) + { + AddEventCullerSelection(); + } }//GEN-LAST:event_EventCullingPanel_EventCullingListBoxMouseClicked private void EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_RemoveAllEventCullingButtonActionPerformed @@ -1444,19 +1671,27 @@ private void EventCullingPanel_AddAllEventCullingButtonActionPerformed(java.awt. }//GEN-LAST:event_EventCullingPanel_AddAllEventCullingButtonActionPerformed private void EventCullingPanel_RemoveEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed + RemoveEventCullerSelection(); +}//GEN-LAST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed + + private void RemoveEventCullerSelection() { SelectedEventCullersList = JGAAP_API.getEventCullers(); JGAAP_API.removeEventCuller(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex())); UpdateSelectedEventCullingListBox(); -}//GEN-LAST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed + } private void EventCullingPanel_AddEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_AddEventCullingButtonActionPerformed + AddEventCullerSelection(); +}//GEN-LAST:event_EventCullingPanel_AddEventCullingButtonActionPerformed + + private void AddEventCullerSelection() { try{ JGAAP_API.addEventCuller(EventCullingPanel_EventCullingListBox.getSelectedValue().toString()); UpdateSelectedEventCullingListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } -}//GEN-LAST:event_EventCullingPanel_AddEventCullingButtonActionPerformed + } private void EventCullingPanel_SelectedEventCullingListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_SelectedEventCullingListBoxMouseMoved JList theList = (JList) evt.getSource(); @@ -1469,6 +1704,11 @@ private void EventCullingPanel_SelectedEventCullingListBoxMouseMoved(java.awt.ev private void EventCullingPanel_SelectedEventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_SelectedEventCullingListBoxMouseClicked EventCullingPanel_EventCullingDescriptionTextbox.setText(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex()).longDescription()); + + if (evt.getClickCount() == 2) + { + RemoveEventCullerSelection(); + } }//GEN-LAST:event_EventCullingPanel_SelectedEventCullingListBoxMouseClicked private void EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_RemoveAllEventSetsButtonActionPerformed @@ -1488,19 +1728,29 @@ private void EventSetsPanel_AddAllEventSetsButtonActionPerformed(java.awt.event. }//GEN-LAST:event_EventSetsPanel_AddAllEventSetsButtonActionPerformed private void EventSetsPanel_RemoveEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed + RemoveEventSetSelection(); +}//GEN-LAST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed + + private void RemoveEventSetSelection() + { SelectedEventDriverList = JGAAP_API.getEventDrivers(); JGAAP_API.removeEventDriver(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex())); UpdateSelectedEventSetListBox(); -}//GEN-LAST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed + } private void EventSetsPanel_AddEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_AddEventSetButtonActionPerformed + AddEventSetSelection(); +}//GEN-LAST:event_EventSetsPanel_AddEventSetButtonActionPerformed + + private void AddEventSetSelection() + { try{ JGAAP_API.addEventDriver(EventSetsPanel_EventSetListBox.getSelectedValue().toString()); UpdateSelectedEventSetListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } -}//GEN-LAST:event_EventSetsPanel_AddEventSetButtonActionPerformed + } private void EventSetsPanel_SelectedEventSetListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_SelectedEventSetListBoxMouseMoved JList theList = (JList) evt.getSource(); @@ -1515,6 +1765,10 @@ private void EventSetsPanel_SelectedEventSetListBoxMouseClicked(java.awt.event.M EventSetsPanel_ParametersPanel.removeAll(); EventSetsPanel_ParametersPanel.setLayout(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).getGUILayout(EventSetsPanel_ParametersPanel)); EventSetsPanel_EventSetDescriptionTextBox.setText(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).longDescription()); + if (evt.getClickCount() == 2) + { + RemoveEventSetSelection(); + } }//GEN-LAST:event_EventSetsPanel_SelectedEventSetListBoxMouseClicked private void EventSetsPanel_EventSetListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_EventSetListBoxMouseMoved @@ -1528,6 +1782,10 @@ private void EventSetsPanel_EventSetListBoxMouseMoved(java.awt.event.MouseEvent private void EventSetsPanel_EventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_EventSetListBoxMouseClicked EventSetsPanel_EventSetDescriptionTextBox.setText(EventDriverMasterList.get(EventSetsPanel_EventSetListBox.getSelectedIndex()).longDescription()); + if (evt.getClickCount() == 2) + { + AddEventSetSelection(); + } }//GEN-LAST:event_EventSetsPanel_EventSetListBoxMouseClicked private void CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed @@ -1548,12 +1806,21 @@ private void CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(java.awt. }//GEN-LAST:event_CanonicizersPanel_AddAllCanonicizersButtonActionPerformed private void CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed + RemoveCanonicizerSelection(); +}//GEN-LAST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed + + private void RemoveCanonicizerSelection() { SelectedCanonicizerList.remove(CanonicizersPanel_SelectedCanonicizerListBox.getSelectedIndex()); UpdateSelectedCanonicizerListBox(); -}//GEN-LAST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed + } private void CanonicizersPanel_AddCanonicizerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed - try{ + AddCanonicizerSelection(); +}//GEN-LAST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed + + private void AddCanonicizerSelection() + { + try{ for (int i = 0; i < CanonicizerMasterList.size(); i++){ if (CanonicizerMasterList.get(i).displayName().equals(CanonicizersPanel_CanonicizerListBox.getSelectedValue().toString())){ Canonicizer temp = CanonicizerMasterList.get(i).getClass().newInstance(); @@ -1564,8 +1831,7 @@ private void CanonicizersPanel_AddCanonicizerButtonActionPerformed(java.awt.even } catch (Exception e){ System.out.println(e.getMessage()); } -}//GEN-LAST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed - + } private void CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); @@ -1577,6 +1843,10 @@ private void CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(java.awt.eve private void CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setText(SelectedCanonicizerList.get(CanonicizersPanel_SelectedCanonicizerListBox.getSelectedIndex()).longDescription()); + if (evt.getClickCount() == 2) + { + RemoveCanonicizerSelection(); + } }//GEN-LAST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked private void CanonicizersPanel_CanonicizerListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_CanonicizerListBoxMouseMoved @@ -1590,6 +1860,10 @@ private void CanonicizersPanel_CanonicizerListBoxMouseMoved(java.awt.event.Mouse private void CanonicizersPanel_CanonicizerListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_CanonicizerListBoxMouseClicked CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setText(CanonicizerMasterList.get(CanonicizersPanel_CanonicizerListBox.getSelectedIndex()).longDescription()); + if (evt.getClickCount() == 2) + { + AddCanonicizerSelection(); + } }//GEN-LAST:event_CanonicizersPanel_CanonicizerListBoxMouseClicked private void DocumentsPanel_LanguageComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_LanguageComboBoxActionPerformed @@ -1705,6 +1979,97 @@ private void CanonicizersPanel_SetToAllDocumentsActionPerformed(java.awt.event.A UpdateDocumentsTable(); }//GEN-LAST:event_CanonicizersPanel_SetToAllDocumentsActionPerformed + private void DocumentsPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_NotesButtonActionPerformed + try { + NotesPage.DisplayNote(Notes[0]); + NotesPage.setVisible(true); + if (NotesPage.SavedNote != null) + { + Notes[0] = NotesPage.SavedNote; + } + } catch (Exception e){ + } + }//GEN-LAST:event_DocumentsPanel_NotesButtonActionPerformed + + private void CanonicizersPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_NotesButtonActionPerformed + try { + NotesPage.DisplayNote(Notes[1]); + NotesPage.setVisible(true); + if (NotesPage.SavedNote != null) + { + Notes[1] = NotesPage.SavedNote; + } + } catch (Exception e){ + } + }//GEN-LAST:event_CanonicizersPanel_NotesButtonActionPerformed + + private void EventSetsPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_NotesButtonActionPerformed + try { + NotesPage.DisplayNote(Notes[2]); + NotesPage.setVisible(true); + if (NotesPage.SavedNote != null) + { + Notes[2] = NotesPage.SavedNote; + } + } catch (Exception e){ + } + }//GEN-LAST:event_EventSetsPanel_NotesButtonActionPerformed + + private void EventCullingPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_NotesButtonActionPerformed + try { + NotesPage.DisplayNote(Notes[3]); + NotesPage.setVisible(true); + if (NotesPage.SavedNote != null) + { + Notes[3] = NotesPage.SavedNote; + } + } catch (Exception e){ + } + }//GEN-LAST:event_EventCullingPanel_NotesButtonActionPerformed + + private void AnalysisMethodPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_NotesButtonActionPerformed + try { + NotesPage.DisplayNote(Notes[4]); + NotesPage.setVisible(true); + if (NotesPage.SavedNote != null) + { + Notes[4] = NotesPage.SavedNote; + } + } catch (Exception e){ + } + }//GEN-LAST:event_AnalysisMethodPanel_NotesButtonActionPerformed + + private void AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(DistanceFunctionsMasterList.get(AnalysisMethodPanel_DistanceFunctionsListBox.getSelectedIndex()).longDescription()); + + if (evt.getClickCount() == 2) + { + AddAnalysisMethodSelection(); + } + }//GEN-LAST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked + + private void AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved + JList theList = (JList) evt.getSource(); + int index = theList.locationToIndex(evt.getPoint()); + if (index > -1) + { + String text = DistanceFunctionsMasterList.get(index).tooltipText(); + theList.setToolTipText(text); + } + }//GEN-LAST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved + + private void Next_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Next_ButtonActionPerformed + int count = JGAAP_TabbedPane.getSelectedIndex(); + if (count < 5) + { + JGAAP_TabbedPane.setSelectedIndex(count + 1); + } + }//GEN-LAST:event_Next_ButtonActionPerformed + + private void Review_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Review_ButtonActionPerformed + JGAAP_TabbedPane.setSelectedIndex(5); + }//GEN-LAST:event_Review_ButtonActionPerformed + private void toggleHelpDialog(){ helpDialog.setVisible(!helpDialog.isVisible()); } @@ -1891,17 +2256,34 @@ private void SetAnalysisMethodList() { { AnalysisMethodListBox_Model.addElement(AnalysisDriverMasterList.get(i).displayName()); } + if (!AnalysisDriverMasterList.isEmpty()) + { + AnalysisMethodPanel_AnalysisMethodsListBox.setSelectedIndex(0); + AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(AnalysisDriverMasterList.get(0).longDescription()); + } + } + private void SetDistanceFunctionList() { for (int i = 0; i < DistanceFunctionsMasterList.size(); i++) { - AnalysisMethodListBox_Model.addElement(DistanceFunctionsMasterList.get(i).displayName()); + DistanceFunctionsListBox_Model.addElement(DistanceFunctionsMasterList.get(i).displayName()); } -} + if (!DistanceFunctionsMasterList.isEmpty()) + { + AnalysisMethodPanel_DistanceFunctionsListBox.setSelectedIndex(0); + AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(DistanceFunctionsMasterList.get(0).longDescription()); + } + } private void SetCanonicizerList() { for (int i = 0; i < CanonicizerMasterList.size(); i++) { CanonicizerListBox_Model.addElement(CanonicizerMasterList.get(i).displayName()); } + if (!CanonicizerMasterList.isEmpty()) + { + CanonicizersPanel_CanonicizerListBox.setSelectedIndex(0); + CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setText(CanonicizerMasterList.get(0).longDescription()); + } } private void SetEventCullingList() { @@ -1909,6 +2291,11 @@ private void SetEventCullingList() { { EventCullingListBox_Model.addElement(EventCullersMasterList.get(i).displayName()); } + if (!EventCullersMasterList.isEmpty()) + { + EventCullingPanel_EventCullingListBox.setSelectedIndex(0); + EventCullingPanel_EventCullingDescriptionTextbox.setText(EventCullersMasterList.get(0).longDescription()); + } } private void SetLanguagesList() { @@ -1934,52 +2321,13 @@ private void SetEventSetList() { { EventSetsListBox_Model.addElement(EventDriverMasterList.get(i).displayName()); } - - /*EventSetsPanel_SelectedEventSetListBox.addMouseListener(new MouseAdapter() { - public void mouseClicked(MouseEvent e) - { - GetEventSetPanel(); - } - });*/ + if (!EventDriverMasterList.isEmpty()) + { + EventSetsPanel_EventSetListBox.setSelectedIndex(0); + EventSetsPanel_EventSetDescriptionTextBox.setText(EventDriverMasterList.get(0).longDescription()); + } + } - - //private void GetEventSetPanel() { - /*EventSetsPanel_ParametersPanel = new JPanel(); - EventSetsPanel_ParametersPanel = EventDriverMasterList.get(1).getGUI(); - EventSetsPanel_ParametersPanel.repaint(); - EventSetsPanel_ParametersPanel.revalidate();*/ - - /*EventSetsPanel_ParametersPanel = new JPanel( new BorderLayout() ); - JButton button1 = new JButton("Button Text"); - EventSetsPanel_ParametersPanel.add(button1, BorderLayout.CENTER); - EventSetsPanel_ParametersPanel.revalidate(); - EventSetsPanel_ParametersPanel.repaint();*/ - - /*javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel); - EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout); - EventSetsPanel_ParametersPanelLayout.setHorizontalGroup( - EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(EventSetsPanel_ParametersPanelLayout.createSequentialGroup() - .addGap(1, 1, 1) - .addComponent(jLabel11) - .addContainerGap(160, Short.MAX_VALUE)) - ); - EventSetsPanel_ParametersPanelLayout.setVerticalGroup( - EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(EventSetsPanel_ParametersPanelLayout.createSequentialGroup() - .addGap(1, 1, 1) - .addComponent(jLabel11) - .addContainerGap(214, Short.MAX_VALUE)) - );*/ - - /*//EventSetsPanel_ParametersPanel = new JPanel(); - EventSetsPanel_ParametersPanel.removeAll(); - EventSetsPanel_ParametersPanel.setLayout(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).getGUILayout(EventSetsPanel_ParametersPanel)); - - //EventSetsPanel_ParametersPanel.revalidate(); - //EventSetsPanel_ParametersPanel.repaint(); - -}*/ private void SetUnknownDocumentColumns() { UnknownAuthorDocumentsTable_Model.addColumn("Title"); @@ -2040,12 +2388,15 @@ public void run() { } // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel AnalysisMethodPanel_AMParametersPanel; private javax.swing.JButton AnalysisMethodPanel_AddAllAnalysisMethodsButton; private javax.swing.JButton AnalysisMethodPanel_AddAnalysisMethodButton; private javax.swing.JTextArea AnalysisMethodPanel_AnalysisMethodDescriptionTextBox; private javax.swing.JList AnalysisMethodPanel_AnalysisMethodsListBox; + private javax.swing.JPanel AnalysisMethodPanel_DFParametersPanel; + private javax.swing.JTextArea AnalysisMethodPanel_DistanceFunctionDescriptionTextBox; + private javax.swing.JList AnalysisMethodPanel_DistanceFunctionsListBox; private javax.swing.JButton AnalysisMethodPanel_NotesButton; - private javax.swing.JPanel AnalysisMethodPanel_ParametersPanel; private javax.swing.JButton AnalysisMethodPanel_RemoveAllAnalysisMethodsButton; private javax.swing.JButton AnalysisMethodPanel_RemoveAnalysisMethodsButton; private javax.swing.JList AnalysisMethodPanel_SelectedAnalysisMethodsListBox; @@ -2097,9 +2448,12 @@ public void run() { private javax.swing.JPanel JGAAP_EventCullingPanel; private javax.swing.JPanel JGAAP_EventSetsPanel; private javax.swing.JMenuBar JGAAP_MenuBar; + private javax.swing.JPanel JGAAP_ReviewPanel; private javax.swing.JTabbedPane JGAAP_TabbedPane; private javax.swing.JMenuItem LoadProblemMenuItem; + private javax.swing.JButton Next_Button; private javax.swing.JButton Process_Button; + private javax.swing.JButton Review_Button; private javax.swing.JMenuItem SaveProblemMenuItem; private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JMenuItem exitMenuItem; @@ -2131,14 +2485,31 @@ public void run() { private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; + private javax.swing.JLabel jLabel35; + private javax.swing.JLabel jLabel36; + private javax.swing.JLabel jLabel37; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; + private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; + private javax.swing.JMenuItem jMenuItem1; + private javax.swing.JMenuItem jMenuItem10; + private javax.swing.JMenuItem jMenuItem11; + private javax.swing.JMenuItem jMenuItem12; + private javax.swing.JMenuItem jMenuItem13; + private javax.swing.JMenuItem jMenuItem2; + private javax.swing.JMenuItem jMenuItem3; + private javax.swing.JMenuItem jMenuItem4; + private javax.swing.JMenuItem jMenuItem5; + private javax.swing.JMenuItem jMenuItem6; + private javax.swing.JMenuItem jMenuItem7; + private javax.swing.JMenuItem jMenuItem8; + private javax.swing.JMenuItem jMenuItem9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane10; private javax.swing.JScrollPane jScrollPane11; @@ -2153,6 +2524,8 @@ public void run() { private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane20; private javax.swing.JScrollPane jScrollPane21; + private javax.swing.JScrollPane jScrollPane22; + private javax.swing.JScrollPane jScrollPane23; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane9; // End of variables declaration//GEN-END:variables diff --git a/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.form b/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.form index 5cab36ad2..97174aca0 100644 --- a/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.form +++ b/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.form @@ -22,30 +22,37 @@ <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> - <Component id="jScrollPane1" alignment="0" pref="905" max="32767" attributes="0"/> + <Component id="Results_TabbedPane" alignment="0" pref="910" max="32767" attributes="0"/> + <Group type="102" alignment="1" attributes="0"> + <EmptySpace pref="817" max="32767" attributes="0"/> + <Component id="ClearTabs_Button" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + </Group> </Group> </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> - <Component id="jScrollPane1" alignment="0" pref="534" max="32767" attributes="0"/> + <Group type="102" alignment="0" attributes="0"> + <Component id="Results_TabbedPane" min="-2" pref="510" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="ClearTabs_Button" min="-2" max="-2" attributes="0"/> + <EmptySpace max="32767" attributes="0"/> + </Group> </Group> </DimensionLayout> </Layout> <SubComponents> - <Container class="javax.swing.JScrollPane" name="jScrollPane1"> - <AuxValues> - <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/> - </AuxValues> + <Container class="javax.swing.JTabbedPane" name="Results_TabbedPane"> - <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> - <SubComponents> - <Component class="javax.swing.JTextArea" name="ResultsTextArea"> - <Properties> - <Property name="columns" type="int" value="20"/> - <Property name="rows" type="int" value="5"/> - </Properties> - </Component> - </SubComponents> + <Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/> </Container> + <Component class="javax.swing.JButton" name="ClearTabs_Button"> + <Properties> + <Property name="text" type="java.lang.String" value="Clear Tabs"/> + </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="ClearTabs_ButtonActionPerformed"/> + </Events> + </Component> </SubComponents> </Form> diff --git a/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.java b/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.java index 3b5a70295..a30e10566 100644 --- a/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.java +++ b/src/com/jgaap/ui/JGAAP_UI_ResultsDialog.java @@ -1,4 +1,3 @@ -// Copyright (c) 2009, 2011 by Patrick Juola. All rights reserved. All unauthorized use prohibited. /* * To change this template, choose Tools | Templates * and open the template in the editor. @@ -7,17 +6,23 @@ /* * JGAAP_UI_ResultsDialog.java * - * Created on Dec 7, 2010, 10:33:01 AM + * Created on Apr 19, 2011, 2:35:09 PM */ package com.jgaap.ui; +import javax.swing.*; +import java.awt.BorderLayout; +import java.util.Calendar; +import java.text.SimpleDateFormat; + /** * * @author Patrick Brennan */ public class JGAAP_UI_ResultsDialog extends javax.swing.JDialog { - private static final long serialVersionUID = 1L; + + public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; /** Creates new form JGAAP_UI_ResultsDialog */ public JGAAP_UI_ResultsDialog(java.awt.Frame parent, boolean modal) { @@ -25,41 +30,53 @@ public JGAAP_UI_ResultsDialog(java.awt.Frame parent, boolean modal) { initComponents(); } - public void DisplayResults(String results) - { - ResultsTextArea.setText(results); - } - /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ + @SuppressWarnings("unchecked") + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { - jScrollPane1 = new javax.swing.JScrollPane(); - ResultsTextArea = new javax.swing.JTextArea(); + Results_TabbedPane = new javax.swing.JTabbedPane(); + ClearTabs_Button = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - ResultsTextArea.setColumns(20); - ResultsTextArea.setRows(5); - jScrollPane1.setViewportView(ResultsTextArea); + ClearTabs_Button.setText("Clear Tabs"); + ClearTabs_Button.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + ClearTabs_ButtonActionPerformed(evt); + } + }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 905, Short.MAX_VALUE) + .addComponent(Results_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 910, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap(817, Short.MAX_VALUE) + .addComponent(ClearTabs_Button) + .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addComponent(Results_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(ClearTabs_Button) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents + private void ClearTabs_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearTabs_ButtonActionPerformed + Results_TabbedPane.removeAll(); + }//GEN-LAST:event_ClearTabs_ButtonActionPerformed + /** * @param args the command line arguments */ @@ -77,9 +94,28 @@ public void windowClosing(java.awt.event.WindowEvent e) { }); } + public static String now() + { + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); + return sdf.format(cal.getTime()); + } + + public void AddResults(String note) + { + JTextArea TextArea = new JTextArea(); + TextArea.setText(note); + JScrollPane ScrollPane = new JScrollPane(TextArea); + JPanel Panel = new JPanel(); + Panel.setLayout(new BorderLayout()); + Panel.add(ScrollPane, BorderLayout.CENTER); + Results_TabbedPane.add(now(),Panel); + + } + // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JTextArea ResultsTextArea; - private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JButton ClearTabs_Button; + private javax.swing.JTabbedPane Results_TabbedPane; // End of variables declaration//GEN-END:variables }
26d26d605e9887885afe78d943fbf152d965e44a
intellij-community
PY-1635 Extract Method in middle of expression- generates broken code--
c
https://github.com/JetBrains/intellij-community
diff --git a/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java b/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java index c4e5eb036be11..04daea9e6c155 100644 --- a/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java +++ b/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java @@ -198,15 +198,15 @@ public void run() { // Generating call element final StringBuilder builder = new StringBuilder(); - if (fragment.isReturnInstructionInside()) { - builder.append("return "); - } + builder.append("return "); if (isMethod){ appendSelf(expression, builder); } builder.append(methodName); builder.append("(").append(createCallArgsString(variableData)).append(")"); - PsiElement callElement = PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyElement.class, builder.toString()); + final PyReturnStatement returnStatement = + (PyReturnStatement) PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyElement.class, builder.toString()); + PsiElement callElement = fragment.isReturnInstructionInside() ? returnStatement : returnStatement.getExpression(); // replace statements with call callElement = PyPsiUtils.replaceExpression(project, expression, callElement); diff --git a/python/testData/refactoring/extractmethod/return_tuple.after.py b/python/testData/refactoring/extractmethod/return_tuple.after.py new file mode 100644 index 0000000000000..dc924a7a7074b --- /dev/null +++ b/python/testData/refactoring/extractmethod/return_tuple.after.py @@ -0,0 +1,5 @@ +def bar(p_name_new, params_new): + return p_name_new + '(' + ', '.join(params_new) + ')' + +def x(p_name, params): + return bar(p_name, params), None \ No newline at end of file diff --git a/python/testData/refactoring/extractmethod/return_tuple.before.py b/python/testData/refactoring/extractmethod/return_tuple.before.py new file mode 100644 index 0000000000000..3e30779879366 --- /dev/null +++ b/python/testData/refactoring/extractmethod/return_tuple.before.py @@ -0,0 +1,2 @@ +def x(p_name, params): + return <selection>p_name + '(' + ', '.join(params) + ')'</selection>, None \ No newline at end of file diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java index 0d00716b87a4c..0f55625d895a9 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java @@ -133,4 +133,8 @@ public void testConditionalReturn() throws Throwable { doTest("conditionalreturn.before.py", "bar", "Cannot perform refactoring when execution flow is interrupted"); } + public void testReturnTuple() throws Throwable { + doTest("return_tuple.before.py", "bar", "return_tuple.after.py"); + } + }
ec559db68e1ad306b1ba97283fbda1074fa50eb0
hadoop
HDFS-1480. All replicas of a block can end up on- the same rack when some datanodes are decommissioning. Contributed by Todd- Lipcon.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1160897 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs/CHANGES.txt index ad1429fa53cae..35f58a5db075c 100644 --- a/hadoop-hdfs/CHANGES.txt +++ b/hadoop-hdfs/CHANGES.txt @@ -989,6 +989,9 @@ Trunk (unreleased changes) HDFS-2267. DataXceiver thread name incorrect while waiting on op during keepalive. (todd) + HDFS-1480. All replicas of a block can end up on the same rack when + some datanodes are decommissioning. (todd) + BREAKDOWN OF HDFS-1073 SUBTASKS HDFS-1521. Persist transaction ID on disk between NN restarts. diff --git a/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java b/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java index 296ee98e801f9..081a60430c526 100644 --- a/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java +++ b/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java @@ -66,6 +66,8 @@ import org.apache.hadoop.net.Node; import org.apache.hadoop.util.Daemon; +import com.google.common.annotations.VisibleForTesting; + /** * Keeps information related to the blocks stored in the Hadoop cluster. * This class is a helper class for {@link FSNamesystem} and requires several @@ -147,7 +149,8 @@ public long getExcessBlocksCount() { // We also store pending replication-orders. // public final UnderReplicatedBlocks neededReplications = new UnderReplicatedBlocks(); - private final PendingReplicationBlocks pendingReplications; + @VisibleForTesting + final PendingReplicationBlocks pendingReplications; /** The maximum number of replicas allowed for a block */ public final short maxReplication; @@ -312,9 +315,14 @@ public void metaSave(PrintWriter out) { for (Block block : neededReplications) { List<DatanodeDescriptor> containingNodes = new ArrayList<DatanodeDescriptor>(); + List<DatanodeDescriptor> containingLiveReplicasNodes = + new ArrayList<DatanodeDescriptor>(); + NumberReplicas numReplicas = new NumberReplicas(); // source node returned is not used - chooseSourceDatanode(block, containingNodes, numReplicas); + chooseSourceDatanode(block, containingNodes, + containingLiveReplicasNodes, numReplicas); + assert containingLiveReplicasNodes.size() == numReplicas.liveReplicas(); int usableReplicas = numReplicas.liveReplicas() + numReplicas.decommissionedReplicas(); @@ -993,9 +1001,10 @@ private List<List<Block>> chooseUnderReplicatedBlocks(int blocksToProcess) { * @param priority a hint of its priority in the neededReplication queue * @return if the block gets replicated or not */ - private boolean computeReplicationWorkForBlock(Block block, int priority) { + @VisibleForTesting + boolean computeReplicationWorkForBlock(Block block, int priority) { int requiredReplication, numEffectiveReplicas; - List<DatanodeDescriptor> containingNodes; + List<DatanodeDescriptor> containingNodes, liveReplicaNodes; DatanodeDescriptor srcNode; INodeFile fileINode = null; int additionalReplRequired; @@ -1016,11 +1025,14 @@ private boolean computeReplicationWorkForBlock(Block block, int priority) { // get a source data-node containingNodes = new ArrayList<DatanodeDescriptor>(); + liveReplicaNodes = new ArrayList<DatanodeDescriptor>(); NumberReplicas numReplicas = new NumberReplicas(); - srcNode = chooseSourceDatanode(block, containingNodes, numReplicas); + srcNode = chooseSourceDatanode( + block, containingNodes, liveReplicaNodes, numReplicas); if(srcNode == null) // block can not be replicated from any node return false; + assert liveReplicaNodes.size() == numReplicas.liveReplicas(); // do not schedule more if enough replicas is already pending numEffectiveReplicas = numReplicas.liveReplicas() + pendingReplications.getNumReplicas(block); @@ -1047,13 +1059,20 @@ private boolean computeReplicationWorkForBlock(Block block, int priority) { } finally { namesystem.writeUnlock(); } + + // Exclude all of the containing nodes from being targets. + // This list includes decommissioning or corrupt nodes. + HashMap<Node, Node> excludedNodes = new HashMap<Node, Node>(); + for (DatanodeDescriptor dn : containingNodes) { + excludedNodes.put(dn, dn); + } // choose replication targets: NOT HOLDING THE GLOBAL LOCK // It is costly to extract the filename for which chooseTargets is called, // so for now we pass in the Inode itself. DatanodeDescriptor targets[] = blockplacement.chooseTarget(fileINode, additionalReplRequired, - srcNode, containingNodes, block.getNumBytes()); + srcNode, liveReplicaNodes, excludedNodes, block.getNumBytes()); if(targets.length == 0) return false; @@ -1182,8 +1201,10 @@ public DatanodeDescriptor[] chooseTarget(final String src, private DatanodeDescriptor chooseSourceDatanode( Block block, List<DatanodeDescriptor> containingNodes, + List<DatanodeDescriptor> nodesContainingLiveReplicas, NumberReplicas numReplicas) { containingNodes.clear(); + nodesContainingLiveReplicas.clear(); DatanodeDescriptor srcNode = null; int live = 0; int decommissioned = 0; @@ -1202,6 +1223,7 @@ else if (node.isDecommissionInProgress() || node.isDecommissioned()) else if (excessBlocks != null && excessBlocks.contains(block)) { excess++; } else { + nodesContainingLiveReplicas.add(node); live++; } containingNodes.add(node); @@ -2049,7 +2071,8 @@ private long addBlock(Block block, List<BlockWithLocations> results) { /** * The given node is reporting that it received a certain block. */ - private void addBlock(DatanodeDescriptor node, Block block, String delHint) + @VisibleForTesting + void addBlock(DatanodeDescriptor node, Block block, String delHint) throws IOException { // decrement number of blocks scheduled to this datanode. node.decBlocksScheduled(); diff --git a/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicy.java b/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicy.java index e1e8c9ced946c..b333972a26221 100644 --- a/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicy.java +++ b/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicy.java @@ -127,9 +127,10 @@ DatanodeDescriptor[] chooseTarget(FSInodeInfo srcInode, int numOfReplicas, DatanodeDescriptor writer, List<DatanodeDescriptor> chosenNodes, + HashMap<Node, Node> excludedNodes, long blocksize) { return chooseTarget(srcInode.getFullPathName(), numOfReplicas, writer, - chosenNodes, blocksize); + chosenNodes, excludedNodes, blocksize); } /** diff --git a/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java b/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java index fcada7b562350..1b483a75373bf 100644 --- a/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java +++ b/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java @@ -102,16 +102,6 @@ public DatanodeDescriptor[] chooseTarget(String srcPath, excludedNodes, blocksize); } - /** {@inheritDoc} */ - @Override - public DatanodeDescriptor[] chooseTarget(FSInodeInfo srcInode, - int numOfReplicas, - DatanodeDescriptor writer, - List<DatanodeDescriptor> chosenNodes, - long blocksize) { - return chooseTarget(numOfReplicas, writer, chosenNodes, false, - null, blocksize); - } /** This is the implementation. */ DatanodeDescriptor[] chooseTarget(int numOfReplicas, diff --git a/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java b/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java new file mode 100644 index 0000000000000..e8193b56d5d52 --- /dev/null +++ b/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java @@ -0,0 +1,391 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hdfs.server.blockmanagement; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.List; +import java.util.Map.Entry; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hdfs.DFSConfigKeys; +import org.apache.hadoop.hdfs.HdfsConfiguration; +import org.apache.hadoop.hdfs.protocol.Block; +import org.apache.hadoop.hdfs.protocol.DatanodeID; +import org.apache.hadoop.hdfs.protocol.FSConstants; +import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo; +import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager; +import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor; +import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor.BlockTargetPair; +import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; +import org.apache.hadoop.hdfs.server.namenode.INodeFile; +import org.apache.hadoop.net.NetworkTopology; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.Lists; + +public class TestBlockManager { + private final List<DatanodeDescriptor> nodes = ImmutableList.of( + new DatanodeDescriptor(new DatanodeID("h1:5020"), "/rackA"), + new DatanodeDescriptor(new DatanodeID("h2:5020"), "/rackA"), + new DatanodeDescriptor(new DatanodeID("h3:5020"), "/rackA"), + new DatanodeDescriptor(new DatanodeID("h4:5020"), "/rackB"), + new DatanodeDescriptor(new DatanodeID("h5:5020"), "/rackB"), + new DatanodeDescriptor(new DatanodeID("h6:5020"), "/rackB") + ); + private final List<DatanodeDescriptor> rackA = nodes.subList(0, 3); + private final List<DatanodeDescriptor> rackB = nodes.subList(3, 6); + + /** + * Some of these tests exercise code which has some randomness involved - + * ie even if there's a bug, they may pass because the random node selection + * chooses the correct result. + * + * Since they're true unit tests and run quickly, we loop them a number + * of times trying to trigger the incorrect behavior. + */ + private static final int NUM_TEST_ITERS = 30; + + private static final int BLOCK_SIZE = 64*1024; + + private Configuration conf; + private FSNamesystem fsn; + private BlockManager bm; + + @Before + public void setupMockCluster() throws IOException { + conf = new HdfsConfiguration(); + conf.set(DFSConfigKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY, + "need to set a dummy value here so it assumes a multi-rack cluster"); + fsn = Mockito.mock(FSNamesystem.class); + Mockito.doReturn(true).when(fsn).hasWriteLock(); + bm = new BlockManager(fsn, conf); + } + + private void addNodes(Iterable<DatanodeDescriptor> nodesToAdd) { + NetworkTopology cluster = bm.getDatanodeManager().getNetworkTopology(); + // construct network topology + for (DatanodeDescriptor dn : nodesToAdd) { + cluster.add(dn); + dn.updateHeartbeat( + 2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L, + 2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L, 0, 0); + } + } + + private void removeNode(DatanodeDescriptor deadNode) { + NetworkTopology cluster = bm.getDatanodeManager().getNetworkTopology(); + cluster.remove(deadNode); + bm.removeBlocksAssociatedTo(deadNode); + } + + + /** + * Test that replication of under-replicated blocks is detected + * and basically works + */ + @Test + public void testBasicReplication() throws Exception { + addNodes(nodes); + for (int i = 0; i < NUM_TEST_ITERS; i++) { + doBasicTest(i); + } + } + + private void doBasicTest(int testIndex) { + List<DatanodeDescriptor> origNodes = nodes(0, 1); + BlockInfo blockInfo = addBlockOnNodes((long)testIndex, origNodes); + + DatanodeDescriptor[] pipeline = scheduleSingleReplication(blockInfo); + assertEquals(2, pipeline.length); + assertTrue("Source of replication should be one of the nodes the block " + + "was on. Was: " + pipeline[0], + origNodes.contains(pipeline[0])); + assertTrue("Destination of replication should be on the other rack. " + + "Was: " + pipeline[1], + rackB.contains(pipeline[1])); + } + + + /** + * Regression test for HDFS-1480 + * - Cluster has 2 racks, A and B, each with three nodes. + * - Block initially written on A1, A2, B1 + * - Admin decommissions two of these nodes (let's say A1 and A2 but it doesn't matter) + * - Re-replication should respect rack policy + */ + @Test + public void testTwoOfThreeNodesDecommissioned() throws Exception { + addNodes(nodes); + for (int i = 0; i < NUM_TEST_ITERS; i++) { + doTestTwoOfThreeNodesDecommissioned(i); + } + } + + private void doTestTwoOfThreeNodesDecommissioned(int testIndex) throws Exception { + // Block originally on A1, A2, B1 + List<DatanodeDescriptor> origNodes = nodes(0, 1, 3); + BlockInfo blockInfo = addBlockOnNodes(testIndex, origNodes); + + // Decommission two of the nodes (A1, A2) + List<DatanodeDescriptor> decomNodes = startDecommission(0, 1); + + DatanodeDescriptor[] pipeline = scheduleSingleReplication(blockInfo); + assertTrue("Source of replication should be one of the nodes the block " + + "was on. Was: " + pipeline[0], + origNodes.contains(pipeline[0])); + assertEquals("Should have two targets", 3, pipeline.length); + + boolean foundOneOnRackA = false; + for (int i = 1; i < pipeline.length; i++) { + DatanodeDescriptor target = pipeline[i]; + if (rackA.contains(target)) { + foundOneOnRackA = true; + } + assertFalse(decomNodes.contains(target)); + assertFalse(origNodes.contains(target)); + } + + assertTrue("Should have at least one target on rack A. Pipeline: " + + Joiner.on(",").join(pipeline), + foundOneOnRackA); + } + + + /** + * Test what happens when a block is on three nodes, and all three of those + * nodes are decommissioned. It should properly re-replicate to three new + * nodes. + */ + @Test + public void testAllNodesHoldingReplicasDecommissioned() throws Exception { + addNodes(nodes); + for (int i = 0; i < NUM_TEST_ITERS; i++) { + doTestAllNodesHoldingReplicasDecommissioned(i); + } + } + + private void doTestAllNodesHoldingReplicasDecommissioned(int testIndex) throws Exception { + // Block originally on A1, A2, B1 + List<DatanodeDescriptor> origNodes = nodes(0, 1, 3); + BlockInfo blockInfo = addBlockOnNodes(testIndex, origNodes); + + // Decommission all of the nodes + List<DatanodeDescriptor> decomNodes = startDecommission(0, 1, 3); + + DatanodeDescriptor[] pipeline = scheduleSingleReplication(blockInfo); + assertTrue("Source of replication should be one of the nodes the block " + + "was on. Was: " + pipeline[0], + origNodes.contains(pipeline[0])); + assertEquals("Should have three targets", 4, pipeline.length); + + boolean foundOneOnRackA = false; + boolean foundOneOnRackB = false; + for (int i = 1; i < pipeline.length; i++) { + DatanodeDescriptor target = pipeline[i]; + if (rackA.contains(target)) { + foundOneOnRackA = true; + } else if (rackB.contains(target)) { + foundOneOnRackB = true; + } + assertFalse(decomNodes.contains(target)); + assertFalse(origNodes.contains(target)); + } + + assertTrue("Should have at least one target on rack A. Pipeline: " + + Joiner.on(",").join(pipeline), + foundOneOnRackA); + assertTrue("Should have at least one target on rack B. Pipeline: " + + Joiner.on(",").join(pipeline), + foundOneOnRackB); + } + + /** + * Test what happens when there are two racks, and an entire rack is + * decommissioned. + * + * Since the cluster is multi-rack, it will consider the block + * under-replicated rather than create a third replica on the + * same rack. Adding a new node on a third rack should cause re-replication + * to that node. + */ + @Test + public void testOneOfTwoRacksDecommissioned() throws Exception { + addNodes(nodes); + for (int i = 0; i < NUM_TEST_ITERS; i++) { + doTestOneOfTwoRacksDecommissioned(i); + } + } + + private void doTestOneOfTwoRacksDecommissioned(int testIndex) throws Exception { + // Block originally on A1, A2, B1 + List<DatanodeDescriptor> origNodes = nodes(0, 1, 3); + BlockInfo blockInfo = addBlockOnNodes(testIndex, origNodes); + + // Decommission all of the nodes in rack A + List<DatanodeDescriptor> decomNodes = startDecommission(0, 1, 2); + + DatanodeDescriptor[] pipeline = scheduleSingleReplication(blockInfo); + assertTrue("Source of replication should be one of the nodes the block " + + "was on. Was: " + pipeline[0], + origNodes.contains(pipeline[0])); + assertEquals("Should have 2 targets", 3, pipeline.length); + + boolean foundOneOnRackB = false; + for (int i = 1; i < pipeline.length; i++) { + DatanodeDescriptor target = pipeline[i]; + if (rackB.contains(target)) { + foundOneOnRackB = true; + } + assertFalse(decomNodes.contains(target)); + assertFalse(origNodes.contains(target)); + } + + assertTrue("Should have at least one target on rack B. Pipeline: " + + Joiner.on(",").join(pipeline), + foundOneOnRackB); + + // Mark the block as received on the target nodes in the pipeline + fulfillPipeline(blockInfo, pipeline); + + // the block is still under-replicated. Add a new node. This should allow + // the third off-rack replica. + DatanodeDescriptor rackCNode = new DatanodeDescriptor(new DatanodeID("h7:5020"), "/rackC"); + addNodes(ImmutableList.of(rackCNode)); + try { + DatanodeDescriptor[] pipeline2 = scheduleSingleReplication(blockInfo); + assertEquals(2, pipeline2.length); + assertEquals(rackCNode, pipeline2[1]); + } finally { + removeNode(rackCNode); + } + } + + /** + * Unit test version of testSufficientlyReplBlocksUsesNewRack from + * {@link TestBlocksWithNotEnoughRacks}. + **/ + @Test + public void testSufficientlyReplBlocksUsesNewRack() throws Exception { + addNodes(nodes); + for (int i = 0; i < NUM_TEST_ITERS; i++) { + doTestSufficientlyReplBlocksUsesNewRack(i); + } + } + + private void doTestSufficientlyReplBlocksUsesNewRack(int testIndex) { + // Originally on only nodes in rack A. + List<DatanodeDescriptor> origNodes = rackA; + BlockInfo blockInfo = addBlockOnNodes((long)testIndex, origNodes); + DatanodeDescriptor pipeline[] = scheduleSingleReplication(blockInfo); + + assertEquals(2, pipeline.length); // single new copy + assertTrue("Source of replication should be one of the nodes the block " + + "was on. Was: " + pipeline[0], + origNodes.contains(pipeline[0])); + assertTrue("Destination of replication should be on the other rack. " + + "Was: " + pipeline[1], + rackB.contains(pipeline[1])); + } + + + /** + * Tell the block manager that replication is completed for the given + * pipeline. + */ + private void fulfillPipeline(BlockInfo blockInfo, + DatanodeDescriptor[] pipeline) throws IOException { + for (int i = 1; i < pipeline.length; i++) { + bm.addBlock(pipeline[i], blockInfo, null); + } + } + + private BlockInfo blockOnNodes(long blkId, List<DatanodeDescriptor> nodes) { + Block block = new Block(blkId); + BlockInfo blockInfo = new BlockInfo(block, 3); + + for (DatanodeDescriptor dn : nodes) { + blockInfo.addNode(dn); + } + return blockInfo; + } + + private List<DatanodeDescriptor> nodes(int ... indexes) { + List<DatanodeDescriptor> ret = Lists.newArrayList(); + for (int idx : indexes) { + ret.add(nodes.get(idx)); + } + return ret; + } + + private List<DatanodeDescriptor> startDecommission(int ... indexes) { + List<DatanodeDescriptor> nodes = nodes(indexes); + for (DatanodeDescriptor node : nodes) { + node.startDecommission(); + } + return nodes; + } + + private BlockInfo addBlockOnNodes(long blockId, List<DatanodeDescriptor> nodes) { + INodeFile iNode = Mockito.mock(INodeFile.class); + Mockito.doReturn((short)3).when(iNode).getReplication(); + BlockInfo blockInfo = blockOnNodes(blockId, nodes); + + bm.blocksMap.addINode(blockInfo, iNode); + return blockInfo; + } + + private DatanodeDescriptor[] scheduleSingleReplication(Block block) { + assertEquals("Block not initially pending replication", + 0, bm.pendingReplications.getNumReplicas(block)); + assertTrue("computeReplicationWork should indicate replication is needed", + bm.computeReplicationWorkForBlock(block, 1)); + assertTrue("replication is pending after work is computed", + bm.pendingReplications.getNumReplicas(block) > 0); + + LinkedListMultimap<DatanodeDescriptor, BlockTargetPair> repls = + getAllPendingReplications(); + assertEquals(1, repls.size()); + Entry<DatanodeDescriptor, BlockTargetPair> repl = repls.entries().iterator().next(); + DatanodeDescriptor[] targets = repl.getValue().targets; + + DatanodeDescriptor[] pipeline = new DatanodeDescriptor[1 + targets.length]; + pipeline[0] = repl.getKey(); + System.arraycopy(targets, 0, pipeline, 1, targets.length); + + return pipeline; + } + + private LinkedListMultimap<DatanodeDescriptor, BlockTargetPair> getAllPendingReplications() { + LinkedListMultimap<DatanodeDescriptor, BlockTargetPair> repls = + LinkedListMultimap.create(); + for (DatanodeDescriptor dn : nodes) { + List<BlockTargetPair> thisRepls = dn.getReplicationCommand(10); + if (thisRepls != null) { + repls.putAll(dn, thisRepls); + } + } + return repls; + } +}
9682dce0f487902ea1bf607641c502dc77ed0506
Delta Spike
DELTASPIKE-281 add unit test and fix some bugs in the locale mechanism
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java index 379146702..779914d02 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java @@ -59,6 +59,8 @@ public String getMessage(MessageContext messageContext, String messageTemplate, Iterator<String> messageSourceIterator = messageSources.iterator(); + Locale locale = messageContext.getLocale(); + String currentMessageSource; while (messageSourceIterator.hasNext()) { @@ -66,7 +68,6 @@ public String getMessage(MessageContext messageContext, String messageTemplate, try { - Locale locale = messageContext.getLocale(); ResourceBundle messageBundle = PropertyFileUtils.getResourceBundle(currentMessageSource, locale); if (category != null && category.length() > 0) @@ -78,7 +79,7 @@ public String getMessage(MessageContext messageContext, String messageTemplate, catch (MissingResourceException e) { // we fallback on the version without the category - messageBundle.getString(resourceKey); + return messageBundle.getString(resourceKey); } } diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java index b22b36ad5..9429e7e61 100644 --- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java +++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/JsfMessageTest.java @@ -62,7 +62,8 @@ public static WebArchive deploy() return ShrinkWrap .create(WebArchive.class, "jsfMessageTest.war") .addPackage(JsfMessageBackingBean.class.getPackage()) - .addAsResource("jsfMessageTest/UserMessage.properties") + .addAsResource("jsfMessageTest/UserMessage_en.properties") + .addAsResource("jsfMessageTest/UserMessage_de.properties") .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJsfArchive()) .addAsWebInfResource("default/WEB-INF/web.xml", "web.xml") .addAsWebResource("jsfMessageTest/page.xhtml", "page.xhtml") @@ -72,10 +73,15 @@ public static WebArchive deploy() @Test @RunAsClient - public void testViewScopedContext() throws Exception + public void testEnglishMessages() throws Exception { driver.get(new URL(contextPath, "page.xhtml").toString()); + //X comment this in if you like to debug the server + //X I've already reported ARQGRA-213 for it + //X System.out.println("contextpath= " + contextPath); + //X Thread.sleep(600000L); + // check the JSF FacesMessages Assert.assertNotNull(ExpectedConditions.presenceOfElementLocated(By.xpath("id('messages')")).apply(driver)); @@ -96,4 +102,30 @@ public void testViewScopedContext() throws Exception By.id("test:valueOutput"), "a simple message without a param.").apply(driver)); } + @Test + @RunAsClient + public void testGermanMessages() throws Exception + { + driver.get(new URL(contextPath, "page.xhtml?lang=de").toString()); + + // check the JSF FacesMessages + Assert.assertNotNull(ExpectedConditions.presenceOfElementLocated(By.xpath("id('messages')")).apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath("id('messages')/ul/li[1]"), "Nachricht mit Details warnInfo!").apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath("id('messages')/ul/li[2]"), "Nachricht ohne Details aber mit Parameter errorInfo.").apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath("id('messages')/ul/li[3]"), "Einfache Nachricht ohne Parameter.").apply(driver)); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.xpath("id('messages')/ul/li[4]"), "Einfache Nachricht mit String Parameter fatalInfo.").apply(driver)); + + // check the free message usage + Assert.assertTrue(ExpectedConditions.textToBePresentInElement( + By.id("test:valueOutput"), "Einfache Nachricht ohne Parameter.").apply(driver)); + } + } diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java index 085591f67..254e273e5 100644 --- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java +++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/message/beans/JsfMessageBackingBean.java @@ -18,12 +18,9 @@ */ package org.apache.deltaspike.test.jsf.impl.message.beans; -import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; -import javax.faces.bean.ViewScoped; import javax.inject.Inject; import javax.inject.Named; -import java.io.Serializable; import org.apache.deltaspike.jsf.message.JsfMessage; @@ -37,6 +34,8 @@ public class JsfMessageBackingBean @Inject private JsfMessage<UserMessage> msg; + private String locale = "en"; + public void init() { @@ -50,4 +49,14 @@ public String getSomeMessage() { return msg.get().simpleMessageNoParam(); } + + public String getLocale() + { + return locale; + } + + public void setLocale(String locale) + { + this.locale = locale; + } } diff --git a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage_de.properties b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage_de.properties new file mode 100644 index 000000000..07d26a701 --- /dev/null +++ b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage_de.properties @@ -0,0 +1,25 @@ +#Licensed to the Apache Software Foundation (ASF) under one +#or more contributor license agreements. See the NOTICE file +#distributed with this work for additional information +#regarding copyright ownership. The ASF licenses this file +#to you under the Apache License, Version 2.0 (the +#"License"); you may not use this file except in compliance +#with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +#Unless required by applicable law or agreed to in writing, +#software distributed under the License is distributed on an +#"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +#KIND, either express or implied. See the License for the +#specific language governing permissions and limitations +#under the License. + +messageWithDetail = Nachricht mit Details %s! +messageWithDetail.detail = Nachricht mit sehr langen und genauen Details %s! + +messageWithoutDetail = Nachricht ohne Details aber mit Parameter %s. + +simpleMessageWithParam = Einfache Nachricht mit String Parameter %s. + +simpleMessageNoParam = Einfache Nachricht ohne Parameter. diff --git a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage_en.properties similarity index 100% rename from deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage.properties rename to deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/UserMessage_en.properties diff --git a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml index 1e21af2d0..4137cc742 100644 --- a/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml +++ b/deltaspike/modules/jsf/impl/src/test/resources/jsfMessageTest/page.xhtml @@ -25,8 +25,9 @@ xmlns:ui="http://java.sun.com/jsf/facelets"> <body> -<f:view> +<f:view locale="#{jsfMessageBackingBean.locale}"> <f:metadata> + <f:viewParam name="lang" id="lang" value="#{jsfMessageBackingBean.locale}"/> <f:event type="javax.faces.event.PreRenderViewEvent" listener="#{jsfMessageBackingBean.init}"/> </f:metadata> <div> @@ -39,6 +40,7 @@ <h:outputLabel for="valueOutput" value="the message:"/> <h:outputText id="valueOutput" value="#{jsfMessageBackingBean.someMessage}"/> <br/> + </h:form> </div> </f:view>
35135dccec1710e50329b5c4a928ea67b4ae0464
orientdb
Fixed issue on empty links--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java index 98a9812434d..fc79a70cc0c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java @@ -139,28 +139,28 @@ public Object execute(final Object... iArgs) { // SEARCH THE DESTINATION RECORD if (value instanceof String) { if (((String) value).length() == 0) - continue; - - value = "'" + value + "'"; + value = null; + else { + value = "'" + value + "'"; + result = database.command(new OSQLSynchQuery<ODocument>(cmd + value)).execute(); + + if (result == null || result.size() == 0) + // throw new OCommandExecutionException("Can't create link because the destination record was not found in class '" + // + destClass.getName() + "' and with the field '" + destField + "' equals to " + value); + value = null; + else if (result.size() > 1) + throw new OCommandExecutionException("Can't create link because multiple records was found in class '" + + destClass.getName() + "' with value " + value + " in field '" + destField + "'"); + else + value = result.get(0); + } + + // SET THE REFERENCE + doc.field(sourceField, value); + doc.save(); + + total++; } - - result = database.command(new OSQLSynchQuery<ODocument>(cmd + value)).execute(); - - if (result == null || result.size() == 0) - // throw new OCommandExecutionException("Can't create link because the destination record was not found in class '" - // + destClass.getName() + "' and with the field '" + destField + "' equals to " + value); - value = null; - else if (result.size() > 1) - throw new OCommandExecutionException("Can't create link because multiple records was found in class '" - + destClass.getName() + "' with value " + value + " in field '" + destField + "'"); - else - value = result.get(0); - - // SET THE REFERENCE - doc.field(sourceField, value); - doc.save(); - - total++; } } }
8276661ff3a71d4fcf50f72dc377f92f17f1d889
intellij-community
Ruby test runner: Statistcis can be sort by- "Tests" column--
a
https://github.com/JetBrains/intellij-community
diff --git a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/BaseColumn.java b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/BaseColumn.java new file mode 100644 index 0000000000000..ef931199a2be3 --- /dev/null +++ b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/BaseColumn.java @@ -0,0 +1,34 @@ +package org.jetbrains.plugins.ruby.testing.testunit.runner.ui.statistics; + +import org.jetbrains.plugins.ruby.testing.testunit.runner.RTestUnitTestProxy; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import com.intellij.util.ui.ColumnInfo; +import com.intellij.util.NullableFunction; + +import java.util.List; + +/** + * @author Roman Chernyatchik + */ +public abstract class BaseColumn extends ColumnInfo<RTestUnitTestProxy, String> { + private NullableFunction<List<RTestUnitTestProxy>, Object> oldSortFun = + new NullableFunction<List<RTestUnitTestProxy>, Object>() { + @Nullable + public Object fun(final List<RTestUnitTestProxy> proxies) { + BaseColumn.super.sort(proxies); + + return null; + } + }; + + public BaseColumn(String name) { + super(name); + } + + @Override + public void sort(@NotNull final List<RTestUnitTestProxy> rTestUnitTestProxies) { + //Invariant: comparator should left Total(initally at row = 0) row as uppermost element! + RTestUnitStatisticsTableModel.applySortOperation(rTestUnitTestProxies, oldSortFun); + } +} diff --git a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnDuration.java b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnDuration.java index 9b556f6a576fc..d26cb91067298 100644 --- a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnDuration.java +++ b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnDuration.java @@ -2,7 +2,6 @@ import com.intellij.ui.ColoredTableCellRenderer; import com.intellij.ui.SimpleTextAttributes; -import com.intellij.util.ui.ColumnInfo; import org.jetbrains.plugins.ruby.RBundle; import org.jetbrains.plugins.ruby.testing.testunit.runner.RTestUnitTestProxy; import org.jetbrains.plugins.ruby.testing.testunit.runner.ui.TestsPresentationUtil; @@ -13,7 +12,7 @@ /** * @author Roman Chernyatchik */ -public class ColumnDuration extends ColumnInfo<RTestUnitTestProxy, String> { +public class ColumnDuration extends BaseColumn { public ColumnDuration() { super(RBundle.message("ruby.test.runner.ui.tabs.statistics.columns.duration.title")); } @@ -22,7 +21,16 @@ public String valueOf(final RTestUnitTestProxy testProxy) { return TestsPresentationUtil.getDurationPresentation(testProxy); } - //TODO sort + //@Nullable + //public Comparator<RTestUnitTestProxy> getComparator(){ + // return new Comparator<RTestUnitTestProxy>() { + // public int compare(final RTestUnitTestProxy o1, final RTestUnitTestProxy o2) { + // //Invariant: comparator should left Total row as uppermost element! + // + // } + // }; + //} + @Override public TableCellRenderer getRenderer(final RTestUnitTestProxy proxy) { diff --git a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnResults.java b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnResults.java index 2eade62a0001e..7fbe23de85616 100644 --- a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnResults.java +++ b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnResults.java @@ -1,7 +1,6 @@ package org.jetbrains.plugins.ruby.testing.testunit.runner.ui.statistics; import com.intellij.ui.ColoredTableCellRenderer; -import com.intellij.util.ui.ColumnInfo; import org.jetbrains.annotations.NonNls; import org.jetbrains.plugins.ruby.RBundle; import org.jetbrains.plugins.ruby.testing.testunit.runner.RTestUnitTestProxy; @@ -13,7 +12,7 @@ /** * @author Roman Chernyatchik */ -public class ColumnResults extends ColumnInfo<RTestUnitTestProxy, String> { +public class ColumnResults extends BaseColumn { @NonNls private static final String UNDERFINED = "<underfined>"; ////TODO sort diff --git a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnTest.java b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnTest.java index 2c994d1fd3c82..a764ba9cea3bd 100644 --- a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnTest.java +++ b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/ColumnTest.java @@ -2,19 +2,20 @@ import com.intellij.ui.ColoredTableCellRenderer; import com.intellij.ui.SimpleTextAttributes; -import com.intellij.util.ui.ColumnInfo; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.ruby.RBundle; import org.jetbrains.plugins.ruby.testing.testunit.runner.RTestUnitTestProxy; import javax.swing.*; import javax.swing.table.TableCellRenderer; +import java.util.Comparator; /** * @author Roman Chernyatchik */ -public class ColumnTest extends ColumnInfo<RTestUnitTestProxy, String> { +public class ColumnTest extends BaseColumn { public ColumnTest() { super(RBundle.message("ruby.test.runner.ui.tabs.statistics.columns.test.title")); } @@ -24,6 +25,15 @@ public String valueOf(final RTestUnitTestProxy testProxy) { return testProxy.getPresentableName(); } + @Nullable + public Comparator<RTestUnitTestProxy> getComparator(){ + return new Comparator<RTestUnitTestProxy>() { + public int compare(final RTestUnitTestProxy o1, final RTestUnitTestProxy o2) { + return o1.getName().compareTo(o2.getName()); + } + }; + } + @Override public TableCellRenderer getRenderer(final RTestUnitTestProxy proxy) { return new TestsCellRenderer(proxy); diff --git a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModel.java b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModel.java index bdd1de2a4fccc..61784c26943d2 100644 --- a/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModel.java +++ b/plugins/ruby/src/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModel.java @@ -1,6 +1,8 @@ package org.jetbrains.plugins.ruby.testing.testunit.runner.ui.statistics; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.ui.table.TableView; +import com.intellij.util.NullableFunction; import com.intellij.util.ui.ListTableModel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -18,8 +20,20 @@ * @author Roman Chernyatchik */ public class RTestUnitStatisticsTableModel extends ListTableModel<RTestUnitTestProxy> { + private static final Logger LOG = Logger.getInstance(RTestUnitStatisticsTableModel.class.getName()); + private RTestUnitTestProxy myCurrentSuite; + private NullableFunction<List<RTestUnitTestProxy>, Object> oldReverseModelItemsFun = + new NullableFunction<List<RTestUnitTestProxy>, Object>() { + @Nullable + public Object fun(final List<RTestUnitTestProxy> proxies) { + RTestUnitStatisticsTableModel.super.reverseModelItems(proxies); + + return null; + } + }; + public RTestUnitStatisticsTableModel() { super(new ColumnTest(), new ColumnDuration(), new ColumnResults()); } @@ -47,6 +61,7 @@ public void onSelectedRequest(@Nullable final RTestUnitTestProxy proxy) { private void findAndSelectInTable(final RTestUnitTestProxy proxy, final TableView<RTestUnitTestProxy> statisticsTableView) { UIUtil.addToInvokeLater(new Runnable() { public void run() { + //TODO reimplement final String presentableName = proxy.getPresentableName(); final int rowCount = statisticsTableView.getRowCount(); final int columnnCount = statisticsTableView.getColumnCount(); @@ -61,6 +76,22 @@ public void run() { }); } + // public TestProxy getTestAt(final int rowIndex) { + // if (rowIndex < 0 || rowIndex > getItems().size()) + // return null; + // return (rowIndex == 0) ? myTest : (TestProxy)getItems().get(rowIndex - 1); + //} + // + //public int getIndexOf(final Object test) { + // if (test == myTest) + // return 0; + // for (int i = 0; i < getItems().size(); i++) { + // final Object child = getItems().get(i); + // if (child == test) return i + 1; + // } + // return -1; + //} + private void updateModel() { UIUtil.addToInvokeLater(new Runnable() { public void run() { @@ -85,6 +116,32 @@ private List<RTestUnitTestProxy> getItemsForSuite(@Nullable final RTestUnitTestP return list; } + @Override + protected void reverseModelItems(final List<RTestUnitTestProxy> rTestUnitTestProxies) { + //Invariant: comparator should left Total(initally at row = 0) row as uppermost element! + applySortOperation(rTestUnitTestProxies, oldReverseModelItemsFun); + } + + /** + * This function allow sort operation to all except first element(e.g. Total row) + * @param proxies Tests or suites + * @param sortOperation Closure + */ + protected static void applySortOperation(final List<RTestUnitTestProxy> proxies, + final NullableFunction<List<RTestUnitTestProxy>, Object> sortOperation) { + + //Invariant: comparator should left Total(initally at row = 0) row as uppermost element! + final int size = proxies.size(); + if (size > 1) { + sortOperation.fun(proxies.subList(1, size)); + } + } + + public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { + // Setting value is prevented! + LOG.assertTrue(false, "value: " + aValue + " row: " + rowIndex + " column: " + columnIndex); + } + @Nullable private RTestUnitTestProxy getCurrentSuiteFor(@Nullable final RTestUnitTestProxy proxy) { if (proxy == null) { diff --git a/plugins/ruby/testSrc/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModelTest.java b/plugins/ruby/testSrc/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModelTest.java index 3df61c2f2a3a1..48d1cc60bab16 100644 --- a/plugins/ruby/testSrc/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModelTest.java +++ b/plugins/ruby/testSrc/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/statistics/RTestUnitStatisticsTableModelTest.java @@ -1,5 +1,6 @@ package org.jetbrains.plugins.ruby.testing.testunit.runner.ui.statistics; +import com.intellij.util.ui.SortableColumnModel; import org.jetbrains.plugins.ruby.testing.testunit.runner.BaseRUnitTestsTestCase; import org.jetbrains.plugins.ruby.testing.testunit.runner.RTestUnitEventsListener; import org.jetbrains.plugins.ruby.testing.testunit.runner.RTestUnitTestProxy; @@ -227,6 +228,28 @@ public void testOnTestFinished_Other() { assertSameElements(getItems(), myRootSuite, test1, suite); } + public void testSort_ColumnTest() { + final RTestUnitTestProxy firstSuite = createSuiteProxy("K_suite1", myRootSuite); + final RTestUnitTestProxy lastSuite = createSuiteProxy("L_suite1", myRootSuite); + final RTestUnitTestProxy firstTest = createTestProxy("A_test", myRootSuite); + final RTestUnitTestProxy lastTest = createTestProxy("Z_test", myRootSuite); + + mySelectionListener.onSelectedRequest(myRootSuite); + assertOrderedEquals(getItems(), myRootSuite, firstTest, firstSuite, lastSuite, lastTest); + + //sort with another sort type + myStatisticsTableModel.sortByColumn(2, SortableColumnModel.SORT_ASCENDING); + //resort + myStatisticsTableModel.sortByColumn(0, SortableColumnModel.SORT_ASCENDING); + assertOrderedEquals(getItems(), myRootSuite, firstTest, firstSuite, lastSuite, lastTest); + //reverse + myStatisticsTableModel.sortByColumn(0, SortableColumnModel.SORT_DESCENDING); + assertOrderedEquals(getItems(), myRootSuite, lastTest, lastSuite, firstSuite, firstTest); + //direct + myStatisticsTableModel.sortByColumn(0, SortableColumnModel.SORT_ASCENDING); + assertOrderedEquals(getItems(), myRootSuite, firstTest, firstSuite, lastSuite, lastTest); + } + private List<RTestUnitTestProxy> getItems() { return myStatisticsTableModel.getItems(); }
a4c5847e42fcba0f109de1a3d312d94588249e66
camel
Fix compile error--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@707028 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/model/HandledPredicate.java b/camel-core/src/main/java/org/apache/camel/model/HandledPredicate.java index 6df5ac5bc42c0..b3aff26d228f9 100644 --- a/camel-core/src/main/java/org/apache/camel/model/HandledPredicate.java +++ b/camel-core/src/main/java/org/apache/camel/model/HandledPredicate.java @@ -61,7 +61,7 @@ public void setPredicate(Predicate predicate) { } public Predicate createPredicate(RouteContext routeContext) { - ExpressionType predicateType = getCompletePredicate(); + ExpressionType predicateType = getHandledPredicate(); if (predicateType != null && predicate == null) { predicate = predicateType.createPredicate(routeContext); }
2d9369db681af2deef27ea4cf3ef965e6c4b5159
tapiji
Remove unused icons from org.eclipse.babel.tapiji.tools.core.ui The tool's core.ui plugin contained various unused icons. Some of them were original photoshop drafs and others are relicts from prototypical enhancements. This change removes all unused and temporal icons. (cherry picked from commit 7cf7e3c7e6fb8f0c983929bda0a281a8d18efe91)
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/Folder.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Folder.png deleted file mode 100644 index a699bfc6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/Folder.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/Glossary.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/Glossary.psd deleted file mode 100644 index 9da95ac3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/Glossary.psd and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/NewGlossary.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/NewGlossary.png deleted file mode 100644 index ac91bf14..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/NewGlossary.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary.png deleted file mode 100644 index 85917f41..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary2.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary2.png deleted file mode 100644 index e02b952f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary2.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary3.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary3.png deleted file mode 100644 index e8a0b0a4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary3.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary4.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary4.png deleted file mode 100644 index 7a2ddc74..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary4.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary5.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary5.png deleted file mode 100644 index 020c1adf..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/OpenGlossary5.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16.png deleted file mode 100644 index 1b0966cb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/Resource16.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI.png deleted file mode 100644 index e274c0cd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_128.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_128.png deleted file mode 100644 index 98514e0e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_128.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_16.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_16.png deleted file mode 100644 index 73b82c2f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_16.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_32.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_32.png deleted file mode 100644 index 3984eba6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_32.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_48.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_48.png deleted file mode 100644 index 190a92e4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_48.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_64.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_64.png deleted file mode 100644 index 89988073..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/TapiJI_64.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/.cvsignore b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/.cvsignore deleted file mode 100644 index f47afba9..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -Thumbs.db diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/__.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/__.gif deleted file mode 100644 index 65167847..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/__.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/_f.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/_f.gif deleted file mode 100644 index a5f340d4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/_f.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ad.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ad.gif deleted file mode 100644 index 0b240549..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ad.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ae.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ae.gif deleted file mode 100644 index a4a82ff8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ae.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/af.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/af.gif deleted file mode 100644 index 70e1a15b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/af.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ag.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ag.gif deleted file mode 100644 index 2dc04e5e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ag.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/al.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/al.gif deleted file mode 100644 index 1384f59b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/al.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/am.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/am.gif deleted file mode 100644 index eda901ed..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/am.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ao.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ao.gif deleted file mode 100644 index 56f02bbc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ao.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/aq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/aq.gif deleted file mode 100644 index d8e99da6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/aq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ar.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ar.gif deleted file mode 100644 index 0231d503..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ar.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/at.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/at.gif deleted file mode 100644 index ecf48b9b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/at.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/au.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/au.gif deleted file mode 100644 index 77761249..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/au.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/az.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/az.gif deleted file mode 100644 index bc77ff24..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/az.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ba.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ba.gif deleted file mode 100644 index 8e4e5499..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ba.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bb.gif deleted file mode 100644 index 54928a68..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bd.gif deleted file mode 100644 index 25890b90..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/be.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/be.gif deleted file mode 100644 index f917f396..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/be.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bf.gif deleted file mode 100644 index 53afd44c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bf.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bg.gif deleted file mode 100644 index 5ce1db10..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bh.gif deleted file mode 100644 index ba39230e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bi.gif deleted file mode 100644 index ee3d6a48..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bj.gif deleted file mode 100644 index 55463ef0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/blank.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/blank.gif deleted file mode 100644 index 314b8633..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/blank.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bn.gif deleted file mode 100644 index ed11638b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bo.gif deleted file mode 100644 index f1796980..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bo.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/br.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/br.gif deleted file mode 100644 index e1069e08..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/br.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bs.gif deleted file mode 100644 index 30c32c32..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bs.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bt.gif deleted file mode 100644 index b53dddfb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bw.gif deleted file mode 100644 index d73ad712..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/by.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/by.gif deleted file mode 100644 index 3335ae02..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/by.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bz.gif deleted file mode 100644 index ec056372..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/bz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ca.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ca.gif deleted file mode 100644 index 547011ac..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ca.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cd.gif deleted file mode 100644 index 44fa4411..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cf.gif deleted file mode 100644 index 41405ce0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cf.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cg.gif deleted file mode 100644 index 00fa29c0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ch.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ch.gif deleted file mode 100644 index b0dc176e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ch.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ci.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ci.gif deleted file mode 100644 index b1167c0d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ci.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cl.gif deleted file mode 100644 index 31dcb03e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cm.gif deleted file mode 100644 index f361dbd7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cn.gif deleted file mode 100644 index f12f17d1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/co.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/co.gif deleted file mode 100644 index d9f14e79..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/co.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cr.gif deleted file mode 100644 index 2a5f0b93..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cs.gif deleted file mode 100644 index 580d26f5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cs.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cu.gif deleted file mode 100644 index 823befcc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cv.gif deleted file mode 100644 index d21a45cb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cy.gif deleted file mode 100644 index 1a332d90..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cz.gif deleted file mode 100644 index 2faee5e1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/cz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dd.gif deleted file mode 100644 index 99eda38f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/de.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/de.gif deleted file mode 100644 index c7b28406..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/de.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dj.gif deleted file mode 100644 index 94fc2eb3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dk.gif deleted file mode 100644 index 4f01ec95..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dm.gif deleted file mode 100644 index b4fed906..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/do.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/do.gif deleted file mode 100644 index 85d7be8b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/do.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dz.gif deleted file mode 100644 index 622ff6ba..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/dz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ec.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ec.gif deleted file mode 100644 index 5d1641b1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ec.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ee.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ee.gif deleted file mode 100644 index c678c73c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ee.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eg.gif deleted file mode 100644 index a740c668..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eh.gif deleted file mode 100644 index 6a75cc3c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/er.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/er.gif deleted file mode 100644 index 71297d62..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/er.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/es.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/es.gif deleted file mode 100644 index 6dee15c1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/es.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/et.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/et.gif deleted file mode 100644 index 4188e4ff..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/et.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eu.gif deleted file mode 100644 index 45caabf2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/eu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fi.gif deleted file mode 100644 index b8311cac..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fj.gif deleted file mode 100644 index f5481b79..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fm.gif deleted file mode 100644 index 050eca09..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fr.gif deleted file mode 100644 index a2a2354d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/fr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ga.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ga.gif deleted file mode 100644 index 54fb2514..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ga.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gb.gif deleted file mode 100644 index 4ae2d0f8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gd.gif deleted file mode 100644 index 0095032c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ge.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ge.gif deleted file mode 100644 index f3927c8a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ge.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gh.gif deleted file mode 100644 index 6d3b6142..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gm.gif deleted file mode 100644 index 2ecf0b0b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gn.gif deleted file mode 100644 index 83179352..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gq.gif deleted file mode 100644 index 6c2bc475..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gr.gif deleted file mode 100644 index 1599add4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gt.gif deleted file mode 100644 index c306f25d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gw.gif deleted file mode 100644 index 6cba5901..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gy.gif deleted file mode 100644 index a4b4da97..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/gy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hk.gif deleted file mode 100644 index 230723af..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hn.gif deleted file mode 100644 index 05501572..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hr.gif deleted file mode 100644 index 893778a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ht.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ht.gif deleted file mode 100644 index e5cf7803..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ht.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hu.gif deleted file mode 100644 index 07778839..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/hu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/id.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/id.gif deleted file mode 100644 index 9fed7642..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/id.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ie.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ie.gif deleted file mode 100644 index 82ec5535..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ie.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/il.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/il.gif deleted file mode 100644 index 554a7612..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/il.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/in.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/in.gif deleted file mode 100644 index 430b37b9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/in.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/iq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/iq.gif deleted file mode 100644 index dae4d593..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/iq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ir.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ir.gif deleted file mode 100644 index 50f5432a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ir.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/is.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/is.gif deleted file mode 100644 index e9580e07..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/is.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/it.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/it.gif deleted file mode 100644 index 4256b464..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/it.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jm.gif deleted file mode 100644 index f1459feb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jo.gif deleted file mode 100644 index a9d36128..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jo.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jp.gif deleted file mode 100644 index ddad6e3b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/jp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ke.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ke.gif deleted file mode 100644 index 6e06f4a7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ke.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kg.gif deleted file mode 100644 index e47fb0f2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kh.gif deleted file mode 100644 index 31f5be16..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ki.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ki.gif deleted file mode 100644 index 9f12bb0d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ki.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/km.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/km.gif deleted file mode 100644 index 027276bf..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/km.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kn.gif deleted file mode 100644 index f690875e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kp.gif deleted file mode 100644 index 42584efa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kr.gif deleted file mode 100644 index 800c6cdd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kw.gif deleted file mode 100644 index ff083b5e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kz.gif deleted file mode 100644 index 9b13afe0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/kz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/la.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/la.gif deleted file mode 100644 index 3c6f2f15..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/la.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lb.gif deleted file mode 100644 index f3c45527..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lc.gif deleted file mode 100644 index fdcbd97f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/li.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/li.gif deleted file mode 100644 index eb9d9384..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/li.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lk.gif deleted file mode 100644 index 3aa25aa8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lr.gif deleted file mode 100644 index f54468fc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ls.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ls.gif deleted file mode 100644 index c1ad8d2f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ls.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lt.gif deleted file mode 100644 index 78447f07..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lu.gif deleted file mode 100644 index d74df5ab..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lv.gif deleted file mode 100644 index 5f7419c6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/lv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ly.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ly.gif deleted file mode 100644 index 8ca9e0a0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ly.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ma.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ma.gif deleted file mode 100644 index 3aab8cbb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ma.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mc.gif deleted file mode 100644 index c22c1717..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/md.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/md.gif deleted file mode 100644 index 4951b21a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/md.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mg.gif deleted file mode 100644 index 24281d87..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mh.gif deleted file mode 100644 index c472aee6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mk.gif deleted file mode 100644 index 88c077fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ml.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ml.gif deleted file mode 100644 index 4eb75ae1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ml.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mm.gif deleted file mode 100644 index bd378555..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mn.gif deleted file mode 100644 index de3029b3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mr.gif deleted file mode 100644 index d7cbb38a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mt.gif deleted file mode 100644 index 677969a7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mu.gif deleted file mode 100644 index d102ab7e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mv.gif deleted file mode 100644 index 69ac6863..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mw.gif deleted file mode 100644 index a0f0320b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mx.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mx.gif deleted file mode 100644 index bbcb376b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mx.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/my.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/my.gif deleted file mode 100644 index 8874751b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/my.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mz.gif deleted file mode 100644 index b63af289..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/mz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/na.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/na.gif deleted file mode 100644 index bee7072e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/na.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ne.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ne.gif deleted file mode 100644 index fc1b74b8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ne.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ng.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ng.gif deleted file mode 100644 index 43af12c9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ng.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ni.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ni.gif deleted file mode 100644 index cac0042d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ni.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nl.gif deleted file mode 100644 index c4258e62..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/no.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/no.gif deleted file mode 100644 index 873baca1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/no.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/np.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/np.gif deleted file mode 100644 index f01f2f9e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/np.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nr.gif deleted file mode 100644 index d485c4b1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nu.gif deleted file mode 100644 index 73177056..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nz.gif deleted file mode 100644 index 49f8464e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/nz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/om.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/om.gif deleted file mode 100644 index d90ca333..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/om.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pa.gif deleted file mode 100644 index cae5432f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pe.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pe.gif deleted file mode 100644 index e6cc7348..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pe.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pg.gif deleted file mode 100644 index 108204f3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ph.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ph.gif deleted file mode 100644 index b141cd81..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ph.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pk.gif deleted file mode 100644 index f612b977..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pl.gif deleted file mode 100644 index 6ff3ba6f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ps.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ps.gif deleted file mode 100644 index 71717cc9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ps.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pt.gif deleted file mode 100644 index 9bfc8ca4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pw.gif deleted file mode 100644 index 0a520911..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/pw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/py.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/py.gif deleted file mode 100644 index b52de243..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/py.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/qa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/qa.gif deleted file mode 100644 index e078e46c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/qa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ro.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ro.gif deleted file mode 100644 index 6bdbad14..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ro.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ru.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ru.gif deleted file mode 100644 index cf4d30c8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ru.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/rw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/rw.gif deleted file mode 100644 index 02cf0cb1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/rw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sa.gif deleted file mode 100644 index 4b7632ee..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sb.gif deleted file mode 100644 index eb8acc08..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sc.gif deleted file mode 100644 index 4324c21f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sd.gif deleted file mode 100644 index 2d74f622..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/se.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/se.gif deleted file mode 100644 index 9bbcb1fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/se.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sg.gif deleted file mode 100644 index b81f461e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/si.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/si.gif deleted file mode 100644 index f6afb67d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/si.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sk.gif deleted file mode 100644 index b0c4ab19..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sl.gif deleted file mode 100644 index 00d59d3b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sm.gif deleted file mode 100644 index 8d9d76b3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/__.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/__.gif deleted file mode 100644 index e077f110..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/__.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/_f.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/_f.gif deleted file mode 100644 index 06c11464..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/_f.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ad.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ad.gif deleted file mode 100644 index 578acbb7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ad.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ae.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ae.gif deleted file mode 100644 index 9e6f62a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ae.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/af.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/af.gif deleted file mode 100644 index 9fe39759..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/af.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ag.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ag.gif deleted file mode 100644 index dff85d5f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ag.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/al.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/al.gif deleted file mode 100644 index 3cd0dbc6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/al.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/am.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/am.gif deleted file mode 100644 index b5968d0e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/am.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ao.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ao.gif deleted file mode 100644 index cf5f1bb4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ao.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/aq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/aq.gif deleted file mode 100644 index 8394537d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/aq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ar.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ar.gif deleted file mode 100644 index 7101d184..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ar.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/at.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/at.gif deleted file mode 100644 index b302cb90..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/at.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/au.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/au.gif deleted file mode 100644 index 1e7d95c2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/au.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/az.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/az.gif deleted file mode 100644 index 02d9ee9b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/az.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ba.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ba.gif deleted file mode 100644 index 1007efd2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ba.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bb.gif deleted file mode 100644 index 29a51f96..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bd.gif deleted file mode 100644 index e6f4dc5e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/be.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/be.gif deleted file mode 100644 index 55ec17f4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/be.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bf.gif deleted file mode 100644 index fc26ebbf..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bf.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bg.gif deleted file mode 100644 index 04664c06..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bh.gif deleted file mode 100644 index 9dc18e6b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bi.gif deleted file mode 100644 index 6aed0376..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bj.gif deleted file mode 100644 index c4d0f869..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/blank.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/blank.gif deleted file mode 100644 index 93f91133..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/blank.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bn.gif deleted file mode 100644 index e9481fe7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bo.gif deleted file mode 100644 index f083da32..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bo.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/br.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/br.gif deleted file mode 100644 index b44b8570..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/br.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bs.gif deleted file mode 100644 index dd013c4a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bs.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bt.gif deleted file mode 100644 index c12cc451..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bw.gif deleted file mode 100644 index 0bd4935a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/by.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/by.gif deleted file mode 100644 index 495e17a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/by.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bz.gif deleted file mode 100644 index ebc5a1f2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/bz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ca.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ca.gif deleted file mode 100644 index 111f6b54..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ca.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cd.gif deleted file mode 100644 index 48a5d4b1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cf.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cf.gif deleted file mode 100644 index 82dfeb88..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cf.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cg.gif deleted file mode 100644 index bc4ce41a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ch.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ch.gif deleted file mode 100644 index c1daa8c3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ch.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ci.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ci.gif deleted file mode 100644 index 01ce79fb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ci.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cl.gif deleted file mode 100644 index 579c7377..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cm.gif deleted file mode 100644 index 5093f621..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cn.gif deleted file mode 100644 index e0644265..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/co.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/co.gif deleted file mode 100644 index ea33538a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/co.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cr.gif deleted file mode 100644 index 1c3175b4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cs.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cs.gif deleted file mode 100644 index 88b65987..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cs.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cu.gif deleted file mode 100644 index 33334341..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cv.gif deleted file mode 100644 index 9b13e53b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cy.gif deleted file mode 100644 index 249719a2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cz.gif deleted file mode 100644 index 0ae066ca..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/cz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dd.gif deleted file mode 100644 index 4a47e19e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/de.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/de.gif deleted file mode 100644 index 6cc466d3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/de.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dj.gif deleted file mode 100644 index e62e277d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dk.gif deleted file mode 100644 index f3803a0b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dm.gif deleted file mode 100644 index 69f80797..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/do.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/do.gif deleted file mode 100644 index 4b9a2695..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/do.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dz.gif deleted file mode 100644 index e88ec913..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/dz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ec.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ec.gif deleted file mode 100644 index 7060478f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ec.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ee.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ee.gif deleted file mode 100644 index 1eb10798..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ee.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eg.gif deleted file mode 100644 index 4efa2884..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eh.gif deleted file mode 100644 index 9acceed3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/er.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/er.gif deleted file mode 100644 index 30550a36..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/er.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/es.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/es.gif deleted file mode 100644 index 9d01bd4d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/es.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/et.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/et.gif deleted file mode 100644 index 7352fcaa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/et.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eu.gif deleted file mode 100644 index 1eadf213..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/eu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fi.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fi.gif deleted file mode 100644 index d61952f4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fi.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fj.gif deleted file mode 100644 index 2bcd330f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fm.gif deleted file mode 100644 index 7f5dbf18..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fr.gif deleted file mode 100644 index 5b9680b6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/fr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ga.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ga.gif deleted file mode 100644 index 10322d22..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ga.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gb.gif deleted file mode 100644 index 03a74145..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gd.gif deleted file mode 100644 index 69e2b79d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ge.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ge.gif deleted file mode 100644 index daeade34..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ge.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gh.gif deleted file mode 100644 index b1ee6cc8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gm.gif deleted file mode 100644 index 0540321d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gn.gif deleted file mode 100644 index 18c92115..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gq.gif deleted file mode 100644 index 21b35aa6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gr.gif deleted file mode 100644 index e6905195..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gt.gif deleted file mode 100644 index 5c3d0618..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gw.gif deleted file mode 100644 index 5d8901f5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gy.gif deleted file mode 100644 index 42483db9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/gy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hk.gif deleted file mode 100644 index c745c141..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hn.gif deleted file mode 100644 index e43bd5e5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hr.gif deleted file mode 100644 index a6f704ca..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ht.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ht.gif deleted file mode 100644 index 854c9698..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ht.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hu.gif deleted file mode 100644 index 04ddf9f4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/hu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/id.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/id.gif deleted file mode 100644 index dcc678e9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/id.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ie.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ie.gif deleted file mode 100644 index b82a61bf..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ie.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/il.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/il.gif deleted file mode 100644 index e53b0625..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/il.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/in.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/in.gif deleted file mode 100644 index 929e0c25..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/in.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/iq.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/iq.gif deleted file mode 100644 index f0845872..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/iq.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ir.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ir.gif deleted file mode 100644 index fbfdf319..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ir.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/is.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/is.gif deleted file mode 100644 index 3f490ab7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/is.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/it.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/it.gif deleted file mode 100644 index 5bc1bb2c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/it.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jm.gif deleted file mode 100644 index 6e97f20d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jo.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jo.gif deleted file mode 100644 index 8dfb7143..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jo.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jp.gif deleted file mode 100644 index 6ecf4ff2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/jp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ke.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ke.gif deleted file mode 100644 index 742aab84..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ke.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kg.gif deleted file mode 100644 index 88608a30..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kh.gif deleted file mode 100644 index ee7ec64b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ki.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ki.gif deleted file mode 100644 index 5eab4ed6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ki.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/km.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/km.gif deleted file mode 100644 index f529c42d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/km.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kn.gif deleted file mode 100644 index 20f55e9b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kp.gif deleted file mode 100644 index 2c99418b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kr.gif deleted file mode 100644 index 139cf5c8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kw.gif deleted file mode 100644 index 27a43e4c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kz.gif deleted file mode 100644 index 81cc714a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/kz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/la.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/la.gif deleted file mode 100644 index 86dc6af2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/la.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lb.gif deleted file mode 100644 index f39803f6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lc.gif deleted file mode 100644 index 95f6ba69..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/li.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/li.gif deleted file mode 100644 index cdfe54c6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/li.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lk.gif deleted file mode 100644 index 5486bf0b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lr.gif deleted file mode 100644 index a70179ad..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ls.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ls.gif deleted file mode 100644 index e4611d05..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ls.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lt.gif deleted file mode 100644 index eca2f152..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lu.gif deleted file mode 100644 index c8e2e76f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lv.gif deleted file mode 100644 index 8e2cabee..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/lv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ly.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ly.gif deleted file mode 100644 index b31fbec6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ly.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ma.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ma.gif deleted file mode 100644 index c9829260..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ma.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mc.gif deleted file mode 100644 index 6bd1424a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/md.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/md.gif deleted file mode 100644 index a19ff5cb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/md.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mg.gif deleted file mode 100644 index a0bed496..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mh.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mh.gif deleted file mode 100644 index b5f879a9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mh.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mk.gif deleted file mode 100644 index 776a1a6b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ml.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ml.gif deleted file mode 100644 index 7ea931ab..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ml.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mm.gif deleted file mode 100644 index 2f8adbd7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mn.gif deleted file mode 100644 index 4d812a01..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mr.gif deleted file mode 100644 index d92a4643..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mt.gif deleted file mode 100644 index aa5a7298..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mu.gif deleted file mode 100644 index 98d3bd9a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mv.gif deleted file mode 100644 index dbd75919..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mw.gif deleted file mode 100644 index 9ba7c7ba..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mx.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mx.gif deleted file mode 100644 index e5e70bb0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mx.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/my.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/my.gif deleted file mode 100644 index 4bb4e268..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/my.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mz.gif deleted file mode 100644 index fe3df698..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/mz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/na.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/na.gif deleted file mode 100644 index e4c953a4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/na.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ne.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ne.gif deleted file mode 100644 index dd616577..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ne.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ng.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ng.gif deleted file mode 100644 index 498b3d59..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ng.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ni.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ni.gif deleted file mode 100644 index b6c8e208..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ni.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nl.gif deleted file mode 100644 index 9053bfc3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/no.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/no.gif deleted file mode 100644 index 8ca359a7..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/no.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/np.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/np.gif deleted file mode 100644 index d0fd2f7a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/np.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nr.gif deleted file mode 100644 index d82bc57d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nu.gif deleted file mode 100644 index 755c1b33..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nz.gif deleted file mode 100644 index 2ebcec83..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/nz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/om.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/om.gif deleted file mode 100644 index 9984131b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/om.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pa.gif deleted file mode 100644 index 016a2274..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pe.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pe.gif deleted file mode 100644 index b8f37c68..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pe.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pg.gif deleted file mode 100644 index fffb3517..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ph.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ph.gif deleted file mode 100644 index 1b126944..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ph.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pk.gif deleted file mode 100644 index 9f5ca278..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pl.gif deleted file mode 100644 index e4252c5d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ps.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ps.gif deleted file mode 100644 index 31d1aefd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ps.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pt.gif deleted file mode 100644 index 2614c827..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pw.gif deleted file mode 100644 index 8da1b47b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/pw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/py.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/py.gif deleted file mode 100644 index 23738a4e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/py.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/qa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/qa.gif deleted file mode 100644 index b4f9f55e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/qa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ro.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ro.gif deleted file mode 100644 index 94c6ade2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ro.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ru.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ru.gif deleted file mode 100644 index a6e78729..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ru.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/rw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/rw.gif deleted file mode 100644 index a925bee8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/rw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sa.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sa.gif deleted file mode 100644 index afcb768a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sa.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sb.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sb.gif deleted file mode 100644 index d2f20798..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sb.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sc.gif deleted file mode 100644 index 815a8cec..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sd.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sd.gif deleted file mode 100644 index 47b2e6a4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sd.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/se.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/se.gif deleted file mode 100644 index 333f7f18..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/se.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sg.gif deleted file mode 100644 index ad264e45..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/si.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/si.gif deleted file mode 100644 index ebc6c9b6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/si.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sk.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sk.gif deleted file mode 100644 index 78e654b0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sk.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sl.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sl.gif deleted file mode 100644 index dacd1f09..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sl.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sm.gif deleted file mode 100644 index c12e13aa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sn.gif deleted file mode 100644 index c6ffb1d1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/so.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/so.gif deleted file mode 100644 index 7bec9284..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/so.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sr.gif deleted file mode 100644 index ba6269f9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/st.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/st.gif deleted file mode 100644 index d29916f3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/st.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/su.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/su.gif deleted file mode 100644 index c64c7b6b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/su.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sv.gif deleted file mode 100644 index 199699ea..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sy.gif deleted file mode 100644 index 56d81175..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sz.gif deleted file mode 100644 index 9a7f9aa1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/sz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/td.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/td.gif deleted file mode 100644 index be3c4e49..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/td.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tg.gif deleted file mode 100644 index d15557fa..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/th.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/th.gif deleted file mode 100644 index f6b68f6d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/th.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tj.gif deleted file mode 100644 index 26c9c6a0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tm.gif deleted file mode 100644 index 09a0f66f..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tn.gif deleted file mode 100644 index ff2ce465..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/to.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/to.gif deleted file mode 100644 index eb45eaf4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/to.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tp.gif deleted file mode 100644 index fd588323..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tr.gif deleted file mode 100644 index a8d150a4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tt.gif deleted file mode 100644 index bbf1729b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tv.gif deleted file mode 100644 index df58585d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tw.gif deleted file mode 100644 index 01f360e5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tz.gif deleted file mode 100644 index ae33cb9a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/tz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ua.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ua.gif deleted file mode 100644 index 1666575a..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ua.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ug.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ug.gif deleted file mode 100644 index 6a8f9df8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ug.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/un.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/un.gif deleted file mode 100644 index 683897e4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/un.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/us.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/us.gif deleted file mode 100644 index 12739673..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/us.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uy.gif deleted file mode 100644 index 2339df56..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uz.gif deleted file mode 100644 index 96d13fd9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/uz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/va.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/va.gif deleted file mode 100644 index 2e4757ec..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/va.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vc.gif deleted file mode 100644 index 5e2edfb1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ve.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ve.gif deleted file mode 100644 index f4d14918..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ve.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vn.gif deleted file mode 100644 index 527ab1e5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vu.gif deleted file mode 100644 index 38dca348..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/vu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ws.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ws.gif deleted file mode 100644 index af159f3c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ws.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ya.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ya.gif deleted file mode 100644 index 07bad2d4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ya.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye.gif deleted file mode 100644 index b5fbb0f5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye0.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye0.gif deleted file mode 100644 index aa1942ee..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/ye0.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/yu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/yu.gif deleted file mode 100644 index d127d277..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/yu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/za.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/za.gif deleted file mode 100644 index 9554d129..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/za.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zm.gif deleted file mode 100644 index ff76b8dd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zw.gif deleted file mode 100644 index 571bac88..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/small/zw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sn.gif deleted file mode 100644 index 1a541741..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/so.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/so.gif deleted file mode 100644 index 7f1dba35..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/so.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sr.gif deleted file mode 100644 index de781c13..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/st.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/st.gif deleted file mode 100644 index cd9036fb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/st.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/su.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/su.gif deleted file mode 100644 index 23e162a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/su.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sv.gif deleted file mode 100644 index bef488e2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sy.gif deleted file mode 100644 index a3a53cd4..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sz.gif deleted file mode 100644 index b3a20ba5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/sz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/td.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/td.gif deleted file mode 100644 index 3ccc8dff..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/td.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tg.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tg.gif deleted file mode 100644 index 674e68f0..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tg.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/th.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/th.gif deleted file mode 100644 index 83318c0c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/th.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tj.gif deleted file mode 100644 index 1f44255c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tm.gif deleted file mode 100644 index a603afd2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tn.gif deleted file mode 100644 index 083238da..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/to.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/to.gif deleted file mode 100644 index 603aa8e3..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/to.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tp.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tp.gif deleted file mode 100644 index 40599d56..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tp.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tr.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tr.gif deleted file mode 100644 index 2eac7305..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tr.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tt.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tt.gif deleted file mode 100644 index f7154195..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tt.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tv.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tv.gif deleted file mode 100644 index 9b018e87..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tv.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tw.gif deleted file mode 100644 index 57a04829..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tz.gif deleted file mode 100644 index 6d28d408..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/tz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ua.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ua.gif deleted file mode 100644 index bebd6705..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ua.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ug.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ug.gif deleted file mode 100644 index 151e3037..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ug.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/un.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/un.gif deleted file mode 100644 index 135b5281..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/un.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/us.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/us.gif deleted file mode 100644 index 850094ea..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/us.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uy.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uy.gif deleted file mode 100644 index 4d129fc5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uy.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uz.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uz.gif deleted file mode 100644 index d9cc88eb..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/uz.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/va.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/va.gif deleted file mode 100644 index 5db146d6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/va.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vc.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vc.gif deleted file mode 100644 index 6519018d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vc.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ve.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ve.gif deleted file mode 100644 index 4abf999b..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ve.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vn.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vn.gif deleted file mode 100644 index e7d1e5b9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vn.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vu.gif deleted file mode 100644 index f8736a18..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/vu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ws.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ws.gif deleted file mode 100644 index b2bc2f76..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ws.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ya.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ya.gif deleted file mode 100644 index 91536134..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ya.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye.gif deleted file mode 100644 index f183847c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye0.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye0.gif deleted file mode 100644 index b9c28b30..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/ye0.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/yu.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/yu.gif deleted file mode 100644 index c91bf1ef..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/yu.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/za.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/za.gif deleted file mode 100644 index 8579793e..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/za.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zm.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zm.gif deleted file mode 100644 index fc686bb8..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zm.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zw.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zw.gif deleted file mode 100644 index 9821c41c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/countries/zw.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/duplicate.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/duplicate.gif deleted file mode 100644 index 3366a273..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/duplicate.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/entry.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/entry.gif deleted file mode 100644 index 442539fc..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/entry.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/file_obj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/file_obj.gif deleted file mode 100644 index 7ccc6a70..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/file_obj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/fldr_obj.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/fldr_obj.gif deleted file mode 100644 index 51e703b1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/fldr_obj.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/icon_new_memory_view.png b/org.eclipse.babel.tapiji.tools.core.ui/icons/icon_new_memory_view.png deleted file mode 100644 index 2ceac484..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/icon_new_memory_view.png and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/keyCommented.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/keyCommented.gif deleted file mode 100644 index 869eb6bd..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/keyCommented.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/keyNone.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/keyNone.gif deleted file mode 100644 index dd1bd7c2..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/keyNone.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int1.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int1.gif deleted file mode 100644 index a1b17488..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int1.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int2.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int2.gif deleted file mode 100644 index 98a2dbc6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/no_int2.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.gif deleted file mode 100644 index d26afe53..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.psd b/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.psd deleted file mode 100644 index eaa418a1..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/original/entry.psd and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/read_only.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/read_only.gif deleted file mode 100644 index dde3cbd6..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/read_only.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/sample.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/sample.gif deleted file mode 100644 index 34fb3c9d..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/sample.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/similar.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/similar.gif deleted file mode 100644 index 74cf98e5..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/similar.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/toc_open.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/toc_open.gif deleted file mode 100644 index 9e665d5c..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/toc_open.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/warning.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/warning.gif deleted file mode 100644 index 801a1f81..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/warning.gif and /dev/null differ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/icons/warningGrey.gif b/org.eclipse.babel.tapiji.tools.core.ui/icons/warningGrey.gif deleted file mode 100644 index e11147e9..00000000 Binary files a/org.eclipse.babel.tapiji.tools.core.ui/icons/warningGrey.gif and /dev/null differ
78930691ca6b664a07a6995c60bb8238cf7edf96
hbase
HBASE-9999 Add support for small reverse scan--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1573949 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hbase
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java index 0290dcac922a..574d937b46d8 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java @@ -39,7 +39,6 @@ import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos; import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException; import org.apache.hadoop.hbase.util.Bytes; -import org.apache.hadoop.hbase.util.ExceptionUtil; /** * Implements the scanner interface for the HBase client. diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java index a980ec968f41..dd20f0a4984b 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java @@ -153,21 +153,23 @@ private boolean nextScanner(int nbRows, final boolean done, LOG.trace("Advancing internal small scanner to startKey at '" + Bytes.toStringBinary(localStartKey) + "'"); } - smallScanCallable = getSmallScanCallable(localStartKey, cacheNum); + smallScanCallable = getSmallScanCallable( + scan, getConnection(), getTable(), localStartKey, cacheNum); if (this.scanMetrics != null && skipRowOfFirstResult == null) { this.scanMetrics.countOfRegions.incrementAndGet(); } return true; } - private RegionServerCallable<Result[]> getSmallScanCallable( + static RegionServerCallable<Result[]> getSmallScanCallable( + final Scan sc, HConnection connection, TableName table, byte[] localStartKey, final int cacheNum) { - this.scan.setStartRow(localStartKey); + sc.setStartRow(localStartKey); RegionServerCallable<Result[]> callable = new RegionServerCallable<Result[]>( - getConnection(), getTable(), scan.getStartRow()) { + connection, table, sc.getStartRow()) { public Result[] call(int callTimeout) throws IOException { ScanRequest request = RequestConverter.buildScanRequest(getLocation() - .getRegionInfo().getRegionName(), scan, cacheNum, true); + .getRegionInfo().getRegionName(), sc, cacheNum, true); PayloadCarryingRpcController controller = new PayloadCarryingRpcController(); controller.setPriority(getTableName()); controller.setCallTimeout(callTimeout); diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HTable.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HTable.java index f3d443670191..624389225cac 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HTable.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HTable.java @@ -742,15 +742,24 @@ public ResultScanner getScanner(final Scan scan) throws IOException { if (scan.getCaching() <= 0) { scan.setCaching(getScannerCaching()); } - if (scan.isSmall() && !scan.isReversed()) { + + if (scan.isReversed()) { + if (scan.isSmall()) { + return new ClientSmallReversedScanner(getConfiguration(), scan, getName(), + this.connection); + } else { + return new ReversedClientScanner(getConfiguration(), scan, getName(), + this.connection); + } + } + + if (scan.isSmall()) { return new ClientSmallScanner(getConfiguration(), scan, getName(), - this.connection); - } else if (scan.isReversed()) { - return new ReversedClientScanner(getConfiguration(), scan, getName(), - this.connection); + this.connection, this.rpcCallerFactory); + } else { + return new ClientScanner(getConfiguration(), scan, + getName(), this.connection); } - return new ClientScanner(getConfiguration(), scan, - getName(), this.connection); } /** diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java index 470ffa132fc6..d6e17ae8f552 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java @@ -29,6 +29,7 @@ import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.ExceptionUtil; /** * A reversed client scanner which support backward scanning @@ -114,6 +115,7 @@ protected boolean nextScanner(int nbRows, final boolean done) this.scanMetrics.countOfRegions.incrementAndGet(); } } catch (IOException e) { + ExceptionUtil.rethrowIfInterrupt(e); close(); throw e; } @@ -151,7 +153,7 @@ protected boolean checkScanStopRow(final byte[] startKey) { * @param row * @return a new byte array which is the closest front row of the specified one */ - private byte[] createClosestRowBefore(byte[] row) { + protected byte[] createClosestRowBefore(byte[] row) { if (row == null) { throw new IllegalArgumentException("The passed row is empty"); } diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedScannerCallable.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedScannerCallable.java index 487777fc8f3d..a974b01c6f69 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedScannerCallable.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedScannerCallable.java @@ -70,7 +70,7 @@ public void prepare(boolean reload) throws IOException { this.location = connection.getRegionLocation(tableName, row, reload); if (this.location == null) { throw new IOException("Failed to find location, tableName=" - + tableName + ", row=" + Bytes.toString(row) + ", reload=" + + tableName + ", row=" + Bytes.toStringBinary(row) + ", reload=" + reload); } } else { diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java index 33a18fb2c407..1520a65a1743 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java @@ -6061,4 +6061,170 @@ public void testReversedScanUnderMultiRegions() throws Exception { assertEquals(insertNum, count); table.close(); } + + + /** + * Tests reversed scan under multi regions + */ + @Test + public void testSmallReversedScanUnderMultiRegions() throws Exception { + // Test Initialization. + byte[] TABLE = Bytes.toBytes("testSmallReversedScanUnderMultiRegions"); + byte[][] splitRows = new byte[][]{ + Bytes.toBytes("000"), Bytes.toBytes("002"), Bytes.toBytes("004"), + Bytes.toBytes("006"), Bytes.toBytes("008"), Bytes.toBytes("010")}; + HTable table = TEST_UTIL.createTable(TABLE, FAMILY, splitRows); + TEST_UTIL.waitUntilAllRegionsAssigned(table.getName()); + + assertEquals(splitRows.length + 1, table.getRegionLocations().size()); + for (byte[] splitRow : splitRows) { + Put put = new Put(splitRow); + put.add(FAMILY, QUALIFIER, VALUE); + table.put(put); + + byte[] nextRow = Bytes.copy(splitRow); + nextRow[nextRow.length - 1]++; + + put = new Put(nextRow); + put.add(FAMILY, QUALIFIER, VALUE); + table.put(put); + } + + // scan forward + ResultScanner scanner = table.getScanner(new Scan()); + int count = 0; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + } + assertEquals(12, count); + + reverseScanTest(table, false); + reverseScanTest(table, true); + + table.close(); + } + + private void reverseScanTest(HTable table, boolean small) throws IOException { + // scan backward + Scan scan = new Scan(); + scan.setReversed(true); + ResultScanner scanner = table.getScanner(scan); + int count = 0; + byte[] lastRow = null; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + byte[] thisRow = r.getRow(); + if (lastRow != null) { + assertTrue("Error scan order, last row= " + Bytes.toString(lastRow) + + ",this row=" + Bytes.toString(thisRow), + Bytes.compareTo(thisRow, lastRow) < 0); + } + lastRow = thisRow; + } + assertEquals(12, count); + + scan = new Scan(); + scan.setSmall(small); + scan.setReversed(true); + scan.setStartRow(Bytes.toBytes("002")); + scanner = table.getScanner(scan); + count = 0; + lastRow = null; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + byte[] thisRow = r.getRow(); + if (lastRow != null) { + assertTrue("Error scan order, last row= " + Bytes.toString(lastRow) + + ",this row=" + Bytes.toString(thisRow), + Bytes.compareTo(thisRow, lastRow) < 0); + } + lastRow = thisRow; + } + assertEquals(3, count); // 000 001 002 + + scan = new Scan(); + scan.setSmall(small); + scan.setReversed(true); + scan.setStartRow(Bytes.toBytes("002")); + scan.setStopRow(Bytes.toBytes("000")); + scanner = table.getScanner(scan); + count = 0; + lastRow = null; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + byte[] thisRow = r.getRow(); + if (lastRow != null) { + assertTrue("Error scan order, last row= " + Bytes.toString(lastRow) + + ",this row=" + Bytes.toString(thisRow), + Bytes.compareTo(thisRow, lastRow) < 0); + } + lastRow = thisRow; + } + assertEquals(2, count); // 001 002 + + scan = new Scan(); + scan.setSmall(small); + scan.setReversed(true); + scan.setStartRow(Bytes.toBytes("001")); + scanner = table.getScanner(scan); + count = 0; + lastRow = null; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + byte[] thisRow = r.getRow(); + if (lastRow != null) { + assertTrue("Error scan order, last row= " + Bytes.toString(lastRow) + + ",this row=" + Bytes.toString(thisRow), + Bytes.compareTo(thisRow, lastRow) < 0); + } + lastRow = thisRow; + } + assertEquals(2, count); // 000 001 + + scan = new Scan(); + scan.setSmall(small); + scan.setReversed(true); + scan.setStartRow(Bytes.toBytes("000")); + scanner = table.getScanner(scan); + count = 0; + lastRow = null; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + byte[] thisRow = r.getRow(); + if (lastRow != null) { + assertTrue("Error scan order, last row= " + Bytes.toString(lastRow) + + ",this row=" + Bytes.toString(thisRow), + Bytes.compareTo(thisRow, lastRow) < 0); + } + lastRow = thisRow; + } + assertEquals(1, count); // 000 + + scan = new Scan(); + scan.setSmall(small); + scan.setReversed(true); + scan.setStartRow(Bytes.toBytes("006")); + scan.setStopRow(Bytes.toBytes("002")); + scanner = table.getScanner(scan); + count = 0; + lastRow = null; + for (Result r : scanner) { + assertTrue(!r.isEmpty()); + count++; + byte[] thisRow = r.getRow(); + if (lastRow != null) { + assertTrue("Error scan order, last row= " + Bytes.toString(lastRow) + + ",this row=" + Bytes.toString(thisRow), + Bytes.compareTo(thisRow, lastRow) < 0); + } + lastRow = thisRow; + } + assertEquals(4, count); // 003 004 005 006 + } }
d585683650c8e2664b86ccc0aeef080d3b417d1d
restlet-framework-java
ServerResource now supports empty POST and PUT- requests.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index ea4508a850..79ade3d4bf 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -16,6 +16,8 @@ Changes log media type. - ServerResource now rejects unconvertable parameters with a 415 status. + - ServerResource now supports empty POST and PUT requests. + - Bugs fixed - Fixed issue in DomRepresentation with createTransformer() method. Fix contributed by Remi Dewitte. diff --git a/modules/org.restlet/src/org/restlet/resource/ServerResource.java b/modules/org.restlet/src/org/restlet/resource/ServerResource.java index b20fa02cd3..3441e8d3d4 100644 --- a/modules/org.restlet/src/org/restlet/resource/ServerResource.java +++ b/modules/org.restlet/src/org/restlet/resource/ServerResource.java @@ -130,7 +130,7 @@ protected Representation delete() throws ResourceException { AnnotationInfo annotationInfo = getAnnotation(Method.DELETE); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } @@ -276,7 +276,7 @@ private RepresentationInfo doGetInfo() throws ResourceException { AnnotationInfo annotationInfo = getAnnotation(Method.GET); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { result = getInfo(); } @@ -347,7 +347,7 @@ protected Representation doHandle() throws ResourceException { AnnotationInfo annotationInfo = getAnnotation(method); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } @@ -360,74 +360,6 @@ protected Representation doHandle() throws ResourceException { return result; } - /** - * Effectively handle a call using an annotated method. - * - * @param annotationInfo - * The annotation descriptor. - * @return The response entity. - * @throws ResourceException - */ - private Representation doHandle(AnnotationInfo annotationInfo) - throws ResourceException { - Representation result = null; - ConverterService cs = getConverterService(); - Class<?>[] parameterTypes = annotationInfo.getJavaInputTypes(); - List<Object> parameters = null; - Object resultObject = null; - Object parameter = null; - - try { - if (parameterTypes.length > 0) { - parameters = new ArrayList<Object>(); - - for (Class<?> parameterType : parameterTypes) { - if (getRequestEntity() != null) { - try { - parameter = cs.toObject(getRequestEntity(), - parameterType, this); - - if (parameter != null) { - parameters.add(parameter); - } else { - throw new ResourceException( - Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); - } - } catch (IOException e) { - e.printStackTrace(); - parameters.add(null); - } - } else { - parameters.add(null); - } - } - - // Actually invoke the method - resultObject = annotationInfo.getJavaMethod().invoke(this, - parameters.toArray()); - } else { - // Actually invoke the method - resultObject = annotationInfo.getJavaMethod().invoke(this); - } - } catch (IllegalArgumentException e) { - throw new ResourceException(e); - } catch (IllegalAccessException e) { - throw new ResourceException(e); - } catch (InvocationTargetException e) { - if (e.getTargetException() instanceof ResourceException) { - throw (ResourceException) e.getTargetException(); - } - - throw new ResourceException(e.getTargetException()); - } - - if (resultObject != null) { - result = cs.toRepresentation(resultObject); - } - - return result; - } - /** * Effectively handles a call with content negotiation of the response * entity using an annotated method. @@ -435,31 +367,32 @@ private Representation doHandle(AnnotationInfo annotationInfo) * @param annotationInfo * The annotation descriptor. * @param variant - * The response variant expected. + * The response variant expected (can be null). * @return The response entity. * @throws ResourceException */ private Representation doHandle(AnnotationInfo annotationInfo, Variant variant) throws ResourceException { Representation result = null; + Class<?>[] parameterTypes = annotationInfo.getJavaInputTypes(); ConverterService cs = getConverterService(); - Object resultObject = null; + // Invoke the annoted method and get the resulting object. + Object resultObject = null; try { - if ((annotationInfo.getJavaInputTypes() != null) - && (annotationInfo.getJavaInputTypes().length > 0)) { + if (parameterTypes.length > 0) { List<Object> parameters = new ArrayList<Object>(); Object parameter = null; - for (Class<?> param : annotationInfo.getJavaInputTypes()) { - if (Variant.class.equals(param)) { + for (Class<?> parameterType : parameterTypes) { + if (Variant.class.equals(parameterType)) { parameters.add(variant); } else { - if (getRequestEntity().isAvailable()) { + if (getRequestEntity() != null + && getRequestEntity().isAvailable()) { try { parameter = cs.toObject(getRequestEntity(), - param, this); - + parameterType, this); } catch (IOException e) { parameter = null; } @@ -481,8 +414,6 @@ private Representation doHandle(AnnotationInfo annotationInfo, } else { resultObject = annotationInfo.getJavaMethod().invoke(this); } - - result = cs.toRepresentation(resultObject, variant, this); } catch (IllegalArgumentException e) { throw new ResourceException(e); } catch (IllegalAccessException e) { @@ -495,6 +426,14 @@ private Representation doHandle(AnnotationInfo annotationInfo, throw new ResourceException(e.getTargetException()); } + if (resultObject != null) { + if (variant != null) { + result = cs.toRepresentation(resultObject, variant, this); + } else { + result = cs.toRepresentation(resultObject); + } + } + return result; } @@ -613,7 +552,7 @@ protected Representation get() throws ResourceException { AnnotationInfo annotationInfo = getAnnotation(Method.GET); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } @@ -967,7 +906,7 @@ protected Representation options() throws ResourceException { AnnotationInfo annotationInfo = getAnnotation(Method.OPTIONS); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } @@ -1029,7 +968,7 @@ protected Representation post(Representation entity) AnnotationInfo annotationInfo = getAnnotation(Method.POST); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } @@ -1096,7 +1035,7 @@ protected Representation put(Representation representation) AnnotationInfo annotationInfo = getAnnotation(Method.PUT); if (annotationInfo != null) { - result = doHandle(annotationInfo); + result = doHandle(annotationInfo, null); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); }
5f234f8fa9c8f645b6281ecb81dfe7d1a0d7284e
drools
JBRULES-527: adding primitive support for hashcode- calculation on indexing--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@7155 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/base/ClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/ClassFieldExtractor.java index 6f8fb45d3f0..ba0b65421c7 100644 --- a/drools-core/src/main/java/org/drools/base/ClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/ClassFieldExtractor.java @@ -144,4 +144,8 @@ public short getShortValue(final Object object) { public Method getNativeReadMethod() { return this.extractor.getNativeReadMethod(); } + + public int getHashCode(Object object) { + return this.extractor.getHashCode( object ); + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseBooleanClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseBooleanClassFieldExtractor.java index 8738ae1de20..aedc2991541 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseBooleanClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseBooleanClassFieldExtractor.java @@ -78,5 +78,9 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + return getBooleanValue( object ) ? 1231 : 1237; + } } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseByteClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseByteClassFieldExtractor.java index 06d5a7896c6..fa3b8dc7025 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseByteClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseByteClassFieldExtractor.java @@ -79,4 +79,7 @@ public Method getNativeReadMethod() { } } + public int getHashCode(Object object) { + return getByteValue( object ); + } } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseCharClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseCharClassFieldExtractor.java index 848749cccf5..257649cfdc6 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseCharClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseCharClassFieldExtractor.java @@ -56,4 +56,8 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + return getCharValue( object ); + } } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseDoubleClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseDoubleClassFieldExtractor.java index 4c5433cef32..5e1b41601d7 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseDoubleClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseDoubleClassFieldExtractor.java @@ -57,4 +57,10 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + long temp = Double.doubleToLongBits( getDoubleValue( object ) ); + return (int) ( temp ^ ( temp >>> 32) ); + } + } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseFloatClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseFloatClassFieldExtractor.java index 1e0932cb9dc..82f4330d633 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseFloatClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseFloatClassFieldExtractor.java @@ -57,4 +57,9 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + return Float.floatToIntBits( getFloatValue( object ) ); + } + } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseIntClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseIntClassFieldExtractor.java index 606029c6a39..28e24f6fde8 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseIntClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseIntClassFieldExtractor.java @@ -57,4 +57,8 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + return getIntValue( object ); + } } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseLongClassFieldExtractors.java b/drools-core/src/main/java/org/drools/base/extractors/BaseLongClassFieldExtractors.java index 8adeb2a55f6..aafa76cd1ad 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseLongClassFieldExtractors.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseLongClassFieldExtractors.java @@ -57,4 +57,10 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + long temp = getLongValue( object ); + return (int) ( temp ^ ( temp >>> 32 )); + } + } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseObjectClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseObjectClassFieldExtractor.java index b3a0a3fa11d..dff24f0b717 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseObjectClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseObjectClassFieldExtractor.java @@ -104,4 +104,9 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + return getValue( object ).hashCode(); + } + } diff --git a/drools-core/src/main/java/org/drools/base/extractors/BaseShortClassFieldExtractor.java b/drools-core/src/main/java/org/drools/base/extractors/BaseShortClassFieldExtractor.java index 5d94f12ef7f..db09964d2b2 100755 --- a/drools-core/src/main/java/org/drools/base/extractors/BaseShortClassFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/base/extractors/BaseShortClassFieldExtractor.java @@ -57,4 +57,8 @@ public Method getNativeReadMethod() { throw new RuntimeDroolsException("This is a bug. Please report to development team: "+e.getMessage(), e); } } + + public int getHashCode(Object object) { + return getShortValue( object ); + } } diff --git a/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java b/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java index a542587afc8..e63b1e71ca4 100644 --- a/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java +++ b/drools-core/src/main/java/org/drools/common/EqualityAssertMapComparator.java @@ -71,6 +71,6 @@ public int compare(final Object o1, } public String toString() { - return "identity"; + return "equality"; } } diff --git a/drools-core/src/main/java/org/drools/facttemplates/FactTemplateFieldExtractor.java b/drools-core/src/main/java/org/drools/facttemplates/FactTemplateFieldExtractor.java index 7388717eed3..33725a3f10a 100644 --- a/drools-core/src/main/java/org/drools/facttemplates/FactTemplateFieldExtractor.java +++ b/drools-core/src/main/java/org/drools/facttemplates/FactTemplateFieldExtractor.java @@ -76,4 +76,7 @@ public Method getNativeReadMethod() { } } + public int getHashCode(Object object) { + return getValue( object ).hashCode(); + } } diff --git a/drools-core/src/main/java/org/drools/rule/Declaration.java b/drools-core/src/main/java/org/drools/rule/Declaration.java index 65b1013bb63..732d91a3c8e 100644 --- a/drools-core/src/main/java/org/drools/rule/Declaration.java +++ b/drools-core/src/main/java/org/drools/rule/Declaration.java @@ -188,6 +188,9 @@ public boolean getBooleanValue(Object object) { return this.extractor.getBooleanValue( object ); } + public int getHashCode(Object object) { + return this.extractor.getHashCode( object ); + } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public String toString() { diff --git a/drools-core/src/main/java/org/drools/spi/ColumnExtractor.java b/drools-core/src/main/java/org/drools/spi/ColumnExtractor.java index 5a2ad1be769..cf2f13c5e68 100644 --- a/drools-core/src/main/java/org/drools/spi/ColumnExtractor.java +++ b/drools-core/src/main/java/org/drools/spi/ColumnExtractor.java @@ -124,4 +124,7 @@ public Method getNativeReadMethod() { } } + public int getHashCode(Object object) { + return getValue( object ).hashCode(); + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/spi/Extractor.java b/drools-core/src/main/java/org/drools/spi/Extractor.java index 98d442cff4a..929c396cf82 100644 --- a/drools-core/src/main/java/org/drools/spi/Extractor.java +++ b/drools-core/src/main/java/org/drools/spi/Extractor.java @@ -48,5 +48,7 @@ public interface Extractor public Class getExtractToClass(); public Method getNativeReadMethod(); + + public int getHashCode(Object object); } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java index 3477b42d3fe..a815e2ab06d 100644 --- a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java +++ b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java @@ -415,15 +415,13 @@ public SingleIndex(final FieldIndex[] indexes, public int hashCodeOf(final Object object) { int hashCode = this.startResult; - final Object value = this.extractor.getValue( object ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.extractor.getHashCode( object ); return this.comparator.rehash( hashCode ); } public int hashCodeOf(final ReteTuple tuple) { int hashCode = this.startResult; - final Object value = this.declaration.getValue( tuple.get( this.declaration ).getObject() ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.declaration.getHashCode( tuple.get( this.declaration ).getObject() ); return this.comparator.rehash( hashCode ); } @@ -479,11 +477,11 @@ public DoubleCompositeIndex(final FieldIndex[] indexes, public int hashCodeOf(final Object object) { int hashCode = this.startResult; - Object value = this.index0.extractor.getValue( object ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + int hash = this.index0.extractor.getHashCode( object ); + hashCode = TupleIndexHashTable.PRIME * hashCode + hash; - value = this.index1.extractor.getValue( object ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hash = this.index1.extractor.getHashCode( object ); + hashCode = TupleIndexHashTable.PRIME * hashCode + hash; return this.comparator.rehash( hashCode ); } @@ -491,11 +489,9 @@ public int hashCodeOf(final Object object) { public int hashCodeOf(final ReteTuple tuple) { int hashCode = this.startResult; - Object value = this.index0.declaration.getValue( tuple.get( this.index0.declaration ).getObject() ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index0.declaration.getHashCode( tuple.get( this.index0.declaration ).getObject() ); - value = this.index1.declaration.getValue( tuple.get( this.index1.declaration ).getObject() ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.declaration.getHashCode( tuple.get( this.index1.declaration ).getObject() ); return this.comparator.rehash( hashCode ); } @@ -590,14 +586,9 @@ public TripleCompositeIndex(final FieldIndex[] indexes, public int hashCodeOf(final Object object) { int hashCode = this.startResult; - Object value = this.index0.extractor.getValue( object ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); - - value = this.index1.extractor.getValue( object ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); - - value = this.index2.extractor.getValue( object ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index0.extractor.getHashCode( object );; + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.extractor.getHashCode( object );; + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index2.extractor.getHashCode( object );; return this.comparator.rehash( hashCode ); } @@ -605,14 +596,9 @@ public int hashCodeOf(final Object object) { public int hashCodeOf(final ReteTuple tuple) { int hashCode = this.startResult; - Object value = this.index0.declaration.getValue( tuple.get( this.index0.declaration ).getObject() ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); - - value = this.index1.declaration.getValue( tuple.get( this.index1.declaration ).getObject() ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); - - value = this.index2.declaration.getValue( tuple.get( this.index2.declaration ).getObject() ); - hashCode += TupleIndexHashTable.PRIME * hashCode + ((value == null) ? 0 : value.hashCode()); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index0.declaration.getHashCode( tuple.get( this.index0.declaration ).getObject() ); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.declaration.getHashCode( tuple.get( this.index1.declaration ).getObject() ); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index2.declaration.getHashCode( tuple.get( this.index2.declaration ).getObject() ); return this.comparator.rehash( hashCode ); } diff --git a/drools-core/src/test/java/org/drools/reteoo/CompositeObjectSinkAdapterTest.java b/drools-core/src/test/java/org/drools/reteoo/CompositeObjectSinkAdapterTest.java index 7339f0b1893..30bd2498b5a 100644 --- a/drools-core/src/test/java/org/drools/reteoo/CompositeObjectSinkAdapterTest.java +++ b/drools-core/src/test/java/org/drools/reteoo/CompositeObjectSinkAdapterTest.java @@ -244,6 +244,10 @@ public ValueType getValueType() { // Auto-generated method stub return null; } + + public int getHashCode(Object object) { + return 0; + } }
62c048660bd3d4062e56646ae7c17b9a2ef15614
hbase
HBASE-10885 Support visibility expressions on- Deletes (Ram)--
a
https://github.com/apache/hbase
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityConstants.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityConstants.java index 301161c1c8ba..bc84207b5cd2 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityConstants.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityConstants.java @@ -40,4 +40,13 @@ public final class VisibilityConstants { /** Qualifier for the internal storage table for visibility labels */ public static final byte[] LABEL_QUALIFIER = new byte[1]; + /** + * Visibility serialization version format. It indicates the visibility labels + * are sorted based on ordinal + **/ + public static final byte VISIBILITY_SERIALIZATION_VERSION = 1; + /** Byte representation of the visibility_serialization_version **/ + public static final byte[] SORTED_ORDINAL_SERIALIZATION_FORMAT = Bytes + .toBytes(VISIBILITY_SERIALIZATION_VERSION); + } diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java index 811de1060886..376e07347bf2 100644 --- a/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java @@ -428,6 +428,14 @@ public static boolean isDeleteFamilyVersion(final Cell cell) { return cell.getTypeByte() == Type.DeleteFamilyVersion.getCode(); } + public static boolean isDeleteColumns(final Cell cell) { + return cell.getTypeByte() == Type.DeleteColumn.getCode(); + } + + public static boolean isDeleteColumnVersion(final Cell cell) { + return cell.getTypeByte() == Type.Delete.getCode(); + } + /** * * @return True if this cell is a delete family or column type. diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/TagType.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/TagType.java index 6c43c7802670..68018c4f4cd5 100644 --- a/hbase-common/src/main/java/org/apache/hadoop/hbase/TagType.java +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/TagType.java @@ -27,4 +27,5 @@ public final class TagType { public static final byte ACL_TAG_TYPE = (byte) 1; public static final byte VISIBILITY_TAG_TYPE = (byte) 2; public static final byte LOG_REPLAY_TAG_TYPE = (byte) 3; + public static final byte VISIBILITY_EXP_SERIALIZATION_TAG_TYPE = (byte)4; } diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LabelExpander.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LabelExpander.java index 0c133f6f6b6d..60a3bc3767e7 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LabelExpander.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LabelExpander.java @@ -25,6 +25,7 @@ import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -38,10 +39,12 @@ import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.io.util.StreamUtils; import org.apache.hadoop.hbase.mapreduce.ImportTsv.TsvParser.BadTsvLineException; import org.apache.hadoop.hbase.security.visibility.Authorizations; import org.apache.hadoop.hbase.security.visibility.ExpressionExpander; import org.apache.hadoop.hbase.security.visibility.ExpressionParser; +import org.apache.hadoop.hbase.security.visibility.InvalidLabelException; import org.apache.hadoop.hbase.security.visibility.ParseException; import org.apache.hadoop.hbase.security.visibility.VisibilityUtils; import org.apache.hadoop.hbase.security.visibility.expression.ExpressionNode; @@ -49,7 +52,6 @@ import org.apache.hadoop.hbase.security.visibility.expression.NonLeafExpressionNode; import org.apache.hadoop.hbase.security.visibility.expression.Operator; import org.apache.hadoop.hbase.util.Bytes; -import org.apache.hadoop.io.WritableUtils; /** * An utility class that helps the mapper and reducers used with visibility to @@ -71,32 +73,37 @@ public LabelExpander(Configuration conf) { // TODO : The code repeats from that in Visibility Controller.. Refactoring // may be needed - public List<Tag> createVisibilityTags(String visibilityLabelsExp) throws IOException, - BadTsvLineException { + private List<Tag> createVisibilityTags(String visibilityLabelsExp) throws IOException, + ParseException, InvalidLabelException { ExpressionNode node = null; - try { - node = parser.parse(visibilityLabelsExp); - } catch (ParseException e) { - throw new BadTsvLineException(e.getMessage()); - } + node = parser.parse(visibilityLabelsExp); node = expander.expand(node); List<Tag> tags = new ArrayList<Tag>(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); + List<Integer> labelOrdinals = new ArrayList<Integer>(); + // We will be adding this tag before the visibility tags and the presence of + // this + // tag indicates we are supporting deletes with cell visibility + tags.add(VisibilityUtils.VIS_SERIALIZATION_TAG); if (node.isSingleNode()) { - writeLabelOrdinalsToStream(node, dos); + getLabelOrdinals(node, labelOrdinals); + writeLabelOrdinalsToStream(labelOrdinals, dos); tags.add(new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray())); baos.reset(); } else { NonLeafExpressionNode nlNode = (NonLeafExpressionNode) node; if (nlNode.getOperator() == Operator.OR) { for (ExpressionNode child : nlNode.getChildExps()) { - writeLabelOrdinalsToStream(child, dos); + getLabelOrdinals(child, labelOrdinals); + writeLabelOrdinalsToStream(labelOrdinals, dos); tags.add(new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray())); baos.reset(); + labelOrdinals.clear(); } } else { - writeLabelOrdinalsToStream(nlNode, dos); + getLabelOrdinals(nlNode, labelOrdinals); + writeLabelOrdinalsToStream(labelOrdinals, dos); tags.add(new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray())); baos.reset(); } @@ -104,34 +111,38 @@ public List<Tag> createVisibilityTags(String visibilityLabelsExp) throws IOExcep return tags; } - private void writeLabelOrdinalsToStream(ExpressionNode node, DataOutputStream dos) - throws IOException, BadTsvLineException { + private void writeLabelOrdinalsToStream(List<Integer> labelOrdinals, DataOutputStream dos) + throws IOException { + Collections.sort(labelOrdinals); + for (Integer labelOrdinal : labelOrdinals) { + StreamUtils.writeRawVInt32(dos, labelOrdinal); + } + } + + private void getLabelOrdinals(ExpressionNode node, List<Integer> labelOrdinals) + throws IOException, InvalidLabelException { if (node.isSingleNode()) { String identifier = null; int labelOrdinal = 0; if (node instanceof LeafExpressionNode) { identifier = ((LeafExpressionNode) node).getIdentifier(); - if (this.labels.get(identifier) != null) { - labelOrdinal = this.labels.get(identifier); - } + labelOrdinal = this.labels.get(identifier); } else { // This is a NOT node. LeafExpressionNode lNode = (LeafExpressionNode) ((NonLeafExpressionNode) node) .getChildExps().get(0); identifier = lNode.getIdentifier(); - if (this.labels.get(identifier) != null) { - labelOrdinal = this.labels.get(identifier); - labelOrdinal = -1 * labelOrdinal; // Store NOT node as -ve ordinal. - } + labelOrdinal = this.labels.get(identifier); + labelOrdinal = -1 * labelOrdinal; // Store NOT node as -ve ordinal. } if (labelOrdinal == 0) { - throw new BadTsvLineException("Invalid visibility label " + identifier); + throw new InvalidLabelException("Invalid visibility label " + identifier); } - WritableUtils.writeVInt(dos, labelOrdinal); + labelOrdinals.add(labelOrdinal); } else { List<ExpressionNode> childExps = ((NonLeafExpressionNode) node).getChildExps(); for (ExpressionNode child : childExps) { - writeLabelOrdinalsToStream(child, dos); + getLabelOrdinals(child, labelOrdinals); } } } @@ -190,6 +201,7 @@ private void createLabels() throws IOException { * @return KeyValue from the cell visibility expr * @throws IOException * @throws BadTsvLineException + * @throws ParseException */ public KeyValue createKVFromCellVisibilityExpr(int rowKeyOffset, int rowKeyLength, byte[] family, int familyOffset, int familyLength, byte[] qualifier, int qualifierOffset, @@ -201,10 +213,14 @@ public KeyValue createKVFromCellVisibilityExpr(int rowKeyOffset, int rowKeyLengt KeyValue kv = null; if (cellVisibilityExpr != null) { // Apply the expansion and parsing here - List<Tag> visibilityTags = createVisibilityTags(cellVisibilityExpr); - kv = new KeyValue(lineBytes, rowKeyOffset, rowKeyLength, family, familyOffset, familyLength, - qualifier, qualifierOffset, qualifierLength, ts, KeyValue.Type.Put, lineBytes, columnOffset, - columnLength, visibilityTags); + try { + List<Tag> visibilityTags = createVisibilityTags(cellVisibilityExpr); + kv = new KeyValue(lineBytes, rowKeyOffset, rowKeyLength, family, familyOffset, + familyLength, qualifier, qualifierOffset, qualifierLength, ts, KeyValue.Type.Put, + lineBytes, columnOffset, columnLength, visibilityTags); + } catch (ParseException e) { + throw new BadTsvLineException("Parse Exception " + e.getMessage()); + } } else { kv = new KeyValue(lineBytes, rowKeyOffset, rowKeyLength, family, familyOffset, familyLength, qualifier, qualifierOffset, qualifierLength, ts, KeyValue.Type.Put, lineBytes, columnOffset, diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/DeleteTracker.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/DeleteTracker.java index 514628d9732d..469d451e62bb 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/DeleteTracker.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/DeleteTracker.java @@ -45,7 +45,7 @@ public interface DeleteTracker { /** * Check if the specified cell buffer has been deleted by a previously * seen delete. - * @param cell - current cell to check if deleted by a previously deleted cell + * @param cell - current cell to check if deleted by a previously seen delete * @return deleteResult The result tells whether the KeyValue is deleted and why */ DeleteResult isDeleted(Cell cell); diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java index c1389386b9ff..2429ed5c001f 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java @@ -2079,8 +2079,8 @@ void prepareDeleteTimestamps(Mutation mutation, Map<byte[], List<Cell>> familyMa get.setMaxVersions(count); get.addColumn(family, qual); if (coprocessorHost != null) { - if (!coprocessorHost.prePrepareTimeStampForDeleteVersion(mutation, cell, byteNow, - get)) { + if (!coprocessorHost.prePrepareTimeStampForDeleteVersion(mutation, cell, + byteNow, get)) { updateDeleteLatestVersionTimeStamp(kv, get, count, byteNow); } } else { @@ -4759,7 +4759,7 @@ public Result get(final Get get) throws IOException { * @param withCoprocessor invoke coprocessor or not. We don't want to * always invoke cp for this private method. */ - private List<Cell> get(Get get, boolean withCoprocessor) + public List<Cell> get(Get get, boolean withCoprocessor) throws IOException { List<Cell> results = new ArrayList<Cell>(); diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanDeleteTracker.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanDeleteTracker.java index 6a767e807406..668e3db1e72a 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanDeleteTracker.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanDeleteTracker.java @@ -45,14 +45,14 @@ @InterfaceAudience.Private public class ScanDeleteTracker implements DeleteTracker { - private boolean hasFamilyStamp = false; - private long familyStamp = 0L; - private SortedSet<Long> familyVersionStamps = new TreeSet<Long>(); - private byte [] deleteBuffer = null; - private int deleteOffset = 0; - private int deleteLength = 0; - private byte deleteType = 0; - private long deleteTimestamp = 0L; + protected boolean hasFamilyStamp = false; + protected long familyStamp = 0L; + protected SortedSet<Long> familyVersionStamps = new TreeSet<Long>(); + protected byte [] deleteBuffer = null; + protected int deleteOffset = 0; + protected int deleteLength = 0; + protected byte deleteType = 0; + protected long deleteTimestamp = 0L; /** * Constructor for ScanDeleteTracker @@ -65,7 +65,7 @@ public ScanDeleteTracker() { * Add the specified KeyValue to the list of deletes to check against for * this row operation. * <p> - * This is called when a Delete is encountered in a StoreFile. + * This is called when a Delete is encountered. * @param cell - the delete cell */ @Override diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityController.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityController.java index fe13430bd8ac..4501c0be9d3d 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityController.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityController.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -75,6 +76,7 @@ import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment; import org.apache.hadoop.hbase.exceptions.DeserializationException; import org.apache.hadoop.hbase.filter.Filter; +import org.apache.hadoop.hbase.filter.FilterBase; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.io.hfile.HFile; import org.apache.hadoop.hbase.io.util.StreamUtils; @@ -93,6 +95,7 @@ import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse; import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsService; import org.apache.hadoop.hbase.regionserver.BloomType; +import org.apache.hadoop.hbase.regionserver.DeleteTracker; import org.apache.hadoop.hbase.regionserver.DisabledRegionSplitPolicy; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.InternalScanner; @@ -149,7 +152,6 @@ public class VisibilityController extends BaseRegionObserver implements MasterOb private boolean acOn = false; private Configuration conf; private volatile boolean initialized = false; - /** Mapping of scanner instances to the user who created them */ private Map<InternalScanner,String> scannerOwners = new MapMaker().weakKeys().makeMap(); @@ -167,6 +169,13 @@ public class VisibilityController extends BaseRegionObserver implements MasterOb LABELS_TABLE_TAGS[0] = new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray()); } + // Add to this list if there are any reserved tag types + private static ArrayList<Byte> reservedVisTagTypes = new ArrayList<Byte>(); + static { + reservedVisTagTypes.add(VisibilityUtils.VISIBILITY_TAG_TYPE); + reservedVisTagTypes.add(VisibilityUtils.VISIBILITY_EXP_SERIALIZATION_TAG_TYPE); + } + @Override public void start(CoprocessorEnvironment env) throws IOException { this.conf = env.getConfiguration(); @@ -690,10 +699,8 @@ public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, new OperationStatus(SANITY_CHECK_FAILURE, de.getMessage())); continue; } - if (m instanceof Put) { - Put p = (Put) m; boolean sanityFailure = false; - for (CellScanner cellScanner = p.cellScanner(); cellScanner.advance();) { + for (CellScanner cellScanner = m.cellScanner(); cellScanner.advance();) { if (!checkForReservedVisibilityTagPresence(cellScanner.current())) { miniBatchOp.setOperationStatus(i, new OperationStatus(SANITY_CHECK_FAILURE, "Mutation contains cell with reserved type tag")); @@ -707,7 +714,7 @@ public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, List<Tag> visibilityTags = labelCache.get(labelsExp); if (visibilityTags == null) { try { - visibilityTags = createVisibilityTags(labelsExp); + visibilityTags = createVisibilityTags(labelsExp, true); } catch (ParseException e) { miniBatchOp.setOperationStatus(i, new OperationStatus(SANITY_CHECK_FAILURE, e.getMessage())); @@ -719,7 +726,7 @@ public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, if (visibilityTags != null) { labelCache.put(labelsExp, visibilityTags); List<Cell> updatedCells = new ArrayList<Cell>(); - for (CellScanner cellScanner = p.cellScanner(); cellScanner.advance();) { + for (CellScanner cellScanner = m.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); List<Tag> tags = Tag.asList(cell.getTagsArray(), cell.getTagsOffset(), cell.getTagsLength()); @@ -732,22 +739,71 @@ public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, cell.getValueLength(), tags); updatedCells.add(updatedCell); } - p.getFamilyCellMap().clear(); - // Clear and add new Cells to the Mutation. - for (Cell cell : updatedCells) { + m.getFamilyCellMap().clear(); + // Clear and add new Cells to the Mutation. + for (Cell cell : updatedCells) { + if (m instanceof Put) { + Put p = (Put) m; p.add(cell); + } else if (m instanceof Delete) { + // TODO : Cells without visibility tags would be handled in follow up issue + Delete d = (Delete) m; + d.addDeleteMarker(cell); } } } } - } else if (cellVisibility != null) { - // CellVisibility in a Delete is not legal! Fail the operation - miniBatchOp.setOperationStatus(i, new OperationStatus(SANITY_CHECK_FAILURE, - "CellVisibility cannot be set on Delete mutation")); } } } + @Override + public void prePrepareTimeStampForDeleteVersion( + ObserverContext<RegionCoprocessorEnvironment> ctx, Mutation delete, Cell cell, + byte[] byteNow, Get get) throws IOException { + KeyValue kv = KeyValueUtil.ensureKeyValue(cell); + CellVisibility cellVisibility = null; + try { + cellVisibility = delete.getCellVisibility(); + } catch (DeserializationException de) { + throw new IOException("Invalid cell visibility specified " + delete, de); + } + // The check for checkForReservedVisibilityTagPresence happens in preBatchMutate happens. + // It happens for every mutation and that would be enough. + List<Tag> visibilityTags = new ArrayList<Tag>(); + if (cellVisibility != null) { + String labelsExp = cellVisibility.getExpression(); + try { + visibilityTags = createVisibilityTags(labelsExp, false); + } catch (ParseException e) { + throw new IOException("Invalid cell visibility expression " + labelsExp, e); + } catch (InvalidLabelException e) { + throw new IOException("Invalid cell visibility specified " + labelsExp, e); + } + } + get.setFilter(new DeleteVersionVisibilityExpressionFilter(visibilityTags)); + List<Cell> result = ctx.getEnvironment().getRegion().get(get, false); + + if (result.size() < get.getMaxVersions()) { + // Nothing to delete + kv.updateLatestStamp(Bytes.toBytes(Long.MIN_VALUE)); + return; + } + if (result.size() > get.getMaxVersions()) { + throw new RuntimeException("Unexpected size: " + result.size() + + ". Results more than the max versions obtained."); + } + KeyValue getkv = KeyValueUtil.ensureKeyValue(result.get(get.getMaxVersions() - 1)); + Bytes.putBytes(kv.getBuffer(), kv.getTimestampOffset(), getkv.getBuffer(), + getkv.getTimestampOffset(), Bytes.SIZEOF_LONG); + // We are bypassing here because in the HRegion.updateDeleteLatestVersionTimeStamp we would + // update with the current timestamp after again doing a get. As the hook as already determined + // the needed timestamp we need to bypass here. + // TODO : See if HRegion.updateDeleteLatestVersionTimeStamp() could be + // called only if the hook is not called. + ctx.bypass(); + } + @Override public void postBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { @@ -844,7 +900,7 @@ private boolean checkForReservedVisibilityTagPresence(Cell cell) throws IOExcept Iterator<Tag> tagsItr = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(), cell.getTagsLength()); while (tagsItr.hasNext()) { - if (tagsItr.next().getType() == VisibilityUtils.VISIBILITY_TAG_TYPE) { + if (reservedVisTagTypes.contains(tagsItr.next().getType())) { return false; } } @@ -852,28 +908,38 @@ private boolean checkForReservedVisibilityTagPresence(Cell cell) throws IOExcept return true; } - private List<Tag> createVisibilityTags(String visibilityLabelsExp) throws IOException, - ParseException, InvalidLabelException { + private List<Tag> createVisibilityTags(String visibilityLabelsExp, boolean addSerializationTag) + throws IOException, ParseException, InvalidLabelException { ExpressionNode node = null; node = this.expressionParser.parse(visibilityLabelsExp); node = this.expressionExpander.expand(node); List<Tag> tags = new ArrayList<Tag>(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); + List<Integer> labelOrdinals = new ArrayList<Integer>(); + // We will be adding this tag before the visibility tags and the presence of this + // tag indicates we are supporting deletes with cell visibility + if (addSerializationTag) { + tags.add(VisibilityUtils.VIS_SERIALIZATION_TAG); + } if (node.isSingleNode()) { - writeLabelOrdinalsToStream(node, dos); + getLabelOrdinals(node, labelOrdinals); + writeLabelOrdinalsToStream(labelOrdinals, dos); tags.add(new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray())); baos.reset(); } else { NonLeafExpressionNode nlNode = (NonLeafExpressionNode) node; if (nlNode.getOperator() == Operator.OR) { for (ExpressionNode child : nlNode.getChildExps()) { - writeLabelOrdinalsToStream(child, dos); + getLabelOrdinals(child, labelOrdinals); + writeLabelOrdinalsToStream(labelOrdinals, dos); tags.add(new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray())); baos.reset(); + labelOrdinals.clear(); } } else { - writeLabelOrdinalsToStream(nlNode, dos); + getLabelOrdinals(nlNode, labelOrdinals); + writeLabelOrdinalsToStream(labelOrdinals, dos); tags.add(new Tag(VisibilityUtils.VISIBILITY_TAG_TYPE, baos.toByteArray())); baos.reset(); } @@ -881,7 +947,15 @@ private List<Tag> createVisibilityTags(String visibilityLabelsExp) throws IOExce return tags; } - private void writeLabelOrdinalsToStream(ExpressionNode node, DataOutputStream dos) + private void writeLabelOrdinalsToStream(List<Integer> labelOrdinals, DataOutputStream dos) + throws IOException { + Collections.sort(labelOrdinals); + for (Integer labelOrdinal : labelOrdinals) { + StreamUtils.writeRawVInt32(dos, labelOrdinal); + } + } + + private void getLabelOrdinals(ExpressionNode node, List<Integer> labelOrdinals) throws IOException, InvalidLabelException { if (node.isSingleNode()) { String identifier = null; @@ -904,11 +978,11 @@ private void writeLabelOrdinalsToStream(ExpressionNode node, DataOutputStream do if (labelOrdinal == 0) { throw new InvalidLabelException("Invalid visibility label " + identifier); } - StreamUtils.writeRawVInt32(dos, labelOrdinal); + labelOrdinals.add(labelOrdinal); } else { List<ExpressionNode> childExps = ((NonLeafExpressionNode) node).getChildExps(); for (ExpressionNode child : childExps) { - writeLabelOrdinalsToStream(child, dos); + getLabelOrdinals(child, labelOrdinals); } } } @@ -949,6 +1023,22 @@ private boolean checkIfScanOrGetFromSuperUser() throws IOException { return false; } + @Override + public DeleteTracker postInstantiateDeleteTracker( + ObserverContext<RegionCoprocessorEnvironment> ctx, DeleteTracker delTracker) + throws IOException { + HRegion region = ctx.getEnvironment().getRegion(); + TableName table = region.getRegionInfo().getTable(); + if (table.isSystemTable()) { + return delTracker; + } + // We are creating a new type of delete tracker here which is able to track + // the timestamps and also the + // visibility tags per cell. The covering cells are determined not only + // based on the delete type and ts + // but also on the visibility expression matching. + return new VisibilityScanDeleteTracker(); + } @Override public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Scan scan, final RegionScanner s) throws IOException { @@ -1126,7 +1216,7 @@ public Cell postMutationBeforeWAL(ObserverContext<RegionCoprocessorEnvironment> } } try { - tags.addAll(createVisibilityTags(cellVisibility.getExpression())); + tags.addAll(createVisibilityTags(cellVisibility.getExpression(), true)); } catch (ParseException e) { throw new IOException(e); } @@ -1416,4 +1506,22 @@ private void checkCallingUserAuth() throws IOException { } } } + + static class DeleteVersionVisibilityExpressionFilter extends FilterBase { + private List<Tag> visibilityTags; + + public DeleteVersionVisibilityExpressionFilter(List<Tag> visibilityTags) { + this.visibilityTags = visibilityTags; + } + + @Override + public ReturnCode filterKeyValue(Cell kv) throws IOException { + boolean matchFound = VisibilityUtils.checkForMatchingVisibilityTags(kv, visibilityTags); + if (matchFound) { + return ReturnCode.INCLUDE; + } else { + return ReturnCode.SKIP; + } + } + } } diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityScanDeleteTracker.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityScanDeleteTracker.java new file mode 100644 index 000000000000..c151b747f123 --- /dev/null +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityScanDeleteTracker.java @@ -0,0 +1,276 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hbase.security.visibility; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.KeyValue; +import org.apache.hadoop.hbase.KeyValue.Type; +import org.apache.hadoop.hbase.Tag; +import org.apache.hadoop.hbase.regionserver.ScanDeleteTracker; +import org.apache.hadoop.hbase.util.Bytes; + +/** + * Similar to ScanDeletTracker but tracks the visibility expression also before + * deciding if a Cell can be considered deleted + */ [email protected] +public class VisibilityScanDeleteTracker extends ScanDeleteTracker { + + // Its better to track the visibility tags in delete based on each type. Create individual + // data structures for tracking each of them. This would ensure that there is no tracking based + // on time and also would handle all cases where deletefamily or deletecolumns is specified with + // Latest_timestamp. In such cases the ts in the delete marker and the masking + // put will not be same. So going with individual data structures for different delete + // type would solve this problem and also ensure that the combination of different type + // of deletes with diff ts would also work fine + // Track per TS + private Map<Long, List<Tag>> visibilityTagsDeleteFamily = new HashMap<Long, List<Tag>>(); + // Delete family version with different ts and different visibility expression could come. + // Need to track it per ts. + private Map<Long,List<Tag>> visibilityTagsDeleteFamilyVersion = new HashMap<Long, List<Tag>>(); + private List<List<Tag>> visibilityTagsDeleteColumns; + // Tracking as List<List> is to handle same ts cell but different visibility tag. + // TODO : Need to handle puts with same ts but different vis tags. + private List<List<Tag>> visiblityTagsDeleteColumnVersion = new ArrayList<List<Tag>>(); + + public VisibilityScanDeleteTracker() { + super(); + } + + @Override + public void add(Cell delCell) { + //Cannot call super.add because need to find if the delete needs to be considered + long timestamp = delCell.getTimestamp(); + int qualifierOffset = delCell.getQualifierOffset(); + int qualifierLength = delCell.getQualifierLength(); + byte type = delCell.getTypeByte(); + if (type == KeyValue.Type.DeleteFamily.getCode()) { + hasFamilyStamp = true; + //familyStamps.add(delCell.getTimestamp()); + extractDeleteTags(delCell, KeyValue.Type.DeleteFamily); + return; + } else if (type == KeyValue.Type.DeleteFamilyVersion.getCode()) { + familyVersionStamps.add(timestamp); + extractDeleteTags(delCell, KeyValue.Type.DeleteFamilyVersion); + return; + } + // new column, or more general delete type + if (deleteBuffer != null) { + if (Bytes.compareTo(deleteBuffer, deleteOffset, deleteLength, delCell.getQualifierArray(), + qualifierOffset, qualifierLength) != 0) { + // A case where there are deletes for a column qualifier but there are + // no corresponding puts for them. Rare case. + visibilityTagsDeleteColumns = null; + visiblityTagsDeleteColumnVersion = null; + } else if (type == KeyValue.Type.Delete.getCode() && (deleteTimestamp != timestamp)) { + // there is a timestamp change which means we could clear the list + // when ts is same and the vis tags are different we need to collect + // them all. Interesting part is that in the normal case of puts if + // there are 2 cells with same ts and diff vis tags only one of them is + // returned. Handling with a single List<Tag> would mean that only one + // of the cell would be considered. Doing this as a precaution. + // Rare cases. + visiblityTagsDeleteColumnVersion = null; + } + } + deleteBuffer = delCell.getQualifierArray(); + deleteOffset = qualifierOffset; + deleteLength = qualifierLength; + deleteType = type; + deleteTimestamp = timestamp; + extractDeleteTags(delCell, KeyValue.Type.codeToType(type)); + } + + private void extractDeleteTags(Cell delCell, Type type) { + // If tag is present in the delete + if (delCell.getTagsLength() > 0) { + switch (type) { + case DeleteFamily: + List<Tag> delTags = new ArrayList<Tag>(); + if (visibilityTagsDeleteFamily != null) { + VisibilityUtils.getVisibilityTags(delCell, delTags); + if (!delTags.isEmpty()) { + visibilityTagsDeleteFamily.put(delCell.getTimestamp(), delTags); + } + } + break; + case DeleteFamilyVersion: + delTags = new ArrayList<Tag>(); + VisibilityUtils.getVisibilityTags(delCell, delTags); + if (!delTags.isEmpty()) { + visibilityTagsDeleteFamilyVersion.put(delCell.getTimestamp(), delTags); + } + break; + case DeleteColumn: + if (visibilityTagsDeleteColumns == null) { + visibilityTagsDeleteColumns = new ArrayList<List<Tag>>(); + } + delTags = new ArrayList<Tag>(); + VisibilityUtils.getVisibilityTags(delCell, delTags); + if (!delTags.isEmpty()) { + visibilityTagsDeleteColumns.add(delTags); + } + break; + case Delete: + if (visiblityTagsDeleteColumnVersion == null) { + visiblityTagsDeleteColumnVersion = new ArrayList<List<Tag>>(); + } + delTags = new ArrayList<Tag>(); + VisibilityUtils.getVisibilityTags(delCell, delTags); + if (!delTags.isEmpty()) { + visiblityTagsDeleteColumnVersion.add(delTags); + } + break; + default: + throw new IllegalArgumentException("Invalid delete type"); + } + } else { + switch (type) { + case DeleteFamily: + visibilityTagsDeleteFamily = null; + break; + case DeleteFamilyVersion: + visibilityTagsDeleteFamilyVersion = null; + break; + case DeleteColumn: + visibilityTagsDeleteColumns = null; + break; + case Delete: + visiblityTagsDeleteColumnVersion = null; + break; + default: + throw new IllegalArgumentException("Invalid delete type"); + } + } + } + + @Override + public DeleteResult isDeleted(Cell cell) { + long timestamp = cell.getTimestamp(); + int qualifierOffset = cell.getQualifierOffset(); + int qualifierLength = cell.getQualifierLength(); + if (hasFamilyStamp) { + if (visibilityTagsDeleteFamily != null) { + Set<Entry<Long, List<Tag>>> deleteFamilies = visibilityTagsDeleteFamily.entrySet(); + Iterator<Entry<Long, List<Tag>>> iterator = deleteFamilies.iterator(); + while (iterator.hasNext()) { + Entry<Long, List<Tag>> entry = iterator.next(); + if (timestamp <= entry.getKey()) { + boolean matchFound = VisibilityUtils.checkForMatchingVisibilityTags(cell, + entry.getValue()); + if (matchFound) { + return DeleteResult.FAMILY_VERSION_DELETED; + } + } + } + } else { + if (!VisibilityUtils.isVisibilityTagsPresent(cell)) { + // No tags + return DeleteResult.FAMILY_VERSION_DELETED; + } + } + } + if (familyVersionStamps.contains(Long.valueOf(timestamp))) { + if (visibilityTagsDeleteFamilyVersion != null) { + List<Tag> tags = visibilityTagsDeleteFamilyVersion.get(Long.valueOf(timestamp)); + if (tags != null) { + boolean matchFound = VisibilityUtils.checkForMatchingVisibilityTags(cell, tags); + if (matchFound) { + return DeleteResult.FAMILY_VERSION_DELETED; + } + } + } else { + if (!VisibilityUtils.isVisibilityTagsPresent(cell)) { + // No tags + return DeleteResult.FAMILY_VERSION_DELETED; + } + } + } + if (deleteBuffer != null) { + int ret = Bytes.compareTo(deleteBuffer, deleteOffset, deleteLength, cell.getQualifierArray(), + qualifierOffset, qualifierLength); + + if (ret == 0) { + if (deleteType == KeyValue.Type.DeleteColumn.getCode()) { + if (visibilityTagsDeleteColumns != null) { + for (List<Tag> tags : visibilityTagsDeleteColumns) { + boolean matchFound = VisibilityUtils.checkForMatchingVisibilityTags(cell, + tags); + if (matchFound) { + return DeleteResult.VERSION_DELETED; + } + } + } else { + if (!VisibilityUtils.isVisibilityTagsPresent(cell)) { + // No tags + return DeleteResult.VERSION_DELETED; + } + } + } + // Delete (aka DeleteVersion) + // If the timestamp is the same, keep this one + if (timestamp == deleteTimestamp) { + if (visiblityTagsDeleteColumnVersion != null) { + for (List<Tag> tags : visiblityTagsDeleteColumnVersion) { + boolean matchFound = VisibilityUtils.checkForMatchingVisibilityTags(cell, + tags); + if (matchFound) { + return DeleteResult.VERSION_DELETED; + } + } + } else { + if (!VisibilityUtils.isVisibilityTagsPresent(cell)) { + // No tags + return DeleteResult.VERSION_DELETED; + } + } + } + } else if (ret < 0) { + // Next column case. + deleteBuffer = null; + visibilityTagsDeleteColumns = null; + visiblityTagsDeleteColumnVersion = null; + } else { + throw new IllegalStateException("isDeleted failed: deleteBuffer=" + + Bytes.toStringBinary(deleteBuffer, deleteOffset, deleteLength) + ", qualifier=" + + Bytes.toStringBinary(cell.getQualifierArray(), qualifierOffset, qualifierLength) + + ", timestamp=" + timestamp + ", comparison result: " + ret); + } + } + return DeleteResult.NOT_DELETED; + } + + @Override + public void reset() { + super.reset(); + visibilityTagsDeleteColumns = null; + visibilityTagsDeleteFamily = new HashMap<Long, List<Tag>>(); + visibilityTagsDeleteFamilyVersion = new HashMap<Long, List<Tag>>(); + visiblityTagsDeleteColumnVersion = null; + } +} diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityUtils.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityUtils.java index 0c7764ff1175..b87f59ad5210 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityUtils.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/visibility/VisibilityUtils.java @@ -19,25 +19,31 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import com.google.protobuf.HBaseZeroCopyByteString; - import org.apache.commons.lang.StringUtils; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellUtil; +import org.apache.hadoop.hbase.Tag; import org.apache.hadoop.hbase.TagType; import org.apache.hadoop.hbase.exceptions.DeserializationException; +import org.apache.hadoop.hbase.io.util.StreamUtils; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.MultiUserAuthorizations; import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.UserAuthorizations; import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabel; import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsRequest; import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.util.ReflectionUtils; +import com.google.protobuf.HBaseZeroCopyByteString; import com.google.protobuf.InvalidProtocolBufferException; /** @@ -46,10 +52,14 @@ @InterfaceAudience.Private public class VisibilityUtils { - public static final String VISIBILITY_LABEL_GENERATOR_CLASS = + public static final String VISIBILITY_LABEL_GENERATOR_CLASS = "hbase.regionserver.scan.visibility.label.generator.class"; public static final byte VISIBILITY_TAG_TYPE = TagType.VISIBILITY_TAG_TYPE; + public static final byte VISIBILITY_EXP_SERIALIZATION_TAG_TYPE = + TagType.VISIBILITY_EXP_SERIALIZATION_TAG_TYPE; public static final String SYSTEM_LABEL = "system"; + public static final Tag VIS_SERIALIZATION_TAG = new Tag(VISIBILITY_EXP_SERIALIZATION_TAG_TYPE, + VisibilityConstants.SORTED_ORDINAL_SERIALIZATION_FORMAT); private static final String COMMA = ","; /** @@ -156,4 +166,162 @@ public static List<ScanLabelGenerator> getScanLabelGenerators(Configuration conf } return slgs; } + + /** + * Get the list of visibility tags in the given cell + * @param cell - the cell + * @param tags - the tags array that will be populated if + * visibility tags are present + * @return true if the tags are in sorted order. + */ + public static boolean getVisibilityTags(Cell cell, List<Tag> tags) { + boolean sortedOrder = false; + Iterator<Tag> tagsIterator = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(), + cell.getTagsLength()); + while (tagsIterator.hasNext()) { + Tag tag = tagsIterator.next(); + if(tag.getType() == VisibilityUtils.VISIBILITY_EXP_SERIALIZATION_TAG_TYPE) { + int serializationVersion = Bytes.toShort(tag.getValue()); + if (serializationVersion == VisibilityConstants.VISIBILITY_SERIALIZATION_VERSION) { + sortedOrder = true; + continue; + } + } + if (tag.getType() == VisibilityUtils.VISIBILITY_TAG_TYPE) { + tags.add(tag); + } + } + return sortedOrder; + } + + /** + * Checks if the cell has a visibility tag + * @param cell + * @return true if found, false if not found + */ + public static boolean isVisibilityTagsPresent(Cell cell) { + Iterator<Tag> tagsIterator = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(), + cell.getTagsLength()); + while (tagsIterator.hasNext()) { + Tag tag = tagsIterator.next(); + if (tag.getType() == VisibilityUtils.VISIBILITY_TAG_TYPE) { + return true; + } + } + return false; + } + + /** + * Checks for the matching visibility labels in the delete mutation and + * the cell in consideration + * @param cell - the cell + * @param visibilityTagsInDeleteCell - that list of tags in the delete mutation + * (the specified Cell Visibility) + * @return true if matching tags are found + */ + public static boolean checkForMatchingVisibilityTags(Cell cell, + List<Tag> visibilityTagsInDeleteCell) { + List<Tag> tags = new ArrayList<Tag>(); + boolean sortedTags = getVisibilityTags(cell, tags); + if (tags.size() == 0) { + // Early out if there are no tags in the cell + return false; + } + if (sortedTags) { + return checkForMatchingVisibilityTagsWithSortedOrder(visibilityTagsInDeleteCell, tags); + } else { + try { + return checkForMatchingVisibilityTagsWithOutSortedOrder(cell, visibilityTagsInDeleteCell); + } catch (IOException e) { + // Should not happen + throw new RuntimeException("Exception while sorting the tags from the cell", e); + } + } + } + + private static boolean checkForMatchingVisibilityTagsWithOutSortedOrder(Cell cell, + List<Tag> visibilityTagsInDeleteCell) throws IOException { + List<List<Integer>> sortedDeleteTags = sortTagsBasedOnOrdinal( + visibilityTagsInDeleteCell); + List<List<Integer>> sortedTags = sortTagsBasedOnOrdinal(cell); + return compareTagsOrdinals(sortedDeleteTags, sortedTags); + } + + private static boolean checkForMatchingVisibilityTagsWithSortedOrder( + List<Tag> visibilityTagsInDeleteCell, List<Tag> tags) { + boolean matchFound = false; + if ((visibilityTagsInDeleteCell.size()) != tags.size()) { + // If the size does not match. Definitely we are not comparing the + // equal tags. + // Return false in that case. + return matchFound; + } + for (Tag tag : visibilityTagsInDeleteCell) { + matchFound = false; + for (Tag givenTag : tags) { + if (Bytes.equals(tag.getBuffer(), tag.getTagOffset(), tag.getTagLength(), + givenTag.getBuffer(), givenTag.getTagOffset(), givenTag.getTagLength())) { + matchFound = true; + break; + } + } + } + return matchFound; + } + + private static List<List<Integer>> sortTagsBasedOnOrdinal(Cell cell) throws IOException { + Iterator<Tag> tagsItr = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(), + cell.getTagsLength()); + List<List<Integer>> fullTagsList = new ArrayList<List<Integer>>(); + while (tagsItr.hasNext()) { + Tag tag = tagsItr.next(); + if (tag.getType() == VisibilityUtils.VISIBILITY_TAG_TYPE) { + getSortedTagOrdinals(fullTagsList, tag); + } + } + return fullTagsList; + } + + private static List<List<Integer>> sortTagsBasedOnOrdinal(List<Tag> tags) throws IOException { + List<List<Integer>> fullTagsList = new ArrayList<List<Integer>>(); + for (Tag tag : tags) { + if (tag.getType() == VisibilityUtils.VISIBILITY_TAG_TYPE) { + getSortedTagOrdinals(fullTagsList, tag); + } + } + return fullTagsList; + } + + private static void getSortedTagOrdinals(List<List<Integer>> fullTagsList, Tag tag) + throws IOException { + List<Integer> tagsOrdinalInSortedOrder = new ArrayList<Integer>(); + int offset = tag.getTagOffset(); + int endOffset = offset + tag.getTagLength(); + while (offset < endOffset) { + Pair<Integer, Integer> result = StreamUtils.readRawVarint32(tag.getBuffer(), offset); + tagsOrdinalInSortedOrder.add(result.getFirst()); + offset += result.getSecond(); + } + Collections.sort(tagsOrdinalInSortedOrder); + fullTagsList.add(tagsOrdinalInSortedOrder); + } + + private static boolean compareTagsOrdinals(List<List<Integer>> tagsInDeletes, + List<List<Integer>> tags) { + boolean matchFound = false; + if (tagsInDeletes.size() != tags.size()) { + return matchFound; + } else { + for (List<Integer> deleteTagOrdinals : tagsInDeletes) { + matchFound = false; + for (List<Integer> tagOrdinals : tags) { + if (deleteTagOrdinals.equals(tagOrdinals)) { + matchFound = true; + break; + } + } + } + return matchFound; + } + } } diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithVisibilityLabels.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithVisibilityLabels.java index b5bd1a6b12cf..0c483aa080c3 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithVisibilityLabels.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/mapreduce/TestImportTSVWithVisibilityLabels.java @@ -42,6 +42,7 @@ import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.LargeTests; +import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; @@ -50,6 +51,7 @@ import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.security.visibility.Authorizations; +import org.apache.hadoop.hbase.security.visibility.CellVisibility; import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator; import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator; import org.apache.hadoop.hbase.security.visibility.VisibilityClient; @@ -161,6 +163,58 @@ public void testMROnTable() throws Exception { util.deleteTable(tableName); } + @Test + public void testMROnTableWithDeletes() throws Exception { + String tableName = "test-" + UUID.randomUUID(); + + // Prepare the arguments required for the test. + String[] args = new String[] { + "-D" + ImportTsv.MAPPER_CONF_KEY + "=org.apache.hadoop.hbase.mapreduce.TsvImporterMapper", + "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B,HBASE_CELL_VISIBILITY", + "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", tableName }; + String data = "KEY\u001bVALUE1\u001bVALUE2\u001bsecret&private\n"; + util.createTable(tableName, FAMILY); + doMROnTableTest(util, FAMILY, data, args, 1); + issueDeleteAndVerifyData(tableName); + util.deleteTable(tableName); + } + + private void issueDeleteAndVerifyData(String tableName) throws IOException { + LOG.debug("Validating table after delete."); + HTable table = new HTable(conf, tableName); + boolean verified = false; + long pause = conf.getLong("hbase.client.pause", 5 * 1000); + int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5); + for (int i = 0; i < numRetries; i++) { + try { + Delete d = new Delete(Bytes.toBytes("KEY")); + d.deleteFamily(Bytes.toBytes(FAMILY)); + d.setCellVisibility(new CellVisibility("private&secret")); + table.delete(d); + + Scan scan = new Scan(); + // Scan entire family. + scan.addFamily(Bytes.toBytes(FAMILY)); + scan.setAuthorizations(new Authorizations("secret", "private")); + ResultScanner resScanner = table.getScanner(scan); + Result[] next = resScanner.next(5); + assertEquals(0, next.length); + verified = true; + break; + } catch (NullPointerException e) { + // If here, a cell was empty. Presume its because updates came in + // after the scanner had been opened. Wait a while and retry. + } + try { + Thread.sleep(pause); + } catch (InterruptedException e) { + // continue + } + } + table.close(); + assertTrue(verified); + } + @Test public void testMROnTableWithBulkload() throws Exception { String tableName = "test-" + UUID.randomUUID(); diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/security/visibility/TestVisibilityLabelsWithDeletes.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/security/visibility/TestVisibilityLabelsWithDeletes.java new file mode 100644 index 000000000000..d3df952f4ab7 --- /dev/null +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/security/visibility/TestVisibilityLabelsWithDeletes.java @@ -0,0 +1,3029 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hbase.security.visibility; + +import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABELS_TABLE_NAME; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.List; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellScanner; +import org.apache.hadoop.hbase.HBaseTestingUtility; +import org.apache.hadoop.hbase.HColumnDescriptor; +import org.apache.hadoop.hbase.HConstants; +import org.apache.hadoop.hbase.HTableDescriptor; +import org.apache.hadoop.hbase.MediumTests; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.HBaseAdmin; +import org.apache.hadoop.hbase.client.HTable; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.ResultScanner; +import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse; +import org.apache.hadoop.hbase.security.User; +import org.apache.hadoop.hbase.util.Bytes; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.rules.TestName; + +/** + * Tests visibility labels with deletes + */ +@Category(MediumTests.class) +public class TestVisibilityLabelsWithDeletes { + private static final String TOPSECRET = "TOPSECRET"; + private static final String PUBLIC = "PUBLIC"; + private static final String PRIVATE = "PRIVATE"; + private static final String CONFIDENTIAL = "CONFIDENTIAL"; + private static final String SECRET = "SECRET"; + public static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); + private static final byte[] row1 = Bytes.toBytes("row1"); + private static final byte[] row2 = Bytes.toBytes("row2"); + private final static byte[] fam = Bytes.toBytes("info"); + private final static byte[] qual = Bytes.toBytes("qual"); + private final static byte[] qual1 = Bytes.toBytes("qual1"); + private final static byte[] qual2 = Bytes.toBytes("qual2"); + private final static byte[] value = Bytes.toBytes("value"); + private final static byte[] value1 = Bytes.toBytes("value1"); + public static Configuration conf; + + @Rule + public final TestName TEST_NAME = new TestName(); + public static User SUPERUSER; + + @BeforeClass + public static void setupBeforeClass() throws Exception { + // setup configuration + conf = TEST_UTIL.getConfiguration(); + conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false); + conf.setInt("hfile.format.version", 3); + conf.set("hbase.coprocessor.master.classes", VisibilityController.class.getName()); + conf.set("hbase.coprocessor.region.classes", VisibilityController.class.getName()); + conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, SimpleScanLabelGenerator.class, + ScanLabelGenerator.class); + conf.set("hbase.superuser", "admin"); + TEST_UTIL.startMiniCluster(2); + SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" }); + + // Wait for the labels table to become available + TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000); + addLabels(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + TEST_UTIL.shutdownMiniCluster(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testVisibilityLabelsWithDeleteColumns() throws Throwable { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + final HTable table = createTableAndWriteDataWithLabels(tableName, SECRET + "&" + TOPSECRET, + SECRET); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + HTable table = null; + try { + table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(TOPSECRET + "&" + SECRET)); + d.deleteColumns(fam, qual); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } finally { + table.close(); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteFamily() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + final HTable table = createTableAndWriteDataWithLabels(tableName, SECRET, CONFIDENTIAL + "|" + + TOPSECRET); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row2); + d.setCellVisibility(new CellVisibility(TOPSECRET + "|" + CONFIDENTIAL)); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteFamilyVersion() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + long[] ts = new long[] { 123l, 125l }; + final HTable table = createTableAndWriteDataWithLabels(tableName, ts, CONFIDENTIAL + "|" + + TOPSECRET, SECRET); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + HTable table = null; + try { + table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(TOPSECRET + "|" + CONFIDENTIAL)); + d.deleteFamilyVersion(fam, 123l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } finally { + table.close(); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteColumnExactVersion() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + long[] ts = new long[] { 123l, 125l }; + final HTable table = createTableAndWriteDataWithLabels(tableName, ts, CONFIDENTIAL + "|" + + TOPSECRET, SECRET); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + HTable table = null; + try { + table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(TOPSECRET + "|" + CONFIDENTIAL)); + d.deleteColumn(fam, qual, 123l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } finally { + table.close(); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteColumnsWithMultipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET+")")); + d.deleteColumns(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteColumnsWithMultipleVersionsNoTimestamp() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumns(fam, qual); + table.delete(d); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET + ")")); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void + testVisibilityLabelsWithDeleteColumnsWithNoMatchVisExpWithMultipleVersionsNoTimestamp() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumns(fam, qual); + table.delete(d); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET + ")")); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteFamilyWithMultipleVersionsNoTimestamp() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteFamily(fam); + table.delete(d); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteFamily(fam); + table.delete(d); + table.flushCommits(); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET + ")")); + d.deleteFamily(fam); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteFamilyWithPutsReAppearing() throws Exception { + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, value); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteFamily(fam); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertEquals(next.length, 1); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, value1); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteFamily(fam); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(CONFIDENTIAL)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertEquals(next.length, 1); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET)); + scanner = table.getScanner(s); + Result[] next1 = scanner.next(3); + assertEquals(next1.length, 0); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityLabelsWithDeleteColumnsWithPutsReAppearing() throws Exception { + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, value); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertEquals(next.length, 1); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, value1); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(CONFIDENTIAL)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertEquals(next.length, 1); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET)); + scanner = table.getScanner(s); + Result[] next1 = scanner.next(3); + assertEquals(next1.length, 0); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testVisibilityCombinations() throws Exception { + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 124l, value1); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + table.flushCommits(); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteColumns(fam, qual, 126l); + table.delete(d); + + table = new HTable(conf, TEST_NAME.getMethodName()); + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumn(fam, qual, 123l); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(CONFIDENTIAL, SECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertEquals(next.length, 0); + } finally { + if (table != null) { + table.close(); + } + } + } + @Test + public void testVisibilityLabelsWithDeleteColumnWithSpecificVersionWithPutsReAppearing() + throws Exception { + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value1); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + table.flushCommits(); + //TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(CONFIDENTIAL, SECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertEquals(next.length, 1); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumn(fam, qual, 123l); + table.delete(d); + + table = new HTable(conf, TEST_NAME.getMethodName()); + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteColumn(fam, qual, 123l); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(CONFIDENTIAL)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertEquals(next.length, 0); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void + testVisibilityLabelsWithDeleteFamilyWithNoMatchingVisExpWithMultipleVersionsNoTimestamp() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteFamily(fam); + table.delete(d); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteFamily(fam); + table.delete(d); + table.flushCommits(); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET + ")")); + d.deleteFamily(fam); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteFamilyAndDeleteColumnsWithAndWithoutVisibilityExp() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteFamily(fam); + table.delete(d); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumns(fam, qual); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + private HTable doPuts(TableName tableName) throws IOException, InterruptedIOException, + RetriesExhaustedWithDetailsException, InterruptedException { + HTable table; + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 124l, value); + put.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 125l, value); + put.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 126l, value); + put.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 127l, value); + put.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + put = new Put(Bytes.toBytes("row2")); + put.add(fam, qual, 127l, value); + put.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + TOPSECRET + + "&" + SECRET + ")")); + table.put(put); + return table; + } + + private HTable doPutsWithDiffCols(TableName tableName) throws IOException, + InterruptedIOException, RetriesExhaustedWithDetailsException, InterruptedException { + HTable table; + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 124l, value); + put.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 125l, value); + put.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual1, 126l, value); + put.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual2, 127l, value); + put.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + table.put(put); + return table; + } + + private HTable doPutsWithoutVisibility(TableName tableName) throws IOException, + InterruptedIOException, RetriesExhaustedWithDetailsException, InterruptedException { + HTable table; + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 124l, value); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 125l, value); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 126l, value); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 127l, value); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + put = new Put(Bytes.toBytes("row2")); + put.add(fam, qual, 127l, value); + table.put(put); + return table; + } + + + @Test + public void testDeleteColumnWithSpecificTimeStampUsingMultipleVersionsUnMatchingVisExpression() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET+")")); + d.deleteColumn(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteColumnWithLatestTimeStampUsingMultipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumn(fam, qual); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test (timeout=180000) + public void testDeleteColumnWithLatestTimeStampWhenNoVersionMatches() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 128l, value); + put.setCellVisibility(new CellVisibility(TOPSECRET)); + table.put(put); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET )); + d.deleteColumn(fam, qual); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 128l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 129l, value); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + table.flushCommits(); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 129l); + } finally { + if (table != null) { + table.close(); + } + } + } + @Test + public void testDeleteColumnWithLatestTimeStampUsingMultipleVersionsAfterCompaction() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumn(fam, qual); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Put put = new Put(Bytes.toBytes("row3")); + put.add(fam, qual, 127l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL + "&" + PRIVATE)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + TEST_UTIL.getHBaseAdmin().majorCompact(tableName.getNameAsString()); + // Sleep to ensure compaction happens. Need to do it in a better way + Thread.sleep(5000); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 3); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteFamilyLatestTimeStampWithMulipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteColumnswithMultipleColumnsWithMultipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPutsWithDiffCols(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumns(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertTrue(Bytes.equals(current.getQualifierArray(), current.getQualifierOffset(), + current.getQualifierLength(), qual1, 0, qual1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + assertTrue(Bytes.equals(current.getQualifierArray(), current.getQualifierOffset(), + current.getQualifierLength(), qual2, 0, qual2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteColumnsWithDiffColsAndTags() throws Exception { + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual1, 125l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual1, 126l, value); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteColumns(fam, qual, 126l); + table.delete(d); + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumns(fam, qual1, 125l); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertEquals(next.length, 1); + } finally { + if (table != null) { + table.close(); + } + } + } + @Test + public void testDeleteColumnsWithDiffColsAndTags1() throws Exception { + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual1, 125l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual1, 126l, value); + put.setCellVisibility(new CellVisibility(SECRET)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET)); + d.deleteColumns(fam, qual, 126l); + table.delete(d); + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteColumns(fam, qual1, 126l); + table.delete(d); + table.flushCommits(); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertEquals(next.length, 1); + } finally { + if (table != null) { + table.close(); + } + } + } + @Test + public void testDeleteFamilyWithoutCellVisibilityWithMulipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPutsWithoutVisibility(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + // All cells wrt row1 should be deleted as we are not passing the Cell Visibility + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteFamilyLatestTimeStampWithMulipleVersionsWithoutCellVisibilityInPuts() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPutsWithoutVisibility(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteFamilySpecificTimeStampWithMulipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET + ")")); + d.deleteFamily(fam, 126l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(6); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testScanAfterCompaction() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + SECRET + "&" + TOPSECRET+")")); + d.deleteFamily(fam, 126l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Put put = new Put(Bytes.toBytes("row3")); + put.add(fam, qual, 127l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL + "&" + PRIVATE)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + TEST_UTIL.getHBaseAdmin().compact(tableName.getNameAsString()); + Thread.sleep(5000); + // Sleep to ensure compaction happens. Need to do it in a better way + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 3); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteFamilySpecificTimeStampWithMulipleVersionsDoneTwice() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + // Do not flush here. + table = doPuts(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteFamily(fam, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteFamily(fam, 127l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + assertEquals(current.getTimestamp(), 127l); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testMultipleDeleteFamilyVersionWithDiffLabels() throws Exception { + PrivilegedExceptionAction<VisibilityLabelsResponse> action = + new PrivilegedExceptionAction<VisibilityLabelsResponse>() { + public VisibilityLabelsResponse run() throws Exception { + try { + return VisibilityClient.setAuths(conf, new String[] { CONFIDENTIAL, PRIVATE, SECRET }, + SUPERUSER.getShortName()); + } catch (Throwable e) { + } + return null; + } + }; + VisibilityLabelsResponse response = SUPERUSER.runAs(action); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = doPuts(tableName); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteFamilyVersion(fam, 123l); + table.delete(d); + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteFamilyVersion(fam, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(5); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test (timeout=180000) + public void testSpecificDeletesFollowedByDeleteFamily() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = doPuts(tableName); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET + ")")); + d.deleteColumn(fam, qual, 126l); + table.delete(d); + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteFamilyVersion(fam, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(5); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(5); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test(timeout = 180000) + public void testSpecificDeletesFollowedByDeleteFamily1() throws Exception { + PrivilegedExceptionAction<VisibilityLabelsResponse> action = + new PrivilegedExceptionAction<VisibilityLabelsResponse>() { + public VisibilityLabelsResponse run() throws Exception { + try { + return VisibilityClient.setAuths(conf, new String[] { CONFIDENTIAL, PRIVATE, SECRET }, + SUPERUSER.getShortName()); + } catch (Throwable e) { + } + return null; + } + }; + VisibilityLabelsResponse response = SUPERUSER.runAs(action); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = doPuts(tableName); + try { + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET + ")")); + d.deleteColumn(fam, qual); + table.delete(d); + + d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteFamilyVersion(fam, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(5); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(5); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteColumnSpecificTimeStampWithMulipleVersionsDoneTwice() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + // Do not flush here. + table = doPuts(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumn(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteColumn(fam, qual, 127l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + assertEquals(current.getTimestamp(), 127l); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteColumnSpecificTimeStampWithMulipleVersionsDoneTwice1() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + // Do not flush here. + table = doPuts(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")" + + "|(" + TOPSECRET + "&" + SECRET + ")")); + d.deleteColumn(fam, qual, 127l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumn(fam, qual, 127l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + assertEquals(current.getTimestamp(), 127l); + } finally { + if (table != null) { + table.close(); + } + } + } + @Test + public void testDeleteColumnSpecificTimeStampWithMulipleVersionsDoneTwice2() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + // Do not flush here. + table = doPuts(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteColumn(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteColumn(fam, qual, 127l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + assertEquals(current.getTimestamp(), 127l); + } finally { + if (table != null) { + table.close(); + } + } + } + @Test + public void testDeleteColumnAndDeleteFamilylSpecificTimeStampWithMulipleVersion() + throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + // Do not flush here. + table = doPuts(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility(SECRET + "&" + TOPSECRET)); + d.deleteColumn(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteFamily(fam, 124l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + assertEquals(current.getTimestamp(), 127l); + } finally { + if (table != null) { + table.close(); + } + } + } + + private void setAuths() throws IOException, InterruptedException { + PrivilegedExceptionAction<VisibilityLabelsResponse> action = + new PrivilegedExceptionAction<VisibilityLabelsResponse>() { + public VisibilityLabelsResponse run() throws Exception { + try { + return VisibilityClient.setAuths(conf, new String[] { CONFIDENTIAL, PRIVATE, SECRET, + TOPSECRET }, SUPERUSER.getShortName()); + } catch (Throwable e) { + } + return null; + } + }; + SUPERUSER.runAs(action); + } + + @Test + public void testDiffDeleteTypesForTheSameCellUsingMultipleVersions() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + // Do not flush here. + table = doPuts(tableName); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + PRIVATE + "&" + CONFIDENTIAL + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteColumns(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + + // Issue 2nd delete + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.setCellVisibility(new CellVisibility("(" + CONFIDENTIAL + "&" + PRIVATE + ")|(" + + TOPSECRET + "&" + SECRET+")")); + d.deleteColumn(fam, qual, 127l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + cellScanner = next[0].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row2, 0, row2.length)); + } finally { + if (table != null) { + table.close(); + } + } + } + + @Test + public void testDeleteColumnLatestWithNoCellVisibility() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + table = doPuts(tableName); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteColumn(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 2); + scanAll(next); + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteColumns(fam, qual, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + scanAll(next); + + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteFamily(fam, 125l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + scanAll(next); + + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteFamily(fam); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + scanAll(next); + + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteColumns(fam, qual); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + scanAll(next); + + actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteFamilyVersion(fam, 126l); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + scanner = table.getScanner(s); + next = scanner.next(3); + assertTrue(next.length == 2); + scanAll(next); + } finally { + if (table != null) { + table.close(); + } + } + } + + private void scanAll(Result[] next) throws IOException { + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), + row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 127l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), + row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 126l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), + row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 125l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), + row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), + row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + cellScanner = next[1].cellScanner(); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), + row2, 0, row2.length)); + } + + @Test + public void testVisibilityExpressionWithNotEqualORCondition() throws Exception { + setAuths(); + TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); + HTable table = null; + try { + HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin(); + HColumnDescriptor colDesc = new HColumnDescriptor(fam); + colDesc.setMaxVersions(5); + HTableDescriptor desc = new HTableDescriptor(tableName); + desc.addFamily(colDesc); + hBaseAdmin.createTable(desc); + table = new HTable(conf, tableName); + Put put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 123l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); + table.put(put); + put = new Put(Bytes.toBytes("row1")); + put.add(fam, qual, 124l, value); + put.setCellVisibility(new CellVisibility(CONFIDENTIAL + "|" + PRIVATE)); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() { + public Void run() throws Exception { + try { + HTable table = new HTable(conf, TEST_NAME.getMethodName()); + Delete d = new Delete(row1); + d.deleteColumn(fam, qual, 124l); + d.setCellVisibility(new CellVisibility(PRIVATE )); + table.delete(d); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(actiona); + + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + Scan s = new Scan(); + s.setMaxVersions(5); + s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL, TOPSECRET)); + ResultScanner scanner = table.getScanner(s); + Result[] next = scanner.next(3); + assertTrue(next.length == 1); + CellScanner cellScanner = next[0].cellScanner(); + cellScanner.advance(); + Cell current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 124l); + cellScanner.advance(); + current = cellScanner.current(); + assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), + current.getRowLength(), row1, 0, row1.length)); + assertEquals(current.getTimestamp(), 123l); + } finally { + if (table != null) { + table.close(); + } + } + } + + public static HTable createTableAndWriteDataWithLabels(TableName tableName, String... labelExps) + throws Exception { + HTable table = null; + table = TEST_UTIL.createTable(tableName, fam); + int i = 1; + List<Put> puts = new ArrayList<Put>(); + for (String labelExp : labelExps) { + Put put = new Put(Bytes.toBytes("row" + i)); + put.add(fam, qual, HConstants.LATEST_TIMESTAMP, value); + put.setCellVisibility(new CellVisibility(labelExp)); + puts.add(put); + table.put(put); + i++; + } + // table.put(puts); + return table; + } + + public static HTable createTableAndWriteDataWithLabels(TableName tableName, long[] timestamp, + String... labelExps) throws Exception { + HTable table = null; + table = TEST_UTIL.createTable(tableName, fam); + int i = 1; + List<Put> puts = new ArrayList<Put>(); + for (String labelExp : labelExps) { + Put put = new Put(Bytes.toBytes("row" + i)); + put.add(fam, qual, timestamp[i - 1], value); + put.setCellVisibility(new CellVisibility(labelExp)); + puts.add(put); + table.put(put); + TEST_UTIL.getHBaseAdmin().flush(tableName.getNameAsString()); + i++; + } + return table; + } + + public static void addLabels() throws Exception { + PrivilegedExceptionAction<VisibilityLabelsResponse> action = + new PrivilegedExceptionAction<VisibilityLabelsResponse>() { + public VisibilityLabelsResponse run() throws Exception { + String[] labels = { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE }; + try { + VisibilityClient.addLabels(conf, labels); + } catch (Throwable t) { + throw new IOException(t); + } + return null; + } + }; + SUPERUSER.runAs(action); + } +}
171accb43d709bd3960187686afbdf68f5239644
aeshell$aesh
[AESH-316] - print warning instead of exception on unsupported C-
a
https://github.com/aeshell/aesh
diff --git a/src/main/java/org/jboss/aesh/edit/mapper/KeyMapper.java b/src/main/java/org/jboss/aesh/edit/mapper/KeyMapper.java index e1ba1bae1..98e5a1101 100644 --- a/src/main/java/org/jboss/aesh/edit/mapper/KeyMapper.java +++ b/src/main/java/org/jboss/aesh/edit/mapper/KeyMapper.java @@ -23,7 +23,11 @@ import org.jboss.aesh.edit.KeyOperation; import org.jboss.aesh.edit.actions.Operation; import org.jboss.aesh.terminal.Key; +import org.jboss.aesh.util.LoggerUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; import java.util.regex.Pattern; /** @@ -41,7 +45,7 @@ public class KeyMapper { private static final Pattern quotePattern = Pattern.compile("^\""); private static final Pattern metaPattern = Pattern.compile("^(\\\\M|M|Meta)-"); // "M- private static final Pattern controlPattern = Pattern.compile("^(\\\\C|C|Control)-"); // "M- - + private static final Logger LOGGER = LoggerUtil.getLogger(KeyMapper.class.getName()); /** * Parse key mapping lines that start with " * @@ -168,14 +172,27 @@ private static int[] convertRandomKeys(String random) { } private static int[] convertRandomControlKeys(String random) { - int[] converted = new int[random.length()]; - for(int i=0; i < random.length(); i++) { - converted[i] = lookupControlKey(Character.toLowerCase(random.charAt(i))); - if(converted[i] == -1) - throw new IllegalArgumentException("ERROR parsing "+random+" keys to aesh. Check your inputrc."); + final int length = random.length(); + final int[] tmpArray = new int[length]; + + int index = 0; + for(int i=0; i < length; i++) { + final int converted = lookupControlKey(Character.toLowerCase(random.charAt(i))); + if(converted == -1){ + LOGGER.warning("ERROR parsing "+random+" keys to aesh. Check your inputrc. Ignoring entry!"); + } else { + tmpArray[index++] = converted; + } + } + if( index != length){ + final int[] trimmedArray = new int[index]; + for(int i = 0; i<index;i++){ + trimmedArray[i] = tmpArray[i]; + } + return trimmedArray; + } else { + return tmpArray; } - - return converted; } private static int lookupControlKey(char c) {
9d6c63f8bee34431384adfb20add2abd5b6aa9c0
hadoop
YARN-3613. TestContainerManagerSecurity should init- and start Yarn cluster in setup instead of individual methods. (nijel via- kasha)--(cherry picked from commit fe0df596271340788095cb43a1944e19ac4c2cf7)-
p
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index d5d57a78a9e56..39f1bd6a4dac0 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -185,6 +185,9 @@ Release 2.8.0 - UNRELEASED YARN-3513. Remove unused variables in ContainersMonitorImpl and add debug log for overall resource usage by all containers. (Naganarasimha G R via devaraj) + YARN-3613. TestContainerManagerSecurity should init and start Yarn cluster in + setup instead of individual methods. (nijel via kasha) + OPTIMIZATIONS YARN-3339. TestDockerContainerExecutor should pull a single image and not diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java index f0dcb562a234c..59bb6aaba1313 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java @@ -82,8 +82,6 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteStreams; @RunWith(Parameterized.class) public class TestContainerManagerSecurity extends KerberosSecurityTestcase { @@ -105,10 +103,20 @@ public void setUp() throws Exception { testRootDir.mkdirs(); httpSpnegoKeytabFile.deleteOnExit(); getKdc().createPrincipal(httpSpnegoKeytabFile, httpSpnegoPrincipal); + + yarnCluster = + new MiniYARNCluster(TestContainerManagerSecurity.class.getName(), 1, 1, + 1); + yarnCluster.init(conf); + yarnCluster.start(); } @After public void tearDown() { + if (yarnCluster != null) { + yarnCluster.stop(); + yarnCluster = null; + } testRootDir.delete(); } @@ -144,11 +152,6 @@ public TestContainerManagerSecurity(Configuration conf) { @Test (timeout = 120000) public void testContainerManager() throws Exception { - try { - yarnCluster = new MiniYARNCluster(TestContainerManagerSecurity.class - .getName(), 1, 1, 1); - yarnCluster.init(conf); - yarnCluster.start(); // TestNMTokens. testNMTokens(conf); @@ -156,36 +159,11 @@ public void testContainerManager() throws Exception { // Testing for container token tampering testContainerToken(conf); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - if (yarnCluster != null) { - yarnCluster.stop(); - yarnCluster = null; - } - } - } - - @Test (timeout = 120000) - public void testContainerManagerWithEpoch() throws Exception { - try { - yarnCluster = new MiniYARNCluster(TestContainerManagerSecurity.class - .getName(), 1, 1, 1); - yarnCluster.init(conf); - yarnCluster.start(); - - // Testing for container token tampering + // Testing for container token tampering with epoch testContainerTokenWithEpoch(conf); - } finally { - if (yarnCluster != null) { - yarnCluster.stop(); - yarnCluster = null; - } - } } - + private void testNMTokens(Configuration conf) throws Exception { NMTokenSecretManagerInRM nmTokenSecretManagerRM = yarnCluster.getResourceManager().getRMContext()
7d5346ed863608b18045d9688b1abd41f0bfa832
agorava$agorava-core
AGOVA-7 Create API and common IMPL for JSR 330 compliant framework Adding support of @OAuthApplication annotation to produce settings
a
https://github.com/agorava/agorava-core
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/MultiSessionServiceImpl.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/MultiSessionServiceImpl.java index d03f509..6497e55 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/MultiSessionServiceImpl.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/MultiSessionServiceImpl.java @@ -22,6 +22,7 @@ import org.agorava.core.api.oauth.OAuthService; import org.agorava.core.api.oauth.OAuthSession; import org.agorava.core.api.service.MultiSessionService; +import org.agorava.core.cdi.extensions.AgoravaExtension; import javax.annotation.PostConstruct; import javax.enterprise.context.SessionScoped; @@ -40,7 +41,7 @@ import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; -import static org.agorava.core.cdi.AgoravaExtension.getServicesToQualifier; +import static org.agorava.core.cdi.extensions.AgoravaExtension.getServicesToQualifier; /** * {@inheritDoc} diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthLiteral.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthLiteral.java deleted file mode 100644 index 9b8a1c6..0000000 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthLiteral.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2013 Agorava - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.agorava.core.cdi; - -import org.agorava.core.api.atinject.OAuth; - -import javax.enterprise.util.AnnotationLiteral; - -/** - * @author Antoine Sabot-Durand - */ -public class OAuthLiteral extends AnnotationLiteral<OAuth> implements OAuth { - - private OAuthVersion version; - - public OAuthLiteral(OAuthVersion version) { - this.version = version; - } - - @Override - public OAuthVersion value() { - return version; - } -} diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthServiceImpl.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthServiceImpl.java index 5fb0a48..4de0a7f 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthServiceImpl.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthServiceImpl.java @@ -16,7 +16,6 @@ package org.agorava.core.cdi; -import org.agorava.core.api.atinject.Current; import org.agorava.core.api.atinject.GenericBean; import org.agorava.core.api.atinject.InjectWithQualifier; import org.agorava.core.api.event.OAuthComplete; @@ -31,12 +30,12 @@ import org.agorava.core.api.rest.Response; import org.agorava.core.api.rest.Verb; import org.agorava.core.api.service.JsonMapperService; +import org.agorava.core.cdi.extensions.AgoravaExtension; import javax.annotation.PostConstruct; import javax.enterprise.event.Event; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; -import javax.enterprise.util.AnnotationLiteral; import javax.inject.Inject; import java.lang.annotation.Annotation; import java.text.MessageFormat; @@ -60,9 +59,6 @@ public class OAuthServiceImpl implements OAuthService { private static final long serialVersionUID = -8423894021913341674L; - private static Annotation currentLiteral = new AnnotationLiteral<Current>() { - private static final long serialVersionUID = -2929657732814790025L; - }; @Inject protected JsonMapperService jsonService; @@ -220,7 +216,7 @@ public void setAccessToken(String token, String secret) { public OAuthSession getSession() { OAuthSession res = null; - Instance<OAuthSession> currentSession = sessions.select(currentLiteral); + Instance<OAuthSession> currentSession = sessions.select(CurrentLiteral.INSTANCE); if (currentSession.isAmbiguous()) { currentSession = currentSession.select(qualifier); diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/AgoravaExtension.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/AgoravaExtension.java similarity index 88% rename from agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/AgoravaExtension.java rename to agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/AgoravaExtension.java index 55c6767..c21c521 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/AgoravaExtension.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/AgoravaExtension.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.agorava.core.cdi; +package org.agorava.core.cdi.extensions; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -26,9 +26,11 @@ import org.agorava.core.api.atinject.TierServiceRelated; import org.agorava.core.api.exception.AgoravaException; import org.agorava.core.api.oauth.OAuthAppSettings; +import org.agorava.core.api.oauth.OAuthAppSettingsBuilder; import org.agorava.core.api.oauth.OAuthApplication; import org.agorava.core.api.oauth.OAuthProvider; import org.agorava.core.api.oauth.OAuthService; +import org.agorava.core.cdi.OAuthServiceImpl; import org.agorava.core.oauth.OAuthSessionImpl; import org.agorava.core.spi.TierConfigOauth; import org.apache.deltaspike.core.api.literal.AnyLiteral; @@ -61,6 +63,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Set; import java.util.logging.Logger; @@ -260,32 +263,53 @@ public void processGenericSession(@Observes ProcessAnnotatedType<? extends OAuth */ public void processOAuthSettingsProducer(@Observes final ProcessProducer<?, OAuthAppSettings> pp) { final AnnotatedMember<OAuthAppSettings> annotatedMember = (AnnotatedMember<OAuthAppSettings>) pp.getAnnotatedMember(); - final Annotation qual = Iterables.getLast(AgoravaExtension.getAnnotationsWithMeta(annotatedMember, - TierServiceRelated.class)); - final Producer<OAuthAppSettings> oldProducer = pp.getProducer(); + + Annotation qual = null; + try { + qual = Iterables.getLast(AgoravaExtension.getAnnotationsWithMeta(annotatedMember, + TierServiceRelated.class)); + } catch (NoSuchElementException e) { + pp.addDefinitionError(new AgoravaException("OAuthAppSettings producers should be annotated with a Service " + + "Provider on " + annotatedMember.getJavaMember().getName() + " in " + annotatedMember.getJavaMember() + .getDeclaringClass())); + } + if (annotatedMember.isAnnotationPresent(OAuthApplication.class)) { - /* TODO:CODE below for future support of OAuthAppSettings creation via annotation + if (annotatedMember instanceof AnnotatedField) { - final OAuthApplication app = annotatedMember.getAnnotation(OAuthApplication.class); + final OAuthApplication app = annotatedMember.getAnnotation(OAuthApplication.class); - Class<? extends OAuthAppSettingsBuilder> builderClass = app.builder(); - OAuthAppSettingsBuilder builderOAuthApp = null; - try { - builderOAuthApp = builderClass.newInstance(); - } catch (Exception e) { - throw new AgoravaException("Unable to create Settings Builder with class " + builderClass, e); - } + Class<? extends OAuthAppSettingsBuilder> builderClass = null; + try { + builderClass = (Class<? extends OAuthAppSettingsBuilder>) Class.forName(app.builder()); + } catch (Exception e) { + pp.addDefinitionError(e); + } + OAuthAppSettingsBuilder builderOAuthApp = null; + try { + builderOAuthApp = builderClass.newInstance(); + } catch (Exception e) { + pp.addDefinitionError(new AgoravaException("Unable to create Settings Builder with class " + + builderClass, e)); + } + + builderOAuthApp.qualifier(qual) + .params(app.params()); - final OAuthAppSettingsBuilder finalBuilderOAuthApp = builderOAuthApp; */ + pp.setProducer(new OAuthAppSettingsProducerWithBuilder(builderOAuthApp, qual)); + } else + pp.addDefinitionError(new AgoravaException("@OAuthApplication are only supported on Field. Agorava cannot " + + "process producer " + annotatedMember.getJavaMember().getName() + " in class " + annotatedMember + .getJavaMember().getDeclaringClass())); + } else { + final Producer<OAuthAppSettings> oldProducer = pp.getProducer(); + pp.setProducer(new OAuthAppSettingsProducerDecorator(oldProducer, qual)); } - pp.setProducer(new OAuthAppSettingsProducerDecorator(oldProducer, qual)); log.log(INFO, "Found settings for {0}", qual); servicesQualifiersConfigured.add(qual); - - //settings = builderOAuthApp.name(servicesHub.getSocialMediaName()).params(app.params()).build(); } @@ -316,7 +340,6 @@ public void processRemoteServiceRoot(@Observes ProcessBean<? extends TierConfigO CommonsProcessOAuthTier(pb); } - private void captureGenericOAuthService(@Observes ProcessBean<? extends OAuthService> pb) { Bean<? extends OAuthService> bean = pb.getBean(); if (bean.getQualifiers().contains(GenericBeanLiteral.INSTANCE)) { diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/GenericBeanLiteral.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/GenericBeanLiteral.java similarity index 86% rename from agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/GenericBeanLiteral.java rename to agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/GenericBeanLiteral.java index 5efd5f6..4a91f9a 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/GenericBeanLiteral.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/GenericBeanLiteral.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.agorava.core.cdi; +package org.agorava.core.cdi.extensions; import org.agorava.core.api.atinject.GenericBean; @@ -23,6 +23,6 @@ /** * @author Antoine Sabot-Durand */ -public class GenericBeanLiteral extends AnnotationLiteral<GenericBean> implements GenericBean { +class GenericBeanLiteral extends AnnotationLiteral<GenericBean> implements GenericBean { public static GenericBeanLiteral INSTANCE = new GenericBeanLiteral(); } diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/InjectLiteral.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/InjectLiteral.java similarity index 87% rename from agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/InjectLiteral.java rename to agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/InjectLiteral.java index cb37765..cc12b75 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/InjectLiteral.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/InjectLiteral.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.agorava.core.cdi; +package org.agorava.core.cdi.extensions; import javax.enterprise.util.AnnotationLiteral; import javax.inject.Inject; @@ -22,7 +22,7 @@ /** * @author Antoine Sabot-Durand */ -public class InjectLiteral extends AnnotationLiteral<Inject> implements Inject { +class InjectLiteral extends AnnotationLiteral<Inject> implements Inject { public static InjectLiteral instance = new InjectLiteral(); } diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/InjectWithQualifierLiteral.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/InjectWithQualifierLiteral.java similarity index 83% rename from agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/InjectWithQualifierLiteral.java rename to agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/InjectWithQualifierLiteral.java index 5ca48a6..dc4fc30 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/InjectWithQualifierLiteral.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/InjectWithQualifierLiteral.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.agorava.core.cdi; +package org.agorava.core.cdi.extensions; import org.agorava.core.api.atinject.InjectWithQualifier; @@ -23,7 +23,7 @@ /** * @author Antoine Sabot-Durand */ -public class InjectWithQualifierLiteral extends AnnotationLiteral<InjectWithQualifierLiteral> implements InjectWithQualifier { +class InjectWithQualifierLiteral extends AnnotationLiteral<InjectWithQualifierLiteral> implements InjectWithQualifier { public static InjectWithQualifierLiteral instance = new InjectWithQualifierLiteral(); } diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthAppSettingsProducerDecorator.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/OAuthAppSettingsProducerDecorator.java similarity index 97% rename from agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthAppSettingsProducerDecorator.java rename to agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/OAuthAppSettingsProducerDecorator.java index a2c9f07..1b96b67 100644 --- a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/OAuthAppSettingsProducerDecorator.java +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/OAuthAppSettingsProducerDecorator.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.agorava.core.cdi; +package org.agorava.core.cdi.extensions; import org.agorava.core.api.oauth.OAuthAppSettings; import org.agorava.core.oauth.SimpleOAuthAppSettingsBuilder; diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/OAuthAppSettingsProducerWithBuilder.java b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/OAuthAppSettingsProducerWithBuilder.java new file mode 100644 index 0000000..008f644 --- /dev/null +++ b/agorava-core-impl-cdi/src/main/java/org/agorava/core/cdi/extensions/OAuthAppSettingsProducerWithBuilder.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Agorava + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.agorava.core.cdi.extensions; + +import org.agorava.core.api.oauth.OAuthAppSettings; +import org.agorava.core.api.oauth.OAuthAppSettingsBuilder; + +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.enterprise.inject.spi.Producer; +import java.lang.annotation.Annotation; +import java.util.HashSet; +import java.util.Set; + +import static org.agorava.core.cdi.extensions.AgoravaExtension.getServicesToQualifier; + +/** + * @author Antoine Sabot-Durand + */ +class OAuthAppSettingsProducerWithBuilder implements Producer<OAuthAppSettings> { + + private OAuthAppSettingsBuilder builder; + + private Annotation qual; + + + OAuthAppSettingsProducerWithBuilder(OAuthAppSettingsBuilder builder, Annotation qual) { + this.builder = builder; + this.qual = qual; + } + + @Override + public OAuthAppSettings produce(CreationalContext<OAuthAppSettings> ctx) { + builder.name(getServicesToQualifier().inverse().get(qual)); + OAuthAppSettings newSettings = builder.build(); + ctx.push(newSettings); + return newSettings; + } + + @Override + public void dispose(OAuthAppSettings instance) { + } + + @Override + public Set<InjectionPoint> getInjectionPoints() { + return new HashSet<InjectionPoint>(); + } +} diff --git a/agorava-core-impl-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/agorava-core-impl-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension index 0d0a2f8..affdf8d 100644 --- a/agorava-core-impl-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension +++ b/agorava-core-impl-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -1 +1 @@ -org.agorava.core.cdi.AgoravaExtension \ No newline at end of file +org.agorava.core.cdi.extensions.AgoravaExtension \ No newline at end of file
580391e0a7dd3b3036aeb13f6ed205ac8df6d55a
internetarchive$heritrix3
Move most of addCookie functionality into AbstractCookieStore
p
https://github.com/internetarchive/heritrix3
diff --git a/modules/src/main/java/org/archive/modules/fetcher/AbstractCookieStore.java b/modules/src/main/java/org/archive/modules/fetcher/AbstractCookieStore.java index d35b911f9..1a43a14a9 100644 --- a/modules/src/main/java/org/archive/modules/fetcher/AbstractCookieStore.java +++ b/modules/src/main/java/org/archive/modules/fetcher/AbstractCookieStore.java @@ -284,8 +284,22 @@ public boolean isCookieCountMaxedForDomain(String domain) { return (cookieStore != null && cookieStore.getCookies().size() >= MAX_COOKIES_FOR_DOMAIN); } - - abstract public void addCookie(Cookie cookie); + + public void addCookie(Cookie cookie) { + if (isCookieCountMaxedForDomain(cookie.getDomain())) { + logger.log( + Level.FINEST, + "Maximum number of cookies reached for domain " + + cookie.getDomain() + ". Will not add new cookie " + + cookie.getName() + " with value " + + cookie.getValue()); + return; + } + + addCookieImpl(cookie); + } + + abstract protected void addCookieImpl(Cookie cookie); abstract public void clear(); abstract protected void prepare(); } diff --git a/modules/src/main/java/org/archive/modules/fetcher/BdbCookieStore.java b/modules/src/main/java/org/archive/modules/fetcher/BdbCookieStore.java index 199f784ee..92220700a 100644 --- a/modules/src/main/java/org/archive/modules/fetcher/BdbCookieStore.java +++ b/modules/src/main/java/org/archive/modules/fetcher/BdbCookieStore.java @@ -135,17 +135,7 @@ public void prepare() { } } - public void addCookie(Cookie cookie) { - if (isCookieCountMaxedForDomain(cookie.getDomain())) { - logger.log( - Level.FINEST, - "Maximum number of cookies reached for domain " - + cookie.getDomain() + ". Will not add new cookie " - + cookie.getName() + " with value " - + cookie.getValue()); - return; - } - + public void addCookieImpl(Cookie cookie) { byte[] key; try { key = sortableKey(cookie).getBytes("UTF-8"); diff --git a/modules/src/main/java/org/archive/modules/fetcher/SimpleCookieStore.java b/modules/src/main/java/org/archive/modules/fetcher/SimpleCookieStore.java index fc45cfb83..89e0a3026 100644 --- a/modules/src/main/java/org/archive/modules/fetcher/SimpleCookieStore.java +++ b/modules/src/main/java/org/archive/modules/fetcher/SimpleCookieStore.java @@ -73,7 +73,7 @@ public CookieStore cookieStoreFor(String host) { } @Override - public void addCookie(Cookie cookie) { + public void addCookieImpl(Cookie cookie) { cookies.addCookie(cookie); }
795fd180f7e758d79c1c37ade7b21a944a183c07
orientdb
Fixed issues with sharing. Added also first test- case on sharding--
c
https://github.com/orientechnologies/orientdb
diff --git a/distributed/pom.xml b/distributed/pom.xml index 1f0f089bfe8..e97400e1ab1 100644 --- a/distributed/pom.xml +++ b/distributed/pom.xml @@ -47,6 +47,12 @@ <version>${project.version}</version> <scope>compile</scope> </dependency> + <dependency> + <groupId>com.orientechnologies</groupId> + <artifactId>orientdb-graphdb</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> diff --git a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterGraphTest.java b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterGraphTest.java new file mode 100644 index 00000000000..a2e394599c7 --- /dev/null +++ b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterGraphTest.java @@ -0,0 +1,268 @@ +///* +// * Copyright 2010-2012 Luca Garulli (l.garulli(at)orientechnologies.com) +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +// +//package com.orientechnologies.orient.server.distributed; +// +//import java.util.ArrayList; +//import java.util.Date; +//import java.util.Iterator; +//import java.util.List; +//import java.util.UUID; +//import java.util.concurrent.Callable; +//import java.util.concurrent.ExecutorService; +//import java.util.concurrent.Executors; +//import java.util.concurrent.Future; +//import java.util.concurrent.TimeUnit; +// +//import junit.framework.Assert; +// +//import com.orientechnologies.orient.core.db.document.ODatabaseDocumentPool; +//import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +//import com.orientechnologies.orient.core.db.record.OIdentifiable; +//import com.orientechnologies.orient.core.exception.OQueryParsingException; +//import com.orientechnologies.orient.core.metadata.schema.OClass; +//import com.orientechnologies.orient.core.metadata.schema.OClass.INDEX_TYPE; +//import com.orientechnologies.orient.core.metadata.schema.OSchema; +//import com.orientechnologies.orient.core.metadata.schema.OType; +//import com.orientechnologies.orient.core.record.impl.ODocument; +//import com.orientechnologies.orient.core.sql.OCommandSQL; +//import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +//import com.tinkerpop.blueprints.Direction; +//import com.tinkerpop.blueprints.Edge; +//import com.tinkerpop.blueprints.Vertex; +//import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; +//import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; +// +///** +// * Test distributed TX +// */ +//public abstract class AbstractServerClusterGraphTest extends AbstractServerClusterTest { +// protected static final int delayWriter = 0; +// protected static final int delayReader = 1000; +// protected static final int writerCount = 5; +// protected int count = 1000; +// protected long beginInstances; +// +// class Writer implements Callable<Void> { +// private final String databaseUrl; +// private final OrientGraphFactory factory; +// private int serverId; +// +// public Writer(final int iServerId, final String db) { +// serverId = iServerId; +// databaseUrl = db; +// factory = new OrientGraphFactory(databaseUrl, "admin", "admin"); +// } +// +// @Override +// public Void call() throws Exception { +// String name = Integer.toString(serverId); +// for (int i = 0; i < count; i++) { +// final OrientBaseGraph graph = factory.getTx(); +// +// if ((i + 1) % 100 == 0) +// System.out.println("\nWriter " + graph.getRawGraph().getURL() + " managed " + (i + 1) + "/" + count + " records so far"); +// +// Vertex shelve = graph.addVertex(null); +// shelve.setProperty("EQUIP_TYPE", "Shelf"); +// Vertex card = graph.addVertex(null); +// card.setProperty("EQUIP_TYPE", "Card"); +// graph.addEdge(null, shelve, card, "GEO"); +// +// try { +// Iterable<Vertex> vertices = graph.command(new OCommandSQL(queryForVertices.toString())).execute(); +// for (Vertex vertex : vertices) { +// Iterator<Edge> egdeIterator = vertex.getEdges(Direction.OUT, "GEO").iterator(); +// while (egdeIterator.hasNext()) { +// Edge e = egdeIterator.next(); +// graph.removeEdge(e); +// } +// } +// +// Thread.sleep(delayWriter); +// +// } catch (InterruptedException e) { +// System.out.println("Writer received interrupt (db=" + database.getURL()); +// Thread.currentThread().interrupt(); +// break; +// } catch (Exception e) { +// System.out.println("Writer received exception (db=" + database.getURL()); +// e.printStackTrace(); +// break; +// } finally { +// database.close(); +// } +// } +// +// System.out.println("\nWriter " + name + " END"); +// return null; +// } +// +// private ODocument createRecord(ODatabaseDocumentTx database, int i) { +// final int uniqueId = count * serverId + i; +// +// ODocument person = new ODocument("Person").fields("id", UUID.randomUUID().toString(), "name", "Billy" + uniqueId, "surname", +// "Mayes" + uniqueId, "birthday", new Date(), "children", uniqueId); +// database.save(person); +// return person; +// } +// +// private void updateRecord(ODatabaseDocumentTx database, ODocument doc) { +// doc.field("updated", true); +// doc.save(); +// } +// +// private void checkRecord(ODatabaseDocumentTx database, ODocument doc) { +// doc.reload(); +// Assert.assertEquals(doc.field("updated"), Boolean.TRUE); +// } +// } +// +// class Reader implements Callable<Void> { +// private final String databaseUrl; +// +// public Reader(final String db) { +// databaseUrl = db; +// } +// +// @Override +// public Void call() throws Exception { +// try { +// while (!Thread.interrupted()) { +// try { +// printStats(databaseUrl); +// Thread.sleep(delayReader); +// +// } catch (Exception e) { +// break; +// } +// } +// +// } finally { +// printStats(databaseUrl); +// } +// return null; +// } +// } +// +// public String getDatabaseName() { +// return "distributed"; +// } +// +// public void executeTest() throws Exception { +// +// ODatabaseDocumentTx database = ODatabaseDocumentPool.global().acquire(getDatabaseURL(serverInstance.get(0)), "admin", "admin"); +// try { +// List<ODocument> result = database.query(new OSQLSynchQuery<OIdentifiable>("select count(*) from Person")); +// beginInstances = result.get(0).field("count"); +// } finally { +// database.close(); +// } +// +// System.out.println("Creating Writers and Readers threads..."); +// +// final ExecutorService executor = Executors.newCachedThreadPool(); +// +// int i = 0; +// List<Callable<Void>> workers = new ArrayList<Callable<Void>>(); +// for (ServerRun server : serverInstance) { +// for (int j = 0; j < writerCount; j++) { +// Writer writer = new Writer(i++, getDatabaseURL(server)); +// workers.add(writer); +// } +// +// Reader reader = new Reader(getDatabaseURL(server)); +// workers.add(reader); +// } +// +// List<Future<Void>> futures = executor.invokeAll(workers); +// +// System.out.println("Threads started, waiting for the end"); +// +// executor.shutdown(); +// Assert.assertTrue(executor.awaitTermination(10, TimeUnit.MINUTES)); +// +// for (Future<Void> future : futures) { +// future.get(); +// } +// +// System.out.println("All threads have finished, shutting down server instances"); +// +// for (ServerRun server : serverInstance) { +// printStats(getDatabaseURL(server)); +// } +// } +// +// protected abstract String getDatabaseURL(ServerRun server); +// +// /** +// * Event called right after the database has been created and right before to be replicated to the X servers +// * +// * @param db +// * Current database +// */ +// protected void onAfterDatabaseCreation(final ODatabaseDocumentTx db) { +// System.out.println("Creating database schema..."); +// +// // CREATE BASIC SCHEMA +// OClass personClass = db.getMetadata().getSchema().createClass("Person"); +// personClass.createProperty("id", OType.STRING); +// personClass.createProperty("name", OType.STRING); +// personClass.createProperty("birthday", OType.DATE); +// personClass.createProperty("children", OType.INTEGER); +// +// final OSchema schema = db.getMetadata().getSchema(); +// OClass person = schema.getClass("Person"); +// person.createIndex("Person.name", INDEX_TYPE.UNIQUE, "name"); +// +// OClass customer = schema.createClass("Customer", person); +// customer.createProperty("totalSold", OType.DECIMAL); +// +// OClass provider = schema.createClass("Provider", person); +// provider.createProperty("totalPurchased", OType.DECIMAL); +// +// new ODocument("Customer").fields("name", "Jay", "surname", "Miner").save(); +// new ODocument("Customer").fields("name", "Luke", "surname", "Skywalker").save(); +// new ODocument("Provider").fields("name", "Yoda", "surname", "Nothing").save(); +// } +// +// private void printStats(final String databaseUrl) { +// final ODatabaseDocumentTx database = ODatabaseDocumentPool.global().acquire(databaseUrl, "admin", "admin"); +// try { +// List<ODocument> result = database.query(new OSQLSynchQuery<OIdentifiable>("select count(*) from Person")); +// +// final String name = database.getURL(); +// +// System.out.println("\nReader " + name + " sql count: " + result.get(0) + " counting class: " + database.countClass("Person") +// + " counting cluster: " + database.countClusterElements("Person")); +// +// if (database.getMetadata().getSchema().existsClass("ODistributedConflict")) +// try { +// List<ODocument> conflicts = database +// .query(new OSQLSynchQuery<OIdentifiable>("select count(*) from ODistributedConflict")); +// long totalConflicts = conflicts.get(0).field("count"); +// Assert.assertEquals(0l, totalConflicts); +// System.out.println("\nReader " + name + " conflicts: " + totalConflicts); +// } catch (OQueryParsingException e) { +// // IGNORE IT +// } +// +// } finally { +// database.close(); +// } +// +// } +//} diff --git a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterTest.java b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterTest.java index ca13222a8ff..659bc01a8d6 100755 --- a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterTest.java +++ b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/AbstractServerClusterTest.java @@ -15,17 +15,16 @@ */ package com.orientechnologies.orient.server.distributed; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.junit.Assert; - import com.hazelcast.core.Hazelcast; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ODocument; +import org.junit.Assert; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; /** * Test class that creates and executes distributed operations against a cluster of servers created in the same JVM. @@ -40,18 +39,44 @@ public abstract class AbstractServerClusterTest { protected AbstractServerClusterTest() { } - protected abstract String getDatabaseName(); + @SuppressWarnings("unchecked") + public static void main(final String[] args) throws Exception { + Class<? extends AbstractServerClusterTest> testClass = null; + String command = null; + int servers = 2; - /** - * Event called right after the database has been created and right before to be replicated to the X servers - * - * @param db - * Current database - */ - protected void onAfterDatabaseCreation(final ODatabaseDocumentTx db) { + if (args.length > 0) + testClass = (Class<? extends AbstractServerClusterTest>) Class.forName(args[0]); + else + syntaxError(); + + if (args.length > 1) + command = args[1]; + else + syntaxError(); + + if (args.length > 2) + servers = Integer.parseInt(args[2]); + + final AbstractServerClusterTest main = testClass.newInstance(); + main.init(servers); + + if (command.equals("prepare")) + main.prepare(true); + else if (command.equals("execute")) + main.execute(); + else if (command.equals("prepare+execute")) { + main.prepare(true); + main.execute(); + } else + System.out.println("Usage: prepare, execute or prepare+execute ..."); } - protected abstract void executeTest() throws Exception; + private static void syntaxError() { + System.err + .println("Syntax error. Usage: <class> <operation> [<servers>]\nWhere <operation> can be: prepare|execute|prepare+execute"); + System.exit(1); + } public void init(final int servers) { Orient.setRegisterDatabaseByPath(true); @@ -63,7 +88,7 @@ public void execute() throws Exception { System.out.println("Starting test against " + serverInstance.size() + " server nodes..."); for (ServerRun server : serverInstance) { - server.startServer("orientdb-dserver-config-" + server.getServerId() + ".xml"); + server.startServer(getDistributedServerConfiguration(server)); try { Thread.sleep(delayServerStartup * serverInstance.size()); } catch (InterruptedException e) { @@ -80,7 +105,6 @@ public void execute() throws Exception { for (ServerRun server : serverInstance) { final ODocument cfg = server.getServerInstance().getDistributedManager().getClusterConfiguration(); Assert.assertNotNull(cfg); - // Assert.assertEquals(((Collection<?>) cfg.field("members")).size(), serverInstance.size()); } System.out.println("Executing test..."); @@ -88,6 +112,7 @@ public void execute() throws Exception { try { executeTest(); } finally { + System.out.println("Shutting down nodes..."); for (ServerRun server : serverInstance) server.shutdownServer(); Hazelcast.shutdownAll(); @@ -95,7 +120,25 @@ public void execute() throws Exception { } } - protected void prepare() throws IOException { + protected abstract String getDatabaseName(); + + /** + * Event called right after the database has been created and right before to be replicated to the X servers + * + * @param db + * Current database + */ + protected void onAfterDatabaseCreation(final ODatabaseDocumentTx db) { + } + + protected abstract void executeTest() throws Exception; + + /** + * Create the database on first node only + * + * @throws IOException + */ + protected void prepare(final boolean iCopyDatabaseToNodes) throws IOException { // CREATE THE DATABASE final Iterator<ServerRun> it = serverInstance.iterator(); final ServerRun master = it.next(); @@ -110,46 +153,16 @@ protected void prepare() throws IOException { // COPY DATABASE TO OTHER SERVERS while (it.hasNext()) { final ServerRun replicaSrv = it.next(); - master.copyDatabase(getDatabaseName(), replicaSrv.getDatabasePath(getDatabaseName())); - } - } - @SuppressWarnings("unchecked") - public static void main(final String[] args) throws Exception { - Class<? extends AbstractServerClusterTest> testClass = null; - String command = null; - int servers = 2; + replicaSrv.deleteNode(); - if (args.length > 0) - testClass = (Class<? extends AbstractServerClusterTest>) Class.forName(args[0]); - else - syntaxError(); - - if (args.length > 1) - command = args[1]; - else - syntaxError(); - - if (args.length > 2) - servers = Integer.parseInt(args[2]); - - final AbstractServerClusterTest main = testClass.newInstance(); - main.init(servers); - - if (command.equals("prepare")) - main.prepare(); - else if (command.equals("execute")) - main.execute(); - else if (command.equals("prepare+execute")) { - main.prepare(); - main.execute(); - } else - System.out.println("Usage: prepare, execute or prepare+execute ..."); + if (iCopyDatabaseToNodes) + master.copyDatabase(getDatabaseName(), replicaSrv.getDatabasePath(getDatabaseName())); + } } - private static void syntaxError() { - System.err - .println("Syntax error. Usage: <class> <operation> [<servers>]\nWhere <operation> can be: prepare|execute|prepare+execute"); - System.exit(1); + protected String getDistributedServerConfiguration(final ServerRun server) { + return "orientdb-dserver-config-" + server.getServerId() + ".xml"; } + } diff --git a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/ServerRun.java b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/ServerRun.java index 8a0dd2acd19..cee2742d9a8 100644 --- a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/ServerRun.java +++ b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/ServerRun.java @@ -31,8 +31,8 @@ * @author Luca Garulli (l.garulli--at--orientechnologies.com) */ public class ServerRun { - protected String rootPath; protected final String serverId; + protected String rootPath; protected OServer server; public ServerRun(final String iRootPath, final String serverId) { @@ -40,6 +40,30 @@ public ServerRun(final String iRootPath, final String serverId) { this.serverId = serverId; } + public static String getServerHome(final String iServerId) { + return "target/server" + iServerId; + } + + public static String getDatabasePath(final String iServerId, final String iDatabaseName) { + return getServerHome(iServerId) + "/databases/" + iDatabaseName; + } + + public OServer getServerInstance() { + return server; + } + + public String getServerId() { + return serverId; + } + + public String getBinaryProtocolAddress() { + return server.getListenerByProtocol(ONetworkProtocolBinary.class).getListeningAddress(); + } + + public void deleteNode() { + OFileUtils.deleteRecursively(new File(getServerHome())); + } + protected ODatabaseDocumentTx createDatabase(final String iName) { OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false); @@ -67,22 +91,15 @@ protected void copyDatabase(final String iDatabaseName, final String iDestinatio OFileUtils.copyDirectory(new File(getDatabasePath(iDatabaseName)), new File(iDestinationDirectory)); } - public OServer getServerInstance() { - return server; - } - - public String getServerId() { - return serverId; - } - - protected OServer startServer(final String iConfigFile) throws Exception, InstantiationException, IllegalAccessException, + protected OServer startServer(final String iServerConfigFile) throws Exception, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IOException { System.out.println("Starting server " + serverId + " from " + getServerHome() + "..."); System.setProperty("ORIENTDB_HOME", getServerHome()); server = new OServer(); - server.startup(getClass().getClassLoader().getResourceAsStream(iConfigFile)); + server.setServerRootDirectory(getServerHome()); + server.startup(getClass().getClassLoader().getResourceAsStream(iServerConfigFile)); server.activate(); return server; } @@ -100,15 +117,4 @@ protected String getDatabasePath(final String iDatabaseName) { return getDatabasePath(serverId, iDatabaseName); } - public String getBinaryProtocolAddress() { - return server.getListenerByProtocol(ONetworkProtocolBinary.class).getListeningAddress(); - } - - public static String getServerHome(final String iServerId) { - return "target/server" + iServerId; - } - - public static String getDatabasePath(final String iServerId, final String iDatabaseName) { - return getServerHome(iServerId) + "/databases/" + iDatabaseName; - } } diff --git a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/TestDistributed.java b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/TestDistributed.java deleted file mode 100644 index b964f7f9703..00000000000 --- a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/TestDistributed.java +++ /dev/null @@ -1,99 +0,0 @@ -//package com.orientechnologies.orient.server.distributed; -// -//import com.hazelcast.core.Hazelcast; -//import com.hazelcast.core.HazelcastInstance; -//import com.orientechnologies.common.io.OFileUtils; -//import com.orientechnologies.orient.core.record.impl.ODocument; -//import com.orientechnologies.orient.server.OServer; -//import com.orientechnologies.orient.server.OServerMain; -//import com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin; -//import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; -//import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -// -//import java.io.File; -//import java.io.FileNotFoundException; -//import java.util.ArrayList; -//import java.util.Collections; -// -//public class TestDistributed { -// -// private OServer server; -// -// public static class StandaloneHazelcastPlugin extends OHazelcastPlugin { -// -// @Override -// protected HazelcastInstance configureHazelcast() throws FileNotFoundException { -// return Hazelcast.newHazelcastInstance(); -// } -// -// @Override -// protected ODocument loadDatabaseConfiguration(String iDatabaseName, File file) { -// ODocument doc = new ODocument(); -// doc.field("replication", true) -// .field("autoDeploy", true) -// .field("hotAlignment", true) -// .field("resyncEvery", 15) -// .field( -// "clusters", -// new ODocument() -// .field("internal", new ODocument().field("replication", false)) -// .field("index", new ODocument().field("replication", false)) -// .field( -// "*", -// new ODocument() -// .field("replication", true) -// .field("readQuorum", 1) -// .field("writeQuorum", 1) -// .field("failureAvailableNodesLessQuorum", false) -// .field("readYourWrites", true) -// .field( -// "partitioning", -// new ODocument() -// .field("strategy", "round-robin") -// .field("default", 0) -// .field("partitions", Collections.singletonList(new ArrayList<String>(Collections.singletonList("<NEW_NODE>"))))))); -// -// return doc; -// } -// } -// -// @Before -// public void setUp() throws Exception { -// File target = new File("target/testdb"); -// OFileUtils.deleteRecursively(target); -// target.mkdirs(); -// -// server = OServerMain.create(); -// server -// .startup("<orient-server>" -// + "<handlers>" -// + "<handler class=\"" -// + StandaloneHazelcastPlugin.class.getName() -// + "\">" -// + "<parameters>" -// + "<parameter name=\"enabled\" value=\"true\" />" -// + "<parameter name=\"sharding.strategy.round-robin\" value=\"com.orientechnologies.orient.server.hazelcast.sharding.strategy.ORoundRobinPartitioninStrategy\" />" -// + "</parameters>" -// + "</handler>" -// + "</handlers>" -// + "<network><protocols></protocols><listeners></listeners><cluster></cluster></network><storages></storages><users></users>" -// + "<properties><entry name=\"server.database.path\" value=\"target/\"/></properties>" + "</orient-server>"); -// server.activate(); -// } -// -// @After -// public void tearDown() { -// server.shutdown(); -// } -// -// @Test -// public void testCreateClass() { -// OrientGraphFactory factory = new OrientGraphFactory("plocal:target/testdb"); -// OrientGraphNoTx graph = factory.getNoTx(); -// -// graph.addVertex(null); -// } -//} diff --git a/distributed/src/test/java/com/orientechnologies/orient/server/distributed/TestSharding.java b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/TestSharding.java new file mode 100644 index 00000000000..e3c415bc60f --- /dev/null +++ b/distributed/src/test/java/com/orientechnologies/orient/server/distributed/TestSharding.java @@ -0,0 +1,69 @@ +package com.orientechnologies.orient.server.distributed; + +import junit.framework.Assert; + +import org.junit.Test; + +import com.orientechnologies.orient.core.sql.OCommandSQL; +import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; +import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; +import com.tinkerpop.blueprints.impls.orient.OrientVertex; +import com.tinkerpop.blueprints.impls.orient.OrientVertexType; + +public class TestSharding extends AbstractServerClusterTest { + + protected OrientVertex[] vertices; + + @Test + public void test() throws Exception { + init(3); + prepare(false); + execute(); + } + + @Override + protected String getDatabaseName() { + return "sharding"; + } + + @Override + protected String getDistributedServerConfiguration(final ServerRun server) { + return "sharded-dserver-config-" + server.getServerId() + ".xml"; + } + + @Override + protected void executeTest() throws Exception { + OrientGraphFactory factory = new OrientGraphFactory("plocal:target/server0/databases/" + getDatabaseName()); + OrientGraphNoTx graph = factory.getNoTx(); + + try { + final OrientVertexType clientType = graph.createVertexType("Client"); + + vertices = new OrientVertex[serverInstance.size()]; + for (int i = 0; i < vertices.length; ++i) { + clientType.addCluster("client_" + i); + + vertices[i] = graph.addVertex("class:Client,cluster:client_" + i); + vertices[i].setProperty("name", "shard_" + i); + } + } finally { + graph.shutdown(); + } + + for (int i = 0; i < vertices.length; ++i) { + OrientGraphFactory f = new OrientGraphFactory("plocal:target/server" + i + "/databases/" + getDatabaseName()); + OrientGraphNoTx g = f.getNoTx(); + try { + Iterable<OrientVertex> result = g.command(new OCommandSQL("select from Client")).execute(); + Assert.assertTrue(result.iterator().hasNext()); + + OrientVertex v = result.iterator().next(); + + Assert.assertEquals(v.getProperty("name"), "shard_" + i); + + } finally { + graph.shutdown(); + } + } + } +} diff --git a/distributed/src/test/resources/sharded-distributed-db-config.json b/distributed/src/test/resources/sharded-distributed-db-config.json new file mode 100644 index 00000000000..a7b381e9498 --- /dev/null +++ b/distributed/src/test/resources/sharded-distributed-db-config.json @@ -0,0 +1,58 @@ +{ + "replication": true, + "autoDeploy": true, + "hotAlignment": true, + "resyncEvery": 15, + "clusters": { + "internal": { + "replication": false + }, + "index": { + "replication": false + }, + "client_0": { + "replication": false, + "partitioning": { + "strategy": "round-robin", + "default": 0, + "partitions": [ + [ "europe" ] + ] + } + }, + "client_1": { + "replication": false, + "partitioning": { + "strategy": "round-robin", + "default": 0, + "partitions": [ + [ "usa" ] + ] + } + }, + "client_2": { + "replication": false, + "partitioning": { + "strategy": "round-robin", + "default": 0, + "partitions": [ + [ "asia" ] + ] + } + }, + "*": { + "replication": true, + "readQuorum": 1, + "writeQuorum": 2, + "failureAvailableNodesLessQuorum": false, + "readYourWrites": true, + "partitioning": { + "strategy": "round-robin", + "default": 0, + "partitions": [ + [ "<NEW_NODE>" ] + ] + } + } + } +} diff --git a/distributed/src/test/resources/sharded-dserver-config-0.xml b/distributed/src/test/resources/sharded-dserver-config-0.xml new file mode 100755 index 00000000000..0e0c1ed1453 --- /dev/null +++ b/distributed/src/test/resources/sharded-dserver-config-0.xml @@ -0,0 +1,106 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<orient-server> + <handlers> + <handler + class="com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin"> + <parameters> + <parameter value="europe" name="nodeName" /> + <parameter value="true" name="enabled" /> + <parameter value="src/test/resources/sharded-hazelcast.xml" + name="configuration.hazelcast" /> + <parameter name="conflict.resolver.impl" + value="com.orientechnologies.orient.server.distributed.conflict.ODefaultReplicationConflictResolver" /> + <parameter name="configuration.db.default" + value="src/test/resources/sharded-distributed-db-config.json" /> + + <parameter name="sharding.strategy.round-robin" + value="com.orientechnologies.orient.server.hazelcast.sharding.strategy.ORoundRobinPartitioninStrategy" /> + </parameters> + </handler> + <handler + class="com.orientechnologies.orient.server.handler.OAutomaticBackup"> + <parameters> + <parameter value="false" name="enabled" /> + <parameter value="4h" name="delay" /> + <parameter value="backup" name="target.directory" /> + <parameter value="${DBNAME}-${DATE:yyyyMMddHHmmss}.json" + name="target.fileName" /> + <parameter value="" name="db.include" /> + <parameter value="" name="db.exclude" /> + </parameters> + </handler> + <handler + class="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter"> + <parameters> + <parameter value="false" name="enabled" /> + </parameters> + </handler> + </handlers> + <network> + <protocols> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary" + name="binary" /> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb" + name="http" /> + </protocols> + <listeners> + <listener protocol="binary" port-range="2424-2430" + ip-address="0.0.0.0" /> + <listener protocol="http" port-range="2480-2490" ip-address="0.0.0.0"> + <parameters> + <!-- Connection's custom parameters. If not specified the global configuration + will be taken --> + <parameter name="network.http.charset" value="utf-8" /> + <!-- Define additional HTTP headers to always send as response --> + <!-- Allow cross-site scripting --> + <!-- parameter name="network.http.additionalResponseHeaders" value="Access-Control-Allow-Origin: + *;Access-Control-Allow-Credentials: true" / --> + </parameters> + <commands> + <command + implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent" + pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg"> + <parameters> + <entry + value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache" + name="http.cache:*.htm *.html" /> + <entry value="Cache-Control: max-age=120" name="http.cache:default" /> + </parameters> + </command> + </commands> + </listener> + </listeners> + </network> + <storages> + </storages> + <users> + <user resources="*" password="test" name="root" /> + <user resources="connect,server.listDatabases" password="guest" + name="guest" /> + <user resources="database.passthrough" + password="79498491C4D4F1360816D003E2004BC04606AA1C31B1A0E3BCF091A30EFDAB7D" + name="replicator" /> + </users> + <properties> + <!-- DATABASE POOL: size min/max --> + <entry name="db.pool.min" value="1" /> + <entry name="db.pool.max" value="20" /> + + <!-- LEVEL1 AND 2 CACHE: enable/disable and set the size as number of entries --> + <entry name="cache.level1.enabled" value="false" /> + <entry name="cache.level1.size" value="1000" /> + <entry name="cache.level2.enabled" value="true" /> + <entry name="cache.level2.size" value="1000" /> + + <!-- PROFILER: configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size> --> + <entry name="profiler.enabled" value="true" /> + <!-- <entry name="profiler.config" value="30,10,10" /> --> + + <!-- LOG: enable/Disable logging. Levels are: finer, fine, finest, info, + warning --> + <entry name="log.console.level" value="info" /> + <entry name="log.file.level" value="fine" /> + </properties> +</orient-server> diff --git a/distributed/src/test/resources/sharded-dserver-config-1.xml b/distributed/src/test/resources/sharded-dserver-config-1.xml new file mode 100755 index 00000000000..6454f9109b8 --- /dev/null +++ b/distributed/src/test/resources/sharded-dserver-config-1.xml @@ -0,0 +1,106 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<orient-server> + <handlers> + <handler + class="com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin"> + <parameters> + <parameter value="usa" name="nodeName" /> + <parameter value="true" name="enabled" /> + <parameter value="src/test/resources/sharded-hazelcast.xml" + name="configuration.hazelcast" /> + <parameter name="conflict.resolver.impl" + value="com.orientechnologies.orient.server.distributed.conflict.ODefaultReplicationConflictResolver" /> + <parameter name="configuration.db.default" + value="src/test/resources/sharded-distributed-db-config.json" /> + + <parameter name="sharding.strategy.round-robin" + value="com.orientechnologies.orient.server.hazelcast.sharding.strategy.ORoundRobinPartitioninStrategy" /> + </parameters> + </handler> + <handler + class="com.orientechnologies.orient.server.handler.OAutomaticBackup"> + <parameters> + <parameter value="false" name="enabled" /> + <parameter value="4h" name="delay" /> + <parameter value="backup" name="target.directory" /> + <parameter value="${DBNAME}-${DATE:yyyyMMddHHmmss}.json" + name="target.fileName" /> + <parameter value="" name="db.include" /> + <parameter value="" name="db.exclude" /> + </parameters> + </handler> + <handler + class="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter"> + <parameters> + <parameter value="false" name="enabled" /> + </parameters> + </handler> + </handlers> + <network> + <protocols> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary" + name="binary" /> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb" + name="http" /> + </protocols> + <listeners> + <listener protocol="binary" port-range="2424-2430" + ip-address="0.0.0.0" /> + <listener protocol="http" port-range="2480-2490" ip-address="0.0.0.0"> + <parameters> + <!-- Connection's custom parameters. If not specified the global configuration + will be taken --> + <parameter name="network.http.charset" value="utf-8" /> + <!-- Define additional HTTP headers to always send as response --> + <!-- Allow cross-site scripting --> + <!-- parameter name="network.http.additionalResponseHeaders" value="Access-Control-Allow-Origin: + *;Access-Control-Allow-Credentials: true" / --> + </parameters> + <commands> + <command + implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent" + pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg"> + <parameters> + <entry + value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache" + name="http.cache:*.htm *.html" /> + <entry value="Cache-Control: max-age=120" name="http.cache:default" /> + </parameters> + </command> + </commands> + </listener> + </listeners> + </network> + <storages> + </storages> + <users> + <user resources="*" password="test" name="root" /> + <user resources="connect,server.listDatabases" password="guest" + name="guest" /> + <user resources="database.passthrough" + password="79498491C4D4F1360816D003E2004BC04606AA1C31B1A0E3BCF091A30EFDAB7D" + name="replicator" /> + </users> + <properties> + <!-- DATABASE POOL: size min/max --> + <entry name="db.pool.min" value="1" /> + <entry name="db.pool.max" value="20" /> + + <!-- LEVEL1 AND 2 CACHE: enable/disable and set the size as number of entries --> + <entry name="cache.level1.enabled" value="false" /> + <entry name="cache.level1.size" value="1000" /> + <entry name="cache.level2.enabled" value="true" /> + <entry name="cache.level2.size" value="1000" /> + + <!-- PROFILER: configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size> --> + <entry name="profiler.enabled" value="true" /> + <!-- <entry name="profiler.config" value="30,10,10" /> --> + + <!-- LOG: enable/Disable logging. Levels are: finer, fine, finest, info, + warning --> + <entry name="log.console.level" value="info" /> + <entry name="log.file.level" value="fine" /> + </properties> +</orient-server> diff --git a/distributed/src/test/resources/sharded-dserver-config-2.xml b/distributed/src/test/resources/sharded-dserver-config-2.xml new file mode 100755 index 00000000000..92c92f707ba --- /dev/null +++ b/distributed/src/test/resources/sharded-dserver-config-2.xml @@ -0,0 +1,106 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<orient-server> + <handlers> + <handler + class="com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin"> + <parameters> + <parameter value="asia" name="nodeName" /> + <parameter value="true" name="enabled" /> + <parameter value="src/test/resources/sharded-hazelcast.xml" + name="configuration.hazelcast" /> + <parameter name="conflict.resolver.impl" + value="com.orientechnologies.orient.server.distributed.conflict.ODefaultReplicationConflictResolver" /> + <parameter name="configuration.db.default" + value="src/test/resources/sharded-distributed-db-config.json" /> + + <parameter name="sharding.strategy.round-robin" + value="com.orientechnologies.orient.server.hazelcast.sharding.strategy.ORoundRobinPartitioninStrategy" /> + </parameters> + </handler> + <handler + class="com.orientechnologies.orient.server.handler.OAutomaticBackup"> + <parameters> + <parameter value="false" name="enabled" /> + <parameter value="4h" name="delay" /> + <parameter value="backup" name="target.directory" /> + <parameter value="${DBNAME}-${DATE:yyyyMMddHHmmss}.json" + name="target.fileName" /> + <parameter value="" name="db.include" /> + <parameter value="" name="db.exclude" /> + </parameters> + </handler> + <handler + class="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter"> + <parameters> + <parameter value="false" name="enabled" /> + </parameters> + </handler> + </handlers> + <network> + <protocols> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary" + name="binary" /> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb" + name="http" /> + </protocols> + <listeners> + <listener protocol="binary" port-range="2424-2430" + ip-address="0.0.0.0" /> + <listener protocol="http" port-range="2480-2490" ip-address="0.0.0.0"> + <parameters> + <!-- Connection's custom parameters. If not specified the global configuration + will be taken --> + <parameter name="network.http.charset" value="utf-8" /> + <!-- Define additional HTTP headers to always send as response --> + <!-- Allow cross-site scripting --> + <!-- parameter name="network.http.additionalResponseHeaders" value="Access-Control-Allow-Origin: + *;Access-Control-Allow-Credentials: true" / --> + </parameters> + <commands> + <command + implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent" + pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg"> + <parameters> + <entry + value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache" + name="http.cache:*.htm *.html" /> + <entry value="Cache-Control: max-age=120" name="http.cache:default" /> + </parameters> + </command> + </commands> + </listener> + </listeners> + </network> + <storages> + </storages> + <users> + <user resources="*" password="test" name="root" /> + <user resources="connect,server.listDatabases" password="guest" + name="guest" /> + <user resources="database.passthrough" + password="79498491C4D4F1360816D003E2004BC04606AA1C31B1A0E3BCF091A30EFDAB7D" + name="replicator" /> + </users> + <properties> + <!-- DATABASE POOL: size min/max --> + <entry name="db.pool.min" value="1" /> + <entry name="db.pool.max" value="20" /> + + <!-- LEVEL1 AND 2 CACHE: enable/disable and set the size as number of entries --> + <entry name="cache.level1.enabled" value="false" /> + <entry name="cache.level1.size" value="1000" /> + <entry name="cache.level2.enabled" value="true" /> + <entry name="cache.level2.size" value="1000" /> + + <!-- PROFILER: configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size> --> + <entry name="profiler.enabled" value="true" /> + <!-- <entry name="profiler.config" value="30,10,10" /> --> + + <!-- LOG: enable/Disable logging. Levels are: finer, fine, finest, info, + warning --> + <entry name="log.console.level" value="info" /> + <entry name="log.file.level" value="fine" /> + </properties> +</orient-server> diff --git a/distributed/src/test/resources/sharded-hazelcast.xml b/distributed/src/test/resources/sharded-hazelcast.xml new file mode 100755 index 00000000000..51c8423e700 --- /dev/null +++ b/distributed/src/test/resources/sharded-hazelcast.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- ~ Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved. ~ + ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may + not use this file except in compliance with the License. ~ You may obtain + a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ + ~ Unless required by applicable law or agreed to in writing, software ~ distributed + under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES + OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for + the specific language governing permissions and ~ limitations under the License. --> + +<hazelcast + xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.0.xsd" + xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <group> + <name>orientdb</name> + <password>orientdb</password> + </group> + <network> + <port auto-increment="true">2434</port> + <join> + <multicast enabled="true"> + <multicast-group>224.2.2.3</multicast-group> + <multicast-port>2434</multicast-port> + </multicast> + <tcp-ip enabled="false"> + <member>127.0.0.1:2435</member> + <interface>127.0.0.1</interface> + </tcp-ip> + </join> + </network> +</hazelcast> diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java index 605f81bf6e7..9df19ef75bc 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java +++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java @@ -146,7 +146,8 @@ public Object command(final OCommandRequestText iCommand) { // ALREADY DISTRIBUTED return wrapped.command(iCommand); - if (!dManager.getDatabaseConfiguration(getName()).isReplicationActive(null)) + final ODistributedConfiguration dbCfg = dManager.getDatabaseConfiguration(getName()); + if (!dbCfg.isReplicationActive(null) && dbCfg.getPartitioningConfiguration(null) == null) // DON'T REPLICATE return wrapped.command(iCommand); @@ -249,12 +250,13 @@ public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRecordId, try { final String clusterName = getClusterNameByRID(iRecordId); - final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); - if (!dManager.getDatabaseConfiguration(getName()).isReplicationActive(clusterName)) + + final ODistributedConfiguration dbCfg = dManager.getDatabaseConfiguration(getName()); + if (!dbCfg.isReplicationActive(clusterName) && dbCfg.getPartitioningConfiguration(clusterName) == null) // DON'T REPLICATE return wrapped.readRecord(iRecordId, iFetchPlan, iIgnoreCache, iCallback, loadTombstones, LOCKING_STRATEGY.DEFAULT); - final ODistributedPartitioningStrategy strategy = dManager.getPartitioningStrategy(dConfig.getPartitionStrategy(clusterName)); + final ODistributedPartitioningStrategy strategy = dManager.getPartitioningStrategy(dbCfg.getPartitionStrategy(clusterName)); final ODistributedPartition partition = strategy.getPartition(dManager, getName(), clusterName); if (partition.getNodes().contains(dManager.getLocalNodeName())) // LOCAL NODE OWNS THE DATA: GET IT LOCALLY BECAUSE IT'S FASTER @@ -293,12 +295,13 @@ public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRec try { final String clusterName = getClusterNameByRID(iRecordId); - if (!dManager.getDatabaseConfiguration(getName()).isReplicationActive(clusterName)) + final ODistributedConfiguration dbCfg = dManager.getDatabaseConfiguration(getName()); + if (!dbCfg.isReplicationActive(clusterName) && dbCfg.getPartitioningConfiguration(clusterName) == null) // DON'T REPLICATE return wrapped.updateRecord(iRecordId, iContent, iVersion, iRecordType, iMode, iCallback); // LOAD PREVIOUS CONTENT TO BE USED IN CASE OF UNDO - final OStorageOperationResult<ORawBuffer> previousContent = wrapped.readRecord(iRecordId, null, false, null, false, + final OStorageOperationResult<ORawBuffer> previousContent = readRecord(iRecordId, null, false, null, false, LOCKING_STRATEGY.DEFAULT); // REPLICATE IT @@ -337,7 +340,8 @@ public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRecordId, try { final String clusterName = getClusterNameByRID(iRecordId); - if (!dManager.getDatabaseConfiguration(getName()).isReplicationActive(clusterName)) + final ODistributedConfiguration dbCfg = dManager.getDatabaseConfiguration(getName()); + if (!dbCfg.isReplicationActive(clusterName) && dbCfg.getPartitioningConfiguration(clusterName) == null) // DON'T REPLICATE return wrapped.deleteRecord(iRecordId, iVersion, iMode, iCallback); @@ -441,7 +445,8 @@ public void commit(final OTransaction iTx, final Runnable callback) { wrapped.commit(iTx, callback); else { try { - if (!dManager.getDatabaseConfiguration(getName()).isReplicationActive(null)) + final ODistributedConfiguration dbCfg = dManager.getDatabaseConfiguration(getName()); + if (!dbCfg.isReplicationActive(null) && dbCfg.getPartitioningConfiguration(null) == null) // DON'T REPLICATE wrapped.commit(iTx, callback); else {
65dfba12937a209965cf87f21c01ce594d3d4a00
Search_api
Issue #1288724 by brunodbo, drunken monkey, fearlsgroove: Added option for using OR in Views fulltext search.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index e6f99e20..0befa20d 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,7 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #1288724 by brunodbo, drunken monkey, fearlsgroove: Added option for using OR + in Views fulltext search. - #1694832 by drunken monkey: Fixed index field settings getting stale when Field API field settings change. - #1285794 by drunken monkey: Fixed "All" option in Views' exposed "Items per diff --git a/contrib/search_api_views/includes/handler_argument_fulltext.inc b/contrib/search_api_views/includes/handler_argument_fulltext.inc index 684df287..a2b3f553 100644 --- a/contrib/search_api_views/includes/handler_argument_fulltext.inc +++ b/contrib/search_api_views/includes/handler_argument_fulltext.inc @@ -11,6 +11,7 @@ class SearchApiViewsHandlerArgumentFulltext extends SearchApiViewsHandlerArgumen public function option_definition() { $options = parent::option_definition(); $options['fields'] = array('default' => array()); + $options['conjunction'] = array('default' => 'AND'); return $options; } @@ -33,6 +34,17 @@ class SearchApiViewsHandlerArgumentFulltext extends SearchApiViewsHandlerArgumen '#multiple' => TRUE, '#default_value' => $this->options['fields'], ); + $form['conjunction'] = array( + '#title' => t('Operator'), + '#description' => t('Determines how multiple keywords entered for the search will be combined.'), + '#type' => 'radios', + '#options' => array( + 'AND' => t('Contains all of these words'), + 'OR' => t('Contains any of these words'), + ), + '#default_value' => $this->options['conjunction'], + ); + } else { $form['fields'] = array( @@ -51,6 +63,9 @@ class SearchApiViewsHandlerArgumentFulltext extends SearchApiViewsHandlerArgumen if ($this->options['fields']) { $this->query->fields($this->options['fields']); } + if ($this->options['conjunction'] != 'AND') { + $this->query->setOption('conjunction', $this->options['conjunction']); + } $old = $this->query->getOriginalKeys(); $this->query->keys($this->argument); diff --git a/contrib/search_api_views/includes/handler_filter_fulltext.inc b/contrib/search_api_views/includes/handler_filter_fulltext.inc index 403d0e36..9ab1f94f 100644 --- a/contrib/search_api_views/includes/handler_filter_fulltext.inc +++ b/contrib/search_api_views/includes/handler_filter_fulltext.inc @@ -5,6 +5,25 @@ */ class SearchApiViewsHandlerFilterFulltext extends SearchApiViewsHandlerFilterText { + /** + * Displays the operator form, adding a description. + */ + public function show_operator_form(&$form, &$form_state) { + $this->operator_form($form, $form_state); + $form['operator']['#description'] = t('This operator is only useful when using \'Search keys\'.'); + } + + /** + * Provide a list of options for the operator form. + */ + public function operator_options() { + return array( + 'AND' => t('Contains all of these words'), + 'OR' => t('Contains any of these words'), + 'NOT' => t('Contains none of these words'), + ); + } + /** * Specify the options this filter uses. */ @@ -87,10 +106,16 @@ class SearchApiViewsHandlerFilterFulltext extends SearchApiViewsHandlerFilterTex return; } + // If the operator was set to OR, set it as the conjunction. (AND is set by + // default.) + if ($this->operator === 'OR') { + $this->query->setOption('conjunction', $this->operator); + } + $this->query->fields($fields); $old = $this->query->getOriginalKeys(); $this->query->keys($this->value); - if ($this->operator != '=') { + if ($this->operator == 'NOT') { $keys = &$this->query->getKeys(); if (is_array($keys)) { $keys['#negation'] = TRUE;
48701edad8513b27acec7216581e64637157c86a
drools
DROOLS-515 Kie-Camel is broken after Camel Update- -Added static field
a
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java index 1730089c241..f9b85e851b4 100644 --- a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java +++ b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java @@ -45,6 +45,7 @@ import org.drools.core.command.runtime.rule.ModifyCommand; import org.drools.core.command.runtime.rule.QueryCommand; import org.drools.core.common.DefaultFactHandle; +import org.drools.core.common.InternalFactHandle; import org.drools.core.util.StringUtils; import org.drools.core.runtime.impl.ExecutionResultImpl; import org.drools.core.runtime.rule.impl.FlatQueryResults; @@ -59,6 +60,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -675,12 +677,15 @@ public void marshal(Object object, ExecutionResults result = (ExecutionResults) object; writer.startNode( "results" ); if ( !result.getIdentifiers().isEmpty() ) { + + Collection<String> identifiers = result.getIdentifiers(); // this gets sorted, otherwise unit tests will not pass - Collection<String> col = result.getIdentifiers(); - String[] identifiers = col.toArray( new String[col.size()]); if ( SORT_MAPS ) { - Arrays.sort(identifiers); + String[] array = identifiers.toArray( new String[identifiers.size()]); + Arrays.sort(array); + identifiers = Arrays.asList(array); } + for ( String identifier : identifiers ) { writer.startNode( "result" ); @@ -706,7 +711,16 @@ public void marshal(Object object, } } - for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) { + + Collection<String> handles = ((ExecutionResultImpl) result).getFactHandles().keySet(); + // this gets sorted, otherwise unit tests will not pass + if (SORT_MAPS) { + String[] array = handles.toArray( new String[handles.size()]); + Arrays.sort(array); + handles = Arrays.asList(array); + } + + for ( String identifier : handles ) { Object handle = result.getFactHandle( identifier ); if ( handle instanceof FactHandle ) { writer.startNode( "fact-handle" ); diff --git a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java index 156116e4bd6..54d5a9070ae 100644 --- a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java +++ b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java @@ -65,6 +65,7 @@ import com.thoughtworks.xstream.io.HierarchicalStreamWriter; public class XStreamXML { + public static volatile boolean SORT_MAPS = false; public static XStream newXStreamMarshaller(XStream xstream) { XStreamHelper.setAliases( xstream ); @@ -808,7 +809,16 @@ public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) { ExecutionResults result = (ExecutionResults) object; - for ( String identifier : result.getIdentifiers() ) { + + Collection<String> identifiers = result.getIdentifiers(); + // this gets sorted, otherwise unit tests will not pass + if ( SORT_MAPS ) { + String[] array = identifiers.toArray( new String[identifiers.size()]); + Arrays.sort(array); + identifiers = Arrays.asList(array); + } + + for ( String identifier : identifiers ) { writer.startNode( "result" ); writer.addAttribute( "identifier", identifier ); @@ -828,7 +838,15 @@ public void marshal(Object object, writer.endNode(); } - for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) { + Collection<String> handles = ((ExecutionResultImpl) result).getFactHandles().keySet(); + // this gets sorted, otherwise unit tests will not pass + if (SORT_MAPS) { + String[] array = handles.toArray( new String[handles.size()]); + Arrays.sort(array); + handles = Arrays.asList(array); + } + + for ( String identifier : handles ) { Object handle = result.getFactHandle( identifier ); if ( handle instanceof FactHandle ) { writer.startNode( "fact-handle" );
afb42145aeb0d228a638628582631975db4bb473
drools
-Few fixes to manners--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@2061 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
c
https://github.com/kiegroup/drools
diff --git a/drools-core/src/test/java/org/drools/examples/manners/Chosen.java b/drools-core/src/test/java/org/drools/examples/manners/Chosen.java index 9ea43fae8b6..cf75f2ae2a9 100644 --- a/drools-core/src/test/java/org/drools/examples/manners/Chosen.java +++ b/drools-core/src/test/java/org/drools/examples/manners/Chosen.java @@ -76,6 +76,6 @@ public Hobby getHobby() { } public String toString() { - return "{guest name=" + this.guestName + ",hobbies=" + this.hobby + "}"; + return "{Chosen id=" + this.id + ", name=" + this.guestName + ", hobbies=" + this.hobby + "}"; } } \ No newline at end of file diff --git a/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java b/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java index eeec4dbb19b..d41aae4b5f3 100644 --- a/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java +++ b/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java @@ -109,9 +109,17 @@ protected void setUp() throws Exception { this.booleanNotEqualEvaluator = EvaluatorFactory.getInstance().getEvaluator( Evaluator.BOOLEAN_TYPE, Evaluator.NOT_EQUAL ); - } - - public void test1() throws DuplicateRuleNameException, InvalidRuleException, IntrospectionException, RuleIntegrationException, RuleSetIntegrationException, InvalidPatternException, FactException, IOException, InterruptedException { + } + + public void test1() throws DuplicateRuleNameException, + InvalidRuleException, + IntrospectionException, + RuleIntegrationException, + RuleSetIntegrationException, + InvalidPatternException, + FactException, + IOException, + InterruptedException { RuleSet ruleSet = new RuleSet( "Miss Manners" ); ruleSet.addRule( getAssignFirstSeatRule() ); ruleSet.addRule( getMakePath() ); @@ -119,59 +127,58 @@ public void test1() throws DuplicateRuleNameException, InvalidRuleException, Int ruleSet.addRule( getPathDone() ); ruleSet.addRule( getAreWeDone() ); ruleSet.addRule( getContinueProcessing() ); -// ruleSet.addRule( getAllDone() ); - + // ruleSet.addRule( getAllDone() ); + final RuleBaseImpl ruleBase = new RuleBaseImpl(); ruleBase.addRuleSet( ruleSet ); - -// final ReteooJungViewer viewer = new ReteooJungViewer(ruleBase); -// -// javax.swing.SwingUtilities.invokeLater(new Runnable() { -// public void run() { -// viewer.showGUI(); -// } -// }); - - + + // final ReteooJungViewer viewer = new ReteooJungViewer(ruleBase); + // + // javax.swing.SwingUtilities.invokeLater(new Runnable() { + // public void run() { + // viewer.showGUI(); + // } + // }); + WorkingMemory workingMemory = ruleBase.newWorkingMemory(); - + InputStream is = getClass().getResourceAsStream( "/manners16.dat" ); - List list = getInputObjects(is); - for (Iterator it = list.iterator(); it.hasNext(); ) { - FactHandle handle = workingMemory.assertObject( it.next() ); + List list = getInputObjects( is ); + for ( Iterator it = list.iterator(); it.hasNext(); ) { + FactHandle handle = workingMemory.assertObject( it.next() ); } - - workingMemory.assertObject( new Count(0) ); - + + workingMemory.assertObject( new Count( 1 ) ); + workingMemory.fireAllRules(); - -// while (viewer.isRunning()) { -// Thread.sleep( 1000 ); -// } - + + // while (viewer.isRunning()) { + // Thread.sleep( 1000 ); + // } + } /** * <pre> - * rule assignFirstSeat() { - * Context context; - * Guest guest; - * Count count; - * when { - * context : Context( state == Context.START_UP ) - * guest : Guest() - * count : Count() - * } then { - * String guestName = guest.getName(); - * drools.assert( new Seating( count.getValue(), 1, true, 1, guestName, 1, guestName) ); - * drools.assert( new Path( count.getValue(), 1, guestName ) ); - * count.setCount( count.getValue() + 1 ); - * - * System.out.println( &quot;seat 1 &quot; + guest.getName() + &quot; ); - * - * context.setPath( Context.ASSIGN_SEATS ); - * } - * } + * rule assignFirstSeat() { + * Context context; + * Guest guest; + * Count count; + * when { + * context : Context( state == Context.START_UP ) + * guest : Guest() + * count : Count() + * } then { + * String guestName = guest.getName(); + * drools.assert( new Seating( count.getValue(), 1, true, 1, guestName, 1, guestName) ); + * drools.assert( new Path( count.getValue(), 1, guestName ) ); + * count.setCount( count.getValue() + 1 ); + * + * System.out.println( &quot;seat 1 &quot; + guest.getName() + &quot; ); + * + * context.setPath( Context.ASSIGN_SEATS ); + * } + * } * </pre> * * @@ -236,16 +243,21 @@ public void invoke(Activation activation) throws ConsequenceException { String guestName = guest.getName(); - drools.assertObject( new Seating( count.getValue(), - 0, - true, - 1, - guestName, - 1, - guestName ) ); - drools.assertObject( new Path( count.getValue(), + Seating seating = new Seating( count.getValue(), + 0, + true, + 1, + guestName, 1, - guestName ) ); + guestName ); + + drools.assertObject( seating ); + + Path path = new Path( count.getValue(), + 0, + guestName ); + + drools.assertObject( path ); count.setValue( count.getValue() + 1 ); drools.modifyObject( tuple.getFactHandleForDeclaration( countDeclaration ), @@ -254,9 +266,10 @@ public void invoke(Activation activation) throws ConsequenceException { context.setState( Context.ASSIGN_SEATS ); drools.modifyObject( tuple.getFactHandleForDeclaration( contextDeclaration ), context ); - System.out.println( "assigned first seat : " + guest ); + System.out.println( "assign first seat : " + seating + " : " + path ); - } catch ( Exception e ) { + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -270,21 +283,21 @@ public void invoke(Activation activation) throws ConsequenceException { /** * <pre> - * rule makePath() { - * Context context; - * int seatingId, seatingPid, pathSeat; - * String pathGuestName; - * - * when { - * context : Context( state == Context.MAKE_PATH ) - * Seating( seatingId:id, seatingPid:pid, pathDone == false ) - * Path( id == seatingPid, pathGuestName:guest, pathSeat:seat ) - * (not Path( id == seatingId, guestName == pathGuestName ) - * } else { - * drools.assert( new Path( seatingId, pathSeat, pathGuestName ) ); - * - * } - * } + * rule makePath() { + * Context context; + * int seatingId, seatingPid, pathSeat; + * String pathGuestName; + * + * when { + * context : Context( state == Context.MAKE_PATH ) + * Seating( seatingId:id, seatingPid:pid, pathDone == false ) + * Path( id == seatingPid, pathGuestName:guest, pathSeat:seat ) + * (not Path( id == seatingId, guestName == pathGuestName ) + * } else { + * drools.assert( new Path( seatingId, pathSeat, pathGuestName ) ); + * + * } + * } * </pre> * * @return @@ -292,7 +305,7 @@ public void invoke(Activation activation) throws ConsequenceException { * @throws InvalidRuleException */ private Rule getMakePath() throws IntrospectionException, - InvalidRuleException { + InvalidRuleException { final Rule rule = new Rule( "makePath" ); // ----------- @@ -385,17 +398,18 @@ public void invoke(Activation activation) throws ConsequenceException { tuple ); int id = ((Integer) tuple.get( seatingIdDeclaration )).intValue(); - String guestName = (String) tuple.get( pathGuestNameDeclaration ); int seat = ((Integer) tuple.get( pathSeatDeclaration )).intValue(); + String guestName = (String) tuple.get( pathGuestNameDeclaration ); Path path = new Path( id, seat, guestName ); - + drools.assertObject( path ); - + System.out.println( "make path : " + path ); - } catch ( Exception e ) { + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -409,37 +423,37 @@ public void invoke(Activation activation) throws ConsequenceException { /** * <pre> - * rule findSeating() { - * Context context; - * int seatingId, seatingPid; - * String seatingRightGuestName, leftGuestName; - * Sex rightGuestSex; - * Hobby rightGuestHobby; - * Count count; - * - * when { - * context : Context( state == Context.ASSIGN_SEATS ) - * Seating( seatingId:id, seatingPid:pid, pathDone == true - * seatingRightSeat:rightSeat seatingRightGuestName:rightGuestName ) - * Guest( name == seatingRightGuestName, rightGuestSex:sex, rightGuestHobby:hobby ) - * Guest( leftGuestName:name , sex != rightGuestSex, hobby == rightGuestHobby ) - * - * count : Count() - * - * not ( Path( id == seatingId, guestName == leftGuestName) ) - * not ( Chosen( id == seatingId, guestName == leftGuestName, hobby == rightGuestHobby) ) - * } then { - * int newSeat = rightSeat + 1; - * drools.assert( new Seating( coung.getValue(), rightSeat, rightSeatName, leftGuestName, newSeat, countValue, id, false ); - * drools.assert( new Path( countValue, leftGuestName, newSeat ); - * drools.assert( new Chosen( id, leftGuestName, rightGuestHobby ) ); - * - * System.out.println( &quot;seat &quot; + rightSeat + &quot; &quot; + rightSeatName + &quot; &quot; + leftGuestName ); - * - * count.setCount( countValue + 1 ); - * context.setPath( Context.MAKE_PATH ); - * } - * } + * rule findSeating() { + * Context context; + * int seatingId, seatingPid; + * String seatingRightGuestName, leftGuestName; + * Sex rightGuestSex; + * Hobby rightGuestHobby; + * Count count; + * + * when { + * context : Context( state == Context.ASSIGN_SEATS ) + * Seating( seatingId:id, seatingPid:pid, pathDone == true + * seatingRightSeat:rightSeat seatingRightGuestName:rightGuestName ) + * Guest( name == seatingRightGuestName, rightGuestSex:sex, rightGuestHobby:hobby ) + * Guest( leftGuestName:name , sex != rightGuestSex, hobby == rightGuestHobby ) + * + * count : Count() + * + * not ( Path( id == seatingId, guestName == leftGuestName) ) + * not ( Chosen( id == seatingId, guestName == leftGuestName, hobby == rightGuestHobby) ) + * } then { + * int newSeat = rightSeat + 1; + * drools.assert( new Seating( coung.getValue(), rightSeat, rightSeatName, leftGuestName, newSeat, countValue, id, false ); + * drools.assert( new Path( countValue, leftGuestName, newSeat ); + * drools.assert( new Chosen( id, leftGuestName, rightGuestHobby ) ); + * + * System.out.println( &quot;seat &quot; + rightSeat + &quot; &quot; + rightSeatName + &quot; &quot; + leftGuestName ); + * + * count.setCount( countValue + 1 ); + * context.setPath( Context.MAKE_PATH ); + * } + * } * </pre> * * @return @@ -447,7 +461,7 @@ public void invoke(Activation activation) throws ConsequenceException { * @throws InvalidRuleException */ private Rule getFindSeating() throws IntrospectionException, - InvalidRuleException { + InvalidRuleException { final Rule rule = new Rule( "findSeating" ); // --------------- @@ -468,7 +482,7 @@ private Rule getFindSeating() throws IntrospectionException, // ------------------------------- // Seating( seatingId:id, seatingPid:pid, pathDone == true - // seatingRightSeat:rightSeat seatingRightGuestName:rightGuestName ) + // seatingRightSeat:rightSeat seatingRightGuestName:rightGuestName ) // ------------------------------- Column seatingColumn = new Column( 1, seatingType ); @@ -497,7 +511,8 @@ private Rule getFindSeating() throws IntrospectionException, final Declaration seatingRightGuestNameDeclaration = rule.getDeclaration( "seatingRightGuestName" ); final Declaration seatingRightSeatDeclaration = rule.getDeclaration( "seatingRightSeat" ); // -------------- - // Guest( name == seatingRightGuestName, rightGuestSex:sex, rightGuestHobby:hobby ) + // Guest( name == seatingRightGuestName, rightGuestSex:sex, + // rightGuestHobby:hobby ) // --------------- Column rightGuestColumn = new Column( 2, guestType ); @@ -521,7 +536,8 @@ private Rule getFindSeating() throws IntrospectionException, final Declaration rightGuestHobbyDeclaration = rule.getDeclaration( "rightGuestHobby" ); // ---------------- - // Guest( leftGuestName:name , sex != rightGuestSex, hobby == rightGuestHobby ) + // Guest( leftGuestName:name , sex != rightGuestSex, hobby == + // rightGuestHobby ) // ---------------- Column leftGuestColumn = new Column( 3, guestType ); @@ -556,7 +572,7 @@ private Rule getFindSeating() throws IntrospectionException, // -------------- // not ( Path( id == seatingId, guestName == leftGuestName) ) // -------------- - Column notPathColumn = new Column( 3, + Column notPathColumn = new Column( 5, pathType ); notPathColumn.addConstraint( getBoundVariableConstraint( notPathColumn, @@ -572,9 +588,10 @@ private Rule getFindSeating() throws IntrospectionException, notPath.addChild( notPathColumn ); rule.addPattern( notPath ); // ------------ - // not ( Chosen( id == seatingId, guestName == leftGuestName, hobby == rightGuestHobby ) ) + // not ( Chosen( id == seatingId, guestName == leftGuestName, hobby == + // rightGuestHobby ) ) // ------------ - Column notChosenColumn = new Column( 5, + Column notChosenColumn = new Column( 6, chosenType ); notChosenColumn.addConstraint( getBoundVariableConstraint( notChosenColumn, @@ -631,18 +648,22 @@ public void invoke(Activation activation) throws ConsequenceException { seatId, false, seatingRightSeat, - leftGuestName, + rightGuestName , seatingRightSeat + 1, - rightGuestName ); + leftGuestName ); drools.assertObject( seating ); - drools.assertObject( new Path( count.getValue(), - seatingRightSeat + 1, - leftGuestName ) ); + Path path = new Path( count.getValue(), + seatingRightSeat + 1, + leftGuestName ); + + drools.assertObject( path ); + + Chosen chosen = new Chosen( seatId, + leftGuestName, + rightGuestHobby ); - drools.assertObject( new Chosen( seatId, - leftGuestName, - rightGuestHobby ) ); + drools.assertObject( chosen ); count.setValue( count.getValue() + 1 ); drools.modifyObject( tuple.getFactHandleForDeclaration( countDeclaration ), @@ -652,9 +673,10 @@ public void invoke(Activation activation) throws ConsequenceException { drools.modifyObject( tuple.getFactHandleForDeclaration( contextDeclaration ), context ); - System.out.println( "assign seating : " + seating ); - - } catch ( Exception e ) { + System.out.println( "find seating : " + seating + " : " + path + " : " + chosen ); + + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -668,25 +690,18 @@ public void invoke(Activation activation) throws ConsequenceException { /** * - * rule pathDone() { - * Context context; - * Seating seating; - * when { - * context : Context( state == Context.MAKE_PATH ) - * seating : Seating( pathDone == false ) - * } then { - * seating.setPathDone( true ); - * context.setName( Context.CHECK_DONE ); - * } - * } - * + * rule pathDone() { Context context; Seating seating; when { context : + * Context( state == Context.MAKE_PATH ) seating : Seating( pathDone == + * false ) } then { seating.setPathDone( true ); context.setName( + * Context.CHECK_DONE ); } } + * * * @return * @throws IntrospectionException * @throws InvalidRuleException */ private Rule getPathDone() throws IntrospectionException, - InvalidRuleException { + InvalidRuleException { final Rule rule = new Rule( "pathDone" ); // ----------- @@ -721,8 +736,8 @@ private Rule getPathDone() throws IntrospectionException, final Declaration seatingDeclaration = rule.getDeclaration( "seating" ); // ------------ - // context.setName( Context.CHECK_DONE ); - // seating.setPathDone( true ); + // context.setName( Context.CHECK_DONE ); + // seating.setPathDone( true ); // ------------ Consequence consequence = new Consequence() { @@ -735,16 +750,17 @@ public void invoke(Activation activation) throws ConsequenceException { Context context = (Context) tuple.get( contextDeclaration ); Seating seating = (Seating) tuple.get( seatingDeclaration ); - + seating.setPathDone( true ); drools.modifyObject( tuple.getFactHandleForDeclaration( seatingDeclaration ), - seating ); - + seating ); + context.setState( Context.CHECK_DONE ); drools.modifyObject( tuple.getFactHandleForDeclaration( contextDeclaration ), - context ); - System.out.println("path done" + seating); - } catch ( Exception e ) { + context ); + System.out.println( "path done" + seating ); + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -758,25 +774,18 @@ public void invoke(Activation activation) throws ConsequenceException { /** * - * rule areWeDone() { - * Context context; - * LastSeat lastSear; - * when { - * context : Context( state == Context.CHECK_DONE ) - * LastSeat( lastSeat: seat ) - * Seating( rightSeat == lastSeat ) - * } then { - * context.setState( Context.PRINT_RESULTS ); - * } - * } - * + * rule areWeDone() { Context context; LastSeat lastSear; when { context : + * Context( state == Context.CHECK_DONE ) LastSeat( lastSeat: seat ) + * Seating( rightSeat == lastSeat ) } then { context.setState( + * Context.PRINT_RESULTS ); } } + * * * @return * @throws IntrospectionException * @throws InvalidRuleException */ private Rule getAreWeDone() throws IntrospectionException, - InvalidRuleException { + InvalidRuleException { final Rule rule = new Rule( "areWeDone" ); // ----------- @@ -797,30 +806,30 @@ private Rule getAreWeDone() throws IntrospectionException, // LastSeat( lastSeat: seat ) // --------------- Column lastSeatColumn = new Column( 1, - lastSeatType, - null ); + lastSeatType, + null ); lastSeatColumn.addConstraint( getFieldBinding( lastSeatColumn, - "seat", - "lastSeat" ) ); + "seat", + "lastSeat" ) ); rule.addPattern( lastSeatColumn ); final Declaration lastSeatDeclaration = rule.getDeclaration( "lastSeat" ); // ------------- - // Seating( rightSeat == lastSeat ) + // Seating( rightSeat == lastSeat ) // ------------- Column seatingColumn = new Column( 2, seatingType, null ); - + seatingColumn.addConstraint( getBoundVariableConstraint( seatingColumn, "rightSeat", lastSeatDeclaration, - integerEqualEvaluator ) ); - + integerEqualEvaluator ) ); + rule.addPattern( seatingColumn ); - + // ------------ - // context.setName( Context.PRINT_RESULTS ); + // context.setName( Context.PRINT_RESULTS ); // ------------ Consequence consequence = new Consequence() { @@ -833,12 +842,13 @@ public void invoke(Activation activation) throws ConsequenceException { Context context = (Context) tuple.get( contextDeclaration ); context.setState( Context.PRINT_RESULTS ); - + drools.modifyObject( tuple.getFactHandleForDeclaration( contextDeclaration ), - context ); - + context ); + System.out.println( "are we done yet" ); - } catch ( Exception e ) { + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -848,25 +858,19 @@ public void invoke(Activation activation) throws ConsequenceException { rule.setConsequence( consequence ); return rule; - } - + } + /** * - * rule continue() { - * Context context; - * when { - * context : Context( state == Context.CHECK_DONE ) - * } then { - * context.setState( Context.ASSIGN_SEATS ); - * } - * } + * rule continue() { Context context; when { context : Context( state == + * Context.CHECK_DONE ) } then { context.setState( Context.ASSIGN_SEATS ); } } * * @return * @throws IntrospectionException * @throws InvalidRuleException */ private Rule getContinueProcessing() throws IntrospectionException, - InvalidRuleException { + InvalidRuleException { final Rule rule = new Rule( "continueProcessng" ); // ----------- @@ -883,9 +887,9 @@ private Rule getContinueProcessing() throws IntrospectionException, rule.addPattern( contextColumn ); final Declaration contextDeclaration = rule.getDeclaration( "context" ); - + // ------------ - // context.setName( Context.ASSIGN_SEATS ); + // context.setName( Context.ASSIGN_SEATS ); // ------------ Consequence consequence = new Consequence() { @@ -898,12 +902,13 @@ public void invoke(Activation activation) throws ConsequenceException { Context context = (Context) tuple.get( contextDeclaration ); context.setState( Context.ASSIGN_SEATS ); - + drools.modifyObject( tuple.getFactHandleForDeclaration( contextDeclaration ), - context ); - - System.out.println("continue processing"); - } catch ( Exception e ) { + context ); + + System.out.println( "continue processing" ); + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -913,26 +918,21 @@ public void invoke(Activation activation) throws ConsequenceException { rule.setConsequence( consequence ); return rule; - } + } /** * - * rule all_done() { - * Context context; - * when { - * context : Context( state == Context.PRINT_RESULTS ) - * } then { - * - * } - * } - * + * rule all_done() { Context context; when { context : Context( state == + * Context.PRINT_RESULTS ) } then { + * } } + * * * @return * @throws IntrospectionException * @throws InvalidRuleException */ private Rule getAllDone() throws IntrospectionException, - InvalidRuleException { + InvalidRuleException { final Rule rule = new Rule( "alldone" ); // ----------- @@ -948,7 +948,7 @@ private Rule getAllDone() throws IntrospectionException, rule.addPattern( contextColumn ); final Declaration contextDeclaration = rule.getDeclaration( "context" ); - + // ------------ // // ------------ @@ -956,8 +956,9 @@ private Rule getAllDone() throws IntrospectionException, public void invoke(Activation activation) throws ConsequenceException { try { - - } catch ( Exception e ) { + System.out.println( "all done" ); + } + catch ( Exception e ) { throw new ConsequenceException( e ); } } @@ -967,77 +968,66 @@ public void invoke(Activation activation) throws ConsequenceException { rule.setConsequence( consequence ); return rule; - } + } /** * Convert the facts from the <code>InputStream</code> to a list of * objects. */ - private List getInputObjects(InputStream inputStream) throws IOException - { - List list = new ArrayList( ); + private List getInputObjects(InputStream inputStream) throws IOException { + List list = new ArrayList(); BufferedReader br = new BufferedReader( new InputStreamReader( inputStream ) ); String line; - while ( (line = br.readLine( )) != null ) - { - if ( line.trim( ).length( ) == 0 || line.trim( ).startsWith( ";" ) ) - { + while ( (line = br.readLine()) != null ) { + if ( line.trim().length() == 0 || line.trim().startsWith( ";" ) ) { continue; } StringTokenizer st = new StringTokenizer( line, "() " ); - String type = st.nextToken( ); + String type = st.nextToken(); - if ( "guest".equals( type ) ) - { - if ( !"name".equals( st.nextToken( ) ) ) - { + if ( "guest".equals( type ) ) { + if ( !"name".equals( st.nextToken() ) ) { throw new IOException( "expected 'name' in: " + line ); } - String name = st.nextToken( ); - if ( !"sex".equals( st.nextToken( ) ) ) - { + String name = st.nextToken(); + if ( !"sex".equals( st.nextToken() ) ) { throw new IOException( "expected 'sex' in: " + line ); } - String sex = st.nextToken( ); - if ( !"hobby".equals( st.nextToken( ) ) ) - { + String sex = st.nextToken(); + if ( !"hobby".equals( st.nextToken() ) ) { throw new IOException( "expected 'hobby' in: " + line ); } - String hobby = st.nextToken( ); + String hobby = st.nextToken(); Guest guest = new Guest( name, - Sex.resolve(sex), - Hobby.resolve(hobby)); + Sex.resolve( sex ), + Hobby.resolve( hobby ) ); - list.add( guest ); + list.add( guest ); } - if ( "last_seat".equals( type ) ) - { - if ( !"seat".equals( st.nextToken( ) ) ) - { + if ( "last_seat".equals( type ) ) { + if ( !"seat".equals( st.nextToken() ) ) { throw new IOException( "expected 'seat' in: " + line ); } - list.add( new LastSeat( new Integer( st.nextToken( ) ).intValue( ) ) ); + list.add( new LastSeat( new Integer( st.nextToken() ).intValue() ) ); } - if ( "context".equals( type ) ) - { - if ( !"state".equals( st.nextToken( ) ) ) - { + if ( "context".equals( type ) ) { + if ( !"state".equals( st.nextToken() ) ) { throw new IOException( "expected 'state' in: " + line ); } - list.add( new Context( st.nextToken( ) ) ); + list.add( new Context( st.nextToken() ) ); } } - inputStream.close( ); + inputStream.close(); return list; - } - + } + private InputStream generateData() { final String LINE_SEPARATOR = System.getProperty( "line.separator" );
1ec0103ac9439f67c4a9dcf9886ea0adf9cfa020
restlet-framework-java
- Fixed filling state bug in Buffer class -- Removed received inbound message from messages queue when fully received -- Connection closing seems to work again - CouchDBUpload test working again--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/connector/HttpClientInboundWay.java b/modules/org.restlet/src/org/restlet/engine/connector/HttpClientInboundWay.java index 21907de577..8c6594124d 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/HttpClientInboundWay.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/HttpClientInboundWay.java @@ -114,6 +114,15 @@ public void onError(Status status) { super.onError(status); } + @Override + public void onCompleted(boolean endDetected) { + if (getMessage() != null) { + getMessages().remove(getMessage()); + } + + super.onCompleted(endDetected); + } + @Override public void updateState() { if (getIoState() == IoState.IDLE) { diff --git a/modules/org.restlet/src/org/restlet/engine/connector/InboundWay.java b/modules/org.restlet/src/org/restlet/engine/connector/InboundWay.java index 0756edfdde..86a7b6de49 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/InboundWay.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/InboundWay.java @@ -322,7 +322,7 @@ public int processIoBuffer() throws IOException { } else { result = super.processIoBuffer(); } - + return result; } diff --git a/modules/org.restlet/src/org/restlet/engine/connector/Way.java b/modules/org.restlet/src/org/restlet/engine/connector/Way.java index 56fcc37c68..3655721368 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/Way.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/Way.java @@ -376,8 +376,10 @@ public void onSelected() { setIoState(IoState.CANCELLED); } - getLogger().log(Level.FINE, - "Way selected. Processing IO for : " + this); + if (getLogger().isLoggable(Level.FINER)) { + getLogger().log(Level.FINER, + "Way selected. Processing IO for : " + this); + } // IO processing int drained = processIoBuffer(); diff --git a/modules/org.restlet/src/org/restlet/engine/io/Buffer.java b/modules/org.restlet/src/org/restlet/engine/io/Buffer.java index 764b529c55..89a6b14e4a 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/Buffer.java +++ b/modules/org.restlet/src/org/restlet/engine/io/Buffer.java @@ -464,6 +464,7 @@ public int process(BufferProcessor processor, Object... args) int filled = 0; boolean lastDrainFailed = false; boolean lastFillFailed = false; + boolean fillEnded = false; while (tryAgain && processor.canLoop()) { if (isDraining()) { @@ -484,18 +485,15 @@ public int process(BufferProcessor processor, Object... args) Context.getCurrentLogger().finer( drained + " bytes drained from buffer"); } - } else if (drained == -1) { - if (result == 0) { - result = -1; + } else { + if (!lastFillFailed && couldFill()) { + // We may still be able to fill + beforeFill(); + } else { + tryAgain = false; } - tryAgain = false; - } else if (!lastFillFailed && couldFill()) { - // We may still be able to fill lastDrainFailed = true; - beforeFill(); - } else { - tryAgain = false; } } else if (isFilling()) { filled = 0; @@ -515,18 +513,16 @@ public int process(BufferProcessor processor, Object... args) Context.getCurrentLogger().finer( filled + " bytes filled into buffer"); } - } else if (filled == -1) { - if (result == 0) { - result = -1; + } else { + if (!lastDrainFailed && couldDrain()) { + // We may still be able to drain + beforeDrain(); + } else { + tryAgain = false; } - tryAgain = false; - } else if (!lastDrainFailed && couldDrain()) { - // We may still be able to drain + fillEnded = (filled == -1); lastFillFailed = true; - beforeDrain(); - } else { - tryAgain = false; } } else { // Can't drain nor fill @@ -534,7 +530,7 @@ public int process(BufferProcessor processor, Object... args) } } - if ((result == 0) && !processor.couldFill()) { + if ((result == 0) && (!processor.couldFill() || fillEnded)) { // Nothing was drained and no hope to fill again result = -1; } diff --git a/modules/org.restlet/src/org/restlet/engine/io/ReadableChunkedChannel.java b/modules/org.restlet/src/org/restlet/engine/io/ReadableChunkedChannel.java index ed78d94097..966c87a757 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/ReadableChunkedChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/ReadableChunkedChannel.java @@ -264,8 +264,8 @@ public int read(ByteBuffer dst) throws IOException { } if ((result == -1) - && (getWrappedChannel() instanceof ReadableBufferedChannel)) { - ((ReadableBufferedChannel) getWrappedChannel()).onCompleted(false); + && (getWrappedChannel() instanceof CompletionListener)) { + ((CompletionListener) getWrappedChannel()).onCompleted(false); } return result; diff --git a/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java b/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java index 7441a25fe3..01070568fb 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/ReadableSizedChannel.java @@ -100,8 +100,8 @@ public int read(ByteBuffer dst) throws IOException { } if ((result == -1) - && (getWrappedChannel() instanceof ReadableBufferedChannel)) { - ((ReadableBufferedChannel) getWrappedChannel()) + && (getWrappedChannel() instanceof CompletionListener)) { + ((CompletionListener) getWrappedChannel()) .onCompleted((wrappedRead == -1)); }
7f0c301cb35e90c12b102e765c9d45f28089e333
aeshell$aesh
added mask functionality
p
https://github.com/aeshell/aesh
diff --git a/src/main/java/Example.java b/src/main/java/Example.java index 34027ffd5..af550d303 100644 --- a/src/main/java/Example.java +++ b/src/main/java/Example.java @@ -55,9 +55,28 @@ else if(line.equals("foobar")) { while ((line = console.read("> ")) != null) { console.pushToConsole("======>\"" + line+"\"\n"); - if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) { + if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit") || + line.equalsIgnoreCase("reset")) { break; } + if(line.equalsIgnoreCase("password")) { + line = console.read("password: ", Character.valueOf((char) 0)); + console.pushToConsole("password typed:"+line+"\n"); + + } + } + if(line.equals("reset")) { + console.stop(); + console = new Console(); + + while ((line = console.read("> ")) != null) { + console.pushToConsole("======>\"" + line+"\"\n"); + if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit") || + line.equalsIgnoreCase("reset")) { + break; + } + + } } try { diff --git a/src/main/java/org/jboss/jreadline/console/Buffer.java b/src/main/java/org/jboss/jreadline/console/Buffer.java index 05c62dced..c6ebe2162 100644 --- a/src/main/java/org/jboss/jreadline/console/Buffer.java +++ b/src/main/java/org/jboss/jreadline/console/Buffer.java @@ -33,11 +33,12 @@ public class Buffer { private StringBuilder line; private String prompt; private int delta; //need to keep track of a delta for ansi terminal + private Character mask; private final static int TAB = 4; protected Buffer() { - this(null); + this(null, null); } /** @@ -46,6 +47,10 @@ protected Buffer() { * @param promptText set prompt */ protected Buffer(String promptText) { + this(promptText, null); + } + + protected Buffer(String promptText, Character mask) { if(promptText != null) prompt = promptText; else @@ -53,6 +58,7 @@ protected Buffer(String promptText) { line = new StringBuilder(); delta = 0; + this.mask = mask; } /** @@ -61,6 +67,10 @@ protected Buffer(String promptText) { * @param promptText set prompt */ protected void reset(String promptText) { + reset(promptText, null); + } + + protected void reset(String promptText, Character mask) { if(promptText != null) prompt = promptText; else @@ -68,6 +78,7 @@ protected void reset(String promptText) { cursor = 0; line = new StringBuilder(); delta = 0; + this.mask = mask; } /** @@ -86,7 +97,7 @@ protected int getCursor() { } protected int getCursorWithPrompt() { - return cursor + prompt.length()+1; + return getCursor() + prompt.length()+1; } protected String getPrompt() { @@ -248,6 +259,17 @@ protected char[] getLineFrom(int position) { } public String getLine() { + if(mask == null) + return line.toString(); + else { + if(line.length() > 0) + return String.format("%"+line.length()+"s", "").replace(' ', mask); + else + return ""; + } + } + + public String getLineNoMask() { return line.toString(); } @@ -296,7 +318,7 @@ public void write(final String str) { line.append(str); } else { - line.insert(cursor, str); + line.insert(getCursor(), str); } cursor += str.length(); diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java index 4be746f06..40b580849 100644 --- a/src/main/java/org/jboss/jreadline/console/Console.java +++ b/src/main/java/org/jboss/jreadline/console/Console.java @@ -134,9 +134,13 @@ public void stop() throws IOException { terminal.reset(); terminal = null; } - + public String read(String prompt) throws IOException { - buffer.reset(prompt); + return read(prompt, null); + } + + public String read(String prompt, Character mask) throws IOException { + buffer.reset(prompt, mask); terminal.write(buffer.getPrompt()); StringBuilder searchTerm = new StringBuilder(); String result = null; @@ -168,7 +172,7 @@ public String read(String prompt) throws IOException { } } else if (action == Action.EDIT) { - writeChar(in[0]); + writeChar(in[0], mask); } // For search movement is used a bit differently. // It only triggers what kind of search action thats performed @@ -226,17 +230,17 @@ else if(action == Action.SEARCH && !settings.isHistoryDisabled()) { case END: // Set buffer to the found string. if (result != null) { - buffer.setLine(result); + setBufferLine(result); redrawLine(); printNewline(); - return buffer.getLine(); + return buffer.getLineNoMask(); } redrawLine(); break; case NEXT_BIG_WORD: if(result != null) { - buffer.setLine(result); + setBufferLine(result); result = null; } //redrawLine(); @@ -294,11 +298,12 @@ else if(operation.getMovement() == Movement.PREV) else if(action == Action.NEWLINE) { // clear the undo stack for each new line clearUndoStack(); - addToHistory(buffer.getLine()); + if(mask == null) // dont push to history if masking + addToHistory(buffer.getLine()); prevAction = Action.NEWLINE; //moveToEnd(); printNewline(); // output newline - return buffer.getLine(); + return buffer.getLineNoMask(); } else if(action == Action.UNDO) { undo(); @@ -384,6 +389,8 @@ private void setBufferLine(String newLine) throws IOException { numNewRows++; if(numNewRows > 0) { int totalRows = newLine.length() / getTerminalWidth() +1; + //logger.info("ADDING "+numNewRows+", totalRows:"+totalRows+ + // ", currentRow:"+currentRow+", cursorRow:"+cursorRow); terminal.write(Buffer.printAnsi(numNewRows+"S")); } } @@ -418,9 +425,18 @@ private void addToHistory(String line) { history.push(line); } - private void writeChar(int c) throws IOException { + private void writeChar(int c, Character mask) throws IOException { + buffer.write((char) c); - terminal.write((char) c); + if(mask != null) { + if(mask == 0) + terminal.write(' '); //TODO: fix this hack + else + terminal.write(mask); + } + else { + terminal.write((char) c); + } // add a 'fake' new line when inserting at the edge of terminal if(buffer.getCursorWithPrompt() > getTerminalWidth() && @@ -571,8 +587,8 @@ private void redrawLine() throws IOException { private void drawLine(String line) throws IOException { //need to clear more than one line - if((line.length()+buffer.getPrompt().length()) > getTerminalWidth() || - (line.length()+buffer.getPrompt().length() + Math.abs(buffer.getDelta()) > getTerminalWidth())) { + if(line.length() > getTerminalWidth() || + (line.length()+ Math.abs(buffer.getDelta()) > getTerminalWidth())) { int currentRow = 0; if(buffer.getCursorWithPrompt() > 0) @@ -628,8 +644,9 @@ private void printSearch(String searchTerm, String result) throws IOException { out.append(searchTerm).append("': "); cursor += out.length(); out.append(result); //.append("\u001b[K"); - drawLine(out.toString()); - terminal.write(Buffer.printAnsi((cursor+1) + "G")); + setBufferLine(out.toString()); + redrawLine(); + //moveCursor(cursor+1); } /**
036ab9cecae204dcdc7e18fc7c36d3687b5f8e8d
tapiji
Add rbmanager.ui to tools team project set
a
https://github.com/tapiji/tapiji
diff --git a/team_project_set_tools.psf b/team_project_set_tools.psf index d45940b7..8158b47a 100644 --- a/team_project_set_tools.psf +++ b/team_project_set_tools.psf @@ -13,7 +13,7 @@ <project reference="1.0,http://git.eclipse.org/gitroot/babel/plugins.git,master,org.eclipse.babel.tapiji.tools.java"/> <project reference="1.0,http://git.eclipse.org/gitroot/babel/plugins.git,master,org.eclipse.babel.tapiji.tools.java.feature"/> <project reference="1.0,http://git.eclipse.org/gitroot/babel/plugins.git,master,org.eclipse.babel.tapiji.tools.java.ui"/> -<project reference="1.0,http://git.eclipse.org/gitroot/babel/plugins.git,master,org.eclipse.babel.tapiji.tools.rbmanager"/> +<project reference="1.0,http://git.eclipse.org/gitroot/babel/plugins.git,master,org.eclipse.babel.tapiji.tools.rbmanager.ui"/> <project reference="1.0,http://git.eclipse.org/gitroot/babel/plugins.git,master,org.eclipse.babel.tapiji.tools.target"/> </provider> @@ -29,7 +29,7 @@ <item factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/org.eclipse.babel.tapiji.tools.java.feature" type="4"/> <item factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/org.eclipse.babel.tapiji.tools.target" type="4"/> <item elementID="=org.eclipse.babel.tapiji.tools.core" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/> -<item elementID="=org.eclipse.babel.tapiji.tools.rbmanager" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/> +<item elementID="=org.eclipse.babel.tapiji.tools.rbmanager.ui" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/> <item elementID="=org.eclipse.babel.tapiji.tools.jsf" factoryID="org.eclipse.jdt.ui.PersistableJavaElementFactory"/> </workingSets>
b2cc0ae3027251df10d4306358cb53fe314ea852
belaban$jgroups
- Replace Math.random() with ThreadLocalRandom.current().nextLong() [https://issues.jboss.org/browse/JGRP-2096] - Removed STABLE.stability_delay from the configs - If coord is the only member sending STABILITY messages, then we'll not use a saparate task
p
https://github.com/belaban/jgroups
diff --git a/conf/fast.xml b/conf/fast.xml index 0240ed3b3e9..7c252235c60 100644 --- a/conf/fast.xml +++ b/conf/fast.xml @@ -61,7 +61,7 @@ xmit_table_msgs_per_row="1000" xmit_table_max_compaction_time="30000" max_msg_batch_size="500"/> - <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" + <pbcast.STABLE desired_avg_gossip="50000" max_bytes="8m"/> <pbcast.GMS print_local_addr="true" join_timeout="3000" view_bundling="true"/> diff --git a/conf/tcp-nio.xml b/conf/tcp-nio.xml index 56d34fda965..46e83e1edc9 100644 --- a/conf/tcp-nio.xml +++ b/conf/tcp-nio.xml @@ -46,7 +46,7 @@ <pbcast.NAKACK2 use_mcast_xmit="false" discard_delivered_msgs="true"/> <UNICAST3 /> - <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" + <pbcast.STABLE desired_avg_gossip="50000" max_bytes="4M"/> <pbcast.GMS print_local_addr="true" join_timeout="2000" view_bundling="true"/> diff --git a/conf/tcp.xml b/conf/tcp.xml index 9041c00959d..c51fb62497f 100644 --- a/conf/tcp.xml +++ b/conf/tcp.xml @@ -46,7 +46,7 @@ <pbcast.NAKACK2 use_mcast_xmit="false" discard_delivered_msgs="true"/> <UNICAST3 /> - <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" + <pbcast.STABLE desired_avg_gossip="50000" max_bytes="4M"/> <pbcast.GMS print_local_addr="true" join_timeout="2000" view_bundling="true"/> diff --git a/conf/toa.xml b/conf/toa.xml index 3a59cdae00e..0232c3f10f8 100644 --- a/conf/toa.xml +++ b/conf/toa.xml @@ -55,7 +55,7 @@ xmit_table_max_compaction_time="60000" conn_expiry_timeout="0" max_msg_batch_size="500"/> - <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" + <pbcast.STABLE desired_avg_gossip="50000" max_bytes="4M"/> <pbcast.GMS print_local_addr="true" join_timeout="3000" view_bundling="true"/> diff --git a/conf/udp-largecluster.xml b/conf/udp-largecluster.xml index 84022eba217..85d09c2b331 100644 --- a/conf/udp-largecluster.xml +++ b/conf/udp-largecluster.xml @@ -59,7 +59,7 @@ xmit_table_msgs_per_row="1000" xmit_table_max_compaction_time="30000" max_msg_batch_size="500"/> - <pbcast.STABLE stability_delay="2000" desired_avg_gossip="60000" + <pbcast.STABLE desired_avg_gossip="60000" max_bytes="4M"/> <pbcast.GMS print_local_addr="true" join_timeout="10000" diff --git a/conf/udp.xml b/conf/udp.xml index 5ed0aba4907..601ed9b81ec 100644 --- a/conf/udp.xml +++ b/conf/udp.xml @@ -60,7 +60,7 @@ xmit_table_max_compaction_time="60000" conn_expiry_timeout="0" max_msg_batch_size="500"/> - <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" + <pbcast.STABLE desired_avg_gossip="50000" max_bytes="4M"/> <pbcast.GMS print_local_addr="true" join_timeout="2000" view_bundling="true"/> diff --git a/src/org/jgroups/protocols/pbcast/STABLE.java b/src/org/jgroups/protocols/pbcast/STABLE.java index c9ee673f354..bb3f2cda832 100644 --- a/src/org/jgroups/protocols/pbcast/STABLE.java +++ b/src/org/jgroups/protocols/pbcast/STABLE.java @@ -408,7 +408,6 @@ protected void resetDigest() { if(view == null) return; digest=new MutableDigest(view.getMembersRaw()); // .set(getDigest()); - log.trace("%s: reset digest to %s", local_addr, printDigest(digest)); votes=new FixedSizeBitSet(view.size()); // all 0's initially } @@ -698,21 +697,44 @@ protected Digest readDigest(byte[] buffer, int offset, int length) { /** - Schedules a stability message to be mcast after a random number of milliseconds (range 1-5 secs). + Schedules a stability message to be mcast after a random number of milliseconds (range [1-stability_delay] secs). The reason for waiting a random amount of time is that, in the worst case, all members receive a STABLE_GOSSIP message from the last outstanding member at the same time and would therefore mcast the STABILITY message at the same time too. To avoid this, each member waits random N msecs. If, before N elapses, some other member sent the STABILITY message, we just cancel our own message. If, during - waiting for N msecs to send STABILITY message S1, another STABILITY message S2 is to be sent, we just - discard S2. - @param tmp A copy of te stability digest, so we don't need to copy it again + waiting for N msecs to send STABILITY message S1, another STABILITY message S2 is to be sent, we just discard S2. + @param tmp A copy of the stability digest, so we don't need to copy it again */ protected void sendStabilityMessage(Digest tmp, final ViewId view_id) { - // give other members a chance to mcast STABILITY message. if we receive STABILITY by the end of our random - // sleep, we will not send the STABILITY msg. this prevents that all mbrs mcast a STABILITY msg at the same time - startStabilityTask(tmp, view_id, Util.random(stability_delay)); + if(send_stable_msgs_to_coord_only || stability_delay <= 1) + _sendStabilityMessage(tmp, view_id); + else { + // give other members a chance to mcast STABILITY message. if we receive STABILITY by the end of our random + // sleep, we will not send the STABILITY msg. this prevents that all mbrs mcast a STABILITY msg at the same time + startStabilityTask(tmp, view_id, Util.random(stability_delay)); + } } + protected void _sendStabilityMessage(Digest stability_digest, final ViewId view_id) { + if(suspended) { + log.debug("STABILITY message will not be sent as suspended=%b", suspended); + return; + } + + // https://issues.jboss.org/browse/JGRP-1638: we reverted to sending the STABILITY message *unreliably*, + // but clear votes *before* sending it + try { + Message msg=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.NO_RELIABILITY) + .putHeader(id, new StableHeader(StableHeader.STABILITY, view_id)) + .setBuffer(marshal(stability_digest)); + log.trace("%s: sending stability msg %s", local_addr, printDigest(stability_digest)); + num_stability_msgs_sent++; + down_prot.down(msg); + } + catch(Exception e) { + log.warn("failed sending STABILITY message", e); + } + } protected Digest getDigest() { return (Digest)down_prot.down(Event.GET_DIGEST_EVT); @@ -803,11 +825,7 @@ public void run() { public String toString() {return STABLE.class.getSimpleName() + ": StableTask";} long computeSleepTime() { - return getRandom((desired_avg_gossip * 2)); - } - - long getRandom(long range) { - return (long)((Math.random() * range) % range); + return Util.random((desired_avg_gossip * 2)); } } @@ -827,24 +845,7 @@ protected StabilitySendTask(Digest d, ViewId view_id) { } public void run() { - if(suspended) { - log.debug("STABILITY message will not be sent as suspended=%s", suspended); - return; - } - - // https://issues.jboss.org/browse/JGRP-1638: we reverted to sending the STABILITY message *unreliably*, - // but clear votes *before* sending it - try { - Message msg=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.NO_RELIABILITY) - .putHeader(id, new StableHeader(StableHeader.STABILITY, view_id)) - .setBuffer(marshal(stability_digest)); - log.trace("%s: sending stability msg %s", local_addr, printDigest(stability_digest)); - num_stability_msgs_sent++; - down_prot.down(msg); - } - catch(Exception e) { - log.warn("failed sending STABILITY message", e); - } + _sendStabilityMessage(stability_digest, view_id); } public String toString() {return STABLE.class.getSimpleName() + ": StabilityTask";} diff --git a/src/org/jgroups/protocols/relay/RELAY2.java b/src/org/jgroups/protocols/relay/RELAY2.java index d0bb56a7cd6..3cecb883950 100644 --- a/src/org/jgroups/protocols/relay/RELAY2.java +++ b/src/org/jgroups/protocols/relay/RELAY2.java @@ -456,8 +456,7 @@ protected void handleRelayMessage(Relay2Header hdr, Message msg) { SiteUUID site_uuid=(SiteUUID)hdr.final_dest; // If configured to do so, we want to load-balance these messages, - int index=(int)Util.random( members.size()) -1; - UUID tmp=(UUID)members.get(index); + UUID tmp=(UUID)Util.pickRandomElement(members); SiteAddress final_dest=new SiteUUID(tmp, site_uuid.getName(), site_uuid.getSite()); // If we select a different address to handle this message, we handle it here. diff --git a/src/org/jgroups/util/Util.java b/src/org/jgroups/util/Util.java index 1f101925dd0..ad6ccd1b025 100644 --- a/src/org/jgroups/util/Util.java +++ b/src/org/jgroups/util/Util.java @@ -1768,9 +1768,10 @@ public static long micros() { } - /** Returns a random value in the range [1 - range] */ + /** Returns a random value in the range [1 - range]. If range is 0, 1 will be returned. If range is negative, an + * exception will be thrown */ public static long random(long range) { - return (long)((Math.random() * range) % range) + 1; + return range == 0? 1 : ThreadLocalRandom.current().nextLong(range) + 1; } @@ -2198,29 +2199,6 @@ public static <T> List<T> newElements(List<T> old_list,List<T> new_list) { } - /** - * Selects a random subset of members according to subset_percentage and returns them. - * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. - */ - public static List<Address> pickSubset(List<Address> members,double subset_percentage) { - List<Address> ret=new ArrayList<>(), tmp_mbrs; - int num_mbrs=members.size(), subset_size, index; - - if(num_mbrs == 0) return ret; - subset_size=(int)Math.ceil(num_mbrs * subset_percentage); - - tmp_mbrs=new ArrayList<>(members); - - for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i--) { - index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); - ret.add(tmp_mbrs.get(index)); - tmp_mbrs.remove(index); - } - - return ret; - } - - public static <T> boolean contains(T key,T[] list) { if(list == null) return false; for(T tmp : list) @@ -2371,24 +2349,18 @@ public static int getRank(Collection<Address> members,Address addr) { public static <T> T pickRandomElement(List<T> list) { if(list == null || list.isEmpty()) return null; int size=list.size(); - int index=(int)((Math.random() * size * 10) % size); + int index=(int)Util.random(size)-1; return list.get(index); } public static <T> T pickRandomElement(T[] array) { if(array == null) return null; int size=array.length; - int index=(int)((Math.random() * size * 10) % size); + int index=(int)Util.random(size)-1; return array[index]; } - /** - * Returns the object next to element in list - * @param list - * @param obj - * @param <T> - * @return - */ + public static <T> T pickNext(List<T> list,T obj) { if(list == null || obj == null) return null; diff --git a/tests/junit-functional/org/jgroups/tests/UtilTest.java b/tests/junit-functional/org/jgroups/tests/UtilTest.java index 3ba0e00d5b8..dbd1535a802 100644 --- a/tests/junit-functional/org/jgroups/tests/UtilTest.java +++ b/tests/junit-functional/org/jgroups/tests/UtilTest.java @@ -10,6 +10,9 @@ import java.io.*; import java.nio.ByteBuffer; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.LongStream; @Test(groups=Global.FUNCTIONAL) @@ -684,6 +687,23 @@ public static void testWriteAndReadStreamableArray() throws Exception { } } + public void testRandom() { + List<Long> list=LongStream.rangeClosed(1,10).boxed().collect(Collectors.toList()); + for(int i=0; i < 1_000_000; i++) { + long random=Util.random(10); + assert random >= 1 && random <= 10: String.format("random is %d", random); + if(list.remove(random) && list.isEmpty()) + break; + } + assert list.isEmpty(); + + long random=Util.random(1); + assert random == 1; + + random=Util.random(0); + assert random == 1; + } + public static void testMatch() { long[] a={1,2,3}; @@ -812,19 +832,29 @@ public static void testNewMembers() { assert new_nodes.contains(e); } - public static void testPickRandomElement() { + public void testPickRandomElement() { List<Integer> v=new ArrayList<>(); for(int i=0; i < 10; i++) { v.add(i); } - - Integer el; for(int i=0; i < 10000; i++) { - el=Util.pickRandomElement(v); + Integer el=Util.pickRandomElement(v); assert el >= 0 && el < 10; } } + public void testPickRandomElement2() { + List<Integer> list=IntStream.rangeClosed(0, 9).boxed().collect(Collectors.toList()); + for(int i=0; i < 1_000_000; i++) { + Integer el=Util.pickRandomElement(list); + boolean rc=list.remove(el); + assert rc; + if(list.isEmpty()) + break; + } + assert list.isEmpty(); + } + public static void testPickNext() { List<Integer> list=new ArrayList<>(10);
bcd1a596f2a4fa0e244c2f31c9256b078c1bfdf6
restlet-framework-java
- Fixed connection closing regression--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java index 0dfbd1fb0e..e2335b6619 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java @@ -83,9 +83,6 @@ protected void controlConnections() throws IOException { // Close connections or register interest in NIO operations for (Connection<?> conn : getHelper().getConnections()) { if (conn.getState() == ConnectionState.CLOSED) { - // Make sure that the registration is removed from the selector - getUpdatedRegistrations().add(conn.getRegistration()); - // Detach the connection and collect it getHelper().getConnections().remove(conn); getHelper().checkin(conn);
e8f9097127843a3e56cd594da91c12430c178525
kotlin
do not mark error type if the expression is- resolved to namespace (EXPRESSION_EXPECTED_NAMESPACE_FOUND error)--
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/jet/checkers/DebugInfoUtil.java b/compiler/frontend/src/org/jetbrains/jet/checkers/DebugInfoUtil.java index 0d62832e48485..572aaf4cd72e7 100644 --- a/compiler/frontend/src/org/jetbrains/jet/checkers/DebugInfoUtil.java +++ b/compiler/frontend/src/org/jetbrains/jet/checkers/DebugInfoUtil.java @@ -70,6 +70,9 @@ else if (factory == Errors.SUPER_IS_NOT_AN_EXPRESSION JetSuperExpression superExpression = (JetSuperExpression) diagnostic.getPsiElement(); markedWithErrorElements.put(superExpression.getInstanceReference(), factory); } + else if (factory == Errors.EXPRESSION_EXPECTED_NAMESPACE_FOUND) { + markedWithErrorElements.put((JetSimpleNameExpression) diagnostic.getPsiElement(), factory); + } } root.acceptChildren(new JetTreeVisitorVoid() { diff --git a/compiler/testData/diagnostics/tests/NamespaceAsExpression.kt b/compiler/testData/diagnostics/tests/NamespaceAsExpression.kt index f26e6530f3dd1..9d2ca455811c4 100644 --- a/compiler/testData/diagnostics/tests/NamespaceAsExpression.kt +++ b/compiler/testData/diagnostics/tests/NamespaceAsExpression.kt @@ -4,5 +4,5 @@ package root.a // FILE: b.kt package root -val x = <!EXPRESSION_EXPECTED_NAMESPACE_FOUND, DEBUG_INFO_ERROR_ELEMENT!>a<!> +val x = <!EXPRESSION_EXPECTED_NAMESPACE_FOUND!>a<!> val y2 = <!NAMESPACE_IS_NOT_AN_EXPRESSION!>package<!> \ No newline at end of file diff --git a/compiler/testData/diagnostics/tests/NamespaceInExpressionPosition.kt b/compiler/testData/diagnostics/tests/NamespaceInExpressionPosition.kt index 3db9bca39918c..740ed2c0b3a4d 100644 --- a/compiler/testData/diagnostics/tests/NamespaceInExpressionPosition.kt +++ b/compiler/testData/diagnostics/tests/NamespaceInExpressionPosition.kt @@ -2,10 +2,10 @@ package foo class X {} -val s = <!EXPRESSION_EXPECTED_NAMESPACE_FOUND, DEBUG_INFO_ERROR_ELEMENT!>java<!> +val s = <!EXPRESSION_EXPECTED_NAMESPACE_FOUND!>java<!> val ss = <!NO_CLASS_OBJECT!>System<!> val sss = <!NO_CLASS_OBJECT!>X<!> -val xs = java.<!EXPRESSION_EXPECTED_NAMESPACE_FOUND, DEBUG_INFO_ERROR_ELEMENT!>lang<!> +val xs = java.<!EXPRESSION_EXPECTED_NAMESPACE_FOUND!>lang<!> val xss = java.lang.<!NO_CLASS_OBJECT!>System<!> val xsss = foo.<!NO_CLASS_OBJECT!>X<!> -val xssss = <!EXPRESSION_EXPECTED_NAMESPACE_FOUND, DEBUG_INFO_ERROR_ELEMENT!>foo<!> \ No newline at end of file +val xssss = <!EXPRESSION_EXPECTED_NAMESPACE_FOUND!>foo<!> \ No newline at end of file
ebe25c83d1f5f1202c560516e8d58294b97ddf37
orientdb
Fixed bug using SQL projection against Object- Database interface. Now returns always documents instead of POJOs when the- ODocument has no class associated.--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java index 38afe2694d8..6e3ad037ca7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java @@ -212,7 +212,11 @@ public <RET extends List<?>> RET query(final OQuery<?> iCommand) { Object obj; for (ODocument doc : result) { // GET THE ASSOCIATED DOCUMENT - obj = getUserObjectByRecord(doc, iCommand.getFetchPlan(), true); + if (doc.getClassName() == null) + obj = doc; + else + obj = getUserObjectByRecord(doc, iCommand.getFetchPlan(), true); + resultPojo.add(obj); } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java index 27699e60437..d073da7d843 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java @@ -30,6 +30,7 @@ import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.OBase64Utils; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; @Test(groups = { "crud", "record-vobject" }, sequential = true) public class CRUDDocumentPhysicalTest { @@ -234,4 +235,35 @@ public void testNestedEmbeddedMap() { Assert.assertEquals(loadedMap3.size(), 0); } + @Test + public void queryWithPositionalParameters() { + database = ODatabaseDocumentPool.global().acquire(url, "admin", "admin"); + database.open("admin", "admin"); + + final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?"); + List<ODocument> result = database.command(query).execute("Barack", "Obama"); + + Assert.assertTrue(result.size() != 0); + + database.close(); + } + + @Test + public void queryWithNamedParameters() { + database = ODatabaseDocumentPool.global().acquire(url, "admin", "admin"); + database.open("admin", "admin"); + + final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>( + "select from Profile where name = :name and surname = :surname"); + + HashMap<String, String> params = new HashMap<String, String>(); + params.put("name", "Barack"); + params.put("surname", "Obama"); + + List<ODocument> result = database.command(query).execute(params); + + Assert.assertTrue(result.size() != 0); + + database.close(); + } } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java index 86d690ad36f..c898058b253 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java @@ -16,6 +16,7 @@ package com.orientechnologies.orient.test.database.auto; import java.util.Date; +import java.util.HashMap; import java.util.List; import org.testng.Assert; @@ -276,4 +277,36 @@ public void deleteFirst() { database.close(); } + + @Test + public void queryWithPositionalParameters() { + database = ODatabaseObjectPool.global().acquire(url, "admin", "admin"); + database.open("admin", "admin"); + + final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?"); + List<ODocument> result = database.command(query).execute("Barack", "Obama"); + + Assert.assertTrue(result.size() != 0); + + database.close(); + } + + @Test + public void queryWithNamedParameters() { + database = ODatabaseObjectPool.global().acquire(url, "admin", "admin"); + database.open("admin", "admin"); + + final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>( + "select from Profile where name = :name and surname = :surname"); + + HashMap<String, String> params = new HashMap<String, String>(); + params.put("name", "Barack"); + params.put("surname", "Obama"); + + List<ODocument> result = database.command(query).execute(params); + + Assert.assertTrue(result.size() != 0); + + database.close(); + } } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java index 9a2111e1fe9..203fb57e5b8 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java @@ -23,15 +23,18 @@ import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; @Test(groups = "sql-select") public class SQLSelectProjectionsTest { + private String url; private ODatabaseDocument database; @Parameters(value = "url") public SQLSelectProjectionsTest(String iURL) { + url = iURL; database = new ODatabaseDocumentTx(iURL); } @@ -52,6 +55,23 @@ public void queryProjectionOk() { database.close(); } + @Test + public void queryProjectionObjectLevel() { + ODatabaseObjectTx db = new ODatabaseObjectTx(url); + db.open("admin", "admin"); + + List<ODocument> result = db.query(new OSQLSynchQuery<ODocument>(" select nick, followings, followers from Profile ")); + + Assert.assertTrue(result.size() != 0); + + for (ODocument d : result) { + Assert.assertNull(d.getClassName()); + Assert.assertEquals(d.getRecordType(), ODocument.RECORD_TYPE); + } + + db.close(); + } + @Test public void queryProjectionLinkedAndFunction() { database.open("admin", "admin"); @@ -141,7 +161,8 @@ public void queryProjectionAliases() { database.open("admin", "admin"); List<ODocument> result = database.command( - new OSQLSynchQuery<ODocument>("select name.append('!') as 1, surname as 2 from Profile where name is not null and surname is not null")).execute(); + new OSQLSynchQuery<ODocument>( + "select name.append('!') as 1, surname as 2 from Profile where name is not null and surname is not null")).execute(); Assert.assertTrue(result.size() != 0); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java index 719e6140bbc..d4f5e5c0261 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java @@ -18,7 +18,6 @@ import java.text.ParseException; import java.util.Collection; import java.util.Date; -import java.util.HashMap; import java.util.List; import org.testng.Assert; @@ -574,34 +573,4 @@ public void queryWithPagination() { database.close(); } - - @Test - public void queryWithPositionalParameters() { - database.open("admin", "admin"); - - final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?"); - List<ODocument> result = database.command(query).execute("Barack", "Obama"); - - Assert.assertTrue(result.size() != 0); - - database.close(); - } - - @Test - public void queryWithNamedParameters() { - database.open("admin", "admin"); - - final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument >( - "select from Profile where name = :name and surname = :surname"); - - HashMap<String, String> params = new HashMap<String, String>(); - params.put("name", "Barack"); - params.put("surname", "Obama"); - - List<ODocument> result = database.command(query).execute(params); - - Assert.assertTrue(result.size() != 0); - - database.close(); - } }
6c0386029b4620e622f6d62939567f88238a21a2
camel
CAMEL-2011: JmsEndpoint is now singleton.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@814584 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java index 78ad2ac9dfc3b..8c6a049c9f13e 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java @@ -305,8 +305,9 @@ public void setSelector(String selector) { this.selector = selector; } + @ManagedAttribute public boolean isSingleton() { - return false; + return true; } public synchronized Requestor getRequestor() throws Exception { diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/JmsSendToAlotOfDestinationWithSameEndpointTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/JmsSendToAlotOfDestinationWithSameEndpointTest.java index 6beb3397d1d43..c6c84ae801834 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/JmsSendToAlotOfDestinationWithSameEndpointTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/JmsSendToAlotOfDestinationWithSameEndpointTest.java @@ -47,7 +47,6 @@ public void testSendToAlotOfMessageToQueues() throws Exception { // use the same endpoint but provide a header with the dynamic queue we send to // this allows us to reuse endpoints and not create a new endpoint for each and every jms queue // we send to - Thread.sleep(50); if (i > 0 && i % 50 == 0) { LOG.info("Send " + i + " messages so far"); }
0a545cb738de474fb6dd20bdd8e28e939ab62dae
camel
CAMEL-2919: Debugger API--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@961615 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java b/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java index c87280b7bfe64..dace795250a2e 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java +++ b/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java @@ -16,13 +16,17 @@ */ package org.apache.camel.impl; +import java.util.EventObject; + import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.spi.Breakpoint; /** * A support class for {@link Breakpoint} implementations to use as base class. * <p/> - * Will be in active state and match any {@link Exchange}s. + * Will be in active state. * * @version $Revision$ */ @@ -42,4 +46,15 @@ public void activate() { state = State.Active; } + public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { + // noop + } + + public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { + // noop + } + + public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) { + // noop + } } diff --git a/camel-core/src/main/java/org/apache/camel/impl/ConditionSupport.java b/camel-core/src/main/java/org/apache/camel/impl/ConditionSupport.java new file mode 100644 index 0000000000000..538f122c1bd38 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/impl/ConditionSupport.java @@ -0,0 +1,40 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.impl; + +import java.util.EventObject; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.spi.Condition; + +/** + * A support class for {@link org.apache.camel.spi.Condition} implementations to use as base class. + * + * @version $Revision$ + */ +public class ConditionSupport implements Condition { + + public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { + return false; + } + + public boolean matchEvent(Exchange exchange, EventObject event) { + return false; + } +} diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 42662acaf56f8..086d43f34524e 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -1023,8 +1023,12 @@ private void doStartCamel() throws Exception { } } + // register debugger if (getDebugger() != null) { LOG.info("Debugger: " + getDebugger() + " is enabled on CamelContext: " + getName()); + // register this camel context on the debugger + getDebugger().setCamelContext(this); + startServices(getDebugger()); addInterceptStrategy(new Debug(getDebugger())); } @@ -1073,6 +1077,7 @@ private void doStartCamel() throws Exception { routeDefinitionInitiated = true; } + // starting will continue in the start method } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java index 38dec875a0c87..acf6f481f7d88 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java @@ -19,14 +19,23 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.EventObject; import java.util.List; +import org.apache.camel.CamelContext; +import org.apache.camel.CamelContextAware; import org.apache.camel.Exchange; +import org.apache.camel.LoggingLevel; import org.apache.camel.Processor; +import org.apache.camel.RouteNode; +import org.apache.camel.management.EventNotifierSupport; +import org.apache.camel.management.event.AbstractExchangeEvent; import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.processor.interceptor.Tracer; import org.apache.camel.spi.Breakpoint; import org.apache.camel.spi.Condition; import org.apache.camel.spi.Debugger; +import org.apache.camel.util.ObjectHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -35,10 +44,11 @@ * * @version $Revision$ */ -public class DefaultDebugger implements Debugger { +public class DefaultDebugger implements Debugger, CamelContextAware { private static final Log LOG = LogFactory.getLog(DefaultDebugger.class); private final List<BreakpointConditions> breakpoints = new ArrayList<BreakpointConditions>(); + private CamelContext camelContext; /** * Holder class for breakpoint and the associated conditions @@ -65,6 +75,21 @@ public List<Condition> getConditions() { } } + public DefaultDebugger() { + } + + public DefaultDebugger(CamelContext camelContext) { + this.camelContext = camelContext; + } + + public CamelContext getCamelContext() { + return camelContext; + } + + public void setCamelContext(CamelContext camelContext) { + this.camelContext = camelContext; + } + public void addBreakpoint(Breakpoint breakpoint) { breakpoints.add(new BreakpointConditions(breakpoint)); } @@ -97,7 +122,24 @@ public List<Breakpoint> getBreakpoints() { return Collections.unmodifiableList(answer); } - public boolean onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition) { + public boolean beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { + boolean match = false; + + // does any of the breakpoints apply? + for (BreakpointConditions breakpoint : breakpoints) { + // breakpoint must be active + if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) { + if (matchConditions(exchange, processor, definition, breakpoint)) { + match = true; + onBeforeProcess(exchange, processor, definition, breakpoint.getBreakpoint()); + } + } + } + + return match; + } + + public boolean afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { boolean match = false; // does any of the breakpoints apply? @@ -106,7 +148,7 @@ public boolean onExchange(Exchange exchange, Processor processor, ProcessorDefin if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) { if (matchConditions(exchange, processor, definition, breakpoint)) { match = true; - onBreakpoint(exchange, processor, definition, breakpoint.getBreakpoint()); + onAfterProcess(exchange, processor, definition, breakpoint.getBreakpoint()); } } } @@ -114,10 +156,61 @@ public boolean onExchange(Exchange exchange, Processor processor, ProcessorDefin return match; } - private boolean matchConditions(Exchange exchange, Processor processor, ProcessorDefinition definition, BreakpointConditions breakpoint) { + public boolean onEvent(Exchange exchange, EventObject event) { + boolean match = false; + + // does any of the breakpoints apply? + for (BreakpointConditions breakpoint : breakpoints) { + // breakpoint must be active + if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) { + if (matchConditions(exchange, event, breakpoint)) { + match = true; + onEvent(exchange, event, breakpoint.getBreakpoint()); + } + } + } + + return match; + } + + protected void onBeforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) { + try { + breakpoint.beforeProcess(exchange, processor, definition); + } catch (Throwable e) { + LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e); + } + } + + protected void onAfterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) { + try { + breakpoint.afterProcess(exchange, processor, definition); + } catch (Throwable e) { + LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e); + } + } + + protected void onEvent(Exchange exchange, EventObject event, Breakpoint breakpoint) { + ProcessorDefinition definition = null; + + // try to get the last known definition + if (exchange.getUnitOfWork() != null && exchange.getUnitOfWork().getTracedRouteNodes() != null) { + RouteNode node = exchange.getUnitOfWork().getTracedRouteNodes().getLastNode(); + if (node != null) { + definition = node.getProcessorDefinition(); + } + } + + try { + breakpoint.onEvent(exchange, event, definition); + } catch (Throwable e) { + LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e); + } + } + + private boolean matchConditions(Exchange exchange, Processor processor, ProcessorDefinition definition, BreakpointConditions breakpoint) { if (breakpoint.getConditions() != null && !breakpoint.getConditions().isEmpty()) { for (Condition condition : breakpoint.getConditions()) { - if (!condition.match(exchange, definition)) { + if (!condition.matchProcess(exchange, processor, definition)) { return false; } } @@ -126,21 +219,66 @@ private boolean matchConditions(Exchange exchange, Processor processor, Process return true; } - protected void onBreakpoint(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) { - breakpoint.onExchange(exchange, processor, definition); + private boolean matchConditions(Exchange exchange, EventObject event, BreakpointConditions breakpoint) { + if (breakpoint.getConditions() != null && !breakpoint.getConditions().isEmpty()) { + for (Condition condition : breakpoint.getConditions()) { + if (!condition.matchEvent(exchange, event)) { + return false; + } + } + } + + return true; } public void start() throws Exception { - // noop + ObjectHelper.notNull(camelContext, "CamelContext", this); + // register our event notifier + camelContext.getManagementStrategy().addEventNotifier(new DebugEventNotifier()); + Tracer tracer = Tracer.getTracer(camelContext); + if (tracer == null) { + // tracer is disabled so enable it silently so we can leverage it to trace the Exchanges for us + tracer = Tracer.createTracer(camelContext); + tracer.setLogLevel(LoggingLevel.OFF); + camelContext.addService(tracer); + camelContext.addInterceptStrategy(tracer); + } } public void stop() throws Exception { breakpoints.clear(); - // noop } @Override public String toString() { return "DefaultDebugger"; } + + private final class DebugEventNotifier extends EventNotifierSupport { + + private DebugEventNotifier() { + setIgnoreCamelContextEvents(true); + setIgnoreServiceEvents(true); + } + + public void notify(EventObject event) throws Exception { + AbstractExchangeEvent aee = (AbstractExchangeEvent) event; + Exchange exchange = aee.getExchange(); + onEvent(exchange, event); + } + + public boolean isEnabled(EventObject event) { + return event instanceof AbstractExchangeEvent; + } + + @Override + protected void doStart() throws Exception { + // noop + } + + @Override + protected void doStop() throws Exception { + // noop + } + } } diff --git a/camel-core/src/main/java/org/apache/camel/management/event/AbstractExchangeEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/AbstractExchangeEvent.java new file mode 100644 index 0000000000000..0a3f2694392aa --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/management/event/AbstractExchangeEvent.java @@ -0,0 +1,40 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.management.event; + +import java.util.EventObject; + +import org.apache.camel.Exchange; + +/** + * Base class for {@link Exchange} events. + * + * @version $Revision$ + */ +public abstract class AbstractExchangeEvent extends EventObject { + + private final Exchange exchange; + + public AbstractExchangeEvent(Exchange source) { + super(source); + this.exchange = source; + } + + public Exchange getExchange() { + return exchange; + } +} diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java index e460e609a188d..4b89267d7c5e7 100644 --- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java +++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java @@ -16,29 +16,20 @@ */ package org.apache.camel.management.event; -import java.util.EventObject; - import org.apache.camel.Exchange; /** * @version $Revision$ */ -public class ExchangeCompletedEvent extends EventObject { +public class ExchangeCompletedEvent extends AbstractExchangeEvent { private static final long serialVersionUID = -3231801412021356098L; - private final Exchange exchange; - public ExchangeCompletedEvent(Exchange source) { super(source); - this.exchange = source; - } - - public Exchange getExchange() { - return exchange; } @Override public String toString() { - return exchange.getExchangeId() + " exchange completed: " + exchange; + return getExchange().getExchangeId() + " exchange completed: " + getExchange(); } } diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java index 1cf6a50d5dfbc..658d9ba3079aa 100644 --- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java +++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java @@ -16,29 +16,20 @@ */ package org.apache.camel.management.event; -import java.util.EventObject; - import org.apache.camel.Exchange; /** * @version $Revision$ */ -public class ExchangeCreatedEvent extends EventObject { +public class ExchangeCreatedEvent extends AbstractExchangeEvent { private static final long serialVersionUID = -19248832613958243L; - private final Exchange exchange; - public ExchangeCreatedEvent(Exchange source) { super(source); - this.exchange = source; - } - - public Exchange getExchange() { - return exchange; } @Override public String toString() { - return exchange.getExchangeId() + " exchange created: " + exchange; + return getExchange().getExchangeId() + " exchange created: " + getExchange(); } } diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java index 15ff4d57b0d30..85e537b3d45d8 100644 --- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java +++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java @@ -16,34 +16,25 @@ */ package org.apache.camel.management.event; -import java.util.EventObject; - import org.apache.camel.Exchange; /** * @version $Revision$ */ -public class ExchangeFailureEvent extends EventObject { +public class ExchangeFailureEvent extends AbstractExchangeEvent { private static final long serialVersionUID = -8484326904627268101L; - private final Exchange exchange; - public ExchangeFailureEvent(Exchange source) { super(source); - this.exchange = source; - } - - public Exchange getExchange() { - return exchange; } @Override public String toString() { - Exception cause = exchange.getException(); + Exception cause = getExchange().getException(); if (cause != null) { - return exchange.getExchangeId() + " exchange failure: " + exchange + " cause " + cause; + return getExchange().getExchangeId() + " exchange failure: " + getExchange() + " cause " + cause; } else { - return exchange.getExchangeId() + " exchange failure: " + exchange; + return getExchange().getExchangeId() + " exchange failure: " + getExchange(); } } } diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java index 740e3b0890b15..c711e06363f51 100644 --- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java +++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java @@ -16,32 +16,24 @@ */ package org.apache.camel.management.event; -import java.util.EventObject; - import org.apache.camel.Exchange; import org.apache.camel.Processor; /** * @version $Revision$ */ -public class ExchangeFailureHandledEvent extends EventObject { +public class ExchangeFailureHandledEvent extends AbstractExchangeEvent { private static final long serialVersionUID = -7554809462006009547L; - private final Exchange exchange; private final Processor failureHandler; private final boolean deadLetterChannel; private final boolean handled; public ExchangeFailureHandledEvent(Exchange source, Processor failureHandler, boolean deadLetterChannel) { super(source); - this.exchange = source; this.failureHandler = failureHandler; this.deadLetterChannel = deadLetterChannel; - this.handled = exchange.getProperty(Exchange.ERRORHANDLER_HANDLED, false, Boolean.class); - } - - public Exchange getExchange() { - return exchange; + this.handled = source.getProperty(Exchange.ERRORHANDLER_HANDLED, false, Boolean.class); } public Processor getFailureHandler() { @@ -59,9 +51,9 @@ public boolean isHandled() { @Override public String toString() { if (isDeadLetterChannel()) { - return exchange.getExchangeId() + " exchange failed: " + exchange + " but was handled by dead letter channel: " + failureHandler; + return getExchange().getExchangeId() + " exchange failed: " + getExchange() + " but was handled by dead letter channel: " + failureHandler; } else { - return exchange.getExchangeId() + " exchange failed: " + exchange + " but was processed by: " + failureHandler; + return getExchange().getExchangeId() + " exchange failed: " + getExchange() + " but was processed by: " + failureHandler; } } } diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java index bbe6f354e5933..d264bc82c43db 100644 --- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java +++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java @@ -16,32 +16,24 @@ */ package org.apache.camel.management.event; -import java.util.EventObject; - import org.apache.camel.Endpoint; import org.apache.camel.Exchange; /** * @version $Revision$ */ -public class ExchangeSentEvent extends EventObject { +public class ExchangeSentEvent extends AbstractExchangeEvent { private static final long serialVersionUID = -19248832613958123L; - private final Exchange exchange; private final Endpoint endpoint; private final long timeTaken; public ExchangeSentEvent(Exchange source, Endpoint endpoint, long timeTaken) { super(source); - this.exchange = source; this.endpoint = endpoint; this.timeTaken = timeTaken; } - public Exchange getExchange() { - return exchange; - } - public Endpoint getEndpoint() { return endpoint; } @@ -52,7 +44,7 @@ public long getTimeTaken() { @Override public String toString() { - return exchange.getExchangeId() + " exchange " + exchange + " sent to: " + endpoint.getEndpointUri() + " took: " + timeTaken + " ms."; + return getExchange().getExchangeId() + " exchange " + getExchange() + " sent to: " + endpoint.getEndpointUri() + " took: " + timeTaken + " ms."; } } \ No newline at end of file diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java index 5f6ddfa1fd180..1733eed3caaee 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java +++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java @@ -26,6 +26,8 @@ import org.apache.camel.spi.InterceptStrategy; /** + * A debug interceptor to notify {@link Debugger} with {@link Exchange}s being processed. + * * @version $Revision$ */ public class Debug implements InterceptStrategy { @@ -40,9 +42,16 @@ public Processor wrapProcessorInInterceptors(final CamelContext context, final P final Processor target, final Processor nextTarget) throws Exception { return new DelegateAsyncProcessor(target) { @Override - public boolean process(Exchange exchange, AsyncCallback callback) { - debugger.onExchange(exchange, target, definition); - return super.process(exchange, callback); + public boolean process(final Exchange exchange, final AsyncCallback callback) { + debugger.beforeProcess(exchange, target, definition); + + return super.process(exchange, new AsyncCallback() { + public void done(boolean doneSync) { + debugger.afterProcess(exchange, processor, definition); + // must notify original callback + callback.done(doneSync); + } + }); } @Override diff --git a/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java b/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java index d4f1d98d33a68..8153955073039 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java +++ b/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java @@ -16,6 +16,8 @@ */ package org.apache.camel.spi; +import java.util.EventObject; + import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.model.ProcessorDefinition; @@ -26,20 +28,19 @@ * This allows you to register {@link org.apache.camel.spi.Breakpoint}s to the {@link org.apache.camel.spi.Debugger} * and have those breakpoints activated when their {@link org.apache.camel.spi.Condition}s match. * <p/> - * If any exceptions is thrown from the {@link #onExchange(org.apache.camel.Exchange, org.apache.camel.Processor, org.apache.camel.model.ProcessorDefinition)} - * method then the {@link org.apache.camel.spi.Debugger} will catch and log those at <tt>WARN</tt> level and continue. + * If any exceptions is thrown from the callback methods then the {@link org.apache.camel.spi.Debugger} + * will catch and log those at <tt>WARN</tt> level and continue. This ensures Camel can continue to route + * the message without having breakpoints causing issues. * + * @version $Revision$ * @see org.apache.camel.spi.Debugger * @see org.apache.camel.spi.Condition - * @version $Revision$ */ public interface Breakpoint { - // TODO: Hook into the EventNotifier so we can have breakpoints trigger on those conditions as well - // exceptions, create, done, etc. and a FollowMe condition to follow a single exchange - // while others are being routed so you can follow one only, eg need an API on Debugger for that - - enum State { Active, Suspended } + enum State { + Active, Suspended + } /** * Gets the state of this break @@ -59,12 +60,32 @@ enum State { Active, Suspended } void activate(); /** - * Callback invoked when the breakpoint was hit. + * Callback invoked when the breakpoint was hit and the {@link Exchange} is about to be processed (before). + * + * @param exchange the {@link Exchange} + * @param processor the {@link Processor} about to be processed + * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the processor + */ + void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition); + + /** + * Callback invoked when the breakpoint was hit and the {@link Exchange} has been processed (after). + * + * @param exchange the {@link Exchange} + * @param processor the {@link Processor} which was processed + * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the processor + */ + void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition); + + /** + * Callback invoked when the breakpoint was hit and any of the {@link Exchange} {@link EventObject event}s occurred. * - * @param exchange the {@link Exchange} - * @param processor the {@link Processor} which is the next target - * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the processor + * @param exchange the {@link Exchange} + * @param event the event (instance of {@link org.apache.camel.management.event.AbstractExchangeEvent} + * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the last processor executed, + * may be <tt>null</tt> if not possible to resolve from tracing + * @see org.apache.camel.management.event.AbstractExchangeEvent */ - void onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition); + void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition); } diff --git a/camel-core/src/main/java/org/apache/camel/spi/Condition.java b/camel-core/src/main/java/org/apache/camel/spi/Condition.java index 9773a05e8f378..e5ccd6617e835 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/Condition.java +++ b/camel-core/src/main/java/org/apache/camel/spi/Condition.java @@ -16,7 +16,10 @@ */ package org.apache.camel.spi; +import java.util.EventObject; + import org.apache.camel.Exchange; +import org.apache.camel.Processor; import org.apache.camel.model.ProcessorDefinition; /** @@ -33,9 +36,20 @@ public interface Condition { * Does the condition match * * @param exchange the exchange - * @param definition the current node in the route where the Exchange is at + * @param processor the {@link Processor} + * @param definition the present location in the route where the {@link Exchange} is located at + * @return <tt>true</tt> to match, <tt>false</tt> otherwise + */ + boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition); + + /** + * Does the condition match + * + * @param exchange the exchange + * @param event the event (instance of {@link org.apache.camel.management.event.AbstractExchangeEvent} * @return <tt>true</tt> to match, <tt>false</tt> otherwise + * @see org.apache.camel.management.event.AbstractExchangeEvent */ - boolean match(Exchange exchange, ProcessorDefinition definition); + boolean matchEvent(Exchange exchange, EventObject event); } diff --git a/camel-core/src/main/java/org/apache/camel/spi/Debugger.java b/camel-core/src/main/java/org/apache/camel/spi/Debugger.java index f2c6a78f91807..13823e54e8a9e 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/Debugger.java +++ b/camel-core/src/main/java/org/apache/camel/spi/Debugger.java @@ -16,8 +16,10 @@ */ package org.apache.camel.spi; +import java.util.EventObject; import java.util.List; +import org.apache.camel.CamelContextAware; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Service; @@ -29,7 +31,7 @@ * * @version $Revision$ */ -public interface Debugger extends Service { +public interface Debugger extends Service, CamelContextAware { /** * Add the given breakpoint @@ -70,15 +72,36 @@ public interface Debugger extends Service { */ List<Breakpoint> getBreakpoints(); + /** + * Callback invoked when an {@link Exchange} is about to be processed which allows implementators + * to notify breakpoints. + * + * @param exchange the exchange + * @param processor the {@link Processor} about to be processed + * @param definition the definition of the processor + * @return <tt>true</tt> if any breakpoint was hit, <tt>false</tt> if not breakpoint was hit + */ + boolean beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition); + + /** + * Callback invoked when an {@link Exchange} has been processed which allows implementators + * to notify breakpoints. + * + * @param exchange the exchange + * @param processor the {@link Processor} which was processed + * @param definition the definition of the processor + * @return <tt>true</tt> if any breakpoint was hit, <tt>false</tt> if not breakpoint was hit + */ + boolean afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition); + /** * Callback invoked when an {@link Exchange} is being processed which allows implementators * to notify breakpoints. * - * @param exchange the exchange - * @param processor the target processor (to be processed next) - * @param definition the definition of the processor + * @param exchange the exchange + * @param event the event (instance of {@link org.apache.camel.management.event.AbstractExchangeEvent} * @return <tt>true</tt> if any breakpoint was hit, <tt>false</tt> if not breakpoint was hit */ - boolean onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition); + boolean onEvent(Exchange exchange, EventObject event); } diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionBreakpointTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionBreakpointTest.java new file mode 100644 index 0000000000000..96a698258ce16 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionBreakpointTest.java @@ -0,0 +1,100 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.processor.interceptor; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.BreakpointSupport; +import org.apache.camel.impl.ConditionSupport; +import org.apache.camel.impl.DefaultDebugger; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.spi.Breakpoint; +import org.apache.camel.spi.Condition; + +/** + * @version $Revision$ + */ +public class DebugExceptionBreakpointTest extends ContextTestSupport { + + private List<String> logs = new ArrayList<String>(); + private Condition exceptionCondition; + private Breakpoint breakpoint; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + breakpoint = new BreakpointSupport() { + @Override + public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { + Exception e = exchange.getException(); + logs.add("Breakpoint at " + definition.getShortName() + " caused by: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); + } + }; + + exceptionCondition = new ConditionSupport() { + @Override + public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { + return exchange.getException() != null; + } + }; + } + + public void testDebug() throws Exception { + context.getDebugger().addBreakpoint(breakpoint, exceptionCondition); + + getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); + + template.sendBody("direct:start", "Hello World"); + try { + template.sendBody("direct:start", "Hello Camel"); + fail("Should have thrown exception"); + } catch (Exception e) { + // ignore + } + + assertMockEndpointsSatisfied(); + + assertEquals(2, logs.size()); + assertEquals("Breakpoint at when caused by: IllegalArgumentException[Damn]", logs.get(0)); + assertEquals("Breakpoint at choice caused by: IllegalArgumentException[Damn]", logs.get(1)); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + // use debugger + context.setDebugger(new DefaultDebugger()); + + from("direct:start") + .to("log:foo") + .choice() + .when(body().contains("Camel")).throwException(new IllegalArgumentException("Damn")) + .end() + .to("mock:result"); + } + }; + } + +} \ No newline at end of file diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java new file mode 100644 index 0000000000000..2a7c6fc5b9ee8 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java @@ -0,0 +1,100 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.processor.interceptor; + +import java.util.ArrayList; +import java.util.EventObject; +import java.util.List; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.BreakpointSupport; +import org.apache.camel.impl.ConditionSupport; +import org.apache.camel.impl.DefaultDebugger; +import org.apache.camel.management.event.AbstractExchangeEvent; +import org.apache.camel.management.event.ExchangeFailureEvent; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.spi.Breakpoint; +import org.apache.camel.spi.Condition; + +/** + * @version $Revision$ + */ +public class DebugExceptionEventBreakpointTest extends ContextTestSupport { + + private List<String> logs = new ArrayList<String>(); + private Condition exceptionCondition; + private Breakpoint breakpoint; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + breakpoint = new BreakpointSupport() { + public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) { + AbstractExchangeEvent aee = (AbstractExchangeEvent) event; + Exception e = aee.getExchange().getException(); + logs.add("Breakpoint at " + definition + " caused by: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); + } + }; + + exceptionCondition = new ConditionSupport() { + public boolean matchEvent(Exchange exchange, EventObject event) { + return event instanceof ExchangeFailureEvent; + } + }; + } + + public void testDebug() throws Exception { + context.getDebugger().addBreakpoint(breakpoint, exceptionCondition); + + getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); + + template.sendBody("direct:start", "Hello World"); + try { + template.sendBody("direct:start", "Hello Camel"); + fail("Should have thrown exception"); + } catch (Exception e) { + // ignore + } + + assertMockEndpointsSatisfied(); + + assertEquals(1, logs.size()); + assertEquals("Breakpoint at ThrowException[java.lang.IllegalArgumentException] caused by: IllegalArgumentException[Damn]", logs.get(0)); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + // use debugger + context.setDebugger(new DefaultDebugger()); + + from("direct:start") + .to("log:foo") + .choice() + .when(body().contains("Camel")).throwException(new IllegalArgumentException("Damn")) + .end() + .to("mock:result"); + } + }; + } + +} \ No newline at end of file diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java index 781d95d0add22..d35e381fe3939 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java @@ -17,6 +17,7 @@ package org.apache.camel.processor.interceptor; import java.util.ArrayList; +import java.util.EventObject; import java.util.List; import org.apache.camel.ContextTestSupport; @@ -24,7 +25,9 @@ import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.BreakpointSupport; +import org.apache.camel.impl.ConditionSupport; import org.apache.camel.impl.DefaultDebugger; +import org.apache.camel.management.event.ExchangeCompletedEvent; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.ToDefinition; import org.apache.camel.spi.Breakpoint; @@ -38,6 +41,7 @@ public class DebugTest extends ContextTestSupport { private List<String> logs = new ArrayList<String>(); private Condition camelCondition; private Condition mockCondition; + private Condition doneCondition; private Breakpoint breakpoint; @Override @@ -45,20 +49,25 @@ protected void setUp() throws Exception { super.setUp(); breakpoint = new BreakpointSupport() { - public void onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition) { + public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { String body = exchange.getIn().getBody(String.class); logs.add("Breakpoint at " + definition + " with body: " + body); } + + public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) { + String body = exchange.getIn().getBody(String.class); + logs.add("Breakpoint event " + event.getClass().getSimpleName() + " with body: " + body); + } }; - camelCondition = new Condition() { - public boolean match(Exchange exchange, ProcessorDefinition definition) { + camelCondition = new ConditionSupport() { + public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { return body().contains("Camel").matches(exchange); } }; - mockCondition = new Condition() { - public boolean match(Exchange exchange, ProcessorDefinition definition) { + mockCondition = new ConditionSupport() { + public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) { // match when sending to mocks if (definition instanceof ToDefinition) { ToDefinition to = (ToDefinition) definition; @@ -67,6 +76,13 @@ public boolean match(Exchange exchange, ProcessorDefinition definition) { return false; } }; + + doneCondition = new ConditionSupport() { + @Override + public boolean matchEvent(Exchange exchange, EventObject event) { + return event instanceof ExchangeCompletedEvent; + } + }; } public void testDebug() throws Exception { @@ -84,6 +100,21 @@ public void testDebug() throws Exception { assertEquals("Breakpoint at To[mock:result] with body: Hello Camel", logs.get(1)); } + public void testDebugEvent() throws Exception { + context.getDebugger().addBreakpoint(breakpoint, doneCondition); + + getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Hello Camel"); + + template.sendBody("direct:start", "Hello World"); + template.sendBody("direct:start", "Hello Camel"); + + assertMockEndpointsSatisfied(); + + assertEquals(2, logs.size()); + assertEquals("Breakpoint event ExchangeCompletedEvent with body: Hello World", logs.get(0)); + assertEquals("Breakpoint event ExchangeCompletedEvent with body: Hello Camel", logs.get(1)); + } + public void testDebugSuspended() throws Exception { context.getDebugger().addBreakpoint(breakpoint, mockCondition, camelCondition);
fb92acb390d3b42ae6224127cd9de576b1488cd1
griddynamics$jagger
Functionality is ready. Docu is left
p
https://github.com/griddynamics/jagger
diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/reporting/MetricPlotsReporter.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/reporting/MetricPlotsReporter.java index 846c5b0dc..d2f3ef3b3 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/reporting/MetricPlotsReporter.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/reporting/MetricPlotsReporter.java @@ -166,7 +166,7 @@ private void createFromTree() { } try { - plotsReal = databaseService.getPlotData(allMetrics); + plotsReal = databaseService.getPlotDataByMetricNode(allMetrics); } catch (Exception e) { log.error("Unable to get plots information for metrics"); } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DataService.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DataService.java index d94f2a261..80fb9b80b 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DataService.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DataService.java @@ -1,7 +1,7 @@ package com.griddynamics.jagger.engine.e1.services; import com.griddynamics.jagger.engine.e1.services.data.service.MetricEntity; -import com.griddynamics.jagger.engine.e1.services.data.service.MetricValueEntity; +import com.griddynamics.jagger.engine.e1.services.data.service.MetricPlotPointEntity; import com.griddynamics.jagger.engine.e1.services.data.service.SessionEntity; import com.griddynamics.jagger.engine.e1.services.data.service.TestEntity; @@ -51,8 +51,6 @@ public interface DataService extends JaggerService { * @return map of <session id, list of test entities> pairs*/ Map<String, Set<TestEntity>> getTests(Set<String> sessionIds); - //??? why no getTests for list of SessionEntity - /** Returns test entity for specify session's id and test name * @author Gribov Kirill * @n @@ -105,65 +103,44 @@ public interface DataService extends JaggerService { * @return map of <test id, list of metric entity> pairs*/ Map<Long, Set<MetricEntity>> getMetricsByTestIds(Set<Long> testIds); - //??? docu - Double getMetricSummary(MetricEntity metric); - - Map<MetricEntity,Double> getMetricSummary(Set<MetricEntity> metrics); - - List<MetricValueEntity> getMetricPlotData(MetricEntity metric); - - Map<MetricEntity,List<MetricValueEntity>> getMetricPlotData(Set<MetricEntity> metrics); - - - //??? Set vs List - - - - /** Returns all metric values for specify test id and metric id - * @author Gribov Kirill + /** Return summary value for selected metric + * @author Dmitry Latnikov * @n - * @param testId - test id - * @param metricId - metric id - * @return list of metric values*/ - List<MetricValueEntity> getMetricValues(Long testId, String metricId); - - /** Returns all metric values for specify test id and metric entity - * @author Gribov Kirill - * @n - * @param testId - test id + * @details + * !Note: It is faster to get summary for set of metrics than fetch every metric in for loop @n + * See docu for overloaded function with set of metrics @n * @param metric - metric entity - * @return list of metric values*/ - List<MetricValueEntity> getMetricValues(Long testId, MetricEntity metric); + * @return summary value for selected metric */ + Double getMetricSummary(MetricEntity metric); - /** Returns all metric values for specify test and metric entity - * @author Gribov Kirill + /** Return summary values for selected metrics + * @author Dmitry Latnikov * @n - * @param test - test entity - * @param metric - metric entity - * @return list of metric values*/ - List<MetricValueEntity> getMetricValues(TestEntity test, MetricEntity metric); + * @details + * Preferable way to get data. Data will be fetched from database in batch in single request => @n + * it is faster to get batch of metrics than fetch every metric in for loop @n + * @param metrics - set of metric entities + * @return map of <metric entity, summary value> */ + Map<MetricEntity,Double> getMetricSummary(Set<MetricEntity> metrics); - /** Search for metric values for specify test id and list of metric ids - * @author Gribov Kirill + /** Return list of points (values vs time) for selected metric + * @author Dmitry Latnikov * @n - * @param testId - id of test - * @param metricIds - a list of metric ids - * @return map of <metric id, list of metric values> pairs*/ - Map<String, List<MetricValueEntity>> getMetricValuesByIds(Long testId, List<String> metricIds); + * @details + * !Note: It is faster to get plot data for set of metrics than fetch every metric in for loop @n + * See docu for overloaded function with set of metrics @n + * @param metric - metric entity + * @return list of points (value vs time) for selected metric */ + List<MetricPlotPointEntity> getMetricPlotData(MetricEntity metric); - /** Search for metric values for specify test and list of metrics - * @author Gribov Kirill + /** Return lists of points (values vs time) for selected metrics + * @author Dmitry Latnikov * @n - * @param test - test entity - * @param metrics - a list of metric entities - * @return map of <metric, list of metric values> pairs*/ - Map<MetricEntity, List<MetricValueEntity>> getMetricValues(TestEntity test, List<MetricEntity> metrics); + * @details + * Preferable way to get data. Data will be fetched from database in batch in single request => @n + * it is faster to get batch of metrics than fetch every metric in for loop @n + * @param metrics - set metric entities + * @return map of <metic entity, list of points (value vs time)> for selected metric */ + Map<MetricEntity,List<MetricPlotPointEntity>> getMetricPlotData(Set<MetricEntity> metrics); - /** Search for metric values for specify test id and list of metrics - * @author Gribov Kirill - * @n - * @param testId - test id - * @param metrics - a list of metric entities - * @return map of <metric, list of metric values> pairs*/ - Map<MetricEntity, List<MetricValueEntity>> getMetricValues(Long testId, List<MetricEntity> metrics); } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DefaultDataService.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DefaultDataService.java index d5ddd915e..271fa548f 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DefaultDataService.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/DefaultDataService.java @@ -2,30 +2,19 @@ import com.griddynamics.jagger.coordinator.NodeContext; import com.griddynamics.jagger.dbapi.DatabaseService; -import com.griddynamics.jagger.dbapi.dto.MetricDto; -import com.griddynamics.jagger.dbapi.dto.MetricNameDto; -import com.griddynamics.jagger.dbapi.dto.SessionDataDto; -import com.griddynamics.jagger.dbapi.dto.TaskDataDto; +import com.griddynamics.jagger.dbapi.dto.*; import com.griddynamics.jagger.dbapi.model.MetricNode; import com.griddynamics.jagger.dbapi.model.RootNode; import com.griddynamics.jagger.dbapi.model.TestDetailsNode; import com.griddynamics.jagger.dbapi.model.TestNode; import com.griddynamics.jagger.dbapi.util.SessionMatchingSetup; import com.griddynamics.jagger.engine.e1.services.data.service.*; -import com.griddynamics.jagger.dbapi.entity.MetricDetails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import java.util.*; -//??? check all overrides - -//??? how to get metric ids for standard metrics and monitoring - -//??? will not need HibDaoSupport - -public class DefaultDataService extends HibernateDaoSupport implements DataService { +public class DefaultDataService implements DataService { private static final Logger log = LoggerFactory.getLogger(DefaultDataService.class); DatabaseService databaseService; @@ -125,8 +114,7 @@ public Map<String, TestEntity> getTestsByName(Set<String> sessionIds, String tes return result; } - - //??? pass testName null to ignore + //pass testName=null to ignore it private Map<String, Set<TestEntity>> getTestsWithName(Set<String> sessionIds, String testName){ if (sessionIds.isEmpty()){ return Collections.emptyMap(); @@ -135,6 +123,7 @@ private Map<String, Set<TestEntity>> getTestsWithName(Set<String> sessionIds, St // Get all test results without matching SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup(false,Collections.<SessionMatchingSetup.MatchBy>emptySet()); List<TaskDataDto> taskDataDtoList = databaseService.getTaskDataForSessions(sessionIds,sessionMatchingSetup); + Map<TaskDataDto,Map<String,TestInfoDto>> testInfoMap = databaseService.getTestInfoByTaskDataDto(taskDataDtoList); Map<String, Set<TestEntity>> result = new HashMap<String, Set<TestEntity>>(); @@ -150,12 +139,8 @@ private Map<String, Set<TestEntity>> getTestsWithName(Set<String> sessionIds, St testEntity.setDescription(taskDataDto.getDescription()); testEntity.setName(taskDataDto.getTaskName()); - - //??? missing load and termination strategy - - //??? - // may be use test info provider? - + testEntity.setLoad(testInfoMap.get(taskDataDto).entrySet().iterator().next().getValue().getClock()); + testEntity.setTerminationStrategy(testInfoMap.get(taskDataDto).entrySet().iterator().next().getValue().getTermination()); if (result.containsKey(taskDataDto.getSessionId())){ result.get(taskDataDto.getSessionId()).add(testEntity); @@ -309,8 +294,6 @@ public Double getMetricSummary(MetricEntity metric) { return map.get(metric); } - //??? check with old monitoring - @Override public Map<MetricEntity, Double> getMetricSummary(Set<MetricEntity> metrics) { @@ -324,7 +307,7 @@ public Map<MetricEntity, Double> getMetricSummary(Set<MetricEntity> metrics) { } } - List<MetricDto> metricDtoList = databaseService.getMetrics(metricNameDtoList); + List<MetricDto> metricDtoList = databaseService.getSummaryByMetricNameDto(metricNameDtoList); Map<MetricEntity,Double> result = new HashMap<MetricEntity, Double>(); for (MetricDto metricDto : metricDtoList) { @@ -337,123 +320,40 @@ public Map<MetricEntity, Double> getMetricSummary(Set<MetricEntity> metrics) { } @Override - public List<MetricValueEntity> getMetricPlotData(MetricEntity metric) { - return null; - } - - @Override - public Map<MetricEntity, List<MetricValueEntity>> getMetricPlotData(Set<MetricEntity> metrics) { - return null; - } - - - //??? get summary and values separately - - - @Override - public List<MetricValueEntity> getMetricValues(Long testId, String metricId){ - Map<String, List<MetricValueEntity>> map = getMetricValuesByIds(testId, Arrays.asList(metricId)); - - List<MetricValueEntity> result = map.get(metricId); - if (result != null){ - return result; - } - - return Collections.emptyList(); - } - - @Override - public List<MetricValueEntity> getMetricValues(TestEntity test, MetricEntity metric){ - return getMetricValues(test.getId(), metric); - } - - @Override - public List<MetricValueEntity> getMetricValues(Long testId, MetricEntity metric){ - Map<MetricEntity, List<MetricValueEntity>> map = getMetricValues(testId, Arrays.asList(metric)); - - List<MetricValueEntity> result = map.get(metric); - if (result != null){ - return result; - } - - return Collections.emptyList(); - } - - @Override - public Map<String, List<MetricValueEntity>> getMetricValuesByIds(Long testId, List<String> metricIds){ - if (metricIds.isEmpty()){ - return Collections.emptyMap(); - } - - MultiMap<String, MetricValueEntity> result = new MultiMap<String,MetricValueEntity>(); + public List<MetricPlotPointEntity> getMetricPlotData(MetricEntity metric) { + Map<MetricEntity, List<MetricPlotPointEntity>> map = getMetricPlotData(new HashSet<MetricEntity>(Arrays.asList(metric))); - List<MetricDetails> metricValues = getHibernateTemplate().findByNamedParam("select metric from MetricDetails metric " + - "where metric.taskData.id=:testId", - "testId", testId); - if (metricValues.isEmpty()){ - return Collections.emptyMap(); - } - - for (MetricDetails metricValue : metricValues){ - MetricValueEntity valueEntity = new MetricValueEntity(); - valueEntity.setTimeStamp(metricValue.getTime()); - valueEntity.setValue(metricValue.getValue()); - - result.put(metricValue.getMetric(), valueEntity); - } - - return result.getOrigin(); - } - - @Override - public Map<MetricEntity, List<MetricValueEntity>> getMetricValues(TestEntity test, List<MetricEntity> metrics){ - return getMetricValues(test.getId(), metrics); + return map.get(metric); } @Override - public Map<MetricEntity, List<MetricValueEntity>> getMetricValues(Long testId, List<MetricEntity> metrics){ - List<String> ids = new ArrayList<String>(metrics.size()); - Map<String, MetricEntity> map = new HashMap<String, MetricEntity>(metrics.size()); - for (MetricEntity metricEntity : metrics){ - ids.add(metricEntity.getMetricId()); - map.put(metricEntity.getMetricId(), metricEntity); - } - - Map<String, List<MetricValueEntity>> metricValues = getMetricValuesByIds(testId, ids); - - Map<MetricEntity, List<MetricValueEntity>> result = new HashMap<MetricEntity, List<MetricValueEntity>>(); - for (String key : map.keySet()){ - result.put(map.get(key), metricValues.get(key)); - } - - return result; - } - - class MultiMap<K,V>{ - private Map<K,List<V>> map; - - public MultiMap(){ - map = new HashMap<K, List<V>>(); - } - - public void put(K key, V value){ - if (map.containsKey(key)){ - map.get(key).add(value); - }else{ - ArrayList<V> list = new ArrayList<V>(); - list.add(value); + public Map<MetricEntity, List<MetricPlotPointEntity>> getMetricPlotData(Set<MetricEntity> metrics) { + Set<MetricNameDto> metricNameDtoSet = new HashSet<MetricNameDto>(); + Map<MetricNameDto,MetricEntity> matchMap = new HashMap<MetricNameDto, MetricEntity>(); - map.put(key, list); + for (MetricEntity metric : metrics) { + if (metric.isPlotAvailable()) { + metricNameDtoSet.add(metric.getMetricNameDto()); + matchMap.put(metric.getMetricNameDto(),metric); } } - public List<V> get(K key){ - return map.get(key); + Map<MetricNameDto,List<PlotDatasetDto>> resultMap = databaseService.getPlotDataByMetricNameDto(metricNameDtoSet); + + Map<MetricEntity,List<MetricPlotPointEntity>> result = new HashMap<MetricEntity, List<MetricPlotPointEntity>>(); + for (Map.Entry<MetricNameDto,List<PlotDatasetDto>> entry : resultMap.entrySet()) { + MetricEntity metricEntity = matchMap.get(entry.getKey()); + List<MetricPlotPointEntity> values = new ArrayList<MetricPlotPointEntity>(); + for (PointDto pointDto : entry.getValue().iterator().next().getPlotData()) { + MetricPlotPointEntity metricPlotPointEntity = new MetricPlotPointEntity(); + metricPlotPointEntity.setTime(pointDto.getX()); + metricPlotPointEntity.setValue(pointDto.getY()); + values.add(metricPlotPointEntity); + } + result.put(metricEntity,values); } - public Map<K,List<V>> getOrigin(){ - return map; - } + return result; } @Override diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/EmptyDataService.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/EmptyDataService.java index c7cf69f12..11657b84e 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/EmptyDataService.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/EmptyDataService.java @@ -1,7 +1,7 @@ package com.griddynamics.jagger.engine.e1.services; import com.griddynamics.jagger.engine.e1.services.data.service.MetricEntity; -import com.griddynamics.jagger.engine.e1.services.data.service.MetricValueEntity; +import com.griddynamics.jagger.engine.e1.services.data.service.MetricPlotPointEntity; import com.griddynamics.jagger.engine.e1.services.data.service.SessionEntity; import com.griddynamics.jagger.engine.e1.services.data.service.TestEntity; import org.slf4j.Logger; @@ -12,8 +12,6 @@ import java.util.Set; -//??? logging - public class EmptyDataService implements DataService { private static Logger log = LoggerFactory.getLogger(EmptyDataService.class); @@ -27,111 +25,97 @@ public EmptyDataService(JaggerPlace jaggerPlace) { @Override public SessionEntity getSession(String sessionId) { + log.warn("Can't get session entity for session id {}. DataService is not supported in {}", sessionId, jaggerPlace); return null; } @Override public Set<SessionEntity> getSessions(Set<String> sessionIds) { + log.warn("Can't get session entities for session ids {}. DataService is not supported in {}", sessionIds, jaggerPlace); return null; } @Override public Set<TestEntity> getTests(SessionEntity session) { + log.warn("Can't get test entities for session {}. DataService is not supported in {}", session, jaggerPlace); return null; } @Override public Set<TestEntity> getTests(String sessionId) { + log.warn("Can't get test entities for session id {}. DataService is not supported in {}", sessionId, jaggerPlace); return null; } @Override public Map<String, Set<TestEntity>> getTests(Set<String> sessionIds) { + log.warn("Can't get test entities for session ids {}. DataService is not supported in {}", sessionIds, jaggerPlace); return null; } @Override public TestEntity getTestByName(String sessionId, String testName) { + log.warn("Can't get test entity {} for session id {}. DataService is not supported in {}", new Object[]{testName, sessionId, jaggerPlace}); return null; } @Override public TestEntity getTestByName(SessionEntity session, String testName) { + log.warn("Can't get test entity {} for session {}. DataService is not supported in {}", new Object[]{testName, session, jaggerPlace}); return null; } @Override public Map<String, TestEntity> getTestsByName(Set<String> sessionIds, String testName) { + log.warn("Can't get test entity {} for sessions {}. DataService is not supported in {}", new Object[]{testName, sessionIds, jaggerPlace}); return null; } @Override public Set<MetricEntity> getMetrics(Long testId) { + log.warn("Can't get metric entities for test id {}. DataService is not supported in {}", testId, jaggerPlace); return null; } @Override public Set<MetricEntity> getMetrics(TestEntity test) { + log.warn("Can't get metric entities for test {}. DataService is not supported in {}", test, jaggerPlace); return null; } @Override public Map<TestEntity, Set<MetricEntity>> getMetricsByTests(Set<TestEntity> tests) { + log.warn("Can't get metric entities for tests {}. DataService is not supported in {}", tests, jaggerPlace); return null; } @Override public Map<Long, Set<MetricEntity>> getMetricsByTestIds(Set<Long> testIds) { + log.warn("Can't get metric entities for test ids {}. DataService is not supported in {}", testIds, jaggerPlace); return null; } @Override public Double getMetricSummary(MetricEntity metric) { + log.warn("Can't get summary value for metric {}. DataService is not supported in {}", metric, jaggerPlace); return null; } @Override public Map<MetricEntity, Double> getMetricSummary(Set<MetricEntity> metrics) { + log.warn("Can't get summary values for metrics {}. DataService is not supported in {}", metrics, jaggerPlace); return null; } @Override - public List<MetricValueEntity> getMetricPlotData(MetricEntity metric) { - return null; - } - - @Override - public Map<MetricEntity, List<MetricValueEntity>> getMetricPlotData(Set<MetricEntity> metrics) { - return null; - } - - @Override - public List<MetricValueEntity> getMetricValues(Long testId, String metricId) { - return null; - } - - @Override - public List<MetricValueEntity> getMetricValues(Long testId, MetricEntity metric) { - return null; - } - - @Override - public List<MetricValueEntity> getMetricValues(TestEntity test, MetricEntity metric) { - return null; - } - - @Override - public Map<String, List<MetricValueEntity>> getMetricValuesByIds(Long testId, List<String> metricIds) { - return null; - } - - @Override - public Map<MetricEntity, List<MetricValueEntity>> getMetricValues(TestEntity test, List<MetricEntity> metrics) { + public List<MetricPlotPointEntity> getMetricPlotData(MetricEntity metric) { + log.warn("Can't get plot data values for metric {}. DataService is not supported in {}", metric, jaggerPlace); return null; } @Override - public Map<MetricEntity, List<MetricValueEntity>> getMetricValues(Long testId, List<MetricEntity> metrics) { + public Map<MetricEntity, List<MetricPlotPointEntity>> getMetricPlotData(Set<MetricEntity> metrics) { + log.warn("Can't get plot data values for metrics {}. DataService is not supported in {}", metrics, jaggerPlace); return null; } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/JaggerMetric.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/JaggerMetric.java deleted file mode 100644 index 70bcf50da..000000000 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/JaggerMetric.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.griddynamics.jagger.engine.e1.services.data.service; - -//??? delete -/** - * Created with IntelliJ IDEA. - * User: kgribov - * Date: 12/19/13 - * Time: 1:16 PM - * To change this template use File | Settings | File Templates. - */ -public class JaggerMetric { - public static final String Throughput = "throughput"; - public static final String SuccessRate = "successRate"; - public static final String AvgLatency = "avgLatency"; - public static final String StdDevLatency = "stdDevLatency"; - public static final String Samples = "samples"; - public static final String Failures = "failuresCount"; - - - -} diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricEntity.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricEntity.java index e8470a8e4..3e19ccdfc 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricEntity.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricEntity.java @@ -2,10 +2,7 @@ import com.griddynamics.jagger.dbapi.dto.MetricNameDto; -//??? has only summary or plot - - - +//??? docu /** * Created with IntelliJ IDEA. * User: kgribov @@ -17,10 +14,6 @@ public class MetricEntity { private MetricNameDto metricNameDto; private boolean summaryAvailable = false; private boolean plotAvailable = false; - //??? -// private String metricId; -// private String displayName; -//??? private Double summaryValue; public void setMetricNameDto(MetricNameDto metricNameDto) { this.metricNameDto = metricNameDto; @@ -33,10 +26,6 @@ public String getMetricId() { return metricNameDto.getMetricName(); } -// public void setMetricId(String metricId) { -// this.metricId = metricId; -// } - public String getDisplayName() { return metricNameDto.getMetricDisplayName(); } @@ -61,43 +50,25 @@ public void setPlotAvailable(boolean plotAvailable) { this.plotAvailable = plotAvailable; } -// public void setDisplayName(String displayName) { -// this.displayName = displayName; -// } - - //??? -// public Double getSummaryValue() { -// return summaryValue; -// } -// -// public void setSummaryValue(Double summaryValue) { -// this.summaryValue = summaryValue; -// } - - - + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MetricEntity that = (MetricEntity) o; + if (plotAvailable != that.plotAvailable) return false; + if (summaryAvailable != that.summaryAvailable) return false; + if (!metricNameDto.equals(that.metricNameDto)) return false; + return true; + } - //??? -// @Override -// public boolean equals(Object o) { -// if (this == o) return true; -// if (o == null || getClass() != o.getClass()) return false; -// -// MetricEntity entity = (MetricEntity) o; -// -// if (displayName != null ? !displayName.equals(entity.displayName) : entity.displayName != null) return false; -// if (metricId != null ? !metricId.equals(entity.metricId) : entity.metricId != null) return false; -// -// return true; -// } -// -// @Override -// public int hashCode() { -// int result = metricId != null ? metricId.hashCode() : 0; -// result = 31 * result + (displayName != null ? displayName.hashCode() : 0); -// return result; -// } + @Override + public int hashCode() { + int result = metricNameDto.hashCode(); + result = 31 * result + (summaryAvailable ? 1 : 0); + result = 31 * result + (plotAvailable ? 1 : 0); + return result; + } } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricPlotPointEntity.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricPlotPointEntity.java new file mode 100644 index 000000000..2e1f5d9ff --- /dev/null +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricPlotPointEntity.java @@ -0,0 +1,23 @@ +package com.griddynamics.jagger.engine.e1.services.data.service; + +//??? docu +public class MetricPlotPointEntity { + private Double time; + private Double value; + + public Double getTime() { + return time; + } + + public void setTime(Double time) { + this.time = time; + } + + public Double getValue() { + return value; + } + + public void setValue(Double value) { + this.value = value; + } +} diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricValueEntity.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricValueEntity.java deleted file mode 100644 index 2540d035a..000000000 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/MetricValueEntity.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.griddynamics.jagger.engine.e1.services.data.service; - -/** - * Created with IntelliJ IDEA. - * User: kgribov - * Date: 12/5/13 - * Time: 12:26 PM - * To change this template use File | Settings | File Templates. - */ -public class MetricValueEntity { - private Long timeStamp; - private Double value; - - public Long getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Long timeStamp) { - this.timeStamp = timeStamp; - } - - public Double getValue() { - return value; - } - - public void setValue(Double value) { - this.value = value; - } -} diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/SessionEntity.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/SessionEntity.java index 23326df06..2fb557513 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/SessionEntity.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/SessionEntity.java @@ -1,5 +1,6 @@ package com.griddynamics.jagger.engine.e1.services.data.service; +//??? docu /** * Created with IntelliJ IDEA. * User: kgribov @@ -54,7 +55,6 @@ public void setKernels(Integer kernels) { this.kernels = kernels; } - //??? regenerate after changes @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/TestEntity.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/TestEntity.java index ad74ea8b5..dcb12f20a 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/TestEntity.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/services/data/service/TestEntity.java @@ -1,5 +1,6 @@ package com.griddynamics.jagger.engine.e1.services.data.service; +//??? docu /** * Created with IntelliJ IDEA. * User: kgribov diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java b/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java index 9e9df59d3..55f2fcd97 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java @@ -51,8 +51,6 @@ public void onTaskDistributionCompleted(String sessionId, String taskId, Task ta SessionEntity sessionEntity = dataService.getSession(sessionId); System.out.println(sessionEntity); - //??? decisionMakerListener - // //??? // RootNode rootNode = databaseService.getControlTreeForSessions(new HashSet<String>(Arrays.asList(sessionId))); // SummaryNode summaryNode = rootNode.getSummaryNode(); diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java index ead329966..fbe2d4351 100644 --- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java +++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java @@ -27,17 +27,27 @@ public interface DatabaseService { /** Returns map <metricNode, plot values> for specific metric nodes from control tree * @param plots - set of metric nodes * @return plot values for metric nodes */ - Map<MetricNode, PlotSeriesDto> getPlotData(Set<MetricNode> plots) throws IllegalArgumentException; + Map<MetricNode, PlotSeriesDto> getPlotDataByMetricNode(Set<MetricNode> plots) throws IllegalArgumentException; + + /** Returns map <metricNameDto, plot values> for specific metric names + * @param metricNames - set of metric names + * @return plot values for metric names */ + Map<MetricNameDto, List<PlotDatasetDto>> getPlotDataByMetricNameDto(Set<MetricNameDto> metricNames) throws IllegalArgumentException; /** Returns summary values for current metrics * @param metricNames - metric names * @return list of summary values */ - List<MetricDto> getMetrics(List<MetricNameDto> metricNames); + List<MetricDto> getSummaryByMetricNameDto(List<MetricNameDto> metricNames); /** Returns test info for specify tests * @param taskDataDtos - selected tests - * @return map of test infos */ - Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfos(Collection<TaskDataDto> taskDataDtos) throws RuntimeException; + * @return map of test info */ + Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfoByTaskDataDto(Collection<TaskDataDto> taskDataDtos) throws RuntimeException; + + /** Returns test info for specify tests ids + * @param taskIds - selected test ids + * @return map of test info */ + Map<Long, Map<String, TestInfoDto>> getTestInfoByTaskIds(Set<Long> taskIds) throws RuntimeException; /** Return information about session nodes * @param sessionIds - selected sessions diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java index f8e6ca666..b86a183bf 100644 --- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java +++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java @@ -231,41 +231,95 @@ public void setFetchUtil(FetchUtil fetchUtil) { //=========================== @Override - public Map<MetricNode, PlotSeriesDto> getPlotData(Set<MetricNode> plots) throws IllegalArgumentException{ + public Map<MetricNode, PlotSeriesDto> getPlotDataByMetricNode(Set<MetricNode> plots) throws IllegalArgumentException{ + + if (plots.isEmpty()) { + return Collections.emptyMap(); + } long temp = System.currentTimeMillis(); - final Multimap<PlotsDbMetricDataFetcher, MetricNameDto> fetchMap = ArrayListMultimap.create(); + Set<MetricNameDto> metricNameDtoSet = new HashSet<MetricNameDto>(); for (MetricNode metricNode : plots) { - for (MetricNameDto metricNameDto : metricNode.getMetricNameDtoList()) { - switch (metricNameDto.getOrigin()) { - case METRIC: - fetchMap.put(customMetricPlotFetcher, metricNameDto); - break; - case TEST_GROUP_METRIC: - fetchMap.put(customTestGroupMetricPlotFetcher, metricNameDto); - break; - case MONITORING: - fetchMap.put(monitoringMetricPlotFetcher, metricNameDto); - break; - case LATENCY: - fetchMap.put(latencyMetricPlotFetcher, metricNameDto); - break; - case LATENCY_PERCENTILE: - fetchMap.put(timeLatencyPercentileMetricPlotFetcher, metricNameDto); - break; - case THROUGHPUT: - fetchMap.put(throughputMetricPlotFetcher, metricNameDto); - break; - default: // if anything else - log.error("MetricNameDto with origin : {} appears in metric name list for plot retrieving ({})", metricNameDto.getOrigin(), metricNameDto); - throw new RuntimeException("Unable to get plot for metric " + metricNameDto.getMetricName() + - " with origin: " + metricNameDto.getOrigin()); + metricNameDtoSet.addAll(metricNode.getMetricNameDtoList()); + } + + Map<MetricNameDto,List<PlotDatasetDto>> resultMap = getPlotDataByMetricNameDto(metricNameDtoSet); + + Multimap<MetricNode, PlotDatasetDto> tempMultiMap = ArrayListMultimap.create(); + + for (Map.Entry<MetricNameDto,List<PlotDatasetDto>> entry : resultMap.entrySet()) { + for (MetricNode metricNode : plots) { + if (metricNode.getMetricNameDtoList().contains(entry.getKey())) { + tempMultiMap.putAll(metricNode, entry.getValue()); + break; } } } + Map<MetricNode, PlotSeriesDto> result = new HashMap<MetricNode, PlotSeriesDto>(); + + for (MetricNode metricNode : plots) { + List<PlotDatasetDto> plotDatasetDtoList = new ArrayList<PlotDatasetDto>(tempMultiMap.get(metricNode)); + + // Sort lines by legend + Collections.sort(plotDatasetDtoList, new Comparator<PlotDatasetDto>() { + @Override + public int compare(PlotDatasetDto o1, PlotDatasetDto o2) { + String param1 = o1.getLegend(); + String param2 = o2.getLegend(); + int res = String.CASE_INSENSITIVE_ORDER.compare(param1,param2); + return (res != 0) ? res : param1.compareTo(param2); + } + }); + + // at the moment all MetricNameDtos in MetricNode have same taskIds => it is valid to use first one for legend provider + result.put(metricNode, new PlotSeriesDto(plotDatasetDtoList,"Time, sec", "",legendProvider.getPlotHeader(metricNode.getMetricNameDtoList().get(0).getTaskIds(), metricNode.getDisplayName()))); + } + + log.debug("Total time of plots for metricNodes retrieving : " + (System.currentTimeMillis() - temp)); + return result; + } + + @Override + public Map<MetricNameDto, List<PlotDatasetDto>> getPlotDataByMetricNameDto(Set<MetricNameDto> metricNames) throws IllegalArgumentException { + + if (metricNames.isEmpty()) { + return Collections.emptyMap(); + } + + long temp = System.currentTimeMillis(); + + final Multimap<PlotsDbMetricDataFetcher, MetricNameDto> fetchMap = ArrayListMultimap.create(); + + for (MetricNameDto metricNameDto : metricNames) { + switch (metricNameDto.getOrigin()) { + case METRIC: + fetchMap.put(customMetricPlotFetcher, metricNameDto); + break; + case TEST_GROUP_METRIC: + fetchMap.put(customTestGroupMetricPlotFetcher, metricNameDto); + break; + case MONITORING: + fetchMap.put(monitoringMetricPlotFetcher, metricNameDto); + break; + case LATENCY: + fetchMap.put(latencyMetricPlotFetcher, metricNameDto); + break; + case LATENCY_PERCENTILE: + fetchMap.put(timeLatencyPercentileMetricPlotFetcher, metricNameDto); + break; + case THROUGHPUT: + fetchMap.put(throughputMetricPlotFetcher, metricNameDto); + break; + default: // if anything else + log.error("MetricNameDto with origin : {} appears in metric name list for plot retrieving ({})", metricNameDto.getOrigin(), metricNameDto); + throw new RuntimeException("Unable to get plot for metric " + metricNameDto.getMetricName() + + " with origin: " + metricNameDto.getOrigin()); + } + } + Set<PlotsDbMetricDataFetcher> fetcherSet = fetchMap.keySet(); List<Future<Set<Pair<MetricNameDto, List<PlotDatasetDto>>>>> futures = new ArrayList<Future<Set<Pair<MetricNameDto, List<PlotDatasetDto>>>>>(); @@ -291,38 +345,14 @@ public Set<Pair<MetricNameDto, List<PlotDatasetDto>>> call() throws Exception { throw new RuntimeException("Exception while plots retrieving", th); } - Multimap<MetricNode, PlotDatasetDto> tempMultiMap = ArrayListMultimap.create(); + Map<MetricNameDto, List<PlotDatasetDto>> result = new HashMap<MetricNameDto, List<PlotDatasetDto>>(); for (Pair<MetricNameDto, List<PlotDatasetDto>> pair : resultSet) { - for (MetricNode metricNode : plots) { - if (metricNode.getMetricNameDtoList().contains(pair.getFirst())) { - tempMultiMap.putAll(metricNode, pair.getSecond()); - break; - } - } + result.put(pair.getFirst(),pair.getSecond()); } - Map<MetricNode, PlotSeriesDto> result = new HashMap<MetricNode, PlotSeriesDto>(); - - for (MetricNode metricNode : plots) { - List<PlotDatasetDto> plotDatasetDtoList = new ArrayList<PlotDatasetDto>(tempMultiMap.get(metricNode)); + log.debug("Total time of plots for metricNameDtos retrieving : " + (System.currentTimeMillis() - temp)); - // Sort lines by legend - Collections.sort(plotDatasetDtoList, new Comparator<PlotDatasetDto>() { - @Override - public int compare(PlotDatasetDto o1, PlotDatasetDto o2) { - String param1 = o1.getLegend(); - String param2 = o2.getLegend(); - int res = String.CASE_INSENSITIVE_ORDER.compare(param1,param2); - return (res != 0) ? res : param1.compareTo(param2); - } - }); - - // at the moment all MetricNameDtos in MetricNode have same taskIds => it is valid to use first one for legend provider - result.put(metricNode, new PlotSeriesDto(plotDatasetDtoList,"Time, sec", "",legendProvider.getPlotHeader(metricNode.getMetricNameDtoList().get(0).getTaskIds(), metricNode.getDisplayName()))); - } - - log.debug("Total time of plots retrieving : " + (System.currentTimeMillis() - temp)); return result; } @@ -371,7 +401,7 @@ public RootNode getControlTreeForSessions(Set<String> sessionIds, SessionMatchin //=========================== @Override - public List<MetricDto> getMetrics(List<MetricNameDto> metricNames) { + public List<MetricDto> getSummaryByMetricNameDto(List<MetricNameDto> metricNames) { long temp = System.currentTimeMillis(); List<MetricDto> result = new ArrayList<MetricDto>(metricNames.size()); @@ -1163,19 +1193,50 @@ private <M extends MetricNode> MetricGroupNode<M> buildTreeAccordingToRules(Stri } @Override - public Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfos(Collection<TaskDataDto> taskDataDtos) throws RuntimeException { + public Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfoByTaskDataDto(Collection<TaskDataDto> taskDataDtos) throws RuntimeException { if (taskDataDtos.isEmpty()) { - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } - List<Long> taskDataIds = new ArrayList<Long>(); + long temp = System.currentTimeMillis(); + + Set<Long> taskDataIds = new HashSet<Long>(); for (TaskDataDto taskDataDto : taskDataDtos) { taskDataIds.addAll(taskDataDto.getIds()); } + Map<Long,Map<String,TestInfoDto>> preliminaryResult = getTestInfoByTaskIds(taskDataIds); + + Map<TaskDataDto, Map<String, TestInfoDto>> resultMap = new HashMap<TaskDataDto, Map<String, TestInfoDto>>(taskDataDtos.size()); + + for (Map.Entry<Long,Map<String,TestInfoDto>> entry : preliminaryResult.entrySet()) { + for (TaskDataDto td : taskDataDtos) { + if (td.getIds().contains(entry.getKey())) { + if (!resultMap.containsKey(td)) { + resultMap.put(td, new HashMap<String, TestInfoDto>()); + } + + resultMap.get(td).putAll(entry.getValue()); + break; + } + } + } + + log.debug("Time spent for testInfo fetching for {} taskDataDtos : {}ms", new Object[]{taskDataDtos.size(), System.currentTimeMillis() - temp}); + + return resultMap; + } + + @Override + public Map<Long, Map<String, TestInfoDto>> getTestInfoByTaskIds(Set<Long> taskIds) throws RuntimeException { + + if (taskIds.isEmpty()) { + return Collections.emptyMap(); + } long temp = System.currentTimeMillis(); + @SuppressWarnings("all") List<Object[]> objectsList = (List<Object[]>)entityManager.createNativeQuery( "select wtd.sessionId, wtd.clock, wtd.clockValue, wtd.termination, taskData.id " + @@ -1183,11 +1244,10 @@ public Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfos(Collection<TaskDa "( select td.id, td.sessionId, td.taskId from TaskData td where td.id in (:taskDataIds) " + ") as taskData " + "on wtd.sessionId=taskData.sessionId and wtd.taskId=taskData.taskId") - .setParameter("taskDataIds", taskDataIds) + .setParameter("taskDataIds", taskIds) .getResultList(); - log.debug("Time spent for testInfo fetching for {} tests : {}ms", new Object[]{taskDataDtos.size(), System.currentTimeMillis() - temp}); - Map<TaskDataDto, Map<String, TestInfoDto>> resultMap = new HashMap<TaskDataDto, Map<String, TestInfoDto>>(taskDataDtos.size()); + Map<Long, Map<String, TestInfoDto>> resultMap = new HashMap<Long, Map<String, TestInfoDto>>(taskIds.size()); for (Object[] objects : objectsList) { @@ -1196,21 +1256,18 @@ public Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfos(Collection<TaskDa String termination = (String)objects[3]; String sessionId = (String)objects[0]; - for (TaskDataDto td : taskDataDtos) { - if (td.getIds().contains(taskId)) { - if (!resultMap.containsKey(td)) { - resultMap.put(td, new HashMap<String, TestInfoDto>()); - } - - TestInfoDto testInfo = new TestInfoDto(); - testInfo.setClock(clock); - testInfo.setTermination(termination); - resultMap.get(td).put(sessionId, testInfo); - break; - } + if (!resultMap.containsKey(taskId)) { + resultMap.put(taskId,new HashMap<String, TestInfoDto>()); } + TestInfoDto testInfo = new TestInfoDto(); + testInfo.setClock(clock); + testInfo.setTermination(termination); + + resultMap.get(taskId).put(sessionId,testInfo); } + log.debug("Time spent for testInfo fetching for {} tests ids: {}ms", new Object[]{taskIds.size(), System.currentTimeMillis() - temp}); + return resultMap; } diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/server/MetricDataServiceImpl.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/server/MetricDataServiceImpl.java index 3dad59df2..ead1c86cb 100644 --- a/webclient/src/main/java/com/griddynamics/jagger/webclient/server/MetricDataServiceImpl.java +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/server/MetricDataServiceImpl.java @@ -19,8 +19,6 @@ */ public class MetricDataServiceImpl implements MetricDataService { - private static final Logger log = LoggerFactory.getLogger(MetricDataServiceImpl.class); - private DatabaseService databaseService; @Required @@ -30,6 +28,6 @@ public void setDatabaseService(DatabaseService databaseService) { @Override public List<MetricDto> getMetrics(List<MetricNameDto> metricNames) throws RuntimeException { - return databaseService.getMetrics(metricNames); + return databaseService.getSummaryByMetricNameDto(metricNames); } } \ No newline at end of file diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/server/PlotProviderServiceImpl.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/server/PlotProviderServiceImpl.java index 07d559c70..145563074 100644 --- a/webclient/src/main/java/com/griddynamics/jagger/webclient/server/PlotProviderServiceImpl.java +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/server/PlotProviderServiceImpl.java @@ -25,12 +25,12 @@ public void setDatabaseService(DatabaseService databaseService) { @Override public Map<MetricNode, PlotSeriesDto> getPlotData(Set<MetricNode> plots) throws RuntimeException { - return databaseService.getPlotData(plots); + return databaseService.getPlotDataByMetricNode(plots); } @Override public Map<SessionPlotNameDto, List<PlotSeriesDto>> getSessionScopePlotData(String sessionId, Collection<SessionPlotNameDto> plotType) throws RuntimeException { - // @todo create session scope plots for monitoring and test-group metrics + //@todo JFG-667 delete this function after creating session scope plots for monitoring and test-group metrics return Collections.EMPTY_MAP; } } diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/server/TestInfoServiceImpl.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/server/TestInfoServiceImpl.java index 4c1350881..a71b64810 100644 --- a/webclient/src/main/java/com/griddynamics/jagger/webclient/server/TestInfoServiceImpl.java +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/server/TestInfoServiceImpl.java @@ -13,8 +13,6 @@ public class TestInfoServiceImpl implements TestInfoService { - - private static final Logger log = LoggerFactory.getLogger(NodeInfoServiceImpl.class); private DatabaseService databaseService; @Required @@ -24,6 +22,6 @@ public void setDatabaseService(DatabaseService databaseService) { @Override public Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfos(Collection<TaskDataDto> taskDataDtos) throws RuntimeException { - return databaseService.getTestInfos(taskDataDtos); + return databaseService.getTestInfoByTaskDataDto(taskDataDtos); } }